code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Common objects and functions shared by all pages that compose the
* File Browser dialog window.
*/
// Automatically detect the correct document.domain (#1919).
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.top.opener.document.domain ;
break ;
}
catch( e )
{}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
function AddSelectOption( selectElement, optionText, optionValue )
{
var oOption = document.createElement("OPTION") ;
oOption.text = optionText ;
oOption.value = optionValue ;
selectElement.options.add(oOption) ;
return oOption ;
}
var oConnector = window.parent.oConnector ;
var oIcons = window.parent.oIcons ;
function StringBuilder( value )
{
this._Strings = new Array( value || '' ) ;
}
StringBuilder.prototype.Append = function( value )
{
if ( value )
this._Strings.push( value ) ;
}
StringBuilder.prototype.ToString = function()
{
return this._Strings.join( '' ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXml object that is used for XML data calls
* and XML processing.
*
* This script is shared by almost all pages that compose the
* File Browser frameset.
*/
var FCKXml = function()
{}
FCKXml.prototype.GetHttpRequest = function()
{
// Gecko / IE7
try { return new XMLHttpRequest(); }
catch(e) {}
// IE6
try { return new ActiveXObject( 'Msxml2.XMLHTTP' ) ; }
catch(e) {}
// IE5
try { return new ActiveXObject( 'Microsoft.XMLHTTP' ) ; }
catch(e) {}
return null ;
}
FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer )
{
var oFCKXml = this ;
var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ;
var oXmlHttp = this.GetHttpRequest() ;
oXmlHttp.open( "GET", urlToCall, bAsync ) ;
if ( bAsync )
{
oXmlHttp.onreadystatechange = function()
{
if ( oXmlHttp.readyState == 4 )
{
var oXml ;
try
{
// this is the same test for an FF2 bug as in fckxml_gecko.js
// but we've moved the responseXML assignment into the try{}
// so we don't even have to check the return status codes.
var test = oXmlHttp.responseXML.firstChild ;
oXml = oXmlHttp.responseXML ;
}
catch ( e )
{
try
{
oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ;
}
catch ( e ) {}
}
if ( !oXml || !oXml.firstChild || oXml.firstChild.nodeName == 'parsererror' )
{
alert( 'The server didn\'t send back a proper XML response. Please contact your system administrator.\n\n' +
'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')\n\n' +
'Requested URL:\n' + urlToCall + '\n\n' +
'Response text:\n' + oXmlHttp.responseText ) ;
return ;
}
oFCKXml.DOMDocument = oXml ;
asyncFunctionPointer( oFCKXml ) ;
}
}
}
oXmlHttp.send( null ) ;
if ( ! bAsync )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
this.DOMDocument = oXmlHttp.responseXML ;
else
{
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
FCKXml.prototype.SelectNodes = function( xpath )
{
if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE
return this.DOMDocument.selectNodes( xpath ) ;
else // Gecko
{
var aNodeArray = new Array();
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
if ( xPathResult )
{
var oNode = xPathResult.iterateNext() ;
while( oNode )
{
aNodeArray[aNodeArray.length] = oNode ;
oNode = xPathResult.iterateNext();
}
}
return aNodeArray ;
}
}
FCKXml.prototype.SelectSingleNode = function( xpath )
{
if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE
return this.DOMDocument.selectSingleNode( xpath ) ;
else // Gecko
{
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null);
if ( xPathResult && xPathResult.singleNodeValue )
return xPathResult.singleNodeValue ;
else
return null ;
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the integration file for JavaScript.
*
* It defines the FCKeditor class that can be used to create editor
* instances in a HTML page in the client side. For server side
* operations, use the specific integration system.
*/
// FCKeditor Class
var FCKeditor = function( instanceName, width, height, toolbarSet, value )
{
// Properties
this.InstanceName = instanceName ;
this.Width = width || '100%' ;
this.Height = height || '200' ;
this.ToolbarSet = toolbarSet || 'Default' ;
this.Value = value || '' ;
this.BasePath = FCKeditor.BasePath ;
this.CheckBrowser = true ;
this.DisplayErrors = true ;
this.Config = new Object() ;
// Events
this.OnError = null ; // function( source, errorNumber, errorDescription )
}
/**
* This is the default BasePath used by all editor instances.
*/
FCKeditor.BasePath = '/fckeditor/' ;
/**
* The minimum height used when replacing textareas.
*/
FCKeditor.MinHeight = 200 ;
/**
* The minimum width used when replacing textareas.
*/
FCKeditor.MinWidth = 750 ;
FCKeditor.prototype.Version = '2.6.3' ;
FCKeditor.prototype.VersionBuild = '19836' ;
FCKeditor.prototype.Create = function()
{
document.write( this.CreateHtml() ) ;
}
FCKeditor.prototype.CreateHtml = function()
{
// Check for errors
if ( !this.InstanceName || this.InstanceName.length == 0 )
{
this._ThrowError( 701, 'You must specify an instance name.' ) ;
return '' ;
}
var sHtml = '' ;
if ( !this.CheckBrowser || this._IsCompatibleBrowser() )
{
sHtml += '<input type="hidden" id="' + this.InstanceName + '" name="' + this.InstanceName + '" value="' + this._HTMLEncode( this.Value ) + '" style="display:none" />' ;
sHtml += this._GetConfigHtml() ;
sHtml += this._GetIFrameHtml() ;
}
else
{
var sWidth = this.Width.toString().indexOf('%') > 0 ? this.Width : this.Width + 'px' ;
var sHeight = this.Height.toString().indexOf('%') > 0 ? this.Height : this.Height + 'px' ;
sHtml += '<textarea name="' + this.InstanceName +
'" rows="4" cols="40" style="width:' + sWidth +
';height:' + sHeight ;
if ( this.TabIndex )
sHtml += '" tabindex="' + this.TabIndex ;
sHtml += '">' +
this._HTMLEncode( this.Value ) +
'<\/textarea>' ;
}
return sHtml ;
}
FCKeditor.prototype.ReplaceTextarea = function()
{
if ( !this.CheckBrowser || this._IsCompatibleBrowser() )
{
// We must check the elements firstly using the Id and then the name.
var oTextarea = document.getElementById( this.InstanceName ) ;
var colElementsByName = document.getElementsByName( this.InstanceName ) ;
var i = 0;
while ( oTextarea || i == 0 )
{
if ( oTextarea && oTextarea.tagName.toLowerCase() == 'textarea' )
break ;
oTextarea = colElementsByName[i++] ;
}
if ( !oTextarea )
{
alert( 'Error: The TEXTAREA with id or name set to "' + this.InstanceName + '" was not found' ) ;
return ;
}
oTextarea.style.display = 'none' ;
if ( oTextarea.tabIndex )
this.TabIndex = oTextarea.tabIndex ;
this._InsertHtmlBefore( this._GetConfigHtml(), oTextarea ) ;
this._InsertHtmlBefore( this._GetIFrameHtml(), oTextarea ) ;
}
}
FCKeditor.prototype._InsertHtmlBefore = function( html, element )
{
if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
}
FCKeditor.prototype._GetConfigHtml = function()
{
var sConfig = '' ;
for ( var o in this.Config )
{
if ( sConfig.length > 0 ) sConfig += '&' ;
sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.Config[o] ) ;
}
return '<input type="hidden" id="' + this.InstanceName + '___Config" value="' + sConfig + '" style="display:none" />' ;
}
FCKeditor.prototype._GetIFrameHtml = function()
{
var sFile = 'fckeditor.html' ;
try
{
if ( (/fcksource=true/i).test( window.top.location.search ) )
sFile = 'fckeditor.original.html' ;
}
catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ }
var sLink = this.BasePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.InstanceName ) ;
if (this.ToolbarSet)
sLink += '&Toolbar=' + this.ToolbarSet ;
html = '<iframe id="' + this.InstanceName +
'___Frame" src="' + sLink +
'" width="' + this.Width +
'" height="' + this.Height ;
if ( this.TabIndex )
html += '" tabindex="' + this.TabIndex ;
html += '" frameborder="0" scrolling="no"></iframe>' ;
return html ;
}
FCKeditor.prototype._IsCompatibleBrowser = function()
{
return FCKeditor_IsCompatibleBrowser() ;
}
FCKeditor.prototype._ThrowError = function( errorNumber, errorDescription )
{
this.ErrorNumber = errorNumber ;
this.ErrorDescription = errorDescription ;
if ( this.DisplayErrors )
{
document.write( '<div style="COLOR: #ff0000">' ) ;
document.write( '[ FCKeditor Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ;
document.write( '</div>' ) ;
}
if ( typeof( this.OnError ) == 'function' )
this.OnError( this, errorNumber, errorDescription ) ;
}
FCKeditor.prototype._HTMLEncode = function( text )
{
if ( typeof( text ) != "string" )
text = text.toString() ;
text = text.replace(
/&/g, "&").replace(
/"/g, """).replace(
/</g, "<").replace(
/>/g, ">") ;
return text ;
}
;(function()
{
var textareaToEditor = function( textarea )
{
var editor = new FCKeditor( textarea.name ) ;
editor.Width = Math.max( textarea.offsetWidth, FCKeditor.MinWidth ) ;
editor.Height = Math.max( textarea.offsetHeight, FCKeditor.MinHeight ) ;
return editor ;
}
/**
* Replace all <textarea> elements available in the document with FCKeditor
* instances.
*
* // Replace all <textarea> elements in the page.
* FCKeditor.ReplaceAllTextareas() ;
*
* // Replace all <textarea class="myClassName"> elements in the page.
* FCKeditor.ReplaceAllTextareas( 'myClassName' ) ;
*
* // Selectively replace <textarea> elements, based on custom assertions.
* FCKeditor.ReplaceAllTextareas( function( textarea, editor )
* {
* // Custom code to evaluate the replace, returning false if it
* // must not be done.
* // It also passes the "editor" parameter, so the developer can
* // customize the instance.
* } ) ;
*/
FCKeditor.ReplaceAllTextareas = function()
{
var textareas = document.getElementsByTagName( 'textarea' ) ;
for ( var i = 0 ; i < textareas.length ; i++ )
{
var editor = null ;
var textarea = textareas[i] ;
var name = textarea.name ;
// The "name" attribute must exist.
if ( !name || name.length == 0 )
continue ;
if ( typeof arguments[0] == 'string' )
{
// The textarea class name could be passed as the function
// parameter.
var classRegex = new RegExp( '(?:^| )' + arguments[0] + '(?:$| )' ) ;
if ( !classRegex.test( textarea.className ) )
continue ;
}
else if ( typeof arguments[0] == 'function' )
{
// An assertion function could be passed as the function parameter.
// It must explicitly return "false" to ignore a specific <textarea>.
editor = textareaToEditor( textarea ) ;
if ( arguments[0]( textarea, editor ) === false )
continue ;
}
if ( !editor )
editor = textareaToEditor( textarea ) ;
editor.ReplaceTextarea() ;
}
}
})() ;
function FCKeditor_IsCompatibleBrowser()
{
var sAgent = navigator.userAgent.toLowerCase() ;
// Internet Explorer 5.5+
if ( /*@cc_on!@*/false && sAgent.indexOf("mac") == -1 )
{
var sBrowserVersion = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
return ( sBrowserVersion >= 5.5 ) ;
}
// Gecko (Opera 9 tries to behave like Gecko at this point).
if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 && !( typeof(opera) == 'object' && opera.postError ) )
return true ;
// Opera 9.50+
if ( window.opera && window.opera.version && parseFloat( window.opera.version() ) >= 9.5 )
return true ;
// Adobe AIR
// Checked before Safari because AIR have the WebKit rich text editor
// features from Safari 3.0.4, but the version reported is 420.
if ( sAgent.indexOf( ' adobeair/' ) != -1 )
return ( sAgent.match( / adobeair\/(\d+)/ )[1] >= 1 ) ; // Build must be at least v1
// Safari 3+
if ( sAgent.indexOf( ' applewebkit/' ) != -1 )
return ( sAgent.match( / applewebkit\/(\d+)/ )[1] >= 522 ) ; // Build must be at least 522 (v3)
return false ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options
*/
FCKConfig.CustomConfigurationsPath = '' ;
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
FCKConfig.EditorAreaStyles = '' ;
FCKConfig.ToolbarComboPreviewCSS = '' ;
FCKConfig.DocType = '' ;
FCKConfig.BaseHref = '' ;
FCKConfig.FullPage = false ;
// The following option determines whether the "Show Blocks" feature is enabled or not at startup.
FCKConfig.StartupShowBlocks = false ;
FCKConfig.Debug = false ;
FCKConfig.AllowQueryStringDebug = true ;
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ;
FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ;
FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;
// FCKConfig.Plugins.Add( 'autogrow' ) ;
// FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.AutoGrowMax = 400 ;
// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%>
// FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code
// FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control>
FCKConfig.AutoDetectLanguage = true ;
FCKConfig.DefaultLanguage = 'zh-cn' ;
FCKConfig.ContentLangDirection = 'ltr' ;
FCKConfig.ProcessHTMLEntities = true ;
FCKConfig.IncludeLatinEntities = true ;
FCKConfig.IncludeGreekEntities = true ;
FCKConfig.ProcessNumericEntities = false ;
FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'"
FCKConfig.FillEmptyBlocks = true ;
FCKConfig.FormatSource = true ;
FCKConfig.FormatOutput = true ;
FCKConfig.FormatIndentator = ' ' ;
FCKConfig.EMailProtection = 'encode' ; // none | encode | function
FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ;
FCKConfig.StartupFocus = false ;
FCKConfig.ForcePasteAsPlainText = false ;
FCKConfig.AutoDetectPasteFromWord = true ; // IE only.
FCKConfig.ShowDropDialog = true ;
FCKConfig.ForceSimpleAmpersand = false ;
FCKConfig.TabSpaces = 0 ;
FCKConfig.ShowBorders = true ;
FCKConfig.SourcePopup = false ;
FCKConfig.ToolbarStartExpanded = true ;
FCKConfig.ToolbarCanCollapse = true ;
FCKConfig.IgnoreEmptyParagraphValue = true ;
FCKConfig.FloatingPanelsZIndex = 10000 ;
FCKConfig.HtmlEncodeOutput = false ;
FCKConfig.PreserveSessionOnFileBrowser = false ;
FCKConfig.TemplateReplaceAll = true ;
FCKConfig.TemplateReplaceCheckbox = true ;
FCKConfig.ToolbarLocation = 'In' ;
FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','UpFileBtn','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;
FCKConfig.ToolbarSets["Basic"] = [
['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About']
] ;
FCKConfig.ToolbarSets["Normal"] = [
['Cut','Copy','Paste','PasteText','PasteWord','-','Undo','Redo','-','Find','Replace','-','RemoveFormat'],
['Link','Unlink','-','Image','Flash','UpFileBtn','Table'],
['FitWindow','-','Source'],
'/',
['FontFormat','FontSize'],
['Bold','Italic','Underline'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
['JustifyLeft','JustifyCenter','JustifyRight'],
['TextColor','BGColor']
] ;
FCKConfig.ToolbarSets["Mail"] = [
['Cut','Copy','Paste','PasteText','PasteWord','-','Undo','Redo','-','Find','Replace','-','RemoveFormat'],
['Table'],
['FitWindow','-','Source'],
'/',
['FontFormat','FontSize'],
['Bold','Italic','Underline'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
['JustifyLeft','JustifyCenter','JustifyRight'],
['TextColor','BGColor']
];
FCKConfig.EnterMode = 'p' ; // p | div | br
FCKConfig.ShiftEnterMode = 'br' ; // p | div | br
FCKConfig.Keystrokes = [
[ CTRL + 65 /*A*/, true ],
[ CTRL + 67 /*C*/, true ],
[ CTRL + 70 /*F*/, true ],
[ CTRL + 83 /*S*/, true ],
[ CTRL + 84 /*T*/, true ],
[ CTRL + 88 /*X*/, true ],
[ CTRL + 86 /*V*/, 'Paste' ],
[ CTRL + 45 /*INS*/, true ],
[ SHIFT + 45 /*INS*/, 'Paste' ],
[ CTRL + 88 /*X*/, 'Cut' ],
[ SHIFT + 46 /*DEL*/, 'Cut' ],
[ CTRL + 90 /*Z*/, 'Undo' ],
[ CTRL + 89 /*Y*/, 'Redo' ],
[ CTRL + SHIFT + 90 /*Z*/, 'Redo' ],
[ CTRL + 76 /*L*/, 'Link' ],
[ CTRL + 66 /*B*/, 'Bold' ],
[ CTRL + 73 /*I*/, 'Italic' ],
[ CTRL + 85 /*U*/, 'Underline' ],
[ CTRL + SHIFT + 83 /*S*/, 'Save' ],
[ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ],
[ SHIFT + 32 /*SPACE*/, 'Nbsp' ]
] ;
FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ;
FCKConfig.BrowserContextMenuOnCtrl = false ;
FCKConfig.BrowserContextMenu = false ;
FCKConfig.EnableMoreFontColors = true ;
FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ;
FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ;
FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ;
FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ;
FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ;
FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages'
FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ;
FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl
FCKConfig.FirefoxSpellChecker = false ;
FCKConfig.MaxUndoLevels = 15 ;
FCKConfig.DisableObjectResizing = false ;
FCKConfig.DisableFFTableHandles = true ;
FCKConfig.LinkDlgHideTarget = false ;
FCKConfig.LinkDlgHideAdvanced = false ;
FCKConfig.ImageDlgHideLink = false ;
FCKConfig.ImageDlgHideAdvanced = false ;
FCKConfig.FlashDlgHideAdvanced = false ;
FCKConfig.ProtectedTags = '' ;
// This will be applied to the body element of the editor
FCKConfig.BodyId = '' ;
FCKConfig.BodyClass = '' ;
FCKConfig.DefaultStyleLabel = '' ;
FCKConfig.DefaultFontFormatLabel = '' ;
FCKConfig.DefaultFontLabel = '' ;
FCKConfig.DefaultFontSizeLabel = '' ;
FCKConfig.DefaultLinkTarget = '' ;
// The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word
FCKConfig.CleanWordKeepsStructure = false ;
// Only inline elements are valid.
FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ;
// Attributes that will be removed
FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ;
FCKConfig.CustomStyles =
{
'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } }
};
// Do not add, rename or remove styles here. Only apply definition changes.
FCKConfig.CoreStyles =
{
// Basic Inline Styles.
'Bold' : { Element : 'strong', Overrides : 'b' },
'Italic' : { Element : 'em', Overrides : 'i' },
'Underline' : { Element : 'u' },
'StrikeThrough' : { Element : 'strike' },
'Subscript' : { Element : 'sub' },
'Superscript' : { Element : 'sup' },
// Basic Block Styles (Font Format Combo).
'p' : { Element : 'p' },
'div' : { Element : 'div' },
'pre' : { Element : 'pre' },
'address' : { Element : 'address' },
'h1' : { Element : 'h1' },
'h2' : { Element : 'h2' },
'h3' : { Element : 'h3' },
'h4' : { Element : 'h4' },
'h5' : { Element : 'h5' },
'h6' : { Element : 'h6' },
// Other formatting features.
'FontFace' :
{
Element : 'span',
Styles : { 'font-family' : '#("Font")' },
Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ]
},
'Size' :
{
Element : 'span',
Styles : { 'font-size' : '#("Size","fontSize")' },
Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ]
},
'Color' :
{
Element : 'span',
Styles : { 'color' : '#("Color","color")' },
Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ]
},
'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } },
'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } }
};
// The distance of an indentation step.
FCKConfig.IndentLength = 40 ;
FCKConfig.IndentUnit = 'px' ;
// Alternatively, FCKeditor allows the use of CSS classes for block indentation.
// This overrides the IndentLength/IndentUnit settings.
FCKConfig.IndentClasses = [] ;
// [ Left, Center, Right, Justified ]
FCKConfig.JustifyClasses = [] ;
// The following value defines which File Browser connector and Quick Upload
// "uploader" to use. It is valid for the default implementaion and it is here
// just to make this configuration file cleaner.
// It is not possible to change this value using an external file or even
// inline when creating the editor instance. In that cases you must set the
// values of LinkBrowserURL, ImageBrowserURL and so on.
// Custom implementations should just ignore it.
var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
// Don't care about the following two lines. It just calculates the correct connector
// extension to use for the default File Browser (Perl uses "cgi").
var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ;
var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ;
FCKConfig.LinkBrowser = true ;
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70%
FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70%
FCKConfig.ImageBrowser = true ;
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ;
FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ;
FCKConfig.FlashBrowser = true ;
FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ;
FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ;
FCKConfig.LinkUpload = true ;
FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ;
FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all
FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.FilesUpload = true ;
FCKConfig.FilesUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload_more.' + _QuickUploadExtension ;
FCKConfig.FilesUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all
FCKConfig.FilesUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.ImageUpload = true ;
FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ;
FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all
FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.FlashUpload = true ;
FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ;
FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all
FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ;
FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ;
FCKConfig.SmileyColumns = 8 ;
FCKConfig.SmileyWindowWidth = 320 ;
FCKConfig.SmileyWindowHeight = 210 ;
FCKConfig.BackgroundBlockerColor = '#ffffff' ;
FCKConfig.BackgroundBlockerOpacity = 0.50 ;
FCKConfig.MsWebBrowserControlCompat = false ;
FCKConfig.PreventSubmitHandler = false ;
| JavaScript |
/**
* 初始化显示信息
* 在这个函数中将会与浏览器环境进行交互取得用户资料
*/
function initInfo() {
var info = eval("(" + window.external.GetHostInfo() + ")");
$("#head h5").html("与 " + info.username + " 对话中 (" + info.ip + "/" + info.group + ")");
$("#head p").html("对方 <u>" + (info.isabsence ? "离开" : "在线") + "</u>"
+ (info.isabsence ? " (" + info.statemsg + ")" : "") + "," + (info.enc ? "对方支持加密通讯" : "对方不支持加密通讯,消息可能会被嗅探")
+ ",双击标签页关闭此聊天窗口。");
host = info;
//初始化事件
$(".umsg input.openPackage").live("click", openPackage);
}
$(initInfo);
/**
* 添加提示信息
* @param {Object} 要显示信息内容
*/
function applyTipInfo(msg) {
var q = $("<div class='tip'>" + msg + "</div>");
$("#chat").append(q);
autoScroll();
}
/**
* 自动将当前浏览器窗口滚动到结尾
*/
function autoScroll() {
window.scroll(0, document.documentElement.scrollHeight);
}
/**
* 根据指定ID的元素进行定位
* @param {Object} 要定位的元素ID
*/
function hashLocate(id) {
location.hash = "#" + id;
}
/**
* 清空整个信息区域
*/
function clearChatHistory() {
$("#chat").empty();
}
//--------------------------------------------------------------------------------------------------------------------------
var host;
var myIndex = 0;
//--------------------------------------------------------------------------------------------------------------------------
//捕捉状态变化事件
function absenceModeChange(s, i) {
applyTipInfo("对方状态变化为 <strong>" + (s ? "离开" : "在线") + "</strong> " + (s ? "(" + i + ")" : "") + "");
}
//昵称变化
function nickNameChange(a, b) {
applyTipInfo("对方个人信息变化为 <strong>" + a + "</strong> (" + b + ")");
}
//打开封包
function openPackage() {
var inputObj = $(this);
var pid = inputObj.attr("pid");
var msgDiv = $("#umsg_" + pid);
$(".packed").slideUp();
$(".content").slideDown();
//发送阅读信息
window.external.SendOpenSignal(pid);
}
//收到对方消息
function messageReceied(packageNo, isEnc, recvTime, content, isPacked, isPassword, autoOpenPackage, isAutoSend, ap) {
var html = "<div class='umsg' id='umsg_" + packageNo + "'>";
html += "<h5>" + host.username + " " + recvTime + " [编号 " + packageNo + "," + (isEnc ? "RSA加密" : "未加密") + (isPacked ? ",已封包" : "") + (isPassword ? ",密码阅读" : "") + "]</h5>";
if (isPacked) {
html += "<p class='packed'>消息已经封包,需要确认您阅读 <input pid='" + packageNo + "' type='button' class='openPackage' value='打开消息' /></p>";
}
html += "<p class='content " + (isPacked ? "hidden" : "") + "'>" + content + "</p>";
var tip = "";
if (isAutoSend) {
tip += "<li>这是一条自动回复的信息</li>";
}
if (ap != "") {
tip += "<li>本消息根据您的设置,已经于 <strong>" + ap + "</strong> 自动回复</li>";
}
if (tip != '') html += "<div class='tip'><ul>" + tip + "</ul></div>";
html += "</div>";
$("#chat").append($(html));
hashLocate("umsg_" + packageNo);
}
//发送消息给对方
function messageSend(un, sendTime, content) {
var html = "<div class='mmsg' id='mmsg_" + myIndex + "'>";
html += "<h5>" + host.username + " " + sendTime + "</h5>";
html += "<p class='content'>" + content + "</p>";
html += "</div>";
$("#chat").append($(html));
hashLocate("mmsg_" + (myIndex++));
}
//=======================================================文件传输部分=======================================================
var fileState = ["等待中", "初始化中", "传输中", "传输失败", "已完成", "正在取消", "已取消"];
var errDesc = ["打开文件", "打开目录", "创建目录", "创建文件", "写入数据"];
function fileOpError(type, path) {
applyTipInfo("文件读取或创建失败,操作:<strong>" + errDesc[type] + "</strong>,文件(夹):<strong>" + path + "</strong>");
}
//=======================================================文件发送部分=======================================================
var filesendIndex = 0;
//拖动文件准备发送
function fileSendingPre(isDirectory, path, size) {
var obj = $("#filesend_pre");
if (obj.length == 0) {
var html = new Array();
html.push('<div class="filesend" id="filesend_pre">');
html.push('<h5>准备发送文件</h5><div class="list"></div><p>您可以继续拖动文件到这个窗口来增加到列表 <input type="button" class="send" value="确定发送" /> <input type="button" class="cancel" value="取消发送" /></p></div>');
html = $(html.join(""));
$("input.send", html).click(submitFileSendDiv);
$("input.cancel", html).click(clearFileSendPreDiv);
$("#chat").append(html);
autoScroll();
obj = html;
}
var newEntry = "[" + (++filesendIndex) + "] <strong>" + path + "</strong> " + (isDirectory ? "[文件夹]" : size) + "<br />";
$(".list", obj).append(newEntry);
hashLocate("filesend_pre");
}
/*确定发送文件*/
function submitFileSendDiv() {
window.external.SubmitFileSend();
}
function clearFileSendPreDiv() {
window.external.ClearFileSendQueue();
$("#filesend_pre").remove();
filesendIndex = 0;
}
//请求发送文件
function fileSendingRequest(v) {
v = eval("(" + v + ")");
var html = new Array();
html.push('<div class="filesend" id="filesend_' + v.pkgid + '">');
html.push('<h5>请求发送文件 [' + v.pkgid + ']</h5><div class="list"><table><tr><th>文件数</th><th>平均速度</th><th>总大小</th><th>已传输</th><th>进度</th><th>已用时间</th><th>剩余时间</th></tr>');
for (var i in v.tasks) {
var o = v.tasks[i];
html.push('<tr idx="' + i + '"><td class="filename" colspan="6"><div style="width:0%;"></div><p>' + o.filename + '</p> </td><td class="state">等待ing</td></tr>');
html.push('<tr idt="' + i + '"><td class="filenum">' + o.sended + '/' + o.filecount + '</td><td class="speed">----</td><td class="sizetotal">' + o.filesize + '</td><td class="sizesend">' + o.sizesended + '</td><td class="percentage">0%</td><td class="usedtime">' + o.timeused + '</td><td class="resttime">' + o.timerest + '</td></tr>');
}
html.push('</table></div><p>等待对方接收</p></div>');
$("#chat").append($(html.join("")));
}
function fileSendingStateChange(pkgid, idx, filename, curName, state) {
var obj = $("#filesend_" + pkgid);
var td = $("tr[idx=" + (idx) + "]", obj);
$(".state", td).html(fileState[state]);
$(">p", obj).html(filename + " " + fileState[state]);
if (state == 4) {
td.remove();
$("tr[idt=" + (idx) + "]", obj).remove();
}
if (state == 3) applyTipInfo("<strong>" + curName + "</strong> 发送失败,等待对方重新接收。");
else if (state == 4) applyTipInfo("<strong>" + curName + "</strong> 发送成功。");
}
function fileSendingTaskFinished(pkgid) {
setTimeout('$("#filesend_' + pkgid + '").remove();', 1000);
}
function fileSendingDiscard(pkgid, cnt) {
applyTipInfo(host.username + " 已经忽略了您发送的文件 (编号 " + pkgid + "),包含下列文件或文件夹:" + cnt);
fileSendingTaskFinished(pkgid);
}
function fileSendingExpired(pkgid, dt) {
applyTipInfo("您于 <strong>" + dt + "</strong> 发送给 " + host.username + " 的文件,对方超时未接收 (编号 " + pkgid + ")");
fileSendingTaskFinished(pkgid);
}
function fileSendingProgressChange(v) {
v = eval("(" + v + ")");
var obj = $("#filesend_" + v.pkgid);
var td = $("tr[idx=" + v.index + "]", obj);
$(".filename div", td).css({ width: v.percentage + "%" });
td = $("table tr[idt=" + v.index + "]", obj);
$(".filenum", td).html(v.sended + "/" + v.filecount);
$(".speed", td).html(v.speed);
$(".sizetotal", td).html(v.filesize);
$(".sizesend", td).html(v.sizesended);
$(".percentage", td).html(v.percentage + " %");
$(".usedtime", td).html(v.timeused);
$(".resttime", td).html(v.timerest);
if (v.state == 2) $(">p", obj).html("正在发送 " + v.filename);
}
/*收到对方文件发送请求*/
function receiveFileRequired(task, saveToSameLocation) {
task = eval("(" + task + ")");
if (task.isretry) {
denyTask = task;
setTimeout("_receiveFileRequired(null,"+saveToSameLocation+");", 1500);
} else {
_receiveFileRequired(task, saveToSameLocation);
}
}
var denyTask = null;
/*收到对方文件发送请求*/
function _receiveFileRequired(task, saveToSameLocation) {
if (task == null) {
task = denyTask;
denyTask = null;
}
var html = new Array();
html.push('<div class="fileAttach" pkgid="' + task.pkgid + '"><h5>对方请求发送文件</h5><table>');
html.push('<tr><th class="idx">序号</th><th class="filename">名称</th><th class="size">大小</th><th class="location">保存位置</th></tr>');
var list = task.tasks;
for (var i in list) {
var t = list[i];
html.push('<tr idx="' + i + '" pkgid="' + task.pkgid + '" tp="' + t.isfolder + '"><td>' + i + '</td><td>' + t.filename + '</td><td>' + t.filesize + (t.isfolder?"(文件夹)":"") + '</td><td><input type="text" readonly="readonly" class="pathtxt" value="' + t.path + '" /><input type="button" value="..." class="browser" /></td></tr>');
}
html.push('</table>');
html.push('<p><input type="checkbox" />保存到同一个目录<input type="button" value="确定接收" class="ok" /><input type="button" value="忽略文件" class="cancel" /></p>');
html.push('</div>');
var cnt = $(html.join(""));
$("#chat").append(cnt);
//Init state
$(":checkbox", cnt).click(function() { window.external.SelectSetSaveFolder(this.checked); })[0].checked = saveToSameLocation;
//init call
$(".browser", cnt).click(selectReceiveFilePath);
$(".cancel", cnt).click(function() {
window.external.CancelFileReceive(task.pkgid);
cnt.remove();
});
$(".ok", cnt).click(function() {
var ok = true;
$(":text", cnt).each(function() { if (!ok) return; if ($(this).val() == "") { ok = false; alert("您尚未选择部分文件的路径!"); } });
if (!ok) return;
window.external.SubmitFileReceive(task.pkgid);
cnt.remove();
});
}
function selectReceiveFilePath() {
var _btn = $(this);
var _td = _btn.parent();
var _tr = _td.parent();
var idx = _tr.attr("idx");
var pkgid = _tr.attr("pkgid");
var _curpath = $(":text", _td).val();
var _filename = $("td:eq(1)", _tr).html();
var _filesize = $("td:eq(2)", _tr).html();
var _tp = _tr.attr("tp");
// if (_tp == 0) {
// _curpath = window.external.SelectSavePath("请选择保存 " + _filename + "(" + _filesize + ") 的位置", _curpath);
// } else {
_curpath = window.external.SelectSaveFolder("请选择保存 " + _filename + "(" + _filesize + ") 的位置", _curpath, pkgid + '', idx + '');
// }
if (_curpath != null && _curpath != "") {
$(":text", _td).val(_curpath);
if ($(".fileAttach :checkbox")[0].checked) {
$(".pathtxt", _tr.parent()).val(_curpath);
}
}
}
//接收文件
function fileRecvRequest(v) {
v = eval("(" + v + ")");
var html = new Array();
html.push('<div class="filerecv" id="filerecv_' + v.pkgid + '">');
html.push('<h5>接收文件 [' + v.pkgid + ']</h5><div class="list"><table><tr><th>文件数</th><th>平均速度</th><th>总大小</th><th>已传输</th><th>进度</th><th>已用时间</th><th>剩余时间</th></tr>');
for (var i in v.tasks) {
var o = v.tasks[i];
html.push('<tr idx="' + i + '"><td class="filename" colspan="6"><div style="width:0%;"></div><p>' + o.filename + '</p> </td><td class="state">等待ing</td></tr>');
html.push('<tr idt="' + i + '"><td class="filenum">' + o.sended + '/' + o.filecount + '</td><td class="speed">----</td><td class="sizetotal">' + o.filesize + '</td><td class="sizesend">' + o.sizesended + '</td><td class="percentage">0%</td><td class="usedtime">' + o.timeused + '</td><td class="resttime">' + o.timerest + '</td></tr>');
}
html.push('</table></div><p>正在连接</p></div>');
$("#chat").append($(html.join("")));
}
function fileRecvStateChange(pkgid, idx, filename, curName, state) {
var obj = $("#filerecv_" + pkgid);
var td = $("tr[idx=" + (idx) + "]", obj);
$(".state", td).html(fileState[state]);
$(">p", obj).html(filename + " " + fileState[state]);
if (state == 4) {
td.remove();
$("tr[idt=" + (idx) + "]", obj).remove();
}
if (state == 3) applyTipInfo("<strong>" + curName + "</strong> 接收失败,请稍后重试。");
else if (state == 4) applyTipInfo("<strong>" + curName + "</strong> 接收成功。");
}
function fileRecvTaskFinished(pkgid) {
setTimeout('$("#filerecv_'+pkgid+'").remove();', 1000);
}
function fileRecvProgressChange(v) {
v = eval("(" + v + ")");
var obj = $("#filerecv_" + v.pkgid);
var td = $("tr[idx=" + v.index + "]", obj);
$(".filename div", td).css({ width: v.percentage + "%" });
td = $("table tr[idt=" + v.index + "]", obj);
$(".filenum", td).html(v.sended + "/" + v.filecount);
$(".speed", td).html(v.speed);
$(".sizetotal", td).html(v.filesize);
$(".sizesend", td).html(v.sizesended);
$(".percentage", td).html(v.percentage + " %");
$(".usedtime", td).html(v.timeused);
$(".resttime", td).html(v.timerest);
if (v.state == 2) $(">p", obj).html("正在接收 " + v.filename);
}
| JavaScript |
/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery-ui-1.8.11.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="knockout-2.0.0.debug.js" />
/// <reference path="modernizr-2.0.6-development-only.js" /> | JavaScript |
/*!
* Note: While Microsoft is not the author of this script file, Microsoft
* grants you the right to use this file for the sole purpose of either:
* (i) interacting through your browser with the Microsoft website, subject
* to the website's terms of use; or (ii) using the files as included with a
* Microsoft product subject to the Microsoft Software License Terms for that
* Microsoft product. Microsoft reserves all other rights to the files not
* expressly granted by Microsoft, whether by implication, estoppel or
* otherwise. The notices and licenses below are for informational purposes
* only.
*
* Provided by Informational Purposes Only
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Modernizr v2.0.6
* http://www.modernizr.com
*
* Copyright (c) 2009-2011 Faruk Ates, Paul Irish, Alex Sexton
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* <html> element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton,
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.0.6',
Modernizr = {},
// option for enabling the HTML classes to be added
enableClasses = true,
docElement = document.documentElement,
docHead = document.head || document.getElementsByTagName('head')[0],
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem = document.createElement('input'),
smile = ':)',
toString = Object.prototype.toString,
// List of property values to set for css tests. See ticket #21
prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
// Following spec is to expose vendor-specific style properties as:
// elem.style.WebkitBorderRadius
// and the following would be incorrect:
// elem.style.webkitBorderRadius
// Webkit ghosts their properties in lowercase but Opera & Moz do not.
// Microsoft foregoes prefixes entirely <= IE8, but appears to
// use a lowercase `ms` instead of the correct `Ms` in IE9
// More here: http://github.com/Modernizr/Modernizr/issues/issue/21
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
ns = {'svg': 'http://www.w3.org/2000/svg'},
tests = {},
inputs = {},
attrs = {},
classes = [],
featureName, // used in testing loop
// Inject element with style element and some CSS rules
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node,
div = document.createElement('div');
if ( parseInt(nodes, 10) ) {
// In order not to give false positives we create a node for each test
// This also allows the method to scale for unspecified uses
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
// <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
// when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
// with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
// http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
style = ['­', '<style>', rule, '</style>'].join('');
div.id = mod;
div.innerHTML += style;
docElement.appendChild(div);
ret = callback(div, rule);
div.parentNode.removeChild(div);
return !!ret;
},
// adapted from matchMedia polyfill
// by Scott Jehl and Paul Irish
// gist.github.com/786768
/*
* The following excerpt, obtained from the above-cited github project, is provided for information purposes only.
*
* matchMedia() polyfill - test whether a CSS media type or media query applies
* primary author: Scott Jehl
* Copyright (c) 2010 Filament Group, Inc
* MIT license
* adapted by Paul Irish to use the matchMedia API
* http://dev.w3.org/csswg/cssom-view/#dom-window-matchmedia
* which webkit now supports: http://trac.webkit.org/changeset/72552
*
* Doesn't implement media.type as there's no way for crossbrowser property
* getters. instead of media.type == 'tv' just use media.matchMedium('tv')
*/
testMediaQuery = function( mq ) {
if ( window.matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
bool = (window.getComputedStyle ?
getComputedStyle(node, null) :
node.currentStyle)['position'] == 'absolute';
});
return bool;
},
/**
* isEventSupported determines if a given element supports the given event
* function from http://yura.thinkweb2.com/isEventSupported/
*/
isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
var isSupported = eventName in element;
if ( !isSupported ) {
// If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = is(element[eventName], 'function');
// If property was created, "remove it" (by setting value to `undefined`)
if ( !is(element[eventName], undefined) ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})();
// hasOwnProperty shim by kangax needed for Safari 2.0 support
var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty;
if ( !is(_hasOwnProperty, undefined) && !is(_hasOwnProperty.call, undefined) ) {
hasOwnProperty = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
return ((property in object) && is(object.constructor.prototype[property], undefined));
};
}
/**
* setCss applies given styles to the Modernizr DOM node.
*/
function setCss( str ) {
mStyle.cssText = str;
}
/**
* setCssAll extrapolates all vendor-specific css strings.
*/
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
/**
* is returns a boolean for if typeof obj is exactly type.
*/
function is( obj, type ) {
return typeof obj === type;
}
/**
* contains returns a boolean for if substr is found within str.
*/
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
/**
* testProps is a generic CSS / DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
* A supported CSS property returns empty string when its not yet set.
*/
function testProps( props, prefixed ) {
for ( var i in props ) {
if ( mStyle[ props[i] ] !== undefined ) {
return prefixed == 'pfx' ? props[i] : true;
}
}
return false;
}
/**
* testPropsAll tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*/
function testPropsAll( prop, prefixed ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1),
props = (prop + ' ' + domPrefixes.join(ucProp + ' ') + ucProp).split(' ');
return testProps(props, prefixed);
}
/**
* testBundle tests a list of CSS features that require element and style injection.
* By bundling them together we can reduce the need to touch the DOM multiple times.
*/
/*>>testBundle*/
var testBundle = (function( styles, tests ) {
var style = styles.join(''),
len = tests.length;
injectElementWithStyles(style, function( node, rule ) {
var style = document.styleSheets[document.styleSheets.length - 1],
// IE8 will bork if you create a custom build that excludes both fontface and generatedcontent tests.
// So we check for cssRules and that there is a rule available
// More here: https://github.com/Modernizr/Modernizr/issues/288 & https://github.com/Modernizr/Modernizr/issues/293
cssText = style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || "",
children = node.childNodes, hash = {};
while ( len-- ) {
hash[children[len].id] = children[len];
}
/*>>touch*/ Modernizr['touch'] = ('ontouchstart' in window) || hash['touch'].offsetTop === 9; /*>>touch*/
/*>>csstransforms3d*/ Modernizr['csstransforms3d'] = hash['csstransforms3d'].offsetLeft === 9; /*>>csstransforms3d*/
/*>>generatedcontent*/Modernizr['generatedcontent'] = hash['generatedcontent'].offsetHeight >= 1; /*>>generatedcontent*/
/*>>fontface*/ Modernizr['fontface'] = /src/i.test(cssText) &&
cssText.indexOf(rule.split(' ')[0]) === 0; /*>>fontface*/
}, len, tests);
})([
// Pass in styles to be injected into document
/*>>fontface*/ '@font-face {font-family:"font";src:url("https://")}' /*>>fontface*/
/*>>touch*/ ,['@media (',prefixes.join('touch-enabled),('),mod,')',
'{#touch{top:9px;position:absolute}}'].join('') /*>>touch*/
/*>>csstransforms3d*/ ,['@media (',prefixes.join('transform-3d),('),mod,')',
'{#csstransforms3d{left:9px;position:absolute}}'].join('')/*>>csstransforms3d*/
/*>>generatedcontent*/,['#generatedcontent:after{content:"',smile,'";visibility:hidden}'].join('') /*>>generatedcontent*/
],
[
/*>>fontface*/ 'fontface' /*>>fontface*/
/*>>touch*/ ,'touch' /*>>touch*/
/*>>csstransforms3d*/ ,'csstransforms3d' /*>>csstransforms3d*/
/*>>generatedcontent*/,'generatedcontent' /*>>generatedcontent*/
]);/*>>testBundle*/
/**
* Tests
* -----
*/
tests['flexbox'] = function() {
/**
* setPrefixedValueCSS sets the property of a specified element
* adding vendor prefixes to the VALUE of the property.
* @param {Element} element
* @param {string} property The property name. This will not be prefixed.
* @param {string} value The value of the property. This WILL be prefixed.
* @param {string=} extra Additional CSS to append unmodified to the end of
* the CSS string.
*/
function setPrefixedValueCSS( element, property, value, extra ) {
property += ':';
element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || '');
}
/**
* setPrefixedPropertyCSS sets the property of a specified element
* adding vendor prefixes to the NAME of the property.
* @param {Element} element
* @param {string} property The property name. This WILL be prefixed.
* @param {string} value The value of the property. This will not be prefixed.
* @param {string=} extra Additional CSS to append unmodified to the end of
* the CSS string.
*/
function setPrefixedPropertyCSS( element, property, value, extra ) {
element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || '');
}
var c = document.createElement('div'),
elem = document.createElement('div');
setPrefixedValueCSS(c, 'display', 'box', 'width:42px;padding:0;');
setPrefixedPropertyCSS(elem, 'box-flex', '1', 'width:10px;');
c.appendChild(elem);
docElement.appendChild(c);
var ret = elem.offsetWidth === 42;
c.removeChild(elem);
docElement.removeChild(c);
return ret;
};
// On the S60 and BB Storm, getContext exists, but always returns undefined
// http://github.com/Modernizr/Modernizr/issues/issue/97/
tests['canvas'] = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
tests['canvastext'] = function() {
return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
};
// This WebGL test may false positive.
// But really it's quite impossible to know whether webgl will succeed until after you create the context.
// You might have hardware that can support a 100x100 webgl canvas, but will not support a 1000x1000 webgl
// canvas. So this feature inference is weak, but intentionally so.
// It is known to false positive in FF4 with certain hardware and the iPad 2.
tests['webgl'] = function() {
return !!window.WebGLRenderingContext;
};
/*
* The Modernizr.touch test only indicates if the browser supports
* touch events, which does not necessarily reflect a touchscreen
* device, as evidenced by tablets running Windows 7 or, alas,
* the Palm Pre / WebOS (touch) phones.
*
* Additionally, Chrome (desktop) used to lie about its support on this,
* but that has since been rectified: http://crbug.com/36415
*
* We also test for Firefox 4 Multitouch Support.
*
* For more info, see: http://modernizr.github.com/Modernizr/touch.html
*/
tests['touch'] = function() {
return Modernizr['touch'];
};
/**
* geolocation tests for the new Geolocation API specification.
* This test is a standards compliant-only test; for more complete
* testing, including a Google Gears fallback, please see:
* http://code.google.com/p/geo-location-javascript/
* or view a fallback solution using google's geo API:
* http://gist.github.com/366184
*/
tests['geolocation'] = function() {
return !!navigator.geolocation;
};
// Per 1.6:
// This used to be Modernizr.crosswindowmessaging but the longer
// name has been deprecated in favor of a shorter and property-matching one.
// The old API is still available in 1.6, but as of 2.0 will throw a warning,
// and in the first release thereafter disappear entirely.
tests['postmessage'] = function() {
return !!window.postMessage;
};
// Web SQL database detection is tricky:
// In chrome incognito mode, openDatabase is truthy, but using it will
// throw an exception: http://crbug.com/42380
// We can create a dummy database, but there is no way to delete it afterwards.
// Meanwhile, Safari users can get prompted on any database creation.
// If they do, any page with Modernizr will give them a prompt:
// http://github.com/Modernizr/Modernizr/issues/closed#issue/113
// We have chosen to allow the Chrome incognito false positive, so that Modernizr
// doesn't litter the web with these test databases. As a developer, you'll have
// to account for this gotcha yourself.
tests['websqldatabase'] = function() {
var result = !!window.openDatabase;
/* if (result){
try {
result = !!openDatabase( mod + "testdb", "1.0", mod + "testdb", 2e4);
} catch(e) {
}
} */
return result;
};
// Vendors had inconsistent prefixing with the experimental Indexed DB:
// - Webkit's implementation is accessible through webkitIndexedDB
// - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
// For speed, we don't test the legacy (and beta-only) indexedDB
tests['indexedDB'] = function() {
for ( var i = -1, len = domPrefixes.length; ++i < len; ){
if ( window[domPrefixes[i].toLowerCase() + 'IndexedDB'] ){
return true;
}
}
return !!window.indexedDB;
};
// documentMode logic from YUI to filter out IE8 Compat Mode
// which false positives.
tests['hashchange'] = function() {
return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
};
// Per 1.6:
// This used to be Modernizr.historymanagement but the longer
// name has been deprecated in favor of a shorter and property-matching one.
// The old API is still available in 1.6, but as of 2.0 will throw a warning,
// and in the first release thereafter disappear entirely.
tests['history'] = function() {
return !!(window.history && history.pushState);
};
tests['draganddrop'] = function() {
return isEventSupported('dragstart') && isEventSupported('drop');
};
// Mozilla is targeting to land MozWebSocket for FF6
// bugzil.la/659324
tests['websockets'] = function() {
for ( var i = -1, len = domPrefixes.length; ++i < len; ){
if ( window[domPrefixes[i] + 'WebSocket'] ){
return true;
}
}
return 'WebSocket' in window;
};
// http://css-tricks.com/rgba-browser-support/
tests['rgba'] = function() {
// Set an rgba() color and check the returned value
setCss('background-color:rgba(150,255,150,.5)');
return contains(mStyle.backgroundColor, 'rgba');
};
tests['hsla'] = function() {
// Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
// except IE9 who retains it as hsla
setCss('background-color:hsla(120,40%,100%,.5)');
return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
};
tests['multiplebgs'] = function() {
// Setting multiple images AND a color on the background shorthand property
// and then querying the style.background property value for the number of
// occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
setCss('background:url(https://),url(https://),red url(https://)');
// If the UA supports multiple backgrounds, there should be three occurrences
// of the string "url(" in the return value for elemStyle.background
return /(url\s*\(.*?){3}/.test(mStyle.background);
};
// In testing support for a given CSS property, it's legit to test:
// `elem.style[styleName] !== undefined`
// If the property is supported it will return an empty string,
// if unsupported it will return undefined.
// We'll take advantage of this quick test and skip setting a style
// on our modernizr element, but instead just testing undefined vs
// empty string.
tests['backgroundsize'] = function() {
return testPropsAll('backgroundSize');
};
tests['borderimage'] = function() {
return testPropsAll('borderImage');
};
// Super comprehensive table about all the unique implementations of
// border-radius: http://muddledramblings.com/table-of-css3-border-radius-compliance
tests['borderradius'] = function() {
return testPropsAll('borderRadius');
};
// WebOS unfortunately false positives on this test.
tests['boxshadow'] = function() {
return testPropsAll('boxShadow');
};
// FF3.0 will false positive on this test
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
};
tests['opacity'] = function() {
// Browsers that actually have CSS Opacity implemented have done so
// according to spec, which means their return values are within the
// range of [0.0,1.0] - including the leading zero.
setCssAll('opacity:.55');
// The non-literal . in this regex is intentional:
// German Chrome returns this value as 0,55
// https://github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
return /^0.55$/.test(mStyle.opacity);
};
tests['cssanimations'] = function() {
return testPropsAll('animationName');
};
tests['csscolumns'] = function() {
return testPropsAll('columnCount');
};
tests['cssgradients'] = function() {
/**
* For CSS Gradients syntax, please see:
* http://webkit.org/blog/175/introducing-css-gradients/
* https://developer.mozilla.org/en/CSS/-moz-linear-gradient
* https://developer.mozilla.org/en/CSS/-moz-radial-gradient
* http://dev.w3.org/csswg/css3-images/#gradients-
*/
var str1 = 'background-image:',
str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
str3 = 'linear-gradient(left top,#9f9, white);';
setCss(
(str1 + prefixes.join(str2 + str1) + prefixes.join(str3 + str1)).slice(0, -str1.length)
);
return contains(mStyle.backgroundImage, 'gradient');
};
tests['cssreflections'] = function() {
return testPropsAll('boxReflect');
};
tests['csstransforms'] = function() {
return !!testProps(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);
};
tests['csstransforms3d'] = function() {
var ret = !!testProps(['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']);
// Webkit’s 3D transforms are passed off to the browser's own graphics renderer.
// It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
// some conditions. As a result, Webkit typically recognizes the syntax but
// will sometimes throw a false positive, thus we must do a more thorough check:
if ( ret && 'webkitPerspective' in docElement.style ) {
// Webkit allows this media query to succeed only if the feature is enabled.
// `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }`
ret = Modernizr['csstransforms3d'];
}
return ret;
};
tests['csstransitions'] = function() {
return testPropsAll('transitionProperty');
};
/*>>fontface*/
// @font-face detection routine by Diego Perini
// http://javascript.nwbox.com/CSSSupport/
tests['fontface'] = function() {
return Modernizr['fontface'];
};
/*>>fontface*/
// CSS generated content detection
tests['generatedcontent'] = function() {
return Modernizr['generatedcontent'];
};
// These tests evaluate support of the video/audio elements, as well as
// testing what types of content they support.
//
// We're using the Boolean constructor here, so that we can extend the value
// e.g. Modernizr.video // true
// Modernizr.video.ogg // 'probably'
//
// Codec values from : http://github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
// thx to NielsLeenheer and zcorpan
// Note: in FF 3.5.1 and 3.5.0, "no" was a return value instead of empty string.
// Modernizr does not normalize for that.
tests['video'] = function() {
var elem = document.createElement('video'),
bool = false;
// IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('video/ogg; codecs="theora"');
// Workaround required for IE9, which doesn't report video support without audio codec specified.
// bug 599718 @ msft connect
var h264 = 'video/mp4; codecs="avc1.42E01E';
bool.h264 = elem.canPlayType(h264 + '"') || elem.canPlayType(h264 + ', mp4a.40.2"');
bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"');
}
} catch(e) { }
return bool;
};
tests['audio'] = function() {
var elem = document.createElement('audio'),
bool = false;
try {
if ( bool = !!elem.canPlayType ) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
bool.mp3 = elem.canPlayType('audio/mpeg;');
// Mimetypes accepted:
// https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// http://bit.ly/iphoneoscodecs
bool.wav = elem.canPlayType('audio/wav; codecs="1"');
bool.m4a = elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;');
}
} catch(e) { }
return bool;
};
// Firefox has made these tests rather unfun.
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw http://bugzil.la/365772 if cookies are disabled
// However, in Firefox 4 betas, if dom.storage.enabled == false, just mentioning
// the property will throw an exception. http://bugzil.la/599479
// This looks to be fixed for FF4 Final.
// Because we are forced to try/catch this, we'll go aggressive.
// FWIW: IE8 Compat mode supports these features completely:
// http://www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
tests['localstorage'] = function() {
try {
return !!localStorage.getItem;
} catch(e) {
return false;
}
};
tests['sessionstorage'] = function() {
try {
return !!sessionStorage.getItem;
} catch(e){
return false;
}
};
tests['webworkers'] = function() {
return !!window.Worker;
};
tests['applicationcache'] = function() {
return !!window.applicationCache;
};
// Thanks to Erik Dahlstrom
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
// specifically for SVG inline in HTML, not within XHTML
// test page: paulirish.com/demo/inline-svg
tests['inlinesvg'] = function() {
var div = document.createElement('div');
div.innerHTML = '<svg/>';
return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
};
// Thanks to F1lt3r and lucideer, ticket #35
tests['smil'] = function() {
return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
};
tests['svgclippaths'] = function() {
// Possibly returns a false positive in Safari 3.2?
return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
};
// input features and input types go directly onto the ret object, bypassing the tests loop.
// Hold this guy to execute in a moment.
function webforms() {
// Run through HTML5's new input attributes to see if the UA understands any.
// We're using f which is the <input> element created early on
// Mike Taylr has created a comprehensive resource for testing these attributes
// when applied to all input types:
// http://miketaylr.com/code/input-type-attr.html
// spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
// Only input placeholder is tested while textarea's placeholder is not.
// Currently Safari 4 and Opera 11 have support only for the input placeholder
// Both tests are available in feature-detects/forms-placeholder.js
Modernizr['input'] = (function( props ) {
for ( var i = 0, len = props.length; i < len; i++ ) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
return attrs;
})('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
// Run through HTML5's new input types to see if the UA understands any.
// This is put behind the tests runloop because it doesn't return a
// true/false like all the other tests; instead, it returns an object
// containing each input type with its corresponding true/false value
// Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/
Modernizr['inputtypes'] = (function(props) {
for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
inputElem.setAttribute('type', inputElemType = props[i]);
bool = inputElem.type !== 'text';
// We first check to see if the type we give it sticks..
// If the type does, we feed it a textual value, which shouldn't be valid.
// If the value doesn't stick, we know there's input sanitization which infers a custom UI
if ( bool ) {
inputElem.value = smile;
inputElem.style.cssText = 'position:absolute;visibility:hidden;';
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
// Safari 2-4 allows the smiley as a value, despite making a slider
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
// Mobile android web browser has false positive, so must
// check the height to see if the widget is actually there.
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
} else if ( /^(search|tel)$/.test(inputElemType) ){
// Spec doesnt define any special parsing or detectable UI
// behaviors so we pass these through as true
// Interestingly, opera fails the earlier test, so it doesn't
// even make it here.
} else if ( /^(url|email)$/.test(inputElemType) ) {
// Real url and email support comes with prebaked validation.
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else if ( /^color$/.test(inputElemType) ) {
// chuck into DOM and force reflow for Opera bug in 11.00
// github.com/Modernizr/Modernizr/issues#issue/159
docElement.appendChild(inputElem);
docElement.offsetWidth;
bool = inputElem.value != smile;
docElement.removeChild(inputElem);
} else {
// If the upgraded input compontent rejects the :) text, we got a winner
bool = inputElem.value != smile;
}
}
inputs[ props[i] ] = !!bool;
}
return inputs;
})('search tel url email datetime date month week time datetime-local number range color'.split(' '));
}
// End of test definitions
// -----------------------
// Run through all tests and detect their support in the current UA.
// todo: hypothetically we could be doing an array of tests and use a basic loop here.
for ( var feature in tests ) {
if ( hasOwnProperty(tests, feature) ) {
// run the test, throw the return value into the Modernizr,
// then based on that boolean, define an appropriate className
// and push it into an array of classes we'll join later.
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
// input tests need to run.
Modernizr.input || webforms();
/**
* addTest allows the user to define their own feature tests
* the result will be added onto the Modernizr object,
* as well as an appropriate className set on the html element
*
* @param feature - String naming the feature
* @param test - Function returning true if feature is supported, false if not
*/
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == "object" ) {
for ( var key in feature ) {
if ( hasOwnProperty( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
// we're going to quit if you're trying to overwrite an existing test
// if we were to allow it, we'd do this:
// var re = new RegExp("\\b(no-)?" + feature + "\\b");
// docElement.className = docElement.className.replace( re, '' );
// but, no rly, stuff 'em.
return;
}
test = typeof test == "boolean" ? test : !!test();
docElement.className += ' ' + (test ? '' : 'no-') + feature;
Modernizr[feature] = test;
}
return Modernizr; // allow chaining.
};
// Reset modElem.cssText to nothing to reduce memory footprint.
setCss('');
modElem = inputElem = null;
//>>BEGIN IEPP
// Enable HTML 5 elements for styling (and printing) in IE.
if ( window.attachEvent && (function(){ var elem = document.createElement('div');
elem.innerHTML = '<elem></elem>';
return elem.childNodes.length !== 1; })() ) {
// iepp v2 by @jon_neal & afarkas : github.com/aFarkas/iepp/
(function(win, doc) {
win.iepp = win.iepp || {};
var iepp = win.iepp,
elems = iepp.html5elements || 'abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video',
elemsArr = elems.split('|'),
elemsArrLen = elemsArr.length,
elemRegExp = new RegExp('(^|\\s)('+elems+')', 'gi'),
tagRegExp = new RegExp('<(\/*)('+elems+')', 'gi'),
filterReg = /^\s*[\{\}]\s*$/,
ruleRegExp = new RegExp('(^|[^\\n]*?\\s)('+elems+')([^\\n]*)({[\\n\\w\\W]*?})', 'gi'),
docFrag = doc.createDocumentFragment(),
html = doc.documentElement,
head = html.firstChild,
bodyElem = doc.createElement('body'),
styleElem = doc.createElement('style'),
printMedias = /print|all/,
body;
function shim(doc) {
var a = -1;
while (++a < elemsArrLen)
// Use createElement so IE allows HTML5-named elements in a document
doc.createElement(elemsArr[a]);
}
iepp.getCSS = function(styleSheetList, mediaType) {
if(styleSheetList+'' === undefined){return '';}
var a = -1,
len = styleSheetList.length,
styleSheet,
cssTextArr = [];
while (++a < len) {
styleSheet = styleSheetList[a];
//currently no test for disabled/alternate stylesheets
if(styleSheet.disabled){continue;}
mediaType = styleSheet.media || mediaType;
// Get css from all non-screen stylesheets and their imports
if (printMedias.test(mediaType)) cssTextArr.push(iepp.getCSS(styleSheet.imports, mediaType), styleSheet.cssText);
//reset mediaType to all with every new *not imported* stylesheet
mediaType = 'all';
}
return cssTextArr.join('');
};
iepp.parseCSS = function(cssText) {
var cssTextArr = [],
rule;
while ((rule = ruleRegExp.exec(cssText)) != null){
// Replace all html5 element references with iepp substitute classnames
cssTextArr.push(( (filterReg.exec(rule[1]) ? '\n' : rule[1]) +rule[2]+rule[3]).replace(elemRegExp, '$1.iepp_$2')+rule[4]);
}
return cssTextArr.join('\n');
};
iepp.writeHTML = function() {
var a = -1;
body = body || doc.body;
while (++a < elemsArrLen) {
var nodeList = doc.getElementsByTagName(elemsArr[a]),
nodeListLen = nodeList.length,
b = -1;
while (++b < nodeListLen)
if (nodeList[b].className.indexOf('iepp_') < 0)
// Append iepp substitute classnames to all html5 elements
nodeList[b].className += ' iepp_'+elemsArr[a];
}
docFrag.appendChild(body);
html.appendChild(bodyElem);
// Write iepp substitute print-safe document
bodyElem.className = body.className;
bodyElem.id = body.id;
// Replace HTML5 elements with <font> which is print-safe and shouldn't conflict since it isn't part of html5
bodyElem.innerHTML = body.innerHTML.replace(tagRegExp, '<$1font');
};
iepp._beforePrint = function() {
// Write iepp custom print CSS
styleElem.styleSheet.cssText = iepp.parseCSS(iepp.getCSS(doc.styleSheets, 'all'));
iepp.writeHTML();
};
iepp.restoreHTML = function(){
// Undo everything done in onbeforeprint
bodyElem.innerHTML = '';
html.removeChild(bodyElem);
html.appendChild(body);
};
iepp._afterPrint = function(){
// Undo everything done in onbeforeprint
iepp.restoreHTML();
styleElem.styleSheet.cssText = '';
};
// Shim the document and iepp fragment
shim(doc);
shim(docFrag);
//
if(iepp.disablePP){return;}
// Add iepp custom print style element
head.insertBefore(styleElem, head.firstChild);
styleElem.media = 'print';
styleElem.className = 'iepp-printshim';
win.attachEvent(
'onbeforeprint',
iepp._beforePrint
);
win.attachEvent(
'onafterprint',
iepp._afterPrint
);
})(window, document);
}
//>>END IEPP
// Assign private properties to the return object with prefix
Modernizr._version = version;
// expose these for the plugin API. Look in the source for how to join() them against your input
Modernizr._prefixes = prefixes;
Modernizr._domPrefixes = domPrefixes;
// Modernizr.mq tests a given media query, live against the current state of the window
// A few important notes:
// * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
// * A max-width or orientation query will be evaluated against the current state, which may change later.
// * You must specify values. Eg. If you are testing support for the min-width media query use:
// Modernizr.mq('(min-width:0)')
// usage:
// Modernizr.mq('only screen and (max-width:768)')
Modernizr.mq = testMediaQuery;
// Modernizr.hasEvent() detects support for a given event, with an optional element to test on
// Modernizr.hasEvent('gesturestart', elem)
Modernizr.hasEvent = isEventSupported;
// Modernizr.testProp() investigates whether a given style property is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testProp('pointerEvents')
Modernizr.testProp = function(prop){
return testProps([prop]);
};
// Modernizr.testAllProps() investigates whether a given style property,
// or any of its vendor-prefixed variants, is recognized
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testAllProps('boxSizing')
Modernizr.testAllProps = testPropsAll;
// Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
// Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
Modernizr.testStyles = injectElementWithStyles;
// Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
// Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
// Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
// Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
//
// str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
// If you're trying to ascertain which transition end event to bind to, you might do something like...
//
// var transEndEventNames = {
// 'WebkitTransition' : 'webkitTransitionEnd',
// 'MozTransition' : 'transitionend',
// 'OTransition' : 'oTransitionEnd',
// 'msTransition' : 'msTransitionEnd', // maybe?
// 'transition' : 'transitionEnd'
// },
// transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
Modernizr.prefixed = function(prop){
return testPropsAll(prop, 'pfx');
};
// Remove "no-js" class from <html> element, if it exists:
docElement.className = docElement.className.replace(/\bno-js\b/, '')
// Add the new classes to the <html> element.
+ (enableClasses ? ' js ' + classes.join(' ') : '');
return Modernizr;
})(this, this.document); | JavaScript |
/*
* Note: While Microsoft is not the author of this script file, Microsoft
* grants you the right to use this file for the sole purpose of either:
* (i) interacting through your browser with the Microsoft website, subject
* to the website's terms of use; or (ii) using the files as included with a
* Microsoft product subject to the Microsoft Software License Terms for that
* Microsoft product. Microsoft reserves all other rights to the files not
* expressly granted by Microsoft, whether by implication, estoppel or
* otherwise. The notices and licenses below are for informational purposes
* only.
*
* Provided for Informational Purposes Only
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* jQuery Mobile Framework 1.0
* http://jquerymobile.com
*
* Copyright 2011 (c) jQuery Project
*
*/
/*!
* jQuery UI Widget @VERSION
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
*
* http://docs.jquery.com/UI/Widget
*/
(function( $, undefined ) {
// jQuery 1.4+
if ( $.cleanData ) {
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
$( elem ).triggerHandler( "remove" );
}
_cleanData( elems );
};
} else {
var _remove = $.fn.remove;
$.fn.remove = function( selector, keepData ) {
return this.each(function() {
if ( !keepData ) {
if ( !selector || $.filter( selector, [ this ] ).length ) {
$( "*", this ).add( [ this ] ).each(function() {
$( this ).triggerHandler( "remove" );
});
}
}
return _remove.call( $(this), selector, keepData );
});
};
}
$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};
$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
// $.each( basePrototype, function( key, val ) {
// if ( $.isPlainObject(val) ) {
// basePrototype[ key ] = $.extend( {}, val );
// }
// });
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );
$.widget.bridge( name, $[ namespace ][ name ] );
};
$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
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 );
if ( !instance ) {
throw "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'";
}
if ( !$.isFunction( instance[options] ) ) {
throw "no such method '" + options + "' for " + name + " widget instance";
}
var methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, name, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
options: {
disabled: false
},
_createWidget: function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
this._getCreateOptions(),
options );
var self = this;
this.element.bind( "remove." + this.widgetName, function() {
self.destroy();
});
this._create();
this._trigger( "create" );
this._init();
},
_getCreateOptions: function() {
var options = {};
if ( $.metadata ) {
options = $.metadata.get( element )[ this.widgetName ];
}
return options;
},
_create: function() {},
_init: function() {},
destroy: function() {
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
},
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.extend( {}, this.options );
}
if (typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
options = {};
options[ key ] = value;
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var self = this;
$.each( options, function( key, value ) {
self._setOption( key, value );
});
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
[ value ? "addClass" : "removeClass"](
this.widgetBaseClass + "-disabled" + " " +
"ui-state-disabled" )
.attr( "aria-disabled", value );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_trigger: function( type, event, data ) {
var callback = this.options[ type ];
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
data = data || {};
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( event.originalEvent ) {
for ( var i = $.event.props.length, prop; i; ) {
prop = $.event.props[ --i ];
event[ prop ] = event.originalEvent[ prop ];
}
}
this.element.trigger( event, data );
return !( $.isFunction(callback) &&
callback.call( this.element[0], event, data ) === false ||
event.isDefaultPrevented() );
}
};
})( jQuery );
/*
* widget factory extentions for mobile
*/
(function( $, undefined ) {
$.widget( "mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function() {
$.Widget.prototype._createWidget.apply( this, arguments );
this._trigger( 'init' );
},
_getCreateOptions: function() {
var elem = this.element,
options = {};
$.each( this.options, function( option ) {
var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
return "-" + c.toLowerCase();
})
);
if ( value !== undefined ) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function( target ) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
var page = $(target).closest(":jqmData(role='page')").data( "page" ),
keepNative = (page && page.keepNativeSelector()) || "";
$( this.options.initSelector, target ).not( keepNative )[ this.widgetName ]();
}
});
})( jQuery );
/*
* a workaround for window.matchMedia
*/
(function( $, undefined ) {
var $window = $( window ),
$html = $( "html" );
/* $.mobile.media method: pass a CSS media type or query and get a bool return
note: this feature relies on actual media query support for media queries, though types will work most anywhere
examples:
$.mobile.media('screen') //>> tests for screen media type
$.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px
$.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4)
*/
$.mobile.media = (function() {
// TODO: use window.matchMedia once at least one UA implements it
var cache = {},
testDiv = $( "<div id='jquery-mediatest'>" ),
fakeBody = $( "<body>" ).append( testDiv );
return function( query ) {
if ( !( query in cache ) ) {
var styleBlock = document.createElement( "style" ),
cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }";
//must set type for IE!
styleBlock.type = "text/css";
if ( styleBlock.styleSheet ){
styleBlock.styleSheet.cssText = cssrule;
} else {
styleBlock.appendChild( document.createTextNode(cssrule) );
}
$html.prepend( fakeBody ).prepend( styleBlock );
cache[ query ] = testDiv.css( "position" ) === "absolute";
fakeBody.add( styleBlock ).remove();
}
return cache[ query ];
};
})();
})(jQuery);
/*
* support tests
*/
(function( $, undefined ) {
var fakeBody = $( "<body>" ).prependTo( "html" ),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB
// thx Modernizr
function propExists( prop ) {
var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
for ( var v in props ){
if ( fbCSS[ props[ v ] ] !== undefined ) {
return true;
}
}
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $( "head base" ),
fauxEle = null,
href = "",
link, rebase;
if ( !base.length ) {
base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
} else {
href = base.attr( "href" );
}
link = $( "<a href='testurl' />" ).prependTo( fakeBody );
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if ( fauxEle ) {
fauxEle.remove();
}
return rebase.indexOf( fauxBase ) === 0;
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.mobile.browser = {};
$.mobile.browser.ie = (function() {
var v = 3,
div = document.createElement( "div" ),
a = div.all || [];
while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] );
return v > 4 ? v : !v;
})();
$.extend( $.support, {
orientation: "orientation" in window && "onorientationchange" in window,
touch: "ontouchend" in document,
cssTransitions: "WebKitTransitionEvent" in window,
pushState: "pushState" in history && "replaceState" in history,
mediaquery: $.mobile.media( "only all" ),
cssPseudoElement: !!propExists( "content" ),
touchOverflow: !!propExists( "overflowScrolling" ),
boxShadow: !!propExists( "boxShadow" ) && !bb,
scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos && !operamini,
dynamicBaseTag: baseTagTest()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function(){
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf( "Nokia" ) > -1 &&
( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
ua.indexOf( "AppleWebKit" ) > -1 &&
ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
})();
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if ( nokiaLTE7_3 ) {
$(function() {
$( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
});
}
// For ruling out shadows via css
if ( !$.support.boxShadow ) {
$( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
}
})( jQuery );
/*
* "mouse" plugin
*/
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function( $, window, document, undefined ) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $( document ),
nextTouchID = 1,
lastTouchID = 0;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent( event ) {
while ( event && typeof event.originalEvent !== "undefined" ) {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent( event, eventType ) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j;
event = $.Event(event);
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( oe ) {
for ( i = props.length, prop; i; ) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ){
event.which = 1;
}
if ( t.search(/^touch/) !== -1 ) {
ne = getNativeEvent( oe );
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined );
if ( touch ) {
for ( j = 0, len = touchEventProps.length; j < len; j++){
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags( element ) {
var flags = {},
b, k;
while ( element ) {
b = $.data( element, dataPropertyName );
for ( k in b ) {
if ( b[ k ] ) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding( element, eventType ) {
var b;
while ( element ) {
b = $.data( element, dataPropertyName );
if ( b && ( !eventType || b[ eventType ] ) ) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout(function(){
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration );
}
function clearResetTimer() {
if ( resetTimerID ){
clearTimeout( resetTimerID );
resetTimerID = 0;
}
}
function triggerVirtualEvent( eventType, event, flags ) {
var ve;
if ( ( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
ve = createVirtualEvent( event, eventType );
$( event.target).trigger( ve );
}
return ve;
}
function mouseEventCallback( event ) {
var touchID = $.data(event.target, touchTargetPropertyName);
if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){
var ve = triggerVirtualEvent( "v" + event.type, event );
if ( ve ) {
if ( ve.isDefaultPrevented() ) {
event.preventDefault();
}
if ( ve.isPropagationStopped() ) {
event.stopPropagation();
}
if ( ve.isImmediatePropagationStopped() ) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart( event ) {
var touches = getNativeEvent( event ).touches,
target, flags;
if ( touches && touches.length === 1 ) {
target = event.target;
flags = getVirtualBindingFlags( target );
if ( flags.hasVirtualBinding ) {
lastTouchID = nextTouchID++;
$.data( target, touchTargetPropertyName, lastTouchID );
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent( event ).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent( "vmouseover", event, flags );
triggerVirtualEvent( "vmousedown", event, flags );
}
}
}
function handleScroll( event ) {
if ( blockTouchTriggers ) {
return;
}
if ( !didScroll ) {
triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
}
didScroll = true;
startResetTimer();
}
function handleTouchMove( event ) {
if ( blockTouchTriggers ) {
return;
}
var t = getNativeEvent( event ).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold;
didScroll = didScroll ||
( Math.abs(t.pageX - startX) > moveThreshold ||
Math.abs(t.pageY - startY) > moveThreshold ),
flags = getVirtualBindingFlags( event.target );
if ( didScroll && !didCancel ) {
triggerVirtualEvent( "vmousecancel", event, flags );
}
triggerVirtualEvent( "vmousemove", event, flags );
startResetTimer();
}
function handleTouchEnd( event ) {
if ( blockTouchTriggers ) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags( event.target ),
t;
triggerVirtualEvent( "vmouseup", event, flags );
if ( !didScroll ) {
var ve = triggerVirtualEvent( "vclick", event, flags );
if ( ve && ve.isDefaultPrevented() ) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent( event ).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent( "vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings( ele ) {
var bindings = $.data( ele, dataPropertyName ),
k;
if ( bindings ) {
for ( k in bindings ) {
if ( bindings[ k ] ) {
return true;
}
}
}
return false;
}
function dummyMouseHandler(){}
function getSpecialEventObject( eventType ) {
var realType = eventType.substr( 1 );
return {
setup: function( data, namespace ) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if ( !hasVirtualBindings( this ) ) {
$.data( this, dataPropertyName, {});
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data( this, dataPropertyName );
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if ( activeDocHandlers[ eventType ] === 1 ) {
$document.bind( realType, mouseEventCallback );
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$( this ).bind( realType, dummyMouseHandler );
// For now, if event capture is not supported, we rely on mouse handlers.
if ( eventCaptureSupported ) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if (activeDocHandlers[ "touchstart" ] === 1) {
$document.bind( "touchstart", handleTouchStart )
.bind( "touchend", handleTouchEnd )
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind( "touchmove", handleTouchMove )
.bind( "scroll", handleScroll );
}
}
},
teardown: function( data, namespace ) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if ( !activeDocHandlers[ eventType ] ) {
$document.unbind( realType, mouseEventCallback );
}
if ( eventCaptureSupported ) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if ( !activeDocHandlers[ "touchstart" ] ) {
$document.unbind( "touchstart", handleTouchStart )
.unbind( "touchmove", handleTouchMove )
.unbind( "touchend", handleTouchEnd )
.unbind( "scroll", handleScroll );
}
}
var $this = $( this ),
bindings = $.data( this, dataPropertyName );
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if ( bindings ) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind( realType, dummyMouseHandler );
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if ( !hasVirtualBindings( this ) ) {
$this.removeData( dataPropertyName );
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for ( var i = 0; i < virtualEventNames.length; i++ ){
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
document.addEventListener( "click", function( e ){
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if ( cnt ) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while ( ele ) {
for ( i = 0; i < cnt; i++ ) {
o = clickBlockList[ i ];
touchID = 0;
if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
$.data( ele, touchTargetPropertyName ) === o.touchID ) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})( jQuery, window, document );
/*
* "events" plugin - Handles events
*/
(function( $, window, undefined ) {
// add new event shortcuts
$.each( ( "touchstart touchmove touchend orientationchange throttledresize " +
"tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) {
$.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
$.attrFn[ name ] = true;
});
var supportTouch = $.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.handle.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout(function() {
trigger( event, false );
}, 50 );
});
}
};
// also handles taphold
$.event.special.tap = {
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( "vmousedown", function( event ) {
if ( event.which && event.which !== 1 ) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout( timer );
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind( "vclick", clickHandler )
.unbind( "vmouseup", clearTapTimer )
.unbind( "vmousecancel", clearTapHandlers );
}
function clickHandler(event) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if ( origTarget == event.target ) {
triggerCustomEvent( thisObject, "tap", event );
}
}
$this.bind( "vmousecancel", clearTapHandlers )
.bind( "vmouseup", clearTapTimer )
.bind( "vclick", clickHandler );
timer = setTimeout(function() {
triggerCustomEvent( thisObject, "taphold", $.Event( "taphold" ) );
}, 750 );
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( touchStartEvent, function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event,
start = {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
},
stop;
function moveHandler( event ) {
if ( !start ) {
return;
}
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
stop = {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
// prevent scrolling
if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
event.preventDefault();
}
}
$this.bind( touchMoveEvent, moveHandler )
.one( touchStopEvent, function( event ) {
$this.unbind( touchMoveEvent, moveHandler );
if ( start && stop ) {
if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
start.origin.trigger( "swipe" )
.trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
}
}
start = stop = undefined;
});
});
}
};
(function( $, window ) {
// "Cowboy" Ben Alman
var win = $( window ),
special_event,
get_orientation,
last_orientation;
$.event.special.orientationchange = special_event = {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind( "throttledresize", handler );
},
teardown: function(){
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind( "throttledresize", handler );
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function( event ) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply( this, arguments );
};
}
};
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if ( orientation !== last_orientation ) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger( "orientationchange" );
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function() {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ( $.support.orientation ) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = window.orientation % 180 == 0;
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
})( jQuery, window );
// throttled resize event
(function() {
$.event.special.throttledresize = {
setup: function() {
$( this ).bind( "resize", handler );
},
teardown: function(){
$( this ).unbind( "resize", handler );
}
};
var throttle = 250,
handler = function() {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if ( diff >= throttle ) {
lastCall = curr;
$( this ).trigger( "throttledresize" );
} else {
if ( heldCall ) {
clearTimeout( heldCall );
}
// Promise a held call will still execute
heldCall = setTimeout( handler, throttle - diff );
}
},
lastCall = 0,
heldCall,
curr,
diff;
})();
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function( event, sourceEvent ) {
$.event.special[ event ] = {
setup: function() {
$( this ).bind( sourceEvent, $.noop );
}
};
});
})( jQuery, this );
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function($,window,undefined){
'$:nomunge'; // Used by YUI compressor.
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || location.href;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function( fn ) {
return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function(){
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function(val){ return val; },
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function() {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function() {
timeout_id && clearTimeout( timeout_id );
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get( last_hash );
if ( hash !== last_hash ) {
history_set( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
$.browser.msie && !supports_onhashchange && (function(){
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function(){
if ( !iframe ) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one( 'load', function(){
iframe_src || history_set( get_fragment() );
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr( 'src', iframe_src || 'javascript:0' )
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter( 'body' )[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function(){
try {
if ( event.propertyName === 'title' ) {
iframe.document.title = doc.title;
}
} catch(e) {}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function() {
return get_fragment( iframe.location.href );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function( hash, history_hash ) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if ( hash !== history_hash ) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery,this);
/*
* "page" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function() {
this._trigger( "beforecreate" );
this.element
.attr( "tabindex", "0" )
.addClass( "ui-page ui-body-" + this.options.theme );
},
keepNativeSelector: function() {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim(options.keepNative);
if( keepNativeDefined && options.keepNative !== options.keepNativeDefault ){
return [options.keepNative, options.keepNativeDefault].join(", ");
}
return options.keepNativeDefault;
}
});
})( jQuery );
/*
* "core" - The base file for jQm
*/
(function( $, window, undefined ) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.extend( $.mobile, {
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "slide",
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Show loading message during Ajax requests
// if false, message will not appear, but loading classes will still be toggled on html el
loadingMessage: "loading",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
gradeA: function(){
return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7;
},
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function( ypos ) {
if ( $.type( ypos ) !== "number" ) {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout(function() {
window.scrollTo( 0, ypos );
$( document ).trigger( "silentscroll", { x: 0, y: ypos });
}, 20 );
setTimeout(function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function( prop ) {
if ( !prop ) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
},
getInheritedTheme: function( el, defaultTheme ) {
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body)-([a-z])\b/,
c, m;
while ( e ) {
var c = e.className || "";
if ( ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
}
});
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function( prop, value ) {
var result;
if ( typeof prop != "undefined" ) {
result = this.data( prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.jqmData = function( elem, prop, value ) {
var result;
if ( typeof prop != "undefined" ) {
result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.fn.jqmRemoveData = function( prop ) {
return this.removeData( $.mobile.nsNormalize( prop ) );
};
$.jqmRemoveData = function( elem, prop ) {
return $.removeData( elem, $.mobile.nsNormalize( prop ) );
};
$.fn.removeWithDependents = function() {
$.removeWithDependents( this );
};
$.removeWithDependents = function( elem ) {
var $elem = $( elem );
( $elem.jqmData('dependents') || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function( newDependents ) {
$.addDependents( $(this), newDependents );
};
$.addDependents = function( elem, newDependents ) {
var dependents = $(elem).jqmData( 'dependents' ) || $();
$(elem).jqmData( 'dependents', $.merge(dependents, newDependents) );
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html elements text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function() {
return $( "<div/>" ).text( $(this).text() ).html();
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function( selector, context, ret, extra ) {
selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
return oldFind.call( this, selector, context, ret, extra );
};
$.extend( $.find, oldFind );
$.find.matches = function( expr, set ) {
return $.find( expr, null, null, set );
};
$.find.matchesSelector = function( node, expr ) {
return $.find( expr, null, null, [ node ] ).length > 0;
};
})( jQuery, this );
/*
* core utilities for auto ajax navigation, base tag mgmt,
*/
( function( $, undefined ) {
//define vars for interal use
var $window = $( window ),
$html = $( 'html' ),
$head = $( 'head' ),
//url path helpers for use in relative url management
path = {
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:password@mycompany.com:8080/mail/inbox
// [3]: http://jblas:password@mycompany.com:8080
// [4]: http:
// [5]: //
// [6]: jblas:password@mycompany.com:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function( url ) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ( $.type( url ) === "object" ) {
return url;
}
var matches = path.urlParseRE.exec( url || "" ) || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function( relPath, absPath ) {
if ( relPath && relPath.charAt( 0 ) === "/" ) {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
var absStack = absPath ? absPath.split( "/" ) : [],
relStack = relPath.split( "/" );
for ( var i = 0; i < relStack.length; i++ ) {
var d = relStack[ i ];
switch ( d ) {
case ".":
break;
case "..":
if ( absStack.length ) {
absStack.pop();
}
break;
default:
absStack.push( d );
break;
}
}
return "/" + absStack.join( "/" );
},
//Returns true if both urls have the same domain.
isSameDomain: function( absUrl1, absUrl2 ) {
return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function( url ) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl( url ).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function( url ) {
return path.parseUrl( url ).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function( relUrl, absUrl ) {
if ( !path.isRelativeUrl( relUrl ) ) {
return relUrl;
}
var relObj = path.parseUrl( relUrl ),
absObj = path.parseUrl( absUrl ),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function( url, params ) {
var u = path.parseUrl( url ),
p = ( typeof params === "object" ) ? $.param( params ) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function( absUrl ) {
var u = path.parseUrl( absUrl );
if ( path.isEmbeddedPage( u ) ) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// otherwise the Data Url won't match the id of the embedded Page.
return u.hash.split( dialogHashKey )[0].replace( /^#/, "" );
} else if ( path.isSameDomain( u, documentBase ) ) {
return u.hrefNoHash.replace( documentBase.domain, "" );
}
return absUrl;
},
//get path from current hash, or from a file path
get: function( newPath ) {
if( newPath === undefined ) {
newPath = location.hash;
}
return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function( url ) {
return ( /\// ).test( url );
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function( url ) {
return url.replace( documentBase.domain, "" );
},
//just return the url without an initial #
stripHash: function( url ) {
return url.replace( /^#/, "" );
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function( hash ) {
return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ) {
var u = path.parseUrl( url );
return u.protocol && u.domain !== documentUrl.domain ? true : false;
},
hasProtocol: function( url ) {
return ( /^(:?\w+:)/ ).test( url );
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function( url ) {
// We only deal with absolute paths.
var u = path.parseUrl( path.makeUrlAbsolute( url, documentBase ) ),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
},
isEmbeddedPage: function( url ) {
var u = path.parseUrl( url );
//if the path is absolute, then we need to compare the url against
//both the documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if ( u.protocol !== "" ) {
return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) );
}
return (/^#/).test( u.href );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
// Array of pages that are visited during a single page load.
// Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs)
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function() {
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function() {
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function() {
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition, title, pageUrl, role ) {
//if there's forward history, wipe it
if( urlHistory.getNext() ) {
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl, role: role } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function() {
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
directHashChange: function( opts ) {
var back , forward, newActiveIndex, prev = this.getActive();
// check if url isp in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i, historyEntry ) {
//if the url is in the stack, it's a forward or a back
if( opts.currentUrl === historyEntry.url ) {
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
forward = !back;
newActiveIndex = i;
}
});
// save new page index, null check to prevent falsey 0 result
this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex;
if( back ) {
( opts.either || opts.isBack )( true );
} else if( forward ) {
( opts.either || opts.isForward )( false );
}
},
//disable hashchange event listener internally to ignore one change
//toggled internally when location.hash is updated to match the url of a successful page load
ignoreNextHashChange: false
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children( "base" ),
//tuck away the original document URL minus any fragment.
documentUrl = path.parseUrl( location.href ),
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl,
//cache the comparison once.
documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash );
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ) {
base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
},
//set the generated BASE element's href attribute to a new page's base path
reset: function() {
base.element.attr( "href", documentBase.hrefNoHash );
}
} : undefined;
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
function reFocus( page ) {
var pageTitle = page.find( ".ui-title:eq(0)" );
if( pageTitle.length ) {
pageTitle.focus();
}
else{
page.focus();
}
}
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ) {
if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) {
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if( pageTransitionQueue.length > 0 ) {
$.mobile.changePage.apply( null, pageTransitionQueue.pop() );
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
firstScrollElem, getScrollElem, setLastScroll, delayedSetLastScroll;
getScrollElem = function() {
var scrollElem = $window, activePage,
touchOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled;
if( touchOverflow ){
activePage = $( ".ui-page-active" );
scrollElem = activePage.is( ".ui-native-fixed" ) ? activePage.find( ".ui-content" ) : activePage;
}
return scrollElem;
};
setLastScroll = function( scrollElem ) {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if( !setLastScrollEnabled ) {
return;
}
var active = $.mobile.urlHistory.getActive();
if( active ) {
var lastScroll = scrollElem && scrollElem.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function() {
setTimeout( setLastScroll, 100, $(this) );
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one( "pagecontainercreate", function(){
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind( "pagechange", function() {
var scrollElem = getScrollElem();
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
scrollElem.unbind( "scrollstop", delayedSetLastScroll );
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
scrollElem.bind( "scrollstop", delayedSetLastScroll );
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
getScrollElem().bind( "scrollstop", delayedSetLastScroll );
// Make the iOS clock quick-scroll work again if we're using native overflow scrolling
/*
if( $.support.touchOverflow ){
if( $.mobile.touchOverflowEnabled ){
$( window ).bind( "scrollstop", function(){
if( $( this ).scrollTop() === 0 ){
$.mobile.activePage.scrollTop( 0 );
}
});
}
}
*/
//function for transitioning between two existing pages
function transitionPages( toPage, fromPage, transition, reverse ) {
//get current scroll distance
var active = $.mobile.urlHistory.getActive(),
touchOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled,
toScroll = active.lastScroll || ( touchOverflow ? 0 : $.mobile.defaultHomeScroll ),
screenHeight = getScreenHeight();
// Scroll to top, hide addr bar
window.scrollTo( 0, $.mobile.defaultHomeScroll );
if( fromPage ) {
//trigger before show/hide events
fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } );
}
if( !touchOverflow){
toPage.height( screenHeight + toScroll );
}
toPage.data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
//clear page loader
$.mobile.hidePageLoadingMsg();
if( touchOverflow && toScroll ){
toPage.addClass( "ui-mobile-pre-transition" );
// Send focus to page as it is now display: block
reFocus( toPage );
//set page's scrollTop to remembered distance
if( toPage.is( ".ui-native-fixed" ) ){
toPage.find( ".ui-content" ).scrollTop( toScroll );
}
else{
toPage.scrollTop( toScroll );
}
}
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[transition || "none"] || $.mobile.defaultTransitionHandler,
promise = th( transition, reverse, toPage, fromPage );
promise.done(function() {
//reset toPage height back
if( !touchOverflow ){
toPage.height( "" );
// Send focus to the newly shown page
reFocus( toPage );
}
// Jump to top or prev scroll, sometimes on iOS the page has not rendered yet.
if( !touchOverflow ){
$.mobile.silentScroll( toScroll );
}
//trigger show/hide events
if( fromPage ) {
if( !touchOverflow ){
fromPage.height( "" );
}
fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } );
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
function getScreenHeight(){
var orientation = $.event.special.orientationchange.orientation(),
port = orientation === "portrait",
winMin = port ? 480 : 320,
screenHeight = port ? screen.availHeight : screen.availWidth,
winHeight = Math.max( winMin, $( window ).height() ),
pageMin = Math.min( screenHeight, winHeight );
return pageMin;
}
$.mobile.getScreenHeight = getScreenHeight;
//simply set the active page's minimum height to screen height, depending on orientation
function resetActivePageHeight(){
// Don't apply this height in touch overflow enabled mode
if( $.support.touchOverflow && $.mobile.touchOverflowEnabled ){
return;
}
$( "." + $.mobile.activePageClass ).css( "min-height", getScreenHeight() );
}
//shared page enhancements
function enhancePage( $page, role ) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if( role ) {
$page.attr( "data-" + $.mobile.ns + "role", role );
}
//run page plugin
$page.page();
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function( callback ) {
if( $.support.cssTransitions ) {
return $( this ).one( 'webkitAnimationEnd', callback );
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout( callback, 0 );
return $( this );
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//default non-animation transition handler
$.mobile.noneTransitionHandler = function( name, reverse, $toPage, $fromPage ) {
if ( $fromPage ) {
$fromPage.removeClass( $.mobile.activePageClass );
}
$toPage.addClass( $.mobile.activePageClass );
return $.Deferred().resolve( name, reverse, $toPage, $fromPage ).promise();
};
//default handler for unknown transitions
$.mobile.defaultTransitionHandler = $.mobile.noneTransitionHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
none: $.mobile.defaultTransitionHandler
};
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
//return the original document url
$.mobile.getDocumentUrl = function(asParsedObject) {
return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href;
};
//return the original document base url
$.mobile.getDocumentBase = function(asParsedObject) {
return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href;
};
$.mobile._bindPageRemove = function() {
var page = $(this);
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if( !page.data("page").options.domCache
&& page.is(":jqmData(external-page='true')") ) {
page.bind( 'pagehide.remove', function() {
var $this = $( this ),
prEvent = new $.Event( "pageremove" );
$this.trigger( prEvent );
if( !prEvent.isDefaultPrevented() ){
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function( url, options ) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// determine the current base url
findBaseWithDefault = function(){
var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
return closestBase || documentBase.hrefNoHash;
},
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if ( settings.data && settings.type === "get" ) {
absUrl = path.addSearchParams( absUrl, settings.data );
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if( settings.data && settings.type === "post" ){
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath( absUrl ),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl( absUrl );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
page = settings.pageContainer.children( "#" + dataUrl )
.attr( "data-" + $.mobile.ns + "url", dataUrl );
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if ( page.length === 0 ) {
if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ( $.mobile.firstPage.parent().length ) {
page = $( $.mobile.firstPage );
}
} else if ( path.isEmbeddedPage( fileUrl ) ) {
deferred.reject( absUrl, options );
return deferred.promise();
}
}
// Reset base to the default document base.
if ( base ) {
base.reset();
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if ( page.length ) {
if ( !settings.reloadPage ) {
enhancePage( page, settings.role );
deferred.resolve( absUrl, options, page );
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event( "pagebeforeload" ),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger( pblEvent, triggerData );
// If the default behavior is prevented, stop here!
if( pblEvent.isDefaultPrevented() ){
return deferred.promise();
}
if ( settings.showLoadMsg ) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function(){
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay ),
// Shared logic for clearing timeout and removing message.
hideMsg = function(){
// Stop message show timer
clearTimeout( loadMsgDelay );
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
deferred.reject( absUrl, options );
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
dataType: "html",
success: function( html, textStatus, xhr ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $( "<div></div>" ),
//page title regexp
newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if( pageElemRegex.test( html )
&& RegExp.$1
&& dataUrlRegex.test( RegExp.$1 )
&& RegExp.$1 ) {
url = fileUrl = path.getFilePath( RegExp.$1 );
}
if ( base ) {
base.set( fileUrl );
}
//workaround to allow scripts to execute when included in page divs
all.get( 0 ).innerHTML = html;
page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
//if page elem couldn't be found, create one and insert the body element's contents
if( !page.length ){
page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" );
}
if ( newPageTitle && !page.jqmData( "title" ) ) {
if ( ~newPageTitle.indexOf( "&" ) ) {
newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
}
page.jqmData( "title", newPageTitle );
}
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ) {
var newPath = path.get( fileUrl );
page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
var thisAttr = $( this ).is( '[href]' ) ? 'href' :
$(this).is('[src]') ? 'src' : 'action',
thisUrl = $( this ).attr( thisAttr );
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
$( this ).attr( thisAttr, newPath + thisUrl );
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
.attr( "data-" + $.mobile.ns + "external-page", true )
.appendTo( settings.pageContainer );
// wait for page creation to leverage options defined on widget
page.one( 'pagecreate', $.mobile._bindPageRemove );
enhancePage( page, settings.role );
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
}
//bind pageHide to removePage after it's hidden, if the page options specify to do so
// Remove loading message.
if ( settings.showLoadMsg ) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger( "pageload", triggerData );
deferred.resolve( absUrl, options, page, dupCachedPage );
},
error: function( xhr, textStatus, errorThrown ) {
//set base back to current path
if( base ) {
base.set( path.get() );
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event( "pageloadfailed" );
// Let listeners know the page load failed.
settings.pageContainer.trigger( plfEvent, triggerData );
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if( plfEvent.isDefaultPrevented() ){
return;
}
// Remove loading message.
if ( settings.showLoadMsg ) {
// Remove loading message.
hideMsg();
//show error message
$( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" )
.css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 })
.appendTo( settings.pageContainer )
.delay( 800 )
.fadeOut( 400, function() {
$( this ).remove();
});
}
deferred.reject( absUrl, options );
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function( toPage, options ) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if( isPageTransitioning ) {
pageTransitionQueue.unshift( arguments );
return;
}
var settings = $.extend( {}, $.mobile.changePage.defaults, options );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
var mpc = settings.pageContainer,
pbcEvent = new $.Event( "pagebeforechange" ),
triggerData = { toPage: toPage, options: settings };
// Let listeners know we're about to change the current page.
mpc.trigger( pbcEvent, triggerData );
// If the default behavior is prevented, stop here!
if( pbcEvent.isDefaultPrevented() ){
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
toPage = triggerData.toPage;
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if ( typeof toPage == "string" ) {
$.mobile.loadPage( toPage, settings )
.done(function( url, options, newPage, dupCachedPage ) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
$.mobile.changePage( newPage, options );
})
.fail(function( url, options ) {
isPageTransitioning = false;
//clear out the active button state
removeActiveLinkClass( true );
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger( "pagechangefailed", triggerData );
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath( url ),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
isPageTransitioning = false;
mpc.trigger( "pagechange", triggerData );
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage( toPage, settings.role );
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if( settings.fromHashChange ) {
urlHistory.directHashChange({
currentUrl: url,
isBack: function() { historyDir = -1; },
isForward: function() { historyDir = 1; }
});
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a live() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if(document.activeElement && document.activeElement.nodeName.toLowerCase() != 'body') {
$(document.activeElement).blur();
} else {
$( "input:focus, textarea:focus, select:focus" ).blur();
}
} catch(e) {}
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if ( isDialog && active ) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
url = ( active.url || "" ) + dialogHashKey;
}
// Set the location hash.
if( settings.changeHash !== false && url ) {
//disable hash listening temporarily
urlHistory.ignoreNextHashChange = true;
//update hash and history
path.set( url );
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).getEncodedText();
if( !!newPageTitle && pageTitle == document.title ) {
pageTitle = newPageTitle;
}
if ( !toPage.jqmData( "title" ) ) {
toPage.jqmData( "title", pageTitle );
}
// Make sure we have a transition defined.
settings.transition = settings.transition
|| ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined )
|| ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if( !historyDir ) {
urlHistory.addNew( url, settings.transition, pageTitle, pageUrl, settings.role );
}
//set page title
document.title = urlHistory.getActive().title;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages( toPage, fromPage, settings.transition, settings.reverse )
.done(function() {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if ( settings.duplicateCachedPage ) {
settings.duplicateCachedPage.remove();
}
//remove initial build class (only present on first pageshow)
$html.removeClass( "ui-mobile-rendering" );
releasePageTransitionLock();
// Let listeners know we're all done changing the current page.
mpc.trigger( "pagechange", triggerData );
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink( ele )
{
while ( ele ) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() == "a" ) {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl( ele )
{
// Find the closest page and extract out its url.
var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
base = documentBase.hrefNoHash;
if ( !url || !path.isPath( url ) ) {
url = base;
}
return path.makeUrlAbsolute( url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following function is called in the init file
$.mobile._registerInternalEvents = function(){
//bind to form submit events, handle with Ajax
$( "form" ).live('submit', function( event ) {
var $this = $( this );
if( !$.mobile.ajaxEnabled ||
$this.is( ":jqmData(ajax='false')" ) ) {
return;
}
var type = $this.attr( "method" ),
target = $this.attr( "target" ),
url = $this.attr( "action" );
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if ( !url ) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl( $this );
if ( url === documentBase.hrefNoHash ) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) );
//external submits use regular HTTP
if( path.isExternal( url ) || target ) {
return;
}
$.mobile.changePage(
url,
{
type: type && type.length && type.toLowerCase() || "get",
data: $this.serialize(),
transition: $this.jqmData( "transition" ),
direction: $this.jqmData( "direction" ),
reloadPage: true
}
);
event.preventDefault();
});
//add active state on vclick
$( document ).bind( "vclick", function( event ) {
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create
if ( event.which > 1 || !$.mobile.linkBindingEnabled ){
return;
}
var link = findClosestLink( event.target );
if ( link ) {
if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) {
removeActiveLinkClass( true );
$activeClickedLink = $( link ).closest( ".ui-btn" ).not( ".ui-disabled" );
$activeClickedLink.addClass( $.mobile.activeBtnClass );
$( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur();
}
}
});
// click routing - direct to HTTP or Ajax, accordingly
$( document ).bind( "click", function( event ) {
if( !$.mobile.linkBindingEnabled ){
return;
}
var link = findClosestLink( event.target );
// If there is no link associated with the click or its not a left
// click we want to ignore the click
if ( !link || event.which > 1) {
return;
}
var $link = $( link ),
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function(){
window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 );
};
//if there's a data-rel=back attr, go back in history
if( $link.is( ":jqmData(rel='back')" ) ) {
window.history.back();
return false;
}
var baseUrl = getClosestBaseUrl( $link ),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
//if ajax is disabled, exit early
if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if ( href.search( "#" ) != -1 ) {
href = href.replace( /[^#]*#/, "" );
if ( !href ) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if ( path.isPath( href ) ) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute( href, baseUrl );
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad );
if( isExternal ) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData( "transition" ),
direction = $link.jqmData( "direction" ),
reverse = ( direction && direction === "reverse" ) ||
// deprecated - remove by 1.0
$link.jqmData( "back" ),
//this may need to be more specific as we use data-rel more
role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
$.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } );
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$( ".ui-page" ).live( "pageshow.prefetch", function() {
var urls = [];
$( this ).find( "a:jqmData(prefetch)" ).each(function(){
var $link = $(this),
url = $link.attr( "href" );
if ( url && $.inArray( url, urls ) === -1 ) {
urls.push( url );
$.mobile.loadPage( url, {role: $link.attr("data-" + $.mobile.ns + "rel")} );
}
});
});
$.mobile._handleHashChange = function( hash ) {
//find first page via hash
var to = path.stripHash( hash ),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash
changePageOptions = {
transition: transition,
changeHash: false,
fromHashChange: true
};
//if listening is disabled (either globally or temporarily), or it's a dialog hash
if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) {
urlHistory.ignoreNextHashChange = false;
return;
}
// special case for dialogs
if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if(!$.mobile.activePage.is( ".ui-dialog" )) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
urlHistory.directHashChange({
currentUrl: to,
isBack: function() { window.history.back(); },
isForward: function() { window.history.forward(); }
});
// prevent changePage()
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
urlHistory.directHashChange({
currentUrl: to,
// regardless of the direction of the history change
// do the following
either: function( isBack ) {
var active = $.mobile.urlHistory.getActive();
to = active.pageUrl;
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend( changePageOptions, {
role: active.role,
transition: active.transition,
reverse: isBack
});
}
});
}
}
//if to is defined, load it
if ( to ) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = ( typeof to === "string" && !path.isPath( to ) ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
$.mobile.changePage( to, changePageOptions );
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage( $.mobile.firstPage, changePageOptions );
}
};
//hashchange event handler
$window.bind( "hashchange", function( e, triggered ) {
$.mobile._handleHashChange( location.hash );
});
//set page min-heights to be device specific
$( document ).bind( "pageshow", resetActivePageHeight );
$( window ).bind( "throttledresize", resetActivePageHeight );
};//_registerInternalEvents callback
})( jQuery );
/*
* history.pushState support, layered on top of hashchange
*/
( function( $, window ) {
// For now, let's Monkeypatch this onto the end of $.mobile._registerInternalEvents
// Scope self to pushStateHandler so we can reference it sanely within the
// methods handed off as event handlers
var pushStateHandler = {},
self = pushStateHandler,
$win = $( window ),
url = $.mobile.path.parseUrl( location.href );
$.extend( pushStateHandler, {
// TODO move to a path helper, this is rather common functionality
initialFilePath: (function() {
return url.pathname + url.search;
})(),
initialHref: url.hrefNoHash,
// Flag for tracking if a Hashchange naturally occurs after each popstate + replace
hashchangeFired: false,
state: function() {
return {
hash: location.hash || "#" + self.initialFilePath,
title: document.title,
// persist across refresh
initialHref: self.initialHref
};
},
resetUIKeys: function( url ) {
var dialog = $.mobile.dialogHashKey,
subkey = "&" + $.mobile.subPageUrlKey,
dialogIndex = url.indexOf( dialog );
if( dialogIndex > -1 ) {
url = url.slice( 0, dialogIndex ) + "#" + url.slice( dialogIndex );
} else if( url.indexOf( subkey ) > -1 ) {
url = url.split( subkey ).join( "#" + subkey );
}
return url;
},
// TODO sort out a single barrier to hashchange functionality
nextHashChangePrevented: function( value ) {
$.mobile.urlHistory.ignoreNextHashChange = value;
self.onHashChangeDisabled = value;
},
// on hash change we want to clean up the url
// NOTE this takes place *after* the vanilla navigation hash change
// handling has taken place and set the state of the DOM
onHashChange: function( e ) {
// disable this hash change
if( self.onHashChangeDisabled ){
return;
}
var href, state,
hash = location.hash,
isPath = $.mobile.path.isPath( hash ),
resolutionUrl = isPath ? location.href : $.mobile.getDocumentUrl();
hash = isPath ? hash.replace( "#", "" ) : hash;
// propulate the hash when its not available
state = self.state();
// make the hash abolute with the current href
href = $.mobile.path.makeUrlAbsolute( hash, resolutionUrl );
if ( isPath ) {
href = self.resetUIKeys( href );
}
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where window.history.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
history.replaceState( state, document.title, href );
},
// on popstate (ie back or forward) we need to replace the hash that was there previously
// cleaned up by the additional hash handling
onPopState: function( e ) {
var poppedState = e.originalEvent.state, holdnexthashchange = false;
// if there's no state its not a popstate we care about, ie chrome's initial popstate
// or forward popstate
if( poppedState ) {
// disable any hashchange triggered by the browser
self.nextHashChangePrevented( true );
// defer our manual hashchange until after the browser fired
// version has come and gone
setTimeout(function() {
// make sure that the manual hash handling takes place
self.nextHashChangePrevented( false );
// change the page based on the hash
$.mobile._handleHashChange( poppedState.hash );
}, 100);
}
},
init: function() {
$win.bind( "hashchange", self.onHashChange );
// Handle popstate events the occur through history changes
$win.bind( "popstate", self.onPopState );
// if there's no hash, we need to replacestate for returning to home
if ( location.hash === "" ) {
history.replaceState( self.state(), document.title, location.href );
}
}
});
$( function() {
if( $.mobile.pushStateEnabled && $.support.pushState ){
pushStateHandler.init();
}
});
})( jQuery, this );
/*
* "transitions" plugin - Page change tranistions
*/
(function( $, window, undefined ) {
function css3TransitionHandler( name, reverse, $to, $from ) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
viewportClass = "ui-mobile-viewport-transitioning viewport-" + name,
doneFunc = function() {
$to.add( $from ).removeClass( "out in reverse " + name );
if ( $from && $from[ 0 ] !== $to[ 0 ] ) {
$from.removeClass( $.mobile.activePageClass );
}
$to.parent().removeClass( viewportClass );
deferred.resolve( name, reverse, $to, $from );
};
$to.animationComplete( doneFunc );
$to.parent().addClass( viewportClass );
if ( $from ) {
$from.addClass( name + " out" + reverseClass );
}
$to.addClass( $.mobile.activePageClass + " " + name + " in" + reverseClass );
return deferred.promise();
}
// Make our transition handler public.
$.mobile.css3TransitionHandler = css3TransitionHandler;
// If the default transition handler is the 'none' handler, replace it with our handler.
if ( $.mobile.defaultTransitionHandler === $.mobile.noneTransitionHandler ) {
$.mobile.defaultTransitionHandler = css3TransitionHandler;
}
})( jQuery, this );
/*
* "degradeInputs" plugin - degrades inputs to another type after custom enhancements are made.
*/
(function( $, undefined ) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
var page = $(e.target).closest(':jqmData(role="page")').data("page"), options;
if( !page ) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
var $this = $( this ),
type = this.getAttribute( "type" ),
optType = options.degradeInputs[ type ] || "text";
if ( options.degradeInputs[ type ] ) {
var html = $( "<div>" ).html( $this.clone() ).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf( " type=" ) > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith( html.replace( findstr, repstr ) );
}
});
});
})( jQuery );/*
* "dialog" plugin.
*/
(function( $, window, undefined ) {
$.widget( "mobile.dialog", $.mobile.widget, {
options: {
closeBtnText : "Close",
overlayTheme : "a",
initSelector : ":jqmData(role='dialog')"
},
_create: function() {
var self = this,
$el = this.element,
headerCloseButton = $( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" );
$el.addClass( "ui-overlay-" + this.options.overlayTheme );
// Class the markup for dialog styling
// Set aria role
$el.attr( "role", "dialog" )
.addClass( "ui-dialog" )
.find( ":jqmData(role='header')" )
.addClass( "ui-corner-top ui-overlay-shadow" )
.prepend( headerCloseButton )
.end()
.find( ":jqmData(role='content'),:jqmData(role='footer')" )
.addClass( "ui-overlay-shadow" )
.last()
.addClass( "ui-corner-bottom" );
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
headerCloseButton.bind( "vclick", function() {
self.close();
});
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind( "vclick submit", function( event ) {
var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
active;
if ( $target.length && !$target.jqmData( "transition" ) ) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
.attr( "data-" + $.mobile.ns + "direction", "reverse" );
}
})
.bind( "pagehide", function() {
$( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass );
});
},
// Close method goes back in history
close: function() {
window.history.back();
}
});
//auto self-init widgets
$( $.mobile.dialog.prototype.options.initSelector ).live( "pagecreate", function(){
$( this ).dialog();
});
})( jQuery, this );
/*
* This plugin handles theming and layout of headers, footers, and content areas
*/
(function( $, undefined ) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
$( ":jqmData(role='page'), :jqmData(role='dialog')" ).live( "pagecreate", function( e ) {
var $page = $( this ),
o = $page.data( "page" ).options,
pageRole = $page.jqmData( "role" ),
pageTheme = o.theme;
$( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this ).each(function() {
var $this = $( this ),
role = $this.jqmData( "role" ),
theme = $this.jqmData( "theme" ),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass( "ui-" + role );
//apply theming and markup modifications to page,header,content,footer
if ( role === "header" || role === "footer" ) {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass( "ui-bar-" + thisTheme )
// Add ARIA role
.attr( "role", role === "header" ? "banner" : "contentinfo" );
// Right,left buttons
$headeranchors = $this.children( "a" );
leftbtn = $headeranchors.hasClass( "ui-btn-left" );
rightbtn = $headeranchors.hasClass( "ui-btn-right" );
leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
// Auto-add back btn on pages beyond first view
if ( o.addBackBtn &&
role === "header" &&
$( ".ui-page" ).length > 1 &&
$this.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
!leftbtn ) {
backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
// If theme is provided, override default inheritance
.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
.prependTo( $this );
}
// Page title
$this.children( "h1, h2, h3, h4, h5, h6" )
.addClass( "ui-title" )
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"tabindex": "0",
"role": "heading",
"aria-level": "1"
});
} else if ( role === "content" ) {
if ( contentTheme ) {
$this.addClass( "ui-body-" + ( contentTheme ) );
}
// Add ARIA role
$this.attr( "role", "main" );
}
});
});
})( jQuery );/*
* "collapsible" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
theme: null,
contentTheme: null,
iconTheme: "d",
initSelector: ":jqmData(role='collapsible')"
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" );
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData( "theme" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
}
collapsibleContent.addClass( ( o.contentTheme ) ? ( "ui-body-" + o.contentTheme ) : "");
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconPos: "left",
icon: "plus",
theme: o.theme
})
.add( ".ui-btn-inner" )
.addClass( "ui-corner-top ui-corner-bottom" );
//events
collapsible
.bind( "expand collapse", function( event ) {
if ( !event.isDefaultPrevented() ) {
event.preventDefault();
var $this = $( this ),
isCollapse = ( event.type === "collapse" ),
contentTheme = o.contentTheme;
collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse)
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-minus", !isCollapse )
.toggleClass( "ui-icon-plus", isCollapse );
$this.toggleClass( "ui-collapsible-collapsed", isCollapse );
collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
if ( contentTheme && ( !collapsibleSet.length || collapsible.jqmData( "collapsible-last" ) ) ) {
collapsibleHeading
.find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) )
.toggleClass( "ui-corner-bottom", isCollapse );
collapsibleContent.toggleClass( "ui-corner-bottom", !isCollapse );
}
collapsibleContent.trigger( "updatelayout" );
}
})
.trigger( o.collapsed ? "collapse" : "expand" );
collapsibleHeading
.bind( "click", function( event ) {
var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ?
"expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
});
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( $.mobile.collapsible.prototype.options.initSelector, e.target ).collapsible();
});
})( jQuery );
/*
* "fieldcontain" plugin - simple class additions to make form row separators
*/
(function( $, undefined ) {
$.fn.fieldcontain = function( options ) {
return this.addClass( "ui-field-contain ui-body ui-br" );
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='fieldcontain')", e.target ).fieldcontain();
});
})( jQuery );/*
* plugin for creating CSS grids
*/
(function( $, undefined ) {
$.fn.grid = function( options ) {
return this.each(function() {
var $this = $( this ),
o = $.extend({
grid: null
},options),
$kids = $this.children(),
gridCols = {solo:1, a:2, b:3, c:4, d:5},
grid = o.grid,
iterator;
if ( !grid ) {
if ( $kids.length <= 5 ) {
for ( var letter in gridCols ) {
if ( gridCols[ letter ] === $kids.length ) {
grid = letter;
}
}
} else {
grid = "a";
}
}
iterator = gridCols[grid];
$this.addClass( "ui-grid-" + grid );
$kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
if ( iterator > 1 ) {
$kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
}
if ( iterator > 2 ) {
$kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" );
}
if ( iterator > 3 ) {
$kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" );
}
if ( iterator > 4 ) {
$kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" );
}
});
};
})( jQuery );/*
* "navbar" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function(){
var $navbar = this.element,
$navbtns = $navbar.find( "a" ),
iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
this.options.iconpos : undefined;
$navbar.addClass( "ui-navbar" )
.attr( "role","navigation" )
.find( "ul" )
.grid({ grid: this.options.grid });
if ( !iconpos ) {
$navbar.addClass( "ui-navbar-noicons" );
}
$navbtns.buttonMarkup({
corners: false,
shadow: false,
iconpos: iconpos
});
$navbar.delegate( "a", "vclick", function( event ) {
$navbtns.not( ".ui-state-persist" ).removeClass( $.mobile.activeBtnClass );
$( this ).addClass( $.mobile.activeBtnClass );
});
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( $.mobile.navbar.prototype.options.initSelector, e.target ).navbar();
});
})( jQuery );
/*
* "listview" plugin
*/
(function( $, undefined ) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget( "mobile.listview", $.mobile.widget, {
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
splitIcon: "arrow-r",
splitTheme: "b",
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this;
// create listview markup
t.element.addClass(function( i, orig ) {
return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" );
});
t.refresh( true );
},
_removeCorners: function( li, which ) {
var top = "ui-corner-top ui-corner-tr ui-corner-tl",
bot = "ui-corner-bottom ui-corner-br ui-corner-bl";
li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) );
if ( which === "top" ) {
li.removeClass( top );
} else if ( which === "bottom" ) {
li.removeClass( bot );
} else {
li.removeClass( top + " " + bot );
}
},
_refreshCorners: function( create ) {
var $li,
$visibleli,
$topli,
$bottomli;
if ( this.options.inset ) {
$li = this.element.children( "li" );
// at create time the li are not visible yet so we need to rely on .ui-screen-hidden
$visibleli = create?$li.not( ".ui-screen-hidden" ):$li.filter( ":visible" );
this._removeCorners( $li );
// Select the first visible li element
$topli = $visibleli.first()
.addClass( "ui-corner-top" );
$topli.add( $topli.find( ".ui-btn-inner" )
.not( ".ui-li-link-alt span:first-child" ) )
.addClass( "ui-corner-top" )
.end()
.find( ".ui-li-link-alt, .ui-li-link-alt span:first-child" )
.addClass( "ui-corner-tr" )
.end()
.find( ".ui-li-thumb" )
.not(".ui-li-icon")
.addClass( "ui-corner-tl" );
// Select the last visible li element
$bottomli = $visibleli.last()
.addClass( "ui-corner-bottom" );
$bottomli.add( $bottomli.find( ".ui-btn-inner" ) )
.find( ".ui-li-link-alt" )
.addClass( "ui-corner-br" )
.end()
.find( ".ui-li-thumb" )
.not(".ui-li-icon")
.addClass( "ui-corner-bl" );
}
if ( !create ) {
this.element.trigger( "updatelayout" );
}
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function( ele, nextProp, lcName, ucName )
{
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function( ele, lcName, ucName )
{
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
results.push( ele );
}
ele = ele.nextSibling;
}
return $( results );
},
_addThumbClasses: function( containers )
{
var i, img, len = containers.length;
for ( i = 0; i < len; i++ ) {
img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
if ( img.length ) {
img.addClass( "ui-li-thumb" );
$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
}
}
},
refresh: function( create ) {
this.parentPage = this.element.closest( ".ui-page" );
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
listsplittheme = $list.jqmData( "splittheme" ),
listspliticon = $list.jqmData( "spliticon" ),
li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1,
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, countParent, icon, imgParents, img;
if ( counter ) {
$list.find( ".ui-li-dec" ).remove();
}
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
item = li.eq( pos );
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if ( create || !item.hasClass( "ui-li" ) ) {
itemTheme = item.jqmData("theme") || o.theme;
a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
if ( a.length ) {
icon = item.jqmData("icon");
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || "arrow-r",
theme: itemTheme
});
if ( ( icon != false ) && ( a.length == 1 ) ) {
item.addClass( "ui-li-has-arrow" );
}
a.first().addClass( "ui-link-inherit" );
if ( a.length > 1 ) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
last.appendTo(item)
.attr( "title", last.getEncodedText() )
.addClass( "ui-li-link-alt" )
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: false
})
.find( ".ui-btn-inner" )
.append(
$( document.createElement( "span" ) ).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
icon: listspliticon || last.jqmData( "icon" ) || o.splitIcon
})
);
}
} else if ( item.jqmData( "role" ) === "list-divider" ) {
itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme;
item.attr( "role", "heading" );
//reset counter when a divider heading is encountered
if ( counter ) {
counter = 1;
}
} else {
itemClass += " ui-li-static ui-body-" + itemTheme;
}
}
if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" );
countParent.addClass( "ui-li-jsnumbering" )
.prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" );
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if ( !itemClassDict[ itemClass ] ) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push( item[ 0 ] );
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for ( itemClass in itemClassDict ) {
$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
}
$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
.end()
.find( "p, dl" ).addClass( "ui-li-desc" )
.end()
.find( ".ui-li-aside" ).each(function() {
var $this = $(this);
$this.prependTo( $this.parent() ); //shift aside to front for css float
})
.end()
.find( ".ui-li-count" ).each( function() {
$( this ).closest( "li" ).addClass( "ui-li-has-count" );
}).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses( li );
this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
this._refreshCorners( create );
},
//create a string for ID/subpage url creation
_idStringEscape: function( str ) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest( ".ui-page" ),
parentUrl = parentPage.jqmData( "url" ),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr( "id" ),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
hasSubPages;
if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
var self = this,
list = $( this ),
listId = list.attr( "id" ) || parentListId + "-" + i,
parent = list.parent(),
nodeEls = $( list.prevAll().toArray().reverse() ),
nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData( "theme" ) || o.theme,
countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
.parent()
.before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
.after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" )
.parent()
.appendTo( $.mobile.pageContainer );
newPage.page();
anchor = parent.find('a:first');
if ( !anchor.length ) {
anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
}
anchor.attr( "href", "#" + id );
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if( hasSubPages &&
parentPage.is( ":jqmData(external-page='true')" ) &&
parentPage.data("page").options.domCache === false ) {
var newRemove = function( e, ui ){
var nextPage = ui.nextPage, npURL;
if( ui.nextPage ){
npURL = nextPage.jqmData( "url" );
if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){
self.childPages().remove();
parentPage.remove();
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind( "pagehide.remove" )
.bind( "pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function(){
var parentUrl = this.parentPage.jqmData( "url" );
return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')");
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( $.mobile.listview.prototype.options.initSelector, e.target ).listview();
});
})( jQuery );
/*
* "listview" filter extension
*/
(function( $, undefined ) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterCallback = function( text, searchValue ){
return text.toLowerCase().indexOf( searchValue ) === -1;
};
$( ":jqmData(role='listview')" ).live( "listviewcreate", function() {
var list = $( this ),
listview = list.data( "listview" );
if ( !listview.options.filter ) {
return;
}
var wrapper = $( "<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}),
search = $( "<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr( "data-" + $.mobile.ns + "type", "search" )
.jqmData( "lastval", "" )
.bind( "keyup change", function() {
var $this = $(this),
val = this.value.toLowerCase(),
listItems = null,
lastval = $this.jqmData( "lastval" ) + "",
childItems = false,
itemtext = "",
item, change;
// Change val as lastval for next execution
$this.jqmData( "lastval" , val );
change = val.substr( 0 , lastval.length - 1 ).replace( lastval , "" );
if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) {
// Removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children( ":not(.ui-screen-hidden)" );
}
if ( val ) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for ( var i = listItems.length - 1; i >= 0; i-- ) {
item = $( listItems[ i ] );
itemtext = item.jqmData( "filtertext" ) || item.text();
if ( item.is( "li:jqmData(role=list-divider)" ) ) {
item.toggleClass( "ui-filter-hidequeue" , !childItems );
// New bucket!
childItems = false;
} else if ( listview.options.filterCallback( itemtext, val ) ) {
//mark to be hidden
item.toggleClass( "ui-filter-hidequeue" , true );
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter( ":not(.ui-filter-hidequeue)" )
.toggleClass( "ui-screen-hidden", false );
// Hide items, marked to be hidden
listItems
.filter( ".ui-filter-hidequeue" )
.toggleClass( "ui-screen-hidden", true )
.toggleClass( "ui-filter-hidequeue", false );
} else {
//filtervalue is empty => show all
listItems.toggleClass( "ui-screen-hidden", false );
}
listview._refreshCorners();
})
.appendTo( wrapper )
.textinput();
if ( $( this ).jqmData( "inset" ) ) {
wrapper.addClass( "ui-listview-filter-inset" );
}
wrapper.bind( "submit", function() {
return false;
})
.insertBefore( list );
});
})( jQuery );/*
* "nojs" plugin - class to make elements hidden to A grade browsers
*/
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
});
})( jQuery );/*
* "checkboxradio" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.checkboxradio", $.mobile.widget, {
options: {
theme: null,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function() {
var self = this,
input = this.element,
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
label = input.closest( "form,fieldset,:jqmData(role='page')" ).find( "label[for='" + input[ 0 ].id + "']"),
inputtype = input.attr( "type" ),
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState,
activeBtn = icon ? "" : " " + $.mobile.activeBtnClass,
checkedClass = "ui-" + checkedState + activeBtn,
uncheckedClass = "ui-" + uncheckedState,
checkedicon = "ui-icon-" + checkedState,
uncheckedicon = "ui-icon-" + uncheckedState;
if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
return;
}
// Expose for other methods
$.extend( this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedicon,
uncheckedicon: uncheckedicon
});
// If there's no selected theme...
if( !this.options.theme ) {
this.options.theme = this.element.jqmData( "theme" );
}
label.buttonMarkup({
theme: this.options.theme,
icon: icon,
shadow: false
});
// Wrap the input + label in a div
input.add( label )
.wrapAll( "<div class='ui-" + inputtype + "'></div>" );
label.bind({
vmouseover: function( event ) {
if ( $( this ).parent().is( ".ui-disabled" ) ) {
event.stopPropagation();
}
},
vclick: function( event ) {
if ( input.is( ":disabled" ) ) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler( 'click' );
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not( input ).prop( "checked", false );
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function() {
self._cacheVals();
},
vclick: function() {
var $this = $(this);
// Adds checked attribute to checked input when keyboard is used
if ( $this.is( ":checked" ) ) {
$this.prop( "checked", true);
self._getInputSet().not($this).prop( "checked", false );
} else {
$this.prop( "checked", false );
}
self._updateAll();
},
focus: function() {
label.addClass( "ui-focus" );
},
blur: function() {
label.removeClass( "ui-focus" );
}
});
this.refresh();
},
_cacheVals: function() {
this._getInputSet().each(function() {
var $this = $(this);
$this.jqmData( "cacheVal", $this.is( ":checked" ) );
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function(){
if(this.inputtype == "checkbox") {
return this.element;
}
return this.element.closest( "form,fieldset,:jqmData(role='page')" )
.find( "input[name='"+ this.element.attr( "name" ) +"'][type='"+ this.inputtype +"']" );
},
_updateAll: function() {
var self = this;
this._getInputSet().each(function() {
var $this = $(this);
if ( $this.is( ":checked" ) || self.inputtype === "checkbox" ) {
$this.trigger( "change" );
}
})
.checkboxradio( "refresh" );
},
refresh: function() {
var input = this.element,
label = this.label,
icon = label.find( ".ui-icon" );
// input[0].checked expando doesn't always report the proper value
// for checked='checked'
if ( $( input[ 0 ] ).prop( "checked" ) ) {
label.addClass( this.checkedClass ).removeClass( this.uncheckedClass );
icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon );
} else {
label.removeClass( this.checkedClass ).addClass( this.uncheckedClass );
icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon );
}
if ( input.is( ":disabled" ) ) {
this.disable();
} else {
this.enable();
}
},
disable: function() {
this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
},
enable: function() {
this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.checkboxradio.prototype.enhanceWithin( e.target );
});
})( jQuery );
/*
* "button" plugin - links that proxy to native input/buttons
*/
(function( $, undefined ) {
$.widget( "mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
inline: null,
corners: true,
shadow: true,
iconshadow: true,
initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']"
},
_create: function() {
var $el = this.element,
o = this.options,
type,
name,
$buttonPlaceholder;
// Add ARIA role
this.button = $( "<div></div>" )
.text( $el.text() || $el.val() )
.insertBefore( $el )
.buttonMarkup({
theme: o.theme,
icon: o.icon,
iconpos: o.iconpos,
inline: o.inline,
corners: o.corners,
shadow: o.shadow,
iconshadow: o.iconshadow
})
.append( $el.addClass( "ui-btn-hidden" ) );
type = $el.attr( "type" );
name = $el.attr( "name" );
// Add hidden input during submit if input type="submit" has a name.
if ( type !== "button" && type !== "reset" && name ) {
$el.bind( "vclick", function() {
// Add hidden input if it doesn’t already exist.
if( $buttonPlaceholder === undefined ) {
$buttonPlaceholder = $( "<input>", {
type: "hidden",
name: $el.attr( "name" ),
value: $el.attr( "value" )
}).insertBefore( $el );
// Bind to doc to remove after submit handling
$( document ).one("submit", function(){
$buttonPlaceholder.remove();
// reset the local var so that the hidden input
// will be re-added on subsequent clicks
$buttonPlaceholder = undefined;
});
}
});
}
this.refresh();
},
enable: function() {
this.element.attr( "disabled", false );
this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
},
refresh: function() {
var $el = this.element;
if ( $el.prop("disabled") ) {
this.disable();
} else {
this.enable();
}
// the textWrapper is stored as a data element on the button object
// to prevent referencing by it's implementation details (eg 'class')
this.button.data( 'textWrapper' ).text( $el.text() || $el.val() );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.button.prototype.enhanceWithin( e.target );
});
})( jQuery );/*
* "slider" plugin
*/
( function( $, undefined ) {
$.widget( "mobile.slider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')"
},
_create: function() {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme( control, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
selectClass = ( cType == "select" ) ? "ui-slider-switch" : "",
controlID = control.attr( "id" ),
labelID = controlID + "-label",
label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ),
val = function() {
return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex;
},
min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0,
max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
step = window.parseFloat( control.attr( "step" ) || 1 ),
slider = $( "<div class='ui-slider " + selectClass + " ui-btn-down-" + trackTheme +
" ui-btn-corner-all' role='application'></div>" ),
handle = $( "<a href='#' class='ui-slider-handle'></a>" )
.appendTo( slider )
.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": val(),
"aria-valuetext": val(),
"title": val(),
"aria-labelledby": labelID
}),
options;
$.extend( this, {
slider: slider,
handle: handle,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if ( cType == "select" ) {
slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
options = control.find( "option" );
control.find( "option" ).each(function( i ) {
var side = !i ? "b":"a",
corners = !i ? "right" :"left",
theme = !i ? " ui-btn-down-" + trackTheme :( " " + $.mobile.activeBtnClass );
$( "<div class='ui-slider-labelbg ui-slider-labelbg-" + side + theme + " ui-btn-corner-" + corners + "'></div>" )
.prependTo( slider );
$( "<span class='ui-slider-label ui-slider-label-" + side + theme + " ui-btn-corner-" + corners + "' role='img'>" + $( this ).getEncodedText() + "</span>" )
.prependTo( handle );
});
}
label.addClass( "ui-slider" );
// monitor the input for updated values
control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" )
.change( function() {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if (!self.mouseMoved) {
self.refresh( val(), true );
}
})
.keyup( function() { // necessary?
self.refresh( val(), true, true );
})
.blur( function() {
self.refresh( val(), true );
});
// prevent screen drag when slider activated
$( document ).bind( "vmousemove", function( event ) {
if ( self.dragging ) {
// self.mouseMoved must be updated before refresh() because it will be used in the control "change" event
self.mouseMoved = true;
if ( cType === "select" ) {
// make the handle move in sync with the mouse
handle.removeClass( "ui-slider-handle-snapping" );
}
self.refresh( event );
// only after refresh() you can calculate self.userModified
self.userModified = self.beforeStart !== control[0].selectedIndex;
return false;
}
});
slider.bind( "vmousedown", function( event ) {
self.dragging = true;
self.userModified = false;
self.mouseMoved = false;
if ( cType === "select" ) {
self.beforeStart = control[0].selectedIndex;
}
self.refresh( event );
return false;
});
slider.add( document )
.bind( "vmouseup", function() {
if ( self.dragging ) {
self.dragging = false;
if ( cType === "select") {
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
if ( self.mouseMoved ) {
// this is a drag, change the value only if user dragged enough
if ( self.userModified ) {
self.refresh( self.beforeStart == 0 ? 1 : 0 );
}
else {
self.refresh( self.beforeStart );
}
}
else {
// this is just a click, change the value
self.refresh( self.beforeStart == 0 ? 1 : 0 );
}
}
self.mouseMoved = false;
return false;
}
});
slider.insertAfter( control );
// NOTE force focus on handle
this.handle
.bind( "vmousedown", function() {
$( this ).focus();
})
.bind( "vclick", false );
this.handle
.bind( "keydown", function( event ) {
var index = val();
if ( self.options.disabled ) {
return;
}
// In all cases prevent the default and mark the handle as active
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if ( !self._keySliding ) {
self._keySliding = true;
$( this ).addClass( "ui-state-active" );
}
break;
}
// move the slider according to the keypress
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
self.refresh( min );
break;
case $.mobile.keyCode.END:
self.refresh( max );
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
self.refresh( index + step );
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
self.refresh( index - step );
break;
}
}) // remove active mark
.keyup( function( event ) {
if ( self._keySliding ) {
self._keySliding = false;
$( this ).removeClass( "ui-state-active" );
}
});
this.refresh(undefined, undefined, true);
},
refresh: function( val, isfromControl, preventInputUpdate ) {
if ( this.options.disabled || this.element.attr('disabled')) {
this.disable();
}
var control = this.element, percent,
cType = control[0].nodeName.toLowerCase(),
min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0,
max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1;
if ( typeof val === "object" ) {
var data = val,
// a slight tolerance helped get to the ends of the slider
tol = 8;
if ( !this.dragging ||
data.pageX < this.slider.offset().left - tol ||
data.pageX > this.slider.offset().left + this.slider.width() + tol ) {
return;
}
percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 );
} else {
if ( val == null ) {
val = cType === "input" ? parseFloat( control.val() ) : control[0].selectedIndex;
}
percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
}
if ( isNaN( percent ) ) {
return;
}
if ( percent < 0 ) {
percent = 0;
}
if ( percent > 100 ) {
percent = 100;
}
var newval = Math.round( ( percent / 100 ) * ( max - min ) ) + min;
if ( newval < min ) {
newval = min;
}
if ( newval > max ) {
newval = max;
}
// Flip the stack of the bg colors
if ( percent > 60 && cType === "select" ) {
// TODO: Dead path?
}
this.handle.css( "left", percent + "%" );
this.handle.attr( {
"aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ),
"aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText(),
title: newval
});
// add/remove classes for flip toggle switch
if ( cType === "select" ) {
if ( newval === 0 ) {
this.slider.addClass( "ui-slider-switch-a" )
.removeClass( "ui-slider-switch-b" );
} else {
this.slider.addClass( "ui-slider-switch-b" )
.removeClass( "ui-slider-switch-a" );
}
}
if ( !preventInputUpdate ) {
var valueChanged = false;
// update control"s value
if ( cType === "input" ) {
valueChanged = control.val() !== newval;
control.val( newval );
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if ( !isfromControl && valueChanged ) {
control.trigger( "change" );
}
}
},
enable: function() {
this.element.attr( "disabled", false );
this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.slider.prototype.enhanceWithin( e.target );
});
})( jQuery );
/*
* "textinput" plugin for text inputs, textareas
*/
(function( $, undefined ) {
$.widget( "mobile.textinput", $.mobile.widget, {
options: {
theme: null,
initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type])"
},
_create: function() {
var input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
themeclass = " ui-body-" + theme,
focusedEl, clearbtn;
$( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
focusedEl = input.addClass("ui-input-text ui-body-"+ theme );
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute( "autocorrect", "off" );
input[0].setAttribute( "autocomplete", "off" );
}
//"search" input widget
if ( input.is( "[type='search'],:jqmData(type='search')" ) ) {
focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent();
clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" )
.tap(function( event ) {
input.val( "" ).focus();
input.trigger( "change" );
clearbtn.addClass( "ui-input-clear-hidden" );
event.preventDefault();
})
.appendTo( focusedEl )
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true
});
function toggleClear() {
setTimeout(function() {
clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
}, 0);
}
toggleClear();
input.bind('paste cut keyup focus change blur', toggleClear);
} else {
input.addClass( "ui-corner-all ui-shadow-inset" + themeclass );
}
input.focus(function() {
focusedEl.addClass( "ui-focus" );
})
.blur(function(){
focusedEl.removeClass( "ui-focus" );
});
// Autogrow
if ( input.is( "textarea" ) ) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyup = function() {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if ( clientHeight < scrollHeight ) {
input.height(scrollHeight + extraLineHeight);
}
},
keyupTimeout;
input.keyup(function() {
clearTimeout( keyupTimeout );
keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer );
});
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ( $.trim( input.val() ) ) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
$( window ).load( keyup );
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
$( document ).one( "pagechange", keyup );
}
}
},
disable: function(){
( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ?
this.element.parent() : this.element ).addClass( "ui-disabled" );
},
enable: function(){
( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ?
this.element.parent() : this.element ).removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.textinput.prototype.enhanceWithin( e.target );
});
})( jQuery );
/*
* custom "selectmenu" plugin
*/
(function( $, undefined ) {
var extendSelect = function( widget ){
var select = widget.select,
selectID = widget.selectID,
label = widget.label,
thisPage = widget.select.closest( ".ui-page" ),
screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"} ).appendTo( thisPage ),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>"+
"</div>"+
"<div data-" + $.mobile.ns + "role='content'></div>"+
"</div>" ).appendTo( $.mobile.pageContainer ).page(),
listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + widget.options.overlayTheme + " " + $.mobile.defaultDialogTransition } ).insertAfter(screen),
list = $( "<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ).appendTo( listbox ),
header = $( "<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo( listbox ),
headerTitle = $( "<h1>", {
"class": "ui-title"
}).appendTo( header ),
headerClose = $( "<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup(),
menuPageContent = menuPage.find( ".ui-content" ),
menuPageClose = menuPage.find( ".ui-header a" );
$.extend( widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
thisPage: thisPage,
menuPage: menuPage,
label: label,
screen: screen,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function() {
var self = this;
// Create list from select, update state
self.refresh();
self.select.attr( "tabindex", "-1" ).focus(function() {
$( this ).blur();
self.button.focus();
});
// Button events
self.button.bind( "vclick keydown" , function( event ) {
if ( event.type == "vclick" ||
event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE ) ) {
self.open();
event.preventDefault();
}
});
// Events for list items
self.list.attr( "role", "listbox" )
.delegate( ".ui-li>a", "focusin", function() {
$( this ).attr( "tabindex", "0" );
})
.delegate( ".ui-li>a", "focusout", function() {
$( this ).attr( "tabindex", "-1" );
})
.delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
option = self._selectOptions().eq( newIndex )[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if ( self.isMultiple ) {
$( this ).find( ".ui-icon" )
.toggleClass( "ui-icon-checkbox-on", option.selected )
.toggleClass( "ui-icon-checkbox-off", !option.selected );
}
// trigger change if value changed
if ( self.isMultiple || oldIndex !== newIndex ) {
self.select.trigger( "change" );
}
//hide custom select for single selects only
if ( !self.isMultiple ) {
self.close();
}
event.preventDefault();
})
.keydown(function( event ) { //keyboard events for menu items
var target = $( event.target ),
li = target.closest( "li" ),
prev, next;
// switch logic based on which key was pressed
switch ( event.keyCode ) {
// up or left arrow keys
case 38:
prev = li.prev();
// if there's a previous option, focus it
if ( prev.length ) {
target
.blur()
.attr( "tabindex", "-1" );
prev.find( "a" ).first().focus();
}
return false;
break;
// down or right arrow keys
case 40:
next = li.next();
// if there's a next option, focus it
if ( next.length ) {
target
.blur()
.attr( "tabindex", "-1" );
next.find( "a" ).first().focus();
}
return false;
break;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger( "click" );
return false;
break;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind( "pagehide", function() {
self.list.appendTo( self.listbox );
self._focusButton();
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call( self.thisPage );
});
// Events on "screen" overlay
self.screen.bind( "vclick", function( event ) {
self.close();
});
// Close button on small overlays
self.headerClose.click( function() {
if ( self.menuType == "overlay" ) {
self.close();
return false;
}
});
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents( this.menuPage );
},
_isRebuildRequired: function() {
var list = this.list.find( "li" ),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
refresh: function( forceRebuild , foo ){
var self = this,
select = this.element,
isMultiple = this.isMultiple,
options = this._selectOptions(),
selected = this.selected(),
// return an array of all selected index's
indicies = this.selectedIndices();
if ( forceRebuild || this._isRebuildRequired() ) {
self._buildList();
}
self.setButtonText();
self.setButtonCount();
self.list.find( "li:not(.ui-li-divider)" )
.removeClass( $.mobile.activeBtnClass )
.attr( "aria-selected", false )
.each(function( i ) {
if ( $.inArray( i, indicies ) > -1 ) {
var item = $( this );
// Aria selected attr
item.attr( "aria-selected", true );
// Multiple selects: add the "on" checkbox state to the icon
if ( self.isMultiple ) {
item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
} else {
item.addClass( $.mobile.activeBtnClass );
}
}
});
},
close: function() {
if ( this.options.disabled || !this.isOpen ) {
return;
}
var self = this;
if ( self.menuType == "page" ) {
// doesn't solve the possible issue with calling change page
// where the objects don't define data urls which prevents dialog key
// stripping - changePage has incoming refactor
window.history.back();
} else {
self.screen.addClass( "ui-screen-hidden" );
self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" );
self.list.appendTo( self.listbox );
self._focusButton();
}
// allow the dialog to be closed again
self.isOpen = false;
},
open: function() {
if ( this.options.disabled ) {
return;
}
var self = this,
menuHeight = self.list.parent().outerHeight(),
menuWidth = self.list.parent().outerWidth(),
activePage = $( ".ui-page-active" ),
tOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled,
tScrollElem = activePage.is( ".ui-native-fixed" ) ? activePage.find( ".ui-content" ) : activePage;
scrollTop = tOverflow ? tScrollElem.scrollTop() : $( window ).scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = window.innerHeight,
screenWidth = window.innerWidth;
//add active class to button
self.button.addClass( $.mobile.activeBtnClass );
//remove after delay
setTimeout( function() {
self.button.removeClass( $.mobile.activeBtnClass );
}, 300);
function focusMenuItem() {
self.list.find( $.mobile.activeBtnClass ).focus();
}
if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind( "pagehide.remove" );
//for WebOS/Opera Mini (set lastscroll using button offset)
if ( scrollTop == 0 && btnOffset > screenHeight ) {
self.thisPage.one( "pagehide", function() {
$( this ).jqmData( "lastScroll", btnOffset );
});
}
self.menuPage.one( "pageshow", function() {
// silentScroll() is called whenever a page is shown to restore
// any previous scroll position the page may have had. We need to
// wait for the "silentscroll" event before setting focus to avoid
// the browser"s "feature" which offsets rendering to make sure
// whatever has focus is in view.
$( window ).one( "silentscroll", function() {
focusMenuItem();
});
self.isOpen = true;
});
self.menuType = "page";
self.menuPageContent.append( self.list );
self.menuPage.find("div .ui-title").text(self.label.text());
$.mobile.changePage( self.menuPage, {
transition: $.mobile.defaultDialogTransition
});
} else {
self.menuType = "overlay";
self.screen.height( $(document).height() )
.removeClass( "ui-screen-hidden" );
// Try and center the overlay over the button
var roomtop = btnOffset - scrollTop,
roombot = scrollTop + screenHeight - btnOffset,
halfheight = menuHeight / 2,
maxwidth = parseFloat( self.list.parent().css( "max-width" ) ),
newtop, newleft;
if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) {
newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight;
} else {
// 30px tolerance off the edges
newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30;
}
// If the menuwidth is smaller than the screen center is
if ( menuWidth < maxwidth ) {
newleft = ( screenWidth - menuWidth ) / 2;
} else {
//otherwise insure a >= 30px offset from the left
newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2;
// 30px tolerance off the edges
if ( newleft < 30 ) {
newleft = 30;
} else if ( (newleft + menuWidth) > screenWidth ) {
newleft = screenWidth - menuWidth - 30;
}
}
self.listbox.append( self.list )
.removeClass( "ui-selectmenu-hidden" )
.css({
top: newtop,
left: newleft
})
.addClass( "in" );
focusMenuItem();
// duplicate with value set in page show for dialog sized selects
self.isOpen = true;
}
},
_buildList: function() {
var self = this,
o = this.options,
placeholder = this.placeholder,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
// Populate menu with options from select element
self.select.find( "option" ).each( function( i ) {
var $this = $( this ),
$parent = $this.parent(),
text = $this.getEncodedText(),
anchor = "<a href='#'>"+ text +"</a>",
classes = [],
extraAttrs = [];
// Are we inside an optgroup?
if ( $parent.is( "optgroup" ) ) {
var optLabel = $parent.attr( "label" );
// has this optgroup already been built yet?
if ( $.inArray( optLabel, optgroups ) === -1 ) {
lis.push( "<li data-" + $.mobile.ns + "role='list-divider'>"+ optLabel +"</li>" );
optgroups.push( optLabel );
}
}
// Find placeholder text
// TODO: Are you sure you want to use getAttribute? ^RW
if ( !this.getAttribute( "value" ) || text.length == 0 || $this.jqmData( "placeholder" ) ) {
if ( o.hidePlaceholderMenuItems ) {
classes.push( "ui-selectmenu-placeholder" );
}
placeholder = self.placeholder = text;
}
// support disabled option tags
if ( this.disabled ) {
classes.push( "ui-disabled" );
extraAttrs.push( "aria-disabled='true'" );
}
lis.push( "<li data-" + $.mobile.ns + "option-index='" + i + "' data-" + $.mobile.ns + "icon='"+ dataIcon +"' class='"+ classes.join(" ") + "' " + extraAttrs.join(" ") +">"+ anchor +"</li>" );
});
self.list.html( lis.join(" ") );
self.list.find( "li" )
.attr({ "role": "option", "tabindex": "-1" })
.first().attr( "tabindex", "0" );
// Hide header close link for single selects
if ( !this.isMultiple ) {
this.headerClose.hide();
}
// Hide header if it's not a multiselect and there's no placeholder
if ( !this.isMultiple && !placeholder.length ) {
this.header.hide();
} else {
this.headerTitle.text( this.placeholder );
}
// Now populated, create listview
self.list.listview();
},
_button: function(){
return $( "<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
}
});
};
$( "select" ).live( "selectmenubeforecreate", function(){
var selectmenuWidget = $( this ).data( "selectmenu" );
if( !selectmenuWidget.options.nativeMenu ){
extendSelect( selectmenuWidget );
}
});
})( jQuery );
/*
* "selectmenu" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.selectmenu", $.mobile.widget, {
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: null,
corners: true,
shadow: true,
iconshadow: true,
menuPageTheme: "b",
overlayTheme: "a",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
initSelector: "select:not(:jqmData(role='slider'))"
},
_button: function(){
return $( "<div/>" );
},
_setDisabled: function( value ) {
this.element.attr( "disabled", value );
this.button.attr( "aria-disabled", value );
return this._setOption( "disabled", value );
},
_focusButton : function() {
var self = this;
setTimeout( function() {
self.button.focus();
}, 40);
},
_selectOptions: function() {
return this.select.find( "option" );
},
// setup items that are generally necessary for select menu extension
_preExtension: function(){
this.select = this.element.wrap( "<div class='ui-select'>" );
this.selectID = this.select.attr( "id" );
this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
this.isMultiple = this.select[ 0 ].multiple;
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
}
},
_create: function() {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger( "beforeCreate" );
this.button = this._button();
var self = this,
options = this.options,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex == -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.text( $( this.select[ 0 ].options.item( selectedIndex ) ).text() )
.insertBefore( this.select )
.buttonMarkup( {
theme: options.theme,
icon: options.icon,
iconpos: options.iconpos,
inline: options.inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow
});
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if ( options.nativeMenu && window.opera && window.opera.version ) {
this.select.addClass( "ui-select-nativeonly" );
}
// Add counter for multi selects
if ( this.isMultiple ) {
this.buttonCount = $( "<span>" )
.addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
.hide()
.appendTo( button.addClass('ui-li-has-count') );
}
// Disable if specified
if ( options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change( function() {
self.refresh();
});
this.build();
},
build: function() {
var self = this;
this.select
.appendTo( self.button )
.bind( "vmousedown", function() {
// Add active class to button
self.button.addClass( $.mobile.activeBtnClass );
})
.bind( "focus vmouseover", function() {
self.button.trigger( "vmouseover" );
})
.bind( "vmousemove", function() {
// Remove active class on scroll/touchmove
self.button.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur vmouseout", function() {
self.button.trigger( "vmouseout" )
.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur", function() {
self.button.removeClass( "ui-btn-down-" + self.options.theme );
});
},
selected: function() {
return this._selectOptions().filter( ":selected" );
},
selectedIndices: function() {
var self = this;
return this.selected().map( function() {
return self._selectOptions().index( this );
}).get();
},
setButtonText: function() {
var self = this, selected = this.selected();
this.button.find( ".ui-btn-text" ).text( function() {
if ( !self.isMultiple ) {
return selected.text();
}
return selected.length ? selected.map( function() {
return $( this ).text();
}).get().join( ", " ) : self.placeholder;
});
},
setButtonCount: function() {
var selected = this.selected();
// multiple count inside button
if ( this.isMultiple ) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
}
},
refresh: function() {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function() {
this._setDisabled( true );
this.button.addClass( "ui-disabled" );
},
enable: function() {
this._setDisabled( false );
this.button.removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.selectmenu.prototype.enhanceWithin( e.target );
});
})( jQuery );
/*
* "buttons" plugin - for making button-like links
*/
( function( $, undefined ) {
$.fn.buttonMarkup = function( options ) {
options = options || {};
for ( var i = 0; i < this.length; i++ ) {
var el = this.eq( i ),
e = el[ 0 ],
o = $.extend( {}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : el.jqmData( "icon" ),
iconpos: options.iconpos !== undefined ? options.iconpos : el.jqmData( "iconpos" ),
theme: options.theme !== undefined ? options.theme : el.jqmData( "theme" ),
inline: options.inline !== undefined ? options.inline : el.jqmData( "inline" ),
shadow: options.shadow !== undefined ? options.shadow : el.jqmData( "shadow" ),
corners: options.corners !== undefined ? options.corners : el.jqmData( "corners" ),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : el.jqmData( "iconshadow" )
}, options ),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
// Button inner markup
buttonInner = document.createElement( o.wrapperEls ),
buttonText = document.createElement( o.wrapperEls ),
buttonIcon = o.icon ? document.createElement( "span" ) : null;
if ( attachEvents ) {
attachEvents();
}
// if not, try to find closest theme container
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( el, "c" );
}
buttonClass = "ui-btn ui-btn-up-" + o.theme;
if ( o.inline ) {
buttonClass += " ui-btn-inline";
}
if ( o.icon ) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if ( o.iconshadow ) {
iconClass += " ui-icon-shadow";
}
}
if ( o.iconpos ) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if ( o.iconpos == "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
}
if ( o.corners ) {
buttonClass += " ui-btn-corner-all";
innerClass += " ui-btn-corner-all";
}
if ( o.shadow ) {
buttonClass += " ui-shadow";
}
e.setAttribute( "data-" + $.mobile.ns + "theme", o.theme );
el.addClass( buttonClass );
buttonInner.className = innerClass;
buttonInner.setAttribute("aria-hidden", "true");
buttonText.className = textClass;
buttonInner.appendChild( buttonText );
if ( buttonIcon ) {
buttonIcon.className = iconClass;
buttonInner.appendChild( buttonIcon );
}
while ( e.firstChild ) {
buttonText.appendChild( e.firstChild );
}
e.appendChild( buttonInner );
// TODO obviously it would be nice to pull this element out instead of
// retrieving it from the DOM again, but this change is much less obtrusive
// and 1.0 draws nigh
$.data( e, 'textWrapper', $( buttonText ) );
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
inline: false,
wrapperEls: "span"
};
function closestEnabledButton( element ) {
var cname;
while ( element ) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && element.className.split(' ');
if ( cname && $.inArray( "ui-btn", cname ) > -1 && $.inArray( "ui-disabled", cname ) < 0 ) {
break;
}
element = element.parentNode;
}
return element;
}
var attachEvents = function() {
$( document ).bind( {
"vmousedown": function( event ) {
var btn = closestEnabledButton( event.target ),
$btn, theme;
if ( btn ) {
$btn = $( btn );
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
}
},
"vmousecancel vmouseup": function( event ) {
var btn = closestEnabledButton( event.target ),
$btn, theme;
if ( btn ) {
$btn = $( btn );
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
$btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
}
},
"vmouseover focus": function( event ) {
var btn = closestEnabledButton( event.target ),
$btn, theme;
if ( btn ) {
$btn = $( btn );
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
}
},
"vmouseout blur": function( event ) {
var btn = closestEnabledButton( event.target ),
$btn, theme;
if ( btn ) {
$btn = $( btn );
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
$btn.removeClass( "ui-btn-hover-" + theme + " ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
}
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
.not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
.buttonMarkup();
});
})( jQuery );
/*
* "controlgroup" plugin - corner-rounding for groups of buttons, checks, radios, etc
*/
(function( $, undefined ) {
$.fn.controlgroup = function( options ) {
return this.each(function() {
var $el = $( this ),
o = $.extend({
direction: $el.jqmData( "type" ) || "vertical",
shadow: false,
excludeInvisible: true
}, options ),
groupheading = $el.children( "legend" ),
flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ],
type = $el.find( "input" ).first().attr( "type" );
// Replace legend with more stylable replacement div
if ( groupheading.length ) {
$el.wrapInner( "<div class='ui-controlgroup-controls'></div>" );
$( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) );
groupheading.remove();
}
$el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction );
// TODO: This should be moved out to the closure
// otherwise it is redefined each time controlgroup() is called
function flipClasses( els ) {
els.removeClass( "ui-btn-corner-all ui-shadow" )
.eq( 0 ).addClass( flCorners[ 0 ] )
.end()
.last().addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" );
}
flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ) );
flipClasses( $el.find( ".ui-btn-inner" ) );
if ( o.shadow ) {
$el.addClass( "ui-shadow" );
}
});
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='controlgroup')", e.target ).controlgroup({ excludeInvisible: false });
});
})(jQuery);/*
* "links" plugin - simple class additions for links
*/
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ){
//links within content areas
$( e.target )
.find( "a" )
.not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
.addClass( "ui-link" );
});
})( jQuery );/*
* "fixHeaderFooter" plugin - on-demand positioning for headers,footers
*/
(function( $, undefined ) {
var slideDownClass = "ui-header-fixed ui-fixed-inline fade",
slideUpClass = "ui-footer-fixed ui-fixed-inline fade",
slideDownSelector = ".ui-header:jqmData(position='fixed')",
slideUpSelector = ".ui-footer:jqmData(position='fixed')";
$.fn.fixHeaderFooter = function( options ) {
if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) {
return this;
}
return this.each(function() {
var $this = $( this );
if ( $this.jqmData( "fullscreen" ) ) {
$this.addClass( "ui-page-fullscreen" );
}
// Should be slidedown
$this.find( slideDownSelector ).addClass( slideDownClass );
// Should be slideup
$this.find( slideUpSelector ).addClass( slideUpClass );
});
};
// single controller for all showing,hiding,toggling
$.mobile.fixedToolbars = (function() {
if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) {
return;
}
var stickyFooter, delayTimer,
currentstate = "inline",
autoHideMode = false,
showDelay = 100,
ignoreTargets = "a,input,textarea,select,button,label,.ui-header-fixed,.ui-footer-fixed",
toolbarSelector = ".ui-header-fixed:first, .ui-footer-fixed:not(.ui-footer-duplicate):last",
// for storing quick references to duplicate footers
supportTouch = $.support.touch,
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
stateBefore = null,
scrollTriggered = false,
touchToggleEnabled = true;
function showEventCallback( event ) {
// An event that affects the dimensions of the visual viewport has
// been triggered. If the header and/or footer for the current page are in overlay
// mode, we want to hide them, and then fire off a timer to show them at a later
// point. Events like a resize can be triggered continuously during a scroll, on
// some platforms, so the timer is used to delay the actual positioning until the
// flood of events have subsided.
//
// If we are in autoHideMode, we don't do anything because we know the scroll
// callbacks for the plugin will fire off a show when the scrolling has stopped.
if ( !autoHideMode && currentstate === "overlay" ) {
if ( !delayTimer ) {
$.mobile.fixedToolbars.hide( true );
}
$.mobile.fixedToolbars.startShowTimer();
}
}
$(function() {
var $document = $( document ),
$window = $( window );
$document
.bind( "vmousedown", function( event ) {
if ( touchToggleEnabled ) {
stateBefore = currentstate;
}
})
.bind( "vclick", function( event ) {
if ( touchToggleEnabled ) {
if ( $(event.target).closest( ignoreTargets ).length ) {
return;
}
if ( !scrollTriggered ) {
$.mobile.fixedToolbars.toggle( stateBefore );
stateBefore = null;
}
}
})
.bind( "silentscroll", showEventCallback );
// The below checks first for a $(document).scrollTop() value, and if zero, binds scroll events to $(window) instead.
// If the scrollTop value is actually zero, both will return zero anyway.
//
// Works with $(document), not $(window) : Opera Mobile (WinMO phone; kinda broken anyway)
// Works with $(window), not $(document) : IE 7/8
// Works with either $(window) or $(document) : Chrome, FF 3.6/4, Android 1.6/2.1, iOS
// Needs work either way : BB5, Opera Mobile (iOS)
( ( $document.scrollTop() === 0 ) ? $window : $document )
.bind( "scrollstart", function( event ) {
scrollTriggered = true;
if ( stateBefore === null ) {
stateBefore = currentstate;
}
// We only enter autoHideMode if the headers/footers are in
// an overlay state or the show timer was started. If the
// show timer is set, clear it so the headers/footers don't
// show up until after we're done scrolling.
var isOverlayState = stateBefore == "overlay";
autoHideMode = isOverlayState || !!delayTimer;
if ( autoHideMode ) {
$.mobile.fixedToolbars.clearShowTimer();
if ( isOverlayState ) {
$.mobile.fixedToolbars.hide( true );
}
}
})
.bind( "scrollstop", function( event ) {
if ( $( event.target ).closest( ignoreTargets ).length ) {
return;
}
scrollTriggered = false;
if ( autoHideMode ) {
$.mobile.fixedToolbars.startShowTimer();
autoHideMode = false;
}
stateBefore = null;
});
$window.bind( "resize updatelayout", showEventCallback );
});
// 1. Before page is shown, check for duplicate footer
// 2. After page is shown, append footer to new page
$( ".ui-page" )
.live( "pagebeforeshow", function( event, ui ) {
var page = $( event.target ),
footer = page.find( ":jqmData(role='footer')" ),
id = footer.data( "id" ),
prevPage = ui.prevPage,
prevFooter = prevPage && prevPage.find( ":jqmData(role='footer')" ),
prevFooterMatches = prevFooter.length && prevFooter.jqmData( "id" ) === id;
if ( id && prevFooterMatches ) {
stickyFooter = footer;
setTop( stickyFooter.removeClass( "fade in out" ).appendTo( $.mobile.pageContainer ) );
}
})
.live( "pageshow", function( event, ui ) {
var $this = $( this );
if ( stickyFooter && stickyFooter.length ) {
setTimeout(function() {
setTop( stickyFooter.appendTo( $this ).addClass( "fade" ) );
stickyFooter = null;
}, 500);
}
$.mobile.fixedToolbars.show( true, this );
});
// When a collapsiable is hidden or shown we need to trigger the fixed toolbar to reposition itself (#1635)
$( ".ui-collapsible-contain" ).live( "collapse expand", showEventCallback );
// element.getBoundingClientRect() is broken in iOS 3.2.1 on the iPad. The
// coordinates inside of the rect it returns don't have the page scroll position
// factored out of it like the other platforms do. To get around this,
// we'll just calculate the top offset the old fashioned way until core has
// a chance to figure out how to handle this situation.
//
// TODO: We'll need to get rid of getOffsetTop() once a fix gets folded into core.
function getOffsetTop( ele ) {
var top = 0,
op, body;
if ( ele ) {
body = document.body;
op = ele.offsetParent;
top = ele.offsetTop;
while ( ele && ele != body ) {
top += ele.scrollTop || 0;
if ( ele == op ) {
top += op.offsetTop;
op = ele.offsetParent;
}
ele = ele.parentNode;
}
}
return top;
}
function setTop( el ) {
var fromTop = $(window).scrollTop(),
thisTop = getOffsetTop( el[ 0 ] ), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead.
thisCSStop = el.css( "top" ) == "auto" ? 0 : parseFloat(el.css( "top" )),
screenHeight = window.innerHeight,
thisHeight = el.outerHeight(),
useRelative = el.parents( ".ui-page:not(.ui-page-fullscreen)" ).length,
relval;
if ( el.is( ".ui-header-fixed" ) ) {
relval = fromTop - thisTop + thisCSStop;
if ( relval < thisTop ) {
relval = 0;
}
return el.css( "top", useRelative ? relval : fromTop );
} else {
// relval = -1 * (thisTop - (fromTop + screenHeight) + thisCSStop + thisHeight);
// if ( relval > thisTop ) { relval = 0; }
relval = fromTop + screenHeight - thisHeight - (thisTop - thisCSStop );
return el.css( "top", useRelative ? relval : fromTop + screenHeight - thisHeight );
}
}
// Exposed methods
return {
show: function( immediately, page ) {
$.mobile.fixedToolbars.clearShowTimer();
currentstate = "overlay";
var $ap = page ? $( page ) :
( $.mobile.activePage ? $.mobile.activePage :
$( ".ui-page-active" ) );
return $ap.children( toolbarSelector ).each(function() {
var el = $( this ),
fromTop = $( window ).scrollTop(),
// el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead.
thisTop = getOffsetTop( el[ 0 ] ),
screenHeight = window.innerHeight,
thisHeight = el.outerHeight(),
alreadyVisible = ( el.is( ".ui-header-fixed" ) && fromTop <= thisTop + thisHeight ) ||
( el.is( ".ui-footer-fixed" ) && thisTop <= fromTop + screenHeight );
// Add state class
el.addClass( "ui-fixed-overlay" ).removeClass( "ui-fixed-inline" );
if ( !alreadyVisible && !immediately ) {
el.animationComplete(function() {
el.removeClass( "in" );
}).addClass( "in" );
}
setTop(el);
});
},
hide: function( immediately ) {
currentstate = "inline";
var $ap = $.mobile.activePage ? $.mobile.activePage :
$( ".ui-page-active" );
return $ap.children( toolbarSelector ).each(function() {
var el = $(this),
thisCSStop = el.css( "top" ),
classes;
thisCSStop = thisCSStop == "auto" ? 0 :
parseFloat(thisCSStop);
// Add state class
el.addClass( "ui-fixed-inline" ).removeClass( "ui-fixed-overlay" );
if ( thisCSStop < 0 || ( el.is( ".ui-header-fixed" ) && thisCSStop !== 0 ) ) {
if ( immediately ) {
el.css( "top", 0);
} else {
if ( el.css( "top" ) !== "auto" && parseFloat( el.css( "top" ) ) !== 0 ) {
classes = "out reverse";
el.animationComplete(function() {
el.removeClass( classes ).css( "top", 0 );
}).addClass( classes );
}
}
}
});
},
startShowTimer: function() {
$.mobile.fixedToolbars.clearShowTimer();
var args = [].slice.call( arguments );
delayTimer = setTimeout(function() {
delayTimer = undefined;
$.mobile.fixedToolbars.show.apply( null, args );
}, showDelay);
},
clearShowTimer: function() {
if ( delayTimer ) {
clearTimeout( delayTimer );
}
delayTimer = undefined;
},
toggle: function( from ) {
if ( from ) {
currentstate = from;
}
return ( currentstate === "overlay" ) ? $.mobile.fixedToolbars.hide() :
$.mobile.fixedToolbars.show();
},
setTouchToggleEnabled: function( enabled ) {
touchToggleEnabled = enabled;
}
};
})();
//auto self-init widgets
$( document ).bind( "pagecreate create", function( event ) {
if ( $( ":jqmData(position='fixed')", event.target ).length ) {
$( event.target ).each(function() {
if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) {
return this;
}
var $this = $( this );
if ( $this.jqmData( "fullscreen" ) ) {
$this.addClass( "ui-page-fullscreen" );
}
// Should be slidedown
$this.find( slideDownSelector ).addClass( slideDownClass );
// Should be slideup
$this.find( slideUpSelector ).addClass( slideUpClass );
})
}
});
})( jQuery );
/*
* "fixHeaderFooter" native plugin - Behavior for "fixed" headers,footers, and scrolling inner content
*/
(function( $, undefined ) {
// Enable touch overflow scrolling when it's natively supported
$.mobile.touchOverflowEnabled = false;
// Enabled zoom when touch overflow is enabled. Can cause usability issues, unfortunately
$.mobile.touchOverflowZoomEnabled = false;
$( document ).bind( "pagecreate", function( event ) {
if( $.support.touchOverflow && $.mobile.touchOverflowEnabled ){
var $target = $( event.target ),
scrollStartY = 0;
if( $target.is( ":jqmData(role='page')" ) ){
$target.each(function() {
var $page = $( this ),
$fixies = $page.find( ":jqmData(role='header'), :jqmData(role='footer')" ).filter( ":jqmData(position='fixed')" ),
fullScreen = $page.jqmData( "fullscreen" ),
$scrollElem = $fixies.length ? $page.find( ".ui-content" ) : $page;
$page.addClass( "ui-mobile-touch-overflow" );
$scrollElem.bind( "scrollstop", function(){
if( $scrollElem.scrollTop() > 0 ){
window.scrollTo( 0, $.mobile.defaultHomeScroll );
}
});
if( $fixies.length ){
$page.addClass( "ui-native-fixed" );
if( fullScreen ){
$page.addClass( "ui-native-fullscreen" );
$fixies.addClass( "fade in" );
$( document ).bind( "vclick", function(){
$fixies
.removeClass( "ui-native-bars-hidden" )
.toggleClass( "in out" )
.animationComplete(function(){
$(this).not( ".in" ).addClass( "ui-native-bars-hidden" );
});
});
}
}
});
}
}
});
})( jQuery );
/*
* "init" - Initialize the framework
*/
(function( $, window, undefined ) {
var $html = $( "html" ),
$head = $( "head" ),
$window = $( window );
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$( window.document ).trigger( "mobileinit" );
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if ( !$.mobile.gradeA() ) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ( $.mobile.ajaxBlacklist ) {
$.mobile.ajaxEnabled = false;
}
// add mobile, initial load "rendering" classes to docEl
$html.addClass( "ui-mobile ui-mobile-rendering" );
// loading div which appears during Ajax requests
// will not appear if $.mobile.loadingMessage is false
var $loader = $( "<div class='ui-loader ui-body-a ui-corner-all'><span class='ui-icon ui-icon-loading spin'></span><h1></h1></div>" );
$.extend($.mobile, {
// turn on/off page loading message.
showPageLoadingMsg: function() {
if ( $.mobile.loadingMessage ) {
var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
$loader
.find( "h1" )
.text( $.mobile.loadingMessage )
.end()
.appendTo( $.mobile.pageContainer )
// position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
}
$html.addClass( "ui-loading" );
},
hidePageLoadingMsg: function() {
$html.removeClass( "ui-loading" );
},
// find and enhance the pages in the dom and transition to the first page.
initializePage: function() {
// find present pages
var $pages = $( ":jqmData(role='page')" );
// if no pages are found, create one with body's inner html
if ( !$pages.length ) {
$pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
}
// add dialogs, set data-url attrs
$pages.add( ":jqmData(role='dialog')" ).each(function() {
var $this = $(this);
// unless the data url is already set set it to the pathname
if ( !$this.jqmData("url") ) {
$this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" );
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger( "pagecontainercreate" );
// cue page loading message
$.mobile.showPageLoadingMsg();
// if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM
if ( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ) {
$.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } );
}
// otherwise, trigger a hashchange to load a deeplink
else {
$window.trigger( "hashchange", [ true ] );
}
}
});
// This function injects a meta viewport tag to prevent scaling. Off by default, on by default when touchOverflow scrolling is enabled
function disableZoom() {
var cont = "user-scalable=no",
meta = $( "meta[name='viewport']" );
if( meta.length ){
meta.attr( "content", meta.attr( "content" ) + ", " + cont );
}
else{
$( "head" ).prepend( "<meta>", { "name": "viewport", "content": cont } );
}
}
// if touch-overflow is enabled, disable user scaling, as it creates usability issues
if( $.support.touchOverflow && $.mobile.touchOverflowEnabled && !$.mobile.touchOverflowZoomEnabled ){
disableZoom();
}
// initialize events now, after mobileinit has occurred
$.mobile._registerInternalEvents();
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function() {
window.scrollTo( 0, 1 );
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1;
//dom-ready inits
if( $.mobile.autoInitializePage ){
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
});
})( jQuery, this );
| JavaScript |
/* Categories Panel */
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:197,
currentBottom:0
}
});
$(window).scroll(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:197,
currentBottom:0
}
});
}).resize(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:197,
currentBottom:0
}
});
});
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:197,
currentBottom:0
}
});
/* Screenshot */
jQuery(document).ready(function() {
jQuery("#game-screen-shot").jcarousel({
scroll: 1,
visible: 2,
initCallback: slider_initCallback,
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
function slider_initCallback(carousel) {
/*
jQuery('.jcarousel-control a').bind('click', function() {
carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
return false;
});*/
carousel.clip.hover(
function() {
sliders[j].stopAuto();
},
function() {
sliders[j].startAuto();
}
);
jQuery('#screen-next').bind('click', function() {
carousel.next();
return false;
});
jQuery('#screen-back').bind('click', function() {
carousel.prev();
return false;
});
}
$("#game-screen-shot").hover(
function () {
var height = $("#game-screen-shot-slider").height();
var width = $("#game-screen-shot-slider").width();
$("#screen-back").css({
top: ((height-$("#screen-next").height()) /2)+"px",
left: "0px"
});
$("#screen-next").css({
top: ((height-$("#screen-back").height()) /2)+"px",
right: "0px"
});
$("#screen-next").fadeIn("slow");
$("#screen-back").fadeIn("slow");
},
function () {
$("#screen-next").fadeOut("slow");
$("#screen-back").fadeOut("slow");
}
); | JavaScript |
/* Banner Slider */
jQuery(document).ready(function() {
jQuery("#banner-slider").jcarousel({
scroll: 1,
visible: 3,
initCallback: slider_initCallback,
itemVisibleInCallback: {
onBeforeAnimation: function(){
$("#banner-slider-current").css({
'opacity':'0'
});
},
onAfterAnimation: function(){
$("#banner-slider-current").css({
'opacity':'1'
});
}
},
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
jQuery(document).ready(function() {
jQuery("#banner-slider-current").jcarousel({
scroll: 1,
visible: 1,
initCallback: slider_initCallback,
itemVisibleInCallback: highlight,
itemVisibleOutCallback: removehighlight,
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
$(window).bind("load", function() {
$("#banner-slider").css({
position: "absolute",
left: -(($("#banner-slider").width()-$("body").width())/2) + "px"
});
});
var sliders = [];
function slider_initCallback(carousel) {
sliders.push(carousel);
carousel.clip.hover(function() {
for(j=0;j<sliders.length;j++){
sliders[j].stopAuto();
}
}, function() {
for(j=0;j<sliders.length;j++){
sliders[j].startAuto();
}
});
jQuery('#slider-next').bind('click', function() {
carousel.next();
return false;
});
jQuery('#slider-back').bind('click', function() {
carousel.prev();
return false;
});
}
function highlight(carousel, obejctli, liindex, listate) {
$('.jcarousel-control a:nth-child(' + liindex + ')').addClass("active");
}
function removehighlight(carousel, obejctli, liindex, listate) {
$('.jcarousel-control a:nth-child(' + liindex + ')').removeClass("active");
}
$("#slider").hover(function () {
var itemWidth = $("#banner-slider-current").width();
var height = $("#slider").height();
var width = $("#slider").width();
var m = $("#slider-next").width()/4;
$("#slider-next").css({
top: ((height-$("#slider-next").height()) /2)+"px",
left: ((width-itemWidth)/2 +itemWidth - m) + "px"
});
$("#slider-back").css({
top: ((height-$("#slider-back").height()) /2)+"px",
right: ((width-itemWidth)/2 +itemWidth - m) + "px"
});
$("#slider-next").fadeIn("slow");
$("#slider-back").fadeIn("slow");
},function () {
$("#slider-next").fadeOut("slow");
$("#slider-back").fadeOut("slow");
});
function bannerHandle_Scroll(){
$("#banner-slider").css({
position: "absolute",
left: -(( $("#banner-slider").width()-$("body").width())/2) + "px"
});
}
$(window).scroll(bannerHandle_Scroll).resize(bannerHandle_Scroll);
/* Categories Panel */
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:247,
currentBottom:50
}
});
$(window).scroll(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:247,
currentBottom:50
}
});
}).resize(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:247,
currentBottom:50
}
});
});
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:247,
currentBottom:50
}
}); | JavaScript |
/* Ugame jquery function */
$.fn.flowUp = function(options){
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "-=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowDown = function(options){
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "+=" + $(this).height() * step + "px"
},
duration,
callback
);
}
/* ACTION PANEL */
$.fn.processScrollEventOnActionPanel = function(){
if(!$(this).is(':hidden')){
$(this).hide();
$(this).flowUp({
step:"1",
duration:"normal"
});
}
}
$.fn.addActionClickHandlerOnActionPanel = function(options){
var panel = options["panel"];
var panels = options["disablePanels"];
//init position for panel
$(panel).flowUp({
step:"1",
duration:"normal"
});
//register Scroll handler for window
$(window).scroll(function(){
$(panel).processScrollEventOnActionPanel();
}).resize(function(){
$(panel).processScrollEventOnActionPanel();
});
//register Click handler for button
$(this).click(function(){
//Hide all disable Panels
jQuery.each(panels, function(i, panel) {
if(!$(panel).is(':hidden')){
$(panel).hide();
$(panel).flowUp({
step:"1",
duration:"normal"
});
}
});
//Show or hide panel
if(!$(panel).is(':hidden')){
$(panel).flowUp({
step:"1",
duration:"normal",
callback: function(){
$(panel).hide();
}
});
}
else
{
$(panel).show();
$(panel).flowDown({
step:"1",
duration:"normal"
});
}
});
}
$("#btn-login").addActionClickHandlerOnActionPanel({
panel:"#login-panel",
disablePanels: ["#language-panel", "#search-panel"]
});
$("#btn-search").addActionClickHandlerOnActionPanel({
panel:"#search-panel",
disablePanels: ["#language-panel", "#login-panel"]
});
$("#btn-language").addActionClickHandlerOnActionPanel({
panel:"#language-panel",
disablePanels: ["#login-panel", "#search-panel"]
});
/* Categories Panel*/
function drawCategoryDock(options) {
var mainNav = options["mainNav"];
var controlBtn = options["controlBtn"];
var subNav = options["subNav"];
var config = options["config"];
$(subNav).hide();
$(controlBtn).parent().removeClass("active");
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > config.showBottom) {
$(mainNav).css({
position: "fixed",
bottom: "0px"
});
} else {
$(mainNav).css({
position: "absolute",
bottom: config.currentBottom + "px"
});
}
}
$.fn.controlSubCategoryNav = function controlSubCategoryNav(options) {
$(this).click(function(){
var mainNav = options["mainNav"];
var subNav = options["subNav"];
var config = options["config"];
var categoryItemWidth = $(this).width() - 1;
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > 247) {
$(subNav).css({
width:categoryItemWidth + "px",
position: "fixed",
bottom: $(mainNav).height()+"px"
});
} else {
$(subNav).css({
width:categoryItemWidth + "px",
position: "absolute",
bottom: $(mainNav).height()+ config.currentBottom+"px"
});
}
if ($(subNav).is(':hidden')) {
$(this).parent().addClass("active");
} else {
$(this).parent().removeClass("active");
}
$(subNav).slideToggle("normal");
});
} | JavaScript |
/* Init control for buttons in action panel */
$("#searchButton").control({
type: FD_PANEL_CONTROL,
panel: "#search-panel"
});
$("#accountButton").control({
type: FD_PANEL_CONTROL,
panel: "#login-panel"
});
$("#settingButton").control({
type: FD_PANEL_CONTROL,
panel: "#language-panel"
}); | JavaScript |
/* Custom jquery function */
$.fn.flowUp = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "-=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowLeft = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "+=" + $(this).width() * step + "px"
},
duration,
callback
);
}
$.fn.flowDown = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "+=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowRight = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "-=" + $(this).width() * step + "px"
},
duration,
callback
);
}
/* Control function */
var CHILD_FD_PANELS = new Array();
var FD_CONTROL_BUTTONS = new Array();
var FD_PANEL_CONTROL = 1;
var CATEGORY_CONTROL = 2;
var LANGUAGE_CONTROL = 3;
$.fn.control = function(options){
var type = options["type"];
if(type == FD_PANEL_CONTROL){
var panel = options["panel"];
CHILD_FD_PANELS.push(panel);
FD_CONTROL_BUTTONS.push(this);
$(this).click(function(){
if ($(panel).parent().is(':hidden') || (!$(panel).parent().is(':hidden') && $(panel).is(':hidden'))){
for (var i=0; i < CHILD_FD_PANELS.length; i++) {
$(CHILD_FD_PANELS[i]).hide();
}
for (i=0; i < FD_CONTROL_BUTTONS.length; i++) {
$(FD_CONTROL_BUTTONS[i]).removeClass("active");
}
$(panel).show();
$(this).addClass("active");
if($(panel).parent().is(':hidden')){
$(panel).parent().slideToggle("fast");
}
}else if (!$(panel).parent().is(':hidden') && !$(panel).is(':hidden')){
$(panel).parent().slideToggle("fast");
for (i=0; i < CHILD_FD_PANELS.length; i++) {
$(CHILD_FD_PANELS[i]).hide();
}
$(this).removeClass("active");
}
});
} else if(type == CATEGORY_CONTROL){
$(this).click(function() {
var subNav = options["subNav"];
var width = $(this).width();
$(subNav).css({
width:width + "px",
position: "absolute",
bottom: $(subNav).parent().height() + 2 + "px"
});
$(subNav).slideToggle("normal");
});
} else if(type == LANGUAGE_CONTROL){
var inputs = $(this);
$.each(inputs, function() {
var pathName = $(this).attr('alt');
$(this).click(function(){
window.location.href = getDirectUrl(pathName);
});
});
}
}
/*Expand & Collapse Panel*/
$.fn.expandCollapsePanel = function(options) {
var button = options["button"];
var container = options["containerPanel"];
var content = options["contentPanel"];
var config = options["config"];
$(button).click(function() {
if(!$(this).hasClass('active')){
$(container).animate({
height: $(content).height()
},function(){
$(container).removeClass('doc-description-collapsed');
$(button).addClass('active');
});
}else{
$(container).addClass('doc-description-collapsed');
$(container).animate({
height: config.height + "px"
},function(){
$(button).removeClass('active');
});
}
});
}
/* getDirectUrl */
function getDirectUrl(pathName){
return window.location.protocol + "//" + window.location.host + pathName;
}
/* Login Panel */
$.fn.login = function(options) {
var loginUrl = options["loginUrl"];
var email = options["email"];
var password = options["password"];
$.ajax({
url: loginUrl,
type: "POST",
dataType: "json",
data: {
email: email,
password: password
},
success: function (responseJson) {
if(responseJson == null){
location.reload();
}
alert(responseJson);
}
});
}
| JavaScript |
/* Categories Panel */
$("#category").control({
type: CATEGORY_CONTROL,
subNav: "#category-sub-nav"
}); | JavaScript |
/**
* Created by JetBrains WebStorm.
* User: user
* Date: 6/27/12
* Time: 9:15 PM
* To change this template use File | Settings | File Templates.
*/
//Execute the function when window load
$(window).bind("load", function() {
//setup the height and position for your sticky footer
footerHeight = 0,
footerTop = 0,
$footer = $("#footer");
positionFooter();
function positionFooter() {
footerHeight = $footer.height();
footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
if ( ($(document.body).height()+footerHeight) < $(window).height()) {
$footer.css({
position: "absolute"
}).animate({
top: footerTop
})
} else {
$footer.css({
position: "static"
})
}
}
$(window).scroll(positionFooter)
.resize(positionFooter)
}) | JavaScript |
/**
* Created by JetBrains WebStorm.
* User: user
* Date: 6/27/12
* Time: 9:15 PM
* To change this template use File | Settings | File Templates.
*/
//Execute the function when window load
$(window).bind("load", function() {
//setup the height and position for your sticky footer
footerHeight = 0,
footerTop = 0,
$footer = $("#footer");
positionFooter();
function positionFooter() {
footerHeight = $footer.height();
footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
if ( ($(document.body).height()+footerHeight) < $(window).height()) {
$footer.css({
position: "absolute"
}).animate({
top: footerTop
})
} else {
$footer.css({
position: "static"
})
}
}
$(window).scroll(positionFooter)
.resize(positionFooter)
}) | JavaScript |
/* Categories Panel */
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:148,
currentBottom:0
}
});
$(window).scroll(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:148,
currentBottom:0
}
});
}).resize(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:148,
currentBottom:0
}
});
});
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:148,
currentBottom:0
}
});
/* Screenshot */
jQuery(document).ready(function() {
jQuery("#game-screen-shot").jcarousel({
scroll: 1,
visible: 2,
initCallback: slider_initCallback,
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
function slider_initCallback(carousel) {
/*
jQuery('.jcarousel-control a').bind('click', function() {
carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
return false;
});*/
carousel.clip.hover(
function() {
sliders[j].stopAuto();
},
function() {
sliders[j].startAuto();
}
);
jQuery('#screen-next').bind('click', function() {
carousel.next();
return false;
});
jQuery('#screen-back').bind('click', function() {
carousel.prev();
return false;
});
}
$("#game-screen-shot").hover(
function () {
var height = $("#game-screen-shot-slider").height();
var width = $("#game-screen-shot-slider").width();
$("#screen-back").css({
top: ((height-$("#screen-next").height()) /2)+"px",
left: "0px"
});
$("#screen-next").css({
top: ((height-$("#screen-back").height()) /2)+"px",
right: "0px"
});
$("#screen-next").fadeIn("slow");
$("#screen-back").fadeIn("slow");
},
function () {
$("#screen-next").fadeOut("slow");
$("#screen-back").fadeOut("slow");
}
); | JavaScript |
/* Banner Slider */
jQuery(document).ready(function() {
jQuery("#banner-slider").jcarousel({
scroll: 1,
visible: 3,
initCallback: slider_initCallback,
itemVisibleInCallback: {
onBeforeAnimation: function(){
$("#banner-slider-current").css({
'opacity':'0'
});
},
onAfterAnimation: function(){
$("#banner-slider-current").css({
'opacity':'1'
});
}
},
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
jQuery(document).ready(function() {
jQuery("#banner-slider-current").jcarousel({
scroll: 1,
visible: 1,
initCallback: slider_initCallback,
itemVisibleInCallback: highlight,
itemVisibleOutCallback: removehighlight,
buttonNextHTML: null,
buttonPrevHTML: null,
wrap: 'both',
auto: 10
});
});
$(window).bind("load", function() {
$("#banner-slider").css({
position: "absolute",
left: -(($("#banner-slider").width()-$("body").width())/2) + "px"
});
});
var sliders = [];
function slider_initCallback(carousel) {
sliders.push(carousel);
carousel.clip.hover(function() {
for(j=0;j<sliders.length;j++){
sliders[j].stopAuto();
}
}, function() {
for(j=0;j<sliders.length;j++){
sliders[j].startAuto();
}
});
jQuery('#slider-next').bind('click', function() {
carousel.next();
return false;
});
jQuery('#slider-back').bind('click', function() {
carousel.prev();
return false;
});
}
function highlight(carousel, obejctli, liindex, listate) {
$('.jcarousel-control a:nth-child(' + liindex + ')').addClass("active");
}
function removehighlight(carousel, obejctli, liindex, listate) {
$('.jcarousel-control a:nth-child(' + liindex + ')').removeClass("active");
}
$("#slider").hover(function () {
var itemWidth = $("#banner-slider-current").width();
var height = $("#slider").height();
var width = $("#slider").width();
var m = $("#slider-next").width()/4;
$("#slider-next").css({
top: ((height-$("#slider-next").height()) /2)+"px",
left: ((width-itemWidth)/2 +itemWidth - m) + "px"
});
$("#slider-back").css({
top: ((height-$("#slider-back").height()) /2)+"px",
right: ((width-itemWidth)/2 +itemWidth - m) + "px"
});
$("#slider-next").fadeIn("slow");
$("#slider-back").fadeIn("slow");
},function () {
$("#slider-next").fadeOut("slow");
$("#slider-back").fadeOut("slow");
});
function bannerHandle_Scroll(){
$("#banner-slider").css({
position: "absolute",
left: -(( $("#banner-slider").width()-$("body").width())/2) + "px"
});
}
$(window).scroll(bannerHandle_Scroll).resize(bannerHandle_Scroll);
/* Categories Panel */
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:235,
currentBottom:38
}
});
$(window).scroll(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:235,
currentBottom:38
}
});
}).resize(function(){
drawCategoryDock({
mainNav: "#category-nav",
controlBtn: "#category",
subNav:"#category-sub-nav",
config:{
showBottom:235,
currentBottom:38
}
});
});
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:235,
currentBottom:38
}
}); | JavaScript |
/* Ugame jquery function */
$.fn.flowUp = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "-=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowLeft = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "+=" + $(this).width() * step + "px"
},
duration,
callback
);
}
$.fn.flowDown = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "+=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowRight = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "-=" + $(this).width() * step + "px"
},
duration,
callback
);
}
/* ACTION PANEL */
$.fn.processScrollEventOnActionPanel = function() {
if (!$(this).is(':hidden')) {
$(this).hide();
$(this).flowUp({
step:"1",
duration:"normal"
});
}
}
$.fn.addActionClickHandlerOnActionPanel = function(options) {
var panel = options["panel"];
var panels = options["disablePanels"];
//init position for panel
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal"
});
}
//register Scroll handler for window
/*
$(window).scroll(function(){
$(panel).processScrollEventOnActionPanel();
}).resize(function(){
$(panel).processScrollEventOnActionPanel();
});*/
//register Click handler for button
$(this).click(function() {
//Hide all disable Panels
jQuery.each(panels, function(i, panel) {
if (!$(panel["id"]).is(':hidden')) {
$(panel["id"]).hide();
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal"
});
}
}
});
//Show or hide panel
if (!$(panel["id"]).is(':hidden')) {
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal",
callback: function(){
$(panel["id"]).hide();
}
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal",
callback: function(){
$(panel["id"]).hide();
}
});
}
}
else {
$(panel["id"]).show();
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowLeft({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowDown({
step:"1",
duration:"normal"
});
}
}
});
}
$("#btn-login").addActionClickHandlerOnActionPanel({
panel:{id:"#login-panel",animate:"LeftRight"},
disablePanels: [
{id:"#language-panel",animate:"UpDown"},
{id:"#search-panel", animate:"LeftRight"}
]
});
$("#btn-search").addActionClickHandlerOnActionPanel({
panel:{id:"#search-panel",animate:"LeftRight"},
disablePanels: [
{id:"#language-panel",animate:"UpDown"},
{id:"#login-panel", animate:"LeftRight"}
]
});
$("#btn-language").addActionClickHandlerOnActionPanel({
panel:{id:"#language-panel",animate:"UpDown"},
disablePanels: [
{id:"#login-panel", animate:"LeftRight"},
{id:"#search-panel", animate:"LeftRight"}
]
});
/* Categories Panel*/
function drawCategoryDock(options) {
var mainNav = options["mainNav"];
var controlBtn = options["controlBtn"];
var subNav = options["subNav"];
var config = options["config"];
$(subNav).hide();
$(controlBtn).parent().removeClass("active");
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > config.showBottom) {
$(mainNav).css({
position: "fixed",
bottom: "0px"
});
} else {
$(mainNav).css({
position: "absolute",
bottom: config.currentBottom + "px"
});
}
}
$.fn.controlSubCategoryNav = function controlSubCategoryNav(options) {
$(this).click(function() {
var mainNav = options["mainNav"];
var subNav = options["subNav"];
var config = options["config"];
var categoryItemWidth = $(this).width() - 1;
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > 247) {
$(subNav).css({
width:categoryItemWidth + "px",
position: "fixed",
bottom: $(mainNav).height() + "px"
});
} else {
$(subNav).css({
width:categoryItemWidth + "px",
position: "absolute",
bottom: $(mainNav).height() + config.currentBottom + "px"
});
}
if ($(subNav).is(':hidden')) {
$(this).parent().addClass("active");
} else {
$(this).parent().removeClass("active");
}
$(subNav).slideToggle("normal");
});
} | JavaScript |
/**
*
* Find more about the scrolling function at
* http://cubiq.org/iscroll
*
* Copyright (c) 2010 Matteo Spinelli, http://cubiq.org/
* Released under MIT license
* http://cubiq.org/dropbox/mit-license.txt
*
* Version 3.7.1 - Last updated: 2010.10.08
*
*/
(function(){
function iScroll (el, options) {
var that = this, i;
that.element = typeof el == 'object' ? el : document.getElementById(el);
that.wrapper = that.element.parentNode;
that.element.style.webkitTransitionProperty = '-webkit-transform';
that.element.style.webkitTransitionTimingFunction = 'cubic-bezier(0,0,0.25,1)';
that.element.style.webkitTransitionDuration = '0';
that.element.style.webkitTransform = translateOpen + '0,0' + translateClose;
// Default options
that.options = {
bounce: has3d,
momentum: has3d,
checkDOMChanges: true,
topOnDOMChanges: false,
hScrollbar: has3d,
vScrollbar: has3d,
fadeScrollbar: isIthing || !isTouch,
shrinkScrollbar: isIthing || !isTouch,
desktopCompatibility: false,
overflow: 'auto',
snap: false,
bounceLock: false,
scrollbarColor: 'rgba(0,0,0,0.5)',
onScrollEnd: function () {}
};
// User defined options
if (typeof options == 'object') {
for (i in options) {
that.options[i] = options[i];
}
}
if (that.options.desktopCompatibility) {
that.options.overflow = 'hidden';
}
that.onScrollEnd = that.options.onScrollEnd;
delete that.options.onScrollEnd;
that.wrapper.style.overflow = that.options.overflow;
that.refresh();
window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', that, false);
if (isTouch || that.options.desktopCompatibility) {
that.element.addEventListener(START_EVENT, that, false);
that.element.addEventListener(MOVE_EVENT, that, false);
that.element.addEventListener(END_EVENT, that, false);
}
if (that.options.checkDOMChanges) {
that.element.addEventListener('DOMSubtreeModified', that, false);
}
}
iScroll.prototype = {
x: 0,
y: 0,
enabled: true,
handleEvent: function (e) {
var that = this;
switch (e.type) {
case START_EVENT:
that.touchStart(e);
break;
case MOVE_EVENT:
that.touchMove(e);
break;
case END_EVENT:
that.touchEnd(e);
break;
case 'webkitTransitionEnd':
that.transitionEnd();
break;
case 'orientationchange':
case 'resize':
that.refresh();
break;
case 'DOMSubtreeModified':
that.onDOMModified(e);
break;
}
},
onDOMModified: function (e) {
var that = this;
// (Hopefully) execute onDOMModified only once
if (e.target.parentNode != that.element) {
return;
}
setTimeout(function () { that.refresh(); }, 0);
if (that.options.topOnDOMChanges && (that.x!=0 || that.y!=0)) {
that.scrollTo(0,0,'0');
}
},
refresh: function () {
var that = this,
resetX = that.x, resetY = that.y,
snap;
that.scrollWidth = that.wrapper.clientWidth;
that.scrollHeight = that.wrapper.clientHeight;
that.scrollerWidth = that.element.offsetWidth;
that.scrollerHeight = that.element.offsetHeight;
that.maxScrollX = that.scrollWidth - that.scrollerWidth;
that.maxScrollY = that.scrollHeight - that.scrollerHeight;
that.directionX = 0;
that.directionY = 0;
if (that.scrollX) {
if (that.maxScrollX >= 0) {
resetX = 0;
} else if (that.x < that.maxScrollX) {
resetX = that.maxScrollX;
}
}
if (that.scrollY) {
if (that.maxScrollY >= 0) {
resetY = 0;
} else if (that.y < that.maxScrollY) {
resetY = that.maxScrollY;
}
}
// Snap
if (that.options.snap) {
that.maxPageX = -Math.floor(that.maxScrollX/that.scrollWidth);
that.maxPageY = -Math.floor(that.maxScrollY/that.scrollHeight);
snap = that.snap(resetX, resetY);
resetX = snap.x;
resetY = snap.y;
}
if (resetX!=that.x || resetY!=that.y) {
that.setTransitionTime('0');
that.setPosition(resetX, resetY, true);
}
that.scrollX = that.scrollerWidth > that.scrollWidth;
that.scrollY = !that.options.bounceLock && !that.scrollX || that.scrollerHeight > that.scrollHeight;
// Update horizontal scrollbar
if (that.options.hScrollbar && that.scrollX) {
that.scrollBarX = that.scrollBarX || new scrollbar('horizontal', that.wrapper, that.options.fadeScrollbar, that.options.shrinkScrollbar, that.options.scrollbarColor);
that.scrollBarX.init(that.scrollWidth, that.scrollerWidth);
} else if (that.scrollBarX) {
that.scrollBarX = that.scrollBarX.remove();
}
// Update vertical scrollbar
if (that.options.vScrollbar && that.scrollY && that.scrollerHeight > that.scrollHeight) {
that.scrollBarY = that.scrollBarY || new scrollbar('vertical', that.wrapper, that.options.fadeScrollbar, that.options.shrinkScrollbar, that.options.scrollbarColor);
that.scrollBarY.init(that.scrollHeight, that.scrollerHeight);
} else if (that.scrollBarY) {
that.scrollBarY = that.scrollBarY.remove();
}
},
setPosition: function (x, y, hideScrollBars) {
var that = this;
that.x = x;
that.y = y;
that.element.style.webkitTransform = translateOpen + that.x + 'px,' + that.y + 'px' + translateClose;
// Move the scrollbars
if (!hideScrollBars) {
if (that.scrollBarX) {
that.scrollBarX.setPosition(that.x);
}
if (that.scrollBarY) {
that.scrollBarY.setPosition(that.y);
}
}
},
setTransitionTime: function(time) {
var that = this;
time = time || '0';
that.element.style.webkitTransitionDuration = time;
if (that.scrollBarX) {
that.scrollBarX.bar.style.webkitTransitionDuration = time;
that.scrollBarX.wrapper.style.webkitTransitionDuration = has3d && that.options.fadeScrollbar ? '300ms' : '0';
}
if (that.scrollBarY) {
that.scrollBarY.bar.style.webkitTransitionDuration = time;
that.scrollBarY.wrapper.style.webkitTransitionDuration = has3d && that.options.fadeScrollbar ? '300ms' : '0';
}
},
touchStart: function(e) {
var that = this,
matrix;
if (!that.enabled) {
return;
}
e.preventDefault();
e.stopPropagation();
that.scrolling = true; // This is probably not needed, but may be useful if iScroll is used in conjuction with other frameworks
that.moved = false;
that.distX = 0;
that.distY = 0;
that.setTransitionTime('0');
// Check if the scroller is really where it should be
if (that.options.momentum || that.options.snap) {
matrix = new WebKitCSSMatrix(window.getComputedStyle(that.element).webkitTransform);
if (matrix.e != that.x || matrix.f != that.y) {
document.removeEventListener('webkitTransitionEnd', that, false);
that.setPosition(matrix.e, matrix.f);
that.moved = true;
}
}
that.touchStartX = isTouch ? e.changedTouches[0].pageX : e.pageX;
that.scrollStartX = that.x;
that.touchStartY = isTouch ? e.changedTouches[0].pageY : e.pageY;
that.scrollStartY = that.y;
that.scrollStartTime = e.timeStamp;
that.directionX = 0;
that.directionY = 0;
},
touchMove: function(e) {
if (!this.scrolling) {
return;
}
var that = this,
pageX = isTouch ? e.changedTouches[0].pageX : e.pageX,
pageY = isTouch ? e.changedTouches[0].pageY : e.pageY,
leftDelta = that.scrollX ? pageX - that.touchStartX : 0,
topDelta = that.scrollY ? pageY - that.touchStartY : 0,
newX = that.x + leftDelta,
newY = that.y + topDelta;
//e.preventDefault();
e.stopPropagation(); // Stopping propagation just saves some cpu cycles (I presume)
that.touchStartX = pageX;
that.touchStartY = pageY;
// Slow down if outside of the boundaries
if (newX >= 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? Math.round(that.x + leftDelta / 3) : (newX >= 0 || that.maxScrollX>=0) ? 0 : that.maxScrollX;
}
if (newY >= 0 || newY < that.maxScrollY) {
newY = that.options.bounce ? Math.round(that.y + topDelta / 3) : (newY >= 0 || that.maxScrollY>=0) ? 0 : that.maxScrollY;
}
if (that.distX + that.distY > 5) { // 5 pixels threshold
// Lock scroll direction
if (that.distX-3 > that.distY) {
newY = that.y;
topDelta = 0;
} else if (that.distY-3 > that.distX) {
newX = that.x;
leftDelta = 0;
}
that.setPosition(newX, newY);
that.moved = true;
that.directionX = leftDelta > 0 ? -1 : 1;
that.directionY = topDelta > 0 ? -1 : 1;
} else {
that.distX+= Math.abs(leftDelta);
that.distY+= Math.abs(topDelta);
// that.dist+= Math.abs(leftDelta) + Math.abs(topDelta);
}
},
touchEnd: function(e) {
if (!this.scrolling) {
return;
}
var that = this,
time = e.timeStamp - that.scrollStartTime,
point = isTouch ? e.changedTouches[0] : e,
target, ev,
momentumX, momentumY,
newDuration = 0,
newPositionX = that.x, newPositionY = that.y,
snap;
that.scrolling = false;
if (!that.moved) {
that.resetPosition();
if (isTouch) {
// Find the last touched element
target = point.target;
while (target.nodeType != 1) {
target = target.parentNode;
}
// Create the fake event
ev = document.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);
}
return;
}
if (!that.options.snap && time > 250) { // Prevent slingshot effect
that.resetPosition();
return;
}
if (that.options.momentum) {
momentumX = that.scrollX === true
? that.momentum(that.x - that.scrollStartX,
time,
that.options.bounce ? -that.x + that.scrollWidth/5 : -that.x,
that.options.bounce ? that.x + that.scrollerWidth - that.scrollWidth + that.scrollWidth/5 : that.x + that.scrollerWidth - that.scrollWidth)
: { dist: 0, time: 0 };
momentumY = that.scrollY === true
? that.momentum(that.y - that.scrollStartY,
time,
that.options.bounce ? -that.y + that.scrollHeight/5 : -that.y,
that.options.bounce ? (that.maxScrollY < 0 ? that.y + that.scrollerHeight - that.scrollHeight : 0) + that.scrollHeight/5 : that.y + that.scrollerHeight - that.scrollHeight)
: { dist: 0, time: 0 };
newDuration = Math.max(Math.max(momentumX.time, momentumY.time), 1); // The minimum animation length must be 1ms
newPositionX = that.x + momentumX.dist;
newPositionY = that.y + momentumY.dist;
}
if (that.options.snap) {
snap = that.snap(newPositionX, newPositionY);
newPositionX = snap.x;
newPositionY = snap.y;
newDuration = Math.max(snap.time, newDuration);
}
that.scrollTo(newPositionX, newPositionY, newDuration + 'ms');
},
transitionEnd: function () {
var that = this;
document.removeEventListener('webkitTransitionEnd', that, false);
that.resetPosition();
},
resetPosition: function () {
var that = this,
resetX = that.x,
resetY = that.y;
if (that.x >= 0) {
resetX = 0;
} else if (that.x < that.maxScrollX) {
resetX = that.maxScrollX;
}
if (that.y >= 0 || that.maxScrollY > 0) {
resetY = 0;
} else if (that.y < that.maxScrollY) {
resetY = that.maxScrollY;
}
if (resetX != that.x || resetY != that.y) {
that.scrollTo(resetX, resetY);
} else {
if (that.moved) {
that.onScrollEnd(); // Execute custom code on scroll end
that.moved = false;
}
// Hide the scrollbars
if (that.scrollBarX) {
that.scrollBarX.hide();
}
if (that.scrollBarY) {
that.scrollBarY.hide();
}
}
},
snap: function (x, y) {
var that = this, time;
if (that.directionX > 0) {
x = Math.floor(x/that.scrollWidth);
} else if (that.directionX < 0) {
x = Math.ceil(x/that.scrollWidth);
} else {
x = Math.round(x/that.scrollWidth);
}
that.pageX = -x;
x = x * that.scrollWidth;
if (x > 0) {
x = that.pageX = 0;
} else if (x < that.maxScrollX) {
that.pageX = that.maxPageX;
x = that.maxScrollX;
}
if (that.directionY > 0) {
y = Math.floor(y/that.scrollHeight);
} else if (that.directionY < 0) {
y = Math.ceil(y/that.scrollHeight);
} else {
y = Math.round(y/that.scrollHeight);
}
that.pageY = -y;
y = y * that.scrollHeight;
if (y > 0) {
y = that.pageY = 0;
} else if (y < that.maxScrollY) {
that.pageY = that.maxPageY;
y = that.maxScrollY;
}
// Snap with constant speed (proportional duration)
time = Math.round(Math.max(
Math.abs(that.x - x) / that.scrollWidth * 500,
Math.abs(that.y - y) / that.scrollHeight * 500
));
return { x: x, y: y, time: time };
},
scrollTo: function (destX, destY, runtime) {
var that = this;
if (that.x == destX && that.y == destY) {
that.resetPosition();
return;
}
that.moved = true;
that.setTransitionTime(runtime || '350ms');
that.setPosition(destX, destY);
if (runtime==='0' || runtime=='0s' || runtime=='0ms') {
that.resetPosition();
} else {
document.addEventListener('webkitTransitionEnd', that, false); // At the end of the transition check if we are still inside of the boundaries
}
},
scrollToPage: function (pageX, pageY, runtime) {
var that = this, snap;
if (!that.options.snap) {
that.pageX = -Math.round(that.x / that.scrollWidth);
that.pageY = -Math.round(that.y / that.scrollHeight);
}
if (pageX == 'next') {
pageX = ++that.pageX;
} else if (pageX == 'prev') {
pageX = --that.pageX;
}
if (pageY == 'next') {
pageY = ++that.pageY;
} else if (pageY == 'prev') {
pageY = --that.pageY;
}
pageX = -pageX*that.scrollWidth;
pageY = -pageY*that.scrollHeight;
snap = that.snap(pageX, pageY);
pageX = snap.x;
pageY = snap.y;
that.scrollTo(pageX, pageY, runtime || '500ms');
},
scrollToElement: function (el, runtime) {
el = typeof el == 'object' ? el : this.element.querySelector(el);
if (!el) {
return;
}
var that = this,
x = that.scrollX ? -el.offsetLeft : 0,
y = that.scrollY ? -el.offsetTop : 0;
if (x >= 0) {
x = 0;
} else if (x < that.maxScrollX) {
x = that.maxScrollX;
}
if (y >= 0) {
y = 0;
} else if (y < that.maxScrollY) {
y = that.maxScrollY;
}
that.scrollTo(x, y, runtime);
},
momentum: function (dist, time, maxDistUpper, maxDistLower) {
var friction = 2.5,
deceleration = 1.2,
speed = Math.abs(dist) / time * 1000,
newDist = speed * speed / friction / 1000,
newTime = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
speed = speed * maxDistUpper / newDist / friction;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
speed = speed * maxDistLower / newDist / friction;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: Math.round(newDist), time: Math.round(newTime) };
},
destroy: function (full) {
var that = this;
window.removeEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', that, false);
that.element.removeEventListener(START_EVENT, that, false);
that.element.removeEventListener(MOVE_EVENT, that, false);
that.element.removeEventListener(END_EVENT, that, false);
document.removeEventListener('webkitTransitionEnd', that, false);
if (that.options.checkDOMChanges) {
that.element.removeEventListener('DOMSubtreeModified', that, false);
}
if (that.scrollBarX) {
that.scrollBarX = that.scrollBarX.remove();
}
if (that.scrollBarY) {
that.scrollBarY = that.scrollBarY.remove();
}
if (full) {
that.wrapper.parentNode.removeChild(that.wrapper);
}
return null;
}
};
function scrollbar (dir, wrapper, fade, shrink, color) {
var that = this,
doc = document;
that.dir = dir;
that.fade = fade;
that.shrink = shrink;
that.uid = ++uid;
// Create main scrollbar
that.bar = doc.createElement('div');
that.bar.style.cssText = 'position:absolute;top:0;left:0;-webkit-transition-timing-function:cubic-bezier(0,0,0.25,1);pointer-events:none;-webkit-transition-duration:0;-webkit-transition-delay:0;-webkit-transition-property:-webkit-transform;z-index:10;background:' + color + ';' +
'-webkit-transform:' + translateOpen + '0,0' + translateClose + ';' +
(dir == 'horizontal' ? '-webkit-border-radius:3px 2px;min-width:6px;min-height:5px' : '-webkit-border-radius:2px 3px;min-width:5px;min-height:6px');
// Create scrollbar wrapper
that.wrapper = doc.createElement('div');
that.wrapper.style.cssText = '-webkit-mask:-webkit-canvas(scrollbar' + that.uid + that.dir + ');position:absolute;z-index:10;pointer-events:none;overflow:hidden;opacity:0;-webkit-transition-duration:' + (fade ? '300ms' : '0') + ';-webkit-transition-delay:0;-webkit-transition-property:opacity;' +
(that.dir == 'horizontal' ? 'bottom:2px;left:2px;right:7px;height:5px' : 'top:2px;right:2px;bottom:7px;width:5px;');
// Add scrollbar to the DOM
that.wrapper.appendChild(that.bar);
wrapper.appendChild(that.wrapper);
}
scrollbar.prototype = {
init: function (scroll, size) {
var that = this,
doc = document,
pi = Math.PI,
ctx;
// Create scrollbar mask
if (that.dir == 'horizontal') {
if (that.maxSize != that.wrapper.offsetWidth) {
that.maxSize = that.wrapper.offsetWidth;
ctx = doc.getCSSCanvasContext("2d", "scrollbar" + that.uid + that.dir, that.maxSize, 5);
ctx.fillStyle = "rgb(0,0,0)";
ctx.beginPath();
ctx.arc(2.5, 2.5, 2.5, pi/2, -pi/2, false);
ctx.lineTo(that.maxSize-2.5, 0);
ctx.arc(that.maxSize-2.5, 2.5, 2.5, -pi/2, pi/2, false);
ctx.closePath();
ctx.fill();
}
} else {
if (that.maxSize != that.wrapper.offsetHeight) {
that.maxSize = that.wrapper.offsetHeight;
ctx = doc.getCSSCanvasContext("2d", "scrollbar" + that.uid + that.dir, 5, that.maxSize);
ctx.fillStyle = "rgb(0,0,0)";
ctx.beginPath();
ctx.arc(2.5, 2.5, 2.5, pi, 0, false);
ctx.lineTo(5, that.maxSize-2.5);
ctx.arc(2.5, that.maxSize-2.5, 2.5, 0, pi, false);
ctx.closePath();
ctx.fill();
}
}
that.size = Math.max(Math.round(that.maxSize * that.maxSize / size), 6);
that.maxScroll = that.maxSize - that.size;
that.toWrapperProp = that.maxScroll / (scroll - size);
that.bar.style[that.dir == 'horizontal' ? 'width' : 'height'] = that.size + 'px';
},
setPosition: function (pos) {
var that = this;
if (that.wrapper.style.opacity != '1') {
that.show();
}
pos = Math.round(that.toWrapperProp * pos);
if (pos < 0) {
pos = that.shrink ? pos + pos*3 : 0;
if (that.size + pos < 7) {
pos = -that.size + 6;
}
} else if (pos > that.maxScroll) {
pos = that.shrink ? pos + (pos-that.maxScroll)*3 : that.maxScroll;
if (that.size + that.maxScroll - pos < 7) {
pos = that.size + that.maxScroll - 6;
}
}
pos = that.dir == 'horizontal'
? translateOpen + pos + 'px,0' + translateClose
: translateOpen + '0,' + pos + 'px' + translateClose;
that.bar.style.webkitTransform = pos;
},
show: function () {
if (has3d) {
this.wrapper.style.webkitTransitionDelay = '0';
}
this.wrapper.style.opacity = '1';
},
hide: function () {
if (has3d) {
this.wrapper.style.webkitTransitionDelay = '350ms';
}
this.wrapper.style.opacity = '0';
},
remove: function () {
this.wrapper.parentNode.removeChild(this.wrapper);
return null;
}
};
// Is translate3d compatible?
var has3d = ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix()),
// Device sniffing
isIthing = (/iphone|ipad/gi).test(navigator.appVersion),
isTouch = ('ontouchstart' in window),
// Event sniffing
START_EVENT = isTouch ? 'touchstart' : 'mousedown',
MOVE_EVENT = isTouch ? 'touchmove' : 'mousemove',
END_EVENT = isTouch ? 'touchend' : 'mouseup',
// Translate3d helper
translateOpen = 'translate' + (has3d ? '3d(' : '('),
translateClose = has3d ? ',0)' : ')',
// Unique ID
uid = 0;
// Expose iScroll to the world
window.iScroll = iScroll;
})(); | JavaScript |
/*
* mopSlider 2.5.1
* By Hiroki Miura (http://www.mopstudio.jp)
* Copyright (c) 2009 mopStudio
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
* May 1, 2010
*/
var autoS=[],indiS=[],mopSldWS=[],intervalS=[],itemMgnS=[],moveS=[];
var animS=[],preTurnS=[],turnS=[],nextMovS=[],nextMovBkS=[],nextNumS=[],nextNumBkS=[];
var sclNumS=[],sldNumS=[];
var posiS=[],posiBkS=[];
var chkNumS=[],chkNumBkS=[];
var mpSldMoS=[];
var boxWS=[],sldWS=[],btnWS=[];
var wchDgS=[];
var btnPastS=[],boxPastS=[],btnPosiS=[],boxPosiS=[],btnMvNumSS=[],boxMvNumSS=[];
var finalCountS=[];
var mpSldCount=0,mpSldNoS=[];
var itemNumS=[];
var sclMaxS=[];
jQuery.fn.extend({
mopSlider:function(stt){
var ua=navigator.userAgent,browser,os,ie67=false;
var px="px"
var btnPosi,boxPosi,btnPast,boxPast,wchDg="";
var btnMvNum,btnMoveTo,boxMvNum,boxMoveTo;
var timeCheck1,timeCheck2,dragCheck1,dragCheck2,finalTime1,finalTime2;
var mpSldNm;
var sclMax,sclNum,caseW,itemNum,sldNum,chkNum,movNum;
var mpSldMo;
var boxW,itemMgnAll;
var finalCount=0;
var indication=stt.indi
var mopSldW=stt.w;
var mopSldH=stt.h;
var sldW=stt.sldW;
var btnW=stt.btnW;
var itemMgn=stt.itemMgn;
var shuffle=stt.shuffle;
var mpSldNo=stt.no;
var mopSldTyp=stt.type;
var auto=stt.auto;
var move=stt.move;
var interval=stt.interval;
var anim,turn="go",preTurn="go";
var posi,posiBk;
var nextMov=[],nextMovBk=[];
var nextNum=0,nextNumBk=0;
var sclW=0,sclWbk=0;
var imagesPath = stt.imagesPath;
/*path to image*/
var btnLeft=new Image();
var btnLeftF=new Image();
var btnRight=new Image();
var btnRightF=new Image();
var btnCenter=new Image();
var btnChange=new Image();
var btnChangeNn=new Image();
var btnChangeF=new Image();
var bkImg=new Image();
var sldcLeftImg=new Image();
var sldcRightImg=new Image();
var sldBkLeft=new Image();
var sldBkCenter=new Image();
var sldBkRight=new Image();
var mopSldSrc=function(mopSldTyp){
if(mopSldTyp=="paper"){
btnLeft.src=imagesPath+"sliderBtnLtW.png";
btnLeftF.src=imagesPath+"sliderBtnLtW_f.png";
btnRight.src=imagesPath+"sliderBtnRtW.png";
btnRightF.src=imagesPath+"sliderBtnRtW_f.png";
btnCenter.src=imagesPath+"sliderBtnW.png";
btnChange.src=imagesPath+"sliderBkRtRtW.png";
btnChangeNn.src=imagesPath+"sliderBkRtRtNnW.png";
btnChangeF.src=imagesPath+"sliderBkRtRtW_f.png";
bkImg.src=imagesPath+"paperBk.gif";
sldcLeftImg.src=imagesPath+"sliderBkLtLtW.png";
sldBkLeft.src=imagesPath+"sliderBkLtW.png";
sldBkCenter.src=imagesPath+"sliderBkW.png";
sldBkRight.src=imagesPath+"sliderBkRtW.png";
}else if(mopSldTyp=="black"){
btnLeft.src=imagesPath+"sliderBtnLt.png";
btnLeftF.src=imagesPath+"sliderBtnLt_f.png";
btnRight.src=imagesPath+"sliderBtnRt.png";
btnRightF.src=imagesPath+"sliderBtnRt_f.png";
btnCenter.src=imagesPath+"sliderBtn.png";
btnChange.src=imagesPath+"sliderBkLtLt.png";
btnChangeNn.src=imagesPath+"sliderBkRtRtNn.png";
btnChangeF.src=imagesPath+"sliderBkRtRt_f.png";
bkImg.src=imagesPath+"monoBk.gif";
sldcLeftImg.src=imagesPath+"sliderBkLtLt.png";
sldBkLeft.src=imagesPath+"sliderBkLt.png";
sldBkCenter.src=imagesPath+"sliderBk.png";
sldBkRight.src=imagesPath+"sliderBkRt.png";
}
}
mopSldSrc(mopSldTyp);
if(stt.auto==null){auto='n'};
if(stt.move==null){move=1000};
if(stt.interval==null){interval=2000};
if(stt.itemMgn==null){itemMgn=20};
if(stt.shuffle==null){shuffle='n'};
mpSldCount+=1;
var num=mpSldCount;
mpSldNo=num;
mpSldNoS.push(mpSldNo);
mpSldNm="#mopSlider"+mpSldNo;
var noSharp=mpSldNm.split("#")[1];
$(mpSldNm).hide();
var arr=jQuery.makeArray($(this).children());
Array.prototype.shuffle = function() {
var i = this.length;
while(i){
var j = Math.floor(Math.random()*i);
var t = this[--i];
this[i] = this[j];
this[j] = t;
};
return this;
};
if((shuffle=='y')||(shuffle==1)){
arr.shuffle();
$(arr).appendTo(this);
};
if(ua.indexOf("Mac",0)>=0){os="mac";}else if(ua.indexOf("Win",0)>=0){os="win";};
if(ua.indexOf("MSIE 6")>-1){browser="ie6";};
if(ua.indexOf("MSIE 7")>-1){browser="ie7";};
if((browser=="ie6")||(browser=="ie7")){ie67=true;};
$(this).css({position:"absolute",overflow: "hidden",left: "0px",display: "block"});
itemNum=$(this).children().length;
itemNumS.push(itemNum);
var allW=0;
var num=0;
for (i=1; i<(itemNum+1); i++){
var itemW=eval($(this).children().eq(num).css("width").split("px")[0]);
nextMov.push(itemW);
var itemH=eval($(this).children().eq(num).css("height").split("px")[0]);
var mgn=(mopSldH-itemH)/2;
$(this).children().eq(num).css({marginTop:mgn+px});
num+=1;
allW+=itemW;
};
var lengthNum=nextMov.length;
for (i=1; i<(nextMov.length); i++){
var pushW=nextMov[lengthNum-1];
nextMovBk.push(pushW);
lengthNum-=1;
};
itemMgnAll=itemMgn*itemNum;
boxW=allW+itemMgnAll+itemMgn;
$(this).wrap('<div id="mopSlider"><div id="'+noSharp+'"><div class="holder"></div></div></div>');
$(this).parent().after(
'<div class="sliderCase">'+
'<div class="sliderCaseLeft"></div>'+
'<div class="sliderCaseRight"></div>'+
'<div class="slider">'+
'<div class="sldLeft"></div>'+
'<div class="sldCenter"></div>'+
'<div class="sldRight"></div>'+
'<div class="sliderBtn">'+
'<div class="sldBtnLeft"></div>'+
'<div class="sldBtnCenter"><div class="indi"></div></div>'+
'<div class="sldBtnRight"></div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="leftTop"><div class="leftTopIn"></div></div>'+
'<div class="rightTop"><div class="rightTopIn"></div></div>'+
'<div class="leftBottom"><div class="leftBottomIn"></div></div>'+
'<div class="rightBottom"><div class="rightBottomIn"></div></div>'+
'<div class="logo"><div class="logoIn"></div></div>'
);
$(mpSldNm+" .sliderCase").css({height:"11px",position:"relative",top:"0px"});
$(mpSldNm+" .sliderCaseLeft").css({height:"11px",width:"12px",position:"absolute",top:"0px",left:"0px",backgroundImage:"url("+sldcLeftImg.src+")",backgroundRepeat:"no-repeat"});
if((auto=="nn")||(auto=="yn")){
$(mpSldNm+" .sliderCaseRight").css({height:"11px",width:"15px",position:"absolute",top:"0px",right:"0px",backgroundImage:"url("+btnChangeNn.src+")",cursor:"",backgroundRepeat:"no-repeat"});
}else{
$(mpSldNm+" .sliderCaseRight").css({height:"11px",width:"15px",position:"absolute",top:"0px",right:"0px",backgroundImage:"url("+btnChange.src+")",cursor:"pointer",backgroundRepeat:"no-repeat"});
}
$(mpSldNm+" .slider").css({height:"11px",position:"relative",top:"0px",left:"12px"});
$(mpSldNm+" .sldLeft").css({left:"0px",position:"absolute",height:"11px",width:"20px",backgroundImage:"url("+sldBkLeft.src+")",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .sldCenter").css({left:"10px",width:sldW-20+px,position:"absolute",height:"11px",backgroundImage:"url("+sldBkCenter.src+")",backgroundRepeat:"repeat-x"});
$(mpSldNm+" .sldRight").css({right:"0px",position:"absolute",height:"11px",width:"10px",backgroundImage:"url("+sldBkRight.src+")",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .sliderBtn").css({position:"absolute",height:"11px",left:"0px",cursor:"default"});
$(mpSldNm+" .sldBtnLeft").css({left:"0px",position:"absolute",height:"11px",width:"10px",backgroundImage:"url("+btnLeft.src+")",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .sldBtnCenter").css({left:"10px",width:btnW-20+px,position:"absolute",height:"11px",backgroundImage:"url("+btnCenter.src+")",backgroundRepeat:"repeat-x"});
$(mpSldNm+" .sldBtnRight").css({right:"0px",position:"absolute",height:"11px",width:"10px",backgroundImage:"url("+btnRight.src+")",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .indi").css({paddingTop:"5px",fontSize: "10px",textAlign:"center",fontFamily:"Arial, Helvetica, sans-serif",letterSpacing:"0.05em",color:"#2b313e"});
$(mpSldNm).css({width:mopSldW+px,height:mopSldH+11+px});
$(mpSldNm).css({position:"relative",overflow:"hidden",margin:"0 auto 0 auto",backgroundImage:"url("+bkImg.src+")"});
if(mopSldTyp=="black"){
$(mpSldNm).css({backgroundColor:"#484848",backgroundRepeat:"repeat-x",backgroundPosition:"bottom"});
}
$(mpSldNm+" .leftTop").css({height:"10px",width:"10px",position:"absolute",top:"0px",left:"0px"});
$(mpSldNm+" .leftTopIn").css({height:"10px",width:"10px",backgroundImage:"url(mopSlider/sliderCrnLtTp.png)",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .rightTop").css({height:"10px",width:"10px",position:"absolute",top:"0px",right:"0px"});
$(mpSldNm+" .rightTopIn").css({height:"10px",width:"10px",backgroundImage:"url(mopSlider/sliderCrnRtTp.png)",backgroundRepeat:"no-repeat"});
$(mpSldNm+" .leftBottom").css({height:"10px",width:"10px",position:"absolute",bottom:"0px",left:"0px"});
$(mpSldNm+" .leftBottomIn").css({height:"10px",width:"10px",backgroundImage:"url(mopSlider/sliderCrnLtBtm.png)",backgroundRepeat:"no-repeat",backgroundPosition:"bottom"});
$(mpSldNm+" .rightBottom").css({height:"10px",width:"10px",position:"absolute",bottom:"0px",right:"0px"});
$(mpSldNm+" .rightBottomIn").css({height:"10px",width:"10px",backgroundImage:"url(mopSlider/sliderCrnRtBtm.png)",backgroundRepeat:"no-repeat",backgroundPosition:"bottom"});
$(mpSldNm+" .logo").css({height:"50px",width:"80px",position:"absolute",top:"0px",left:"0px"});
$(mpSldNm+" .logoIn").css({height:"50px",width:"80px",backgroundImage:"url(mopSlider/logo.png)",backgroundRepeat:"no-repeat"});
if(os=="mac"){$(mpSldNm+" .indi").css({letterSpacing:"0.1em"})};/*foe mac*/
sclMax=boxW-mopSldW;
sclNum=sclMax*0.01;/*0 to100 (box)*/
sldNum=(sldW-btnW)*0.01;/*0 to100 (slider)*/
var lastLength,lastLengthBk;
for (i=1; i<(nextMov.length+1); i++){
var lenchCheck=i-1;
sclW+=nextMov[lenchCheck]+itemMgn;
if(sclW>=sclMax){
lastLength=lenchCheck;
break;
}
}
for (i=1; i<(nextMovBk.length+1); i++){
var lenchCheckBk=i-1;
sclWbk+=nextMovBk[lenchCheckBk]+itemMgn;
if(sclWbk>=sclMax){
lastLengthBk=lenchCheckBk;
break;
}
}
var lastMov=eval(nextMov[lastLength]+itemMgn);
var amari=sclW-sclMax;
chkNum=sclMax-lastMov+amari;
var lastMovBk=eval(nextMovBk[lastLengthBk]+itemMgn);
var amariBk=sclWbk-sclMax;
chkNumBk=lastMovBk-amariBk;
nextMov[lastLength]-=amari;
nextMovBk[lastLengthBk]-=amariBk;
var holderWidth=(mopSldW+sclMax*2);
$(mpSldNm+" .holder").css({width:holderWidth+"px",height:mopSldH+px,position:"relative",left:-(sclMax)+px,cursor:"default"});
$(mpSldNm+" .holder").children().css({width:boxW+px,left:sclMax+px});
$(mpSldNm+" .holder").children().children().css({marginLeft:itemMgn+"px",float:"left",position:"relative"});
$(mpSldNm+" .sliderCase").css({width:sldW+25+px});
var sldCaseW=eval($(mpSldNm+" .sliderCase").css("width").split("px")[0]);
var sliderLeftMgn=(mopSldW-sldCaseW)/2;
$(mpSldNm+" .sliderCase").css({left:sliderLeftMgn+px});
$(mpSldNm+" .slider").css({width:sldW+px});
$(mpSldNm+" .sliderBtn").css({width:btnW+px});
$(this).pngFix();
$(mpSldNm+" .sliderCase,"+mpSldNm+" .leftTop,"+mpSldNm+" .rightTop").pngFix();
$(mpSldNm+" .leftBottom,"+mpSldNm+" .rightBottom,"+mpSldNm+" .logo").pngFix();
$(mpSldNm+" .indi").html(indication);
if(auto=='y'){anim="y";}else if(auto=='n'){anim="n";}else if(auto=='nn'){anim="nn";}else if(auto=='yn'){anim="y";}
animS.push(anim);
autoS.push(auto);
indiS.push(indication);
nextMovS.push(nextMov); nextMovBkS.push(nextMovBk);
preTurnS.push(preTurn); turnS.push(turn);
sclNumS.push(sclNum); sldNumS.push(sldNum);
chkNumS.push(chkNum); chkNumBkS.push(chkNumBk);
mpSldMoS.push(mpSldMo);
boxWS.push(boxW); mopSldWS.push(mopSldW);
nextNumS.push(nextNum); nextNumBkS.push(nextNumBk);
sldWS.push(sldW); btnWS.push(btnW);
wchDgS.push(wchDg);
btnPastS.push(btnPast); boxPastS.push(boxPast);
btnPosiS.push(btnPosi); boxPosiS.push(boxPosi);
finalCountS.push(finalCount);
btnMvNumSS.push(finalCount); boxMvNumSS.push(finalCount);
intervalS.push(interval);
itemMgnS.push(itemMgn);
sclMaxS.push(sclMax);
moveS.push(move);
$(mpSldNm).show();
$(mpSldNm+" .sliderBtn").draggable({
axis:"x",
containment:"parent",
start:function(){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
wchDgS[j]="btn";
}
}
btnMvNum=0;
dragCheck1=setInterval("mpSldF.dragCheckItv('"+mpSldNo+"','"+mpSldNm+"')",20);
timeCheck1=setInterval("mpSldF.timeCheckItv('"+mpSldNo+"','"+mpSldNm+"')",50);
},
drag:function(){},
stop:function(){
clearInterval(dragCheck1);
mpSldF.finalMove(mpSldNo,mpSldNm);
}
});
$(mpSldNm+" .holder").children().draggable({
axis:"x",
containment:"parent",
start:function(){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
wchDgS[j]="holder";
}
}
boxMvNum=0;
dragCheck1=setInterval("mpSldF.dragCheckItv('"+mpSldNo+"','"+mpSldNm+"')",20);
timeCheck1=setInterval("mpSldF.timeCheckItv('"+mpSldNo+"','"+mpSldNm+"')",50);
},
drag:function(){},
stop:function(){
clearInterval(dragCheck1);
mpSldF.finalMove(mpSldNo,mpSldNm);
}
});
$("#mopSlider .sliderBtn").mousedown(
function(){
clearInterval(timeCheck1);
clearInterval(finalTime1);
}
);
$("#mopSlider .holder").children().mousedown(
function(){
clearInterval(timeCheck1);
clearInterval(finalTime1);
}
);
var movCheck=function(mpSldNo,mpSldNm){
var j=mpSldNo-1;
sldNum=sldNumS[j];
var boxPosiPx=$(mpSldNm+" .holder").children().css("left");
boxPosi=eval(boxPosiPx.split("px")[0]);
var boxPosi0=-(boxPosi-sclMaxS[j]);
var boxNum=-(boxPosi0/sclNumS[j]);
if(((boxPosi0)>(chkNumS[j]))&&(preTurnS[j]=="go")){
preTurnS[j]="bk";
}else if(((boxPosi0)<(chkNumBkS[j]))&&(preTurnS[j]=="bk")){
preTurnS[j]="go";
};
$(mpSldNm+" .sliderBtn").css({left:-(boxNum*sldNumS[j])+px});
}
var turnCheck=function(mpSldNo){
var j=mpSldNo-1;
if(preTurnS[j]=="bk"){
turnS[j]="bk";
mpSldF.goInit(mpSldNo);
}else if(preTurnS[j]=="go"){
turnS[j]="go";
mpSldF.bkInit(mpSldNo);
};
}
mpSldF={
dragCheckItv:function(mpSldNo,mpSldNm){
var sldNum100;
var boxPosi0;
var boxNum;
var j=mpSldNo-1;
btnPosiS[j]=eval($(mpSldNm+" .sliderBtn").css("left").split("px")[0]);
boxPosiS[j]=eval($(mpSldNm+" .holder").children().css("left").split("px")[0]);
sldNum100=btnPosiS[j]/sldNumS[j];
boxPosi0=-(boxPosiS[j]-sclMaxS[j]);
boxNum=-(boxPosi0/sclNumS[j]);
if(wchDgS[j]=="btn"){
$(mpSldNm+" .holder").children().css({left:Math.floor(-(sldNum100*sclNumS[j])+sclMaxS[j])+px});
}else if(wchDgS[j]=="holder"){
$(mpSldNm+" .sliderBtn").css({left:-(boxNum*sldNumS[j])+px});
};
$(".mopCheck").html(boxNum+" "+sldNum100);
},
move:function(mpSldNo,mpSldNm){
var j=mpSldNo-1;
if(itemNumS[j]!=1){
turnCheck(mpSldNo);
}
if(animS[j]=="y"){
if(turnS[j]=="go"){
if(itemNumS[j]==1){
turnS[j]="bk";
}
$(mpSldNm+" .holder").children().animate({left:-posiS[j]+sclMaxS[j]+px},
{duration:moveS[j],easing:'swing',
step:function(){movCheck(mpSldNo,mpSldNm)},
complete:function(){
if(itemNumS[j]!=1){
nextNumS[j]+=1;
posiS[j]+=((nextMovS[j][nextNumS[j]])+itemMgnS[j]);
}
}
}
);
}else if(turnS[j]=="bk"){
if(itemNumS[j]==1){
turnS[j]="go";
}
$(mpSldNm+" .holder").children().animate({left:posiBkS[j]+px},
{duration:moveS[j],easing:'swing',
step:function(){movCheck(mpSldNo,mpSldNm)},
complete:function(){
if(itemNumS[j]!=1){
nextNumBkS[j]+=1;
posiBkS[j]+=((nextMovBkS[j][nextNumBkS[j]])+itemMgnS[j]);
}
}
}
);
}
}
mpSldMoS[j]=setTimeout("mpSldF.move('"+mpSldNo+"','"+mpSldNm+"')",intervalS[j]+moveS[j]);
},
goInit:function(mpSldNo){
var j=mpSldNo-1;
nextNumS[j]=0;
posiS[j]=(nextMovS[j][nextNumS[j]]+itemMgnS[j]);
},
bkInit:function(mpSldNo){
var j=mpSldNo-1;
nextNumBkS[j]=0;
if(itemNumS[j]!=1){
posiBkS[j]=(nextMovBkS[j][nextNumBkS[j]]+itemMgnS[j]);
}else{
posiBkS[j]=(nextMovS[j][nextNumS[j]]+itemMgnS[j]);
}
},
manualAct:function(mpSldNo,mpSldNm,mopSldTyp){
$(mpSldNm+" .holder").children().stop();
var j=mpSldNo-1;
clearInterval(mpSldMoS[j]);
animS[j]='n'
$(mpSldNm+" .indi").html(indiS[j]);
if(autoS[j]!='yn'){
mopSldSrc(mopSldTyp);
if(browser!="ie6"){
$(mpSldNm+" .sldBtnLeft").css({backgroundImage:"url("+btnLeft.src+")"});
$(mpSldNm+" .sldBtnRight").css({backgroundImage:"url("+btnRight.src+")"});
$(mpSldNm+" .sliderCaseRight").css({backgroundImage:"url("+btnChange.src+")"});
}
}
$(mpSldNm+" .holder").children().css({cursor:"default"});
},
autoAct:function(mpSldNo,mpSldNm,mopSldTyp,chkNum,chkNumBk){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
sclMax=boxWS[j]-mopSldWS[j];
animS[j]='y';
turnS[j]="go";
clearInterval(mpSldMoS[j]);
}
}
$(mpSldNm+" .holder").children().css({cursor:""});
mpSldF.goInit(mpSldNo);
mpSldF.bkInit(mpSldNo);
mpSldF.auto(mpSldNo,mpSldNm,mopSldTyp);
if(eval($(mpSldNm+" .sliderBtn").css("left").split("px")[0])<10){
moveSS=100;
}else{
moveSS=moveS[j]
}
$(mpSldNm+" .holder").children().animate({left:sclMax+px},
{duration:moveSS,easing:'swing',
step:function(){
movCheck(mpSldNo,mpSldNm,boxW,mopSldW);
},
complete:function(){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
mpSldMoS[j]=setTimeout("mpSldF.move('"+mpSldNo+"','"+mpSldNm+"')",intervalS[j]);
}
}
}
}
);
},
auto:function(mpSldNo,mpSldNm,mopSldTyp){
mopSldSrc(mopSldTyp);
$(mpSldNm+" .indi").html("Auto");
var j=mpSldNo-1;
if(autoS[j]!="yn"){
if(browser!="ie6"){
$(mpSldNm+" .sldBtnLeft").css({backgroundImage:"url("+btnLeftF.src+")"});
$(mpSldNm+" .sldBtnRight").css({backgroundImage:"url("+btnRightF.src+")"});
$(mpSldNm+" .sliderCaseRight").css({backgroundImage:"url("+btnChangeF.src+")"});
}
}
},
timeCheckItv:function(mpSldNo,mpSldNm){
var j=mpSldNo-1;
btnPastS[j]=btnPosiS[j];
boxPastS[j]=boxPosiS[j];
},
finalMove:function(mpSldNo,mpSldNm){
var j=mpSldNo-1;
finalCountS[j]=0;
if((btnPosiS[j]!=undefined)&&(btnPastS[j]!=undefined)){
btnMvNumSS[j]=btnPosiS[j]-btnPastS[j];
boxMvNumSS[j]=boxPosiS[j]-boxPastS[j];
}
finalTime1=setInterval("mpSldF.finalTimeItv('"+mpSldNo+"','"+mpSldNm+"')",50);
},
finalTimeItv:function(mpSldNo,mpSldNm){
var j=mpSldNo-1;
finalCountS[j]+=1;
if(finalCountS[j]==1){
btnMvNum=btnMvNumSS[j];
boxMvNum=boxMvNumSS[j];
mpSldNmTemp=mpSldNm;
}
btnPosiS[j]=eval($(mpSldNmTemp+" .sliderBtn").css("left").split("px")[0]);
boxPosiS[j]=eval($(mpSldNmTemp+" .holder").children().css("left").split("px")[0]);
if(wchDgS[j]=="btn"){
if((btnMvNum<0.1)&&(btnMvNum>-0.1)){
btnMvNum=0;
}else{
if(browser=="ie6"){
btnMvNum=btnMvNum/1.75;
}else{
btnMvNum=btnMvNum/1.5;
}
}
btnMoveTo=btnMvNum+btnPosiS[j];
if(btnMoveTo>(sldWS[j]-btnWS[j])){
btnMoveTo=sldWS[j]-btnWS[j];
}else if(btnMoveTo<0){
btnMoveTo=0;
};
$(mpSldNmTemp+" .sliderBtn").css({left:btnMoveTo+px});
btnPastS[j]=btnMoveTo;
if(btnMvNum==0){
clearInterval(finalTime1);
}
mpSldF.checkFinal(mpSldNo,mpSldNm);
}
else if(wchDgS[j]=="holder"){
if((boxMvNum<1)&&(boxMvNum>-1)){
boxMvNum=0;
}else{
if(browser=="ie6"){
boxMvNum=boxMvNum/1.75;
}else{
boxMvNum=boxMvNum/1.5;
}
}
boxMoveTo=boxMvNum+boxPosiS[j];
if(boxMoveTo>sclMaxS[j]){
boxMoveTo=sclMaxS[j];
}else if(boxMoveTo<0){
boxMoveTo=0;
};
$(mpSldNmTemp+" .holder").children().css({left:boxMoveTo+px});
/*set boxPast*/
boxPastS[j]=boxMoveTo;
if(boxMvNum==0){
clearInterval(finalTime1);
}
mpSldF.checkFinal(mpSldNo,mpSldNm);
}
},
checkFinal:function(mpSldNo,mpSldNm){
var sldNum100;
var boxPosi0;
var boxNum;
var j=mpSldNo-1;
btnPosiS[j]=eval($(mpSldNm+" .sliderBtn").css("left").split("px")[0]);
boxPosiS[j]=eval($(mpSldNm+" .holder").children().css("left").split("px")[0]);
sldNum100=btnPosiS[j]/sldNumS[j];
boxPosi0=-(boxPosiS[j]-sclMaxS[j]);
boxNum=-(boxPosi0/sclNumS[j]);
if(wchDgS[j]=="btn"){
$(mpSldNm+" .holder").children().css({left:Math.floor(-(sldNum100*sclNumS[j])+sclMaxS[j])+px});
}else if(wchDgS[j]=="holder"){
$(mpSldNm+" .sliderBtn").css({left:-(boxNum*sldNumS[j])+px});
};
}
}
/*end mpSldF*/
$(mpSldNm+" .sliderCaseRight").click(
function(){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
if(autoS[j]!="yn"){
if(animS[j]=="y"){
mpSldF.manualAct(mpSldNo,mpSldNm,mopSldTyp);
}else if(animS[j]=="n"){
mpSldF.autoAct(mpSldNo,mpSldNm,mopSldTyp,chkNum,chkNumBk);
clearInterval(mpSldMoS[j]);
}
}
}
}
}
);
var clickToManual=function(){
for (i=1; i<(mpSldNoS.length+1); i++){
var j=i-1;
if(mpSldNo==i){
if(animS[j]=="y"){
mpSldF.manualAct(mpSldNo,mpSldNm,mopSldTyp);
}
}
}
}
$(mpSldNm+" .holder").children().mousedown(function(){clickToManual();});
$(mpSldNm+" .sliderBtn").mousedown(function(){clickToManual();});
animGo=function(mpSldNo,mpSldNm,mopSldTyp){
var j=mpSldNo-1;
if(animS[j]=="y"){
if(animS[j]=="y"){
mpSldF.auto(mpSldNo,mpSldNm,mopSldTyp);
}
mpSldMoS[j]=setTimeout("mpSldF.move('"+mpSldNo+"','"+mpSldNm+"')",intervalS[j]);
}else if(animS[j]=="n"){
mpSldF.manualAct(mpSldNo,mpSldNm,mopSldTyp);
}
}
setTimeout("animGo('"+mpSldNo+"','"+mpSldNm+"','"+mopSldTyp+"')",500);
mpSldF.goInit(mpSldNo);
mpSldF.bkInit(mpSldNo);
}
}); | JavaScript |
/* Categories Panel */
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:148,
currentBottom:0
}
}); | JavaScript |
/**
* --------------------------------------------------------------------
* jQuery-Plugin "pngFix"
* Version: 1.2, 09.03.2009
* by Andreas Eberhard, andreas.eberhard@gmail.com
* http://jquery.andreaseberhard.de/
*
* Copyright (c) 2007 Andreas Eberhard
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Changelog:
* 09.03.2009 Version 1.2
* - Update for jQuery 1.3.x, removed @ from selectors
* 11.09.2007 Version 1.1
* - removed noConflict
* - added png-support for input type=image
* - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
* 31.05.2007 initial Version 1.0
* --------------------------------------------------------------------
* @example $(function(){$(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready
*
* jQuery(function(){jQuery(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready when using noConflict
*
* @example $(function(){$('div.examples').pngFix();});
* @desc Fixes all PNG's within div with class examples
*
* @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
* @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
* --------------------------------------------------------------------
*/
(function($) {
jQuery.fn.pngFix = function(settings) {
// Settings
settings = jQuery.extend({
blankgif: 'pngFix/blank.gif'
}, settings);
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
//fix images with png-source
jQuery(this).find("img[src$=.png]").each(function() {
jQuery(this).attr('width',jQuery(this).width());
jQuery(this).attr('height',jQuery(this).height());
var prevStyle = '';
var strNewHTML = '';
var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
if (this.style.border) {
prevStyle += 'border:'+this.style.border+';';
this.style.border = '';
}
if (this.style.padding) {
prevStyle += 'padding:'+this.style.padding+';';
this.style.padding = '';
}
if (this.style.margin) {
prevStyle += 'margin:'+this.style.margin+';';
this.style.margin = '';
}
var imgStyle = (this.style.cssText);
strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
strNewHTML += imgStyle+'"></span>';
if (prevStyle != ''){
strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
}
jQuery(this).hide();
jQuery(this).after(strNewHTML);
});
// fix css background pngs
jQuery(this).find("*").each(function(){
var bgIMG = jQuery(this).css('background-image');
if(bgIMG.indexOf(".png")!=-1){
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
}
});
//fix input with png-source
jQuery(this).find("input[src$=.png]").each(function() {
var bgIMG = jQuery(this).attr('src');
jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
jQuery(this).attr('src', settings.blankgif)
});
}
return jQuery;
};
})(jQuery);
| JavaScript |
/* Categories Panel */
$("#category").controlSubCategoryNav({
mainNav: "#category-nav",
subNav:"#category-sub-nav",
config:{
showBottom:235,
currentBottom:38
}
}); | JavaScript |
/* Ugame jquery function */
$.fn.flowUp = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "-=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowLeft = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "+=" + $(this).width() * step + "px"
},
duration,
callback
);
}
$.fn.flowDown = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "+=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowRight = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "-=" + $(this).width() * step + "px"
},
duration,
callback
);
}
/* ACTION PANEL */
$.fn.processScrollEventOnActionPanel = function() {
if (!$(this).is(':hidden')) {
$(this).hide();
$(this).flowUp({
step:"1",
duration:"normal"
});
}
}
$.fn.addActionClickHandlerOnActionPanel = function(options) {
var panel = options["panel"];
var panels = options["disablePanels"];
//init position for panel
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal"
});
}
//register Scroll handler for window
/*
$(window).scroll(function(){
$(panel).processScrollEventOnActionPanel();
}).resize(function(){
$(panel).processScrollEventOnActionPanel();
});*/
//register Click handler for button
$(this).click(function() {
//Hide all disable Panels
jQuery.each(panels, function(i, panel) {
if (!$(panel["id"]).is(':hidden')) {
$(panel["id"]).hide();
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal"
});
}
}
});
//Show or hide panel
if (!$(panel["id"]).is(':hidden')) {
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowRight({
step:"1",
duration:"normal",
callback: function(){
$(panel["id"]).hide();
}
});
} else {
$(panel["id"]).flowUp({
step:"1",
duration:"normal",
callback: function(){
$(panel["id"]).hide();
}
});
}
}
else {
$(panel["id"]).show();
if (panel["animate"] == "LeftRight") {
$(panel["id"]).flowLeft({
step:"1",
duration:"normal"
});
} else {
$(panel["id"]).flowDown({
step:"1",
duration:"normal"
});
}
}
});
}
$("#btn-login").addActionClickHandlerOnActionPanel({
panel:{id:"#login-panel",animate:"LeftRight"},
disablePanels: [
{id:"#language-panel",animate:"UpDown"},
{id:"#search-panel", animate:"LeftRight"}
]
});
$("#btn-search").addActionClickHandlerOnActionPanel({
panel:{id:"#search-panel",animate:"LeftRight"},
disablePanels: [
{id:"#language-panel",animate:"UpDown"},
{id:"#login-panel", animate:"LeftRight"}
]
});
$("#btn-language").addActionClickHandlerOnActionPanel({
panel:{id:"#language-panel",animate:"UpDown"},
disablePanels: [
{id:"#login-panel", animate:"LeftRight"},
{id:"#search-panel", animate:"LeftRight"}
]
});
/* Categories Panel*/
function drawCategoryDock(options) {
var mainNav = options["mainNav"];
var controlBtn = options["controlBtn"];
var subNav = options["subNav"];
var config = options["config"];
$(subNav).hide();
$(controlBtn).parent().removeClass("active");
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > config.showBottom) {
$(mainNav).css({
position: "fixed",
bottom: "0px"
});
} else {
$(mainNav).css({
position: "absolute",
bottom: config.currentBottom + "px"
});
}
}
$.fn.controlSubCategoryNav = function controlSubCategoryNav(options) {
$(this).click(function() {
var mainNav = options["mainNav"];
var subNav = options["subNav"];
var config = options["config"];
var categoryItemWidth = $(this).width() - 1;
var bottom = $("body").height() - ($(window).height() + $(window).scrollTop());
if (bottom > 247) {
$(subNav).css({
width:categoryItemWidth + "px",
position: "fixed",
bottom: $(mainNav).height() + "px"
});
} else {
$(subNav).css({
width:categoryItemWidth + "px",
position: "absolute",
bottom: $(mainNav).height() + config.currentBottom + "px"
});
}
if ($(subNav).is(':hidden')) {
$(this).parent().addClass("active");
} else {
$(this).parent().removeClass("active");
}
$(subNav).slideToggle("normal");
});
} | JavaScript |
/*!
* iScroll Lite base on iScroll v4.1.6 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(){
var m = Math,
mround = function (r) { return r >> 0; },
vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
(/firefox/i).test(navigator.userAgent) ? 'Moz' :
'opera' in window ? 'O' : '',
// Browser capabilities
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isPlaybook = (/playbook/gi).test(navigator.appVersion),
isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
hasTouch = 'ontouchstart' in window && !isTouchPad,
hasTransform = vendor + 'Transform' in document.documentElement.style,
hasTransitionEnd = isIDevice || isPlaybook,
nextFrame = (function() {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { return setTimeout(callback, 17); }
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.oCancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| clearTimeout
})(),
// Events
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',
// Helpers
trnOpen = 'translate' + (has3d ? '3d(' : '('),
trnClose = has3d ? ',0)' : ')',
// Constructor
iScroll = function (el, options) {
var that = this,
doc = document,
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,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: 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 : false;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Set some default styles
that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
if (that.options.useTransition) that.scroller.style[vendor + 'TransitionTimingFunction'] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose;
else that.scroller.style.cssText += ';position:absolute;top:' + that.y + 'px;left:' + that.x + 'px';
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) that._bind('mouseout', that.wrapper);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
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 'mouseout': that._mouseout(e); break;
case 'webkitTransitionEnd': that._transitionEnd(e); break;
}
},
_resize: function () {
this.refresh();
},
_pos: function (x, y) {
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
} else {
x = mround(x);
y = mround(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition) 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;
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
x = matrix[4] * 1;
y = matrix[5] * 1;
} else {
x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, 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);
that._bind(END_EV);
that._bind(CANCEL_EV);
},
_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,
timestamp = e.timeStamp || Date.now();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
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 > 0 || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= 0 || that.maxScrollY >= 0 ? 0 : 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,
newDuration;
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (!that.moved) {
if (hasTouch) {
// 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 = document.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._resetPos(200);
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 : 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 > 0 && newPosY > 0) || (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);
that.scrollTo(mround(newPosX), mround(newPosY), newDuration);
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 >= 0 || that.maxScrollY > 0 ? 0 : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
that.moved = false;
}
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_mouseout: function (e) {
var t = e.relatedTarget;
if (!t) {
this._end(e);
return;
}
while (t = t.parentNode) if (t == this.wrapper) return;
this._end(e);
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind('webkitTransitionEnd');
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('webkitTransitionEnd');
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) {
this.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
},
_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: mround(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
return { left: left, top: top };
},
_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[vendor + 'Transform'] = '';
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
that._unbind('mouseout', that.wrapper);
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset;
that.wrapperW = that.wrapper.clientWidth;
that.wrapperH = that.wrapper.clientHeight;
that.scrollerW = that.scroller.offsetWidth;
that.scrollerH = that.scroller.offsetHeight;
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH;
that.dirX = 0;
that.dirY = 0;
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that._resetPos(200);
},
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 > 0 ? 0 : 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);
},
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);
this._unbind(END_EV);
this._unbind(CANCEL_EV);
},
enable: function () {
this.enabled = true;
},
stop: function () {
cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
}
};
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})();
| JavaScript |
/*!
* iScroll v4.2 ~ 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,
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',
WHEEL_EV = vendor == 'Moz' ? 'DOMMouseScroll' : 'mousewheel',
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) {
that._bind('mouseout', that.wrapper);
if (that.options.wheelAction != 'none')
that._bind(WHEEL_EV);
}
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 WHEEL_EV: that._wheel(e); break;
case 'mouseout': that._mouseout(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[4] * 1;
y = matrix[5] * 1;
} else {
x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
}
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);
}
}
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);
that._bind(END_EV);
that._bind(CANCEL_EV);
},
_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);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
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(200);
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);
}
},
_mouseout: function (e) {
var t = e.relatedTarget;
if (!t) {
this._end(e);
return;
}
while (t = t.parentNode) if (t == this.wrapper) return;
this._end(e);
},
_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);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (!that.options.hasTouch) {
that._unbind('mouseout', that.wrapper);
that._unbind(WHEEL_EV);
}
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(200);
}
},
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);
this._unbind(END_EV);
this._unbind(CANCEL_EV);
},
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 |
/* Description Panel */
$("#game-description").expandable({
expandButton:"#game-description .expand-button",
contentPanel:"#game-description .content",
minHeight:150
});
document.addEventListener('DOMContentLoaded', function(){
screenShot = new iScroll('item-screenshot-slider', {
useTransform: false,
hScrollbar: false,
vScrollbar: false,
onBeforeScrollStart: function (e) {
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
}
});
}, false);
$("body").everyTime(1000, function (i) {
$('#item-screenshot-slider').children().autoWidth({
margin: 30
});
screenShot.refresh();
}, 1);
function loadAutoComments(){
if(typeof commentCurrentPage === 'undefined'){
commentCurrentPage = 1;
}
$("#comment-list").loadComments({
id: $("#item-id").val(),
page: commentCurrentPage,
container: $("#comment-list"),
next: $("#comment-next-btn"),
prev: $("#comment-prev-btn")
});
}
$("#comment-list").everyTime(5000, function (i) {
loadAutoComments();
}, 0);
document.addEventListener('DOMContentLoaded', loadAutoComments, false);
$("#comment-next-btn").click(function(){
if(commentCurrentPage < commentPageCount){
var nextPage = parseInt(commentCurrentPage) + 1;
$("#comment-list").loadComments({
id: $("#item-id").val(),
page: nextPage,
container: $("#comment-list"),
next: $("#comment-next-btn"),
prev: $("#comment-prev-btn")
});
}
return false;
});
$("#comment-prev-btn").click(function(){
if(commentCurrentPage > 1){
var prevPage = parseInt(commentCurrentPage) - 1;
$("#comment-list").loadComments({
id: $("#item-id").val(),
page: prevPage,
container: $("#comment-list"),
next: $("#comment-next-btn"),
prev: $("#comment-prev-btn")
});
}
return false;
});
$("#btn-send").click(function(){
$("#btn-send").sendComment({
id: $("#item-id").val(),
content: $("#txt-comment"),
page: 1,
container: $("#comment-list"),
next: $("#comment-next-btn"),
prev: $("#comment-prev-btn"),
locale: $("#locale").val()
});
});
$("#txt-comment").keydown(function(e){
// Enter was pressed without shift key
if (e.keyCode == 13 && !e.shiftKey){
// prevent default behavior
$("#txt-comment").sendComment({
id: $("#item-id").val(),
content: $("#txt-comment"),
page: 1,
container: $("#comment-list"),
next: $("#comment-next-btn"),
prev: $("#comment-prev-btn"),
locale: $("#locale").val()
});
e.preventDefault();
}
}); | JavaScript |
!function ($, iScroll) {
$.ender({
iScroll: function (options) {
return new iScroll(this[0], options)
}
}, true)
}(ender, require('iscroll').iScroll) | JavaScript |
/*
*http://blog.stevenlevithan.com/archives/date-time-format
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
}; | JavaScript |
/* Init control for buttons in action panel */
$("#searchButton").control({
type: FD_PANEL_CONTROL,
panel: "#search-panel"
});
$("#accountButton").control({
type: FD_PANEL_CONTROL,
panel: "#login-panel"
});
$("#settingButton").control({
type: FD_PANEL_CONTROL,
panel: "#language-panel"
});
$("input[name='language']").control({
type: LANGUAGE_CONTROL
});
$(".sign-in").click(function(){
$(this).login({
email: $("#txt-email").val(),
password: $("#txt-password").val(),
loginUrl: $("#login-form").attr('action')
});
});
$("#txt-password").keypress(function(e) {
if(e.which == 13) {
$(".sign-in").login({
email: $("#txt-email").val(),
password: $("#txt-password").val(),
loginUrl: $("#login-form").attr('action')
});
}
});
$("#txt-email").keypress(function(e) {
if(e.which == 13) {
$(".sign-in").login({
email: $("#txt-email").val(),
password: $("#txt-password").val(),
loginUrl: $("#login-form").attr('action')
});
}
});
$("#btn-close").click(function(){
$(".errorMsg").text("");
$("#modal-dialog").hide();
});
/* search handler */
$("#search-content").keypress(function(e) {
if(e.which == 13) {
$("#search-content").search();
}
});
$("#submit-search").click(function(){
$("#search-content").search();
});
$(window).resize(function(){
$('.dialog').css("margin-top", -$('.dialog').height()/2 + "px");
});
document.addEventListener('touchmove', function (e) {
e.preventDefault();
}, false);
document.addEventListener('DOMContentLoaded', function(){
mainScroll = new iScroll('wrapper', {
useTransform: false,
hScrollbar: false,
vScrollbar: false,
onBeforeScrollStart: function (e) {
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA' && target.tagName != 'P')
e.preventDefault();
}
});
}, false);
$("#wrapper").everyTime(1000, function (i) {
mainScroll.refresh();
}, 0); | JavaScript |
$("#terms-of-use").expandable({
expandButton:"#terms-of-use .expand-button",
contentPanel:"#terms-of-use .content",
minHeight:150
});
$("#register-button").click(function(){
$("#regiter-form").submit();
}); | JavaScript |
/* Custom jquery function */
$.fn.flowUp = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "-=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowLeft = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "+=" + $(this).width() * step + "px"
},
duration,
callback
);
}
$.fn.flowDown = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"top": "+=" + $(this).height() * step + "px"
},
duration,
callback
);
}
$.fn.flowRight = function(options) {
var step = options["step"];
var duration = options["duration"];
var callback = options["callback"];
$(this).animate({
"position":"absolute",
"right": "-=" + $(this).width() * step + "px"
},
duration,
callback
);
}
/* Control function */
var CHILD_FD_PANELS = new Array();
var FD_CONTROL_BUTTONS = new Array();
var FD_PANEL_CONTROL = 1;
var CATEGORY_CONTROL = 2;
var LANGUAGE_CONTROL = 3;
$.fn.control = function(options){
var type = options["type"];
if(type == FD_PANEL_CONTROL){
var panel = options["panel"];
CHILD_FD_PANELS.push(panel);
FD_CONTROL_BUTTONS.push(this);
$(this).click(function(){
if ($(panel).parent().is(':hidden') || (!$(panel).parent().is(':hidden') && $(panel).is(':hidden'))){
for (var i=0; i < CHILD_FD_PANELS.length; i++) {
$(CHILD_FD_PANELS[i]).hide();
}
for (i=0; i < FD_CONTROL_BUTTONS.length; i++) {
$(FD_CONTROL_BUTTONS[i]).removeClass("active");
}
$(panel).show();
$(this).addClass("active");
if($(panel).parent().is(':hidden')){
$(panel).parent().slideToggle("fast");
}
}else if (!$(panel).parent().is(':hidden') && !$(panel).is(':hidden')){
$(panel).parent().slideToggle("fast");
for (i=0; i < CHILD_FD_PANELS.length; i++) {
$(CHILD_FD_PANELS[i]).hide();
}
$(this).removeClass("active");
}
});
} else if(type == CATEGORY_CONTROL){
$(this).click(function() {
var subNav = options["subNav"];
var width = $(this).width();
$(subNav).css({
width:width + "px",
position: "absolute",
bottom: $(subNav).parent().height() + 2 + "px"
});
$(subNav).slideToggle("normal");
});
} else if(type == LANGUAGE_CONTROL){
var inputs = $(this);
$.each(inputs, function() {
var pathName = $(this).attr('alt');
$(this).click(function(){
window.location.href = getDirectUrl(pathName);
});
});
}
}
/*Expand & Collapse Panel*/
$.fn.expandable = function(options) {
var expandablePanel = this;
var expandButton = options["expandButton"];
var contentPanel = options["contentPanel"];
var minHeight = options["minHeight"];
$(expandButton).click(function() {
if($(expandablePanel).hasClass('collapsed')){
var curHeight = $(expandablePanel).height();
var autoHeight = $(expandablePanel).css('height', 'auto').height();
$(expandablePanel).height(curHeight).animate({
height: autoHeight
},function(){
$(expandablePanel).removeClass('collapsed');
});
}else{
$(expandablePanel).addClass('collapsed');
$(expandablePanel).animate({
height: minHeight + "px"
});
}
});
$(window).resize(function() {
if($(expandablePanel).height() > minHeight){
if($(contentPanel).height() < $(expandablePanel).height()){
var curHeight = $(expandablePanel).height()
var autoHeight = $(expandablePanel).css('height', 'auto').height();
$(expandablePanel).height(curHeight).animate({
height: autoHeight
});
$(expandablePanel).animate({
height: $(contentPanel).height()
});
}else{
$(expandablePanel).addClass('collapsed');
$(expandablePanel).animate({
height: $(contentPanel).height()
},function(){
$(expandablePanel).removeClass('collapsed');
});
}
}
});
}
/* getDirectUrl */
function getDirectUrl(pathName){
return window.location.protocol + "//" + window.location.host + pathName;
}
/* Search Panel */
$.fn.search = function() {
if($(this).val()==""){
return;
}else{
var protocol = window.location.protocol;
var host = window.location.host;
var moduleName = window.location.pathname.split("/")[1];
var url = protocol + "//" + host+"/"+moduleName+ "/1/" + $(this).val();
window.location.href = url;
}
}
/* Login Panel */
$.fn.login = function(options) {
var loginUrl = options["loginUrl"];
var email = options["email"];
var password = options["password"];
$.ajax({
url: loginUrl,
type: "POST",
dataType: "json",
data: {
email: email,
password: password
},
success: function (responseJson) {
if(responseJson == null){
location.reload();
}else{
alert(responseJson);
}
}
});
}
function alertMessage(message){
var dialogLayout = $("#modal-dialog");
var dialog = $(".dialog");
var msg = $(".errorMsg");
$(msg).text(message);
$(dialogLayout).show();
$(dialog).css("margin-top", -$(dialog).height()/2 + "px");
}
/* Comment */
$.fn.loadComments = function(options) {
var url = "/comment-engine/" + options.id + "/" + options.page;
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function (responseJson) {
if(responseJson != null){
var html = "";
for(var i=0; i<responseJson.result.length; i++){
html += "<div class='comment-item'>";
html += "<p class='comment-name'>";
html += responseJson.result[i].customer.fullName;
html += "<span> (";
html += (new Date(responseJson.result[i].createdDate)).format("HH:MM");
html += " " + (new Date(responseJson.result[i].createdDate)).format("mmm d, yyyy");
html += ")</span>";
html += "</p>";
html += "<p class='comment-content'>";
html += responseJson.result[i].content;
html += "</p>";
html += "</div><!-- End .comment-item -->";
}
options.container.html(html);
commentCurrentPage = responseJson.page;
commentPageCount = responseJson.pageCount;
var pageSize = responseJson.pageSize;
if(responseJson.count <= pageSize){
$("#page-nav").hide();
return;
}else{
$("#page-nav").show();
}
var from = (commentCurrentPage-1)*pageSize +1;
var to = pageSize*commentCurrentPage;
to = to > responseJson.count ? responseJson.count : to;
var value = from == to ? from :from +"-"+ to;
$("#comment-page-number").text(value);
$("#comment-page-count").text(responseJson.count);
}
}
});
}
$.fn.sendComment = function(options){
if(options.content.val()==""){
return;
}else{
var url = "/comment-engine/create/" + options.id;
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
content: options.content.val(),
locale: options.locale
},
success: function (responseJson) {
if(responseJson == null){
options.content.val("").blur();
options.container.loadComments({
id: options.id,
page: options.page,
container: options.container,
next: options.next,
prev: options.prev
});
}else{
alert(responseJson);
}
}
});
}
}
$.fn.autoWidth = function(options){
var width = 0;
$(this).children().each(function(index, child){
width = width+$(child).width()+options.margin;
});
$(this).css("width", width + "px");
} | JavaScript |
/* Categories Panel */
$("#category").control({
type: CATEGORY_CONTROL,
subNav: "#category-sub-nav"
});
document.addEventListener('DOMContentLoaded', function(){
itemSlider = new iScroll('item-slider', {
useTransform: false,
hScrollbar: false,
vScrollbar: false,
onBeforeScrollStart: function (e) {
var target = e.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
e.preventDefault();
}
});
}, false);
$("body").everyTime(1000, function (i) {
$('#item-slider').children().autoWidth({
margin: 20
});
itemSlider.refresh();
}, 1); | JavaScript |
/**
* jQuery.timers - Timer abstractions for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/10/16
*
* @author Blair Mitchelmore
* @version 1.2
*
**/
jQuery.fn.extend({
everyTime: function (interval, label, fn, times) {
return this.each(function () {
jQuery.timer.add(this, interval, label, fn, times);
});
},
oneTime: function (interval, label, fn) {
return this.each(function () {
jQuery.timer.add(this, interval, label, fn, 1);
});
},
stopTime: function (label, fn) {
return this.each(function () {
jQuery.timer.remove(this, label, fn);
});
}
});
jQuery.extend({
timer: {
global: [],
guid: 1,
dataKey: "jQuery.timer",
regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
powers: {
// Yeah this is major overkill...
'ms': 1,
'cs': 10,
'ds': 100,
's': 1000,
'das': 10000,
'hs': 100000,
'ks': 1000000
},
timeParse: function (value) {
if (value == undefined || value == null)
return null;
var result = this.regex.exec(jQuery.trim(value.toString()));
if (result[2]) {
var num = parseFloat(result[1]);
var mult = this.powers[result[2]] || 1;
return num * mult;
} else {
return value;
}
},
add: function (element, interval, label, fn, times) {
var counter = 0;
if (jQuery.isFunction(label)) {
if (!times)
times = fn;
fn = label;
label = interval;
}
interval = jQuery.timer.timeParse(interval);
if (typeof interval != 'number' || isNaN(interval) || interval < 0)
return;
if (typeof times != 'number' || isNaN(times) || times < 0)
times = 0;
times = times || 0;
var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
if (!timers[label])
timers[label] = {};
fn.timerID = fn.timerID || this.guid++;
var handler = function () {
if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
jQuery.timer.remove(element, label, fn);
};
handler.timerID = fn.timerID;
if (!timers[label][fn.timerID])
timers[label][fn.timerID] = window.setInterval(handler, interval);
this.global.push(element);
},
remove: function (element, label, fn) {
var timers = jQuery.data(element, this.dataKey), ret;
if (timers) {
if (!label) {
for (label in timers)
this.remove(element, label, fn);
} else if (timers[label]) {
if (fn) {
if (fn.timerID) {
window.clearInterval(timers[label][fn.timerID]);
delete timers[label][fn.timerID];
}
} else {
for (var fn in timers[label]) {
window.clearInterval(timers[label][fn]);
delete timers[label][fn];
}
}
for (ret in timers[label]) break;
if (!ret) {
ret = null;
delete timers[label];
}
}
for (ret in timers) break;
if (!ret)
jQuery.removeData(element, this.dataKey);
}
}
}
});
jQuery(window).bind("unload", function () {
jQuery.each(jQuery.timer.global, function (index, item) {
jQuery.timer.remove(item);
});
}); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: handlers.js 31539 2012-09-06 07:54:49Z zhengqingpeng $
*/
var sdCloseTime = 2;
function preLoad() {
if(!this.support.loading) {
disableMultiUpload(this.customSettings);
return false;
}
}
function loadFailed() {
disableMultiUpload(this.customSettings);
}
function disableMultiUpload(obj) {
if(obj.uploadSource == 'forum' && obj.uploadFrom != 'fastpost') {
try{
obj.singleUpload.style.display = '';
var dIdStr = obj.singleUpload.getAttribute("did");
if(dIdStr != null) {
if(typeof forum_post_inited == 'undefined') {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
}
var idArr = dIdStr.split("|");
$(idArr[0]).style.display = 'none';
if(idArr[1] == 'local') {
switchImagebutton('local');
} else if(idArr[1] == 'upload') {
switchAttachbutton('upload');
}
}
} catch (e) {
}
}
}
function fileDialogStart() {
if(this.customSettings.uploadSource == 'forum') {
this.customSettings.alertType = 0;
if(this.customSettings.uploadFrom == 'fastpost') {
if(typeof forum_post_inited == 'undefined') {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
}
}
}
}
function fileQueued(file) {
try {
var createQueue = true;
var progress = new FileProgress(file, this.customSettings.progressTarget);
if(this.customSettings.uploadSource == 'forum') {
if(this.customSettings.maxAttachNum != undefined) {
if(this.customSettings.maxAttachNum > 0) {
this.customSettings.maxAttachNum--;
} else {
this.customSettings.alertType = 6;
createQueue = false;
}
}
if(createQueue && this.customSettings.maxSizePerDay != undefined) {
if(this.customSettings.maxSizePerDay - file.size > 0) {
this.customSettings.maxSizePerDay = this.customSettings.maxSizePerDay - file.size
} else {
this.customSettings.alertType = 11;
createQueue = false;
}
}
if(createQueue && this.customSettings.filterType != undefined) {
var fileSize = this.customSettings.filterType[file.type.substr(1).toLowerCase()];
if(fileSize != undefined && fileSize && file.size > fileSize) {
this.customSettings.alertType = 5;
createQueue = false;
}
}
} else if(this.customSettings.uploadSource == 'portal') {
var inputObj = $('catid');
if(inputObj && parseInt(inputObj.value)) {
this.addPostParam('catid', inputObj.value);
}
}
if(createQueue) {
progress.setStatus("等待上传...");
} else {
this.cancelUpload(file.id);
progress.setCancelled();
}
progress.toggleCancel(true, this);
} catch (ex) {
this.debug(ex);
}
}
function fileQueueError(file, errorCode, message) {
try {
if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
message = parseInt(message);
showDialog("您选择的文件个数超过限制。\n"+(message === 0 ? "您已达到上传文件的上限了。" : "您还可以选择 " + message + " 个文件"), 'notice', null, null, 0, null, null, null, null, sdCloseTime);
return;
}
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setError();
progress.toggleCancel(false);
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
progress.setStatus("文件太大.");
this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
progress.setStatus("不能上传零字节文件.");
this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
progress.setStatus("禁止上传该类型的文件.");
this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
alert("You have selected too many files. " + (message > 1 ? "You may only add " + message + " more files" : "You cannot add any more files."));
break;
default:
if (file !== null) {
progress.setStatus("Unhandled Error");
}
this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
}
} catch (ex) {
this.debug(ex);
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if(this.customSettings.uploadSource == 'forum') {
if(this.customSettings.uploadType == 'attach') {
if(typeof switchAttachbutton == "function") {
switchAttachbutton('attachlist');
}
try {
if(this.getStats().files_queued) {
$('attach_tblheader').style.display = '';
$('attach_notice').style.display = '';
}
} catch (ex) {}
} else if(this.customSettings.uploadType == 'image') {
if(typeof switchImagebutton == "function") {
switchImagebutton('imgattachlist');
}
try {
$('imgattach_notice').style.display = '';
} catch (ex) {}
}
var objId = this.customSettings.uploadType == 'attach' ? 'attachlist' : 'imgattachlist';
var listObj = $(objId);
var tableObj = listObj.getElementsByTagName("table");
if(!tableObj.length) {
listObj.innerHTML = "";
}
} else if(this.customSettings.uploadType == 'blog') {
if(typeof switchImagebutton == "function") {
switchImagebutton('imgattachlist');
}
}
this.startUpload();
} catch (ex) {
this.debug(ex);
}
}
function uploadStart(file) {
try {
this.addPostParam('filetype', file.type);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setStatus("上传中...");
progress.toggleCancel(true, this);
if(this.customSettings.uploadSource == 'forum') {
var objId = this.customSettings.uploadType == 'attach' ? 'attachlist' : 'imgattachlist';
var attachlistObj = $(objId).parentNode;
attachlistObj.scrollTop = $(file.id).offsetTop - attachlistObj.clientHeight;
}
} catch (ex) {
}
return true;
}
function uploadProgress(file, bytesLoaded, bytesTotal) {
try {
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setStatus("正在上传("+percent+"%)...");
} catch (ex) {
this.debug(ex);
}
}
function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.progressTarget);
if(this.customSettings.uploadSource == 'forum') {
aid = parseInt(serverData);
if(aid > 0) {
if(this.customSettings.uploadType == 'attach') {
ajaxget('forum.php?mod=ajax&action=attachlist&aids=' + aid + (!fid ? '' : '&fid=' + fid)+(typeof resulttype == 'undefined' ? '' : '&result=simple'), file.id);
} else if(this.customSettings.uploadType == 'image') {
var tdObj = getInsertTdId(this.customSettings.imgBoxObj, 'image_td_'+aid);
ajaxget('forum.php?mod=ajax&action=imagelist&type=single&pid=' + pid + '&aids=' + aid + (!fid ? '' : '&fid=' + fid), tdObj.id);
$(file.id).style.display = 'none';
}
} else {
aid = aid < -1 ? Math.abs(aid) : aid;
if(typeof STATUSMSG[aid] == "string") {
progress.setStatus(STATUSMSG[aid]);
showDialog(STATUSMSG[aid], 'notice', null, null, 0, null, null, null, null, sdCloseTime);
} else {
progress.setStatus("取消上传");
}
this.cancelUpload(file.id);
progress.setCancelled();
progress.toggleCancel(true, this);
var stats = this.getStats();
var obj = {'successful_uploads':--stats.successful_uploads, 'upload_cancelled':++stats.upload_cancelled};
this.setStats(obj);
}
} else if(this.customSettings.uploadType == 'album') {
var data = eval('('+serverData+')');
if(parseInt(data.picid)) {
var newTr = document.createElement("TR");
var newTd = document.createElement("TD");
var img = new Image();
img.src = data.url;
var imgObj = document.createElement("img");
imgObj.src = img.src;
newTd.className = 'c';
newTd.appendChild(imgObj);
newTr.appendChild(newTd);
newTd = document.createElement("TD");
newTd.innerHTML = '<strong>'+file.name+'</strong>';
newTr.appendChild(newTd);
newTd = document.createElement("TD");
newTd.className = 'd';
newTd.innerHTML = '图片描述<br/><textarea name="title['+data.picid+']" cols="40" rows="2" class="pt"></textarea>';
newTr.appendChild(newTd);
this.customSettings.imgBoxObj.appendChild(newTr);
} else {
showDialog('图片上传失败', 'notice', null, null, 0, null, null, null, null, sdCloseTime);
}
$(file.id).style.display = 'none';
} else if(this.customSettings.uploadType == 'blog') {
var data = eval('('+serverData+')');
if(parseInt(data.picid)) {
var tdObj = getInsertTdId(this.customSettings.imgBoxObj, 'image_td_'+data.picid);
var img = new Image();
img.src = data.url;
var imgObj = document.createElement("img");
imgObj.src = img.src;
imgObj.className = "cur1";
imgObj.onclick = function() {insertImage(data.bigimg);};
tdObj.appendChild(imgObj);
var inputObj = document.createElement("input");
inputObj.type = 'hidden';
inputObj.name = 'picids['+data.picid+']';
inputObj.value= data.picid;
tdObj.appendChild(inputObj);
} else {
showDialog('图片上传失败', 'notice', null, null, 0, null, null, null, null, sdCloseTime);
}
$(file.id).style.display = 'none';
} else if(this.customSettings.uploadSource == 'portal') {
var data = eval('('+serverData+')');
if(data.aid) {
if(this.customSettings.uploadType == 'attach') {
ajaxget('portal.php?mod=attachment&op=getattach&type=attach&id=' + data.aid, file.id);
if($('attach_tblheader')) {
$('attach_tblheader').style.display = '';
}
} else {
var tdObj = getInsertTdId(this.customSettings.imgBoxObj, 'attach_list_'+data.aid);
ajaxget('portal.php?mod=attachment&op=getattach&id=' + data.aid, tdObj.id);
$(file.id).style.display = 'none';
}
} else {
showDialog('上传失败', 'notice', null, null, 0, null, null, null, null, sdCloseTime);
progress.setStatus("Cancelled");
this.cancelUpload(file.id);
progress.setCancelled();
progress.toggleCancel(true, this);
}
} else {
progress.setComplete();
progress.setStatus("上传完成.");
progress.toggleCancel(false);
}
} catch (ex) {
this.debug(ex);
}
}
function getInsertTdId(boxObj, tdId) {
var tableObj = boxObj.getElementsByTagName("table");
var tbodyObj, trObj, tdObj;
if(!tableObj.length) {
tableObj = document.createElement("table");
tableObj.className = "imgl";
tbodyObj = document.createElement("TBODY");
tableObj.appendChild(tbodyObj);
boxObj.appendChild(tableObj);
} else if(!tableObj[0].getElementsByTagName("tbody").length) {
tbodyObj = document.createElement("TBODY");
tableObj.appendChild(tbodyObj);
} else {
tableObj = tableObj[0];
tbodyObj = tableObj.getElementsByTagName("tbody")[0];
}
var createTr = true;
var inserID = 0;
if(tbodyObj.childNodes.length) {
trObj = tbodyObj.childNodes[tbodyObj.childNodes.length -1];
var findObj = trObj.getElementsByTagName("TD");
for(var j=0; j < findObj.length; j++) {
if(findObj[j].id == "") {
inserID = j;
tdObj = findObj[j];
break;
}
}
if(inserID) {
createTr = false;
}
}
if(createTr) {
trObj = document.createElement("TR");
for(var i=0; i < 4; i++) {
var newTd = document.createElement("TD");
newTd.width = "25%";
newTd.vAlign = "bottom";
newTd.appendChild(document.createTextNode(" "));
trObj.appendChild(newTd);
}
tdObj = trObj.childNodes[0];
tbodyObj.appendChild(trObj);
}
tdObj.id = tdId;
return tdObj;
}
function uploadComplete(file) {
try {
if (this.getStats().files_queued === 0) {
} else {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function uploadError(file, errorCode, message) {
try {
var progress = new FileProgress(file, this.customSettings.progressTarget);
progress.setError();
progress.toggleCancel(false);
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
progress.setStatus("Upload Error: " + message);
this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
progress.setStatus("Configuration Error");
this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
progress.setStatus("Upload Failed.");
this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
progress.setStatus("Server (IO) Error");
this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
progress.setStatus("Security Error");
this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
progress.setStatus("Upload limit exceeded.");
this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
progress.setStatus("File not found.");
this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
progress.setStatus("Failed Validation. Upload skipped.");
this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
if (this.getStats().files_queued === 0) {
}
progress.setStatus(this.customSettings.alertType ? STATUSMSG[this.customSettings.alertType] : "Cancelled");
progress.setCancelled();
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
progress.setStatus("Stopped");
break;
default:
progress.setStatus("Unhandled Error: " + error_code);
this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
break;
}
} catch (ex) {
this.debug(ex);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal.js 29595 2012-04-20 10:05:13Z zhangguosheng $
*/
function block_get_setting(classname, script, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=setting&bid='+bid+'&classname='+classname+'&script='+script+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_setting'), s);
});
}
function switch_blocktab(type) {
if(type == 'setting') {
$('blockformsetting').style.display = '';
$('blockformdata').style.display = 'none';
$('li_setting').className = 'a';
$('li_data').className = '';
} else {
$('blockformsetting').style.display = 'none';
$('blockformdata').style.display = '';
$('li_setting').className = '';
$('li_data').className = 'a';
}
}
function showpicedit(pre) {
pre = pre ? pre : 'pic';
if($(pre+'way_remote').checked) {
$(pre+'_remote').style.display = "block";
$(pre+'_upload').style.display = "none";
} else {
$(pre+'_remote').style.display = "none";
$(pre+'_upload').style.display = "block";
}
}
function block_show_thumbsetting(classname, styleid, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=thumbsetting&classname='+classname+'&styleid='+styleid+'&bid='+bid+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_thumbsetting'), s);
});
}
function block_showstyle(stylename) {
var el_span = $('span_'+stylename);
var el_value = $('value_' + stylename);
if (el_value.value == '1'){
el_value.value = '0';
el_span.className = "";
} else {
el_value.value = '1';
el_span.className = "a";
}
}
function block_pushitem(bid, itemid) {
var id = $('push_id').value;
var idtype = $('push_idtype').value;
if(id && idtype) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=push&&bid='+bid+'&itemid='+itemid+'&idtype='+idtype+'&id='+id+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_pushcontent'), s);
evalscript(s);
});
}
}
function block_delete_item(bid, itemid, itemtype, itemfrom, from) {
var msg = itemtype==1 ? '您确定要删除该数据吗?' : '您确定要屏蔽该数据吗?';
if(confirm(msg)) {
var url = 'portal.php?mod=portalcp&ac=block&op=remove&bid='+bid+'&itemid='+itemid;
if(itemfrom=='ajax') {
var x = new Ajax();
x.get(url+'&inajax=1', function(){
if(succeedhandle_showblock) succeedhandle_showblock('', '', {'bid':bid});
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=data&bid='+bid+'&from='+from+'&tab=data&t='+(+ new Date()), 'get', 0);
});
} else {
location.href = url;
}
}
doane();
}
function portal_comment_requote(cid, aid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=comment&op=requote&cid='+cid+'&aid='+aid+'&inajax=1', function(s){
$('message').focus();
ajaxinnerhtml($('message'), s);
});
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function searchblock(from) {
var value = $('searchkey').value;
var targettplname = $('targettplname').value;
value = BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(value) : (value ? value.replace(/#/g,'%23') : '');
var url = 'portal.php?mod=portalcp&ac=portalblock&searchkey='+value+'&from='+from;
url += targettplname != '' ? '&targettplname='+targettplname+'&type=page' : '&type=block';
reloadselection(url);
}
function reloadselection(url) {
ajaxget(url+'&t='+(+ new Date()), 'block_selection');
}
function getColorPalette(colorid, id, background) {
return "<input id=\"c"+colorid+"\" onclick=\"createPalette('"+colorid+"', '"+id+"');\" type=\"button\" class=\"pn colorwd\" value=\"\" style=\"background-color: "+background+"\">";
}
function listblock_bypage(id, idtype) {
var tpl = $('rtargettplname') ? $('rtargettplname').value : '';
var searchkey = $('rsearchkey') ? $('rsearchkey').value.replace('#', '%23') : '';
ajaxget('portal.php?mod=portalcp&ac=portalblock&op=recommend&getdata=yes&searchkey='+searchkey+'&targettplname='+tpl+'&id='+id+'&idtype='+idtype, 'itemeditarea');
}
function recommenditem_check() {
var sel = $('recommend_bid');
if(sel && sel.value) {
document.forms['recommendform'].action = document.forms['recommendform'].action+'&bid='+sel.value;
return true;
} else {
alert("请选择一个模块!");
return false;
}
}
function recommenditem_byblock(bid, id, idtype) {
var editarea = $('itemeditarea');
if(editarea) {
var olditemeditarea = $('olditemeditarea');
ajaxinnerhtml(olditemeditarea, editarea.innerHTML);
if(!$('recommendback')) {
var back = document.createElement('div');
back.innerHTML = '<em id="recommendback" onclick="recommenditem_back()" class="cur1"> «返回</em>';
var return_mods = $('return_mods') || $('return_recommend') || $('return_');
if(return_mods) {
return_mods.parentNode.appendChild(back.childNodes[0]);
}
}
if(bid) {
if($('recommend_bid')) {
$('recommend_bid').value = bid;
}
ajaxget('portal.php?mod=portalcp&ac=block&op=recommend&bid='+bid+'&id='+id+'&idtype='+idtype+'&handlekey=recommenditem', 'itemeditarea');
} else {
ajaxinnerhtml(editarea, '<tr><td> </td><td> </td></tr>');
}
}
}
function delete_recommenditem(dataid, bid) {
if(dataid && bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=delrecommend&bid='+bid+'&dataid='+dataid+'&inajax=1', function(s){
$('recommenditem_'+dataid).parentNode.removeChild($('recommenditem_'+dataid));
if(!$('recommenditem_ul').getElementsByTagName('li').length) {
$('hasinblocks').parentNode.removeChild($('hasinblocks'));
}
});
}
}
function recommenditem_back(){
var editarea = $('itemeditarea');
var oldeditarea = $('olditemeditarea');
var recommendback = $('recommendback');
if(oldeditarea){
ajaxinnerhtml(editarea, oldeditarea.innerHTML);
ajaxupdateevents(editarea);
}
if(recommendback) {
recommendback.parentNode.removeChild(recommendback);
}
if($('recommend_bid')) {
$('recommend_bid').value = '';
}
}
function blockBindTips() {
var elems = ($('blockformsetting') || document).getElementsByTagName('img');
var k = 0;
var stamp = (+new Date());
var tips = '';
for(var i = 0; i < elems.length; i++) {
tips = elems[i]['tips'] || elems[i].getAttribute('tips') || '';
if(tips && ! elems[i].isBindTips) {
elems[i].isBindTips = '1';
elems[i].id = elems[i].id ? elems[i].id : ('elem_' + stamp + k.toString());
k++;
showPrompt(elems[i].id, 'mouseover', tips, 1, true);
}
}
}
function blockSetCacheTime(timer) {
$('txt_cachetime').value=timer;
doane();
}
function toggleSettingShow() {
if(!$('tbody_setting').style.display) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
doane();
}
function switchSetting() {
var checked = $('isblank').checked;
if(checked) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
}
function checkblockname(form) {
if(!(trim(form.name.value) > '')) {
showDialog('模块标识不能为空', 'error', null, function(){form.name.focus();});
return false;
}
if(form.summary && form.summary.value) {
var tag = blockCheckTag(form.summary.value, true);
if(tag) {
showBlockSummary();
form.summary.focus();
showDialog('自定义内容错误,HTML代码:'+tag+' 标签不匹配', 'error', null, function(){form.summary.select();});
return false;
}
}
return true;
}
function blockCheckTag(summary, returnValue) {
var obj = null, fn = null;
if(typeof summary == 'object') {
obj = summary;
summary = summary.value;
fn = function(){obj.focus();obj.select();};
}
if(trim(summary) > '') {
var tags = ['div', 'table', 'tbody', 'tr', 'td', 'th'];
for(var i = 0; i < tags.length; i++) {
var tag = tags[i];
var reg = new RegExp('<'+tag+'', 'gi');
var preTag = [];
var one = [];
while (one = reg.exec(summary)) {
preTag.push(one[0]);
}
reg = new RegExp('</'+tag+'>', 'gi');
var endTag = [];
var one = [];
while (one = reg.exec(summary)) {
endTag.push(one[0]);
}
if(!preTag && !endTag) continue;
if((!preTag && endTag) || (preTag && !endTag) || preTag.length != endTag.length) {
if(returnValue) {
return tag;
} else {
showDialog('HTML代码:'+tag+' 标签不匹配', 'error', null, fn, true, fn);
return false;
}
}
}
}
return false;
}
function showBlockSummary() {
$('block_sumamry_content').style.display='';
$('a_summary_show').style.display='none';
$('a_summary_hide').style.display='';
return false;
}
function hideBlockSummary() {
$('block_sumamry_content').style.display='none';
$('a_summary_hide').style.display='none';
$('a_summary_show').style.display='';
return false;
}
function blockconver(ele,bid) {
if(ele && bid) {
if(confirm('您确定要转换模块的类型从 '+ele.options[0].innerHTML+' 到 '+ele.options[ele.selectedIndex].innerHTML)) {
ajaxget('portal.php?mod=portalcp&ac=block&op=convert&bid='+bid+'&toblockclass='+ele.value,'blockshow');
} else {
ele.selectedIndex = 0;
}
}
}
function blockFavorite(bid){
if(bid) {
ajaxget('portal.php?mod=portalcp&ac=block&op=favorite&bid='+bid,'bfav_'+bid);
}
}
function strLenCalc(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = 0, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen += 2;
} else {
curlen += 1;
}
}
checklen = $(checklen);
if(checklen.style.display == 'none') checklen.style.display = '';
if(curlen <= maxlen) {
checklen.innerHTML = '已输入 <b>'+(curlen)+'</b> 个字符';
return true;
} else {
checklen.innerHTML = '超出 <b style="color:red">'+(curlen - maxlen)+'</b> 个字符';
return false;
}
}
function check_itemdata_lentgh(form) {
if(form.title && (!strLenCalc(form.title, "titlechk", form.title.getAttribute('_maxlength')) || !form.title.value)) {
form.title.focus();
showDialog('标题长度不正确', 'error', null, function(){form.title.select();});
return false;
}
if(form.summary && !strLenCalc(form.summary, "summarychk", form.summary.getAttribute('_maxlength'))) {
form.summary.focus();
showDialog('简介长度不正确', 'error', null, function(){form.summary.select();});
return false;
}
return true;
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tree.js 23838 2011-08-11 06:51:58Z monkey $
*/
var icon = new Object();
icon.root = IMGDIR + '/tree_root.gif';
icon.folder = IMGDIR + '/tree_folder.gif';
icon.folderOpen = IMGDIR + '/tree_folderopen.gif';
icon.file = IMGDIR + '/tree_file.gif';
icon.empty = IMGDIR + '/tree_empty.gif';
icon.line = IMGDIR + '/tree_line.gif';
icon.lineMiddle = IMGDIR + '/tree_linemiddle.gif';
icon.lineBottom = IMGDIR + '/tree_linebottom.gif';
icon.plus = IMGDIR + '/tree_plus.gif';
icon.plusMiddle = IMGDIR + '/tree_plusmiddle.gif';
icon.plusBottom = IMGDIR + '/tree_plusbottom.gif';
icon.minus = IMGDIR + '/tree_minus.gif';
icon.minusMiddle = IMGDIR + '/tree_minusmiddle.gif';
icon.minusBottom = IMGDIR + '/tree_minusbottom.gif';
function treeNode(id, pid, name, url, target, open) {
var obj = new Object();
obj.id = id;
obj.pid = pid;
obj.name = name;
obj.url = url;
obj.target = target;
obj.open = open;
obj._isOpen = open;
obj._lastChildId = 0;
obj._pid = 0;
return obj;
}
function dzTree(treeName) {
this.nodes = new Array();
this.openIds = getcookie('leftmenu_openids');
this.pushNodes = new Array();
this.addNode = function(id, pid, name, url, target, open) {
var theNode = new treeNode(id, pid, name, url, target, open);
this.pushNodes.push(id);
if(!this.nodes[pid]) {
this.nodes[pid] = new Array();
}
this.nodes[pid]._lastChildId = id;
for(k in this.nodes) {
if(this.openIds && this.openIds.indexOf('_' + theNode.id) != -1) {
theNode._isOpen = true;
}
if(this.nodes[k].pid == id) {
theNode._lastChildId = this.nodes[k].id;
}
}
this.nodes[id] = theNode;
};
this.show = function() {
var s = '<div class="tree">';
s += this.createTree(this.nodes[0]);
s += '</div>';
document.write(s);
};
this.createTree = function(node, padding) {
padding = padding ? padding : '';
if(node.id == 0){
var icon1 = '';
} else {
var icon1 = '<img src="' + this.getIcon1(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon1_' + node.id + '" style="cursor: pointer;">';
}
var icon2 = '<img src="' + this.getIcon2(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon2_' + node.id + '" style="cursor: pointer;">';
var s = '<div class="node" id="node_' + node.id + '">' + padding + icon1 + icon2 + this.getName(node) + '</div>';
s += '<div class="nodes" id="nodes_' + node.id + '" style="display:' + (node._isOpen ? '' : 'none') + '">';
for(k in this.pushNodes) {
var id = this.pushNodes[k];
var theNode = this.nodes[id];
if(theNode.pid == node.id) {
if(node.id == 0){
var thePadding = '';
} else {
var thePadding = padding + (node.id == this.nodes[node.pid]._lastChildId ? '<img src="' + icon.empty + '">' : '<img src="' + icon.line + '">');
}
if(!theNode._lastChildId) {
var icon1 = '<img src="' + this.getIcon1(theNode) + '"' + ' id="icon1_' + theNode.id + '">';
var icon2 = '<img src="' + this.getIcon2(theNode) + '" id="icon2_' + theNode.id + '">';
s += '<div class="node" id="node_' + theNode.id + '">' + thePadding + icon1 + icon2 + this.getName(theNode) + '</div>';
} else {
s += this.createTree(theNode, thePadding);
}
}
}
s += '</div>';
return s;
};
this.getIcon1 = function(theNode) {
var parentNode = this.nodes[theNode.pid];
var src = '';
if(theNode._lastChildId) {
if(theNode._isOpen) {
if(theNode.id == 0) {
return icon.minus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.minusBottom;
} else {
src = icon.minusMiddle;
}
} else {
if(theNode.id == 0) {
return icon.plus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.plusBottom;
} else {
src = icon.plusMiddle;
}
}
} else {
if(theNode.id == parentNode._lastChildId) {
src = icon.lineBottom;
} else {
src = icon.lineMiddle;
}
}
return src;
};
this.getIcon2 = function(theNode) {
var src = '';
if(theNode.id == 0 ) {
return icon.root;
}
if(theNode._lastChildId) {
if(theNode._isOpen) {
src = icon.folderOpen;
} else {
src = icon.folder;
}
} else {
src = icon.file;
}
return src;
};
this.getName = function(theNode) {
if(theNode.url) {
return '<a href="'+theNode.url+'" target="' + theNode.target + '"> '+theNode.name+'</a>';
} else {
return theNode.name;
}
};
this.switchDisplay = function(nodeId) {
eval('var theTree = ' + treeName);
var theNode = theTree.nodes[nodeId];
if($('nodes_' + nodeId).style.display == 'none') {
theTree.openIds = updatestring(theTree.openIds, nodeId);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = true;
$('nodes_' + nodeId).style.display = '';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
} else {
theTree.openIds = updatestring(theTree.openIds, nodeId, true);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = false;
$('nodes_' + nodeId).style.display = 'none';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
}
};
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: bbcode.js 31520 2012-09-05 05:50:12Z chenmengshu $
*/
var re, DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
EXTRAFUNC['bbcode2html'] = [];
EXTRAFUNC['html2bbcode'] = [];
function addslashes(str) {
return preg_replace(['\\\\', '\\\'', '\\\/', '\\\(', '\\\)', '\\\[', '\\\]', '\\\{', '\\\}', '\\\^', '\\\$', '\\\?', '\\\.', '\\\*', '\\\+', '\\\|'], ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|'], str);
}
function atag(aoptions, text) {
if(trim(text) == '') {
return '';
}
var pend = parsestyle(aoptions, '', '');
href = getoptionvalue('href', aoptions);
if(href.substr(0, 11) == 'javascript:') {
return trim(recursion('a', text, 'atag'));
}
return pend['prepend'] + '[url=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/url]' + pend['append'];
}
function bbcode2html(str) {
if(str == '') {
return '';
}
if(typeof(parsetype) == 'undefined') {
parsetype = 0;
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode && parsetype != 1) {
str = str.replace(/\[code\]([\s\S]+?)\[\/code\]/ig, function($1, $2) {return parsecode($2);});
}
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'html', false);
}
}
for(i in EXTRAFUNC['bbcode2html']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['bbcode2html'][i] + '()');
} catch(e) {}
}
if(!fetchCheckbox('smileyoff') && allowsmilies) {
if(typeof smilies_type == 'object') {
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
re = new RegExp(preg_quote(smilies_array[typeid][page][i][1]), "g");
str = str.replace(re, '<img src="' + STATICURL + 'image/smiley/' + smilies_type['_' + typeid][1] + '/' + smilies_array[typeid][page][i][2] + '" border="0" smilieid="' + smilies_array[typeid][page][i][0] + '" alt="' + smilies_array[typeid][page][i][1] + '" />');
}
}
}
}
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = clearcode(str);
str = str.replace(/\[url\]\s*((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.)([^\[\"']+?)\s*\[\/url\]/ig, function($1, $2, $3, $4) {return cuturl($2 + $4);});
str = str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\r\n\[\"']+?)\]([\s\S]+?)\[\/url\]/ig, '<a href="$1$3" target="_blank">$4</a>');
str = str.replace(/\[email\](.*?)\[\/email\]/ig, '<a href="mailto:$1">$1</a>');
str = str.replace(/\[email=(.[^\[]*)\](.*?)\[\/email\]/ig, '<a href="mailto:$1" target="_blank">$2</a>');
str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">');
str = str.replace(/\[backcolor=([^\[\<]+?)\]/ig, '<font style="background-color:$1">');
str = str.replace(/\[size=(\d+?)\]/ig, '<font size="$1">');
str = str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]/ig, '<font style="font-size: $1">');
str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">');
str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<div align="$1">');
str = str.replace(/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/ig, '<p style="line-height: $1px; text-indent: $2em; text-align: $3;">');
str = str.replace(/\[float=left\]/ig, '<br style="clear: both"><span style="float: left; margin-right: 5px;">');
str = str.replace(/\[float=right\]/ig, '<br style="clear: both"><span style="float: right; margin-left: 5px;">');
if(parsetype != 1) {
str = str.replace(/\[quote]([\s\S]*?)\[\/quote\]\s?\s?/ig, '<div class="quote"><blockquote>$1</blockquote></div>\n');
}
re = /\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*([\s\S]+?)\s*\[\/table\]/ig;
for (i = 0; i < 4; i++) {
str = str.replace(re, function($1, $2, $3, $4) {return parsetable($2, $3, $4);});
}
str = preg_replace([
'\\\[\\\/color\\\]', '\\\[\\\/backcolor\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[\\\/p\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[s\\\]', '\\\[\\\/s\\\]', '\\\[hr\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
'\\\[list=A\\\]', '\\s?\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]', '\\\[\\\/float\\\]'
], [
'</font>', '</font>', '</font>', '</font>', '</div>', '</p>', '<b>', '</b>', '<i>',
'</i>', '<u>', '</u>', '<strike>', '</strike>', '<hr class="l" />', '<ul>', '<ul type=1 class="litype_1">', '<ul type=a class="litype_2">',
'<ul type=A class="litype_3">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
], str, 'g');
}
if(!fetchCheckbox('bbcodeoff')) {
if(allowimgcode) {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src="$1" border="0" alt="" style="max-width:400px" />');
str = str.replace(/\[attachimg\](\d+)\[\/attachimg\]/ig, function ($1, $2) {
if(!$('image_' + $2)) {
return '';
}
width = $('image_' + $2).getAttribute('cwidth');
if(!width) {
re = /cwidth=(["']?)(\d+)(\1)/i;
var matches = re.exec($('image_' + $2).outerHTML);
if(matches != null) {
width = matches[2];
}
}
return '<img src="' + $('image_' + $2).src + '" border="0" aid="attachimg_' + $2 + '" width="' + width + '" alt="" />';
});
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, function ($1, $2, $3, $4) {return '<img' + ($2 > 0 ? ' width="' + $2 + '"' : '') + ($3 > 0 ? ' iheight="' + $3 + '"' : '') + ' src="' + $4 + '" border="0" alt="" />'});
} else {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
}
}
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
return $2 + preg_replace(['\t', ' ', ' ', '(\r\n|\n|\r)'], [' ', ' ', ' ', '<br />'], $3);
});
} else {
str = str.replace(/<script[^\>]*?>([^\x00]*?)<\/script>/ig, '');
}
return str;
}
function clearcode(str) {
str= str.replace(/\[url\]\[\/url\]/ig, '', str);
str= str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\s\[\"']+?)\]\[\/url\]/ig, '', str);
str= str.replace(/\[email\]\[\/email\]/ig, '', str);
str= str.replace(/\[email=(.[^\[]*)\]\[\/email\]/ig, '', str);
str= str.replace(/\[color=([^\[\<]+?)\]\[\/color\]/ig, '', str);
str= str.replace(/\[size=(\d+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[font=([^\[\<]+?)\]\[\/font\]/ig, '', str);
str= str.replace(/\[align=([^\[\<]+?)\]\[\/align\]/ig, '', str);
str= str.replace(/\[p=(\d{1,2}), (\d{1,2}), (left|center|right)\]\[\/p\]/ig, '', str);
str= str.replace(/\[float=([^\[\<]+?)\]\[\/float\]/ig, '', str);
str= str.replace(/\[quote\]\[\/quote\]/ig, '', str);
str= str.replace(/\[code\]\[\/code\]/ig, '', str);
str= str.replace(/\[table\]\[\/table\]/ig, '', str);
str= str.replace(/\[free\]\[\/free\]/ig, '', str);
str= str.replace(/\[b\]\[\/b]/ig, '', str);
str= str.replace(/\[u\]\[\/u]/ig, '', str);
str= str.replace(/\[i\]\[\/i]/ig, '', str);
str= str.replace(/\[s\]\[\/s]/ig, '', str);
return str;
}
function cuturl(url) {
var length = 65;
var urllink = '<a href="' + (url.toLowerCase().substr(0, 4) == 'www.' ? 'http://' + url : url) + '" target="_blank">';
if(url.length > length) {
url = url.substr(0, parseInt(length * 0.5)) + ' ... ' + url.substr(url.length - parseInt(length * 0.3));
}
urllink += url + '</a>';
return urllink;
}
function dstag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
var pend = parsestyle(options, '', '');
var prepend = pend['prepend'];
var append = pend['append'];
if(in_array(tagname, ['div', 'p'])) {
align = getoptionvalue('align', options);
if(in_array(align, ['left', 'center', 'right'])) {
prepend = '[align=' + align + ']' + prepend;
append += '[/align]';
} else {
append += '\n';
}
}
return prepend + recursion(tagname, text, 'dstag') + append;
}
function ptag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
if(trim(options) == '') {
return text + '\n';
}
var lineHeight = null;
var textIndent = null;
var align, re, matches;
re = /line-height\s?:\s?(\d{1,3})px/i;
matches = re.exec(options);
if(matches != null) {
lineHeight = matches[1];
}
re = /text-indent\s?:\s?(\d{1,3})em/i;
matches = re.exec(options);
if(matches != null) {
textIndent = matches[1];
}
re = /text-align\s?:\s?(left|center|right)/i;
matches = re.exec(options);
if(matches != null) {
align = matches[1];
} else {
align = getoptionvalue('align', options);
}
align = in_array(align, ['left', 'center', 'right']) ? align : 'left';
style = getoptionvalue('style', options);
style = preg_replace(['line-height\\\s?:\\\s?(\\\d{1,3})px', 'text-indent\\\s?:\\\s?(\\\d{1,3})em', 'text-align\\\s?:\\\s?(left|center|right)'], '', style);
if(lineHeight === null && textIndent === null) {
return '[align=' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/align]';
} else {
return '[p=' + lineHeight + ', ' + textIndent + ', ' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/p]';
}
}
function fetchCheckbox(cbn) {
return $(cbn) && $(cbn).checked == true ? 1 : 0;
}
function fetchoptionvalue(option, text) {
if((position = strpos(text, option)) !== false) {
delimiter = position + option.length;
if(text.charAt(delimiter) == '"') {
delimchar = '"';
} else if(text.charAt(delimiter) == '\'') {
delimchar = '\'';
} else {
delimchar = ' ';
}
delimloc = strpos(text, delimchar, delimiter + 1);
if(delimloc === false) {
delimloc = text.length;
} else if(delimchar == '"' || delimchar == '\'') {
delimiter++;
}
return trim(text.substr(delimiter, delimloc - delimiter));
} else {
return '';
}
}
function fonttag(fontoptions, text) {
var prepend = '';
var append = '';
var tags = new Array();
tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
for(bbcode in tags) {
optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
if(optionvalue) {
prepend += '[' + bbcode + '=' + optionvalue + ']';
append = '[/' + bbcode + ']' + append;
}
}
var pend = parsestyle(fontoptions, prepend, append);
return pend['prepend'] + recursion('font', text, 'fonttag') + pend['append'];
}
function getoptionvalue(option, text) {
re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
var matches = re.exec(text);
if(matches != null) {
return trim(matches[3]);
}
return '';
}
function html2bbcode(str) {
if((allowhtml && fetchCheckbox('htmlon')) || trim(str) == '') {
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*aid=[^>]*)>/ig, function($1, $2) {return imgtag($2);});
return str;
}
str = str.replace(/<div\sclass=["']?blockcode["']?>[\s\S]*?<blockquote>([\s\S]+?)<\/blockquote>[\s\S]*?<\/div>/ig, function($1, $2) {return codetag($2);});
str = preg_replace(['<style.*?>[\\\s\\\S]*?<\/style>', '<script.*?>[\\\s\\\S]*?<\/script>', '<noscript.*?>[\\\s\\\S]*?<\/noscript>', '<select.*?>[\s\S]*?<\/select>', '<object.*?>[\s\S]*?<\/object>', '<!--[\\\s\\\S]*?-->', ' on[a-zA-Z]{3,16}\\\s?=\\\s?"[\\\s\\\S]*?"'], '', str);
str= str.replace(/(\r\n|\n|\r)/ig, '');
str= str.replace(/&((#(32|127|160|173))|shy|nbsp);/ig, ' ');
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'bbcode', false);
}
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<br\s+?style=(["']?)clear: both;?(\1)[^\>]*>/ig, '');
str = str.replace(/<br[^\>]*>/ig, "\n");
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = preg_replace([
'<table[^>]*float:\\\s*(left|right)[^>]*><tbody><tr><td>\\\s*([\\\s\\\S]+?)\\\s*<\/td><\/tr></tbody><\/table>',
'<table([^>]*(width|background|background-color|backcolor)[^>]*)>',
'<table[^>]*>',
'<tr[^>]*(?:background|background-color|backcolor)[:=]\\\s*(["\']?)([\(\)\\\s%,#\\\w]+)(\\1)[^>]*>',
'<tr[^>]*>',
'(<t[dh]([^>]*(left|center|right)[^>]*)>)\\\s*([\\\s\\\S]+?)\\\s*(<\/t[dh]>)',
'<t[dh]([^>]*(width|colspan|rowspan)[^>]*)>',
'<t[dh][^>]*>',
'<\/t[dh]>',
'<\/tr>',
'<\/table>',
'<h\\\d[^>]*>',
'<\/h\\\d>'
], [
function($1, $2, $3) {return '[float=' + $2 + ']' + $3 + '[/float]';},
function($1, $2) {return tabletag($2);},
'[table]\n',
function($1, $2, $3) {return '[tr=' + $3 + ']';},
'[tr]',
function($1, $2, $3, $4, $5, $6) {return $2 + '[align=' + $4 + ']' + $5 + '[/align]' + $6},
function($1, $2) {return tdtag($2);},
'[td]',
'[/td]',
'[/tr]\n',
'[/table]',
'[b]',
'[/b]'
], str);
str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
str = str.replace(/<hr[^>]*>/ig, "[hr]");
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, '$4');
str = str.replace(/<div[^>]*quote[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[quote]$1[/quote]");
str = str.replace(/<div[^>]*blockcode[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[code]$1[/code]");
str = recursion('b', str, 'simpletag', 'b');
str = recursion('strong', str, 'simpletag', 'b');
str = recursion('i', str, 'simpletag', 'i');
str = recursion('em', str, 'simpletag', 'i');
str = recursion('u', str, 'simpletag', 'u');
str = recursion('strike', str, 'simpletag', 's');
str = recursion('a', str, 'atag');
str = recursion('font', str, 'fonttag');
str = recursion('blockquote', str, 'simpletag', 'indent');
str = recursion('ol', str, 'listtag');
str = recursion('ul', str, 'listtag');
str = recursion('div', str, 'dstag');
str = recursion('p', str, 'ptag');
str = recursion('span', str, 'fonttag');
}
str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
str = clearcode(str);
return preg_replace([' ', '<', '>', '&'], [' ', '<', '>', '&'], str);
}
function tablesimple(s, table, str) {
if(strpos(str, '[tr=') || strpos(str, '[td=')) {
return s;
} else {
return '[table=' + table + ']\n' + preg_replace(['\\\[tr\\\]', '\\\[\\\/td\\\]\\\s?\\\[td\\\]', '\\\[\\\/tr\\\]\s?', '\\\[td\\\]', '\\\[\\\/td\\\]', '\\\[\\\/td\\\]\\\[\\\/tr\\\]'], ['', '|', '', '', '', '', ''], str) + '[/table]';
}
}
function imgtag(attributes) {
var width = '';
var height = '';
re = /src=(["']?)([\s\S]*?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
var src = matches[2];
} else {
return '';
}
re = /(max-)?width\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null && !matches[1]) {
width = matches[2];
}
re = /height\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[1];
}
if(!width) {
re = /width=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
}
if(!height) {
re = /height=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[2];
}
}
re = /aid=(["']?)attachimg_(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
return '[attachimg]' + matches[2] + '[/attachimg]';
}
width = width > 0 ? width : 0;
height = height > 0 ? height : 0;
return width > 0 || height > 0 ?
'[img=' + width + ',' + height + ']' + src + '[/img]' :
'[img]' + src + '[/img]';
}
function listtag(listoptions, text, tagname) {
text = text.replace(/<li>(([\s\S](?!<\/li))*?)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (BROWSER.opera ? '</li>' : '');
text = recursion('li', text, 'litag');
var opentag = '[list]';
var listtype = fetchoptionvalue('type=', listoptions);
listtype = listtype != '' ? listtype : (tagname == 'ol' ? '1' : '');
if(in_array(listtype, ['1', 'a', 'A'])) {
opentag = '[list=' + listtype + ']';
}
return text ? opentag + '\n' + recursion(tagname, text, 'listtag') + '[/list]' : '';
}
function litag(listoptions, text) {
return '[*]' + text.replace(/(\s+)$/g, '') + '\n';
}
function parsecode(text) {
DISCUZCODE['num']++;
DISCUZCODE['html'][DISCUZCODE['num']] = '<div class="blockcode"><blockquote>' + htmlspecialchars(text) + '</blockquote></div>';
return "[\tDISCUZ_CODE_" + DISCUZCODE['num'] + "\t]";
}
function parsestyle(tagoptions, prepend, append) {
var searchlist = [
['align', true, 'text-align:\\s*(left|center|right);?', 1],
['float', true, 'float:\\s*(left|right);?', 1],
['color', true, '(^|[;\\s])color:\\s*([^;]+);?', 2],
['backcolor', true, '(^|[;\\s])background-color:\\s*([^;]+);?', 2],
['font', true, 'font-family:\\s*([^;]+);?', 1],
['size', true, 'font-size:\\s*(\\d+(\\.\\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
['size', true, 'font-size:\\s*(x\\-small|small|medium|large|x\\-large|xx\\-large|\\-webkit\\-xxx\\-large);?', 1, 'size'],
['b', false, 'font-weight:\\s*(bold);?'],
['i', false, 'font-style:\\s*(italic);?'],
['u', false, 'text-decoration:\\s*(underline);?'],
['s', false, 'text-decoration:\\s*(line-through);?']
];
var sizealias = {'x-small':1,'small':2,'medium':3,'large':4,'x-large':5,'xx-large':6,'-webkit-xxx-large':7};
var style = getoptionvalue('style', tagoptions);
re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/i;
style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});
var len = searchlist.length;
for(var i = 0; i < len; i++) {
searchlist[i][4] = !searchlist[i][4] ? '' : searchlist[i][4];
re = new RegExp(searchlist[i][2], "ig");
match = re.exec(style);
if(match != null) {
opnvalue = match[searchlist[i][3]];
if(searchlist[i][4] == 'size') {
opnvalue = sizealias[opnvalue];
}
prepend += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
append = '[/' + searchlist[i][0] + ']' + append;
}
}
return {'prepend' : prepend, 'append' : append};
}
function parsetable(width, bgcolor, str) {
if(isUndefined(width)) {
var width = '';
} else {
try {
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
} catch(e) { width = ''; }
}
if(isUndefined(str)) {
return;
}
if(strpos(str, '[/tr]') === false && strpos(str, '[/td]') === false) {
var rows = str.split('\n');
var s = '';
for(i = 0;i < rows.length;i++) {
s += '<tr><td>' + preg_replace(['\r', '\\\\\\\|', '\\\|', '\\\\n'], ['', '|', '</td><td>', '\n'], rows[i]) + '</td></tr>';
}
str = s;
simple = ' simpletable';
} else {
simple = '';
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2, $3) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' width="' + $3 + '"' : '') + '>';
});
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4, $5) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' colspan="' + $3 + '"' : '') + ($4 ? ' rowspan="' + $4 + '"' : '') + ($5 ? ' width="' + $5 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2) {
return '</td><td' + ($2 ? ' width="' + $2 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4) {
return '</td><td' + ($2 ? ' colspan="' + $2 + '"' : '') + ($3 ? ' rowspan="' + $3 + '"' : '') + ($4 ? ' width="' + $4 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[\/tr\]\s*/ig, '</td></tr>');
str = str.replace(/<td> <\/td>/ig, '<td> </td>');
}
return '<table ' + (width == '' ? '' : 'width="' + width + '" ') + 'class="t_table"' + (isUndefined(bgcolor) ? '' : ' style="background-color: ' + bgcolor + '"') + simple +'>' + str + '</table>';
}
function preg_quote(str) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, "\\$1");
}
function recursion(tagname, text, dofunction, extraargs) {
if(extraargs == null) {
extraargs = '';
}
tagname = tagname.toLowerCase();
var open_tag = '<' + tagname;
var open_tag_len = open_tag.length;
var close_tag = '</' + tagname + '>';
var close_tag_len = close_tag.length;
var beginsearchpos = 0;
do {
var textlower = text.toLowerCase();
var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
if(tagbegin == -1) {
break;
}
var strlen = text.length;
var inquote = '';
var found = false;
var tagnameend = false;
var optionend = 0;
var t_char = '';
for(optionend = tagbegin; optionend <= strlen; optionend++) {
t_char = text.charAt(optionend);
if((t_char == '"' || t_char == "'") && inquote == '') {
inquote = t_char;
} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
inquote = '';
} else if(t_char == '>' && !inquote) {
found = true;
break;
} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
tagnameend = optionend;
}
}
if(!found) {
break;
}
if(!tagnameend) {
tagnameend = optionend;
}
var offset = optionend - (tagbegin + open_tag_len);
var tagoptions = text.substr(tagbegin + open_tag_len, offset);
var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);
if(acttagname != tagname) {
beginsearchpos = optionend;
continue;
}
var tagend = textlower.indexOf(close_tag, optionend);
if(tagend == -1) {
break;
}
var nestedopenpos = textlower.indexOf(open_tag, optionend);
while(nestedopenpos != -1 && tagend != -1) {
if(nestedopenpos > tagend) {
break;
}
tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
}
if(tagend == -1) {
beginsearchpos = optionend;
continue;
}
var localbegin = optionend + 1;
var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);
text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);
beginsearchpos = tagbegin + localtext.length;
} while(tagbegin != -1);
return text;
}
function simpletag(options, text, tagname, parseto) {
if(trim(text) == '') {
return '';
}
text = recursion(tagname, text, 'simpletag', parseto);
return '[' + parseto + ']' + text + '[/' + parseto + ']';
}
function smileycode(smileyid) {
if(typeof smilies_type != 'object') return;
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
if(smilies_array[typeid][page][i][0] == smileyid) {
return smilies_array[typeid][page][i][1];
break;
}
}
}
}
}
function strpos(haystack, needle, _offset) {
if(isUndefined(_offset)) {
_offset = 0;
}
var _index = haystack.toLowerCase().indexOf(needle.toLowerCase(), _offset);
return _index == -1 ? false : _index;
}
function tabletag(attributes) {
var width = '';
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
(matches[2] <= 560 ? matches[2] : '98%');
} else {
re = /width\s?:\s?(\d{1,4})([px|%])/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] + '%' : '98%') : (matches[1] <= 560 ? matches[1] : '98%');
}
}
var bgcolor = '';
re = /(?:background|background-color|bgcolor)[:=]\s*(["']?)((rgb\(\d{1,3}%?,\s*\d{1,3}%?,\s*\d{1,3}%?\))|(#[0-9a-fA-F]{3,6})|([a-zA-Z]{1,20}))(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
bgcolor = matches[2];
width = width ? width : '98%';
}
return bgcolor ? '[table=' + width + ',' + bgcolor + ']\n' : (width ? '[table=' + width + ']\n' : '[table]\n');
}
function tdtag(attributes) {
var colspan = 1;
var rowspan = 1;
var width = '';
re = /colspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
colspan = matches[2];
}
re = /rowspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
rowspan = matches[2];
}
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
return in_array(width, ['', '0', '100%']) ?
(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
(colspan == 1 && rowspan == 1 ? '[td=' + width + ']' : '[td=' + colspan + ',' + rowspan + ',' + width + ']');
}
if(typeof jsloaded == 'function') {
jsloaded('bbcode');
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_post.js 32414 2013-01-15 03:30:57Z monkey $
*/
var forum_post_inited = true;
var postSubmited = false;
var AID = {0:1,1:1};
var UPLOADSTATUS = -1;
var UPLOADFAILED = UPLOADCOMPLETE = AUTOPOST = 0;
var CURRENTATTACH = '0';
var FAILEDATTACHS = '';
var UPLOADWINRECALL = null;
var imgexts = typeof imgexts == 'undefined' ? 'jpg, jpeg, gif, png, bmp' : imgexts;
var ATTACHORIMAGE = '0';
var STATUSMSG = {
'-1' : '内部服务器错误',
'0' : '上传成功',
'1' : '不支持此类扩展名',
'2' : '服务器限制无法上传那么大的附件',
'3' : '用户组限制无法上传那么大的附件',
'4' : '不支持此类扩展名',
'5' : '文件类型限制无法上传那么大的附件',
'6' : '今日您已无法上传更多的附件',
'7' : '请选择图片文件(' + imgexts + ')',
'8' : '附件文件无法保存',
'9' : '没有合法的文件被上传',
'10' : '非法操作',
'11' : '今日您已无法上传那么大的附件'
};
EXTRAFUNC['validator'] = [];
function checkFocus() {
var obj = wysiwyg ? editwin : textobj;
if(!obj.hasfocus) {
obj.focus();
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && $('postsubmit')) {
if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate($('postform'))) {
doane(event);
return;
}
postSubmited = true;
$('postsubmit').disabled = true;
$('postform').submit();
}
if(event.keyCode == 9) {
doane(event);
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : theform.message.value;
if(!theform.parseurloff.checked) {
message = parseurl(message);
}
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
if(!tradepost) {
var tradepost = 0;
}
function validate(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : theform.message.value;
if(!theform.parseurloff.checked) {
message = parseurl(message);
}
if(($('postsubmit').name != 'replysubmit' && !($('postsubmit').name == 'editsubmit' && !isfirstpost) && theform.subject.value == "") || !sortid && !special && trim(message) == "") {
showError('抱歉,您尚未输入标题或内容');
return false;
} else if(mb_strlen(theform.subject.value) > 80) {
showError('您的标题超过 80 个字符的限制');
return false;
}
if(ispicstyleforum == 1 && ATTACHORIMAGE == 0 && isfirstpost) {
}
if(in_array($('postsubmit').name, ['topicsubmit', 'editsubmit'])) {
if(theform.typeid && (theform.typeid.options && theform.typeid.options[theform.typeid.selectedIndex].value == 0) && typerequired) {
showError('请选择主题对应的分类');
return false;
}
if(theform.sortid && (theform.sortid.options && theform.sortid.options[theform.sortid.selectedIndex].value == 0) && sortrequired) {
showError('请选择主题对应的分类信息');
return false;
}
}
for(i in EXTRAFUNC['validator']) {
try {
eval('var v = ' + EXTRAFUNC['validator'][i] + '()');
if(!v) {
return false;
}
} catch(e) {}
}
if(!disablepostctrl && !sortid && !special && ((postminchars != 0 && mb_strlen(message) < postminchars) || (postmaxchars != 0 && mb_strlen(message) > postmaxchars))) {
showError('您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(message) + ' 字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节');
return false;
}
if(UPLOADSTATUS == 0) {
if(!confirm('您有等待上传的附件,确认不上传这些附件吗?')) {
return false;
}
} else if(UPLOADSTATUS == 1) {
showDialog('您有正在上传的附件,请稍候,上传完成后帖子将会自动发表...', 'notice');
AUTOPOST = 1;
return false;
}
if(isfirstpost && $('adddynamic') != null && $('adddynamic').checked && $('postsave') != null && isNaN(parseInt($('postsave').value)) && ($('readperm') != null && $('readperm').value || $('price') != null && $('price').value)) {
if(confirm('由于您设置了阅读权限或出售帖,您确认还转播给您的听众看吗?') == false) {
return false;
}
}
theform.message.value = message;
if($('postsubmit').name == 'editsubmit') {
postsubmit(theform);
return true;
} else if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit'])) {
if(seccodecheck || secqaacheck) {
var chk = 1, chkv = '';
if(secqaacheck) {
chkv = $('checksecqaaverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') != -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') == -1) {
showError('验证问答错误,请重新填写');
chk = 0;
}
}
if(seccodecheck) {
chkv = $('checkseccodeverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') !== -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') === -1) {
showError('验证码错误,请重新填写');
chk = 0;
}
}
if(chk) {
postsubmit(theform);
}
} else {
postsubmit(theform);
}
return false;
}
}
function postsubmit(theform) {
if($(editorid + '_attachlist')) {
$('postbox').appendChild($(editorid + '_attachlist'));
$(editorid + '_attachlist').style.display = 'none';
}
if($(editorid + '_imgattachlist')) {
$('postbox').appendChild($(editorid + '_imgattachlist'));
$(editorid + '_imgattachlist').style.display = 'none';
}
hideMenu();
theform.replysubmit ? theform.replysubmit.disabled = true : (theform.editsubmit ? theform.editsubmit.disabled = true : theform.topicsubmit.disabled = true);
theform.submit();
}
function relatekw(subject, message) {
if(isUndefined(subject) || subject == -1) {
subject = $('subject').value;
subject = subject.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
subject = subject.replace(/\s{2,}/ig, ' ');
}
if(isUndefined(message) || message == -1) {
message = getEditorContents();
message = message.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
message = message.replace(/\s{2,}/ig, ' ');
}
subject = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(subject) : subject);
message = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(message) : message);
message = message.replace(/&/ig, '', message).substr(0, 500);
ajaxget('forum.php?mod=relatekw&subjectenc=' + subject + '&messageenc=' + message, 'tagselect');
}
function switchicon(iconid, obj) {
$('iconid').value = iconid;
$('icon_img').src = obj.src;
hideMenu();
}
function clearContent() {
if(wysiwyg) {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
} else {
textobj.value = '';
}
}
function uploadNextAttach() {
var str = $('attachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
var att = CURRENTATTACH.split('|');
var sizelimit = '';
if(arr[4] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[4] == 'perday') {
sizelimit = '(不能超过 ' + arr[5] + ' 字节)';
} else if(arr[4] > 0) {
sizelimit = '(不能超过 ' + arr[4] + ' 字节)';
}
uploadAttach(parseInt(att[0]), arr[0] == 'DISCUZUPLOAD' ? parseInt(arr[1]) : -1, att[1], sizelimit);
}
function uploadAttach(curId, statusid, prefix, sizelimit) {
prefix = isUndefined(prefix) ? '' : prefix;
var nextId = 0;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
nextId = i;
if(curId == 0) {
break;
} else {
if(i > curId) {
break;
}
}
}
}
if(nextId == 0) {
return;
}
CURRENTATTACH = nextId + '|' + prefix;
if(curId > 0) {
if(statusid == 0) {
UPLOADCOMPLETE++;
} else {
FAILEDATTACHS += '<br />' + mb_cutstr($(prefix + 'attachnew_' + curId).value.substr($(prefix + 'attachnew_' + curId).value.replace(/\\/g, '/').lastIndexOf('/') + 1), 25) + ': ' + STATUSMSG[statusid] + sizelimit;
UPLOADFAILED++;
}
$(prefix + 'cpdel_' + curId).innerHTML = '<img src="' + IMGDIR + '/check_' + (statusid == 0 ? 'right' : 'error') + '.gif" alt="' + STATUSMSG[statusid] + '" />';
if(nextId == curId || in_array(statusid, [6, 8])) {
if(prefix == 'img') {
updateImageList();
} else {
updateAttachList();
}
if(UPLOADFAILED > 0) {
showDialog('附件上传完成!成功 ' + UPLOADCOMPLETE + ' 个,失败 ' + UPLOADFAILED + ' 个:' + FAILEDATTACHS);
FAILEDATTACHS = '';
}
UPLOADSTATUS = 2;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
reAddAttach(prefix, i)
}
}
$(prefix + 'uploadbtn').style.display = '';
$(prefix + 'uploading').style.display = 'none';
if(AUTOPOST) {
hideMenu();
validate($('postform'));
} else if(UPLOADFAILED == 0 && (prefix == 'img' || prefix == '')) {
showDialog('附件上传完成!', 'right', null, null, 0, null, null, null, null, 3);
}
UPLOADFAILED = UPLOADCOMPLETE = 0;
CURRENTATTACH = '0';
FAILEDATTACHS = '';
return;
}
} else {
$(prefix + 'uploadbtn').style.display = 'none';
$(prefix + 'uploading').style.display = '';
}
$(prefix + 'cpdel_' + nextId).innerHTML = '<img src="' + IMGDIR + '/loading.gif" alt="上传中..." />';
UPLOADSTATUS = 1;
$(prefix + 'attachform_' + nextId).submit();
}
function addAttach(prefix) {
var id = AID[prefix ? 1 : 0];
var tags, newnode, i;
prefix = isUndefined(prefix) ? '' : prefix;
newnode = $(prefix + 'attachbtnhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'Filedata') {
tags[i].id = prefix + 'attachnew_' + id;
tags[i].onchange = function() {insertAttach(prefix, id);};
tags[i].unselectable = 'on';
} else if(tags[i].name == 'attachid') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('form');
tags[0].name = tags[0].id = prefix + 'attachform_' + id;
$(prefix + 'attachbtn').appendChild(newnode);
newnode = $(prefix + 'attachbodyhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == prefix + 'localid[]') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == prefix + 'localfile[]') {
tags[i].id = prefix + 'localfile_' + id;
} else if(tags[i].id == prefix + 'cpdel[]') {
tags[i].id = prefix + 'cpdel_' + id;
} else if(tags[i].id == prefix + 'localno[]') {
tags[i].id = prefix + 'localno_' + id;
} else if(tags[i].id == prefix + 'deschidden[]') {
tags[i].id = prefix + 'deschidden_' + id;
}
}
AID[prefix ? 1 : 0]++;
newnode.style.display = 'none';
$(prefix + 'attachbody').appendChild(newnode);
}
function insertAttach(prefix, id) {
var path = $(prefix + 'attachnew_' + id).value;
var extpos = path.lastIndexOf('.');
var ext = extpos == -1 ? '' : path.substr(extpos + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $(prefix + 'attachnew_' + id).value.substr($(prefix + 'attachnew_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
var filename = mb_cutstr(localfile, 30);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
reAddAttach(prefix, id);
showError('对不起,不支持上传此类扩展名的附件。');
return;
}
if(prefix == 'img' && imgexts.indexOf(ext) == -1) {
reAddAttach(prefix, id);
showError('请选择图片文件(' + imgexts + ')');
return;
}
$(prefix + 'cpdel_' + id).innerHTML = '<a href="javascript:;" class="d" onclick="reAddAttach(\'' + prefix + '\', ' + id + ')">删除</a>';
$(prefix + 'localfile_' + id).innerHTML = '<span>' + filename + '</span>';
$(prefix + 'attachnew_' + id).style.display = 'none';
$(prefix + 'deschidden_' + id).style.display = '';
$(prefix + 'deschidden_' + id).title = localfile;
$(prefix + 'localno_' + id).parentNode.parentNode.style.display = '';
addAttach(prefix);
UPLOADSTATUS = 0;
}
function reAddAttach(prefix, id) {
$(prefix + 'attachbody').removeChild($(prefix + 'localno_' + id).parentNode.parentNode);
$(prefix + 'attachbtn').removeChild($(prefix + 'attachnew_' + id).parentNode.parentNode);
$(prefix + 'attachbody').innerHTML == '' && addAttach(prefix);
$('localimgpreview_' + id) ? document.body.removeChild($('localimgpreview_' + id)) : null;
}
function delAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('attach_' + id)) {
$('attach_' + id).style.display = 'none';
ATTACHNUM['attach' + (type ? 'un' : '') + 'used']--;
updateattachnum('attach');
}
}
appendAttachDel(ids);
}
function delImgAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('image_td_' + id)) {
$('image_td_' + id).className = 'imgdeleted';
$('image_' + id).onclick = null;
$('image_desc_' + id).disabled = true;
ATTACHNUM['image' + (type ? 'un' : '') + 'used']--;
updateattachnum('image');
}
}
appendAttachDel(ids);
}
function appendAttachDel(ids) {
if(!ids) {
return;
}
var aids = '';
for(id in ids) {
aids += '&aids[]=' + id;
}
var x = new Ajax();
x.get('forum.php?mod=ajax&action=deleteattach&inajax=yes&tid=' + (typeof tid == 'undefined' ? 0 : tid) + '&pid=' + (typeof pid == 'undefined' ? 0 : pid) + aids + ($('modthreadkey') ? '&modthreadkey=' + $('modthreadkey').value : ''), function() {});
if($('delattachop')) {
$('delattachop').value = 1;
}
}
function updateAttach(aid) {
objupdate = $('attachupdate'+aid);
obj = $('attach' + aid);
if(!objupdate.innerHTML) {
obj.style.display = 'none';
objupdate.innerHTML = '<input type="file" name="attachupdate[paid' + aid + ']"><a href="javascript:;" onclick="updateAttach(' + aid + ')">取消</a>';
} else {
obj.style.display = '';
objupdate.innerHTML = '';
}
}
function updateattachnum(type) {
ATTACHNUM[type + 'used'] = ATTACHNUM[type + 'used'] >= 0 ? ATTACHNUM[type + 'used'] : 0;
ATTACHNUM[type + 'unused'] = ATTACHNUM[type + 'unused'] >= 0 ? ATTACHNUM[type + 'unused'] : 0;
var num = ATTACHNUM[type + 'used'] + ATTACHNUM[type + 'unused'];
if(num) {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = '包含 ' + num + (type == 'image' ? ' 个图片附件' : ' 个附件');
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = '';
}
ATTACHORIMAGE = 1;
} else {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = type == 'image' ? '图片' : '附件';
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = 'none';
}
}
}
function swfHandler(action, type) {
if(action == 2) {
if(type == 'image') {
updateImageList();
} else {
updateAttachList();
}
}
}
function updateAttachList(action, aids) {
ajaxget('forum.php?mod=ajax&action=attachlist' + (!action ? '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'attachlist');
switchAttachbutton('attachlist');$('attach_tblheader').style.display = $('attach_notice').style.display = '';
}
function updateImageList(action, aids) {
ajaxget('forum.php?mod=ajax&action=imagelist' + (!action ? '&pid=' + pid + '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'imgattachlist');
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
}
function updateDownImageList(msg) {
if(msg == '') {
showError('抱歉,暂无远程附件');
} else {
ajaxget('forum.php?mod=ajax&action=imagelist&pid=' + pid + '&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'imgattachlist', null, null, null, function(){if(wysiwyg) {editdoc.body.innerHTML = msg;switchEditor(0);switchEditor(1)} else {textobj.value = msg;}});
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
showDialog('远程附件下载完成!', 'right', null, null, 0, null, null, null, null, 3);
}
}
function switchButton(btn, type) {
var btnpre = editorid + '_btn_';
if(!$(btnpre + btn) || !$(editorid + '_' + btn)) {
return;
}
var tabs = $(editorid + '_' + type + '_ctrl').getElementsByTagName('LI');
$(btnpre + btn).style.display = '';
$(editorid + '_' + btn).style.display = '';
$(btnpre + btn).className = 'current';
var btni = '';
for(i = 0;i < tabs.length;i++) {
if(tabs[i].id.indexOf(btnpre) !== -1) {
btni = tabs[i].id.substr(btnpre.length);
}
if(btni != btn) {
if(!$(editorid + '_' + btni) || !$(editorid + '_btn_' + btni)) {
continue;
}
$(editorid + '_' + btni).style.display = 'none';
$(editorid + '_btn_' + btni).className = '';
}
}
}
function uploadWindowstart() {
$('uploadwindowing').style.visibility = 'visible';
}
function uploadWindowload() {
$('uploadwindowing').style.visibility = 'hidden';
var str = $('uploadattachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
if(arr[0] == 'DISCUZUPLOAD' && arr[2] == 0) {
UPLOADWINRECALL(arr[3], arr[5], arr[6]);
hideWindow('upload', 0);
} else {
var sizelimit = '';
if(arr[7] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[7] == 'perday') {
sizelimit = '(不能超过 ' + arr[8] + ' 字节)';
} else if(arr[7] > 0) {
sizelimit = '(不能超过 ' + arr[7] + ' 字节)';
}
showError(STATUSMSG[arr[2]] + sizelimit);
}
if($('attachlimitnotice')) {
ajaxget('forum.php?mod=ajax&action=updateattachlimit&fid=' + fid, 'attachlimitnotice');
}
}
function uploadWindow(recall, type) {
var type = isUndefined(type) ? 'image' : type;
UPLOADWINRECALL = recall;
showWindow('upload', 'forum.php?mod=misc&action=upload&fid=' + fid + '&type=' + type, 'get', 0, {'zindex':601});
}
function updatetradeattach(aid, url, attachurl) {
$('tradeaid').value = aid;
$('tradeattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updateactivityattach(aid, url, attachurl) {
$('activityaid').value = aid;
$('activityattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updatesortattach(aid, url, attachurl, identifier) {
$('sortaid_' + identifier).value = aid;
$('sortattachurl_' + identifier).value = attachurl + '/' + url;
$('sortattach_image_' + identifier).innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function switchpollm(swt) {
t = $('pollchecked').checked && swt ? 2 : 1;
var v = '';
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
if(t == 2 && e.tagName == 'INPUT') {
v += e.value + '\n';
} else if(t == 1 && e.tagName == 'TEXTAREA') {
v += e.value;
}
}
}
}
if(t == 1) {
var a = v.split('\n');
var pcount = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
pcount++;
if(e.tagName == 'INPUT') e.value = '';
}
}
}
for(var i = 0; i < a.length - pcount + 2; i++) {
addpolloption();
}
var ii = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption') && e.tagName == 'INPUT' && a[ii]) {
e.value = a[ii++];
}
}
}
} else if(t == 2) {
$('postform').polloptions.value = trim(v);
}
$('postform').tpolloption.value = t;
if(swt) {
display('pollm_c_1');
display('pollm_c_2');
}
}
function addpolloption() {
if(curoptions < maxoptions) {
$('polloption_new').outerHTML = '<p>' + $('polloption_hidden').innerHTML + '</p>' + $('polloption_new').outerHTML;
curoptions++;
} else {
$('polloption_new').outerHTML = '<span>已达到最大投票数'+maxoptions+'</span>';
}
}
function delpolloption(obj) {
obj.parentNode.parentNode.removeChild(obj.parentNode);
curoptions--;
}
function insertsave(pid) {
var x = new Ajax();
x.get('forum.php?mod=misc&action=loadsave&inajax=yes&pid=' + pid + '&type=' + wysiwyg, function(str, x) {
insertText(str, str.length, 0);
});
}
function userdataoption(op) {
if(!op) {
saveUserdata('forum_'+discuz_uid, '');
display('rstnotice');
} else {
loadData();
checkFocus();
}
doane();
}
function attachoption(type, op) {
if(!op) {
if(type == 'attach') {
delAttach(ATTACHUNUSEDAID, 1);
ATTACHNUM['attachunused'] = 0;
display('attachnotice_attach');
} else {
delImgAttach(IMGUNUSEDAID, 1);
ATTACHNUM['imageunused'] = 0;
display('attachnotice_img');
}
} else if(op == 1) {
var obj = $('unusedwin') ? $('unusedwin') : $('unusedlist_' + type);
list = obj.getElementsByTagName('INPUT'), aids = '';
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused') && list[i].checked) {
aids += '|' + list[i].value;
}
}
if(aids) {
if(type == 'attach') {
updateAttachList(1, aids);
} else {
list = $('imgattachlist').getElementsByTagName('TD');
re = /^image\_td\_(\d+)$/;
for(i = 0;i < list.length;i++) {
var matches = re.exec(list[i].id);
if(matches != null) {
aids += '|' + matches[1];
}
}
updateImageList(1, aids);
}
}
display('attachnotice_' + type);
} else if(op == 2) {
showDialog('<div id="unusedwin" class="c altw" style="overflow:auto;height:100px;">' + $('unusedlist_' + type).innerHTML + '</div>' +
'<p class="o pns"><span class="z xg1"><label for="unusedwinchkall"><input id="unusedwinchkall" type="checkbox" onclick="attachoption(\'' + type + '\', 3)" checked="checked" />全选</label></span>' +
'<button onclick="attachoption(\'' + type + '\', 1);hideMenu(\'fwin_dialog\', \'dialog\')" class="pn pnc"><strong>使用</strong></button></p>', 'info', '未使用的' + (type == 'attach' ? '附件' : '图片'));
} else if(op == 3) {
list = $('unusedwin').getElementsByTagName('INPUT');
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused')) {
list[i].checked = $('unusedwinchkall').checked;
}
}
return;
}
doane();
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
seditor_insertunit('fastpost', txt);
}
function insertAttachimgTag(aid) {
var txt = '[attachimg]' + aid + '[/attachimg]';
seditor_insertunit('fastpost', txt);
}
function insertText(str) {
seditor_insertunit('fastpost', str);
}
function insertAllAttachTag() {
var attachListObj = $('e_attachlist').getElementsByTagName("tbody");
for(var i in attachListObj) {
if(typeof attachListObj[i] == "object") {
var attach = attachListObj[i];
var ids = attach.id.split('_');
if(ids[0] == 'attach') {
if($('attachname'+ids[1]) && attach.style.display != 'none') {
if(parseInt($('attachname'+ids[1]).getAttribute('isimage'))) {
insertAttachimgTag(ids[1]);
} else {
insertAttachTag(ids[1]);
}
var txt = wysiwyg ? '\r\n<br/><br/>\r\n' : '\r\n\r\n';
insertText(txt, strlen(txt), 0);
}
}
}
}
doane();
}
function selectAllSaveImg(state) {
var inputListObj = $('imgattachlist').getElementsByTagName("input");
for(i in inputListObj) {
if(typeof inputListObj[i] == "object" && inputListObj[i].id) {
var inputObj = inputListObj[i];
var ids = inputObj.id.split('_');
if(ids[0] == 'albumaidchk' && $('image_td_' + ids[1]).className != 'imgdeleted' && inputObj.checked != state) {
inputObj.click();
}
}
}
}
function showExtra(id) {
if ($(id+'_c').style.display == 'block') {
$(id+'_b').className = 'pn z';
$(id+'_c').style.display = 'none';
} else {
var extraButton = $('post_extra_tb').getElementsByTagName('label');
var extraForm = $('post_extra_c').getElementsByTagName('div');
for (i=0;i<extraButton.length;i++) {
extraButton[i].className = '';
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
$(id+'_b').className = 'a';
$(id+'_c').style.display = 'block';
}
}
function extraCheck(op) {
if(!op && $('extra_replycredit_chk')) {
$('extra_replycredit_chk').className = $('replycredit_extcredits').value > 0 && $('replycredit_times').value > 0 ? 'a' : '';
} else if(op == 1 && $('readperm')) {
$('extra_readperm_chk').className = $('readperm').value !== '' ? 'a' : '';
} else if(op == 2 && $('price')) {
$('extra_price_chk').className = $('price').value > 0 ? 'a' : '';
} else if(op == 3 && $('rushreply')) {
$('extra_rushreplyset_chk').className = $('rushreply').checked ? 'a' : '';
} else if(op == 4 && $('tags')) {
$('extra_tag_chk').className = $('tags').value !== '' ? 'a' : '';
} else if(op == 5 && $('cronpublish')) {
$('extra_pubdate_chk').className = $('cronpublish').checked ? 'a' : '';
}
}
function hidenFollowBtn(flag) {
var fobj = $('adddynamicspan');
if(fobj) {
if(flag) {
$('adddynamic').checked = !flag;
fobj.style.display = 'none';
} else {
fobj.style.display = '';
}
}
}
function getreplycredit() {
var replycredit_extcredits = $('replycredit_extcredits');
var replycredit_times = $('replycredit_times');
var credit_once = parseInt(replycredit_extcredits.value) > 0 ? parseInt(replycredit_extcredits.value) : 0;
var times = parseInt(replycredit_times.value) > 0 ? parseInt(replycredit_times.value) : 0;
if(parseInt(credit_once * times) - have_replycredit > 0) {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit + ((parseInt(credit_once * times) - have_replycredit) * creditstax));
} else {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit);
}
var reply_credits_sum = Math.ceil(parseInt(credit_once * times));
if(real_reply_credit > userextcredit) {
$('replycredit').innerHTML = '<b class="xi1">回帖奖励积分总额过大('+real_reply_credit+')</b>';
} else {
if(have_replycredit > 0 && real_reply_credit < 0) {
$('replycredit').innerHTML = "<font class='xi1'>返还"+Math.abs(real_reply_credit)+"</font>";
} else {
$('replycredit').innerHTML = replycredit_result_lang + (real_reply_credit > 0 ? real_reply_credit : 0 );
}
$('replycredit_sum').innerHTML = reply_credits_sum > 0 ? reply_credits_sum : 0 ;
}
}
function extraCheckall() {
for(i = 0;i < 5;i++) {
extraCheck(i);
}
}
function deleteThread() {
if(confirm('确定要删除该帖子吗?') != 0){
$('delete').value = '1';
$('postform').submit();
}
}
function hideAttachMenu(id) {
if($(editorid + '_' + id + '_menu')) {
$(editorid + '_' + id + '_menu').style.visibility = 'hidden';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: swfupload.js 32391 2013-01-08 08:06:04Z zhengqingpeng $
*/
var SWFUpload;
var swfobject;
if (SWFUpload == undefined) {
SWFUpload = function (settings) {
this.initSWFUpload(settings);
};
}
SWFUpload.prototype.initSWFUpload = function (userSettings) {
try {
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
this.settings = {};
this.eventQueue = [];
this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
this.movieElement = null;
SWFUpload.instances[this.movieName] = this;
this.initSettings(userSettings);
this.loadSupport();
if (this.swfuploadPreload()) {
this.loadFlash();
}
this.displayDebugInfo();
} catch (ex) {
delete SWFUpload.instances[this.movieName];
throw ex;
}
};
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.5.0 2010-01-15 Beta 2";
SWFUpload.QUEUE_ERROR = {
QUEUE_LIMIT_EXCEEDED : -100,
FILE_EXCEEDS_SIZE_LIMIT : -110,
ZERO_BYTE_FILE : -120,
INVALID_FILETYPE : -130
};
SWFUpload.UPLOAD_ERROR = {
HTTP_ERROR : -200,
MISSING_UPLOAD_URL : -210,
IO_ERROR : -220,
SECURITY_ERROR : -230,
UPLOAD_LIMIT_EXCEEDED : -240,
UPLOAD_FAILED : -250,
SPECIFIED_FILE_ID_NOT_FOUND : -260,
FILE_VALIDATION_FAILED : -270,
FILE_CANCELLED : -280,
UPLOAD_STOPPED : -290,
RESIZE : -300
};
SWFUpload.FILE_STATUS = {
QUEUED : -1,
IN_PROGRESS : -2,
ERROR : -3,
COMPLETE : -4,
CANCELLED : -5
};
SWFUpload.UPLOAD_TYPE = {
NORMAL : -1,
RESIZED : -2
};
SWFUpload.BUTTON_ACTION = {
SELECT_FILE : -100,
SELECT_FILES : -110,
START_UPLOAD : -120,
JAVASCRIPT : -130, // DEPRECATED
NONE : -130
};
SWFUpload.CURSOR = {
ARROW : -1,
HAND : -2
};
SWFUpload.WINDOW_MODE = {
WINDOW : "window",
TRANSPARENT : "transparent",
OPAQUE : "opaque"
};
SWFUpload.RESIZE_ENCODING = {
JPEG : -1,
PNG : -2
};
SWFUpload.completeURL = function (url) {
try {
var path = "", indexSlash = -1;
if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//) || url === "") {
return url;
}
indexSlash = window.location.pathname.lastIndexOf("/");
if (indexSlash <= 0) {
path = "/";
} else {
path = window.location.pathname.substr(0, indexSlash) + "/";
}
return path + url;
} catch (ex) {
return url;
}
};
SWFUpload.onload = function () {};
SWFUpload.prototype.initSettings = function (userSettings) {
this.ensureDefault = function (settingName, defaultValue) {
var setting = userSettings[settingName];
if (setting != undefined) {
this.settings[settingName] = setting;
} else {
this.settings[settingName] = defaultValue;
}
};
this.ensureDefault("upload_url", "");
this.ensureDefault("preserve_relative_urls", false);
this.ensureDefault("file_post_name", "Filedata");
this.ensureDefault("post_params", {});
this.ensureDefault("use_query_string", false);
this.ensureDefault("requeue_on_error", false);
this.ensureDefault("http_success", []);
this.ensureDefault("assume_success_timeout", 0);
this.ensureDefault("file_types", "*.*");
this.ensureDefault("file_types_description", "All Files");
this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
this.ensureDefault("file_upload_limit", 0);
this.ensureDefault("file_queue_limit", 0);
this.ensureDefault("flash_url", IMGDIR+"/swfupload.swf");
this.ensureDefault("flash9_url", IMGDIR+"/swfupload.swf");
this.ensureDefault("prevent_swf_caching", true);
this.ensureDefault("button_image_url", "");
this.ensureDefault("button_width", 1);
this.ensureDefault("button_height", 1);
this.ensureDefault("button_text", "");
this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
this.ensureDefault("button_text_top_padding", 0);
this.ensureDefault("button_text_left_padding", 0);
this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
this.ensureDefault("button_disabled", false);
this.ensureDefault("button_placeholder_id", "");
this.ensureDefault("button_placeholder", null);
this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
this.ensureDefault("debug", false);
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
this.settings.return_upload_start_handler = this.returnUploadStart;
this.ensureDefault("swfupload_preload_handler", null);
this.ensureDefault("swfupload_load_failed_handler", null);
this.ensureDefault("swfupload_loaded_handler", null);
this.ensureDefault("file_dialog_start_handler", null);
this.ensureDefault("file_queued_handler", null);
this.ensureDefault("file_queue_error_handler", null);
this.ensureDefault("file_dialog_complete_handler", null);
this.ensureDefault("upload_resize_start_handler", null);
this.ensureDefault("upload_start_handler", null);
this.ensureDefault("upload_progress_handler", null);
this.ensureDefault("upload_error_handler", null);
this.ensureDefault("upload_success_handler", null);
this.ensureDefault("upload_complete_handler", null);
this.ensureDefault("mouse_click_handler", null);
this.ensureDefault("mouse_out_handler", null);
this.ensureDefault("mouse_over_handler", null);
this.ensureDefault("debug_handler", this.debugMessage);
this.ensureDefault("custom_settings", {});
this.customSettings = this.settings.custom_settings;
if (!!this.settings.prevent_swf_caching) {
this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
this.settings.flash9_url = this.settings.flash9_url + (this.settings.flash9_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
}
if (!this.settings.preserve_relative_urls) {
this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
}
delete this.ensureDefault;
};
SWFUpload.prototype.loadSupport = function () {
this.support = {
loading : swfobject.hasFlashPlayerVersion("9.0.28"),
imageResize : false
};
};
SWFUpload.prototype.loadFlash = function () {
var targetElement, tempParent, wrapperType, flashHTML, els;
if (!this.support.loading) {
this.queueEvent("swfupload_load_failed_handler", ["Flash Player doesn't support SWFUpload"]);
return;
}
if (document.getElementById(this.movieName) !== null) {
this.support.loading = false;
this.queueEvent("swfupload_load_failed_handler", ["Element ID already in use"]);
return;
}
targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
if (targetElement == undefined) {
this.support.loading = false;
this.queueEvent("swfupload_load_failed_handler", ["button place holder not found"]);
return;
}
wrapperType = (targetElement.currentStyle && targetElement.currentStyle["display"] || window.getComputedStyle && document.defaultView.getComputedStyle(targetElement, null).getPropertyValue("display")) !== "block" ? "span" : "div";
tempParent = document.createElement(wrapperType);
flashHTML = this.getFlashHTML();
try {
tempParent.innerHTML = flashHTML; // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
} catch (ex) {
this.support.loading = false;
this.queueEvent("swfupload_load_failed_handler", ["Exception loading Flash HTML into placeholder"]);
return;
}
els = tempParent.getElementsByTagName("object");
if (!els || els.length > 1 || els.length === 0) {
this.support.loading = false;
this.queueEvent("swfupload_load_failed_handler", ["Unable to find movie after adding to DOM"]);
return;
} else if (els.length === 1) {
this.movieElement = els[0];
}
targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
if (window[this.movieName] == undefined) {
window[this.movieName] = this.getMovieElement();
}
};
SWFUpload.prototype.getFlashHTML = function (flashVersion) {
if(BROWSER.ie && !BROWSER.opera) {
return AC_FL_RunContent('id', this.movieName, 'width', this.settings.button_width, 'height', this.settings.button_height, 'src', this.settings.flash_url, 'quality', 'high', 'wmode', this.settings.button_window_mode, 'flashvars', this.getFlashVars(), 'AllowScriptAccess', 'always');
} else {
return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', (this.support.imageResize ? this.settings.flash_url : this.settings.flash9_url), '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
'<param name="wmode" value="', this.settings.button_window_mode, '" />',
'<param name="movie" value="', (this.support.imageResize ? this.settings.flash_url : this.settings.flash9_url), '" />',
'<param name="quality" value="high" />',
'<param name="allowScriptAccess" value="always" />',
'<param name="flashvars" value="' + this.getFlashVars() + '" />',
'</object>'].join("");
}
};
SWFUpload.prototype.getFlashVars = function () {
var httpSuccessString, paramString;
paramString = this.buildParamString();
httpSuccessString = this.settings.http_success.join(",");
return ["movieName=", encodeURIComponent(this.movieName),
"&uploadURL=", encodeURIComponent(this.settings.upload_url),
"&useQueryString=", encodeURIComponent(this.settings.use_query_string),
"&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
"&httpSuccess=", encodeURIComponent(httpSuccessString),
"&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
"&params=", encodeURIComponent(paramString),
"&filePostName=", encodeURIComponent(this.settings.file_post_name),
"&fileTypes=", encodeURIComponent(this.settings.file_types),
"&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
"&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
"&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
"&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
"&debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
"&buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
"&buttonWidth=", encodeURIComponent(this.settings.button_width),
"&buttonHeight=", encodeURIComponent(this.settings.button_height),
"&buttonText=", encodeURIComponent(this.settings.button_text),
"&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
"&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
"&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
"&buttonAction=", encodeURIComponent(this.settings.button_action),
"&buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
"&buttonCursor=", encodeURIComponent(this.settings.button_cursor)
].join("");
};
SWFUpload.prototype.getMovieElement = function () {
if (this.movieElement == undefined) {
this.movieElement = document.getElementById(this.movieName);
}
if (this.movieElement === null) {
throw "Could not find Flash element";
}
return this.movieElement;
};
SWFUpload.prototype.buildParamString = function () {
var name, postParams, paramStringPairs = [];
postParams = this.settings.post_params;
if (typeof(postParams) === "object") {
for (name in postParams) {
if (postParams.hasOwnProperty(name)) {
paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
}
}
}
return paramStringPairs.join("&");
};
SWFUpload.prototype.destroy = function () {
var movieElement;
try {
this.cancelUpload(null, false);
movieElement = this.cleanUp();
if (movieElement) {
try {
movieElement.parentNode.removeChild(movieElement);
} catch (ex) {}
}
window[this.movieName] = null;
SWFUpload.instances[this.movieName] = null;
delete SWFUpload.instances[this.movieName];
this.movieElement = null;
this.settings = null;
this.customSettings = null;
this.eventQueue = null;
this.movieName = null;
return true;
} catch (ex2) {
return false;
}
};
SWFUpload.prototype.displayDebugInfo = function () {
this.debug(
[
"---SWFUpload Instance Info---\n",
"Version: ", SWFUpload.version, "\n",
"Movie Name: ", this.movieName, "\n",
"Settings:\n",
"\t", "upload_url: ", this.settings.upload_url, "\n",
"\t", "flash_url: ", this.settings.flash_url, "\n",
"\t", "flash9_url: ", this.settings.flash9_url, "\n",
"\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
"\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
"\t", "http_success: ", this.settings.http_success.join(", "), "\n",
"\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
"\t", "file_post_name: ", this.settings.file_post_name, "\n",
"\t", "post_params: ", this.settings.post_params.toString(), "\n",
"\t", "file_types: ", this.settings.file_types, "\n",
"\t", "file_types_description: ", this.settings.file_types_description, "\n",
"\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
"\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
"\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
"\t", "debug: ", this.settings.debug.toString(), "\n",
"\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
"\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
"\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
"\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
"\t", "button_width: ", this.settings.button_width.toString(), "\n",
"\t", "button_height: ", this.settings.button_height.toString(), "\n",
"\t", "button_text: ", this.settings.button_text.toString(), "\n",
"\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
"\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
"\t", "button_action: ", this.settings.button_action.toString(), "\n",
"\t", "button_cursor: ", this.settings.button_cursor.toString(), "\n",
"\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
"\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
"Event Handlers:\n",
"\t", "swfupload_preload_handler assigned: ", (typeof this.settings.swfupload_preload_handler === "function").toString(), "\n",
"\t", "swfupload_load_failed_handler assigned: ", (typeof this.settings.swfupload_load_failed_handler === "function").toString(), "\n",
"\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
"\t", "mouse_click_handler assigned: ", (typeof this.settings.mouse_click_handler === "function").toString(), "\n",
"\t", "mouse_over_handler assigned: ", (typeof this.settings.mouse_over_handler === "function").toString(), "\n",
"\t", "mouse_out_handler assigned: ", (typeof this.settings.mouse_out_handler === "function").toString(), "\n",
"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
"\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
"\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
"\t", "upload_resize_start_handler assigned: ", (typeof this.settings.upload_resize_start_handler === "function").toString(), "\n",
"\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
"\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
"\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
"\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
"\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
"\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n",
"Support:\n",
"\t", "Load: ", (this.support.loading ? "Yes" : "No"), "\n",
"\t", "Image Resize: ", (this.support.imageResize ? "Yes" : "No"), "\n"
].join("")
);
};
SWFUpload.prototype.addSetting = function (name, value, default_value) {
if (value == undefined) {
return (this.settings[name] = default_value);
} else {
return (this.settings[name] = value);
}
};
SWFUpload.prototype.getSetting = function (name) {
if (this.settings[name] != undefined) {
return this.settings[name];
}
return "";
};
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
var movieElement, returnValue, returnString;
argumentArray = argumentArray || [];
movieElement = this.getMovieElement();
try {
if (movieElement != undefined) {
returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
returnValue = eval(returnString);
} else {
this.debug("Can't call flash because the movie wasn't found.");
}
} catch (ex) {
this.debug("Exception calling flash function '" + functionName + "': " + ex.message);
}
if (returnValue != undefined && typeof returnValue.post === "object") {
returnValue = this.unescapeFilePostParams(returnValue);
}
return returnValue;
};
SWFUpload.prototype.selectFile = function () {
this.callFlash("SelectFile");
};
SWFUpload.prototype.selectFiles = function () {
this.callFlash("SelectFiles");
};
SWFUpload.prototype.startUpload = function (fileID) {
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.startResizedUpload = function (fileID, width, height, encoding, quality, allowEnlarging) {
this.callFlash("StartUpload", [fileID, { "width": width, "height" : height, "encoding" : encoding, "quality" : quality, "allowEnlarging" : allowEnlarging }]);
};
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
if (triggerErrorEvent !== false) {
triggerErrorEvent = true;
}
this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};
SWFUpload.prototype.stopUpload = function () {
this.callFlash("StopUpload");
};
SWFUpload.prototype.requeueUpload = function (indexOrFileID) {
return this.callFlash("RequeueUpload", [indexOrFileID]);
};
SWFUpload.prototype.getStats = function () {
return this.callFlash("GetStats");
};
SWFUpload.prototype.setStats = function (statsObject) {
this.callFlash("SetStats", [statsObject]);
};
SWFUpload.prototype.getFile = function (fileID) {
if (typeof(fileID) === "number") {
return this.callFlash("GetFileByIndex", [fileID]);
} else {
return this.callFlash("GetFile", [fileID]);
}
};
SWFUpload.prototype.getQueueFile = function (fileID) {
if (typeof(fileID) === "number") {
return this.callFlash("GetFileByQueueIndex", [fileID]);
} else {
return this.callFlash("GetFile", [fileID]);
}
};
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
return this.callFlash("AddFileParam", [fileID, name, value]);
};
SWFUpload.prototype.removeFileParam = function (fileID, name) {
this.callFlash("RemoveFileParam", [fileID, name]);
};
SWFUpload.prototype.setUploadURL = function (url) {
this.settings.upload_url = url.toString();
this.callFlash("SetUploadURL", [url]);
};
SWFUpload.prototype.setPostParams = function (paramsObject) {
this.settings.post_params = paramsObject;
this.callFlash("SetPostParams", [paramsObject]);
};
SWFUpload.prototype.addPostParam = function (name, value) {
this.settings.post_params[name] = value;
this.callFlash("SetPostParams", [this.settings.post_params]);
};
SWFUpload.prototype.removePostParam = function (name) {
delete this.settings.post_params[name];
this.callFlash("SetPostParams", [this.settings.post_params]);
};
SWFUpload.prototype.setFileTypes = function (types, description) {
this.settings.file_types = types;
this.settings.file_types_description = description;
this.callFlash("SetFileTypes", [types, description]);
};
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
this.settings.file_size_limit = fileSizeLimit;
this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
this.settings.file_upload_limit = fileUploadLimit;
this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
this.settings.file_queue_limit = fileQueueLimit;
this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};
SWFUpload.prototype.setFilePostName = function (filePostName) {
this.settings.file_post_name = filePostName;
this.callFlash("SetFilePostName", [filePostName]);
};
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
this.settings.use_query_string = useQueryString;
this.callFlash("SetUseQueryString", [useQueryString]);
};
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
this.settings.requeue_on_error = requeueOnError;
this.callFlash("SetRequeueOnError", [requeueOnError]);
};
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
if (typeof http_status_codes === "string") {
http_status_codes = http_status_codes.replace(" ", "").split(",");
}
this.settings.http_success = http_status_codes;
this.callFlash("SetHTTPSuccess", [http_status_codes]);
};
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
this.settings.assume_success_timeout = timeout_seconds;
this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
this.settings.debug_enabled = debugEnabled;
this.callFlash("SetDebugEnabled", [debugEnabled]);
};
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
if (buttonImageURL == undefined) {
buttonImageURL = "";
}
this.settings.button_image_url = buttonImageURL;
this.callFlash("SetButtonImageURL", [buttonImageURL]);
};
SWFUpload.prototype.setButtonDimensions = function (width, height) {
this.settings.button_width = width;
this.settings.button_height = height;
var movie = this.getMovieElement();
if (movie != undefined) {
movie.style.width = width + "px";
movie.style.height = height + "px";
}
this.callFlash("SetButtonDimensions", [width, height]);
};
SWFUpload.prototype.setButtonText = function (html) {
this.settings.button_text = html;
this.callFlash("SetButtonText", [html]);
};
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
this.settings.button_text_top_padding = top;
this.settings.button_text_left_padding = left;
this.callFlash("SetButtonTextPadding", [left, top]);
};
SWFUpload.prototype.setButtonTextStyle = function (css) {
this.settings.button_text_style = css;
this.callFlash("SetButtonTextStyle", [css]);
};
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
this.settings.button_disabled = isDisabled;
this.callFlash("SetButtonDisabled", [isDisabled]);
};
SWFUpload.prototype.setButtonAction = function (buttonAction) {
this.settings.button_action = buttonAction;
this.callFlash("SetButtonAction", [buttonAction]);
};
SWFUpload.prototype.setButtonCursor = function (cursor) {
this.settings.button_cursor = cursor;
this.callFlash("SetButtonCursor", [cursor]);
};
SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
var self = this;
if (argumentArray == undefined) {
argumentArray = [];
} else if (!(argumentArray instanceof Array)) {
argumentArray = [argumentArray];
}
if (typeof this.settings[handlerName] === "function") {
this.eventQueue.push(function () {
this.settings[handlerName].apply(this, argumentArray);
});
setTimeout(function () {
self.executeNextEvent();
}, 0);
} else if (this.settings[handlerName] !== null) {
throw "Event handler " + handlerName + " is unknown or is not a function";
}
};
SWFUpload.prototype.executeNextEvent = function () {
var f = this.eventQueue ? this.eventQueue.shift() : null;
if (typeof(f) === "function") {
f.apply(this);
}
};
SWFUpload.prototype.unescapeFilePostParams = function (file) {
var reg = /[$]([0-9a-f]{4})/i, unescapedPost = {}, uk, k, match;
if (file != undefined) {
for (k in file.post) {
if (file.post.hasOwnProperty(k)) {
uk = k;
while ((match = reg.exec(uk)) !== null) {
uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
}
unescapedPost[uk] = file.post[k];
}
}
file.post = unescapedPost;
}
return file;
};
SWFUpload.prototype.swfuploadPreload = function () {
var returnValue;
if (typeof this.settings.swfupload_preload_handler === "function") {
returnValue = this.settings.swfupload_preload_handler.call(this);
} else if (this.settings.swfupload_preload_handler != undefined) {
throw "upload_start_handler must be a function";
}
if (returnValue === undefined) {
returnValue = true;
}
return !!returnValue;
};
SWFUpload.prototype.flashReady = function () {
var movieElement = this.cleanUp();
if (!movieElement) {
this.debug("Flash called back ready but the flash movie can't be found.");
return;
}
this.queueEvent("swfupload_loaded_handler");
};
SWFUpload.prototype.cleanUp = function () {
var key, movieElement = this.getMovieElement();
try {
if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
for (key in movieElement) {
try {
if (typeof(movieElement[key]) === "function") {
movieElement[key] = null;
}
} catch (ex) {
}
}
}
} catch (ex1) {
}
window["__flash__removeCallback"] = function (instance, name) {
try {
if (instance) {
instance[name] = null;
}
} catch (flashEx) {
}
};
return movieElement;
};
SWFUpload.prototype.mouseClick = function () {
this.queueEvent("mouse_click_handler");
};
SWFUpload.prototype.mouseOver = function () {
this.queueEvent("mouse_over_handler");
};
SWFUpload.prototype.mouseOut = function () {
this.queueEvent("mouse_out_handler");
};
SWFUpload.prototype.fileDialogStart = function () {
this.queueEvent("file_dialog_start_handler");
};
SWFUpload.prototype.fileQueued = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queued_handler", file);
};
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};
SWFUpload.prototype.uploadResizeStart = function (file, resizeSettings) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_resize_start_handler", [file, resizeSettings.width, resizeSettings.height, resizeSettings.encoding, resizeSettings.quality]);
};
SWFUpload.prototype.uploadStart = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("return_upload_start_handler", file);
};
SWFUpload.prototype.returnUploadStart = function (file) {
var returnValue;
if (typeof this.settings.upload_start_handler === "function") {
file = this.unescapeFilePostParams(file);
returnValue = this.settings.upload_start_handler.call(this, file);
} else if (this.settings.upload_start_handler != undefined) {
throw "upload_start_handler must be a function";
}
if (returnValue === undefined) {
returnValue = true;
}
returnValue = !!returnValue;
this.callFlash("ReturnUploadStart", [returnValue]);
};
SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};
SWFUpload.prototype.uploadError = function (file, errorCode, message) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_error_handler", [file, errorCode, message]);
};
SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};
SWFUpload.prototype.uploadComplete = function (file) {
file = this.unescapeFilePostParams(file);
this.queueEvent("upload_complete_handler", file);
};
SWFUpload.prototype.debug = function (message) {
this.queueEvent("debug_handler", message);
};
SWFUpload.prototype.debugMessage = function (message) {
var exceptionMessage, exceptionValues, key;
if (this.settings.debug) {
exceptionValues = [];
if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
for (key in message) {
if (message.hasOwnProperty(key)) {
exceptionValues.push(key + ": " + message[key]);
}
}
exceptionMessage = exceptionValues.join("\n") || "";
exceptionValues = exceptionMessage.split("\n");
exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
SWFUpload.Console.writeLine(exceptionMessage);
} else {
SWFUpload.Console.writeLine(message);
}
}
};
SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
var console, documentForm;
try {
console = document.getElementById("SWFUpload_Console");
if (!console) {
documentForm = document.createElement("form");
document.getElementsByTagName("body")[0].appendChild(documentForm);
console = document.createElement("textarea");
console.id = "SWFUpload_Console";
console.style.fontFamily = "monospace";
console.setAttribute("wrap", "off");
console.wrap = "off";
console.style.overflow = "auto";
console.style.width = "700px";
console.style.height = "350px";
console.style.margin = "5px";
documentForm.appendChild(console);
}
console.value += message + "\n";
console.scrollTop = console.scrollHeight - console.clientHeight;
} catch (ex) {
alert("Exception: " + ex.name + " Message: " + ex.message);
}
};
swfobject = function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
swfobject.addDomLoadEvent(function () {
if (typeof(SWFUpload.onload) === "function") {
SWFUpload.onload.call(window);
}
}); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: admincp.js 31416 2012-08-27 07:50:15Z zhangguosheng $
*/
function redirect(url) {
window.location.replace(url);
}
function scrollTopBody() {
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkAll(type, form, value, checkall, changestyle) {
var checkall = checkall ? checkall : 'chkall';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(type == 'option' && e.type == 'radio' && e.value == value && e.disabled != true) {
e.checked = true;
} else if(type == 'value' && e.type == 'checkbox' && e.getAttribute('chkvalue') == value) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
multiupdate(e);
}
} else if(type == 'prefix' && e.name && e.name != checkall && (!value || (value && e.name.match(value)))) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
if(e.parentNode && e.parentNode.tagName.toLowerCase() == 'li') {
e.parentNode.className = e.checked ? 'checked' : '';
}
if(e.parentNode.parentNode && e.parentNode.parentNode.tagName.toLowerCase() == 'div') {
e.parentNode.parentNode.className = e.checked ? 'item checked' : 'item';
}
}
}
}
}
function altStyle(obj, disabled) {
function altStyleClear(obj) {
var input, lis, i;
lis = obj.parentNode.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].className = '';
}
}
var disabled = !disabled ? 0 : disabled;
if(disabled) {
return;
}
var input, lis, i, cc, o;
cc = 0;
lis = obj.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].onclick = function(e) {
o = BROWSER.ie ? event.srcElement.tagName : e.target.tagName;
altKey = BROWSER.ie ? window.event.altKey : e.altKey;
if(cc) {
return;
}
cc = 1;
input = this.getElementsByTagName('input')[0];
if(input.getAttribute('type') == 'checkbox' || input.getAttribute('type') == 'radio') {
if(input.getAttribute('type') == 'radio') {
altStyleClear(this);
}
if(BROWSER.ie || o != 'INPUT' && input.onclick) {
input.click();
}
if(this.className != 'checked') {
this.className = 'checked';
input.checked = true;
} else {
this.className = '';
input.checked = false;
}
if(altKey && input.name.match(/^multinew\[\d+\]/)) {
miid = input.id.split('|');
mi = 0;
while($(miid[0] + '|' + mi)) {
$(miid[0] + '|' + mi).checked = input.checked;
if(input.getAttribute('type') == 'radio') {
altStyleClear($(miid[0] + '|' + mi).parentNode);
}
$(miid[0] + '|' + mi).parentNode.className = input.checked ? 'checked' : '';
mi++;
}
}
}
};
lis[i].onmouseup = function(e) {
cc = 0;
}
}
}
var addrowdirect = 0;
var addrowkey = 0;
function addrow(obj, type) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
if(!addrowdirect) {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex);
} else {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex + 1);
}
var typedata = rowtypedata[type];
for(var i = 0; i <= typedata.length - 1; i++) {
var cell = row.insertCell(i);
cell.colSpan = typedata[i][0];
var tmp = typedata[i][1];
if(typedata[i][2]) {
cell.className = typedata[i][2];
}
tmp = tmp.replace(/\{(n)\}/g, function($1) {return addrowkey;});
tmp = tmp.replace(/\{(\d+)\}/g, function($1, $2) {return addrow.arguments[parseInt($2) + 1];});
cell.innerHTML = tmp;
}
addrowkey ++;
addrowdirect = 0;
}
function deleterow(obj) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
var tr = obj.parentNode.parentNode.parentNode;
table.deleteRow(tr.rowIndex);
}
function dropmenu(obj){
showMenu({'ctrlid':obj.id, 'menuid':obj.id + 'child', 'evt':'mouseover'});
$(obj.id + 'child').style.top = (parseInt($(obj.id + 'child').style.top) - Math.max(document.body.scrollTop, document.documentElement.scrollTop)) + 'px';
if(BROWSER.ie > 6 || !BROWSER.ie) {
$(obj.id + 'child').style.left = (parseInt($(obj.id + 'child').style.left) - Math.max(document.body.scrollLeft, document.documentElement.scrollLeft)) + 'px';
}
}
var heightag = BROWSER.chrome ? 4 : 0;
function textareasize(obj, op) {
if(!op) {
if(obj.scrollHeight > 70) {
obj.style.height = (obj.scrollHeight < 300 ? obj.scrollHeight - heightag: 300) + 'px';
if(obj.style.position == 'absolute') {
obj.parentNode.style.height = (parseInt(obj.style.height) + 20) + 'px';
}
}
} else {
if(obj.style.position == 'absolute') {
obj.style.position = '';
obj.style.width = '';
obj.parentNode.style.height = '';
} else {
obj.parentNode.style.height = obj.parentNode.offsetHeight + 'px';
obj.style.width = BROWSER.ie > 6 || !BROWSER.ie ? '90%' : '600px';
obj.style.position = 'absolute';
}
}
}
function showanchor(obj) {
var navs = $('submenu').getElementsByTagName('li');
for(var i = 0; i < navs.length; i++) {
if(navs[i].id.substr(0, 4) == 'nav_' && navs[i].id != obj.id) {
if($(navs[i].id.substr(4))) {
navs[i].className = '';
$(navs[i].id.substr(4)).style.display = 'none';
if($(navs[i].id.substr(4) + '_tips')) $(navs[i].id.substr(4) + '_tips').style.display = 'none';
}
}
}
obj.className = 'current';
currentAnchor = obj.id.substr(4);
$(currentAnchor).style.display = '';
if($(currentAnchor + '_tips')) $(currentAnchor + '_tips').style.display = '';
if($(currentAnchor + 'form')) {
$(currentAnchor + 'form').anchor.value = currentAnchor;
} else if($('cpform')) {
$('cpform').anchor.value = currentAnchor;
}
}
function updatecolorpreview(obj) {
$(obj).style.background = $(obj + '_v').value;
}
function entersubmit(e, name) {
if(loadUserdata('is_blindman')) {
return false;
}
var e = e ? e : event;
if(e.keyCode != 13) {
return;
}
var tag = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tag != 'TEXTAREA') {
doane(e);
if($('submit_' + name).offsetWidth) {
$('formscrolltop').value = document.documentElement.scrollTop;
$('submit_' + name).click();
}
}
}
function parsetag(tag) {
var parse = function (tds) {
for(var i = 0; i < tds.length; i++) {
if(tds[i].getAttribute('s') == '1') {
var str = tds[i].innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
if(tag && $3.indexOf(tag) != -1) {
re = new RegExp(tag, "g");
$3 = $3.replace(re, '<h_>');
}
return $2 + $3;
});
tds[i].innerHTML = str.replace(/<h_>/ig, function($1, $2) {
return '<font class="highlight">' + tag + '</font>';
});
}
}
};
parse(document.body.getElementsByTagName('td'));
parse(document.body.getElementsByTagName('span'));
}
function sdisplay(id, obj) {
obj.innerHTML = $(id).style.display == 'none' ? '<img src="static/image/admincp/desc.gif" style="vertical-align:middle" />' : '<img src="static/image/admincp/add.gif" style="vertical-align:middle" />';
display(id);
}
if(ISFRAME) {
try {
_attachEvent(document.documentElement, 'keydown', parent.resetEscAndF5);
} catch(e) {}
}
var multiids = new Array();
function multiupdate(obj) {
v = obj.value;
if(obj.checked) {
multiids[v] = v;
} else {
multiids[v] = null;
}
}
function getmultiids() {
var ids = '', comma = '';
for(i in multiids) {
if(multiids[i] != null) {
ids += comma + multiids[i];
comma = ',';
}
}
return ids;
}
function toggle_group(oid, obj, conf) {
obj = obj ? obj : $('a_'+oid);
if(!conf) {
var conf = {'show':'[-]','hide':'[+]'};
}
var obody = $(oid);
if(obody.style.display == 'none') {
obody.style.display = '';
obj.innerHTML = conf.show;
} else {
obody.style.display = 'none';
obj.innerHTML = conf.hide;
}
}
function show_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = '';
$('a_group_' + matches[1]).innerHTML = '[-]';
}
}
}
function hide_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = 'none';
$('a_group_' + matches[1]).innerHTML = '[+]';
}
}
}
function show_all_hook(prefix, tagname) {
var tbodys = $("cpform").getElementsByTagName(tagname);
for(var i = 0; i < tbodys.length; i++) {
var re = new RegExp('^' + prefix + '(.+)$');
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = '';
$('a_' + prefix + matches[1]).innerHTML = '[-]';
}
}
}
function hide_all_hook(prefix, tagname) {
var tbodys = $("cpform").getElementsByTagName(tagname);
for(var i = 0; i < tbodys.length; i++) {
var re = new RegExp('^' + prefix + '(.+)$');
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = 'none';
$('a_' + prefix + matches[1]).innerHTML = '[+]';
}
}
}
function srchforum() {
var fname = $('srchforumipt').value.toLowerCase();
if(!fname) return false;
var inputs = $("cpform").getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.match(/^name\[\d+\]$/)) {
if(inputs[i].value.toLowerCase().indexOf(fname) !== -1) {
inputs[i].parentNode.parentNode.parentNode.parentNode.style.display = '';
inputs[i].parentNode.parentNode.parentNode.style.background = '#eee';
window.scrollTo(0, fetchOffset(inputs[i]).top - 100);
return false;
}
}
}
return false;
}
function setfaq(obj, id) {
if(!$(id)) {
return;
}
$(id).style.display = '';
if(!obj.onmouseout) {
obj.onmouseout = function () {
$(id).style.display = 'none';
}
}
}
function floatbottom(id) {
if(!$(id)) {
return;
}
$(id).style.position = 'fixed';
$(id).style.bottom = '0';
$(id).parentNode.style.paddingBottom = '15px';
if(!BROWSER.ie || BROWSER.ie && BROWSER.ie > 6) {
window.onscroll = function() {
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
$(id).style.marginLeft = '-' + scrollLeft + 'px';
};
$(id).style.display = '';
}
}
var sethtml_id = null;
function sethtml(id) {
$(id).className = 'txt html';
$(id).contentEditable = true;
$(id).onkeyup = function () {
$(id + '_v').value = $(id).innerHTML;
};
var curvalue = $(id).innerHTML;
var div = document.createElement('div');
div.id = id + '_c_menu';
div.style.display = 'none';
div.innerHTML = '<iframe id="' + id + '_c_frame" src="" frameborder="0" width="210" height="148" scrolling="no"></iframe>';
$(id).parentNode.appendChild(div);
var btn = document.createElement('input');
btn.id = id + '_c';
btn.type = 'button';
btn.className = 'htmlbtn c';
if(curvalue.search(/<font/ig) !== -1) {
btn.className = 'htmlbtn c current';
}
btn.onclick = function() {
$(id + '_c_frame').src = 'static/image/admincp/getcolor.htm?||sethtml_color';
showMenu({'ctrlid' : id + '_c'});
sethtml_id = id;
};
$(id).parentNode.appendChild(btn);
var btn = document.createElement('input');
btn.id = id + '_b';
btn.type = 'button';
btn.className = 'htmlbtn b';
if(curvalue.search(/<b>/ig) !== -1) {
btn.className = 'htmlbtn b current';
}
btn.onclick = function() {
var oldvalue = $(id).innerHTML;
$(id).innerHTML = preg_replace(['<b>', '</b>'], '', $(id).innerHTML);
if(oldvalue == $(id).innerHTML) {
$(id + '_b').className = 'htmlbtn b current';
$(id).innerHTML = '<b>' + $(id).innerHTML + '</b>';
} else {
$(id + '_b').className = 'htmlbtn b';
}
$(id + '_v').value = $(id).innerHTML;
};
$(id).parentNode.appendChild(btn);
var btn = document.createElement('input');
btn.id = id + '_i';
btn.type = 'button';
btn.className = 'htmlbtn i';
if(curvalue.search(/<i>/ig) !== -1) {
btn.className = 'htmlbtn i current';
}
btn.onclick = function() {
var oldvalue = $(id).innerHTML;
$(id).innerHTML = preg_replace(['<i>', '</i>'], '', $(id).innerHTML);
if(oldvalue == $(id).innerHTML) {
$(id + '_i').className = 'htmlbtn i current';
$(id).innerHTML = '<i>' + $(id).innerHTML + '</i>';
} else {
$(id + '_i').className = 'htmlbtn i';
}
$(id + '_v').value = $(id).innerHTML;
};
$(id).parentNode.appendChild(btn);
var btn = document.createElement('input');
btn.id = id + '_u';
btn.type = 'button';
btn.style.textDecoration = 'underline';
btn.className = 'htmlbtn u';
if(curvalue.search(/<u>/ig) !== -1) {
btn.className = 'htmlbtn u current';
}
btn.onclick = function() {
var oldvalue = $(id).innerHTML;
$(id).innerHTML = preg_replace(['<u>', '</u>'], '', $(id).innerHTML);
if(oldvalue == $(id).innerHTML) {
$(id + '_u').className = 'htmlbtn u current';
$(id).innerHTML = '<u>' + $(id).innerHTML + '</u>';
} else {
$(id + '_u').className = 'htmlbtn u';
}
$(id + '_v').value = $(id).innerHTML;
};
$(id).parentNode.appendChild(btn);
}
function sethtml_color(color) {
$(sethtml_id).innerHTML = preg_replace(['<font[^>]+?>', '</font>'], '', $(sethtml_id).innerHTML);
if(color != 'transparent') {
$(sethtml_id + '_c').className = 'htmlbtn c current';
$(sethtml_id).innerHTML = '<font color=' + color + '>' + $(sethtml_id).innerHTML + '</font>';
} else {
$(sethtml_id + '_c').className = 'htmlbtn c';
}
$(sethtml_id + '_v').value = $(sethtml_id).innerHTML;
}
function uploadthreadtypexml(formobj, formaction) {
formobj.action = formaction;
formobj.submit();
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common.js 32580 2013-02-22 03:40:28Z monkey $
*/
var BROWSER = {};
var USERAGENT = navigator.userAgent.toLowerCase();
browserVersion({'ie':'msie','firefox':'','chrome':'','opera':'','safari':'','mozilla':'','webkit':'','maxthon':'','qq':'qqbrowser'});
if(BROWSER.safari) {
BROWSER.firefox = true;
}
BROWSER.opera = BROWSER.opera ? opera.version() : 0;
HTMLNODE = document.getElementsByTagName('head')[0].parentNode;
if(BROWSER.ie) {
BROWSER.iemode = parseInt(typeof document.documentMode != 'undefined' ? document.documentMode : BROWSER.ie);
HTMLNODE.className = 'ie_all ie' + BROWSER.iemode;
}
var CSSLOADED = [];
var JSLOADED = [];
var JSMENU = [];
JSMENU['active'] = [];
JSMENU['timer'] = [];
JSMENU['drag'] = [];
JSMENU['layer'] = 0;
JSMENU['zIndex'] = {'win':200,'menu':300,'dialog':400,'prompt':500};
JSMENU['float'] = '';
var CURRENTSTYPE = null;
var discuz_uid = isUndefined(discuz_uid) ? 0 : discuz_uid;
var creditnotice = isUndefined(creditnotice) ? '' : creditnotice;
var cookiedomain = isUndefined(cookiedomain) ? '' : cookiedomain;
var cookiepath = isUndefined(cookiepath) ? '' : cookiepath;
var EXTRAFUNC = [], EXTRASTR = '';
EXTRAFUNC['showmenu'] = [];
var DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
var USERABOUT_BOX = true;
var USERCARDST = null;
var CLIPBOARDSWFDATA = '';
var NOTICETITLE = [];
if(BROWSER.firefox && window.HTMLElement) {
HTMLElement.prototype.__defineGetter__( "innerText", function(){
var anyString = "";
var childS = this.childNodes;
for(var i=0; i <childS.length; i++) {
if(childS[i].nodeType==1) {
anyString += childS[i].tagName=="BR" ? '\n' : childS[i].innerText;
} else if(childS[i].nodeType==3) {
anyString += childS[i].nodeValue;
}
}
return anyString;
});
HTMLElement.prototype.__defineSetter__( "innerText", function(sText){
this.textContent=sText;
});
HTMLElement.prototype.__defineSetter__('outerHTML', function(sHTML) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df,this);
return sHTML;
});
HTMLElement.prototype.__defineGetter__('outerHTML', function() {
var attr;
var attrs = this.attributes;
var str = '<' + this.tagName.toLowerCase();
for(var i = 0;i < attrs.length;i++){
attr = attrs[i];
if(attr.specified)
str += ' ' + attr.name + '="' + attr.value + '"';
}
if(!this.canHaveChildren) {
return str + '>';
}
return str + '>' + this.innerHTML + '</' + this.tagName.toLowerCase() + '>';
});
HTMLElement.prototype.__defineGetter__('canHaveChildren', function() {
switch(this.tagName.toLowerCase()) {
case 'area':case 'base':case 'basefont':case 'col':case 'frame':case 'hr':case 'img':case 'br':case 'input':case 'isindex':case 'link':case 'meta':case 'param':
return false;
}
return true;
});
}
function $(id) {
return !id ? null : document.getElementById(id);
}
function $C(classname, ele, tag) {
var returns = [];
ele = ele || document;
tag = tag || '*';
if(ele.getElementsByClassName) {
var eles = ele.getElementsByClassName(classname);
if(tag != '*') {
for (var i = 0, L = eles.length; i < L; i++) {
if (eles[i].tagName.toLowerCase() == tag.toLowerCase()) {
returns.push(eles[i]);
}
}
} else {
returns = eles;
}
}else {
eles = ele.getElementsByTagName(tag);
var pattern = new RegExp("(^|\\s)"+classname+"(\\s|$)");
for (i = 0, L = eles.length; i < L; i++) {
if (pattern.test(eles[i].className)) {
returns.push(eles[i]);
}
}
}
return returns;
}
function _attachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(eventobj.attachEvent) {
obj.attachEvent('on' + evt, func);
}
}
function _detachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.removeEventListener) {
obj.removeEventListener(evt, func, false);
} else if(eventobj.detachEvent) {
obj.detachEvent('on' + evt, func);
}
}
function browserVersion(types) {
var other = 1;
for(i in types) {
var v = types[i] ? types[i] : i;
if(USERAGENT.indexOf(v) != -1) {
var re = new RegExp(v + '(\\/|\\s)([\\d\\.]+)', 'ig');
var matches = re.exec(USERAGENT);
var ver = matches != null ? matches[2] : 0;
other = ver !== 0 && v != 'mozilla' ? 0 : other;
}else {
var ver = 0;
}
eval('BROWSER.' + i + '= ver');
}
BROWSER.other = other;
}
function getEvent() {
if(document.all) return window.event;
func = getEvent.caller;
while(func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func=func.caller;
}
return null;
}
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function in_array(needle, haystack) {
if(typeof needle == 'string' || typeof needle == 'number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function trim(str) {
return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function strlen(str) {
return (BROWSER.ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
}
return len;
}
function mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : dot;
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function preg_replace(search, replace, str, regswitch) {
var regswitch = !regswitch ? 'ig' : regswitch;
var len = search.length;
for(var i = 0; i < len; i++) {
re = new RegExp(search[i], regswitch);
str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
}
return str;
}
function htmlspecialchars(str) {
return preg_replace(['&', '<', '>', '"'], ['&', '<', '>', '"'], str);
}
function display(id) {
var obj = $(id);
if(obj.style.visibility) {
obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible';
} else {
obj.style.display = obj.style.display == '' ? 'none' : '';
}
}
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
count = 0;
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name && e.name != checkall && !e.disabled && (!prefix || (prefix && e.name.match(prefix)))) {
e.checked = form.elements[checkall].checked;
if(e.checked) {
count++;
}
}
}
return count;
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
if(cookieValue == '' || seconds < 0) {
cookieValue = '';
seconds = -2592000;
}
expires.setTime(expires.getTime() + seconds * 1000);
domain = !domain ? cookiedomain : domain;
path = !path ? cookiepath : path;
document.cookie = escape(cookiepre + cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function getcookie(name, nounescape) {
name = cookiepre + name;
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
if(cookie_start == -1) {
return '';
} else {
var v = document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length));
return !nounescape ? unescape(v) : v;
}
}
function Ajax(recvType, waitId) {
var aj = new Object();
aj.loading = '请稍候...';
aj.recvType = recvType ? recvType : 'XML';
aj.waitId = waitId ? $(waitId) : null;
aj.resultHandle = null;
aj.sendString = '';
aj.targetUrl = '';
aj.setLoading = function(loading) {
if(typeof loading !== 'undefined' && loading !== null) aj.loading = loading;
};
aj.setRecvType = function(recvtype) {
aj.recvType = recvtype;
};
aj.setWaitId = function(waitid) {
aj.waitId = typeof waitid == 'object' ? waitid : $(waitid);
};
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) {
return request;
}
} catch(e) {}
}
}
return request;
};
aj.XMLHttpRequest = aj.createXMLHttpRequest();
aj.showLoading = function() {
if(aj.waitId && (aj.XMLHttpRequest.readyState != 4 || aj.XMLHttpRequest.status != 200)) {
aj.waitId.style.display = '';
aj.waitId.innerHTML = '<span><img src="' + IMGDIR + '/loading.gif" class="vm"> ' + aj.loading + '</span>';
}
};
aj.processHandle = function() {
if(aj.XMLHttpRequest.readyState == 4 && aj.XMLHttpRequest.status == 200) {
if(aj.waitId) {
aj.waitId.style.display = 'none';
}
if(aj.recvType == 'HTML') {
aj.resultHandle(aj.XMLHttpRequest.responseText, aj);
} else if(aj.recvType == 'XML') {
if(!aj.XMLHttpRequest.responseXML || !aj.XMLHttpRequest.responseXML.lastChild || aj.XMLHttpRequest.responseXML.lastChild.localName == 'parsererror') {
aj.resultHandle('<a href="' + aj.targetUrl + '" target="_blank" style="color:red">内部错误,无法显示此内容</a>' , aj);
} else {
aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue, aj);
}
}
}
};
aj.get = function(targetUrl, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
aj.targetUrl = targetUrl;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
var attackevasive = isUndefined(attackevasive) ? 0 : attackevasive;
if(window.XMLHttpRequest) {
aj.XMLHttpRequest.open('GET', aj.targetUrl);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(null);
} else {
aj.XMLHttpRequest.open("GET", targetUrl, true);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send();
}
};
aj.post = function(targetUrl, sendString, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.XMLHttpRequest.open('POST', targetUrl);
aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(aj.sendString);
};
return aj;
}
function getHost(url) {
var host = "null";
if(typeof url == "undefined"|| null == url) {
url = window.location.href;
}
var regex = /^\w+\:\/\/([^\/]*).*/;
var match = url.match(regex);
if(typeof match != "undefined" && null != match) {
host = match[1];
}
return host;
}
function hostconvert(url) {
if(!url.match(/^https?:\/\//)) url = SITEURL + url;
var url_host = getHost(url);
var cur_host = getHost().toLowerCase();
if(url_host && cur_host != url_host) {
url = url.replace(url_host, cur_host);
}
return url;
}
function newfunction(func) {
var args = [];
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(event) {
doane(event);
window[func].apply(window, args);
return false;
}
}
function evalscript(s) {
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
var arr = [];
while(arr = p.exec(s)) {
var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
var arr1 = [];
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}
var safescripts = {}, evalscripts = [];
function safescript(id, call, seconds, times, timeoutcall, endcall, index) {
seconds = seconds || 1000;
times = times || 0;
var checked = true;
try {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
} catch(e) {
checked = false;
}
if(!checked) {
if(!safescripts[id] || !index) {
safescripts[id] = safescripts[id] || [];
safescripts[id].push({
'times':0,
'si':setInterval(function () {
safescript(id, call, seconds, times, timeoutcall, endcall, safescripts[id].length);
}, seconds)
});
} else {
index = (index || 1) - 1;
safescripts[id][index]['times']++;
if(safescripts[id][index]['times'] >= times) {
clearInterval(safescripts[id][index]['si']);
if(typeof timeoutcall == 'function') {
timeoutcall();
} else {
eval(timeoutcall);
}
}
}
} else {
try {
index = (index || 1) - 1;
if(safescripts[id][index]['si']) {
clearInterval(safescripts[id][index]['si']);
}
if(typeof endcall == 'function') {
endcall();
} else {
eval(endcall);
}
} catch(e) {}
}
}
function $F(func, args, script) {
var run = function () {
var argc = args.length, s = '';
for(i = 0;i < argc;i++) {
s += ',args[' + i + ']';
}
eval('var check = typeof ' + func + ' == \'function\'');
if(check) {
eval(func + '(' + s.substr(1) + ')');
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
var checkrun = function () {
if(JSLOADED[src]) {
run();
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
script = script || 'common_extra';
src = JSPATH + script + '.js?' + VERHASH;
if(!JSLOADED[src]) {
appendscript(src);
}
checkrun();
}
function appendscript(src, text, reload, charset) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
scriptNode.onloadDone = false;
scriptNode.onload = function () {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
};
scriptNode.onreadystatechange = function () {
if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
}
};
} else if(text){
scriptNode.text = text;
}
document.getElementsByTagName('head')[0].appendChild(scriptNode);
} catch(e) {}
}
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}
function ajaxupdateevents(obj, tagName) {
tagName = tagName ? tagName : 'A';
var objs = obj.getElementsByTagName(tagName);
for(k in objs) {
var o = objs[k];
ajaxupdateevent(o);
}
}
function ajaxupdateevent(o) {
if(typeof o == 'object' && o.getAttribute) {
if(o.getAttribute('ajaxtarget')) {
if(!o.id) o.id = Math.random();
var ajaxevent = o.getAttribute('ajaxevent') ? o.getAttribute('ajaxevent') : 'click';
var ajaxurl = o.getAttribute('ajaxurl') ? o.getAttribute('ajaxurl') : o.href;
_attachEvent(o, ajaxevent, newfunction('ajaxget', ajaxurl, o.getAttribute('ajaxtarget'), o.getAttribute('ajaxwaitid'), o.getAttribute('ajaxloading'), o.getAttribute('ajaxdisplay')));
if(o.getAttribute('ajaxfunc')) {
o.getAttribute('ajaxfunc').match(/(\w+)\((.+?)\)/);
_attachEvent(o, ajaxevent, newfunction(RegExp.$1, RegExp.$2));
}
}
}
}
function ajaxget(url, showid, waitid, loading, display, recall) {
waitid = typeof waitid == 'undefined' || waitid === null ? showid : waitid;
var x = new Ajax();
x.setLoading(loading);
x.setWaitId(waitid);
x.display = typeof display == 'undefined' || display == null ? '' : display;
x.showId = $(showid);
if(url.substr(strlen(url) - 1) == '#') {
url = url.substr(0, strlen(url) - 1);
x.autogoto = 1;
}
var url = url + '&inajax=1&ajaxtarget=' + showid;
x.get(url, function(s, x) {
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
x.showId.style.display = x.display;
ajaxinnerhtml(x.showId, s);
ajaxupdateevents(x.showId);
if(x.autogoto) scroll(0, x.showId.offsetTop);
}
}
ajaxerror = null;
if(recall && typeof recall == 'function') {
recall();
} else if(recall) {
eval(recall);
}
if(!evaled) evalscript(s);
});
}
function ajaxpost(formid, showid, waitid, showidclass, submitbtn, recall) {
var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');
var showidclass = !showidclass ? '' : showidclass;
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
var curform = $(formid);
var formtarget = curform.target;
var handleResult = function() {
var s = '';
var evaled = false;
showloading('none');
try {
s = $(ajaxframeid).contentWindow.document.XMLDocument.text;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.wholeText;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.nodeValue;
} catch(e) {
s = '内部错误,无法显示此内容';
}
}
}
if(s != '' && s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(showidclass) {
if(showidclass != 'onerror') {
$(showid).className = showidclass;
} else {
showError(s);
ajaxerror = true;
}
}
if(submitbtn) {
submitbtn.disabled = false;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
ajaxinnerhtml($(showid), s);
}
ajaxerror = null;
if($(formid)) $(formid).target = formtarget;
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
if(!evaled) evalscript(s);
ajaxframe.loading = 0;
if(!BROWSER.firefox) {
$('append_parent').removeChild(ajaxframe.parentNode);
} else {
setTimeout(
function(){
$('append_parent').removeChild(ajaxframe.parentNode);
},
100
);
}
};
if(!ajaxframe) {
var div = document.createElement('div');
div.style.display = 'none';
div.innerHTML = '<iframe name="' + ajaxframeid + '" id="' + ajaxframeid + '" loading="1"></iframe>';
$('append_parent').appendChild(div);
ajaxframe = $(ajaxframeid);
} else if(ajaxframe.loading) {
return false;
}
_attachEvent(ajaxframe, 'load', handleResult);
showloading();
curform.target = ajaxframeid;
var action = curform.getAttribute('action');
action = hostconvert(action);
curform.action = action.replace(/\&inajax\=1/g, '')+'&inajax=1';
curform.submit();
if(submitbtn) {
submitbtn.disabled = true;
}
doane();
return false;
}
function ajaxmenu(ctrlObj, timeout, cache, duration, pos, recall, idclass, contentclass) {
if(!ctrlObj.getAttribute('mid')) {
var ctrlid = ctrlObj.id;
if(!ctrlid) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
} else {
var ctrlid = ctrlObj.getAttribute('mid');
if(!ctrlObj.id) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
}
var menuid = ctrlid + '_menu';
var menu = $(menuid);
if(isUndefined(timeout)) timeout = 3000;
if(isUndefined(cache)) cache = 1;
if(isUndefined(pos)) pos = '43';
if(isUndefined(duration)) duration = timeout > 0 ? 0 : 3;
if(isUndefined(idclass)) idclass = 'p_pop';
if(isUndefined(contentclass)) contentclass = 'p_opt';
var func = function() {
showMenu({'ctrlid':ctrlObj.id,'menuid':menuid,'duration':duration,'timeout':timeout,'pos':pos,'cache':cache,'layer':2});
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
};
if(menu) {
if(menu.style.display == '') {
hideMenu(menuid);
} else {
func();
}
} else {
menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = idclass;
menu.innerHTML = '<div class="' + contentclass + '" id="' + menuid + '_content"></div>';
$('append_parent').appendChild(menu);
var url = (!isUndefined(ctrlObj.attributes['shref']) ? ctrlObj.attributes['shref'].value : (!isUndefined(ctrlObj.href) ? ctrlObj.href : ctrlObj.attributes['href'].value));
url += (url.indexOf('?') != -1 ? '&' :'?') + 'ajaxmenu=1';
ajaxget(url, menuid + '_content', 'ajaxwaitid', '', '', func);
}
doane();
}
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function showPreview(val, id) {
var showObj = $(id);
if(showObj) {
showObj.innerHTML = val.replace(/\n/ig, "<bupdateseccoder />");
}
}
function showloading(display, waiting) {
var display = display ? display : 'block';
var waiting = waiting ? waiting : '请稍候...';
$('ajaxwaitid').innerHTML = waiting;
$('ajaxwaitid').style.display = display;
}
function ajaxinnerhtml(showid, s) {
if(showid.tagName != 'TBODY') {
showid.innerHTML = s;
} else {
while(showid.firstChild) {
showid.firstChild.parentNode.removeChild(showid.firstChild);
}
var div1 = document.createElement('DIV');
div1.id = showid.id+'_div';
div1.innerHTML = '<table><tbody id="'+showid.id+'_tbody">'+s+'</tbody></table>';
$('append_parent').appendChild(div1);
var trs = div1.getElementsByTagName('TR');
var l = trs.length;
for(var i=0; i<l; i++) {
showid.appendChild(trs[0]);
}
var inputs = div1.getElementsByTagName('INPUT');
var l = inputs.length;
for(var i=0; i<l; i++) {
showid.appendChild(inputs[0]);
}
div1.parentNode.removeChild(div1);
}
}
function doane(event, preventDefault, stopPropagation) {
var preventDefault = isUndefined(preventDefault) ? 1 : preventDefault;
var stopPropagation = isUndefined(stopPropagation) ? 1 : stopPropagation;
e = event ? event : window.event;
if(!e) {
e = getEvent();
}
if(!e) {
return null;
}
if(preventDefault) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
if(stopPropagation) {
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
return e;
}
function loadcss(cssname) {
if(!CSSLOADED[cssname]) {
if(!$('css_' + cssname)) {
css = document.createElement('link');
css.id = 'css_' + cssname,
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
var headNode = document.getElementsByTagName("head")[0];
headNode.appendChild(css);
} else {
$('css_' + cssname).href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
}
CSSLOADED[cssname] = 1;
}
}
function showMenu(v) {
var ctrlid = isUndefined(v['ctrlid']) ? v : v['ctrlid'];
var showid = isUndefined(v['showid']) ? ctrlid : v['showid'];
var menuid = isUndefined(v['menuid']) ? showid + '_menu' : v['menuid'];
var ctrlObj = $(ctrlid);
var menuObj = $(menuid);
if(!menuObj) return;
var mtype = isUndefined(v['mtype']) ? 'menu' : v['mtype'];
var evt = isUndefined(v['evt']) ? 'mouseover' : v['evt'];
var pos = isUndefined(v['pos']) ? '43' : v['pos'];
var layer = isUndefined(v['layer']) ? 1 : v['layer'];
var duration = isUndefined(v['duration']) ? 2 : v['duration'];
var timeout = isUndefined(v['timeout']) ? 250 : v['timeout'];
var maxh = isUndefined(v['maxh']) ? 600 : v['maxh'];
var cache = isUndefined(v['cache']) ? 1 : v['cache'];
var drag = isUndefined(v['drag']) ? '' : v['drag'];
var dragobj = drag && $(drag) ? $(drag) : menuObj;
var fade = isUndefined(v['fade']) ? 0 : v['fade'];
var cover = isUndefined(v['cover']) ? 0 : v['cover'];
var zindex = isUndefined(v['zindex']) ? JSMENU['zIndex']['menu'] : v['zindex'];
var ctrlclass = isUndefined(v['ctrlclass']) ? '' : v['ctrlclass'];
var winhandlekey = isUndefined(v['win']) ? '' : v['win'];
zindex = cover ? zindex + 500 : zindex;
if(typeof JSMENU['active'][layer] == 'undefined') {
JSMENU['active'][layer] = [];
}
for(i in EXTRAFUNC['showmenu']) {
try {
eval(EXTRAFUNC['showmenu'][i] + '()');
} catch(e) {}
}
if(evt == 'click' && in_array(menuid, JSMENU['active'][layer]) && mtype != 'win') {
hideMenu(menuid, mtype);
return;
}
if(mtype == 'menu') {
hideMenu(layer, mtype);
}
if(ctrlObj) {
if(!ctrlObj.getAttribute('initialized')) {
ctrlObj.setAttribute('initialized', true);
ctrlObj.unselectable = true;
ctrlObj.outfunc = typeof ctrlObj.onmouseout == 'function' ? ctrlObj.onmouseout : null;
ctrlObj.onmouseout = function() {
if(this.outfunc) this.outfunc();
if(duration < 3 && !JSMENU['timer'][menuid]) {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
}
};
ctrlObj.overfunc = typeof ctrlObj.onmouseover == 'function' ? ctrlObj.onmouseover : null;
ctrlObj.onmouseover = function(e) {
doane(e);
if(this.overfunc) this.overfunc();
if(evt == 'click') {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
} else {
for(var i in JSMENU['timer']) {
if(JSMENU['timer'][i]) {
clearTimeout(JSMENU['timer'][i]);
JSMENU['timer'][i] = null;
}
}
}
};
}
}
if(!menuObj.getAttribute('initialized')) {
menuObj.setAttribute('initialized', true);
menuObj.ctrlkey = ctrlid;
menuObj.mtype = mtype;
menuObj.layer = layer;
menuObj.cover = cover;
if(ctrlObj && ctrlObj.getAttribute('fwin')) {menuObj.scrolly = true;}
menuObj.style.position = 'absolute';
menuObj.style.zIndex = zindex + layer;
menuObj.onclick = function(e) {
return doane(e, 0, 1);
};
if(duration < 3) {
if(duration > 1) {
menuObj.onmouseover = function() {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
};
}
if(duration != 1) {
menuObj.onmouseout = function() {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
};
}
}
if(cover) {
var coverObj = document.createElement('div');
coverObj.id = menuid + '_cover';
coverObj.style.position = 'absolute';
coverObj.style.zIndex = menuObj.style.zIndex - 1;
coverObj.style.left = coverObj.style.top = '0px';
coverObj.style.width = '100%';
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
coverObj.style.backgroundColor = '#000';
coverObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
coverObj.style.opacity = 0.5;
coverObj.onclick = function () { hideMenu(); };
$('append_parent').appendChild(coverObj);
_attachEvent(window, 'load', function () {
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
}, document);
}
}
if(drag) {
dragobj.style.cursor = 'move';
dragobj.onmousedown = function(event) {try{dragMenu(menuObj, event, 1);}catch(e){}};
}
if(cover) $(menuid + '_cover').style.display = '';
if(fade) {
var O = 0;
var fadeIn = function(O) {
if(O > 100) {
clearTimeout(fadeInTimer);
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O += 20;
var fadeInTimer = setTimeout(function () {
fadeIn(O);
}, 40);
};
fadeIn(O);
menuObj.fade = true;
} else {
menuObj.fade = false;
}
menuObj.style.display = '';
if(ctrlObj && ctrlclass) {
ctrlObj.className += ' ' + ctrlclass;
menuObj.setAttribute('ctrlid', ctrlid);
menuObj.setAttribute('ctrlclass', ctrlclass);
}
if(pos != '*') {
setMenuPosition(showid, menuid, pos);
}
if(BROWSER.ie && BROWSER.ie < 7 && winhandlekey && $('fwin_' + winhandlekey)) {
$(menuid).style.left = (parseInt($(menuid).style.left) - parseInt($('fwin_' + winhandlekey).style.left)) + 'px';
$(menuid).style.top = (parseInt($(menuid).style.top) - parseInt($('fwin_' + winhandlekey).style.top)) + 'px';
}
if(maxh && menuObj.scrollHeight > maxh) {
menuObj.style.height = maxh + 'px';
if(BROWSER.opera) {
menuObj.style.overflow = 'auto';
} else {
menuObj.style.overflowY = 'auto';
}
}
if(!duration) {
setTimeout('hideMenu(\'' + menuid + '\', \'' + mtype + '\')', timeout);
}
if(!in_array(menuid, JSMENU['active'][layer])) JSMENU['active'][layer].push(menuid);
menuObj.cache = cache;
if(layer > JSMENU['layer']) {
JSMENU['layer'] = layer;
}
var hasshow = function(ele) {
while(ele.parentNode && ((typeof(ele['currentStyle']) === 'undefined') ? window.getComputedStyle(ele,null) : ele['currentStyle'])['display'] !== 'none') {
ele = ele.parentNode;
}
if(ele === document) {
return true;
} else {
return false;
}
};
if(!menuObj.getAttribute('disautofocus')) {
try{
var focused = false;
var tags = ['input', 'select', 'textarea', 'button', 'a'];
for(var i = 0; i < tags.length; i++) {
var _all = menuObj.getElementsByTagName(tags[i]);
if(_all.length) {
for(j = 0; j < _all.length; j++) {
if((!_all[j]['type'] || _all[j]['type'] != 'hidden') && hasshow(_all[j])) {
_all[j].className += ' hidefocus';
_all[j].focus();
focused = true;
var cobj = _all[j];
_attachEvent(_all[j], 'blur', function (){cobj.className = trim(cobj.className.replace(' hidefocus', ''));});
break;
}
}
}
if(focused) {
break;
}
}
} catch (e) {
}
}
}
var delayShowST = null;
function delayShow(ctrlObj, call, time) {
if(typeof ctrlObj == 'object') {
var ctrlid = ctrlObj.id;
call = call || function () { showMenu(ctrlid); };
}
var time = isUndefined(time) ? 500 : time;
delayShowST = setTimeout(function () {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
}, time);
if(!ctrlObj.delayinit) {
_attachEvent(ctrlObj, 'mouseout', function() {clearTimeout(delayShowST);});
ctrlObj.delayinit = 1;
}
}
var dragMenuDisabled = false;
function dragMenu(menuObj, e, op) {
e = e ? e : window.event;
if(op == 1) {
if(dragMenuDisabled || in_array(e.target ? e.target.tagName : e.srcElement.tagName, ['TEXTAREA', 'INPUT', 'BUTTON', 'SELECT'])) {
return;
}
JSMENU['drag'] = [e.clientX, e.clientY];
JSMENU['drag'][2] = parseInt(menuObj.style.left);
JSMENU['drag'][3] = parseInt(menuObj.style.top);
document.onmousemove = function(e) {try{dragMenu(menuObj, e, 2);}catch(err){}};
document.onmouseup = function(e) {try{dragMenu(menuObj, e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && JSMENU['drag'][0]) {
var menudragnow = [e.clientX, e.clientY];
menuObj.style.left = (JSMENU['drag'][2] + menudragnow[0] - JSMENU['drag'][0]) + 'px';
menuObj.style.top = (JSMENU['drag'][3] + menudragnow[1] - JSMENU['drag'][1]) + 'px';
menuObj.removeAttribute('top_');menuObj.removeAttribute('left_');
doane(e);
}else if(op == 3) {
JSMENU['drag'] = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function setMenuPosition(showid, menuid, pos) {
var showObj = $(showid);
var menuObj = menuid ? $(menuid) : $(showid + '_menu');
if(isUndefined(pos) || !pos) pos = '43';
var basePoint = parseInt(pos.substr(0, 1));
var direction = parseInt(pos.substr(1, 1));
var important = pos.indexOf('!') != -1 ? 1 : 0;
var sxy = 0, sx = 0, sy = 0, sw = 0, sh = 0, ml = 0, mt = 0, mw = 0, mcw = 0, mh = 0, mch = 0, bpl = 0, bpt = 0;
if(!menuObj || (basePoint > 0 && !showObj)) return;
if(showObj) {
sxy = fetchOffset(showObj);
sx = sxy['left'];
sy = sxy['top'];
sw = showObj.offsetWidth;
sh = showObj.offsetHeight;
}
mw = menuObj.offsetWidth;
mcw = menuObj.clientWidth;
mh = menuObj.offsetHeight;
mch = menuObj.clientHeight;
switch(basePoint) {
case 1:
bpl = sx;
bpt = sy;
break;
case 2:
bpl = sx + sw;
bpt = sy;
break;
case 3:
bpl = sx + sw;
bpt = sy + sh;
break;
case 4:
bpl = sx;
bpt = sy + sh;
break;
}
switch(direction) {
case 0:
menuObj.style.left = (document.body.clientWidth - menuObj.clientWidth) / 2 + 'px';
mt = (document.documentElement.clientHeight - menuObj.clientHeight) / 2;
break;
case 1:
ml = bpl - mw;
mt = bpt - mh;
break;
case 2:
ml = bpl;
mt = bpt - mh;
break;
case 3:
ml = bpl;
mt = bpt;
break;
case 4:
ml = bpl - mw;
mt = bpt;
break;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(!important) {
if(in_array(direction, [1, 4]) && ml < 0) {
ml = bpl;
if(in_array(basePoint, [1, 4])) ml += sw;
} else if(ml + mw > scrollLeft + document.body.clientWidth && sx >= mw) {
ml = bpl - mw;
if(in_array(basePoint, [2, 3])) {
ml -= sw;
} else if(basePoint == 4) {
ml += sw;
}
}
if(in_array(direction, [1, 2]) && mt < 0) {
mt = bpt;
if(in_array(basePoint, [1, 2])) mt += sh;
} else if(mt + mh > scrollTop + document.documentElement.clientHeight && sy >= mh) {
mt = bpt - mh;
if(in_array(basePoint, [3, 4])) mt -= sh;
}
}
if(pos.substr(0, 3) == '210') {
ml += 69 - sw / 2;
mt -= 5;
if(showObj.tagName == 'TEXTAREA') {
ml -= sw / 2;
mt += sh / 2;
}
}
if(direction == 0 || menuObj.scrolly) {
if(BROWSER.ie && BROWSER.ie < 7) {
if(direction == 0) mt += scrollTop;
} else {
if(menuObj.scrolly) mt -= scrollTop;
menuObj.style.position = 'fixed';
}
}
if(ml) menuObj.style.left = ml + 'px';
if(mt) menuObj.style.top = mt + 'px';
if(direction == 0 && BROWSER.ie && !document.documentElement.clientHeight) {
menuObj.style.position = 'absolute';
menuObj.style.top = (document.body.clientHeight - menuObj.clientHeight) / 2 + 'px';
}
if(menuObj.style.clip && !BROWSER.opera) {
menuObj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function hideMenu(attr, mtype) {
attr = isUndefined(attr) ? '' : attr;
mtype = isUndefined(mtype) ? 'menu' : mtype;
if(attr == '') {
for(var i = 1; i <= JSMENU['layer']; i++) {
hideMenu(i, mtype);
}
return;
} else if(typeof attr == 'number') {
for(var j in JSMENU['active'][attr]) {
hideMenu(JSMENU['active'][attr][j], mtype);
}
return;
}else if(typeof attr == 'string') {
var menuObj = $(attr);
if(!menuObj || (mtype && menuObj.mtype != mtype)) return;
var ctrlObj = '', ctrlclass = '';
if((ctrlObj = $(menuObj.getAttribute('ctrlid'))) && (ctrlclass = menuObj.getAttribute('ctrlclass'))) {
var reg = new RegExp(' ' + ctrlclass);
ctrlObj.className = ctrlObj.className.replace(reg, '');
}
clearTimeout(JSMENU['timer'][attr]);
var hide = function() {
if(menuObj.cache) {
if(menuObj.style.visibility != 'hidden') {
menuObj.style.display = 'none';
if(menuObj.cover) $(attr + '_cover').style.display = 'none';
}
}else {
menuObj.parentNode.removeChild(menuObj);
if(menuObj.cover) $(attr + '_cover').parentNode.removeChild($(attr + '_cover'));
}
var tmp = [];
for(var k in JSMENU['active'][menuObj.layer]) {
if(attr != JSMENU['active'][menuObj.layer][k]) tmp.push(JSMENU['active'][menuObj.layer][k]);
}
JSMENU['active'][menuObj.layer] = tmp;
};
if(menuObj.fade) {
var O = 100;
var fadeOut = function(O) {
if(O == 0) {
clearTimeout(fadeOutTimer);
hide();
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O -= 20;
var fadeOutTimer = setTimeout(function () {
fadeOut(O);
}, 40);
};
fadeOut(O);
} else {
hide();
}
}
}
function getCurrentStyle(obj, cssproperty, csspropertyNS) {
if(obj.style[cssproperty]){
return obj.style[cssproperty];
}
if (obj.currentStyle) {
return obj.currentStyle[cssproperty];
} else if (document.defaultView.getComputedStyle(obj, null)) {
var currentStyle = document.defaultView.getComputedStyle(obj, null);
var value = currentStyle.getPropertyValue(csspropertyNS);
if(!value){
value = currentStyle[cssproperty];
}
return value;
} else if (window.getComputedStyle) {
var currentStyle = window.getComputedStyle(obj, "");
return currentStyle.getPropertyValue(csspropertyNS);
}
}
function fetchOffset(obj, mode) {
var left_offset = 0, top_offset = 0, mode = !mode ? 0 : mode;
if(obj.getBoundingClientRect && !mode) {
var rect = obj.getBoundingClientRect();
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(document.documentElement.dir == 'rtl') {
scrollLeft = scrollLeft + document.documentElement.clientWidth - document.documentElement.scrollWidth;
}
left_offset = rect.left + scrollLeft - document.documentElement.clientLeft;
top_offset = rect.top + scrollTop - document.documentElement.clientTop;
}
if(left_offset <= 0 || top_offset <= 0) {
left_offset = obj.offsetLeft;
top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
position = getCurrentStyle(obj, 'position', 'position');
if(position == 'relative') {
continue;
}
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
}
return {'left' : left_offset, 'top' : top_offset};
}
function showTip(ctrlobj) {
$F('_showTip', arguments);
}
function showPrompt(ctrlid, evt, msg, timeout) {
$F('_showPrompt', arguments);
}
function showCreditPrompt() {
$F('_showCreditPrompt', []);
}
var showDialogST = null;
function showDialog(msg, mode, t, func, cover, funccancel, leftmsg, confirmtxt, canceltxt, closetime, locationtime) {
clearTimeout(showDialogST);
cover = isUndefined(cover) ? (mode == 'info' ? 0 : 1) : cover;
leftmsg = isUndefined(leftmsg) ? '' : leftmsg;
mode = in_array(mode, ['confirm', 'notice', 'info', 'right']) ? mode : 'alert';
var menuid = 'fwin_dialog';
var menuObj = $(menuid);
var showconfirm = 1;
confirmtxtdefault = '确定';
closetime = isUndefined(closetime) ? '' : closetime;
closefunc = function () {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if(closetime) {
leftmsg = closetime + ' 秒后窗口关闭';
showDialogST = setTimeout(closefunc, closetime * 1000);
showconfirm = 0;
}
locationtime = isUndefined(locationtime) ? '' : locationtime;
if(locationtime) {
leftmsg = locationtime + ' 秒后页面跳转';
showDialogST = setTimeout(closefunc, locationtime * 1000);
showconfirm = 0;
}
confirmtxt = confirmtxt ? confirmtxt : confirmtxtdefault;
canceltxt = canceltxt ? canceltxt : '取消';
if(menuObj) hideMenu('fwin_dialog', 'dialog');
menuObj = document.createElement('div');
menuObj.style.display = 'none';
menuObj.className = 'fwinmask';
menuObj.id = menuid;
$('append_parent').appendChild(menuObj);
var hidedom = '';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
var s = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c"><h3 class="flb"><em>';
s += t ? t : '提示信息';
s += '</em><span><a href="javascript:;" id="fwin_dialog_close" class="flbc" onclick="hideMenu(\'' + menuid + '\', \'dialog\')" title="关闭">关闭</a></span></h3>';
if(mode == 'info') {
s += msg ? msg : '';
} else {
s += '<div class="c altw"><div class="' + (mode == 'alert' ? 'alert_error' : (mode == 'right' ? 'alert_right' : 'alert_info')) + '"><p>' + msg + '</p></div></div>';
s += '<p class="o pns">' + (leftmsg ? '<span class="z xg1">' + leftmsg + '</span>' : '') + (showconfirm ? '<button id="fwin_dialog_submit" value="true" class="pn pnc"><strong>'+confirmtxt+'</strong></button>' : '');
s += mode == 'confirm' ? '<button id="fwin_dialog_cancel" value="true" class="pn" onclick="hideMenu(\'' + menuid + '\', \'dialog\')"><strong>'+canceltxt+'</strong></button>' : '';
s += '</p>';
}
s += '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
menuObj.innerHTML = s;
if($('fwin_dialog_submit')) $('fwin_dialog_submit').onclick = function() {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if($('fwin_dialog_cancel')) {
$('fwin_dialog_cancel').onclick = function() {
if(typeof funccancel == 'function') funccancel();
else eval(funccancel);
hideMenu(menuid, 'dialog');
};
$('fwin_dialog_close').onclick = $('fwin_dialog_cancel').onclick;
}
showMenu({'mtype':'dialog','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['dialog'],'cache':0,'cover':cover});
try {
if($('fwin_dialog_submit')) $('fwin_dialog_submit').focus();
} catch(e) {}
}
function showWindow(k, url, mode, cache, menuv) {
mode = isUndefined(mode) ? 'get' : mode;
cache = isUndefined(cache) ? 1 : cache;
var menuid = 'fwin_' + k;
var menuObj = $(menuid);
var drag = null;
var loadingst = null;
var hidedom = '';
if(disallowfloat && disallowfloat.indexOf(k) != -1) {
if(BROWSER.ie) url += (url.indexOf('?') != -1 ? '&' : '?') + 'referer=' + escape(location.href);
location.href = url;
doane();
return;
}
var fetchContent = function() {
if(mode == 'get') {
menuObj.url = url;
url += (url.search(/\?/) > 0 ? '&' : '?') + 'infloat=yes&handlekey=' + k;
url += cache == -1 ? '&t='+(+ new Date()) : '';
if(BROWSER.ie && url.indexOf('referer=') < 0) {
url = url + '&referer=' + encodeURIComponent(location);
}
ajaxget(url, 'fwin_content_' + k, null, '', '', function() {initMenu();show();});
} else if(mode == 'post') {
menuObj.act = $(url).action;
ajaxpost(url, 'fwin_content_' + k, '', '', '', function() {initMenu();show();});
}
if(parseInt(BROWSER.ie) != 6) {
loadingst = setTimeout(function() {showDialog('', 'info', '<img src="' + IMGDIR + '/loading.gif"> 请稍候...')}, 500);
}
};
var initMenu = function() {
clearTimeout(loadingst);
var objs = menuObj.getElementsByTagName('*');
var fctrlidinit = false;
for(var i = 0; i < objs.length; i++) {
if(objs[i].id) {
objs[i].setAttribute('fwin', k);
}
if(objs[i].className == 'flb' && !fctrlidinit) {
if(!objs[i].id) objs[i].id = 'fctrl_' + k;
drag = objs[i].id;
fctrlidinit = true;
}
}
};
var show = function() {
hideMenu('fwin_dialog', 'dialog');
v = {'mtype':'win','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['win'],'drag':typeof drag == null ? '' : drag,'cache':cache};
for(k in menuv) {
v[k] = menuv[k];
}
showMenu(v);
};
if(!menuObj) {
menuObj = document.createElement('div');
menuObj.id = menuid;
menuObj.className = 'fwinmask';
menuObj.style.display = 'none';
$('append_parent').appendChild(menuObj);
evt = ' style="cursor:move" onmousedown="dragMenu($(\'' + menuid + '\'), event, 1)" ondblclick="hideWindow(\'' + k + '\')"';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
menuObj.innerHTML = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"' + evt + '></td><td class="t_r"></td></tr><tr><td class="m_l"' + evt + ')"> </td><td class="m_c" id="fwin_content_' + k + '">'
+ '</td><td class="m_r"' + evt + '"></td></tr><tr><td class="b_l"></td><td class="b_c"' + evt + '></td><td class="b_r"></td></tr></table>';
if(mode == 'html') {
$('fwin_content_' + k).innerHTML = url;
initMenu();
show();
} else {
fetchContent();
}
} else if((mode == 'get' && (url != menuObj.url || cache != 1)) || (mode == 'post' && $(url).action != menuObj.act)) {
fetchContent();
} else {
show();
}
doane();
}
function showError(msg) {
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
msg = msg.replace(p, '');
if(msg !== '') {
showDialog(msg, 'alert', '错误信息', null, true, null, '', '', '', 3);
}
}
function hideWindow(k, all, clear) {
all = isUndefined(all) ? 1 : all;
clear = isUndefined(clear) ? 1 : clear;
hideMenu('fwin_' + k, 'win');
if(clear && $('fwin_' + k)) {
$('append_parent').removeChild($('fwin_' + k));
}
if(all) {
hideMenu();
}
}
function AC_FL_RunContent() {
var str = '';
var ret = AC_GetArgs(arguments, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
if(BROWSER.ie && !BROWSER.opera) {
str += '<object ';
for (var i in ret.objAttrs) {
str += i + '="' + ret.objAttrs[i] + '" ';
}
str += '>';
for (var i in ret.params) {
str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
}
str += '</object>';
} else {
str += '<embed ';
for (var i in ret.embedAttrs) {
str += i + '="' + ret.embedAttrs[i] + '" ';
}
str += '></embed>';
}
return str;
}
function AC_GetArgs(args, classid, mimeType) {
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i = 0; i < args.length; i = i + 2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":break;
case "pluginspage":ret.embedAttrs[args[i]] = 'http://www.macromedia.com/go/getflashplayer';break;
case "src":ret.embedAttrs[args[i]] = args[i+1];ret.params["movie"] = args[i+1];break;
case "codebase":ret.objAttrs[args[i]] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';break;
case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblclick":case "ondrag":case "ondragend":
case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":
case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":
case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":
case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":
case "id":ret.objAttrs[args[i]] = args[i+1];break;
case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":
case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;
default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if(mimeType) {
ret.embedAttrs["type"] = mimeType;
}
return ret;
}
function simulateSelect(selectId, widthvalue) {
var selectObj = $(selectId);
if(!selectObj) return;
if(BROWSER.other) {
if(selectObj.getAttribute('change')) {
selectObj.onchange = function () {eval(selectObj.getAttribute('change'));}
}
return;
}
var widthvalue = widthvalue ? widthvalue : 70;
var defaultopt = selectObj.options[0] ? selectObj.options[0].innerHTML : '';
var defaultv = '';
var menuObj = document.createElement('div');
var ul = document.createElement('ul');
var handleKeyDown = function(e) {
e = BROWSER.ie ? event : e;
if(e.keyCode == 40 || e.keyCode == 38) doane(e);
};
var selectwidth = (selectObj.getAttribute('width', i) ? selectObj.getAttribute('width', i) : widthvalue) + 'px';
var tabindex = selectObj.getAttribute('tabindex', i) ? selectObj.getAttribute('tabindex', i) : 1;
for(var i = 0; i < selectObj.options.length; i++) {
var li = document.createElement('li');
li.innerHTML = selectObj.options[i].innerHTML;
li.k_id = i;
li.k_value = selectObj.options[i].value;
if(selectObj.options[i].selected) {
defaultopt = selectObj.options[i].innerHTML;
defaultv = selectObj.options[i].value;
li.className = 'current';
selectObj.setAttribute('selecti', i);
}
li.onclick = function() {
if($(selectId + '_ctrl').innerHTML != this.innerHTML) {
var lis = menuObj.getElementsByTagName('li');
lis[$(selectId).getAttribute('selecti')].className = '';
this.className = 'current';
$(selectId + '_ctrl').innerHTML = this.innerHTML;
$(selectId).setAttribute('selecti', this.k_id);
$(selectId).options.length = 0;
$(selectId).options[0] = new Option('', this.k_value);
eval(selectObj.getAttribute('change'));
}
hideMenu(menuObj.id);
return false;
};
ul.appendChild(li);
}
selectObj.options.length = 0;
selectObj.options[0]= new Option('', defaultv);
selectObj.style.display = 'none';
selectObj.outerHTML += '<a href="javascript:;" id="' + selectId + '_ctrl" style="width:' + selectwidth + '" tabindex="' + tabindex + '">' + defaultopt + '</a>';
menuObj.id = selectId + '_ctrl_menu';
menuObj.className = 'sltm';
menuObj.style.display = 'none';
menuObj.style.width = selectwidth;
menuObj.appendChild(ul);
$('append_parent').appendChild(menuObj);
$(selectId + '_ctrl').onclick = function(e) {
$(selectId + '_ctrl_menu').style.width = selectwidth;
showMenu({'ctrlid':(selectId == 'loginfield' ? 'account' : selectId + '_ctrl'),'menuid':selectId + '_ctrl_menu','evt':'click','pos':'43'});
doane(e);
};
$(selectId + '_ctrl').onfocus = menuObj.onfocus = function() {
_attachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onblur = menuObj.onblur = function() {
_detachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onkeyup = function(e) {
e = e ? e : window.event;
value = e.keyCode;
if(value == 40 || value == 38) {
if(menuObj.style.display == 'none') {
$(selectId + '_ctrl').onclick();
} else {
lis = menuObj.getElementsByTagName('li');
selecti = selectObj.getAttribute('selecti');
lis[selecti].className = '';
if(value == 40) {
selecti = parseInt(selecti) + 1;
} else if(value == 38) {
selecti = parseInt(selecti) - 1;
}
if(selecti < 0) {
selecti = lis.length - 1
} else if(selecti > lis.length - 1) {
selecti = 0;
}
lis[selecti].className = 'current';
selectObj.setAttribute('selecti', selecti);
lis[selecti].parentNode.scrollTop = lis[selecti].offsetTop;
}
} else if(value == 13) {
var lis = menuObj.getElementsByTagName('li');
lis[selectObj.getAttribute('selecti')].onclick();
} else if(value == 27) {
hideMenu(menuObj.id);
}
};
}
function switchTab(prefix, current, total, activeclass) {
$F('_switchTab', arguments);
}
function imageRotate(imgid, direct) {
$F('_imageRotate', arguments);
}
function thumbImg(obj, method) {
if(!obj) {
return;
}
obj.onload = null;
file = obj.src;
zw = obj.offsetWidth;
zh = obj.offsetHeight;
if(zw < 2) {
if(!obj.id) {
obj.id = 'img_' + Math.random();
}
setTimeout("thumbImg($('" + obj.id + "'), " + method + ")", 100);
return;
}
zr = zw / zh;
method = !method ? 0 : 1;
if(method) {
fixw = obj.getAttribute('_width');
fixh = obj.getAttribute('_height');
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
}
if(zh > fixh) {
zh = fixh;
zw = zh * zr;
}
} else {
fixw = typeof imagemaxwidth == 'undefined' ? '600' : imagemaxwidth;
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
obj.style.cursor = 'pointer';
if(!obj.onclick) {
obj.onclick = function() {
zoom(obj, obj.src);
};
}
}
}
obj.width = zw;
obj.height = zh;
}
var zoomstatus = 1;
function zoom(obj, zimg, nocover, pn, showexif) {
$F('_zoom', arguments);
}
function showselect(obj, inpid, t, rettype) {
$F('_showselect', arguments);
}
function showColorBox(ctrlid, layer, k, bgcolor) {
$F('_showColorBox', arguments);
}
function ctrlEnter(event, btnId, onlyEnter) {
if(isUndefined(onlyEnter)) onlyEnter = 0;
if((event.ctrlKey || onlyEnter) && event.keyCode == 13) {
$(btnId).click();
return false;
}
return true;
}
function parseurl(str, mode, parsecode) {
if(isUndefined(parsecode)) parsecode = true;
if(parsecode) str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
str = str.replace(/([^>=\]"'\/@]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|qqdl|synacast):\/\/))([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w>=\]"'\/@]|^)((www\.)([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w->=\]:"'\.\/]|^)(([\-\.\w]+@[\.\-\w]+(\.\w+)+))/ig, mode == 'html' ? '$1<a href="mailto:$2">$2</a>' : '$1[email]$2[/email]');
if(parsecode) {
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
}
return str;
}
function codetag(text) {
DISCUZCODE['num']++;
if(typeof wysiwyg != 'undefined' && wysiwyg) text = text.replace(/<br[^\>]*>/ig, '\n');
text = text.replace(/\$/ig, '$$$$');
DISCUZCODE['html'][DISCUZCODE['num']] = '[code]' + text + '[/code]';
return '[\tDISCUZ_CODE_' + DISCUZCODE['num'] + '\t]';
}
function saveUserdata(name, data) {
try {
if(window.localStorage){
localStorage.setItem('Discuz_' + name, data);
} else if(window.sessionStorage){
sessionStorage.setItem('Discuz_' + name, data);
}
} catch(e) {
if(BROWSER.ie){
if(data.length < 54889) {
with(document.documentElement) {
setAttribute("value", data);
save('Discuz_' + name);
}
}
}
}
setcookie('clearUserdata', '', -1);
}
function loadUserdata(name) {
if(window.localStorage){
return localStorage.getItem('Discuz_' + name);
} else if(window.sessionStorage){
return sessionStorage.getItem('Discuz_' + name);
} else if(BROWSER.ie){
with(document.documentElement) {
load('Discuz_' + name);
return getAttribute("value");
}
}
}
function initTab(frameId, type) {
$F('_initTab', arguments);
}
function openDiy(){
window.location.href = ((window.location.href + '').replace(/[\?\&]diy=yes/g, '').split('#')[0] + ( window.location.search && window.location.search.indexOf('?diy=yes') < 0 ? '&diy=yes' : '?diy=yes'));
}
function hasClass(elem, className) {
return elem.className && (" " + elem.className + " ").indexOf(" " + className + " ") != -1;
}
function runslideshow() {
$F('_runslideshow', []);
}
function toggle_collapse(objname, noimg, complex, lang) {
$F('_toggle_collapse', arguments);
}
function updatestring(str1, str2, clear) {
str2 = '_' + str2 + '_';
return clear ? str1.replace(str2, '') : (str1.indexOf(str2) == -1 ? str1 + str2 : str1);
}
function getClipboardData() {
window.document.clipboardswf.SetVariable('str', CLIPBOARDSWFDATA);
}
function setCopy(text, msg) {
$F('_setCopy', arguments);
}
function copycode(obj) {
$F('_copycode', arguments);
}
function showdistrict(container, elems, totallevel, changelevel, containertype) {
$F('_showdistrict', arguments);
}
function setDoodle(fid, oid, url, tid, from) {
$F('_setDoodle', arguments);
}
function initSearchmenu(searchform, cloudSearchUrl) {
var defaultUrl = 'search.php?searchsubmit=yes';
if(typeof cloudSearchUrl == "undefined" || cloudSearchUrl == null || cloudSearchUrl == '') {
cloudSearchUrl = defaultUrl;
}
var searchtxt = $(searchform + '_txt');
if(!searchtxt) {
searchtxt = $(searchform);
}
var tclass = searchtxt.className;
searchtxt.className = tclass + ' xg1';
if (!!("placeholder" in document.createElement("input"))) {
if(searchtxt.value == '请输入搜索内容') {
searchtxt.value = '';
}
searchtxt.placeholder = '请输入搜索内容';
} else {
searchtxt.onfocus = function () {
if(searchtxt.value == '请输入搜索内容') {
searchtxt.value = '';
searchtxt.className = tclass;
}
};
searchtxt.onblur = function () {
if(searchtxt.value == '' ) {
searchtxt.value = '请输入搜索内容';
searchtxt.className = tclass + ' xg1';
}
};
}
if(!$(searchform + '_type_menu')) return false;
var o = $(searchform + '_type');
var a = $(searchform + '_type_menu').getElementsByTagName('a');
var formobj = searchtxt.form;
for(var i=0; i<a.length; i++){
if(a[i].className == 'curtype'){
o.innerHTML = a[i].innerHTML;
$(searchform + '_mod').value = a[i].rel;
formobj.method = 'post';
if((a[i].rel == 'forum' || a[i].rel == 'curforum') && defaultUrl != cloudSearchUrl) {
formobj.action = cloudSearchUrl;
formobj.method = 'get';
if($('srchFId')) {
$('srchFId').value = a[i].rel == 'forum' ? 0 : a[i].getAttribute('fid');
}
} else {
formobj.action = defaultUrl;
}
}
a[i].onclick = function(){
o.innerHTML = this.innerHTML;
$(searchform + '_mod').value = this.rel;
formobj.method = 'post';
if((this.rel == 'forum' || this.rel == 'curforum') && defaultUrl != cloudSearchUrl) {
formobj.action = cloudSearchUrl;
formobj.method = 'get';
if($('srchFId')) {
$('srchFId').value = this.rel == 'forum' ? 0 : this.getAttribute('fid');
}
} else {
formobj.action = defaultUrl;
}
};
}
}
function searchFocus(obj) {
if(obj.value == '请输入搜索内容') {
obj.value = '';
}
if($('cloudsearchquery') != null) {
$('cloudsearchquery').value = obj.value;
}
}
function extstyle(css) {
$F('_extstyle', arguments);
}
function widthauto(obj) {
$F('_widthauto', arguments);
}
var secST = new Array();
function updatesecqaa(idhash) {
$F('_updatesecqaa', arguments);
}
function updateseccode(idhash, play) {
$F('_updateseccode', arguments);
}
function checksec(type, idhash, showmsg, recall) {
$F('_checksec', arguments);
}
function createPalette(colorid, id, func) {
$F('_createPalette', arguments);
}
function showForummenu(fid) {
$F('_showForummenu', arguments);
}
function cardInit() {
var cardShow = function (obj) {
if(BROWSER.ie && BROWSER.ie < 7 && obj.href.indexOf('username') != -1) {
return;
}
pos = obj.getAttribute('c') == '1' ? '43' : obj.getAttribute('c');
USERCARDST = setTimeout(function() {ajaxmenu(obj, 500, 1, 2, pos, null, 'p_pop card');}, 250);
};
var cardids = {};
var a = document.body.getElementsByTagName('a');
for(var i = 0;i < a.length;i++){
if(a[i].getAttribute('c')) {
var href = a[i].getAttribute('href', 1);
if(typeof cardids[href] == 'undefined') {
cardids[href] = Math.round(Math.random()*10000);
}
a[i].setAttribute('mid', 'card_' + cardids[href]);
a[i].onmouseover = function() {cardShow(this)};
a[i].onmouseout = function() {clearTimeout(USERCARDST);};
}
}
}
function navShow(id) {
var mnobj = $('snav_mn_' + id);
if(!mnobj) {
return;
}
var uls = $('mu').getElementsByTagName('ul');
for(i = 0;i < uls.length;i++) {
if(uls[i].className != 'cl current') {
uls[i].style.display = 'none';
}
}
if(mnobj.className != 'cl current') {
showMenu({'ctrlid':'mn_' + id,'menuid':'snav_mn_' + id,'pos':'*'});
mnobj.className = 'cl floatmu';
mnobj.style.width = ($('nv').clientWidth) + 'px';
mnobj.style.display = '';
}
}
function strLenCalc(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = maxlen, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen -= charset == 'utf-8' ? 2 : 1;
}
}
if(curlen >= len) {
$(checklen).innerHTML = curlen - len;
} else {
obj.value = mb_cutstr(v, maxlen, 0);
}
}
function patchNotice() {
if($('patch_notice')) {
ajaxget('misc.php?mod=patch&action=patchnotice', 'patch_notice', '');
}
}
function pluginNotice() {
if($('plugin_notice')) {
ajaxget('misc.php?mod=patch&action=pluginnotice', 'plugin_notice', '');
}
}
function noticeTitle() {
NOTICETITLE = {'State':0, 'oldTitle':document.title, flashNumber:0, sleep:15};
if(!getcookie('noticeTitle')) {
window.setInterval('noticeTitleFlash();', 500);
} else {
window.setTimeout('noticeTitleFlash();', 500);
}
setcookie('noticeTitle', 1, 600);
}
function noticeTitleFlash() {
if(NOTICETITLE.flashNumber < 5 || NOTICETITLE.flashNumber > 4 && !NOTICETITLE['State']) {
document.title = (NOTICETITLE['State'] ? '【 】' : '【新提醒】') + NOTICETITLE['oldTitle'];
NOTICETITLE['State'] = !NOTICETITLE['State'];
}
NOTICETITLE.flashNumber = NOTICETITLE.flashNumber < NOTICETITLE.sleep ? ++NOTICETITLE.flashNumber : 0;
}
function relatedlinks(rlinkmsgid) {
$F('_relatedlinks', arguments);
}
function con_handle_response(response) {
return response;
}
function showTopLink() {
var ft = $('ft');
if(ft){
var scrolltop = $('scrolltop');
var viewPortHeight = parseInt(document.documentElement.clientHeight);
var scrollHeight = parseInt(document.body.getBoundingClientRect().top);
var basew = parseInt(ft.clientWidth);
var sw = scrolltop.clientWidth;
if (basew < 1000) {
var left = parseInt(fetchOffset(ft)['left']);
left = left < sw ? left * 2 - sw : left;
scrolltop.style.left = ( basew + left ) + 'px';
} else {
scrolltop.style.left = 'auto';
scrolltop.style.right = 0;
}
if (BROWSER.ie && BROWSER.ie < 7) {
scrolltop.style.top = viewPortHeight - scrollHeight - 150 + 'px';
}
if (scrollHeight < -100) {
scrolltop.style.visibility = 'visible';
} else {
scrolltop.style.visibility = 'hidden';
}
}
}
function showCreditmenu() {
$F('_showCreditmenu', []);
}
function showUpgradeinfo() {
showMenu({'ctrlid':'g_upmine', 'pos':'21'});
}
function addFavorite(url, title) {
try {
window.external.addFavorite(url, title);
} catch (e){
try {
window.sidebar.addPanel(title, url, '');
} catch (e) {
showDialog("请按 Ctrl+D 键添加到收藏夹", 'notice');
}
}
}
function setHomepage(sURL) {
if(BROWSER.ie){
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage(sURL);
} else {
showDialog("非 IE 浏览器请手动将本站设为首页", 'notice');
doane();
}
}
function smilies_show(id, smcols, seditorkey) {
$F('_smilies_show', arguments, 'smilies');
}
function showfocus(ftype, autoshow) {
var id = parseInt($('focuscur').innerHTML);
if(ftype == 'prev') {
id = (id-1) < 1 ? focusnum : (id-1);
if(!autoshow) {
window.clearInterval(focusautoshow);
}
} else if(ftype == 'next') {
id = (id+1) > focusnum ? 1 : (id+1);
if(!autoshow) {
window.clearInterval(focusautoshow);
}
}
$('focuscur').innerHTML = id;
$('focus_con').innerHTML = $('focus_'+(id-1)).innerHTML;
}
function rateStarHover(target,level) {
if(level == 0) {
$(target).style.width = '';
} else {
$(target).style.width = level * 16 + 'px';
}
}
function rateStarSet(target,level,input) {
$(input).value = level;
$(target).className = 'star star' + level;
}
function img_onmouseoverfunc(obj) {
if(typeof showsetcover == 'function') {
showsetcover(obj);
}
return;
}
function toggleBlind(dom) {
if(dom) {
if(loadUserdata('is_blindman')) {
saveUserdata('is_blindman', '');
dom.title = '开启辅助访问';
} else {
saveUserdata('is_blindman', '1');
dom.title = '关闭辅助访问';
}
}
}
function checkBlind() {
var dom = $('switchblind');
if(dom) {
if(loadUserdata('is_blindman')) {
dom.title = '关闭辅助访问';
} else {
dom.title = '开启辅助访问';
}
}
}
if(typeof IN_ADMINCP == 'undefined') {
if(creditnotice != '' && getcookie('creditnotice')) {
_attachEvent(window, 'load', showCreditPrompt, document);
}
if(typeof showusercard != 'undefined' && showusercard == 1) {
_attachEvent(window, 'load', cardInit, document);
}
}
if(BROWSER.ie) {
document.documentElement.addBehavior("#default#userdata");
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_blog.js 23838 2011-08-11 06:51:58Z monkey $
*/
function validate_ajax(obj) {
var subject = $('subject');
if (subject) {
var slen = strlen(subject.value);
if (slen < 1 || slen > 80) {
alert("标题长度(1~80字符)不符合要求");
subject.focus();
return false;
}
}
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s.indexOf('succeed') == -1) {
alert(s);
$('seccode').focus();
return false;
} else {
edit_save();
obj.form.submit();
return true;
}
});
} else {
edit_save();
obj.form.submit();
return true;
}
}
function edit_album_show(id) {
var obj = $('uchome-edit-'+id);
if(id == 'album') {
$('uchome-edit-pic').style.display = 'none';
}
if(id == 'pic') {
$('uchome-edit-album').style.display = 'none';
}
if(obj.style.display == '') {
obj.style.display = 'none';
} else {
obj.style.display = '';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_uploadpic.js 23838 2011-08-11 06:51:58Z monkey $
*/
var attachexts = new Array();
var attachwh = new Array();
var insertType = 1;
var thumbwidth = parseInt(60);
var thumbheight = parseInt(60);
var extensions = 'jpg,jpeg,gif,png';
var forms;
var nowUid = 0;
var albumid = 0;
var uploadStat = 0;
var picid = 0;
var nowid = 0;
var mainForm;
var successState = false;
function delAttach(id) {
$('attachbody').removeChild($('attach_' + id).parentNode.parentNode.parentNode);
if($('attachbody').innerHTML == '') {
addAttach();
}
$('localimgpreview_' + id + '_menu') ? document.body.removeChild($('localimgpreview_' + id + '_menu')) : null;
}
function addAttach() {
newnode = $('attachbodyhidden').rows[0].cloneNode(true);
var id = nowid;
var tags;
tags = newnode.getElementsByTagName('form');
for(i in tags) {
if(tags[i].id == 'upload') {
tags[i].id = 'upload_' + id;
}
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {insertAttach(id)};
tags[i].unselectable = 'on';
}
if(tags[i].id == 'albumid') {
tags[i].id = 'albumid_' + id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
addAttach();
function insertAttach(id) {
var localimgpreview = '';
var path = $('attach_' + id).value;
var ext = getExt(path);
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类扩展名的图片');
return;
}
attachexts[id] = inArray(ext, ['gif', 'jpg', 'jpeg', 'png']) ? 2 : 1;
var inhtml = '<table cellspacing="0" cellpadding="0" class="up_row"><tr>';
if(typeof no_insert=='undefined') {
localfile += ' <a href="javascript:;" class="xi2" title="点击这里插入内容中当前光标的位置" onclick="insertAttachimgTag(' + id + ');return false;">[插入]</a>';
}
inhtml += '<td><strong>' + localfile +'</strong>';
inhtml += '</td><td class="d">图片描述<br/><textarea name="pic_title" cols="40" rows="2" class="pt"></textarea>';
inhtml += '</td><td class="o"><span id="showmsg' + id + '"><a href="javascript:;" onclick="delAttach(' + id + ');return false;" class="xi2">[删除]</a></span>';
inhtml += '</td></tr></table>';
$('localfile_' + id).innerHTML = inhtml;
$('attach_' + id).style.display = 'none';
addAttach();
}
function getPath(obj){
if (obj) {
if (BROWSER.ie && BROWSER.ie < 7) {
obj.select();
return document.selection.createRange().text;
} else if(BROWSER.firefox) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
} else {
return '';
}
return obj.value;
}
}
function inArray(needle, haystack) {
if(typeof needle == 'string') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function insertAttachimgTag(id) {
edit_insert('[imgid=' + id + ']');
}
function uploadSubmit(obj) {
obj.disabled = true;
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
upload();
}
function start_upload() {
$('btnupload').disabled = true;
mainForm = $('albumresultform');
forms = $('attachbody').getElementsByTagName("FORM");
upload();
}
function upload() {
if(typeof(forms[nowUid]) == 'undefined') return false;
var nid = forms[nowUid].id.split('_');
nid = nid[1];
if(nowUid>0) {
var upobj = $('showmsg'+nowid);
if(uploadStat==1) {
upobj.innerHTML = '上传成功';
successState = true;
var InputNode;
try {
var InputNode = document.createElement("<input type=\"hidden\" id=\"picid_" + picid + "\" value=\""+ nowid +"\" name=\"picids["+picid+"]\">");
} catch(e) {
var InputNode = document.createElement("input");
InputNode.setAttribute("name", "picids["+picid+"]");
InputNode.setAttribute("type", "hidden");
InputNode.setAttribute("id", "picid_" + picid);
InputNode.setAttribute("value", nowid);
}
mainForm.appendChild(InputNode);
} else {
upobj.style.color = "#f00";
upobj.innerHTML = '上传失败 '+uploadStat;
}
}
if($('showmsg'+nid) != null) {
$('showmsg'+nid).innerHTML = '上传中,请等待(<a href="javascript:;" onclick="forms[nowUid].submit();">重试</a>)';
$('albumid_'+nid).value = albumid;
forms[nowUid].submit();
} else if(nowUid+1 == forms.length) {
if(typeof (no_insert) != 'undefined') {
var albumidcheck = parseInt(parent.albumid);
$('opalbumid').value = isNaN(albumidcheck)? 0 : albumid;
if(!successState) return false;
}
window.onbeforeunload = null;
mainForm.submit();
}
nowid = nid;
nowUid++;
uploadStat = 0;
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_upload.js 23838 2011-08-11 06:51:58Z monkey $
*/
var nowid = 0;
var extensions = '';
function addAttach() {
var newnode = $('upload').cloneNode(true);
var id = nowid;
var tags;
newnode.id = 'upload_' + id;
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)};
tags[i].unselectable = 'on';
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
function insertAttach(id) {
var path = $('attach_' + id).value;
if(path == '') {
return;
}
var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类文件');
return;
}
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
$('localfile_' + id).innerHTML = localfile + ' 上传中...';
$('attach_' + id).style.display = 'none';
$('upload_' + id).action += '&attach_target_id=' + id;
$('upload_' + id).submit();
addAttach();
}
function deleteAttach(attachid, url) {
ajaxget(url);
$('attach_list_' + attachid).style.display = 'none';
}
function setConver(attach) {
$('conver').value = attach;
}
addAttach(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: swfupload.queue.js 23838 2011-08-11 06:51:58Z monkey $
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function (userSettings) {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this, userSettings);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = userSettings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: threadsort.js 30962 2012-07-04 07:57:45Z zhangjie $
*/
function xmlobj() {
var obj = new Object();
obj.createXMLDoc = function(xmlstring) {
var xmlobj = false;
if(window.DOMParser && document.implementation && document.implementation.createDocument) {
try{
var domparser = new DOMParser();
xmlobj = domparser.parseFromString(xmlstring, 'text/xml');
} catch(e) {
}
} else if(window.ActiveXObject) {
var versions = ["MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XmlDom"];
for(var i=0; i<versions.length; i++) {
try {
xmlobj = new ActiveXObject(versions[i]);
if(xmlobj) {
xmlobj.async = false;
xmlobj.loadXML(xmlstring);
}
} catch(e) {}
}
}
return xmlobj;
};
obj.xml2json = function(xmlobj, node) {
var nodeattr = node.attributes;
if(nodeattr != null) {
if(nodeattr.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodeattr.length;i++) {
xmlobj[nodeattr[i].name] = nodeattr[i].value;
}
}
var nodetext = "text";
if(node.text == null) {
nodetext = "textContent";
}
var nodechilds = node.childNodes;
if(nodechilds != null) {
if(nodechilds.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodechilds.length;i++) {
if(nodechilds[i].tagName != null) {
if(nodechilds[i].childNodes[0] != null && nodechilds[i].childNodes.length <= 1 && (nodechilds[i].childNodes[0].nodeType == 3 || nodechilds[i].childNodes[0].nodeType == 4)) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
} else {
if(typeof(xmlobj[nodechilds[i].tagName]) == "object" && xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = nodechilds[i][nodetext];
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = nodechilds[i][nodetext];
}
}
} else {
if(nodechilds[i].childNodes.length) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName], nodechilds[i]);
} else {
if(xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length-1], nodechilds[i]);
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][1], nodechilds[i]);
}
}
} else {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
}
}
}
}
}
};
return obj;
}
var xml = new xmlobj();
var xmlpar = xml.createXMLDoc(forum_optionlist);
var forum_optionlist_obj = new Object();
xml.xml2json(forum_optionlist_obj, xmlpar);
function changeselectthreadsort(selectchoiceoptionid, optionid, type) {
if(selectchoiceoptionid == '0') {
return;
}
var soptionid = 's' + optionid;
var sselectchoiceoptionid = 's' + selectchoiceoptionid;
forum_optionlist = forum_optionlist_obj['forum_optionlist'];
var choicesarr = forum_optionlist[soptionid]['schoices'];
var lastcount = 1;
var name = issearch = id = nameid = '';
if(type == 'search') {
issearch = ', \'search\'';
name = ' name="searchoption[' + optionid + '][value]"';
id = 'id="' + forum_optionlist[soptionid]['sidentifier'] + '"';
} else {
name = ' name="typeoption[' + forum_optionlist[soptionid]['sidentifier'] + ']"';
id = 'id="typeoption_' + forum_optionlist[soptionid]['sidentifier'] + '"';
}
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[sselectchoiceoptionid]['scount'] == 1) {
nameid = name + ' ' + id;
}
var selectoption = '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')" ' + ((forum_optionlist[soptionid]['sunchangeable'] == 1 && type == 'update') ? 'disabled' : '') + '><option value="0">请选择</option>';
for(var i in choicesarr) {
nameid = '';
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[i]['scount'] == choicesarr[sselectchoiceoptionid]['scount']) {
nameid = name + ' ' + id;
}
if(choicesarr[i]['sfoptionid'] != '0') {
var patrn1 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "$", 'i');
if(selectchoiceoptionid.match(patrn1) == null && selectchoiceoptionid.match(patrn2) == null) {
continue;
}
}
if(choicesarr[i]['scount'] != lastcount) {
if(parseInt(choicesarr[i]['scount']) >= (parseInt(choicesarr[sselectchoiceoptionid]['scount']) + parseInt(choicesarr[sselectchoiceoptionid]['slevel']))) {
break;
}
selectoption += '</select>' + "\r\n" + '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')" ' + ((forum_optionlist[soptionid]['sunchangeable'] == 1 && type == 'update') ? 'disabled' : '') + '><option value="0">请选择</option>';
lastcount = parseInt(choicesarr[i]['scount']);
}
var patrn1 = new RegExp("^" + choicesarr[i]['soptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['soptionid'] + "$", 'i');
var isnext = '';
if(parseInt(choicesarr[i]['slevel']) != 1) {
isnext = '»';
}
if(selectchoiceoptionid.match(patrn1) != null || selectchoiceoptionid.match(patrn2) != null) {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '" selected="selected">' + choicesarr[i]['scontent'] + isnext + '</option>';
} else {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '">' + choicesarr[i]['scontent'] + isnext + '</option>';
}
}
selectoption += '</select>';
if(type == 'search') {
selectoption += "\r\n" + '<input type="hidden" name="searchoption[' + optionid + '][type]" value="select">';
}
$('select_' + forum_optionlist[soptionid]['sidentifier']).innerHTML = selectoption;
}
function checkoption(identifier, required, checktype, checkmaxnum, checkminnum, checkmaxlength) {
if(checktype != 'image' && checktype != 'select' && !$('typeoption_' + identifier) || !$('check' + identifier)) {
return true;
}
var ce = $('check' + identifier);
ce.innerHTML = '';
if(checktype == 'select') {
if(required != '0' && ($('typeoption_' + identifier) == null || $('typeoption_' + identifier).value == '0')) {
warning(ce, '必填项目没有填写');
return false;
} else if(required == '0' && ($('typeoption_' + identifier) == null || $('typeoption_' + identifier).value == '0')) {
ce.innerHTML = '<img src="' + IMGDIR + '/check_error.gif" width="16" height="16" class="vm" /> 请选择下一级';
ce.className = "warning";
return true;
}
}
if(checktype == 'radio' || checktype == 'checkbox') {
var nodes = $('typeoption_' + identifier).parentNode.parentNode.parentNode.getElementsByTagName('INPUT');
var nodechecked = false;
for(var i=0; i<nodes.length; i++) {
if(nodes[i].id == 'typeoption_' + identifier) {
if(nodes[i].checked) {
nodechecked = true;
}
}
}
if(!nodechecked && required != '0') {
warning(ce, '必填项目没有填写');
return false;
}
}
if(checktype == 'image') {
var checkvalue = $('sortaid_' + identifier).value;
} else {
var checkvalue = $('typeoption_' + identifier).value;
}
if(required != '0') {
if(checkvalue == '') {
warning(ce, '必填项目没有填写');
return false;
} else {
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
}
if(checkvalue) {
if(checktype == 'email' && !(/^[\-\.\w]+@[\.\-\w]+(\.\w+)+$/.test(checkvalue))) {
warning(ce, '邮件地址不正确');
return false;
} else if((checktype == 'text' || checktype == 'textarea') && checkmaxlength != '0' && mb_strlen(checkvalue) > checkmaxlength) {
warning(ce, '填写项目长度过长');
return false;
} else if((checktype == 'number' || checktype == 'range')) {
if(isNaN(checkvalue)) {
warning(ce, '数字填写不正确');
return false;
} else if(checkmaxnum != '0' && parseInt(checkvalue) > parseInt(checkmaxnum)) {
warning(ce, '大于设置最大值');
return false;
} else if(checkminnum != '0' && parseInt(checkvalue) < parseInt(checkminnum)) {
warning(ce, '小于设置最小值');
return false;
}
} else if(checktype == 'url' && !(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w[\/]?$/i.test(checkvalue))) {
warning(ce, '请正确填写以http://开头的URL地址');
return false;
}
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
return true;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id$
*/
var _share_tencent_weibo = function() {
var share_btn = function(_arr) {
if (_arr[0]) {
return _arr[0];
}
else {
var o = document.createElement("a"),
_ostyle = "width:92px;height:22px;background:url(http://open.t.qq.com/apps/qshare/images/icon.gif) no-repeat #f00;position:absolute;display:none;";
o.setAttribute("style", _ostyle);
o.style.cssText = _ostyle;
o.setAttribute("href", "javascript:;");
document.body.insertBefore(o, document.body.childNodes[0]);
return o;
}
} (arguments);
var share_area = function(_arr) {
if (_arr[1]) {
if ((typeof _arr[1] == "object" && _arr[1].length) || (_arr[1].constructor == Array)) {
return _arr[1];
} else {
return [_arr[1]];
}
}
else {
return [document.body];
}
} (arguments);
var current_area = share_area[0];
var _site = arguments[2] ? arguments[2] : "";
var _appkey = encodeURI(arguments[3] ? arguments[3] : "");
var _web = {
"name": arguments[4] || "",
"href": location.href,
"hash": location.hash
};
var _pic = function(area) {
var _imgarr = area.getElementsByTagName("img");
var _srcarr = [];
for (var i = 0; i < _imgarr.length; i++) {
_srcarr.push(_imgarr[i].src);
}
return _srcarr.join("|");
};
var _u = 'http://v.t.qq.com/share/share.php?url=$url$&appkey=' + _appkey + '&site=' + _site + '&title=$title$&pic=$pic$';
var _select = function() {
return (document.selection ? document.selection.createRange().text: document.getSelection()).toString().replace(/[\s\n]+/g, " ");
};
if ( !! window.find) {
HTMLElement.prototype.contains = function(B) {
return this.compareDocumentPosition(B) - 19 > 0
}
}
String.prototype.elength = function() {
return this.replace(/[^\u0000-\u00ff]/g, "aa").length;
}
document.onmouseup = function(e) {
e = e || window.event;
var o = e.target || e.srcElement;
for (var i = 0; i < share_area.length; i++) {
if (share_area[i].contains(o) || share_area[i] == o) {
var _e = {
"x": e.clientX,
"y": e.clientY
};
var _o = {
"w": share_btn.clientWidth,
"h": share_btn.clientHeight
};
var _d = window.pageYOffset || (document.documentElement || document.body).scrollTop || 0;
var x = (_e.x - _o.w < 0) ? _e.x + _o.w: _e.x - _o.w,
y = (_e.y - _o.h < 0) ? _e.y + _d - _o.h: _e.y + _d - _o.h + ( - [1, ] ? 10 : 0);
if (_select() && _select().length >= 10) {
with(share_btn.style) {
display = "inline-block";
left = (x - 5) + "px";
top = y + "px";
position = "absolute";
zIndex = "999999";
}
current_area = share_area[i];
break;
} else {
share_btn.style.display = "none";
}
} else {
share_btn.style.display = "none";
}
}
};
share_btn.onclick = function() {
var _str = _select();
var _strmaxlen = 280 - ("\u6211\u6765\u81EA\u4E8E\u817E\u8BAF\u5FAE\u535A\u5F00\u653E\u5E73\u53F0" + " " + _web.name).elength();
var _resultstr = "";
if (_str.elength() > _strmaxlen) {
_strmaxlen = _strmaxlen - 3;
for (var i = _strmaxlen >> 1; i <= _strmaxlen; i++) {
if ((_str.slice(0, i)).elength() > _strmaxlen) {
break;
}
else {
_resultstr = _str.slice(0, i);
}
}
_resultstr += "...";
} else {
_resultstr = _str;
}
if (_str) {
var url = _u.replace("$title$", encodeURIComponent(_resultstr + " " + _web.name)).replace("$pic$", _pic(current_area));
url = url.replace("$url$", encodeURIComponent(_web.href.replace(_web.hash, "") + "#" + (current_area["name"] || current_area["id"] || "")));
if (!- [1, ]) {
url = url.substr(0, 2048);
}
window.open(url, 'null', 'width=700,height=680,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,location=yes,resizable=no,status=no');
}
};
}; | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_slide.js 23838 2011-08-11 06:51:58Z monkey $
*/
if(isUndefined(sliderun)) {
var sliderun = 1;
function slide() {
var s = new Object();
s.slideId = Math.random();
s.slideSpeed = slideSpeed;
s.size = slideImgsize;
s.imgs = slideImgs;
s.imgLoad = new Array();
s.imgnum = slideImgs.length;
s.imgLinks = slideImgLinks;
s.imgTexts = slideImgTexts;
s.slideBorderColor = slideBorderColor;
s.slideBgColor = slideBgColor;
s.slideSwitchColor = slideSwitchColor;
s.slideSwitchbgColor = slideSwitchbgColor;
s.slideSwitchHiColor = slideSwitchHiColor;
s.currentImg = 0;
s.prevImg = 0;
s.imgLoaded = 0;
s.st = null;
s.loadImage = function () {
if(!s.imgnum) {
return;
}
s.size[0] = parseInt(s.size[0]);
s.size[1] = parseInt(s.size[1]);
document.write('<div class="slideouter" id="outer_'+s.slideId+'" style="cursor:pointer;position:absolute;width:'+(s.size[0]-2)+'px;height:'+(s.size[1]-2)+'px;border:1px solid '+s.slideBorderColor+'"></div>');
document.write('<table cellspacing="0" cellpadding="0" style="cursor:pointer;width:'+s.size[0]+'px;height:'+s.size[1]+'px;table-layout:fixed;overflow:hidden;background:'+s.slideBgColor+';text-align:center"><tr><td valign="middle" style="padding:0" id="slide_'+s.slideId+'">');
document.write((typeof IMGDIR == 'undefined' ? '' : '<img src="'+IMGDIR+'/loading.gif" />') + '<br /><span id="percent_'+s.slideId+'">0%</span></td></tr></table>');
document.write('<div id="switch_'+s.slideId+'" style="position:absolute;margin-left:1px;margin-top:-18px"></div>');
$('outer_' + s.slideId).onclick = s.imageLink;
for(i = 1;i < s.imgnum;i++) {
switchdiv = document.createElement('div');
switchdiv.id = 'switch_' + i + '_' + s.slideId;
switchdiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=70)';
switchdiv.style.opacity = 0.7;
switchdiv.style.styleFloat = 'left';
switchdiv.style.cssFloat = 'left';
switchdiv.style.cursor = 'pointer';
switchdiv.style.width = '17px';
switchdiv.style.height = '17px';
switchdiv.style.overflow = 'hidden';
switchdiv.style.fontWeight = 'bold';
switchdiv.style.textAlign = 'center';
switchdiv.style.fontSize = '9px';
switchdiv.style.color = s.slideSwitchColor;
switchdiv.style.borderRight = '1px solid ' + s.slideBorderColor;
switchdiv.style.borderTop = '1px solid ' + s.slideBorderColor;
switchdiv.style.backgroundColor = s.slideSwitchbgColor;
switchdiv.className = 'slideswitch';
switchdiv.i = i;
switchdiv.onclick = function () {
s.switchImage(this);
};
switchdiv.innerHTML = i;
$('switch_'+s.slideId).appendChild(switchdiv);
s.imgLoad[i] = new Image();
s.imgLoad[i].src = s.imgs[i];
s.imgLoad[i].onerror = function () { s.imgLoaded++; };
}
s.loadCheck();
};
s.imageLink = function () {
window.open(s.imgLinks[s.currentImg]);
};
s.switchImage = function (obj) {
s.showImage(obj.i);
s.interval();
};
s.loadCheck = function () {
for(i = 1;i < s.imgnum;i++) {
if(s.imgLoad[i].complete && !s.imgLoad[i].status) {
s.imgLoaded++;
s.imgLoad[i].status = 1;
if(s.imgLoad[i].width > s.size[0] || s.imgLoad[i].height > s.size[1]) {
zr = s.imgLoad[i].width / s.imgLoad[i].height;
if(zr > 1) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
} else {
s.imgLoad[i].width = s.size[0];
s.imgLoad[i].height = s.size[0] / zr;
if(s.imgLoad[i].height > s.size[1]) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
}
}
}
}
}
if(s.imgLoaded < s.imgnum - 1) {
$('percent_' + s.slideId).innerHTML = (parseInt(s.imgLoad.length / s.imgnum * 100)) + '%';
setTimeout(function () { s.loadCheck(); }, 100);
} else {
for(i = 1;i < s.imgnum;i++) {
s.imgLoad[i].onclick = s.imageLink;
s.imgLoad[i].title = s.imgTexts[i];
}
s.showImage();
s.interval();
}
};
s.interval = function () {
clearInterval(s.st);
s.st = setInterval(function () { s.showImage(); }, s.slideSpeed);
};
s.showImage = function (i) {
if(!i) {
s.currentImg++;
s.currentImg = s.currentImg < s.imgnum ? s.currentImg : 1;
} else {
s.currentImg = i;
}
if(s.prevImg) {
$('switch_' + s.prevImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchbgColor;
}
$('switch_' + s.currentImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchHiColor;
$('slide_' + s.slideId).innerHTML = '';
$('slide_' + s.slideId).appendChild(s.imgLoad[s.currentImg]);
s.prevImg = s.currentImg;
};
s.loadImage();
}
}
slide(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_friendselector.js 26733 2011-12-21 07:18:01Z zhengqingpeng $
*/
(function() {
friendSelector = function(parameter) {
this.dataSource = {};
this.selectUser = {};
this.prompterUser = [];
this.showObj = $(isUndefined(parameter['showId']) ? 'selectorBox' : parameter['showId']);
if(!this.showObj) return;
this.handleObj = $(isUndefined(parameter['searchId']) ? 'valueId' : parameter['searchId']);
this.showType = isUndefined(parameter['showType']) ? 0 : parameter['showType'];
this.searchStr = null;
this.selectNumber = 0;
this.maxSelectNumber = isUndefined(parameter['maxSelectNumber']) ? 0 : parseInt(parameter['maxSelectNumber']);
this.allNumber = 0;
this.notInDataSourceNumber = 0;
this.handleKey = isUndefined(parameter['handleKey']) ? 'this' : parameter['handleKey'];
this.selectTabId = isUndefined(parameter['selectTabId']) ? 'selectTabId' : parameter['selectTabId'];
this.unSelectTabId = isUndefined(parameter['unSelectTabId']) ? 'unSelectTabId' : parameter['unSelectTabId'];
this.maxSelectTabId = isUndefined(parameter['maxSelectTabId']) ? 'maxSelectTabId' : parameter['maxSelectTabId'];
this.formId = isUndefined(parameter['formId']) ? '' : parameter['formId'];
this.filterUser = isUndefined(parameter['filterUser']) ? {} : parameter['filterUser'];
this.showAll = true;
this.newPMUser = {};
this.interlaced = true;
this.handover = true;
this.parentKeyCode = 0;
this.pmSelBoxState = 0;
this.selBoxObj = isUndefined(parameter['selBox']) ? null : $(parameter['selBox']);
this.containerBoxObj = isUndefined(parameter['selBoxMenu']) ? null : $(parameter['selBoxMenu']);
this.imgBtn = null;
this.initialize();
return this;
};
friendSelector.prototype = {
addDataSource : function(data, clear) {
if(typeof data == 'object') {
var userData = data['userdata'];
clear = isUndefined(clear) ? 0: clear;
if(clear) {
this.showObj.innerHTML = "";
if(this.showType == 3) {
this.selBoxObj.innerHTML = '';
}
this.allNumber = 0;
this.dataSource = {};
}
for(var i in userData) {
if(typeof this.filterUser[i] != 'undefined') {
continue;
}
var append = clear ? true : false;
if(typeof this.dataSource[i] == 'undefined') {
this.dataSource[i] = userData[i];
append = true;
this.allNumber++;
}
if(append) {
this.interlaced = !this.interlaced;
if(this.showType == 3) {
this.append(i, 0, 1);
} else {
this.append(i);
}
}
}
if(this.showType == 1) {
this.showSelectNumber();
} else if(this.showType == 2) {
if(this.newPMUser) {
window.setInterval(this.handleKey+".handoverCSS()", 400);
}
}
}
},
addFilterUser : function(data) {
var filterData = {};
if(typeof data != 'object') {
filterData[data] = data;
} else if(typeof data == 'object') {
filterData = data;
} else {
return false;
}
for(var id in filterData) {
this.filterUser[filterData[id]] = filterData[id];
}
return true;
},
handoverCSS : function() {
for(var uid in this.newPMUser) {
$('avt_'+uid).className = this.handover ? 'avt newpm' : 'avt';
}
this.handover = !this.handover;
},
handleEvent : function(key, event) {
var username = '';
this.searchStr = '';
if(key != '') {
if(event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 59) {
if(this.showType == 3) {
if(event.keyCode == 13) {
var currentnum = this.getCurrentPrompterUser();
if(currentnum != -1) {
key = this.dataSource[this.prompterUser[currentnum]]['username'];
}
}
if(this.parentKeyCode != 229) {
this.selectUserName(this.trim(key));
this.showObj.style.display = 'none';
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
}
} else if(event.keyCode == 38 || event.keyCode == 40) {
} else {
if(this.showType == 3) {
this.showObj.innerHTML = "";
var result = false;
var reg = new RegExp(key, "ig");
this.searchStr = key;
this.prompterUser = [];
for(var uid in this.dataSource) {
username = this.dataSource[uid]['username'];
if(username.match(reg)) {
this.prompterUser.push(uid);
this.append(uid, 1);
result = true;
}
}
if(!result) {
$(this.handleObj.id+'_menu').style.display = 'none';
} else {
showMenu({'showid':this.showObj.id, 'duration':3, 'pos':'43'});
showMenu({'showid':this.handleObj.id, 'duration':3, 'pos':'43'});
}
}
}
} else if(this.showType != 3) {
this.showObj.innerHTML = "";
for(var uid in this.dataSource) {
this.append(uid);
}
} else {
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
},
selectUserName:function(userName) {
this.handleObj.value = '';
if(userName != '') {
var uid = this.isFriend(userName);
if(uid && typeof this.selectUser[uid] == 'undefined' || uid === 0 && typeof this.selectUser[userName] == 'undefined') {
var spanObj = document.createElement("span");
if(uid) {
this.selectUser[uid] = this.dataSource[uid];
spanObj.id = 'uid' + uid;
if($('chk'+uid) != null) {
$('chk'+uid).checked = true;
}
} else {
var id = 'str' + Math.floor(Math.random() * 10000);
spanObj.id = id;
this.selectUser[userName] = userName;
}
this.selectNumber++;
spanObj.innerHTML= '<a href="javascript:;" class="x" onclick="'+this.handleKey+'.delSelUser(\''+(spanObj.id)+'\');">删除</a><em class="z" title="' + userName + '">' + userName + '</em><input type="hidden" name="users[]" value="'+userName+'" uid="uid'+uid+'" />';
this.handleObj.parentNode.insertBefore(spanObj, this.handleObj);
this.showObj.style.display = 'none';
} else {
alert('已经存在'+userName);
}
}
},
delSelUser:function(id) {
id = isUndefined(id) ? 0 : id;
var uid = id.substring(0, 3) == 'uid' ? parseInt(id.substring(3)) : 0;
var spanObj;
if(uid) {
spanObj = $(id);
delete this.selectUser[uid];
if($('chk'+uid) != null) {
$('chk'+uid).checked = false;
}
} else if(id.substring(0, 3) == 'str') {
spanObj = $(id);
delete this.selectUser[spanObj.getElementsByTagName('input')[0].value];
}
if(spanObj != null) {
this.selectNumber--;
spanObj.parentNode.removeChild(spanObj);
}
},
trim:function(str) {
return str.replace(/\s|,|;/g, '');
},
isFriend:function(userName) {
var id = 0;
for(var uid in this.dataSource) {
if(this.dataSource[uid]['username'] === userName) {
id = uid;
break;
}
}
return id;
},
directionKeyDown : function(event) {},
clearDataSource : function() {
this.dataSource = {};
this.selectUser = {};
},
showUser : function(type) {
this.showObj.innerHTML = '';
type = isUndefined(type) ? 0 : parseInt(type);
this.showAll = true;
if(type == 1) {
for(var uid in this.selectUser) {
this.append(uid);
}
this.showAll = false;
} else {
for(var uid in this.dataSource) {
if(type == 2) {
if(typeof this.selectUser[uid] != 'undefined') {
continue;
}
this.showAll = false;
}
this.append(uid);
}
}
if(this.showType == 1) {
for(var i = 0; i < 3; i++) {
$('showUser_'+i).className = '';
}
$('showUser_'+type).className = 'a brs';
}
},
append : function(uid, filtrate, form) {
filtrate = isUndefined(filtrate) ? 0 : filtrate;
form = isUndefined(form) ? 0 : form;
var liObj = document.createElement("li");
var appendUserData = this.dataSource[uid] || this.selectUser[uid];
var username = appendUserData['username'];
liObj.userid = appendUserData['uid'];
if(typeof this.selectUser[uid] != 'undefined') {
liObj.className = "a";
}
if(filtrate) {
var reg = new RegExp("(" + this.searchStr + ")","ig");
username = username.replace(reg , "<strong>$1</strong>");
}
if(this.showType == 1) {
liObj.innerHTML = '<a href="javascript:;" id="' + liObj.userid + '" onclick="' + this.handleKey + '.select(this.id)" class="cl"><span class="avt brs" style="background-image: url(' + appendUserData['avatar'] + ');"><span></span></span><span class="d">' + username + '</span></a>';
} else if(this.showType == 2) {
if(appendUserData['new'] && typeof this.newPMUser[uid] == 'undefined') {
this.newPMUser[uid] = uid;
}
liObj.className = this.interlaced ? 'alt' : '';
liObj.innerHTML = '<div id="avt_' + liObj.userid + '" class="avt"><a href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+appendUserData['pmid']+'&daterange='+appendUserData['daterange']+'" title="'+username+'" id="avatarmsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);"><img src="' + appendUserData['avatar'] + '" alt="'+username+'" /></a></div><p><a class="xg1" href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+appendUserData['pmid']+'&daterange='+appendUserData['daterange']+'" title="'+username+'" id="usernamemsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);">'+username+'</a></p>';
} else {
if(form) {
var checkstate = typeof this.selectUser[uid] == 'undefined' ? '' : ' checked="checked" ';
liObj.innerHTML = '<label><input type="checkbox" name="selUsers[]" id="chk'+uid+'" value="'+ appendUserData['username'] +'" onclick="if(this.checked) {' + this.handleKey + '.selectUserName(this.value);} else {' + this.handleKey + '.delSelUser(\'uid'+uid+'\');}" '+checkstate+' class="pc" /> <span class="xi2">' + username + '</span></label>';
this.selBoxObj.appendChild(liObj);
return true;
} else {
liObj.innerHTML = '<a href="javascript:;" username="' + this.dataSource[uid]['username'] + '" onmouseover="' + this.handleKey + '.mouseOverPrompter(this);" onclick="' + this.handleKey + '.selectUserName(this.getAttribute(\'username\'));$(\'username\').focus();" class="cl" id="prompter_' + uid + '">' + username + '</a>';
}
}
this.showObj.appendChild(liObj);
},
select : function(uid) {
uid = parseInt(uid);
if(uid){
var select = false;
if(typeof this.selectUser[uid] == 'undefined') {
if(this.maxSelectNumber && this.selectNumber >= this.maxSelectNumber) {
alert('最多只允许选择'+this.maxSelectNumber+'个用户');
return false;
}
this.selectUser[uid] = this.dataSource[uid];
this.selectNumber++;
if(this.showType == '1') {
$(uid).parentNode.className = 'a';
}
select = true;
} else {
delete this.selectUser[uid];
this.selectNumber--;
$(uid).parentNode.className = '';
}
if(this.formId != '') {
var formObj = $(this.formId);
var opId = 'selUids_' + uid;
if(select) {
var inputObj = document.createElement("input");
inputObj.type = 'hidden';
inputObj.id = opId;
inputObj.name = 'uids[]';
inputObj.value = uid;
formObj.appendChild(inputObj);
} else {
formObj.removeChild($(opId));
}
}
if(this.showType == 1) {
this.showSelectNumber();
}
}
},
delNewFlag : function(uid) {
delete this.newPMUser[uid];
},
showSelectNumber:function() {
if($(this.selectTabId) != null && typeof $(this.selectTabId) != 'undefined') {
$(this.selectTabId).innerHTML = this.selectNumber;
}
if($(this.unSelectTabId) != null && typeof $(this.unSelectTabId) != 'undefined') {
this.notInDataSourceNumber = 0;
for(var i in this.selectUser) {
if(typeof this.dataSource[i] == 'undefined') {
this.notInDataSourceNumber++;
}
}
$(this.unSelectTabId).innerHTML = this.allNumber + this.notInDataSourceNumber - this.selectNumber;
}
if($(this.maxSelectTabId) != null && this.maxSelectNumber && typeof $(this.maxSelectTabId) != 'undefined') {
$(this.maxSelectTabId).innerHTML = this.maxSelectNumber - this.selectNumber;
}
},
getCurrentPrompterUser:function() {
var len = this.prompterUser.length;
var selectnum = -1;
if(len) {
for(var i = 0; i < len; i++) {
var obj = $('prompter_' + this.prompterUser[i]);
if(obj != null && obj.className == 'a') {
selectnum = i;
}
}
}
return selectnum;
},
mouseOverPrompter:function(obj) {
var len = this.prompterUser.length;
if(len) {
for(var i = 0; i < len; i++) {
$('prompter_' + this.prompterUser[i]).className = 'cl';
}
obj.className = 'a';
}
},
initialize:function() {
var instance = this;
this.handleObj.onkeyup = function(event) {
event = event ? event : window.event;
instance.handleEvent(this.value, event);
};
if(this.showType == 3) {
this.handleObj.onkeydown = function(event) {
event = event ? event : window.event;
instance.parentKeyCode = event.keyCode;
instance.showObj.style.display = '';
if(event.keyCode == 8 && this.value == '') {
var preNode = this.previousSibling;
if(preNode.tagName == 'SPAN') {
var uid = preNode.getElementsByTagName('input')[0].getAttribute('uid');
if(parseInt(uid.substring(3))) {
instance.delSelUser(uid);
} else {
delete instance.selectUser[preNode.getElementsByTagName('input')[0].value];
instance.selectNumber--;
this.parentNode.removeChild(preNode);
}
}
} else if(event.keyCode == 38) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == 0) ? (instance.prompterUser.length-1) : currentnum - 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 40) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == (instance.prompterUser.length - 1)) ? 0 : currentnum + 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 13) {
doane(event);
}
if(typeof instance != "undefined" && instance.pmSelBoxState) {
instance.pmSelBoxState = 0;
instance.changePMBoxImg(instance.imgBtn);
instance.containerBoxObj.style.display = 'none';
}
};
}
},
changePMBoxImg:function(obj) {
var btnImg = new Image();
btnImg.src = IMGDIR + '/' + (this.pmSelBoxState ? 'icon_top.gif' : 'icon_down.gif');
if(obj != null) {
obj.src = btnImg.src;
}
},
showPMFriend:function(boxId, listId, obj) {
this.pmSelBoxState = !this.pmSelBoxState;
this.imgBtn = obj;
this.changePMBoxImg(obj);
if(this.pmSelBoxState) {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
}
this.containerBoxObj.style.display = this.pmSelBoxState ? '' : 'none';
this.showObj.innerHTML = "";
},
showPMBoxUser:function() {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
},
extend:function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: at.js 27406 2012-01-30 09:22:34Z monkey $
*/
if(typeof EXTRAFUNC['keydown'] != "undefined") {
EXTRAFUNC['keydown']['at'] = 'extrafunc_atMenu';
EXTRAFUNC['keyup']['at'] = 'extrafunc_atMenuKeyUp';
EXTRAFUNC['showEditorMenu']['at'] = 'extrafunc_atListMenu';
}
var atKeywords = null, keyMenuObj = null,atResult = [];
var curatli = 0, atliclass = '', atsubmitid = '', atkeypress = 0;
function extrafunc_atMenu() {
if(BROWSER.opera) {
return;
}
if(wysiwyg && EXTRAEVENT.shiftKey && EXTRAEVENT.keyCode == 50 && postaction && (postaction == 'newthread' || postaction == 'reply' || postaction == 'edit')) {
keyMenu('@', atMenu);
ctlent_enable[13] = 0;
doane(EXTRAEVENT);
atkeypress = 1;
}
if($('at_menu') && $('at_menu').style.display == '' && (EXTRAEVENT.keyCode == 38 || EXTRAEVENT.keyCode == 40 || EXTRAEVENT.keyCode == 13)) {
doane(EXTRAEVENT);
}
}
function extrafunc_atMenuKeyUp() {
if(BROWSER.opera) {
return;
}
if(wysiwyg && EXTRAEVENT.shiftKey && EXTRAEVENT.keyCode == 50 && postaction && (postaction == 'newthread' || postaction == 'reply' || postaction == 'edit') && !atkeypress) {
keyBackspace();
keyMenu('@', atMenu);
ctlent_enable[13] = 0;
doane(EXTRAEVENT);
}
if(wysiwyg && $('at_menu') && $('at_menu').style.display == '' && postaction && (postaction == 'newthread' || postaction == 'reply' || postaction == 'edit')) {
if(EXTRAEVENT.keyCode == 32 || EXTRAEVENT.keyCode == 9 || EXTRAEVENT.keyCode == 13 || EXTRAEVENT.keyCode == 8 && !keyMenuObj.innerHTML.substr(1).length) {
$('at_menu').style.display = 'none';
ctlent_enable[13] = 1;
} else {
atFilter(keyMenuObj.innerHTML.substr(1), 'at_menu', 'atMenuSet', EXTRAEVENT);
}
}
atkeypress = 0;
}
function extrafunc_atListMenu(tag, op) {
if(tag != 'at') {
return false;
}
if(!op) {
if($('at_menu')) {
$('at_menu').style.display = 'none';
ctlent_enable[13] = 1;
}
curatli = 0;
setTimeout(function() {atFilter('', 'at_list','atListSet');$('atkeyword').focus();}, 100);
return '请输用户名:<br /><input type="text" id="atkeyword" style="width:240px" value="" class="px" onkeydown="atEnter(event, \'atListSet\')" onkeyup="atFilter(this.value, \'at_list\',\'atListSet\',event, true);" /><div class="p_pop" id="at_list" style="width:250px;"><ul><li>@朋友账号,就能提醒他来看帖子</li></ul></div>';
} else {
if($('atkeyword').value) {
str = '@' + $('atkeyword').value + (wysiwyg ? ' ' : ' ');
insertText(str, strlen(str), 0, true, EXTRASEL);
} else {
insertText('', 0, 0, true, EXTRASEL);
}
checkFocus();
return true;
}
}
function atMenu(x, y) {
if(!$('at_menu')) {
div = document.createElement("div");
div.id = "at_menu";
document.body.appendChild(div);
div.style.position = 'absolute';
div.className = 'p_pop';
div.style.zIndex = '100000';
}
$('at_menu').style.marginTop = (keyMenuObj.offsetHeight + 2) + 'px';
$('at_menu').style.marginLeft = (keyMenuObj.offsetWidth + 2) + 'px';
$('at_menu').style.left = x + 'px';
$('at_menu').style.top = y + 'px';
$('at_menu').style.display = '';
$('at_menu').innerHTML = '<img src="' + IMGDIR + '/loading.gif" class="vm"> 请稍候... ';
}
function atSearch(kw, call) {
if(atKeywords === null) {
atKeywords = '';
var x = new Ajax();
x.get('misc.php?mod=getatuser&inajax=1', function(s) {
if(s) {
atKeywords = s.split(',');
}
if(call) {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
}
});
}
var lsi = 0;
for(i in atKeywords) {
if(atKeywords[i].indexOf(kw) !== -1 || kw === '') {
atResult[lsi] = kw !== '' ? atKeywords[i].replace(kw, '<b>' + kw + '</b>') : atKeywords[i];
lsi++;
if(lsi > 10) {
break;
}
}
}
if(kw && !lsi) {
curatli = -1;
}
}
function atEnter(e, call) {
if(e) {
if(e.keyCode == 38 && curatli > 0) {
curatli--;
return false;
}
if(e.keyCode == 40 && curatli < (atResult.length -1)) {
curatli++;
return false;
}
if(e.keyCode == 13) {
var call = !call ? 'insertText' : call;
if(curatli > -1) {
eval(call+'($(\'atli_'+curatli+'\').innerText)');
}
hideMenu();
doane(e);
return true;
}
}
return false;
}
function atFilter(kw, id, call, e, nae) {
var nae = !nae ? false : nae;
atResult = [];
atSearch(kw, function () { atFilter(kw, id, call); });
if(nae || !atEnter(e, call)) {
var newlist = '';
if(atResult.length) {
$(id).style.visibility = 'visible';
for(i in atResult) {
var atclass = i == curatli ? ' class="a"' : '';
newlist += '<li><a href="javascript:;" id="atli_'+i+'"'+atclass+' onclick="'+call+'(this.innerText)">' + atResult[i] + '</a></li>';
}
$(id).innerHTML = '<ul>' + newlist + '<li class="xg1">@朋友账号,就能提醒他来看帖子</li></ul>';
} else {
$(id).style.visibility = 'hidden';
}
}
}
function atListSet(kw) {
$('atkeyword').value = kw;
if(!atsubmitid) {
$(editorid + '_at_submit').click();
} else {
$(atsubmitid).click();
}
}
function atMenuSet(kw) {
keyMenuObj.innerHTML = '@' + kw + (wysiwyg ? ' ' : ' ');
$('at_menu').style.display = 'none';
ctlent_enable[13] = 1;
curatli = 0;
if(BROWSER.firefox) {
var selection = editwin.getSelection();
var range = selection.getRangeAt(0);
var tmp = keyMenuObj.firstChild;
range.setStart(tmp, keyMenuObj.innerHTML.length - 5);
range.setEnd(tmp, keyMenuObj.innerHTML.length - 5);
selection.removeAllRanges();
selection.addRange(range);
}
checkFocus();
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_viewthread.js 28794 2012-03-13 05:39:46Z zhangguosheng $
*/
var replyreload = '', attachimgST = new Array(), zoomgroup = new Array(), zoomgroupinit = new Array();
function attachimggroup(pid) {
if(!zoomgroupinit[pid]) {
for(i = 0;i < aimgcount[pid].length;i++) {
zoomgroup['aimg_' + aimgcount[pid][i]] = pid;
}
zoomgroupinit[pid] = true;
}
}
function attachimgshow(pid, onlyinpost) {
onlyinpost = !onlyinpost ? false : onlyinpost;
aimgs = aimgcount[pid];
aimgcomplete = 0;
loadingcount = 0;
for(i = 0;i < aimgs.length;i++) {
obj = $('aimg_' + aimgs[i]);
if(!obj) {
aimgcomplete++;
continue;
}
if(onlyinpost && obj.getAttribute('inpost') || !onlyinpost) {
if(!obj.status) {
obj.status = 1;
if(obj.getAttribute('file')) obj.src = obj.getAttribute('file');
loadingcount++;
} else if(obj.status == 1) {
if(obj.complete) {
obj.status = 2;
} else {
loadingcount++;
}
} else if(obj.status == 2) {
aimgcomplete++;
if(obj.getAttribute('thumbImg')) {
thumbImg(obj);
}
}
if(loadingcount >= 10) {
break;
}
}
}
if(aimgcomplete < aimgs.length) {
setTimeout(function () {
attachimgshow(pid, onlyinpost);
}, 100);
}
}
function attachimglstshow(pid, islazy, fid, showexif) {
var aimgs = aimgcount[pid];
var s = '';
if(fid) {
s = ' onmouseover="showMenu({\'ctrlid\':this.id, \'pos\': \'12!\'});"';
}
if(typeof aimgcount == 'object' && $('imagelistthumb_' + pid)) {
for(pid in aimgcount) {
var imagelist = '';
for(i = 0;i < aimgcount[pid].length;i++) {
if(!$('aimg_' + aimgcount[pid][i]) || $('aimg_' + aimgcount[pid][i]).getAttribute('inpost') || parseInt(aimgcount[pid][i]) != aimgcount[pid][i]) {
continue;
}
if(fid) {
imagelist += '<div id="pattimg_' + aimgcount[pid][i] + '_menu" class="tip tip_4" style="display: none;"><div class="tip_horn"></div><div class="tip_c"><a href="forum.php?mod=ajax&action=setthreadcover&aid=' + aimgcount[pid][i] + '&fid=' + fid + '" class="xi2" onclick="showWindow(\'setcover' + aimgcount[pid][i] + '\', this.href)">设为封面</a></div></div>';
}
imagelist += '<div class="pattimg">' +
'<a id="pattimg_' + aimgcount[pid][i] + '" class="pattimg_zoom" href="javascript:;"' + s + ' onclick="zoom($(\'aimg_' + aimgcount[pid][i] + '\'), attachimggetsrc(\'aimg_' + aimgcount[pid][i] + '\'), 0, 0, ' + (parseInt(showexif) ? 1 : 0) + ')" title="点击放大">点击放大</a>' +
'<img ' + (islazy ? 'file' : 'src') + '="forum.php?mod=image&aid=' + aimgcount[pid][i] + '&size=100x100&key=' + imagelistkey + '&atid=' + tid + '" width="100" height="100" /></div>';
}
if($('imagelistthumb_' + pid)) {
$('imagelistthumb_' + pid).innerHTML = imagelist;
}
}
}
}
function attachimggetsrc(img) {
return $(img).getAttribute('zoomfile') ? $(img).getAttribute('zoomfile') : $(img).getAttribute('file');
}
function attachimglst(pid, op, islazy) {
if(!op) {
$('imagelist_' + pid).style.display = 'none';
$('imagelistthumb_' + pid).style.display = '';
} else {
$('imagelistthumb_' + pid).style.display = 'none';
$('imagelist_' + pid).style.display = '';
if(islazy) {
o = new lazyload();
o.showImage();
} else {
attachimgshow(pid);
}
}
doane();
}
function attachimginfo(obj, infoobj, show, event) {
objinfo = fetchOffset(obj);
if(show) {
$(infoobj).style.left = objinfo['left'] + 'px';
$(infoobj).style.top = obj.offsetHeight < 40 ? (objinfo['top'] + obj.offsetHeight) + 'px' : objinfo['top'] + 'px';
$(infoobj).style.display = '';
} else {
if(BROWSER.ie) {
$(infoobj).style.display = 'none';
return;
} else {
var mousex = document.body.scrollLeft + event.clientX;
var mousey = document.documentElement.scrollTop + event.clientY;
if(mousex < objinfo['left'] || mousex > objinfo['left'] + objinfo['width'] || mousey < objinfo['top'] || mousey > objinfo['top'] + objinfo['height']) {
$(infoobj).style.display = 'none';
}
}
}
}
function signature(obj) {
if(obj.style.maxHeightIE != '') {
var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight + 'px';
if(obj.innerHTML.indexOf('<IMG ') == -1) {
obj.style.maxHeightIE = '';
}
return height;
}
}
function tagshow(event) {
var obj = BROWSER.ie ? event.srcElement : event.target;
ajaxmenu(obj, 0, 1, 2);
}
function parsetag(pid) {
if(!$('postmessage_'+pid) || $('postmessage_'+pid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var havetag = false;
var tagfindarray = new Array();
var str = $('postmessage_'+pid).innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3, $4) {
for(i in tagarray) {
if(tagarray[i] && $3.indexOf(tagarray[i]) != -1) {
havetag = true;
$3 = $3.replace(tagarray[i], '<h_ ' + i + '>');
tmp = $3.replace(/&[a-z]*?<h_ \d+>[a-z]*?;/ig, '');
if(tmp != $3) {
$3 = tmp;
} else {
tagfindarray[i] = tagarray[i];
tagarray[i] = '';
}
}
}
return $2 + $3;
});
if(havetag) {
$('postmessage_'+pid).innerHTML = str.replace(/<h_ (\d+)>/ig, function($1, $2) {
return '<span href=\"forum.php?mod=tag&name=' + tagencarray[$2] + '\" onclick=\"tagshow(event)\" class=\"t_tag\">' + tagfindarray[$2] + '</span>';
});
}
}
function setanswer(pid, from){
if(confirm('您确认要把该回复选为“最佳答案”吗?')){
if(BROWSER.ie) {
doane(event);
}
$('modactions').action='forum.php?mod=misc&action=bestanswer&tid=' + tid + '&pid=' + pid + '&from=' + from + '&bestanswersubmit=yes';
$('modactions').submit();
}
}
var authort;
function showauthor(ctrlObj, menuid) {
authort = setTimeout(function () {
showMenu({'menuid':menuid});
if($(menuid + '_ma').innerHTML == '') $(menuid + '_ma').innerHTML = ctrlObj.innerHTML;
}, 500);
if(!ctrlObj.onmouseout) {
ctrlObj.onmouseout = function() {
clearTimeout(authort);
}
}
}
function fastpostappendreply() {
if($('fastpostrefresh') != null) {
setcookie('fastpostrefresh', $('fastpostrefresh').checked ? 1 : 0, 2592000);
if($('fastpostrefresh').checked) {
location.href = 'forum.php?mod=redirect&tid='+tid+'&goto=lastpost&random=' + Math.random() + '#lastpost';
return;
}
}
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
$('fastpostsubmit').disabled = false;
if($('fastpostmessage')) {
$('fastpostmessage').value = '';
} else {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
}
if($('secanswer3')) {
$('checksecanswer3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('secanswer3').value = '';
secclick3['secanswer3'] = 0;
}
if($('seccodeverify3')) {
$('checkseccodeverify3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('seccodeverify3').value = '';
secclick3['seccodeverify3'] = 0;
}
showCreditPrompt();
}
function succeedhandle_fastpost(locationhref, message, param) {
var pid = param['pid'];
var tid = param['tid'];
var from = param['from'];
if(pid) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + pid + '&from=' + from, 'post_new', 'ajaxwaitid', '', null, 'fastpostappendreply()');
if(replyreload) {
var reloadpids = replyreload.split(',');
for(i = 1;i < reloadpids.length;i++) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + reloadpids[i] + '&from=' + from, 'post_' + reloadpids[i]);
}
}
$('fastpostreturn').className = '';
} else {
if(!message) {
message = '本版回帖需要审核,您的帖子将在通过审核后显示';
}
$('post_new').style.display = $('fastpostmessage').value = $('fastpostreturn').className = '';
$('fastpostreturn').innerHTML = message;
}
if(param['sechash']) {
updatesecqaa(param['sechash']);
updateseccode(param['sechash']);
}
if($('attach_tblheader')) {
$('attach_tblheader').style.display = 'none';
}
if($('attachlist')) {
$('attachlist').innerHTML = '';
}
}
function errorhandle_fastpost() {
$('fastpostsubmit').disabled = false;
}
function succeedhandle_comment(locationhref, message, param) {
ajaxget('forum.php?mod=misc&action=commentmore&tid=' + param['tid'] + '&pid=' + param['pid'], 'comment_' + param['pid']);
hideWindow('comment');
showCreditPrompt();
}
function succeedhandle_postappend(locationhref, message, param) {
ajaxget('forum.php?mod=viewthread&tid=' + param['tid'] + '&viewpid=' + param['pid'], 'post_' + param['pid']);
hideWindow('postappend');
}
function recommendupdate(n) {
if(getcookie('recommend')) {
var objv = n > 0 ? $('recommendv_add') : $('recommendv_subtract');
objv.innerHTML = parseInt(objv.innerHTML) + 1;
setTimeout(function () {
$('recommentc').innerHTML = parseInt($('recommentc').innerHTML) + n;
$('recommentv').style.display = 'none';
}, 1000);
setcookie('recommend', '');
}
}
function favoriteupdate() {
var obj = $('favoritenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function relayupdate() {
var obj = $('relaynumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function shareupdate() {
var obj = $('sharenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function switchrecommendv() {
display('recommendv');
display('recommendav');
}
function appendreply() {
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
if($('postform')) {
$('postform').replysubmit.disabled = false;
}
showCreditPrompt();
}
function poll_checkbox(obj) {
if(obj.checked) {
p++;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(p == max_obj) {
if(e.name.match('pollanswers') && !e.checked) {
e.disabled = true;
}
}
}
} else {
p--;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(e.name.match('pollanswers') && e.disabled) {
e.disabled = false;
}
}
}
$('pollsubmit').disabled = p <= max_obj && p > 0 ? false : true;
}
function itemdisable(i) {
if($('itemt_' + i).className == 'z') {
$('itemt_' + i).className = 'z xg1';
$('itemc_' + i).value = '';
itemset(i);
} else {
$('itemt_' + i).className = 'z';
$('itemc_' + i).value = $('itemc_' + i).value > 0 ? $('itemc_' + i).value : 0;
}
}
function itemop(i, v) {
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function itemclk(i, v) {
$('itemc_' + i).value = v;
$('itemt_' + i).className = 'z';
}
function itemset(i) {
var v = $('itemc_' + i).value;
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function checkmgcmn(id) {
if($('mgc_' + id) && !$('mgc_' + id + '_menu').getElementsByTagName('li').length) {
$('mgc_' + id).innerHTML = '';
$('mgc_' + id).style.display = 'none';
}
}
function toggleRatelogCollapse(tarId, ctrlObj) {
if($(tarId).className == 'rate') {
$(tarId).className = 'rate rate_collapse';
setcookie('ratecollapse', 1, 2592000);
ctrlObj.innerHTML = '展开';
} else {
$(tarId).className = 'rate';
setcookie('ratecollapse', 0, -2592000);
ctrlObj.innerHTML = '收起';
}
}
function copyThreadUrl(obj) {
setCopy($('thread_subject').innerHTML.replace(/&/g, '&') + '\n' + obj.href + '\n', '帖子地址已经复制到剪贴板');
return false;
}
function replyNotice() {
var newurl = 'forum.php?mod=misc&action=replynotice&tid=' + tid + '&op=';
var replynotice = $('replynotice');
var status = replynotice.getAttribute("status");
if(status == 1) {
replynotice.href = newurl + 'receive';
replynotice.innerHTML = '接收回复通知';
replynotice.setAttribute("status", 0);
} else {
replynotice.href = newurl + 'ignore';
replynotice.innerHTML = '取消回复通知';
replynotice.setAttribute("status", 1);
}
}
var connect_share_loaded = 0;
function connect_share(connect_share_url, connect_uin) {
if(parseInt(discuz_uid) <= 0) {
return true;
} else {
if(connect_uin) {
setTimeout(function () {
if(!connect_share_loaded) {
showDialog('分享服务连接失败,请稍后再试。', 'notice');
$('append_parent').removeChild($('connect_load_js'));
}
}, 5000);
connect_load(connect_share_url);
} else {
showDialog($('connect_share_unbind').innerHTML, 'info', '请先绑定QQ账号');
}
return false;
}
}
function connect_load(src) {
var e = document.createElement('script');
e.type = "text/javascript";
e.id = 'connect_load_js';
e.src = src + '&_r=' + Math.random();
e.async = true;
$('append_parent').appendChild(e);
}
function connect_show_dialog(title, html, type) {
var type = type ? type : 'info';
showDialog(html, type, title, null, 0);
}
function connect_get_thread() {
connect_thread_info.subject = $('connect_thread_title').value;
if ($('postmessage_' + connect_thread_info.post_id)) {
connect_thread_info.html_content = preg_replace(["'"], ['%27'], encodeURIComponent(preg_replace(['本帖最后由 .*? 于 .*? 编辑',' ','<em onclick="copycode\\(\\$\\(\'code0\'\\)\\);">复制代码</em>'], ['',' ', ''], $('postmessage_' + connect_thread_info.post_id).innerHTML)));
}
return connect_thread_info;
}
function lazyload(className) {
var obj = this;
lazyload.className = className;
this.getOffset = function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
};
this.initImages = function (ele) {
lazyload.imgs = [];
var eles = lazyload.className ? $C(lazyload.className, ele) : [document.body];
for (var i = 0; i < eles.length; i++) {
var imgs = eles[i].getElementsByTagName('IMG');
for(var j = 0; j < imgs.length; j++) {
if(imgs[j].getAttribute('file') && !imgs[j].getAttribute('lazyloaded')) {
if(this.getOffset(imgs[j]) > document.documentElement.clientHeight) {
lazyload.imgs.push(imgs[j]);
} else {
imgs[j].setAttribute('src', imgs[j].getAttribute('file'));
imgs[j].setAttribute('lazyloaded', 'true');
}
}
}
}
};
this.showImage = function() {
this.initImages();
if(!lazyload.imgs.length) return false;
var imgs = [];
var scrollTop = Math.max(document.documentElement.scrollTop , document.body.scrollTop);
for (var i=0; i<lazyload.imgs.length; i++) {
var img = lazyload.imgs[i];
var offsetTop = this.getOffset(img);
if (!img.getAttribute('lazyloaded') && offsetTop > document.documentElement.clientHeight && (offsetTop - scrollTop < document.documentElement.clientHeight)) {
var dom = document.createElement('div');
var width = img.getAttribute('width') ? img.getAttribute('width') : 100;
var height = img.getAttribute('height') ? img.getAttribute('height') : 100;
dom.innerHTML = '<div style="width: '+width+'px; height: '+height+'px;background: url('+IMGDIR + '/loading.gif) no-repeat center center;"></div>';
img.parentNode.insertBefore(dom.childNodes[0], img);
img.onload = function () {if(!this.getAttribute('_load')) {this.setAttribute('_load', 1);this.style.width = this.style.height = '';this.parentNode.removeChild(this.previousSibling);}};
img.style.width = img.style.height = '1px';
img.setAttribute('src', img.getAttribute('file') ? img.getAttribute('file') : img.getAttribute('src'));
img.setAttribute('lazyloaded', true);
} else {
imgs.push(img);
}
}
lazyload.imgs = imgs;
return true;
};
this.showImage();
_attachEvent(window, 'scroll', function(){obj.showImage();});
}
function update_collection(){
sum = 1;
$('collectionnumber').innerText = parseInt($('collectionnumber').innerText)+sum;
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_diy.js 31093 2012-07-16 03:54:34Z zhangguosheng $
*/
String.prototype.property2js = function(){
var t = this.replace(/-([a-z])/g, function($0, $1) {return $1.toUpperCase();});
return t;
};
function styleCss(n) {
if(typeof n == "number") {
var _s = document.styleSheets[n];
} else {
return false;
}
this.sheet = _s;
this.rules = _s.cssRules ? _s.cssRules : _s.rules;
};
styleCss.prototype.indexOf = function(selector) {
for(var i = 0; i < this.rules.length; i++) {
if (typeof(this.rules[i].selectorText) == 'undefined') continue;
if(this.rules[i].selectorText == selector) {
return i;
}
}
return -1;
};
styleCss.prototype.removeRule = function(n) {
if(typeof n == "number") {
if(n < this.rules.length) {
this.sheet.removeRule ? this.sheet.removeRule(n) : this.sheet.deleteRule(n);
}
} else {
var i = this.indexOf(n);
if (i>0) this.sheet.removeRule ? this.sheet.removeRule(i) : this.sheet.deleteRule(i);
}
};
styleCss.prototype.addRule = function(selector, styles, n, porperty) {
var i = this.indexOf(selector);
var s = '';
var reg = '';
if (i != -1) {
reg = new RegExp('^'+porperty+'.*;','i');
s = this.getRule(selector);
if (s) {
s = s.replace(selector,'').replace('{', '').replace('}', '').replace(/ /g, ' ').replace(/^ | $/g,'');
s = (s != '' && s.substr(-1,1) != ';') ? s+ ';' : s;
s = s.toLowerCase().replace(reg, '');
if (s.length == 1) s = '';
}
this.removeRule(i);
}
s = s.indexOf('!important') > -1 || s.indexOf('! important') > -1 ? s : s.replace(/;/g,' !important;');
s = s + styles;
if (typeof n == 'undefined' || !isNaN(n)) {
n = this.rules.length;
}
if (this.sheet.insertRule) {
this.sheet.insertRule(selector+'{'+s+'}', n);
} else {
if (s) this.sheet.addRule(selector, s, n);
}
};
styleCss.prototype.setRule = function(selector, attribute, value) {
var i = this.indexOf(selector);
if(-1 == i) return false;
this.rules[i].style[attribute] = value;
return true;
};
styleCss.prototype.getRule = function(selector, attribute) {
var i = this.indexOf(selector);
if(-1 == i) return '';
var value = '';
if (typeof attribute == 'undefined') {
value = typeof this.rules[i].cssText != 'undefined' ? this.rules[i].cssText : this.rules[i].style['cssText'];
} else {
value = this.rules[i].style[attribute];
}
return typeof value != 'undefined' ? value : '';
};
styleCss.prototype.removeAllRule = function(noSearch) {
var num = this.rules.length;
var j = 0;
for(var i = 0; i < num; i ++) {
var selector = this.rules[this.rules.length - 1 - j].selectorText;
if(noSearch == 1) {
this.sheet.removeRule ? this.sheet.removeRule(this.rules.length - 1 - j) : this.sheet.deleteRule(this.rules.length - 1 - j);
} else {
j++;
}
}
};
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (element, index) {
var length = this.length;
if (index == null) {
index = 0;
} else {
index = (!isNaN(index) ? index : parseInt(index));
if (index < 0) index = length + index;
if (index < 0) index = 0;
}
for (var i = index; i < length; i++) {
var current = this[i];
if (!(typeof(current) === 'undefined') || i in this) {
if (current === element) return i;
}
}
return -1;
};
}
if (!Array.prototype.filter){
Array.prototype.filter = function(fun , thisp){
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this){
var val = this[i];
if (fun.call(thisp, val, i, this)) res.push(val);
}
}
return res;
};
}
var Util = {
event: function(event){
Util.e = event || window.event;
Util.e.aim = Util.e.target || Util.e.srcElement;
if (!Util.e.preventDefault) {
Util.e.preventDefault = function(){
Util.e.returnValue = false;
};
}
if (!Util.e.stopPropagation) {
Util.e.stopPropagation = function(){
Util.e.cancelBubble = true;
};
}
if (typeof Util.e.layerX == "undefined") {
Util.e.layerX = Util.e.offsetX;
}
if (typeof Util.e.layerY == "undefined") {
Util.e.layerY = Util.e.offsetY;
}
if (typeof Util.e.which == "undefined") {
Util.e.which = Util.e.button;
}
return Util.e;
},
url: function(s){
var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
if (/\\\\$/.test(s2)) {
s2 += ' ';
}
return "url('" + s2 + "')";
},
trimUrl : function(s){
var s2 = s.toLowerCase().replace(/url\(|\"|\'|\)/g,'');
return s2;
},
swapDomNodes: function(a, b){
var afterA = a.nextSibling;
if (afterA == b) {
swapDomNodes(b, a);
return;
}
var aParent = a.parentNode;
b.parentNode.replaceChild(a, b);
aParent.insertBefore(b, afterA);
},
hasClass: function(el, name){
return el && el.nodeType == 1 && el.className.split(/\s+/).indexOf(name) != -1;
},
addClass: function(el, name){
el.className += this.hasClass(el, name) ? '' : ' ' + name;
},
removeClass: function(el, name){
var names = el.className.split(/\s+/);
el.className = names.filter(function(n){
return name != n;
}).join(' ');
},
getTarget: function(e, attributeName, value){
var target = e.target || e.srcElement;
while (target != null) {
if (attributeName == 'className') {
if (this.hasClass(target, value)) {
return target;
}
}else if (target[attributeName] == value) {
return target;
}
target = target.parentNode;
}
return false;
},
getOffset:function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
},
insertBefore: function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (targetNode.id && targetNode.id.indexOf('temp')>-1) {
parentNode.insertBefore(newNode,targetNode);
} else if (!next) {
parentNode.appendChild(newNode);
} else {
parentNode.insertBefore(newNode,targetNode);
}
},
insertAfter : function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (next) {
parentNode.insertBefore(newNode,next);
} else {
parentNode.appendChild(newNode);
}
},
getScroll: function () {
var t, l, w, h;
if (document.documentElement && document.documentElement.scrollTop) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
return {t: t, l: l, w: w, h: h};
},
hide:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele){ele.style.display = 'none';ele.style.visibility = 'hidden';}
},
show:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele) {
this.removeClass(ele, 'hide');
ele.style.display = '';
ele.style.visibility = 'visible';
}
},
cancelSelect : function () {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
},
getSelectText : function () {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
} else {
t = '';
}
return t;
},
toggleEle : function (ele) {
ele = (typeof ele !='object') ? $(ele) : ele;
if (!ele) return false;
var value = this.getFinallyStyle(ele,'display');
if (value =='none') {
this.show(ele);
this.hide($('uploadmsg_button'));
} else {
this.hide(ele);
this.show($('uploadmsg_button'));
}
},
getFinallyStyle : function (ele,property) {
ele = (typeof ele !='object') ? $(ele) : ele;
var style = (typeof(ele['currentStyle']) == 'undefined') ? window.getComputedStyle(ele,null)[property] : ele['currentStyle'][property];
if (typeof style == 'undefined' && property == 'backgroundPosition') {
style = ele['currentStyle']['backgroundPositionX'] + ' ' +ele['currentStyle']['backgroundPositionY'];
}
return style;
},
recolored:function (){
var b = document.body;
b.style.zoom = b.style.zoom=="1"?"100%":"1";
},
getRandom : function (len,type) {
len = len < 0 ? 0 : len;
type = type && type<=3? type : 3;
var str = '';
for (var i = 0; i < len; i++) {
var j = Math.ceil(Math.random()*type);
if (j == 1) {
str += Math.ceil(Math.random()*9);
} else if (j == 2) {
str += String.fromCharCode(Math.ceil(Math.random()*25+65));
} else {
str += String.fromCharCode(Math.ceil(Math.random()*25+97));
}
}
return str;
},
fade : function(obj,timer,ftype,cur,fn) {
if (this.stack == undefined) {this.stack = [];}
obj = typeof obj == 'string' ? $(obj) : obj;
if (!obj) return false;
for (var i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj && (cur == 0 || cur == 100)) return false;
}
if (cur == 0 || cur == 100) {this.stack.push(obj);}
ftype = ftype != 'in' && ftype != 'out' ? 'out' : ftype;
timer = timer || 400;
var step = 100/(timer/20);
obj.style.filter = 'Alpha(opacity=' + cur + ')';
obj.style.opacity = cur / 100;
cur = ftype == 'in' ? cur + step : cur - step ;
var fadeTimer = (function(){
return setTimeout(function () {
Util.fade(obj, timer, ftype, cur, fn);
}, 20);
})();
this[ftype == 'in' ? 'show' : 'hide'](obj);
if(ftype == 'in' && cur >= 100 || ftype == 'out' && cur <= 0) {
clearTimeout(fadeTimer);
for (i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj ) {
this.stack.splice(i,1);break;
}
}
fn = fn || function(){};
fn(obj);
}
return obj;
},
fadeIn : function (obj,timer,fn) {
return this.fade(obj, timer, 'in', 0, fn);
},
fadeOut : function (obj,timer,fn) {
return this.fade(obj, timer, 'out', 100, fn);
},
getStyle : function (ele) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText : s;
}
return false;
},
setStyle : function (ele,cssText) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText = cssText : ele.setAttribute('style',cssText);
}
return false;
},
getText : function (ele) {
var t = ele.innerText ? ele.innerText : ele.textContent;
return !t ? '' : t;
},
rgb2hex : function (color) {
if (!color) return '';
var reg = new RegExp('(\\d+)[, ]+(\\d+)[, ]+(\\d+)','g');
var rgb = reg.exec(color);
if (rgb == null) rgb = [0,0,0,0];
var red = rgb[1], green = rgb[2], blue = rgb[3];
var decColor = 65536 * parseInt(red) + 256 * parseInt(green) + parseInt(blue);
var hex = decColor.toString(16).toUpperCase();
var pre = new Array(6 - hex.length + 1).join('0');
hex = pre + hex;
return hex;
},
formatColor : function (color) {
return color == '' || color.indexOf('#')>-1 || color.toLowerCase() == 'transparent' ? color : '#'+Util.rgb2hex(color);
}
};
(function(){
Frame = function(name, className, top, left, moveable){
this.name = name;
this.top = top;
this.left = left;
this.moveable = moveable ? true : false;
this.columns = [];
this.className = className;
this.titles = [];
if (typeof Frame._init == 'undefined') {
Frame.prototype.addColumn = function (column) {
if (column instanceof Column) {
this.columns[column.name] = column;
}
};
Frame.prototype.addFrame = function(columnId, frame) {
if (frame instanceof Frame || frame instanceof Tab){
this.columns[columnId].children.push(frame);
}
};
Frame.prototype.addBlock = function(columnId, block) {
if (block instanceof Block){
this.columns[columnId].children.push(block);
}
};
}
Frame._init = true;
};
Column = function (name, className) {
this.name = name;
this.className = className;
this.children = [];
};
Tab = function (name, className, top, left, moveable) {
Frame.apply(this, arguments);
};
Tab.prototype = new Frame();
Block = function(name, className, top, left) {
this.name = name;
this.top = top;
this.left = left;
this.className = className;
this.titles = [];
};
Drag = function () {
this.data = [];
this.scroll = {};
this.menu = [];
this.data = [];
this.allBlocks = [];
this.overObj = '';
this.dragObj = '';
this.dragObjFrame = '';
this.overObjFrame = '';
this.isDragging = false;
this.layout = 2;
this.frameClass = 'frame';
this.blockClass = 'block';
this.areaClass = 'area';
this.moveableArea = [];
this.moveableColumn = 'column';
this.moveableObject = 'move-span';
this.titleClass = 'title';
this.hideClass = 'hide';
this.titleTextClass = 'titletext';
this.frameTitleClass = 'frame-title',
this.tabClass = 'frame-tab';
this.tabActivityClass = 'tabactivity';
this.tabTitleClass = 'tab-title';
this.tabContentClass = 'tb-c';
this.moving = 'moving';
this.contentClass = 'dxb_bc';
this.tmpBoxElement = null ;
this.dargRelative = {};
this.scroll = {};
this.menu = [];
this.rein = [];
this.newFlag = false;
this.isChange = false;
this.fn = '';
this._replaceFlag = false;
this.sampleMode = false;
this.sampleBlocks = null;
this.advancedStyleSheet = null;
};
Drag.prototype = {
getTmpBoxElement : function () {
if (!this.tmpBoxElement) {
this.tmpBoxElement = document.createElement("div");
this.tmpBoxElement.id = 'tmpbox';
this.tmpBoxElement.className = "tmpbox" ;
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
this.tmpBoxElement.style.height = this.overObj.offsetHeight-4+"px";
} else if (this.overObj && this.overObj.offsetWidth > 0) {
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
}
return this.tmpBoxElement;
},
getPositionStr : function (){
this.initPosition();
var start = '<?xml version="1.0" encoding="ISO-8859-1"?><root>';
var end ="</root>";
var str = "";
for (var i in this.data) {
if (typeof this.data[i] == 'function') continue;
str += '<item id="' + i + '">';
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
str += this._getFrameXML(this.data[i][j]);
}
str += '</item>';
}
return start + str + end;
},
_getFrameXML : function (frame) {
if (!(frame instanceof Frame || frame instanceof Tab) || frame.name.indexOf('temp') > 0) return '';
var itemId = frame instanceof Tab ? 'tab' : 'frame';
var Cstr = "";
var name = frame.name;
var frameAttr = this._getAttrXML(frame);
var columns = frame['columns'];
for (var j in columns) {
if (columns[j] instanceof Column) {
var Bstr = '';
var colChildren = columns[j].children;
for (var k in colChildren) {
if (k == 'attr' || typeof colChildren[k] == 'function' || colChildren[k].name.indexOf('temp') > 0) continue;
if (colChildren[k] instanceof Block) {
Bstr += '<item id="block`' + colChildren[k]['name'] + '">';
Bstr += this._getAttrXML(colChildren[k]);
Bstr += '</item>';
} else if (colChildren[k] instanceof Frame || colChildren[k] instanceof Tab) {
Bstr += this._getFrameXML(colChildren[k]);
}
}
var columnAttr = this._getAttrXML(columns[j]);
Cstr += '<item id="column`' + j + '">' + columnAttr + Bstr + '</item>';
}
}
return '<item id="' + itemId + '`' + name + '">' + frameAttr + Cstr + '</item>';
},
_getAttrXML : function (obj) {
var attrXml = '<item id="attr">';
var trimAttr = ['left', 'top'];
var xml = '';
if (obj instanceof Frame || obj instanceof Tab || obj instanceof Block || obj instanceof Column) {
for (var i in obj) {
if (i == 'titles') {
xml += this._getTitlesXML(obj[i]);
}
if (!(typeof obj[i] == 'object' || typeof obj[i] == 'function')) {
if (trimAttr.indexOf(i) >= 0) continue;
xml += '<item id="' + i + '"><![CDATA[' + obj[i] + ']]></item>';
}
}
}else {
xml += '';
}
return attrXml + xml + '</item>';
},
_getTitlesXML : function (titles) {
var xml = '<item id="titles">';
for (var i in titles) {
if (typeof titles[i] == 'function') continue;
xml += '<item id="'+i+'">';
for (var j in titles[i]) {
if (typeof titles[i][j] == 'function') continue;
xml += '<item id="'+j+'"><![CDATA[' + titles[i][j] + ']]></item>';
}
xml += '</item>';
}
xml += '</item>';
return xml;
},
getCurrentOverObj : function (e) {
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var max = 10000000;
for (var i in this.data) {
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
var min = this._getMinDistance(this.data[i][j], max);
if (min.distance < max) {
var id = min.id;
max = min.distance;
}
}
}
return $(id);
},
_getMinDistance : function (ele, max) {
if(ele.name==this.dragObj.id) return {"id":ele.name, "distance":max};
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var id;
var isTabInTab = Util.hasClass(this.dragObj, this.tabClass) && Util.hasClass($(ele.name).parentNode.parentNode, this.tabClass);
if (ele instanceof Frame || ele instanceof Tab) {
if (ele.moveable && !isTabInTab) {
var isTab = Util.hasClass(this.dragObj, this.tabClass);
var isFrame = Util.hasClass(this.dragObj, this.frameClass);
var isBlock = Util.hasClass(this.dragObj, this.blockClass) && Util.hasClass($(ele.name).parentNode, this.moveableColumn);
if ( isTab || isFrame || isBlock) {
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
max = distance;
id = ele.name;
}
}
}
for (var i in ele['columns']) {
var column = ele['columns'][i];
if (column instanceof Column) {
for (var j in column['children']) {
if ((column['children'][j] instanceof Tab || column['children'][j] instanceof Frame || column['children'][j] instanceof Block)) {
var min = this._getMinDistance(column['children'][j], max);
if (min.distance < max) {
id = min.id;
max = min.distance;
}
}
}
}
}
return {"id":id, "distance":max};
} else {
if (isTabInTab) return {'id': ele['name'], 'distance': max};
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
return {'id': ele['name'], 'distance': distance};
} else {
return {'id': ele['name'], 'distance': max};
}
}
},
getObjByName : function (name, data) {
if (!name) return false;
data = data || this.data;
if ( data instanceof Frame) {
if (data.name == name) {
return data;
} else {
var d = this.getObjByName(name,data['columns']);
if (name == d.name) return d;
}
} else if (data instanceof Block) {
if (data.name == name) return data;
} else if (typeof data == 'object') {
for (var i in data) {
var d = this.getObjByName(name, data[i]);
if (name == d.name) return d;
}
}
return false;
},
initPosition : function () {
this.data = [],this.allBlocks = [];
var blocks = $C(this.blockClass);
for(var i = 0; i < blocks.length; i++) {
if (blocks[i]['id'].indexOf('temp') < 0) {
this.checkEdit(blocks[i]);
this.allBlocks.push(blocks[i]['id'].replace('portal_block_',''));
}
}
var areaLen = this.moveableArea.length;
for (var j = 0; j < areaLen; j++ ) {
var area = this.moveableArea[j];
var areaData = [];
if (typeof area == 'object') {
this.checkTempDiv(area.id);
var frames = area.childNodes;
for (var i in frames) {
if (typeof(frames[i]) != 'object') continue;
if (Util.hasClass(frames[i], this.frameClass) || Util.hasClass(frames[i], this.blockClass)
|| Util.hasClass(frames[i], this.tabClass) || Util.hasClass(frames[i], this.moveableObject)) {
areaData.push(this.initFrame(frames[i]));
}
}
this.data[area.id] = areaData;
}
}
this._replaceFlag = true;
},
removeBlockPointer : function(e) {this.removeBlock(e);},
toggleContent : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('_edit_toggle','');
} else {
id = e;
}
var obj = this.getObjByName(id);
var display = '';
if (obj instanceof Block || obj instanceof Tab) {
display = $(id+'_content').style.display;
Util.toggleEle(id+'_content');
} else {
var col = obj.columns;
for (var i in col) {
display = $(i).style.display;
Util.toggleEle($(i));
}
}
if(display != '') {
e.aim.src=STATICURL+'/image/common/fl_collapsed_no.gif';
} else {
e.aim.src=STATICURL+'/image/common/fl_collapsed_yes.gif';
}
},
checkEdit : function (ele) {
if (!ele || Util.hasClass(ele, 'temp') || ele.getAttribute('noedit')) return false;
var id = ele.id;
var _method = this;
if (!$(id+'_edit')) {
var _method = this;
var dom = document.createElement('div');
dom.className = 'edit hide';
dom.id = id+'_edit';
dom.innerHTML = '<span id="'+id+'_edit_menu">编辑</span>';
ele.appendChild(dom);
$(id+'_edit_menu').onclick = function (e){Drag.prototype.toggleMenu.call(_method, e, this);};
}
ele.onmouseover = function (e) {Drag.prototype.showEdit.call(_method,e);};
ele.onmouseout = function (e) {Drag.prototype.hideEdit.call(_method,e);};
},
initFrame : function (frameEle) {
if (typeof(frameEle) != 'object') return '';
var frameId = frameEle.id;
if(!this.sampleMode) {
this.checkEdit(frameEle);
}
var moveable = Util.hasClass(frameEle, this.moveableObject);
var frameObj = '';
if (Util.hasClass(frameEle, this.tabClass)) {
this._initTabActivity(frameEle);
frameObj = new Tab(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
} else if (Util.hasClass(frameEle, this.frameClass) || Util.hasClass(frameEle, this.moveableObject)) {
if (Util.hasClass(frameEle, this.frameClass) && !this._replaceFlag) this._replaceFrameColumn(frameEle);
frameObj = new Frame(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
}
this._initColumn(frameObj, frameEle);
return frameObj;
},
_initColumn : function (frameObj,frameEle) {
var columns = frameEle.children;
if (Util.hasClass(frameEle.parentNode.parentNode,this.tabClass)) {
var col2 = $(frameEle.id+'_content').children;
var len = columns.length;
for (var i in col2) {
if (typeof(col2[i]) == 'object') columns[len+i] = col2[i];
}
}
for (var i in columns) {
if (typeof(columns[i]) != 'object') continue;
if (Util.hasClass(columns[i], this.titleClass)) {
this._initTitle(frameObj, columns[i]);
}
this._initEleTitle(frameObj, frameEle);
if (Util.hasClass(columns[i], this.moveableColumn)) {
var columnId = columns[i].id;
var column = new Column(columnId, columns[i].className);
frameObj.addColumn(column);
this.checkTempDiv(columnId);
var elements = columns[i].children;
var eleLen = elements.length;
for (var j = 0; j < eleLen; j++) {
var ele = elements[j];
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var frameObj2 = this.initFrame(ele);
frameObj.addFrame(columnId, frameObj2);
} else if (Util.hasClass(ele, this.blockClass) || Util.hasClass(ele, this.moveableObject)) {
var block = new Block(ele.id, ele.className, Util.getOffset(ele, false), Util.getOffset(ele, true));
for (var k in ele.children) {
if (Util.hasClass(ele.children[k], this.titleClass)) this._initTitle(block, ele.children[k]);
}
this._initEleTitle(block, ele);
frameObj.addBlock(columnId, block);
}
}
}
}
},
_initTitle : function (obj, ele) {
if (Util.hasClass(ele, this.titleClass)) {
obj.titles['className'] = [ele.className];
obj.titles['style'] = {};
if (ele.style.backgroundImage) obj.titles['style']['background-image'] = ele.style.backgroundImage;
if (ele.style.backgroundRepeat) obj.titles['style']['background-repeat'] = ele.style.backgroundRepeat;
if (ele.style.backgroundColor) obj.titles['style']['background-color'] = ele.style.backgroundColor;
if (obj instanceof Tab) {
obj.titles['switchType'] = [];
obj.titles['switchType'][0] = ele.getAttribute('switchtype') ? ele.getAttribute('switchtype') : 'click';
}
var ch = ele.children;
for (var k in ch) {
if (Util.hasClass(ch[k], this.titleTextClass)){
this._getTitleData(obj, ch[k], 'first');
} else if (typeof ch[k] == 'object' && !Util.hasClass(ch[k], this.moveableObject)) {
this._getTitleData(obj, ch[k]);
}
}
}
},
_getTitleData : function (obj, ele, i) {
var shref = '',ssize = '',sfloat = '',scolor = '',smargin = '',stext = '', src = '';
var collection = ele.getElementsByTagName('a');
if (collection.length > 0) {
shref = collection[0]['href'];
scolor = collection[0].style['color'] + ' !important';
}
collection = ele.getElementsByTagName('img');
if (collection.length > 0) {
src = collection[0]['src'];
}
stext = Util.getText(ele);
if (stext || src) {
scolor = scolor ? scolor : ele.style['color'];
sfloat = ele.style['styleFloat'] ? ele.style['styleFloat'] : ele.style['cssFloat'] ;
sfloat = sfloat == undefined ? '' : sfloat;
var margin_ = sfloat == '' ? 'left' : sfloat;
smargin = parseInt(ele.style[('margin-'+margin_).property2js()]);
smargin = smargin ? smargin : '';
ssize = parseInt(ele.style['fontSize']);
ssize = ssize ? ssize : '';
var data = {'text':stext, 'href':shref,'color':scolor, 'float':sfloat, 'margin':smargin, 'font-size':ssize, 'className':ele.className, 'src':src};
if (i) {
obj.titles[i] = data;
} else {
obj.titles.push(data);
}
}
},
_initEleTitle : function (obj,ele) {
if (Util.hasClass(ele, this.moveableObject)) {
if (obj.titles['first'] && obj.titles['first']['text']) {
var title = obj.titles['first']['text'];
} else {
var title = obj.name;
}
}
},
showBlockName : function (ele) {
var title = $C('block-name', ele, 'div');
if(title.length) {
Util.show(title[0]);
}
},
hideBlockName : function (ele) {
var title = $C('block-name', ele, 'div');
if(title.length) {
Util.hide(title[0]);
}
},
showEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
if (targetObject) {
Util.show(targetObject.id + '_edit');
targetObject.style.backgroundColor="#fffacd";
this.showBlockName(targetObject);
} else {
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.show(targetFrame.id + '_edit');
targetFrame.style.backgroundColor="#fffacd";
}
}
},
hideEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.hide(targetFrame.id + '_edit');
targetFrame.style.backgroundColor = '';
}
if (typeof targetObject == 'object') {
Util.hide(targetObject.id + '_edit');
targetObject.style.backgroundColor = '';
this.hideBlockName(targetObject);
}
},
toggleMenu : function (e, obj) {
e = Util.event(e);
e.stopPropagation();
var objPara = {'top' : Util.getOffset( obj, false),'left' : Util.getOffset( obj, true),
'width' : obj['offsetWidth'], 'height' : obj['offsetHeight']};
var dom = $('edit_menu');
if (dom) {
if (objPara.top + objPara.height == Util.getOffset(dom, false) && objPara.left == Util.getOffset(dom, true)) {
dom.parentNode.removeChild(dom);
} else {
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = this._getMenuHtml(e, obj);
}
} else {
var html = this._getMenuHtml(e, obj);
if (html != '') {
dom = document.createElement('div');
dom.id = 'edit_menu';
dom.className = 'edit-menu';
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = html;
document.body.appendChild(dom);
var _method = this;
document.body.onclick = function(e){Drag.prototype.removeMenu.call(_method, e);};
}
}
},
_getMenuHtml : function (e,obj) {
var id = obj.id.replace('_edit_menu','');
var html = '<ul>';
if (typeof this.menu[id] == 'object') html += this._getMenuHtmlLi(id, this.menu[id]);
if (Util.hasClass($(id),this.tabClass) && typeof this.menu['tab'] == 'object') html += this._getMenuHtmlLi(id, this.menu['tab']);
if (Util.hasClass($(id),this.frameClass) && typeof this.menu['frame'] == 'object') html += this._getMenuHtmlLi(id, this.menu['frame']);
if (Util.hasClass($(id),this.blockClass) && typeof this.menu['block'] == 'object') html += this._getMenuHtmlLi(id, this.menu['block']);
if (typeof this.menu['default'] == 'object' && this.getObjByName(id)) html += this._getMenuHtmlLi(id, this.menu['default']);
html += '</ul>';
return html == '<ul></ul>' ? '' : html;
},
_getMenuHtmlLi : function (id, cmds) {
var li = '';
var len = cmds.length;
for (var i=0; i<len; i++) {
li += '<li class="mitem" id="cmd_'+id+'" onclick='+"'"+cmds[i]['cmd']+"'"+'>'+cmds[i]['cmdName']+'</li>';
}
return li;
},
removeMenu : function (e) {
var dom = $('edit_menu');
if (dom) dom.parentNode.removeChild(dom);
document.body.onclick = '';
},
addMenu : function (objId,cmdName,cmd) {
if (typeof this.menu[objId] == 'undefined') this.menu[objId] = [];
this.menu[objId].push({'cmdName':cmdName, 'cmd':cmd});
},
setDefalutMenu : function () {},
setSampleMenu : function () {},
getPositionKey : function (n) {
this.initPosition();
n = parseInt(n);
var i = 0;
for (var k in this.position) {
if (i++ >= n) break;
}
return k;
},
checkTempDiv : function (_id) {
if(_id) {
var id = _id+'_temp';
var dom = $(id);
if (dom == null || typeof dom == 'undefined') {
dom = document.createElement("div");
dom.className = this.moveableObject+' temp';
dom.id = id;
$(_id).appendChild(dom);
}
}
},
_setCssPosition : function (ele, value) {
while (ele && ele.parentNode && ele.id != 'ct') {
if (Util.hasClass(ele,this.frameClass) || Util.hasClass(ele,this.tabClass)) ele.style.position = value;
ele = ele.parentNode;
}
},
initDragObj : function (e) {
e = Util.event(e);
var target = Util.getTarget(e,'className',this.moveableObject);
if (!target) {return false;}
if (this.overObj != target && target.id !='tmpbox') {
this.overObj = target;
this.overObj.style.cursor = 'move';
}
},
dragStart : function (e) {
e = Util.event(e);
if (e.aim['id'] && e.aim['id'].indexOf && e.aim['id'].indexOf('_edit') > 0) return false;
if(e.which != 1 ) {return false;}
this.overObj = this.dragObj = Util.getTarget(e,'className',this.moveableObject);
if (!this.dragObj || Util.hasClass(this.dragObj,'temp')) {return false;}
if (!this.getTmpBoxElement()) return false;
this.getRelative();
this._setCssPosition(this.dragObj.parentNode.parentNode, "static");
var offLeft = Util.getOffset( this.dragObj, true );
var offTop = Util.getOffset( this.dragObj, false );
var offWidth = this.dragObj['offsetWidth'];
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = offLeft + "px";
this.dragObj.style.top = offTop - 3 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
},
getRelative : function () {
this.dargRelative = {'up': this.dragObj.previousSibling, 'down': this.dragObj.nextSibling};
},
resetObj : function (e) {
if (this.dragObj){
e = Util.event(e);
var p = Util.getScroll();
var _t = p.t - this.scroll.t;
var _l = p.l - this.scroll.l;
var t = parseInt(this.dragObj.style.top);
var l = parseInt(this.dragObj.style.left);
t += _t;
l += _l;
this.dragObj.style.top =t+'px';
this.dragObj.style.left =l+'px';
this.scroll = Util.getScroll();
}
},
drag : function (e) {
e = Util.event(e);
if(!this.isDragging) {
this.dragObj.style.filter = "alpha(opacity=60)" ;
this.dragObj.style.opacity = 0.6 ;
this.isDragging = true ;
}
var _clientX = e.clientX;
var _clientY = e.clientY;
if (this.dragObj.lastMouseX == _clientX && this.dragObj.lastMouseY == _clientY) return false ;
var _lastY = parseInt(this.dragObj.style.top);
var _lastX = parseInt(this.dragObj.style.left);
_lastX = isNaN(_lastX) ? 0 :_lastX;
_lastY = isNaN(_lastY) ? 0 :_lastY;
var newX, newY;
newY = _lastY + _clientY - this.dragObj.lastMouseY;
newX = _lastX + _clientX - this.dragObj.lastMouseX;
this.dragObj.style.left = newX +"px ";
this.dragObj.style.top = newY + "px ";
this.dragObj.lastMouseX = _clientX;
this.dragObj.lastMouseY = _clientY;
var obj = this.getCurrentOverObj(e);
if (obj && this.overObj != obj) {
this.overObj = obj;
this.getTmpBoxElement();
Util.insertBefore(this.tmpBoxElement, this.overObj);
this.dragObjFrame = this.dragObj.parentNode.parentNode;
this.overObjFrame = this.overObj.parentNode.parentNode;
}
Util.cancelSelect();
},
_pushTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var dom = $(ele.id+'_content');
if (!dom) {
dom = document.createElement('div');
dom.id = ele.id+'_content';
dom.className = Util.hasClass(ele, this.frameClass) ? this.contentClass+' cl '+ele.className.substr(ele.className.lastIndexOf(' ')+1) : this.contentClass+' cl';
}
var frame = this.getObjByName(ele.id);
if (frame) {
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) dom.appendChild($(i));
}
} else {
var children = ele.childNodes;
var arrDom = [];
for (var i in children) {
if (typeof children[i] != 'object') continue;
if (Util.hasClass(children[i],this.moveableColumn) || Util.hasClass(children[i],this.tabContentClass)) {
arrDom.push(children[i]);
}
}
var len = arrDom.length;
for (var i = 0; i < len; i++) {
dom.appendChild(arrDom[i]);
}
}
$(tab.id+'_content').appendChild(dom);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) $(tab.id+'_content').appendChild($(ele.id+'_content'));
}
},
_popTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
Util.removeClass(ele, this.tabActivityClass);
var eleContent = $(ele.id+'_content');
if (!eleContent) return false;
var children = eleContent.childNodes;
var arrEle = [];
for (var i in children) {
if (typeof children[i] == 'object') arrEle.push(children[i]);
}
var len = arrEle.length;
for (var i = 0; i < len; i++) {
ele.appendChild(arrEle[i]);
}
children = '';
$(tab.id+'_content').removeChild(eleContent);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) Util.show($(ele.id+'_content'));
if ($(ele.id+'_content')) ele.appendChild($(ele.id+'_content'));
}
},
_initTabActivity : function (ele) {
if (!Util.hasClass(ele,this.tabClass)) return false;
var tabs = $(ele.id+'_title').childNodes;
var arrTab = [];
for (var i in tabs) {
if (typeof tabs[i] != 'object') continue;
var tabId = tabs[i].id;
if (Util.hasClass(tabs[i],this.frameClass) || Util.hasClass(tabs[i],this.tabClass)) {
if (!this._replaceFlag) this._replaceFrameColumn(tabs[i]);
if (!$(tabId + '_content')) {
var arrColumn = [];
for (var j in tabs[i].childNodes) {
if (Util.hasClass(tabs[i].childNodes[j], this.moveableColumn)) arrColumn.push(tabs[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId + '_content';
frameContent.className = Util.hasClass(tabs[i], this.frameClass) ? this.contentClass+' cl '+tabs[i].className.substr(tabs[i].className.lastIndexOf(' ')+1) : this.contentClass+' cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
}
arrTab.push(tabs[i]);
} else if (Util.hasClass(tabs[i],this.blockClass)) {
var frameContent = $(tabId+'_content');
if (frameContent) {
frameContent = Util.hasClass(frameContent.parentNode,this.blockClass) ? frameContent : '';
} else {
frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
}
arrTab.push(tabs[i]);
}
if (frameContent) $(ele.id + '_content').appendChild(frameContent);
}
var len = arrTab.length;
for (var i = 0; i < len; i++) {
Util[i > 0 ? 'hide' : 'show']($(arrTab[i].id+'_content'));
}
},
dragEnd : function (e) {
e = Util.event(e);
if(!this.dragObj) {return false;}
document.onscroll = function(){};
window.onscroll = function(){};
document.onmousemove = function(e){};
document.onmouseup = '';
if (this.tmpBoxElement.parentNode) {
if (this.tmpBoxElement.parentNode == document.body) {
document.body.removeChild(this.tmpBoxElement);
document.body.removeChild(this.dragObj);
this.fn = '';
} else {
Util.removeClass(this.dragObj,this.moving);
this.dragObj.style.display = 'none';
this.dragObj.style.width = '' ;
this.dragObj.style.top = '';
this.dragObj.style.left = '';
this.dragObj.style.zIndex = '';
this.dragObj.style.position = 'relative';
this.dragObj.style.backgroundColor = '';
this.isDragging = false ;
this.tmpBoxElement.parentNode.replaceChild(this.dragObj, this.tmpBoxElement);
Util.fadeIn(this.dragObj);
this.tmpBoxElement='';
this._setCssPosition(this.dragObjFrame, 'relative');
this.doEndDrag();
this.initPosition();
if (!(this.dargRelative.up == this.dragObj.previousSibling && this.dargRelative.down == this.dragObj.nextSibling)) {
this.setClose();
}
this.dragObjFrame = this.overObjFrame = null;
}
}
this.newFlag = false;
if (typeof this.fn == 'function') {this.fn();}
},
doEndDrag : function () {
if (!Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
this._pushTabContent(this.overObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && !Util.hasClass(this.overObjFrame, this.tabClass)) {
this._popTabContent(this.dragObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
if (this.dragObjFrame != this.overObjFrame) {
this._popTabContent(this.dragObjFrame, this.dragObj);
this._pushTabContent(this.overObjFrame, this.dragObj);
}
} else {
}
},
_replaceFrameColumn : function (ele,flag) {
var children = ele.childNodes;
var fcn = ele.className.match(/(frame-[\w-]*)/);
if (!fcn) return false;
var frameClassName = fcn[1];
for (var i in children) {
if (Util.hasClass(children[i], this.moveableColumn)) {
var className = children[i].className;
className = className.replace(' col-l', ' '+frameClassName+'-l');
className = className.replace(' col-r', ' '+frameClassName+'-r');
className = className.replace(' col-c', ' '+frameClassName+'-c');
className = className.replace(' mn', ' '+frameClassName+'-l');
className = className.replace(' sd', ' '+frameClassName+'-r');
children[i].className = className;
}
}
},
stopCmd : function () {
this.rein.length > 0 ? this.rein.pop()() : '';
},
setClose : function () {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
},
clearClose : function () {
this.isChange = false;
window.onbeforeunload = function () {};
},
_getMoveableArea : function (ele) {
ele = ele ? ele : document.body;
this.moveableArea = $C(this.areaClass, ele, 'div');
},
initMoveableArea : function () {
var _method = this;
this._getMoveableArea();
var len = this.moveableArea.length;
for (var i = 0; i < len; i++) {
var el = this.moveableArea[i];
if (el == null || typeof el == 'undefined') return false;
el.ondragstart = function (e) {return false;};
el.onmouseover = function (e) {Drag.prototype.initDragObj.call(_method, e);};
el.onmousedown = function (e) {Drag.prototype.dragStart.call(_method, e);};
el.onmouseup = function (e) {Drag.prototype.dragEnd.call(_method, e);};
el.onclick = function (e) {e = Util.event(e);e.preventDefault();};
}
if ($('contentframe')) $('contentframe').ondragstart = function (e) {return false;};
},
disableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = true;
}
},
enableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = false;
}
},
init : function (sampleMode) {
this.initCommon();
this.setSampleMode(sampleMode);
if(!this.sampleMode) {
this.initAdvanced();
} else {
this.initSample();
}
return true;
},
initAdvanced : function () {
this.initMoveableArea();
this.initPosition();
this.setDefalutMenu();
this.enableAdvancedStyleSheet();
this.showControlPanel();
this.initTips();
if(this.goonDIY) this.goonDIY();
this.openfn();
},
openfn : function () {
var openfn = loadUserdata('openfn');
if(openfn) {
if(typeof openfn == 'function') {
openfn();
} else {
eval(openfn);
}
saveUserdata('openfn', '');
}
},
initCommon : function () {
this.advancedStyleSheet = $('diy_common');
this.menu = [];
},
initSample : function () {
this._getMoveableArea();
this.initPosition();
this.sampleBlocks = $C(this.blockClass);
this.initSampleBlocks();
this.setSampleMenu();
this.disableAdvancedStyleSheet();
this.hideControlPanel();
},
initSampleBlocks : function () {
if(this.sampleBlocks) {
for(var i = 0; i < this.sampleBlocks.length; i++){
this.checkEdit(this.sampleBlocks[i]);
}
}
},
setSampleMode : function (sampleMode) {
if(loadUserdata('diy_advance_mode')) {
this.sampleMode = '';
} else {
this.sampleMode = sampleMode;
saveUserdata('diy_advance_mode', sampleMode ? '' : '1');
}
},
hideControlPanel : function() {
Util.show('samplepanel');
Util.hide('controlpanel');
Util.hide('diy-tg');
},
showControlPanel : function() {
Util.hide('samplepanel');
Util.show('controlpanel');
Util.show('diy-tg');
},
checkHasFrame : function (obj) {
obj = !obj ? this.data : obj;
for (var i in obj) {
if (obj[i] instanceof Frame && obj[i].className.indexOf('temp') < 0 ) {
return true;
} else if (typeof obj[i] == 'object') {
if (this.checkHasFrame(obj[i])) return true;
}
}
return false;
},
deleteFrame : function (name) {
if (typeof name == 'string') {
if (typeof window['c'+name+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name+'_frame'];
} else {
for(var i = 0,L = name.length;i < L;i++) {
if (typeof window['c'+name[i]+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name[i]+'_frame'];
}
}
},
saveViewTip : function (tipname) {
if(tipname) {
saveUserdata(tipname, '1');
Util.hide(tipname);
}
doane();
},
initTips : function () {
var tips = ['diy_backup_tip'];
for(var i = 0; i < tips.length; i++) {
if(tips[i] && !loadUserdata(tips[i])) {
Util.show(tips[i]);
}
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
DIY = function() {
this.frames = [];
this.isChange = false;
this.spacecss = [];
this.style = 't1';
this.currentDiy = 'body';
this.opSet = [];
this.opPointer = 0;
this.backFlag = false;
this.styleSheet = {} ;
this.scrollHeight = 0 ;
};
DIY.prototype = {
init : function (mod) {
drag.init(mod);
this.style = document.diyform.style.value;
if (this.style == '') {
var reg = RegExp('topic\(.*)\/style\.css');
var href = $('style_css') ? $('style_css').href : '';
var arr = reg.exec(href);
this.style = arr && arr.length > 1 ? arr[1] : '';
}
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
},
initStyleSheet : function () {
var all = document.styleSheets;
for (var i=0;i<all.length;i++) {
var ownerNode = all[i].ownerNode || all[i].owningElement;
if (ownerNode.id == 'diy_style') {
this.styleSheet = new styleCss(i);
return true;
}
}
},
initDiyStyle : function (css) {
var allCssText = css || $('diy_style').innerHTML;
allCssText = allCssText ? allCssText.replace(/\n|\r|\t| /g,'') : '';
var random = Math.random(), rules = '';
var reg = new RegExp('(.*?) ?\{(.*?)\}','g');
while((rules = reg.exec(allCssText))) {
var selector = this.checkSelector(rules[1]);
var cssText = rules[2];
var cssarr = cssText.split(';');
var l = cssarr.length;
for (var k = 0; k < l; k++) {
var attribute = trim(cssarr[k].substr(0, cssarr[k].indexOf(':')).toLowerCase());
var value = cssarr[k].substr(cssarr[k].indexOf(':')+1).toLowerCase();
if (!attribute || !value) continue;
if (!this.spacecss[selector]) this.spacecss[selector] = [];
this.spacecss[selector][attribute] = value;
if (css) this.setStyle(selector, attribute, value, random);
}
}
},
checkSelector : function (selector) {
var s = selector.toLowerCase();
if (s.toLowerCase().indexOf('body') > -1) {
var body = BROWSER.ie ? 'BODY' : 'body';
selector = selector.replace(/body/i,body);
}
if (s.indexOf(' a') > -1) {
selector = BROWSER.ie ? selector.replace(/ [aA]/,' A') : selector.replace(/ [aA]/,' a');
}
return selector;
},
initPalette : function (id) {
var bgcolor = '',selector = '',bgimg = '',bgrepeat = '', bgposition = '', bgattachment = '', bgfontColor = '', bglinkColor = '', i = 0;
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
var attachment = ['scroll','fixed'];
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
var position_ = ['0% 0%','50% 0%','100% 0%','0% 50%','50% 50%','100% 50%','0% 100%','50% 100%','100% 100%'];
selector = this.getSelector(id);
bgcolor = Util.formatColor(this.styleSheet.getRule(selector,'backgroundColor'));
bgimg = this.styleSheet.getRule(selector,'backgroundImage');
bgrepeat = this.styleSheet.getRule(selector,'backgroundRepeat');
bgposition = this.styleSheet.getRule(selector,'backgroundPosition');
bgattachment = this.styleSheet.getRule(selector,'backgroundAttachment');
bgfontColor = Util.formatColor(this.styleSheet.getRule(selector,'color'));
bglinkColor = Util.formatColor(this.styleSheet.getRule(this.getSelector(selector+' a'),'color'));
var selectedIndex = 0;
for (i=0;i<repeat.length;i++) {
if (bgrepeat == repeat[i]) selectedIndex= i;
}
$('repeat_mode').selectedIndex = selectedIndex;
for (i=0;i<attachment.length;i++) {
$('rabga'+i).checked = (bgattachment == attachment[i] ? true : false);
}
var flag = '';
for (i=0;i<position.length;i++) {
var className = bgposition == position[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
flag = flag ? flag : className;
}
if (flag != 'red') {
for (i=0;i<position_.length;i++) {
className = bgposition == position_[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
}
}
$('colorValue').value = bgcolor;
if ($('cbpb')) $('cbpb').style.backgroundColor = bgcolor;
$('textColorValue').value = bgfontColor;
if ($('ctpb')) $('ctpb').style.backgroundColor = bgfontColor;
$('linkColorValue').value = bglinkColor;
if ($('clpb')) $('clpb').style.backgroundColor = bglinkColor;
Util.show($('currentimgdiv'));
Util.hide($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = 'disabled';
bgimg = bgimg != '' && bgimg != 'none' ? bgimg.replace(/url\(['|"]{0,1}/,'').replace(/['|"]{0,1}\)/,'') : 'static/image/common/nophotosmall.gif';
$('currentimg').src = bgimg;
},
changeBgImgDiv : function () {
Util.hide($('currentimgdiv'));
Util.show($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = '';
},
getSpacecssStr : function() {
var css = '';
var selectors = ['body', '#hd','#ct', 'BODY'];
for (var i in this.spacecss) {
var name = i.split(' ')[0];
if(selectors.indexOf(name) == -1 && !drag.getObjByName(name.substr(1))) {
for(var k in this.spacecss) {
if (k.indexOf(i) > -1) {
this.spacecss[k] = [];
}
}
continue;
}
var rule = this.spacecss[i];
if (typeof rule == "function") continue;
var one = '';
rule = this.formatCssRule(rule);
for (var j in rule) {
var content = this.spacecss[i][j];
if (content && typeof content == "string" && content.length > 0) {
content = this.trimCssImportant(content);
content = content ? content + ' !important;' : ';';
one += j + ":" + content;
}
}
if (one == '') continue;
css += i + " {" + one + "}";
}
return css;
},
formatCssRule : function (rule) {
var arr = ['top', 'right', 'bottom', 'left'], i = 0;
if (typeof rule['margin-top'] != 'undefined') {
var margin = rule['margin-bottom'];
if (margin && margin == rule['margin-top'] && margin == rule['margin-right'] && margin == rule['margin-left']) {
rule['margin'] = margin;
for(i=0;i<arr.length;i++) {
delete rule['margin-'+arr[i]];
}
} else {
delete rule['margin'];
}
}
var border = '', borderb = '', borderr = '', borderl = '';
if (typeof rule['border-top-color'] != 'undefined' || typeof rule['border-top-width'] != 'undefined' || typeof rule['border-top-style'] != 'undefined') {
var format = function (css) {
css = css.join(' ').replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'');
return css ? css + ' !important' : '';
};
border = format([rule['border-top-color'], rule['border-top-width'], rule['border-top-style']]);
borderr = format([rule['border-right-color'], rule['border-right-width'], rule['border-right-style']]);
borderb = format([rule['border-bottom-color'], rule['border-bottom-width'], rule['border-bottom-style']]);
borderl = format([rule['border-left-color'], rule['border-left-width'], rule['border-left-style']]);
} else if (typeof rule['border-top'] != 'undefined') {
border = rule['border-top'];borderr = rule['border-right'];borderb = rule['border-bottom'];borderl = rule['border-left'];
}
if (border) {
if (border == borderb && border == borderr && border == borderl) {
rule['border'] = border;
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]];
}
} else {
rule['border-top'] = border;rule['border-right'] = borderr;rule['border-bottom'] = borderb;rule['border-left'] = borderl;
delete rule['border'];
}
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]+'-color'];delete rule['border-'+arr[i]+'-width'];delete rule['border-'+arr[i]+'-style'];
}
}
return rule;
},
changeLayout : function (newLayout) {
if (this.currentLayout == newLayout) return false;
var data = $('layout'+newLayout).getAttribute('data');
var dataArr = data.split(' ');
var currentLayoutLength = this.currentLayout.length;
var newLayoutLength = newLayout.length;
if (newLayoutLength == currentLayoutLength){
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
if (typeof(dataArr[2]) != 'undefined') $('frame1_right').style.width = dataArr[2]+'px';
} else if (newLayoutLength > currentLayoutLength) {
var block = this.getRandomBlockName();
var dom = document.createElement('div');
dom.id = 'frame1_right';
dom.className = drag.moveableColumn + ' z';
dom.appendChild($(block));
$('frame1').appendChild(dom);
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
dom.style.width = dataArr[2]+'px';
} else if (newLayoutLength < currentLayoutLength) {
var _length = drag.data['diypage'][0]['columns']['frame1_right']['children'].length;
var tobj = $('frame1_center_temp');
for (var i = 0; i < _length; i++) {
var name = drag.data['diypage'][0]['columns']['frame1_right']['children'][i].name;
if (name.indexOf('temp') < 0) $('frame1_center').insertBefore($(name),tobj);
}
$('frame1').removeChild($('frame1_right'));
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
}
var className = $('layout'+this.currentLayout).className;
$('layout'+this.currentLayout).className = '';
$('layout'+newLayout).className = className;
this.currentLayout = newLayout;
drag.initPosition();
drag.setClose();
},
getRandomBlockName : function () {
var left = drag.data['diypage'][0]['columns']['frame1_left']['children'];
if (left.length > 2) {
var block = left[0];
} else {
var block = drag.data['diypage'][0]['columns']['frame1_center']['children'][0];
}
return block.name;
},
changeStyle : function (t) {
if (t == '') return false;
$('style_css').href=STATICURL+t+"/style.css";
if (!this.backFlag) {
var oldData = [this.style];
var newData = [t];
var random = Math.random();
this.addOpRecord ('this.changeStyle', newData, oldData, random);
}
var arr = t.split("/");
this.style = arr[arr.length-1];
drag.setClose();
},
setCurrentDiy : function (type) {
if (type) {
$('diy_tag_'+this.currentDiy).className = '';
this.currentDiy = type;
$('diy_tag_'+this.currentDiy).className = 'activity';
this.initPalette(this.currentDiy);
}
},
hideBg : function () {
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', '', random);
this.setStyle(this.currentDiy, 'background-color', '', random);
if (this.currentDiy == 'hd') this.setStyle(this.currentDiy, 'height', '', random);
this.initPalette(this.currentDiy);
},
toggleHeader : function () {
var random = Math.random();
if ($('header_hide_cb').checked) {
this.setStyle('#hd', 'height', '260px', random);
this.setStyle('#hd', 'background-image', 'none', random);
this.setStyle('#hd', 'border-width', '0px', random);
} else {
this.setStyle('#hd', 'height', '', random);
this.setStyle('#hd', 'background-image', '', random);
this.setStyle('#hd', 'border-width', '', random);
}
},
setBgImage : function (value) {
var path = typeof value == "string" ? value : value.src;
if (path.indexOf('.thumb') > 0) {
path = path.substring(0,path.indexOf('.thumb'));
}
if (path == '' || path == 'undefined') return false;
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', Util.url(path), random);
this.setStyle(this.currentDiy, 'background-repeat', 'repeat', random);
if (this.currentDiy == 'hd') {
var _method = this;
var img = new Image();
img.onload = function () {
if (parseInt(img.height) < 140) {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'background-repeat', 'repeat', random);
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', '', random);
} else {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', img.height+"px", random);
}
};
img.src = path;
}
},
setBgRepeat : function (value) {
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
if (typeof repeat[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-repeat', repeat[value]);
},
setBgAttachment : function (value) {
var attachment = ['scroll','fixed'];
if (typeof attachment[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-attachment', attachment[value]);
},
setBgColor : function (color) {
this.setStyle(this.currentDiy, 'background-color', color);
},
setTextColor : function (color) {
this.setStyle(this.currentDiy, 'color', color);
},
setLinkColor : function (color) {
this.setStyle(this.currentDiy + ' a', 'color', color);
},
setBgPosition : function (id) {
var td = $(id);
var i = id.substr(id.length-1);
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
td.className = 'red';
for (var j=0;j<9;j++) {
if (i != j) {
$('bgimgposition'+j).className = '';
}
}
this.setStyle(this.currentDiy, 'background-position', position[i]);
},
getSelector : function (currentDiv) {
var arr = currentDiv.split(' ');
currentDiv = arr[0];
var link = '';
if (arr.length > 1) {
link = (arr[arr.length-1].toLowerCase() == 'a') ? link = ' '+arr.pop() : '';
currentDiv = arr.join(' ');
}
var selector = '';
switch(currentDiv) {
case 'blocktitle' :
selector = '#ct .move-span .blocktitle';
break;
case 'body' :
case 'BODY' :
selector = BROWSER.ie ? 'BODY' : 'body';
break;
default :
selector = currentDiv.indexOf("#")>-1 ? currentDiv : "#"+currentDiv;
}
var rega = BROWSER.ie ? ' A' : ' a';
selector = (selector+link).replace(/ a/i,rega);
return selector;
},
setStyle : function (currentDiv, property, value, random, num){
property = trim(property).toLowerCase();
var propertyJs = property.property2js();
if (typeof value == 'undefined') value = '';
var selector = this.getSelector(currentDiv);
if (!this.backFlag) {
var rule = this.styleSheet.getRule(selector,propertyJs);
rule = rule.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
var oldData = [currentDiv, property, rule];
var newData = [currentDiv, property, value];
if (typeof random == 'undefined') random = Math.random();
this.addOpRecord ('this.setStyle', newData, oldData, random);
}
value = this.trimCssImportant(value);
value = value ? value + ' !important' : '';
var pvalue = value ? property+':'+value : '';
this.styleSheet.addRule(selector,pvalue,num,property);
Util.recolored();
if (typeof this.spacecss[selector] == 'undefined') {
this.spacecss[selector] = [];
}
this.spacecss[selector][property] = value;
drag.setClose();
},
trimCssImportant : function (value) {
if (value instanceof Array) value = value.join(' ');
return value ? value.replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'') : '';
},
removeCssSelector : function (selector) {
for (var i in this.spacecss) {
if (typeof this.spacecss[i] == "function") continue;
if (i.indexOf(selector) > -1) {
this.styleSheet.removeRule(i);
this.spacecss[i] = [];
}
}
},
undo : function () {
if (this.opSet.length == 0) return false;
var oldData = '';
if (this.opPointer <= 0) {return '';}
var step = this.opSet[--this.opPointer];
var random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
oldData = typeof step['oldData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+oldData+')');
this.backFlag = false;
}
} else {
oldData = typeof step['oldData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+oldData+')');
this.backFlag = false;
}
$('button_redo').className = '';
if (this.opPointer == 0) {
$('button_undo').className = 'unusable';
drag.isChange = false;
drag.clearClose();
return '';
} else if (random == this.opSet[this.opPointer-1]['random']) {
this.undo();
return '';
} else {
return '';
}
},
redo : function () {
if (this.opSet.length == 0) return false;
var newData = '',random = '';
if (this.opPointer >= this.opSet.length) return '';
var step = this.opSet[this.opPointer++];
random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
newData = typeof step['newData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+newData+')');
this.backFlag = false;
}
}else {
newData = typeof step['newData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+newData+')');
this.backFlag = false;
}
$('button_undo').className = '';
if (this.opPointer == this.opSet.length) {
$('button_redo').className = 'unusable';
return '';
} else if(random == this.opSet[this.opPointer]['random']){
this.redo();
}
},
addOpRecord : function (cmd, newData, oldData, random) {
if (this.opPointer == 0) this.opSet = [];
this.opSet[this.opPointer++] = {'cmd':cmd, 'newData':newData, 'oldData':oldData, 'random':random};
$('button_undo').className = '';
$('button_redo').className = 'unusable';
Util.show('recover_button');
},
recoverStyle : function () {
var random = Math.random();
for (var selector in this.spacecss){
var style = this.spacecss[selector];
if (typeof style == "function") {continue;}
for (var attribute in style) {
if (typeof style[attribute] == "function") {continue;}
this.setStyle(selector,attribute,'',random);
}
}
Util.hide('recover_button');
drag.setClose();
this.initPalette(this.currentDiy);
},
uploadSubmit : function (){
if (document.uploadpic.attach.value.length<3) {
alert('请选择您要上传的图片');
return false;
}
if (document.uploadpic.albumid != null) document.uploadpic.albumid.value = $('selectalbum').value;
return true;
},
save : function () {
return false;
},
cancel : function () {
var flag = false;
if (this.isChange) {
flag = confirm(this.cancelConfirm ? this.cancelConfirm : '退出将不会保存您刚才的设置。是否确认退出?');
}
if (!this.isChange || flag) {
location.href = location.href.replace(/[\?|\&]diy\=yes/g,'');
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_drag.js 23838 2011-08-11 06:51:58Z monkey $
*/
var Drags = [];
var nDrags = 1;
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var dragHelper = null;
var tempDiv = null;
var rootParent = null;
var rootSibling = null;
var D1Target = null;
Number.prototype.NaN0=function(){return isNaN(this)?0:this;};
function CreateDragContainer(){
var cDrag = DragDrops.length;
DragDrops[cDrag] = [];
for(var i=0; i<arguments.length; i++){
var cObj = arguments[i];
DragDrops[cDrag].push(cObj);
cObj.setAttribute('DropObj', cDrag);
for(var j=0; j<cObj.childNodes.length; j++){
if(cObj.childNodes[j].nodeName=='#text') continue;
cObj.childNodes[j].setAttribute('DragObj', cDrag);
}
}
}
function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
return {x:left, y:top};
}
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
function writeHistory(object, message){
if(!object || !object.parentNode || typeof object.parentNode.getAttribute == 'unknown' || !object.parentNode.getAttribute) return;
var historyDiv = object.parentNode.getAttribute('history');
if(historyDiv){
historyDiv = document.getElementById(historyDiv);
historyDiv.appendChild(document.createTextNode(object.id+': '+message));
historyDiv.appendChild(document.createElement('BR'));
historyDiv.scrollTop += 50;
}
}
function getMouseOffset(target, ev){
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
function mouseMove(ev){
ev = ev || window.event;
var target = ev.target || ev.srcElement;
var mousePos = mouseCoords(ev);
if(Drags[0]){
if(lastTarget && (target!==lastTarget)){
writeHistory(lastTarget, 'Mouse Out Fired');
var origClass = lastTarget.getAttribute('origClass');
if(origClass) lastTarget.className = origClass;
}
var dragObj = target.getAttribute('DragObj');
if(dragObj!=null){
if(target!=lastTarget){
writeHistory(target, 'Mouse Over Fired');
var oClass = target.getAttribute('overClass');
if(oClass){
target.setAttribute('origClass', target.className);
target.className = oClass;
}
}
if(iMouseDown && !lMouseState){
writeHistory(target, 'Start Dragging');
curTarget = target;
rootParent = curTarget.parentNode;
rootSibling = curTarget.nextSibling;
mouseOffset = getMouseOffset(target, ev);
for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
dragHelper.appendChild(curTarget.cloneNode(true));
dragHelper.style.display = 'block';
var dragClass = curTarget.getAttribute('dragClass');
if(dragClass){
dragHelper.firstChild.className = dragClass;
}
dragHelper.firstChild.removeAttribute('DragObj');
var dragConts = DragDrops[dragObj];
curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));
curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
curTarget.style.display = 'none';
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
var pos = getPosition(dragConts[i]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
for(var j=0; j<dragConts[i].childNodes.length; j++){
with(dragConts[i].childNodes[j]){
if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;
var pos = getPosition(dragConts[i].childNodes[j]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
}
}
}
}
if(curTarget){
dragHelper.style.top = (mousePos.y - mouseOffset.y)+"px";
dragHelper.style.left = (mousePos.x - mouseOffset.x)+"px";
var dragConts = DragDrops[curTarget.getAttribute('DragObj')];
var activeCont = null;
var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
if((parseInt(getAttribute('startLeft')) < xPos) &&
(parseInt(getAttribute('startTop')) < yPos) &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
activeCont = dragConts[i];
break;
}
}
}
if(activeCont){
if(activeCont!=curTarget.parentNode){
writeHistory(curTarget, 'Moved into '+activeCont.id);
}
var beforeNode = null;
for(var i=activeCont.childNodes.length-1; i>=0; i--){
with(activeCont.childNodes[i]){
if(nodeName=='#text') continue;
if(curTarget != activeCont.childNodes[i] &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
beforeNode = activeCont.childNodes[i];
}
}
}
if(beforeNode){
if(beforeNode!=curTarget.nextSibling){
writeHistory(curTarget, 'Inserted Before '+beforeNode.id);
activeCont.insertBefore(curTarget, beforeNode);
}
} else {
if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
writeHistory(curTarget, 'Inserted at end of '+activeCont.id);
activeCont.appendChild(curTarget);
}
}
setTimeout(function(){
var contPos = getPosition(activeCont);
activeCont.setAttribute('startWidth', parseInt(activeCont.offsetWidth));
activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
activeCont.setAttribute('startLeft', contPos.x);
activeCont.setAttribute('startTop', contPos.y);}, 5);
if(curTarget.style.display!=''){
writeHistory(curTarget, 'Made Visible');
curTarget.style.display = '';
curTarget.style.visibility = 'hidden';
}
} else {
if(curTarget.style.display!='none'){
writeHistory(curTarget, 'Hidden');
curTarget.style.display = 'none';
}
}
}
lMouseState = iMouseDown;
lastTarget = target;
}
if(dragObject){
dragObject.style.position = 'absolute';
dragObject.style.top = mousePos.y - mouseOffset.y;
dragObject.style.left = mousePos.x - mouseOffset.x;
}
lMouseState = iMouseDown;
if(curTarget || dragObject) return false;
}
function mouseUp(ev){
if(Drags[0]){
if(curTarget){
writeHistory(curTarget, 'Mouse Up Fired');
dragHelper.style.display = 'none';
if(curTarget.style.display == 'none'){
if(rootSibling){
rootParent.insertBefore(curTarget, rootSibling);
} else {
rootParent.appendChild(curTarget);
}
}
curTarget.style.display = '';
curTarget.style.visibility = 'visible';
}
curTarget = null;
}
dragObject = null;
iMouseDown = false;
}
function mouseDown(ev){
mousedown(ev);
ev = ev || window.event;
var target = ev.target || ev.srcElement;
iMouseDown = true;
if(Drags[0]){
if(lastTarget){
writeHistory(lastTarget, 'Mouse Down Fired');
}
}
if(target.onmousedown || target.getAttribute('DragObj')){
return false;
}
}
function makeDraggable(item){
if(!item) return;
item.onmousedown = function(ev){
dragObject = this;
mouseOffset = getMouseOffset(this, ev);
return false;
}
}
function init_drag2(){
document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;
Drags[0] = $('Drags0');
if(Drags[0]){
CreateDragContainer($('DragContainer0'));
}
if(Drags[0]){
var cObj = $('applistcontent');
dragHelper = document.createElement('div');
dragHelper.style.cssName = "apps dragable";
dragHelper.style.cssText = 'position:absolute;display:none;width:374px;';
cObj.parentNode.insertBefore(dragHelper, cObj);
}
}
function mousedown(evnt){
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: smilies.js 29684 2012-04-25 04:00:58Z zhangguosheng $
*/
function _smilies_show(id, smcols, seditorkey) {
if(seditorkey && !$(seditorkey + 'sml_menu')) {
var div = document.createElement("div");
div.id = seditorkey + 'sml_menu';
div.style.display = 'none';
div.className = 'sllt';
$('append_parent').appendChild(div);
var div = document.createElement("div");
div.id = id;
div.style.overflow = 'hidden';
$(seditorkey + 'sml_menu').appendChild(div);
}
if(typeof smilies_type == 'undefined') {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
scriptNode.src = 'data/cache/common_smilies_var.js?' + VERHASH;
$('append_parent').appendChild(scriptNode);
if(BROWSER.ie) {
scriptNode.onreadystatechange = function() {
smilies_onload(id, smcols, seditorkey);
};
} else {
scriptNode.onload = function() {
smilies_onload(id, smcols, seditorkey);
};
}
} else {
smilies_onload(id, smcols, seditorkey);
}
}
function smilies_onload(id, smcols, seditorkey) {
seditorkey = !seditorkey ? '' : seditorkey;
smile = getcookie('smile').split('D');
if(typeof smilies_type == 'object') {
if(smile[0] && smilies_array[smile[0]]) {
CURRENTSTYPE = smile[0];
} else {
for(i in smilies_array) {
CURRENTSTYPE = i;break;
}
}
smiliestype = '<div id="'+id+'_tb" class="tb tb_s cl"><ul>';
for(i in smilies_type) {
key = i.substring(1);
if(smilies_type[i][0]) {
smiliestype += '<li ' + (CURRENTSTYPE == key ? 'class="current"' : '') + ' id="'+seditorkey+'stype_'+key+'" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', '+key+', 1, \'' + seditorkey + '\');if(CURRENTSTYPE) {$(\''+seditorkey+'stype_\'+CURRENTSTYPE).className=\'\';}this.className=\'current\';CURRENTSTYPE='+key+';doane(event);"><a href="javascript:;" hidefocus="true">'+smilies_type[i][0]+'</a></li>';
}
}
smiliestype += '</ul></div>';
$(id).innerHTML = smiliestype + '<div id="' + id + '_data"></div><div class="sllt_p" id="' + id + '_page"></div>';
smilies_switch(id, smcols, CURRENTSTYPE, smile[1], seditorkey);
smilies_fastdata = '';
if(seditorkey == 'fastpost' && $('fastsmilies') && smilies_fast) {
var j = 0;
for(i = 0;i < smilies_fast.length; i++) {
if(j == 0) {
smilies_fastdata += '<tr>';
}
j = ++j > 3 ? 0 : j;
s = smilies_array[smilies_fast[i][0]][smilies_fast[i][1]][smilies_fast[i][2]];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + smilies_fast[i][0]][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smilies_fastdata += s ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'fastsmiliesdiv\', this, ' + s[5] + ')" onmouseout="$(\'smilies_preview\').style.display = \'none\'" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
}
$('fastsmilies').innerHTML = '<table cellspacing="0" cellpadding="0"><tr>' + smilies_fastdata + '</tr></table>';
}
}
}
function smilies_switch(id, smcols, type, page, seditorkey) {
page = page ? page : 1;
if(!smilies_array[type] || !smilies_array[type][page]) return;
setcookie('smile', type + 'D' + page, 31536000);
smiliesdata = '<table id="' + id + '_table" cellpadding="0" cellspacing="0"><tr>';
j = k = 0;
img = [];
for(var i = 0; i < smilies_array[type][page].length; i++) {
if(j >= smcols) {
smiliesdata += '<tr>';
j = 0;
}
s = smilies_array[type][page][i];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + type][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smiliesdata += s && s[0] ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'' + id + '\', this, ' + s[5] + ')" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
j++;k++;
}
smiliesdata += '</table>';
smiliespage = '';
if(smilies_array[type].length > 2) {
prevpage = ((prevpage = parseInt(page) - 1) < 1) ? smilies_array[type].length - 1 : prevpage;
nextpage = ((nextpage = parseInt(page) + 1) == smilies_array[type].length) ? 1 : nextpage;
smiliespage = '<div class="z"><a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + prevpage + ', \'' + seditorkey + '\');doane(event);">上页</a>' +
'<a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + nextpage + ', \'' + seditorkey + '\');doane(event);">下页</a></div>' +
page + '/' + (smilies_array[type].length - 1);
}
$(id + '_data').innerHTML = smiliesdata;
$(id + '_page').innerHTML = smiliespage;
$(id + '_tb').style.width = smcols*(16+parseInt(s[3])) + 'px';
}
function smilies_preview(seditorkey, id, obj, w) {
var menu = $('smilies_preview');
if(!menu) {
menu = document.createElement('div');
menu.id = 'smilies_preview';
menu.className = 'sl_pv';
menu.style.display = 'none';
$('append_parent').appendChild(menu);
}
menu.innerHTML = '<img width="' + w + '" src="' + obj.childNodes[0].src + '" />';
mpos = fetchOffset($(id + '_data'));
spos = fetchOffset(obj);
pos = spos['left'] >= mpos['left'] + $(id + '_data').offsetWidth / 2 ? '13' : '24';
showMenu({'ctrlid':obj.id,'showid':id + '_data','menuid':menu.id,'pos':pos,'layer':3});
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: register.js 31582 2012-09-11 03:21:49Z zhangjie $
*/
var lastusername = '', lastpassword = '', lastemail = '', lastinvitecode = '', stmp = new Array();
function errormessage(id, msg) {
if($(id)) {
showInputTip();
msg = !msg ? '' : msg;
if($('tip_' + id)) {
if(msg == 'succeed') {
msg = '';
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
$('tip_' + id).parentNode.className += ' p_right';
} else if(msg !== '') {
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
}
}
if($('chk_' + id)) {
$('chk_' + id).innerHTML = msg;
}
$(id).className = $(id).className.replace(/ er/, '');
$(id).className += !msg ? '' : ' er';
}
}
function addFormEvent(formid, focus){
var si = 0;
var formNode = $(formid).getElementsByTagName('input');
for(i = 0;i < formNode.length;i++) {
if(formNode[i].name == '') {
formNode[i].name = formNode[i].id;
stmp[si] = i;
si++;
}
if(formNode[i].type == 'text' || formNode[i].type == 'password'){
formNode[i].onfocus = function(){
showInputTip(!this.id ? this.name : this.id);
}
}
}
if(!si) {
return;
}
formNode[stmp[0]].onblur = function () {
checkusername(formNode[stmp[0]].id);
};
formNode[stmp[1]].onblur = function () {
if(formNode[stmp[1]].value == '') {
var pwmsg = '请填写密码';
if(pwlength > 0) {
pwmsg += ', 最小长度为 '+pwlength+' 个字符';
}
errormessage(formNode[stmp[1]].id, pwmsg);
}else{
errormessage(formNode[stmp[1]].id, 'succeed');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
formNode[stmp[1]].onkeyup = function () {
if(pwlength == 0 || $(formNode[stmp[1]].id).value.length >= pwlength) {
var passlevels = new Array('','弱','中','强');
var passlevel = checkstrongpw(formNode[stmp[1]].id);
errormessage(formNode[stmp[1]].id, '<span class="passlevel passlevel'+passlevel+'">密码强度:'+passlevels[passlevel]+'</span>');
}
};
formNode[stmp[2]].onblur = function () {
if(formNode[stmp[2]].value == '') {
errormessage(formNode[stmp[2]].id, '请再次输入密码');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
addMailEvent(formNode[stmp[3]]);
try {
if(focus) {
$('invitecode').focus();
} else {
formNode[stmp[0]].focus();
}
} catch(e) {}
}
function addMailEvent(mailObj) {
mailObj.onclick = function (event) {
emailMenu(event, mailObj.id);
};
mailObj.onkeyup = function (event) {
emailMenu(event, mailObj.id);
};
mailObj.onkeydown = function (event) {
emailMenuOp(4, event, mailObj.id);
};
mailObj.onblur = function () {
if(mailObj.value == '') {
errormessage(mailObj.id, '请输入邮箱地址');
}
emailMenuOp(3, null, mailObj.id);
};
stmp['email'] = mailObj.id;
}
function checkstrongpw(id) {
var passlevel = 0;
if($(id).value.match(/\d+/g)) {
passlevel ++;
}
if($(id).value.match(/[a-z]+/ig)) {
passlevel ++;
}
if($(id).value.match(/[^a-z0-9]+/ig)) {
passlevel ++;
}
return passlevel;
}
function showInputTip(id) {
var p_tips = $('registerform').getElementsByTagName('i');
for(i = 0;i < p_tips.length;i++){
if(p_tips[i].className == 'p_tip'){
p_tips[i].style.display = 'none';
}
}
if($('tip_' + id)) {
$('tip_' + id).style.display = 'block';
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function trim(str) {
return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1');
}
var emailMenuST = null, emailMenui = 0, emaildomains = ['qq.com', '163.com', 'sina.com', 'sohu.com', 'yahoo.cn', 'gmail.com', 'hotmail.com'];
function emailMenuOp(op, e, id) {
if(op == 3 && BROWSER.ie && BROWSER.ie < 7) {
checkemail(id);
}
if(!$('emailmore_menu')) {
return;
}
if(op == 1) {
$('emailmore_menu').style.display = 'none';
} else if(op == 2) {
showMenu({'ctrlid':'emailmore','pos': '13!'});
} else if(op == 3) {
emailMenuST = setTimeout(function () {
emailMenuOp(1, id);
checkemail(id);
}, 500);
} else if(op == 4) {
e = e ? e : window.event;
var obj = $(id);
if(e.keyCode == 13) {
var v = obj.value.indexOf('@') != -1 ? obj.value.substring(0, obj.value.indexOf('@')) : obj.value;
obj.value = v + '@' + emaildomains[emailMenui];
doane(e);
}
} else if(op == 5) {
var as = $('emailmore_menu').getElementsByTagName('a');
for(i = 0;i < as.length;i++){
as[i].className = '';
}
}
}
function emailMenu(e, id) {
if(BROWSER.ie && BROWSER.ie < 7) {
return;
}
e = e ? e : window.event;
var obj = $(id);
if(obj.value.indexOf('@') != -1) {
$('emailmore_menu').style.display = 'none';
return;
}
var value = e.keyCode;
var v = obj.value;
if(!obj.value.length) {
emailMenuOp(1);
return;
}
if(value == 40) {
emailMenui++;
if(emailMenui >= emaildomains.length) {
emailMenui = 0;
}
} else if(value == 38) {
emailMenui--;
if(emailMenui < 0) {
emailMenui = emaildomains.length - 1;
}
} else if(value == 13) {
$('emailmore_menu').style.display = 'none';
return;
}
if(!$('emailmore_menu')) {
menu = document.createElement('div');
menu.id = 'emailmore_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
menu.setAttribute('disautofocus', true);
$('append_parent').appendChild(menu);
}
var s = '<ul>';
for(var i = 0; i < emaildomains.length; i++) {
s += '<li><a href="javascript:;" onmouseover="emailMenuOp(5)" ' + (emailMenui == i ? 'class="a" ' : '') + 'onclick="$(stmp[\'email\']).value=this.innerHTML;display(\'emailmore_menu\');checkemail(stmp[\'email\']);">' + v + '@' + emaildomains[i] + '</a></li>';
}
s += '</ul>';
$('emailmore_menu').innerHTML = s;
emailMenuOp(2);
}
function checksubmit() {
var p_chks = $('registerform').getElementsByTagName('kbd');
for(i = 0;i < p_chks.length;i++){
if(p_chks[i].className == 'p_chk'){
p_chks[i].innerHTML = '';
}
}
ajaxpost('registerform', 'returnmessage4', 'returnmessage4', 'onerror');
return;
}
function checkusername(id) {
errormessage(id);
var username = trim($(id).value);
if($('tip_' + id).parentNode.className.match(/ p_right/) && (username == '' || username == lastusername)) {
return;
} else {
lastusername = username;
}
if(username.match(/<|"/ig)) {
errormessage(id, '用户名包含敏感字符');
return;
}
var unlen = username.replace(/[^\x00-\xff]/g, "**").length;
if(unlen < 3 || unlen > 15) {
errormessage(id, unlen < 3 ? '用户名不得小于 3 个字符' : '用户名不得超过 15 个字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkusername&username=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(username) : username.replace(/%/g, '%25')), function(s) {
errormessage(id, s);
});
}
function checkpassword(id1, id2) {
if(!$(id1).value && !$(id2).value) {
return;
}
if(pwlength > 0) {
if($(id1).value.length < pwlength) {
errormessage(id1, '密码太短,不得少于 '+pwlength+' 个字符');
return;
}
}
if(strongpw) {
var strongpw_error = false, j = 0;
var strongpw_str = new Array();
for(var i in strongpw) {
if(strongpw[i] === 1 && !$(id1).value.match(/\d+/g)) {
strongpw_error = true;
strongpw_str[j] = '数字';
j++;
}
if(strongpw[i] === 2 && !$(id1).value.match(/[a-z]+/g)) {
strongpw_error = true;
strongpw_str[j] = '小写字母';
j++;
}
if(strongpw[i] === 3 && !$(id1).value.match(/[A-Z]+/g)) {
strongpw_error = true;
strongpw_str[j] = '大写字母';
j++;
}
if(strongpw[i] === 4 && !$(id1).value.match(/[^A-Za-z0-9]+/g)) {
strongpw_error = true;
strongpw_str[j] = '特殊符号';
j++;
}
}
if(strongpw_error) {
errormessage(id1, '密码太弱,密码中必须包含 '+strongpw_str.join(','));
return;
}
}
errormessage(id2);
if($(id1).value != $(id2).value) {
errormessage(id2, '两次输入的密码不一致');
} else {
errormessage(id2, 'succeed');
}
}
function checkemail(id) {
errormessage(id);
var email = trim($(id).value);
if($(id).parentNode.className.match(/ p_right/) && (email == '' || email == lastemail)) {
return;
} else {
lastemail = email;
}
if(email.match(/<|"/ig)) {
errormessage(id, 'Email 包含敏感字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkemail&email=' + email, function(s) {
errormessage(id, s);
});
}
function checkinvite() {
errormessage('invitecode');
var invitecode = trim($('invitecode').value);
if(invitecode == '' || invitecode == lastinvitecode) {
return;
} else {
lastinvitecode = invitecode;
}
if(invitecode.match(/<|"/ig)) {
errormessage('invitecode', '邀请码包含敏感字符');
return;
}
var x = new Ajax();
$('tip_invitecode').parentNode.className = $('tip_invitecode').parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkinvitecode&invitecode=' + invitecode, function(s) {
errormessage('invitecode', s);
});
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: md5.js 29228 2012-03-30 01:46:00Z monkey $
*/
var hexcase = 0;
var chrsz = 8;
function hex_md5(s){
return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}
function core_md5(x, len) {
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
var pwmd5log = new Array();
function pwmd5() {
if(!$(pwmd5.arguments[0]) || $(pwmd5.arguments[0]).value == '') {
return;
}
numargs = pwmd5.arguments.length;
for(var i = 0; i < numargs; i++) {
if(!pwmd5log[pwmd5.arguments[i]] || $(pwmd5.arguments[i]).value.length != 32) {
pwmd5log[pwmd5.arguments[i]] = $(pwmd5.arguments[i]).value = hex_md5($(pwmd5.arguments[i]).value);
}
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 31416 2012-08-27 07:50:15Z zhangguosheng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('您确认要把此主题从热点主题中移除么?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['展开', '收起'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = '抱歉,您尚未输入标题或内容';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = '您的标题超过 80 个字符的限制';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = '您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(theform.message.value) + ' ' + '字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('没有可以恢复的数据!', 'info');
}
return;
}
if(!quiet && !confirm('此操作将覆盖当前帖子内容,确定要恢复数据吗?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">有新回复的主题,点击查看', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: calendar.js 27363 2012-01-18 08:46:14Z monkey $
*/
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var halfhour = false;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:100000;" onclick="doane(event)">';
s += '<div style="width: 210px;"><table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;">';
s += '<tr align="center" id="calendar_week"><td onclick="refreshcalendar(yy, mm-1)" title="上一月" style="cursor: pointer;"><a href="javascript:;">«</a></td><td colspan="5" style="text-align: center"><a href="javascript:;" onclick="showdiv(\'year\');doane(event)" class="dropmenu" title="点击选择年份" id="year"></a> - <a id="month" class="dropmenu" title="点击选择月份" href="javascript:;" onclick="showdiv(\'month\');doane(event)"></a></td><td onclick="refreshcalendar(yy, mm+1)" title="下一月" style="cursor: pointer;"><a href="javascript:;">»</a></td></tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute" class="pns"><td colspan="4" align="left"><input type="text" size="1" value="" id="hour" class="px vm" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'>点';
s += '<span id="fullhourselector"><input type="text" size="1" value="" id="minute" class="px vm" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'>分</span>';
s += '<span id="halfhourselector"><select id="minutehalfhourly" onchange=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'><option value="00">00</option><option value="30">30</option></select>分</span>';
s += '</td><td align="right" colspan="3"><button class="pn" onclick="confirmcalendar();"><em>确定</em></button></td></tr>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="doane(event)" style="display: none;z-index:100001;"><div class="col">';
for(var k = 2020; k >= 1931; k--) {
s += k != 2020 && k % 10 == 0 ? '</div><div class="col">' : '';
s += '<a href="javascript:;" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="calendar_today"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="doane(event)" style="display: none;z-index:100001;">';
for(var k = 1; k <= 12; k++) {
s += '<a href="javascript:;" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'"><span' + (today.getMonth()+1 == k ? ' class="calendar_today"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
if(BROWSER.ie && BROWSER.ie < 7) {
s += '<iframe id="calendariframe" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_year" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_month" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
}
var div = document.createElement('div');
div.innerHTML = s;
$('append_parent').appendChild(div);
document.onclick = function(event) {
closecalendar(event);
};
$('calendar').onclick = function(event) {
doane(event);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
};
}
function closecalendar(event) {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
if(!addtime) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
}
}
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($((halfhour) ? 'minutehalfhourly' : 'minute').value) : '');
}
function confirmcalendar() {
if(addtime && controlid.value === '') {
controlid.value = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + zerofill($('hour').value) + ':' + zerofill($((halfhour) ? 'minutehalfhourly' : 'minute').value);
}
closecalendar();
}
function initclosecalendar() {
var e = getEvent();
var aim = e.target || e.srcElement;
while (aim.parentNode != document.body) {
if (aim.parentNode.id == 'append_parent') {
aim.onclick = function () {closecalendar(e);};
}
aim = aim.parentNode;
}
}
function showcalendar(event, controlid1, addtime1, startdate1, enddate1, halfhour1) {
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
halfhour = halfhour1 ? true : false;
var p = fetchOffset(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['left']+'px';
$('calendar').style.top = (p['top'] + 20)+'px';
doane(event);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = 'calendar_default';
$('calendar_year_' + today.getFullYear()).className = 'calendar_today';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = 'calendar_default';
$('calendar_month_' + (today.getMonth() + 1)).className = 'calendar_today';
}
$('calendar_year_' + currday.getFullYear()).className = 'calendar_checked';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'calendar_checked';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
if(halfhour) {
$('halfhourselector').style.display = '';
$('fullhourselector').style.display = 'none';
} else {
$('halfhourselector').style.display = 'none';
$('fullhourselector').style.display = '';
}
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.top = $('calendar').style.top;
$('calendariframe').style.left = $('calendar').style.left;
$('calendariframe').style.width = $('calendar').offsetWidth;
$('calendariframe').style.height = $('calendar').offsetHeight;
$('calendariframe').style.display = 'block';
}
initclosecalendar();
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.style.cursor = 'pointer';
dd.onclick = function () {
settime(this.childNodes[0].innerHTML);
doane();
};
dd.innerHTML = '<a href="javascript:;">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'calendar_expire';
} else {
dd.className = 'calendar_default';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'calendar_today';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'calendar_checked';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = fetchOffset($(id));
$('calendar_' + id).style.left = p['left']+'px';
$('calendar_' + id).style.top = (p['top'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_' + id).style.top = $('calendar_' + id).style.top;
$('calendariframe_' + id).style.left = $('calendar_' + id).style.left;
$('calendariframe_' + id).style.width = $('calendar_' + id).offsetWidth;
$('calendariframe_' + id ).style.height = $('calendar_' + id).offsetHeight;
$('calendariframe_' + id).style.display = 'block';
}
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
if(!BROWSER.other) {
loadcss('forum_calendar');
loadcalendar();
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home.js 32101 2012-11-09 09:39:45Z zhengqingpeng $
*/
var note_step = 0;
var note_oldtitle = document.title;
var note_timer;
function addSort(obj) {
if (obj.value == 'addoption') {
showWindow('addoption', 'home.php?mod=spacecp&ac=blog&op=addoption&handlekey=addoption&oid='+obj.id);
}
}
function addOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
} else {
obj.value=obj.options[0].value;
}
}
function blogAddOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
newOption = newOption.replace(/^\s+|\s+$/g,"");
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
return true;
} else {
alert('分类名不能为空!');
return false;
}
}
function blogCancelAddOption(aid) {
var obj = $(aid);
obj.value=obj.options[0].value;
}
function checkAll(form, name) {
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(name)) {
e.checked = form.elements['chkall'].checked;
}
}
}
function cnCode(str) {
str = str.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
str = str.replace(/\s{2,}/ig, ' ');
return BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(str) : str;
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function resizeImg(id,size) {
var theImages = $(id).getElementsByTagName('img');
for (i=0; i<theImages.length; i++) {
theImages[i].onload = function() {
if (this.width > size) {
this.style.width = size + 'px';
if (this.parentNode.tagName.toLowerCase() != 'a') {
var zoomDiv = document.createElement('div');
this.parentNode.insertBefore(zoomDiv,this);
zoomDiv.appendChild(this);
zoomDiv.style.position = 'relative';
zoomDiv.style.cursor = 'pointer';
this.title = '点击图片,在新窗口显示原始尺寸';
var zoom = document.createElement('img');
zoom.src = 'image/zoom.gif';
zoom.style.position = 'absolute';
zoom.style.marginLeft = size -28 + 'px';
zoom.style.marginTop = '5px';
this.parentNode.insertBefore(zoom,this);
zoomDiv.onmouseover = function() {
zoom.src = 'image/zoom_h.gif';
};
zoomDiv.onmouseout = function() {
zoom.src = 'image/zoom.gif';
};
zoomDiv.onclick = function() {
window.open(this.childNodes[1].src);
};
}
}
}
}
}
function zoomTextarea(id, zoom) {
zoomSize = zoom ? 10 : -10;
obj = $(id);
if(obj.rows + zoomSize > 0 && obj.cols + zoomSize * 3 > 0) {
obj.rows += zoomSize;
obj.cols += zoomSize * 3;
}
}
function ischeck(id, prefix) {
form = document.getElementById(id);
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(prefix) && e.checked) {
if(confirm("您确定要执行本操作吗?")) {
return true;
} else {
return false;
}
}
}
alert('请选择要操作的对象');
return false;
}
function copyRow(tbody) {
var add = false;
var newnode;
if($(tbody).rows.length == 1 && $(tbody).rows[0].style.display == 'none') {
$(tbody).rows[0].style.display = '';
newnode = $(tbody).rows[0];
} else {
newnode = $(tbody).rows[0].cloneNode(true);
add = true;
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
if(add) {
$(tbody).appendChild(newnode);
}
}
function delRow(obj, tbody) {
if($(tbody).rows.length == 1) {
var trobj = obj.parentNode.parentNode;
tags = trobj.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
trobj.style.display='none';
} else {
$(tbody).removeChild(obj.parentNode.parentNode);
}
}
function insertWebImg(obj) {
if(checkImage(obj.value)) {
insertImage(obj.value);
obj.value = 'http://';
} else {
alert('图片地址不正确');
}
}
function checkFocus(target) {
var obj = $(target);
if(!obj.hasfocus) {
obj.focus();
}
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function checkImage(url) {
var re = /^http\:\/\/.{5,200}\.(jpg|gif|png)$/i;
return url.match(re);
}
function quick_validate(obj) {
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s != 'succeed') {
alert(s);
$('seccode').focus();
return false;
} else {
obj.form.submit();
return true;
}
});
} else {
obj.form.submit();
return true;
}
}
function stopMusic(preID, playerID) {
var musicFlash = preID.toString() + '_' + playerID.toString();
if($(musicFlash)) {
$(musicFlash).SetVariable('closePlayer', 1);
}
}
function showFlash(host, flashvar, obj, shareid) {
var flashAddr = {
'youku.com' : 'http://player.youku.com/player.php/sid/FLASHVAR=/v.swf',
'ku6.com' : 'http://player.ku6.com/refer/FLASHVAR/v.swf',
'youtube.com' : 'http://www.youtube.com/v/FLASHVAR',
'5show.com' : 'http://www.5show.com/swf/5show_player.swf?flv_id=FLASHVAR',
'sina.com.cn' : 'http://vhead.blog.sina.com.cn/player/outer_player.swf?vid=FLASHVAR',
'sohu.com' : 'http://v.blog.sohu.com/fo/v4/FLASHVAR',
'mofile.com' : 'http://tv.mofile.com/cn/xplayer.swf?v=FLASHVAR',
'music' : 'FLASHVAR',
'flash' : 'FLASHVAR'
};
var flash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="480" height="400">'
+ '<param name="movie" value="FLASHADDR" />'
+ '<param name="quality" value="high" />'
+ '<param name="bgcolor" value="#FFFFFF" />'
+ '<param name="allowScriptAccess" value="none" />'
+ '<param name="allowNetworking" value="internal" />'
+ '<embed width="480" height="400" menu="false" quality="high" allowScriptAccess="none" allowNetworking="internal" src="FLASHADDR" type="application/x-shockwave-flash" />'
+ '</object>';
var videoFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="450">'
+ '<param value="transparent" name="wmode"/>'
+ '<param value="FLASHADDR" name="movie" />'
+ '<param name="allowScriptAccess" value="none" />'
+ '<param name="allowNetworking" value="none" />'
+ '<embed src="FLASHADDR" wmode="transparent" allowfullscreen="true" type="application/x-shockwave-flash" width="480" height="450" allowScriptAccess="none" allowNetworking="internal"></embed>'
+ '</object>';
var musicFlash = '<object id="audioplayer_SHAREID" height="24" width="290" data="' + STATICURL + 'image/common/player.swf" type="application/x-shockwave-flash">'
+ '<param value="' + STATICURL + 'image/common/player.swf" name="movie"/>'
+ '<param value="autostart=yes&bg=0xCDDFF3&leftbg=0x357DCE&lefticon=0xF2F2F2&rightbg=0xF06A51&rightbghover=0xAF2910&righticon=0xF2F2F2&righticonhover=0xFFFFFF&text=0x357DCE&slider=0x357DCE&track=0xFFFFFF&border=0xFFFFFF&loader=0xAF2910&soundFile=FLASHADDR" name="FlashVars"/>'
+ '<param value="high" name="quality"/>'
+ '<param value="false" name="menu"/>'
+ '<param value="#FFFFFF" name="bgcolor"/>'
+ '</object>';
var musicMedia = '<object height="64" width="290" data="FLASHADDR" type="audio/x-ms-wma">'
+ '<param value="FLASHADDR" name="src"/>'
+ '<param value="1" name="autostart"/>'
+ '<param value="true" name="controller"/>'
+ '</object>';
var flashHtml = videoFlash;
var videoMp3 = true;
if('' == flashvar) {
alert('音乐地址错误,不能为空');
return false;
}
if('music' == host) {
var mp3Reg = new RegExp('.mp3$', 'ig');
var flashReg = new RegExp('.swf$', 'ig');
flashHtml = musicMedia;
videoMp3 = false;
if(mp3Reg.test(flashvar)) {
videoMp3 = true;
flashHtml = musicFlash;
} else if(flashReg.test(flashvar)) {
videoMp3 = true;
flashHtml = flash;
}
}
flashvar = encodeURI(flashvar);
if(flashAddr[host]) {
var flash = flashAddr[host].replace('FLASHVAR', flashvar);
flashHtml = flashHtml.replace(/FLASHADDR/g, flash);
flashHtml = flashHtml.replace(/SHAREID/g, shareid);
}
if(!obj) {
$('flash_div_' + shareid).innerHTML = flashHtml;
return true;
}
if($('flash_div_' + shareid)) {
$('flash_div_' + shareid).style.display = '';
$('flash_hide_' + shareid).style.display = '';
obj.style.display = 'none';
return true;
}
if(flashAddr[host]) {
var flashObj = document.createElement('div');
flashObj.id = 'flash_div_' + shareid;
obj.parentNode.insertBefore(flashObj, obj);
flashObj.innerHTML = flashHtml;
obj.style.display = 'none';
var hideObj = document.createElement('div');
hideObj.id = 'flash_hide_' + shareid;
var nodetxt = document.createTextNode("收起");
hideObj.appendChild(nodetxt);
obj.parentNode.insertBefore(hideObj, obj);
hideObj.style.cursor = 'pointer';
hideObj.onclick = function() {
if(true == videoMp3) {
stopMusic('audioplayer', shareid);
flashObj.parentNode.removeChild(flashObj);
hideObj.parentNode.removeChild(hideObj);
} else {
flashObj.style.display = 'none';
hideObj.style.display = 'none';
}
obj.style.display = '';
};
}
}
function userapp_open() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'fold';
$('a_app_more').innerHTML = '收起';
$('a_app_more').onclick = function() {
userapp_close();
};
});
}
function userapp_close() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&subop=off&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'unfold';
$('a_app_more').innerHTML = '展开';
$('a_app_more').onclick = function() {
userapp_open();
};
});
}
function startMarquee(h, speed, delay, sid) {
var t = null;
var p = false;
var o = $(sid);
o.innerHTML += o.innerHTML;
o.onmouseover = function() {p = true};
o.onmouseout = function() {p = false};
o.scrollTop = 0;
function start() {
t = setInterval(scrolling, speed);
if(!p) {
o.scrollTop += 2;
}
}
function scrolling() {
if(p) return;
if(o.scrollTop % h != 0) {
o.scrollTop += 2;
if(o.scrollTop >= o.scrollHeight/2) o.scrollTop = 0;
} else {
clearInterval(t);
setTimeout(start, delay);
}
}
setTimeout(start, delay);
}
function readfeed(obj, id) {
if(Cookie.get("read_feed_ids")) {
var fcookie = Cookie.get("read_feed_ids");
fcookie = id + ',' + fcookie;
} else {
var fcookie = id;
}
Cookie.set("read_feed_ids", fcookie, 48);
obj.className = 'feedread';
}
function showreward() {
if(Cookie.get('reward_notice_disable')) {
return false;
}
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getreward', function(s){
if(s) {
msgwin(s, 2000);
}
});
}
function msgwin(s, t) {
var msgWinObj = $('msgwin');
if(!msgWinObj) {
var msgWinObj = document.createElement("div");
msgWinObj.id = 'msgwin';
msgWinObj.style.display = 'none';
msgWinObj.style.position = 'absolute';
msgWinObj.style.zIndex = '100000';
$('append_parent').appendChild(msgWinObj);
}
msgWinObj.innerHTML = s;
msgWinObj.style.display = '';
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
msgWinObj.style.opacity = 0;
var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
pbegin = sTop + (document.documentElement.clientHeight / 2);
pend = sTop + (document.documentElement.clientHeight / 5);
setTimeout(function () {showmsgwin(pbegin, pend, 0, t)}, 10);
msgWinObj.style.left = ((document.documentElement.clientWidth - msgWinObj.clientWidth) / 2) + 'px';
msgWinObj.style.top = pbegin + 'px';
}
function showmsgwin(b, e, a, t) {
step = (b - e) / 10;
var msgWinObj = $('msgwin');
newp = (parseInt(msgWinObj.style.top) - step);
if(newp > e) {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + a + ')';
msgWinObj.style.opacity = a / 100;
msgWinObj.style.top = newp + 'px';
setTimeout(function () {showmsgwin(b, e, a += 10, t)}, 10);
} else {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
msgWinObj.style.opacity = 1;
setTimeout('displayOpacity(\'msgwin\', 100)', t);
}
}
function displayOpacity(id, n) {
if(!$(id)) {
return;
}
if(n >= 0) {
n -= 10;
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + n + ')';
$(id).style.opacity = n / 100;
setTimeout('displayOpacity(\'' + id + '\',' + n + ')', 50);
} else {
$(id).style.display = 'none';
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
$(id).style.opacity = 1;
}
}
function urlto(url) {
window.location.href = url;
}
function explode(sep, string) {
return string.split(sep);
}
function selector(pattern, context) {
var re = new RegExp('([a-z0-9]*)([\.#:]*)(.*|$)', 'ig');
var match = re.exec(pattern);
var conditions = cc = [];
if (match[2] == '#') conditions.push(['id', '=', match[3]]);
else if(match[2] == '.') conditions.push(['className', '~=', match[3]]);
else if(match[2] == ':') conditions.push(['type', '=', match[3]]);
var s = match[3].replace(/\[(.*)\]/g,'$1').split('@');
for(var i=0; i<s.length; i++) {
if (cc = /([\w]+)([=^%!$~]+)(.*)$/.exec(s[i]))
conditions.push([cc[1], cc[2], cc[3]]);
}
var list = conditions[0] && conditions[0][0] == 'id' ? [document.getElementById(conditions[0][2])] : (context || document).getElementsByTagName(match[1] || "*");
if(!list || !list.length) return [];
if(conditions) {
var elements = [];
var attrMapping = {'for': 'htmlFor', 'class': 'className'};
for(var i=0; i<list.length; i++) {
var pass = true;
for(var j=0; j<conditions.length; j++) {
var attr = attrMapping[conditions[j][0]] || conditions[j][0];
var val = list[i][attr] || (list[i].getAttribute ? list[i].getAttribute(attr) : '');
var pattern = null;
if(conditions[j][1] == '=') {
pattern = new RegExp('^'+conditions[j][2]+'$', 'i');
} else if(conditions[j][1] == '^=') {
pattern = new RegExp('^' + conditions[j][2], 'i');
} else if(conditions[j][1] == '$=') {
pattern = new RegExp(conditions[j][2] + '$', 'i');
} else if(conditions[j][1] == '%=') {
pattern = new RegExp(conditions[j][2], 'i');
} else if(conditions[j][1] == '~=') {
pattern = new RegExp('(^|[ ])' + conditions[j][2] + '([ ]|$)', 'i');
}
if(pattern && !pattern.test(val)) {
pass = false;
break;
}
}
if(pass) elements.push(list[i]);
}
return elements;
} else {
return list;
}
}
function showBlock(cid, oid) {
if(parseInt(cid)) {
var listObj = $(oid);
var x = new Ajax();
x.get('portal.php?mod=cp&ac=block&operation=getblock&classid='+cid, function(s){
listObj.innerHTML = s;
})
}
}
function resizeTx(obj){
var oid = obj.id + '_limit';
if(!BROWSER.ie) obj.style.height = 0;
obj.style.height = obj.scrollHeight + 'px';
if($(oid)) $(oid).style.display = obj.scrollHeight > 30 ? '':'none';
}
function showFace(showid, target, dropstr) {
if($(showid + '_menu') != null) {
$(showid+'_menu').style.display = '';
} else {
var faceDiv = document.createElement("div");
faceDiv.id = showid+'_menu';
faceDiv.className = 'p_pop facel';
faceDiv.style.position = 'absolute';
faceDiv.style.zIndex = 1001;
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertFace(\''+showid+'\','+i+', \''+ target +'\', \''+dropstr+'\')" style="cursor:pointer; position:relative;" />';
faceul.appendChild(faceli);
}
faceDiv.appendChild(faceul);
$('append_parent').appendChild(faceDiv)
}
setMenuPosition(showid, 0);
doane();
_attachEvent(document.body, 'click', function(){if($(showid+'_menu')) $(showid+'_menu').style.display = 'none';});
}
function insertFace(showid, id, target, dropstr) {
var faceText = '[em:'+id+':]';
if($(target) != null) {
insertContent(target, faceText);
if(dropstr) {
$(target).value = $(target).value.replace(dropstr, "");
}
}
}
function wall_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
obj.insertBefore(newdl, obj.firstChild);
if($('comment_message')) {
$('comment_message').value= '';
}
showCreditPrompt();
}
function share_add(sid) {
var obj = $('share_ul');
var newli = document.createElement("li");
newli.id = 'share_' + sid + '_li';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=share&inajax=1&sid='+sid, function(s){
newli.innerHTML = s;
});
obj.insertBefore(newli, obj.firstChild);
$('share_link').value = 'http://';
$('share_general').value = '';
showCreditPrompt();
}
function comment_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
if($('comment_prepend')){
obj = obj.firstChild;
while (obj && obj.nodeType != 1){
obj = obj.nextSibling;
}
obj.parentNode.insertBefore(newdl, obj);
} else {
obj.appendChild(newdl);
}
if($('comment_message')) {
$('comment_message').value= '';
}
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a + 1;
$('comment_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
function comment_edit(cid) {
var obj = $('comment_'+ cid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+ cid, function(s){
obj.innerHTML = s;
var elems = selector('dd[class~=magicflicker]');
for(var i=0; i<elems.length; i++){
magicColor(elems[i]);
}
});
}
function comment_delete(cid) {
var obj = $('comment_'+ cid +'_li');
obj.style.display = "none";
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a - 1;
$('comment_replynum').innerHTML = b + '';
}
}
function share_delete(sid) {
var obj = $('share_'+ sid +'_li');
obj.style.display = "none";
}
function friend_delete(uid) {
var obj = $('friend_'+ uid +'_li');
if(obj != null) obj.style.display = "none";
var obj2 = $('friend_tbody_'+uid);
if(obj2 != null) obj2.style.display = "none";
}
function friend_changegroup(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
var obj = $('friend_group_'+ uid);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendgroup&uid='+uid, function(s){
obj.innerHTML = s;
});
}
}
function friend_changegroupname(group) {
var obj = $('friend_groupname_'+ group);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendname&inajax=1&group='+group, function(s){
obj.innerHTML = s;
});
}
function post_add(pid, result) {
if(result) {
var obj = $('post_ul');
var newli = document.createElement("div");
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post', function(s){
newli.innerHTML = s;
});
obj.appendChild(newli);
if($('message')) {
$('message').value= '';
newnode = $('quickpostimg').rows[0].cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
var allRows = $('quickpostimg').rows;
while(allRows.length) {
$('quickpostimg').removeChild(allRows[0]);
}
$('quickpostimg').appendChild(newnode);
}
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a + 1;
$('post_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
}
function post_edit(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post&pid='+ pid, function(s){
obj.innerHTML = s;
});
}
}
function post_delete(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
obj.style.display = "none";
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a - 1;
$('post_replynum').innerHTML = b + '';
}
}
}
function poke_send(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
if($('poke_'+ uid)) {
$('poke_'+ uid).style.display = "none";
}
showCreditPrompt();
}
}
function myfriend_post(uid) {
if($('friend_'+uid)) {
$('friend_'+uid).innerHTML = '<p>你们现在是好友了,接下来,您还可以:<a href="home.php?mod=space&do=wall&uid='+uid+'" class="xi2" target="_blank">给TA留言</a> ,或者 <a href="home.php?mod=spacecp&ac=poke&op=send&uid='+uid+'&handlekey=propokehk_'+uid+'" id="a_poke_'+uid+'" class="xi2" onclick="showWindow(this.id, this.href, \'get\', 0, {\'ctrlid\':this.id,\'pos\':\'13\'});">打个招呼</a></p>';
}
showCreditPrompt();
}
function myfriend_ignore(id) {
var ids = explode('_', id);
var uid = ids[1];
$('friend_tbody_'+uid).style.display = "none";
}
function mtag_join(tagid, result) {
if(result) {
location.reload();
}
}
function resend_mail(mid) {
if(mid) {
var obj = $('sendmail_'+ mid +'_li');
obj.style.display = "none";
}
}
function userapp_delete(id, result) {
if(result) {
var ids = explode('_', id);
var appid = ids[1];
$('space_app_'+appid).style.display = "none";
}
}
function docomment_get(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = '';
$(showid).className = 'cmt brm';
ajaxget('home.php?mod=spacecp&ac=doing&op=getcomment&handlekey=msg_'+doid+'&doid='+doid+'&key='+key, showid);
if($(opid)) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
docomment_colse(doid, key);
}
}
showCreditPrompt();
}
function docomment_colse(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '回复';
$(opid).onclick = function() {
docomment_get(doid, key);
}
}
function docomment_form(doid, id, key) {
var showid = key + '_form_'+doid+'_'+id;
var divid = key +'_'+ doid;
var url = 'home.php?mod=spacecp&ac=doing&op=docomment&handlekey=msg_'+id+'&doid='+doid+'&id='+id+'&key='+key;
if(parseInt(discuz_uid)) {
ajaxget(url, showid);
if($(divid)) {
$(divid).style.display = '';
}
} else {
showWindow(divid, url);
}
}
function docomment_form_close(doid, id, key) {
var showid = key + '_form_' + doid + '_' + id;
var opid = key + '_do_a_op_' + doid;
$(showid).innerHTML = '';
$(showid).style.display = 'none';
var liObj = $(key+'_'+doid).getElementsByTagName('li');
if(!liObj.length) {
$(key+'_'+doid).style.display = 'none';
if($(opid)) {
$(opid).innerHTML = '回复';
$(opid).onclick = function () {
docomment_get(doid, key);
}
}
}
}
function feedcomment_get(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = '';
ajaxget('home.php?mod=spacecp&ac=feed&op=getcomment&feedid='+feedid+'&handlekey=feedhk_'+feedid, showid);
if($(opid) != null) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
feedcomment_close(feedid);
}
}
}
function feedcomment_add(cid, feedid) {
var obj = $('comment_ol_'+feedid);
var newdl = document.createElement("dl");
newdl.id = 'comment_'+cid+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+cid, function(s){
newdl.innerHTML = s;
});
obj.appendChild(newdl);
$('feedmessage_'+feedid).value= '';
showCreditPrompt();
}
function feedcomment_close(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '评论';
$(opid).onclick = function() {
feedcomment_get(feedid);
}
}
function feed_post_result(feedid, result) {
if(result) {
location.reload();
}
}
function feed_more_show(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = '';
$(showid).className = 'sub_doing';
$(opid).innerHTML = '« 收起列表';
$(opid).onclick = function() {
feed_more_close(feedid);
}
}
function feed_more_close(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = 'none';
$(opid).innerHTML = '» 更多动态';
$(opid).onclick = function() {
feed_more_show(feedid);
}
}
function poll_post_result(id, result) {
if(result) {
var aObj = $('__'+id).getElementsByTagName("a");
window.location.href = aObj[0].href;
}
}
function show_click(idtype, id, clickid) {
ajaxget('home.php?mod=spacecp&ac=click&op=show&clickid='+clickid+'&idtype='+idtype+'&id='+id, 'click_div');
showCreditPrompt();
}
function feed_menu(feedid, show) {
var obj = $('a_feed_menu_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
var obj = $('feedmagic_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function magicColor(elem, t) {
t = t || 10;
elem = (elem && elem.constructor == String) ? $(elem) : elem;
if(!elem){
setTimeout(function(){magicColor(elem, t-1);}, 400);
return;
}
if(window.mcHandler == undefined) {
window.mcHandler = {elements:[]};
window.mcHandler.colorIndex = 0;
window.mcHandler.run = function(){
var color = ["#CC0000","#CC6D00","#CCCC00","#00CC00","#0000CC","#00CCCC","#CC00CC"][(window.mcHandler.colorIndex++) % 7];
for(var i = 0, L=window.mcHandler.elements.length; i<L; i++)
window.mcHandler.elements[i].style.color = color;
}
}
window.mcHandler.elements.push(elem);
if(window.mcHandler.timer == undefined) {
window.mcHandler.timer = setInterval(window.mcHandler.run, 500);
}
}
function passwordShow(value) {
if(value==4) {
$('span_password').style.display = '';
$('tb_selectgroup').style.display = 'none';
} else if(value==2) {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = '';
} else {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = 'none';
}
}
function getgroup(gid) {
if(gid) {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=privacy&inajax=1&op=getgroup&gid='+gid, function(s){
s = s + ' ';
$('target_names').innerHTML += s;
});
}
}
function pmsendappend() {
$('pm_append').style.display = '';
$('pm_append').id = '';
div = document.createElement('div');
div.id = 'pm_append';
div.style.display = 'none';
$('pm_ul').appendChild(div);
$('replymessage').value = '';
showCreditPrompt();
}
function succeedhandle_pmsend(locationhref, message, param) {
ajaxget('home.php?mod=spacecp&ac=pm&op=viewpmid&pmid=' + param['pmid'], 'pm_append', 'ajaxwaitid', '', null, 'pmsendappend()');
}
function getchatpmappendmember() {
var users = document.getElementsByName('users[]');
var appendmember = '';
if(users.length) {
var comma = '';
for(var i = 0; i < users.length; i++) {
appendmember += comma + users[i].value;
if(!comma) {
comma = ',';
}
}
}
if($('username').value) {
appendmember = appendmember ? (appendmember + ',' + $('username').value) : $('username').value;
}
var href = $('a_appendmember').href + '&memberusername=' + appendmember;
showWindow('a_appendmember', href, 'get', 0);
}
function markreadpm(markreadids) {
var markreadidarr = markreadids.split(',');
if(markreadidarr.length > 0) {
for(var i = 0; i < markreadidarr.length; i++) {
$(markreadidarr[i]).className = 'bbda cl';
}
}
}
function setpmstatus(form) {
var ids_gpmid = new Array();
var ids_plid = new Array();
var type = '';
var requesturl = '';
var markreadids = new Array();
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.id && e.id.match('a_delete') && e.checked) {
var idarr = new Array();
idarr = e.id.split('_');
if(idarr[1] == 'deleteg') {
ids_gpmid.push(idarr[2]);
markreadids.push('gpmlist_' + idarr[2]);
} else if(idarr[1] == 'delete') {
ids_plid.push(idarr[2]);
markreadids.push('pmlist_' + idarr[2]);
}
}
}
if(ids_gpmid.length > 0) {
requesturl += '&gpmids=' + ids_gpmid.join(',');
}
if(ids_plid.length > 0) {
requesturl += '&plids=' + ids_plid.join(',');
}
if(requesturl) {
ajaxget('home.php?mod=spacecp&ac=pm&op=setpmstatus' + requesturl, '', 'ajaxwaitid', '', 'none', 'markreadpm(\''+ markreadids.join(',') +'\')');
}
}
function changedeletedpm(pmid) {
$('pmlist_' + pmid).style.display = 'none';
var membernum = parseInt($('membernum').innerHTML);
$('membernum').innerHTML = membernum - 1;
}
function changeOrderRange(id) {
if(!$(id)) return false;
var url = window.location.href;
var a = $(id).getElementsByTagName('a');
for(var i = 0; i < a.length; i++) {
a[i].onclick = function () {
if(url.indexOf("&orderby=") == -1) {
url += "&orderby=" + this.id;
} else {
url = url.replace(/orderby=.*/, "orderby=" + this.id);
}
window.location = url;
return false;
}
}
}
function addBlockLink(id, tag) {
if(!$(id)) return false;
var a = $(id).getElementsByTagName(tag);
var taglist = {'A':1, 'INPUT':1, 'IMG':1};
for(var i = 0, len = a.length; i < len; i++) {
a[i].onmouseover = function () {
if(this.className.indexOf(' hover') == -1) {
this.className = this.className + ' hover';
}
};
a[i].onmouseout = function () {
this.className = this.className.replace(' hover', '');
};
a[i].onclick = function (e) {
e = e ? e : window.event;
var target = e.target || e.srcElement;
if(!taglist[target.tagName]) {
window.location.href = $(this.id + '_a').href;
}
};
}
}
function checkSynSignature() {
if($('to_signhtml').value == '1') {
$('syn_signature').className = 'syn_signature';
$('to_signhtml').value = '0';
} else {
$('syn_signature').className = 'syn_signature_check';
$('to_signhtml').value = '1';
}
}
function searchpostbyusername(keyword, srchuname) {
window.location.href = 'search.php?mod=forum&srchtxt=' + keyword + '&srchuname=' + srchuname + '&searchsubmit=yes';
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_diy.js 31093 2012-07-16 03:54:34Z zhangguosheng $
*/
var drag = new Drag();
drag.extend({
'getBlocksTimer' : '',
'blocks' : [],
'blockDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_block_bm'},{'key':'样式1','value':'xbs_1'},{'key':'样式2','value':'xbs xbs_2'},{'key':'样式3','value':'xbs xbs_3'},{'key':'样式4','value':'xbs xbs_4'},{'key':'样式5','value':'xbs xbs_5'},{'key':'样式6','value':'xbs xbs_6'},{'key':'样式7','value':'xbs xbs_7'}],
'frameDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_frame_bm'},{'key':'无边框框架','value':'xfs xfs_nbd'},{'key':'样式1','value':'xfs xfs_1'},{'key':'样式2','value':'xfs xfs_2'},{'key':'样式3','value':'xfs xfs_3'},{'key':'样式4','value':'xfs xfs_4'},{'key':'样式5','value':'xfs xfs_5'}],
setDefalutMenu : function () {
this.addMenu('default','标题','drag.openTitleEdit(event)');
this.addMenu('default','样式','drag.openStyleEdit(event)');
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
this.addMenu('frame', '导出', 'drag.frameExport(event)');
this.addMenu('tab', '导出', 'drag.frameExport(event)');
},
setSampleMenu : function () {
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
},
openBlockEdit : function (e,op) {
e = Util.event(e);
op = (op=='data') ? 'data' : 'block';
var bid = e.aim.id.replace('cmd_portal_block_','');
this.removeMenu();
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op='+op+'&bid='+bid+'&tpl='+document.diyform.template.value, 'get', -1);
},
getDiyClassName : function (id,index) {
var obj = this.getObjByName(id);
var ele = $(id);
var eleClassName = ele.className.replace(/ {2,}/g,' ');
var className = '',srcClassName = '';
if (obj instanceof Block) {
className = eleClassName.split(this.blockClass+' ');
srcClassName = this.blockClass;
} else if(obj instanceof Tab) {
className = eleClassName.split(this.tabClass+' ');
srcClassName = this.tabClass;
} else if(obj instanceof Frame) {
className = eleClassName.split(this.frameClass+' ');
srcClassName = this.frameClass;
}
if (index != null && index<className.length) {
className = className[index].replace(/^ | $/g,'');
} else {
className.push(srcClassName);
}
return className;
},
getOption : function (arr,value) {
var html = '';
for (var i in arr) {
if (typeof arr[i] == 'function') continue;
var selected = arr[i]['value'] == value ? ' selected="selected"' : '';
html += '<option value="'+arr[i]['value']+'"'+selected+'>'+arr[i]['key']+'</option>';
}
return html;
},
getRule : function (selector,attr) {
selector = spaceDiy.checkSelector(selector);
var value = (!selector || !attr) ? '' : spaceDiy.styleSheet.getRule(selector, attr);
return value;
},
openStyleEdit : function (e) {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
var bgcolor = '',bgimage = '',bgrepeat = '',html = '',diyClassName = '',fontcolor = '',fontsize = '',linkcolor = '',linkfontsize = '';
var bdtstyle = '',bdtwidth = '',bdtcolor = '',bdrstyle = '',bdrwidth = '',bdrcolor = '',bdbstyle = '',bdbwidth = '',bdbcolor = '',bdlstyle = '',bdlwidth = '',bdlcolor = '';
var margint = '',marginr = '',marginb = '',marginl = '',cmargint = '',cmarginr = '',cmarginb = '',cmarginl ='';
var selector = '#'+id;
bgcolor = this.getRule(selector, 'backgroundColor');
bgimage = this.getRule(selector, 'backgroundImage');
bgrepeat = this.getRule(selector, 'backgroundRepeat');
bgimage = bgimage && bgimage != 'none' ? Util.trimUrl(bgimage) : '';
fontcolor = this.getRule(selector+' .'+this.contentClass, 'color');
fontsize = this.getRule(selector+' .'+this.contentClass, 'fontSize').replace('px','');
var linkSelector = spaceDiy.checkSelector(selector+ ' .'+this.contentClass+' a');
linkcolor = this.getRule(linkSelector, 'color');
linkfontsize = this.getRule(linkSelector, 'fontSize').replace('px','');
fontcolor = Util.formatColor(fontcolor);
linkcolor = Util.formatColor(linkcolor);
bdtstyle = this.getRule(selector, 'borderTopStyle');
bdrstyle = this.getRule(selector, 'borderRightStyle');
bdbstyle = this.getRule(selector, 'borderBottomStyle');
bdlstyle = this.getRule(selector, 'borderLeftStyle');
bdtwidth = this.getRule(selector, 'borderTopWidth');
bdrwidth = this.getRule(selector, 'borderRightWidth');
bdbwidth = this.getRule(selector, 'borderBottomWidth');
bdlwidth = this.getRule(selector, 'borderLeftWidth');
bdtcolor = this.getRule(selector, 'borderTopColor');
bdrcolor = this.getRule(selector, 'borderRightColor');
bdbcolor = this.getRule(selector, 'borderBottomColor');
bdlcolor = this.getRule(selector, 'borderLeftColor');
bgcolor = Util.formatColor(bgcolor);
bdtcolor = Util.formatColor(bdtcolor);
bdrcolor = Util.formatColor(bdrcolor);
bdbcolor = Util.formatColor(bdbcolor);
bdlcolor = Util.formatColor(bdlcolor);
margint = this.getRule(selector, 'marginTop').replace('px','');
marginr = this.getRule(selector, 'marginRight').replace('px','');
marginb = this.getRule(selector, 'marginBottom').replace('px','');
marginl = this.getRule(selector, 'marginLeft').replace('px','');
if (objType == 1) {
selector = selector + ' .'+this.contentClass;
cmargint = this.getRule(selector, 'marginTop').replace('px','');
cmarginr = this.getRule(selector, 'marginRight').replace('px','');
cmarginb = this.getRule(selector, 'marginBottom').replace('px','');
cmarginl = this.getRule(selector, 'marginLeft').replace('px','');
}
diyClassName = this.getDiyClassName(id,0);
var widtharr = [];
for (var k=0;k<11;k++) {
var key = k+'px';
widtharr.push({'key':key,'value':key});
}
var bigarr = [];
for (var k=0;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var stylearr = [{'key':'无样式','value':'none'},{'key':'实线','value':'solid'},{'key':'点线','value':'dotted'},{'key':'虚线','value':'dashed'}];
var table = '<table class="tfm">';
table += '<tr><th>字体</th><td><input type="text" id="fontsize" class="px p_fre vm" value="'+fontsize+'" size="2" />px <input type="text" id="fontcolor" class="px p_fre vm" value="'+fontcolor+'" size="2" />';
table += getColorPalette(id+'_fontPalette', 'fontcolor' ,fontcolor)+'</td></tr>';
table += '<tr><th>链接</th><td><input type="text" id="linkfontsize" class="px p_fre vm" value="'+linkfontsize+'" size="2" />px <input type="text" id="linkcolor" class="px p_fre vm" value="'+linkcolor+'" size="2" />';
table += getColorPalette(id+'_linkPalette', 'linkcolor' ,linkcolor)+'</td></tr>';
var ulclass = 'borderul', opchecked = '';
if (bdtwidth != '' || bdtcolor != '' ) {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>边框</th><td><ul id="borderul" class="'+ulclass+'">';
table += '<li><label>上</label><select class="ps vm" id="bdtwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdtwidth)+'</select>';
table += ' <select class="ps vm" id="bdtstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdtstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdtcolor" class="px p_fre vm" value="'+bdtcolor+'" size="7" />';
table += getColorPalette(id+'_bdtPalette', 'bdtcolor' ,bdtcolor)+'</li>';
table += '<li class="bordera mtn"><label>右</label><select class="ps vm" id="bdrwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdrwidth)+'</select>';
table += ' <select class="ps vm" id="bdrstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdrstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdrcolor" class="px p_fre vm" value="'+bdrcolor+'" size="7" />';
table += getColorPalette(id+'_bdrPalette', 'bdrcolor' ,bdrcolor)+'</li>';
table += '<li class="bordera mtn"><label>下</label><select class="ps vm" id="bdbwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdbwidth)+'</select>';
table += ' <select class="ps vm" id="bdbstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdbstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdbcolor" class="px p_fre vm" value="'+bdbcolor+'" size="7" />';
table += getColorPalette(id+'_bdbPalette', 'bdbcolor' ,bdbcolor)+'</li>';
table += '<li class="bordera mtn"><label>左</label><select class="ps vm" id="bdlwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdlwidth)+'</select>';
table += ' <select class="ps vm" id="bdlstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdlstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdlcolor" class="px p_fre vm" value="'+bdlcolor+'" size="7" />';
table += getColorPalette(id+'_bdlPalette', 'bdlcolor' ,bdlcolor)+'</li>';
table += '</ul><p class="ptm"><label><input id="borderop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'borderul\').className = $(\'borderul\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
bigarr = [];
for (k=-20;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
ulclass = 'borderul', opchecked = '';
if (margint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>外边距</th><td><div id="margindiv" class="'+ulclass+'"><span><label>上</label> <input type="text" id="margint" class="px p_fre vm" value="'+margint+'" size="1"/>px </span>';
table += '<span class="bordera"><label>右</label> <input type="text" id="marginr" class="px p_fre vm" value="'+marginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input type="text" id="marginb" class="px p_fre vm" value="'+marginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input type="text" id="marginl" class="px p_fre vm" value="'+marginl+'" size="1" />px</span>';
table += '</div><p class="ptm"><label><input id="marginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'margindiv\').className = $(\'margindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
if (objType == 1) {
ulclass = 'borderul', opchecked = '';
if (cmargint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>内边距</th><td><div id="cmargindiv" class="'+ulclass+'"><span><label>上</label> <input class="px p_fre" id="cmargint" value="'+cmargint+'" size="1" />px </span>';
table += '<span class="bordera"><label>右</label> <input class="px p_fre" id="cmarginr" value="'+cmarginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input class="px p_fre" id="cmarginb" value="'+cmarginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input class="px p_fre" id="cmarginl" value="'+cmarginl+'" size="1" />px </span>';
table += '</div><p class="ptm"><label><input id="cmarginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'cmargindiv\').className = $(\'cmargindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'"> 分别设置</label></p></td></tr>';
}
table += '<tr><th>背景颜色</th><td><input type="text" id="bgcolor" class="px p_fre vm" value="'+bgcolor+'" size="4" />';
table += getColorPalette(id+'_bgcPalette', 'bgcolor' ,bgcolor)+'</td></tr>';
table += '<tr><th>背景图片</th><td><input type="text" id="bgimage" class="px p_fre vm" value="'+bgimage+'" size="25" /> <select class="ps vm" id="bgrepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
var classarr = objType == 1 ? this.blockDefaultClass : this.frameDefaultClass;
table += '<tr><th>指定class</th><td><input type="text" id="diyClassName" class="px p_fre" value="'+diyClassName+'" size="8" /> <select class="ps vm" id="bgrepeat" onchange="$(\'diyClassName\').value=this.value;" >'+this.getOption(classarr, diyClassName)+'</select></td></tr>';
table += '</table>';
var wname = objType ? '模块' : '框架';
html = '<div class="c diywin" style="width:450px;position:relative;">'+table+'</div>';
var h = '<h3 class="flb"><em>编辑'+wname+'样式</em><span><a href="javascript:;" class="flbc" onclick="drag.closeStyleEdit(\''+id+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveStyle(\''+id+'\');drag.closeStyleEdit(\''+id+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeStyleEdit(\''+id+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('eleStyle',h + html + f, 'html', 0);
},
closeStyleEdit : function (id) {
this.deleteFrame([id+'_bgcPalette',id+'_bdtPalette',id+'_bdrPalette',id+'_bdbPalette',id+'_bdlPalette',id+'_fontPalette',id+'_linkPalette']);
hideWindow('eleStyle');
},
saveStyle : function (id) {
var className = this.getDiyClassName(id);
var diyClassName = $('diyClassName').value;
$(id).className = diyClassName+' '+className[2]+' '+className[1];
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
if (objType == 1) this.saveBlockClassName(id,diyClassName);
var selector = '#'+id;
var random = Math.random();
spaceDiy.setStyle(selector, 'background-color', $('bgcolor').value, random);
var bgimage = $('bgimage').value && $('bgimage') != 'none' ? Util.url($('bgimage').value) : '';
var bgrepeat = bgimage ? $('bgrepeat').value : '';
if ($('bgcolor').value != '' && bgimage == '') bgimage = 'none';
spaceDiy.setStyle(selector, 'background-image', bgimage, random);
spaceDiy.setStyle(selector, 'background-repeat', bgrepeat, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'color', $('fontcolor').value, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'font-size', this.formatValue('fontsize'), random);
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'color', $('linkcolor').value, random);
var linkfontsize = parseInt($('linkfontsize').value);
linkfontsize = isNaN(linkfontsize) ? '' : linkfontsize+'px';
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'font-size', this.formatValue('linkfontsize'), random);
if ($('borderop').checked) {
var bdtwidth = $('bdtwidth').value,bdrwidth = $('bdrwidth').value,bdbwidth = $('bdbwidth').value,bdlwidth = $('bdlwidth').value;
var bdtstyle = $('bdtstyle').value,bdrstyle = $('bdrstyle').value,bdbstyle = $('bdbstyle').value,bdlstyle = $('bdlstyle').value;
var bdtcolor = $('bdtcolor').value,bdrcolor = $('bdrcolor').value,bdbcolor = $('bdbcolor').value,bdlcolor = $('bdlcolor').value;
} else {
bdlwidth = bdbwidth = bdrwidth = bdtwidth = $('bdtwidth').value;
bdlstyle = bdbstyle = bdrstyle = bdtstyle = $('bdtstyle').value;
bdlcolor = bdbcolor = bdrcolor = bdtcolor = $('bdtcolor').value;
}
spaceDiy.setStyle(selector, 'border', '', random);
spaceDiy.setStyle(selector, 'border-top-width', bdtwidth, random);
spaceDiy.setStyle(selector, 'border-right-width', bdrwidth, random);
spaceDiy.setStyle(selector, 'border-bottom-width', bdbwidth, random);
spaceDiy.setStyle(selector, 'border-left-width', bdlwidth, random);
spaceDiy.setStyle(selector, 'border-top-style', bdtstyle, random);
spaceDiy.setStyle(selector, 'border-right-style', bdrstyle, random);
spaceDiy.setStyle(selector, 'border-bottom-style', bdbstyle, random);
spaceDiy.setStyle(selector, 'border-left-style', bdlstyle, random);
spaceDiy.setStyle(selector, 'border-top-color', bdtcolor, random);
spaceDiy.setStyle(selector, 'border-right-color', bdrcolor, random);
spaceDiy.setStyle(selector, 'border-bottom-color', bdbcolor, random);
spaceDiy.setStyle(selector, 'border-left-color', bdlcolor, random);
if ($('marginop').checked) {
var margint = this.formatValue('margint'),marginr = this.formatValue('marginr'), marginb = this.formatValue('marginb'), marginl = this.formatValue('marginl');
} else {
marginl = marginb = marginr = margint = this.formatValue('margint');
}
spaceDiy.setStyle(selector, 'margin-top',margint, random);
spaceDiy.setStyle(selector, 'margin-right', marginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', marginb, random);
spaceDiy.setStyle(selector, 'margin-left', marginl, random);
if (objType == 1) {
if ($('cmarginop').checked) {
var cmargint = this.formatValue('cmargint'),cmarginr = this.formatValue('cmarginr'), cmarginb = this.formatValue('cmarginb'), cmarginl = this.formatValue('cmarginl');
} else {
cmarginl = cmarginb = cmarginr = cmargint = this.formatValue('cmargint');
}
selector = selector + ' .'+this.contentClass;
spaceDiy.setStyle(selector, 'margin-top', cmargint, random);
spaceDiy.setStyle(selector, 'margin-right', cmarginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', cmarginb, random);
spaceDiy.setStyle(selector, 'margin-left', cmarginl, random);
}
this.setClose();
},
formatValue : function(id) {
var value = '';
if ($(id)) {
value = parseInt($(id).value);
value = isNaN(value) ? '' : value+'px';
}
return value;
},
saveBlockClassName : function(id,className){
if (!$('saveblockclassname')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblockclassname" method="post" action=""><input type="hidden" name="classname" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="saveclassnamesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblockclassname').action = 'portal.php?mod=portalcp&ac=block&op=saveblockclassname&bid='+id.replace('portal_block_','');
document.forms.saveblockclassname.classname.value = className;
ajaxpost('saveblockclassname','ajaxwaitid');
},
closeTitleEdit : function (fid) {
this.deleteFrame(fid+'bgPalette_0');
for (var i = 0 ; i<=10; i++) {
this.deleteFrame(fid+'Palette_'+i);
}
hideWindow('frameTitle');
},
openTitleEdit : function (e) {
if (typeof e == 'object') {
e = Util.event(e);
var fid = e.aim.id.replace('cmd_','');
} else {
fid = e;
}
var obj = this.getObjByName(fid);
var titlename = obj instanceof Block ? '模块' : '框架';
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var len = obj.titles.length;
var bgimage = obj.titles.style && obj.titles.style['background-image'] ? obj.titles.style['background-image'] : '';
bgimage = bgimage != 'none' ? Util.trimUrl(bgimage) : '';
var bgcolor = obj.titles.style && obj.titles.style['background-color'] ? obj.titles.style['background-color'] : '';
bgcolor = Util.formatColor(bgcolor);
var bgrepeat = obj.titles.style && obj.titles.style['background-repeat'] ? obj.titles.style['background-repeat'] : '';
var common = '<table class="tfm">';
common += '<tr><th>背景图片:</th><td><input type="text" id="titleBgImage" class="px p_fre" value="'+bgimage+'" /> <select class="ps vm" id="titleBgRepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
common += '<tr><th>背景颜色:</th><td><input type="text" id="titleBgColor" class="px p_fre" value="'+bgcolor+'" size="7" />';
common += getColorPalette(fid+'bgPalette_0', 'titleBgColor' ,bgcolor)+'</td></tr>';
if (obj instanceof Tab) {
var switchArr = [{'key':'点击','value':'click'},{'key':'滑过','value':'mouseover'}];
var switchType = obj.titles['switchType'] ? obj.titles['switchType'][0] : 'click';
common += '<tr><th>切换类型:</th><td><select class="ps" id="switchType" >'+this.getOption(switchArr,switchType)+'</select></td></tr>';
}
common += '</table><hr class="l">';
var li = '';
li += '<div id="titleInput_0"><table class="tfm"><tr><th>'+titlename+'标题:</th><td><input type="text" id="titleText_0" class="px p_fre" value="`title`" /></td></tr>';
li += '<tr><th>链接:</th><td><input type="text" id="titleLink_0" class="px p_fre" value="`link`" /></td></tr>';
li += '<tr><th>图片:</th><td><input type="text" id="titleSrc_0" class="px p_fre" value="`src`" /></td></tr>';
li += '<tr><th>位置:</th><td><select id="titleFloat_0" class="ps vm"><option value="" `left`>居左</option><option value="right" `right`>居右</option></select>';
li += ' 偏移量: <input type="text" id="titleMargin_0" class="px p_fre vm" value="`margin`" size="2" />px</td></tr>';
li += '<tr><th>字体:</th><td><select class="ps vm" id="titleSize_0" ><option value="">大小</option>`size`</select>';
li += ' 颜色: <input type="text" id="titleColor_0" class="px p_fre vm" value="`color`" size="4" />';
li += getColorPalette(fid+'Palette_0', 'titleColor_0' ,'`color`');
li += '</td></tr><tr><td colspan="2"><hr class="l"></td></tr></table></div>';
var html = '';
if (obj.titles['first']) {
html = this.getTitleHtml(obj, 'first', li);
}
for (var i = 0; i < len; i++ ) {
html += this.getTitleHtml(obj, i, li);
}
if (!html) {
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
var ssize = this.getOption(bigarr,ssize);
html = li.replace('`size`', ssize).replace(/`\w+`/g, '');
}
var c = len + 1;
html = '<div class="c diywin" style="width:450px;height:400px; overflow:auto;"><table cellspacing="0" cellpadding="0" class="tfm pns"><tr><th></th><td><button type="button" id="addTitleInput" class="pn" onclick="drag.addTitleInput('+c+');"><em>添加新标题</em></button></td></tr></table><div id="titleEdit">'+html+common+'</div></div>';
var h = '<h3 class="flb"><em>编辑'+titlename+'标题</em><span><a href="javascript:;" class="flbc" onclick="drag.closeTitleEdit(\''+fid+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveTitleEdit(\''+fid+'\');drag.closeTitleEdit(\''+fid+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeTitleEdit(\''+fid+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('frameTitle',h + html + f, 'html', 0);
},
getTitleHtml : function (obj, i, li) {
var shtml = '',stitle = '',slink = '',sfloat = '',ssize = '',scolor = '',margin = '',src = '';
var c = i == 'first' ? '0' : i+1;
stitle = obj.titles[i]['text'] ? obj.titles[i]['text'] : '';
slink = obj.titles[i]['href'] ? obj.titles[i]['href'] : '';
sfloat = obj.titles[i]['float'] ? obj.titles[i]['float'] : '';
margin = obj.titles[i]['margin'] ? obj.titles[i]['margin'] : '';
ssize = obj.titles[i]['font-size'] ? obj.titles[i]['font-size']+'px' : '';
scolor = obj.titles[i]['color'] ? obj.titles[i]['color'] : '';
src = obj.titles[i]['src'] ? obj.titles[i]['src'] : '';
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
ssize = this.getOption(bigarr,ssize);
shtml = li.replace(/_0/g, '_' + c).replace('`title`', stitle).replace('`link`', slink).replace('`size`', ssize).replace('`src`',src);
var left = sfloat == '' ? 'selected' : '';
var right = sfloat == 'right' ? 'selected' : '';
scolor = Util.formatColor(scolor);
shtml = shtml.replace(/`color`/g, scolor).replace('`left`', left).replace('`right`', right).replace('`margin`', margin);
return shtml;
},
addTitleInput : function (c) {
if (c > 10) return false;
var pre = $('titleInput_'+(c-1));
var dom = document.createElement('div');
dom.className = 'tfm';
var exp = new RegExp('_'+(c-1), 'g');
dom.id = 'titleInput_'+c;
dom.innerHTML = pre.innerHTML.replace(exp, '_'+c);
Util.insertAfter(dom, pre);
$('addTitleInput').onclick = function () {drag.addTitleInput(c+1)};
},
saveTitleEdit : function (fid) {
var obj = this.getObjByName(fid);
var ele = $(fid);
var children = ele.childNodes;
var title = first = '';
var hastitle = 0;
var c = 0;
for (var i in children) {
if (typeof children[i] == 'object' && Util.hasClass(children[i], this.titleClass)) {
title = children[i];
break;
}
}
if (title) {
var arrDel = [];
for (var i in title.childNodes) {
if (typeof title.childNodes[i] == 'object' && Util.hasClass(title.childNodes[i], this.titleTextClass)) {
first = title.childNodes[i];
this._createTitleHtml(first, c);
if (first.innerHTML != '') hastitle = 1;
} else if (typeof title.childNodes[i] == 'object' && !Util.hasClass(title.childNodes[i], this.moveableObject)) {
arrDel.push(title.childNodes[i]);
}
}
for (var i = 0; i < arrDel.length; i++) {
title.removeChild(arrDel[i]);
}
} else {
var titleClassName = '';
if(obj instanceof Tab) {
titleClassName = 'tab-';
} else if(obj instanceof Frame) {
titleClassName = 'frame-';
} else if(obj instanceof Block) {
titleClassName = 'block';
}
title = document.createElement('div');
title.className = titleClassName + 'title' + ' '+ this.titleClass;
ele.insertBefore(title,ele.firstChild);
}
if (!first) {
var first = document.createElement('span');
first.className = this.titleTextClass;
this._createTitleHtml(first, c);
if (first.innerHTML != '') {
title.insertBefore(first, title.firstChild);
hastitle = 1;
}
}
while ($('titleText_'+(++c))) {
var dom = document.createElement('span');
dom.className = 'subtitle';
this._createTitleHtml(dom, c);
if (dom.innerHTML != '') {
if (dom.innerHTML) Util.insertAfter(dom, first);
first = dom;
hastitle = 1;
}
}
var titleBgImage = $('titleBgImage').value;
titleBgImage = titleBgImage && titleBgImage != 'none' ? Util.url(titleBgImage) : '';
if ($('titleBgColor').value != '' && titleBgImage == '') titleBgImage = 'none';
title.style['backgroundImage'] = titleBgImage;
if (titleBgImage) {
title.style['backgroundRepeat'] = $('titleBgRepeat').value;
}
title.style['backgroundColor'] = $('titleBgColor').value;
if ($('switchType')) {
title.switchType = [];
title.switchType[0] = $('switchType').value ? $('switchType').value : 'click';
title.setAttribute('switchtype',title.switchType[0]);
}
obj.titles = [];
if (hastitle == 1) {
this._initTitle(obj,title);
} else {
if (!(obj instanceof Tab)) title.parentNode.removeChild(title);
title = '';
this.initPosition();
}
if (obj instanceof Block) this.saveBlockTitle(fid,title);
this.setClose();
},
_createTitleHtml : function (ele,tid) {
var html = '',img = '';
tid = '_' + tid ;
var ttext = $('titleText'+tid).value;
var tlink = $('titleLink'+tid).value;
var tfloat = $('titleFloat'+tid).value;
var tmargin_ = tfloat != '' ? tfloat : 'left';
var tmargin = $('titleMargin'+tid).value;
var tsize = $('titleSize'+tid).value;
var tcolor = $('titleColor'+tid).value;
var src = $('titleSrc'+tid).value;
var divStyle = 'float:'+tfloat+';margin-'+tmargin_+':'+tmargin+'px;font-size:'+tsize;
var aStyle = 'color:'+tcolor+' !important;';
if (src) {
img = '<img class="vm" src="'+src+'" alt="'+ttext+'" />';
}
if (ttext || img) {
if (tlink) {
Util.setStyle(ele, divStyle);
html = '<a href='+tlink+' target="_blank" style="'+aStyle+'">'+img+ttext+'</a>';
} else {
Util.setStyle(ele, divStyle+';'+aStyle);
html = img+ttext;
}
}
ele.innerHTML = html;
return true;
},
saveBlockTitle : function (id,title) {
if (!$('saveblocktitle')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblocktitle" method="post" action=""><input type="hidden" name="title" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="savetitlesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblocktitle').action = 'portal.php?mod=portalcp&ac=block&op=saveblocktitle&bid='+id.replace('portal_block_','');
var html = !title ? '' : title.outerHTML;
document.forms.saveblocktitle.title.value = html;
ajaxpost('saveblocktitle','ajaxwaitid');
},
removeBlock : function (e, flag) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var obj = this.getObjByName(id);
if (!flag) {
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
}
if (obj instanceof Block) {
this.delBlock(id);
} else if (obj instanceof Frame) {
this.delFrame(obj);
}
$(id).parentNode.removeChild($(id));
var content = $(id+'_content');
if(content) {
content.parentNode.removeChild(content);
}
this.setClose();
this.initPosition();
this.initChkBlock();
},
delBlock : function (bid) {
spaceDiy.removeCssSelector('#'+bid);
this.stopSlide(bid);
},
delFrame : function (frame) {
spaceDiy.removeCssSelector('#'+frame.name);
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) {
var children = frame['columns'][i]['children'];
for (var j in children) {
if (children[j] instanceof Frame) {
this.delFrame(children[j]);
} else if (children[j] instanceof Block) {
this.delBlock(children[j]['name']);
}
}
}
}
this.setClose();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.checked = true;
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
getBlockData : function (blockname) {
var bid = this.dragObj.id;
var eleid = bid;
if (bid.indexOf('portal_block_') != -1) {
eleid = 0;
}else {
bid = 0;
}
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=block&classname='+blockname+'&bid='+bid+'&eleid='+eleid+'&tpl='+document.diyform.template.value,'get',-1);
drag.initPosition();
this.fn = '';
return true;
},
stopSlide : function (id) {
if (typeof slideshow == 'undefined' || typeof slideshow.entities == 'undefined') return false;
var slidebox = $C('slidebox',$(id));
if(slidebox && slidebox.length > 0) {
if(slidebox[0].id) {
var timer = slideshow.entities[slidebox[0].id].timer;
if(timer) clearTimeout(timer);
slideshow.entities[slidebox[0].id] = '';
}
}
},
blockForceUpdate : function (e,all) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var bid = id.replace('portal_block_', '');
var bcontent = $(id+'_content');
if (!bcontent) {
bcontent = document.createElement('div');
bcontent.id = id+'_content';
bcontent.className = this.contentClass;
}
this.stopSlide(id);
var height = Util.getFinallyStyle(bcontent, 'height');
bcontent.style.lineHeight = height == 'auto' ? '' : (height == '0px' ? '20px' : height);
var boldcontent = bcontent.innerHTML;
bcontent.innerHTML = '<center>正在加载内容...</center>';
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=getblock&forceupdate=1&inajax=1&bid='+bid+'&tpl='+document.diyform.template.value, function(s) {
if(s.indexOf('errorhandle_') != -1) {
bcontent.innerHTML = boldcontent;
runslideshow();
showDialog('抱歉,您没有权限添加或编辑模块', 'alert');
doane();
} else {
var obj = document.createElement('div');
obj.innerHTML = s;
bcontent.parentNode.removeChild(bcontent);
$(id).innerHTML = obj.childNodes[0].innerHTML;
evalscript(s);
if(s.indexOf('runslideshow()') != -1) {runslideshow();}
drag.initPosition();
if (all) {drag.getBlocks();}
}
});
},
frameExport : function (e) {
var flag = true;
if (drag.isChange) {
flag = confirm('您已经做过修改,请保存后再做导出,否则导出的数据将不包括您这次所做的修改。');
}
if (flag) {
if ( typeof e == 'object') {
e = Util.event(e);
var frame = e.aim.id.replace('cmd_','');
} else {
frame = e == undefined ? '' : e;
}
if (!$('frameexport')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="frameexport" method="post" action="" target="_blank"><input type="hidden" name="frame" value="" />\n\
<input type="hidden" name="tpl" value="'+document.diyform.template.value+'" />\n\
<input type="hidden" name="tpldirectory" value="'+document.diyform.tpldirectory.value+'" />\n\
<input type="hidden" name="diysign" value="'+document.diyform.diysign.value+'" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="exportsubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('frameexport').action = 'portal.php?mod=portalcp&ac=diy&op=export';
document.forms.frameexport.frame.value = frame;
document.forms.frameexport.submit();
}
doane();
},
openFrameImport : function (type) {
type = type || 0;
showWindow('showimport','portal.php?mod=portalcp&ac=diy&op=import&tpl='+document.diyform.template.value+'&tpldirectory='+document.diyform.tpldirectory.value+'&diysign='+document.diyform.diysign.value+'&type='+type, 'get');
},
endBlockForceUpdateBatch : function () {
if($('allupdate')) {
$('allupdate').innerHTML = '已操作完成。';
$('fwin_dialog_submit').style.display = '';
$('fwin_dialog_cancel').style.display = 'none';
}
this.initPosition();
},
getBlocks : function () {
if (this.blocks.length == 0) {
this.endBlockForceUpdateBatch();
}
if (this.blocks.length > 0) {
var cur = this.blocksLen - this.blocks.length;
if($('allupdate')) {
$('allupdate').innerHTML = '共<span style="color:blue">'+this.blocksLen+'</span>个模块,正在更新第<span style="color:red">'+cur+'</span>个,已完成<span style="color:red">'+(parseInt(cur / this.blocksLen * 100)) + '%</span>';
var bid = 'portal_block_'+this.blocks.pop();
this.blockForceUpdate(bid,true);
}
}
},
blockForceUpdateBatch : function (blocks) {
if (blocks) {
this.blocks = blocks;
} else {
this.initPosition();
this.blocks = this.allBlocks;
}
this.blocksLen = this.blocks.length;
showDialog('<div id="allupdate" style="width:350px;line-height:28px;">开始更新...</div>','confirm','更新模块数据', '', true, 'drag.endBlockForceUpdateBatch()');
var wait = function() {
if($('fwin_dialog_submit')) {
$('fwin_dialog_submit').style.display = 'none';
$('fwin_dialog_cancel').className = 'pn pnc';
setTimeout(function(){drag.getBlocks()},500);
} else {
setTimeout(wait,100);
}
};
wait();
doane();
},
clearAll : function () {
if (confirm('您确实要清空页面上所在DIY数据吗,清空以后将不可恢复')) {
for (var i in this.data) {
for (var j in this.data[i]) {
if (typeof(this.data[i][j]) == 'object' && this.data[i][j].name.indexOf('_temp')<0) {
this.delFrame(this.data[i][j]);
$(this.data[i][j].name).parentNode.removeChild($(this.data[i][j].name));
}
}
}
this.initPosition();
this.setClose();
}
doane();
},
createObj : function (e,objType,contentType) {
if (objType == 'block' && !this.checkHasFrame()) {alert("提示:未找到框架,请先添加框架。");spaceDiy.getdiy('frame');return false;}
e = Util.event(e);
if(e.which != 1 ) {return false;}
var html = '',offWidth = 0;
if (objType == 'frame') {
html = this.getFrameHtml(contentType);
offWidth = 600;
} else if (objType == 'block') {
html = this.getBlockHtml(contentType);
offWidth = 200;
this.fn = function (e) {drag.getBlockData(contentType);};
} else if (objType == 'tab') {
html = this.getTabHtml(contentType);
offWidth = 300;
}
var ele = document.createElement('div');
ele.innerHTML = html;
ele = ele.childNodes[0];
document.body.appendChild(ele);
this.dragObj = this.overObj = ele;
if (!this.getTmpBoxElement()) return false;
var scroll = Util.getScroll();
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = e.clientX + scroll.l - 60 + "px";
this.dragObj.style.top = e.clientY + scroll.t - 10 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.style.cursor = 'move';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
this.newFlag = true;
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
document.onmouseup = function (e){Drag.prototype.dragEnd.call(_method, e);};
},
getFrameHtml : function (type) {
var id = 'frame'+Util.getRandom(6);
var className = [this.frameClass,this.moveableObject].join(' ');
className = className + ' cl frame-' + type;
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+this.titleClass+' '+this.frameTitleClass+'"><span class="'+this.titleTextClass+'">'+type+'框架</span></div>';
var cols = type.split('-');
var clsl='',clsc='',clsr='';
clsl = ' frame-'+type+'-l';
clsc = ' frame-'+type+'-c';
clsr = ' frame-'+type+'-r';
var len = cols.length;
if (len == 1) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsc+'"></div>';
} else if (len == 2) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+ '"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsr+ '"></div>';
} else if (len == 3) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+'"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsc+'"></div>';
str += '<div id="'+id+'_right" class="'+this.moveableColumn+clsr+'"></div>';
}
str += '</div>';
return str;
},
getTabHtml : function () {
var id = 'tab'+Util.getRandom(6);
var className = [this.tabClass,this.moveableObject].join(' ');
className = className + ' cl';
var titleClassName = [this.tabTitleClass, this.titleClass, this.moveableColumn, 'cl'].join(' ');
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+titleClassName+'"><span class="'+this.titleTextClass+'">tab标签</span></div>';
str += '<div id="'+id+'_content" class="'+this.tabContentClass+'"></div>';
str += '</div>';
return str;
},
getBlockHtml : function () {
var id = 'block'+Util.getRandom(6);
var str = '<div id="'+id+'" class="block move-span"></div>';
str += '</div>';
return str;
},
setClose : function () {
if(this.sampleMode) {
return true;
} else {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
spaceDiy.enablePreviewButton();
}
},
clearClose : function () {
this.isChange = false;
this.isClearClose = true;
window.onbeforeunload = function () {};
},
goonDIY : function () {
if ($('prefile').value == '1') {
showDialog('<div style="line-height:28px;">按继续按钮将打开暂存数据并DIY,<br />按删除按钮将删除暂存数据。</div>','confirm','是否继续暂存数据的DIY?', function(){location.replace(location.href+'&preview=yes');}, true, 'spaceDiy.cancelDIY()', '', '继续', '删除');
} else if (location.search.indexOf('preview=yes') > -1) {
spaceDiy.enablePreviewButton();
} else {
spaceDiy.disablePreviewButton();
}
setInterval(function(){spaceDiy.save('savecache', 1);},180000);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save : function (optype,rejs) {
optype = typeof optype == 'undefined' ? '' : optype;
if (optype == 'savecache' && !drag.isChange) {return false;}
var tplpre = document.diyform.template.value.split(':');
if (!optype) {
if (['portal/portal_topic_content', 'portal/list', 'portal/view'].indexOf(tplpre[0]) == -1) {
if (document.diyform.template.value.indexOf(':') > -1 && !document.selectsave) {
var schecked = '',dchecked = '';
if (document.diyform.savemod.value == '1') {
dchecked = ' checked';
} else {
schecked = ' checked';
}
showDialog('<form name="selectsave" action="" method="get"><label><input type="radio" value="0" name="savemod"'+schecked+' />应用于此类全部页面</label>\n\
<label><input type="radio" value="1" name="savemod"'+dchecked+' />只应用于本页面</label></form>','notice', '', spaceDiy.save);
return false;
}
if (document.selectsave) {
if (document.selectsave.savemod[0].checked) {
document.diyform.savemod.value = document.selectsave.savemod[0].value;
} else {
document.diyform.savemod.value = document.selectsave.savemod[1].value;
}
}
} else {
document.diyform.savemod.value = 1;
}
} else if (optype == 'savecache') {
if (!drag.isChange) return false;
this.checkPreview_form();
document.diyform.rejs.value = rejs ? 0 : 1;
} else if (optype =='preview') {
if (drag.isChange) {
optype = 'savecache';
} else {
this.checkPreview_form();
$('preview_form').submit();
return false;
}
}
document.diyform.action = document.diyform.action.replace(/[&|\?]inajax=1/, '');
document.diyform.optype.value = optype;
document.diyform.spacecss.value = spaceDiy.getSpacecssStr();
document.diyform.style.value = spaceDiy.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.gobackurl.value = spaceDiy.cancelDiyUrl();
drag.clearClose();
if (optype == 'savecache') {
document.diyform.handlekey.value = 'diyform';
ajaxpost('diyform','ajaxwaitid','ajaxwaitid','onerror');
} else {
saveUserdata('diy_advance_mode', '');
document.diyform.submit();
}
},
checkPreview_form : function () {
if (!$('preview_form')) {
var dom = document.createElement('div');
var search = '';
var sarr = location.search.replace('?','').split('&');
for (var i = 0;i<sarr.length;i++){
var kv = sarr[i].split('=');
if (kv.length>1 && kv[0] != 'diy') {
search += '<input type="hidden" value="'+kv[1]+'" name="'+kv[0]+'" />';
}
}
search += '<input type="hidden" value="yes" name="preview" />';
dom.innerHTML = '<form action="'+location.href+'" target="_bloak" method="get" id="preview_form">'+search+'</form>';
var form = dom.getElementsByTagName('form');
$('append_parent').appendChild(form[0]);
}
},
cancelDiyUrl : function () {
return location.href.replace(/[\?|\&]diy\=yes/g,'').replace(/[\?|\&]preview=yes/,'');
},
cancel : function () {
saveUserdata('diy_advance_mode', '');
if (drag.isClearClose) {
showDialog('<div style="line-height:28px;">是否保留暂存数据?<br />按确定按钮将保留暂存数据,按取消按钮将删除暂存数据。</div>','confirm','保留暂存数据', function(){location.href = spaceDiy.cancelDiyUrl();}, true, function(){window.onunload=function(){spaceDiy.cancelDIY()};location.href = spaceDiy.cancelDiyUrl();});
} else {
location.href = this.cancelDiyUrl();
}
},
recover : function() {
if (confirm('您确定要恢复到上一版本保存的结果吗?')) {
drag.clearClose();
document.diyform.recover.value = '1';
document.diyform.gobackurl.value = location.href.replace(/(\?diy=yes)|(\&diy=yes)/,'').replace(/[\?|\&]preview=yes/,'');
document.diyform.submit();
}
doane();
},
enablePreviewButton : function () {
if ($('preview')){
$('preview').className = '';
if(drag.isChange) {
$('diy_preview').onclick = function () {spaceDiy.save('savecache');return false;};
} else {
$('diy_preview').onclick = function () {spaceDiy.save('preview');return false;};
}
Util.show($('savecachemsg'))
}
},
disablePreviewButton : function () {
if ($('preview')) {
$('preview').className = 'unusable';
$('diy_preview').onclick = function () {return false;};
}
},
cancelDIY : function () {
this.disablePreviewButton();
document.diyform.optype.value = 'canceldiy';
var x = new Ajax();
x.post($('diyform').action+'&inajax=1','optype=canceldiy&diysubmit=1&template='+document.diyform.template.value+'&savemod='+document.diyform.savemod.value+'&formhash='+document.diyform.formhash.value+'&tpldirectory='+document.diyform.tpldirectory.value+'&diysign='+document.diyform.diysign.value,function(s){});
},
switchBlockclass : function(blockclass) {
var navs = $('contentblockclass_nav').getElementsByTagName('a');
var contents = $('contentblockclass').getElementsByTagName('ul');
for(var i=0; i<navs.length; i++) {
if(navs[i].id=='bcnav_'+blockclass) {
navs[i].className = 'a';
} else {
navs[i].className = '';
}
}
for(var i=0; i<contents.length; i++) {
if(contents[i].id=='contentblockclass_'+blockclass) {
contents[i].style.display = '';
} else {
contents[i].style.display = 'none';
}
}
},
getdiy : function (type) {
if (type) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
var contentid = 'content'+nav[i].id.replace('nav', '');
if ($(contentid)) $(contentid).style.display = 'none';
}
}
$('nav'+type).className = 'current';
if (type == 'start' || type == 'frame') {
$('content'+type).style.display = 'block';
return true;
}
if(type == 'blockclass' && $('content'+type).innerHTML !='') {
$('content'+type).style.display = 'block';
return true;
}
var para = '&op='+type;
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'diy' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('portal.php?mod=portalcp&ac=diy'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s, x) {
if (s) {
if (typeof cpb_frame == 'object' && !BROWSER.ie) {delete cpb_frame;}
if (!$('content'+type)) {
var dom = document.createElement('div');
dom.id = 'content'+type;
$('controlcontent').appendChild(dom);
}
$('content'+type).innerHTML = s;
$('content'+type).style.display = 'block';
if (type == 'diy') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
}
});
spaceDiy.init(1);
function succeedhandle_diyform (url, message, values) {
if (values['rejs'] == '1') {
document.diyform.rejs.value = '';
parent.$('preview_form').submit();
}
spaceDiy.enablePreviewButton();
return false;
} | JavaScript |
/*
A simple class for displaying file information and progress
Note: This is a demonstration only and not part of SWFUpload.
Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/
function FileProgress(file, targetID) {
this.fileProgressID = file.id;
this.opacity = 100;
this.height = 0;
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.reset();
}
this.height = this.fileProgressWrapper.offsetHeight;
this.setTimer(null);
}
FileProgress.prototype.setTimer = function (timer) {
this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
return this.fileProgressElement["FP_TIMER"] || null;
};
FileProgress.prototype.reset = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[2].innerHTML = " ";
this.fileProgressElement.childNodes[2].className = "progressBarStatus";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = "0%";
this.appear();
};
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
this.appear();
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "progressContainer blue";
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 5000));
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfUploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfUploadInstance.cancelUpload(fileID);
return false;
};
}
};
FileProgress.prototype.appear = function () {
if (this.getTimer() !== null) {
clearTimeout(this.getTimer());
this.setTimer(null);
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
} catch (e) {
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
}
} else {
this.fileProgressWrapper.style.opacity = 1;
}
this.fileProgressWrapper.style.height = "";
this.height = this.fileProgressWrapper.offsetHeight;
this.opacity = 100;
this.fileProgressWrapper.style.display = "";
};
FileProgress.prototype.disappear = function () {
var reduceOpacityBy = 15;
var reduceHeightBy = 4;
var rate = 30; // 15 fps
if (this.opacity > 0) {
this.opacity -= reduceOpacityBy;
if (this.opacity < 0) {
this.opacity = 0;
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
} catch (e) {
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
}
} else {
this.fileProgressWrapper.style.opacity = this.opacity / 100;
}
}
if (this.height > 0) {
this.height -= reduceHeightBy;
if (this.height < 0) {
this.height = 0;
}
this.fileProgressWrapper.style.height = this.height + "px";
}
if (this.height > 0 || this.opacity > 0) {
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, rate));
} else {
this.fileProgressWrapper.style.display = "none";
this.setTimer(null);
}
}; | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: imgcropper.js 30998 2012-07-06 07:22:08Z zhangguosheng $
*/
(function(){
ImgCropper = function() {
this.options = {
opacity: 50,
color: "",
width: 0,
height: 0,
resize: false,
right: "",
left: "",
up: "",
down: "",
rightDown: "",
leftDown: "",
rightUp: "",
leftUp: "",
min: false,
minWidth: 50,
minHeight: 50,
scale: false,
ratio: 0,
Preview: "",
viewWidth: 0,
viewHeight: 0
};
this.setParameter.apply(this, arguments);
};
ImgCropper.prototype = {
setParameter: function(container, handle, url, options) {
this._container = $(container);
this._layHandle = $(handle);
this.url = url;
this._layBase = this._container.appendChild(document.createElement("img"));
this._layCropper = this._container.appendChild(document.createElement("img"));
this._layCropper.onload = Util.bindApply(this, this.setPos);
this._tempImg = document.createElement("img");
this._tempImg.onload = Util.bindApply(this, this.setSize);
this.options = Util.setOptions(this.options, options || {});
this.opacity = Math.round(this.options.opacity);
this.color = this.options.color;
this.scale = !!this.options.scale;
this.ratio = Math.max(this.options.ratio, 0);
this.width = Math.round(this.options.width);
this.height = Math.round(this.options.height);
this.setLayHandle = true;
var oPreview = $(this.options.Preview);
if(oPreview){
oPreview.style.position = "relative";
oPreview.style.overflow = "hidden";
this.viewWidth = Math.round(this.options.viewWidth);
this.viewHeight = Math.round(this.options.viewHeight);
this._view = oPreview.appendChild(document.createElement("img"));
this._view.style.position = "absolute";
this._view.onload = Util.bindApply(this, this.SetPreview);
}
this._drag = new dzDrag(handle, {limit:true, container:container, onDragMove: Util.bindApply(this, this.setPos)});
this.resize = !!this.options.resize;
if(this.resize){
var op = this.options;
var _resize = new ImgCropperResize(container, {max: false, scale:true, min:true, minWidth:options.minWidth, minHeight:options.minHeight, onResize: Util.bindApply(this, this.scaleImg)});
op.rightDown && (_resize.set(op.rightDown, "right-down"));
op.leftDown && (_resize.set(op.leftDown, "left-down"));
op.rightUp && (_resize.set(op.rightUp, "right-up"));
op.leftUp && (_resize.set(op.leftUp, "left-up"));
op.right && (_resize.set(op.right, "right"));
op.left && (_resize.set(op.left, "left"));
op.down && (_resize.set(op.down, "down"));
op.up && (_resize.set(op.up, "up"));
this.min = !!this.options.min;
this.minWidth = Math.round(this.options.minWidth);
this.minHeight = Math.round(this.options.minHeight);
this._resize = _resize;
}
this._container.style.position = "relative";
this._container.style.overflow = "hidden";
this._layHandle.style.zIndex = 200;
this._layCropper.style.zIndex = 100;
this._layBase.style.position = this._layCropper.style.position = "absolute";
this._layBase.style.top = this._layBase.style.left = this._layCropper.style.top = this._layCropper.style.left = 0;
this.initialize();
},
initialize: function() {
this.color && (this._container.style.backgroundColor = this.color);
this._tempImg.src = this._layBase.src = this._layCropper.src = this.url;
if(BROWSER.ie){
this._layBase.style.filter = "alpha(opacity:" + this.opacity + ")";
this._layHandle.style.filter = "alpha(opacity:0)";
this._layHandle.style.backgroundColor = "#FFF";
} else {
this._layBase.style.opacity = this.opacity / 100;
}
this._view && (this._view.src = this.url);
if(this.resize){
with(this._resize){
Scale = this.scale; Ratio = this.ratio; Min = this.min; minWidth = this.minWidth; minHeight = this.minHeight;
}
}
},
setPos: function() {
if(BROWSER.ie == 6.0){ with(this._layHandle.style){ zoom = .9; zoom = 1; }; };
var p = this.getPos();
this._layCropper.style.clip = "rect(" + p.Top + "px " + (p.Left + p.Width) + "px " + (p.Top + p.Height) + "px " + p.Left + "px)";
this.SetPreview();
parent.resetHeight(this._container, this.getPos(), this._layBase);
},
scaleImg:function() {
this.height = this._resize._styleHeight;
this.width = this._resize._styleWidth;
this.initialize();
this.setSize();
this.setPos();
var maxRight = (parseInt(this._layHandle.style.left) || 0) + (parseInt(this._layHandle.offsetWidth) || 0);
var maxBottom = (parseInt(this._layHandle.style.top) || 0) + (parseInt(this._layHandle.offsetHeight) || 0);
if(this._container != null) {
if(maxRight > this._container.clientWidth) {
var nowLeft = this._container.clientWidth - this._layHandle.offsetWidth;
this._layHandle.style.left = (nowLeft < 0 ? 0 : nowLeft) + "px";
}
if(maxBottom > this._container.clientHeight) {
var nowTop = this._container.clientHeight - this._layHandle.offsetHeight;
this._layHandle.style.top = (nowTop < 0 ? 0 : nowTop) + "px";
}
}
parent.resetHeight(this._container, this.getPos(), this._layBase);
},
SetPreview: function() {
if(this._view){
var p = this.getPos(), s = this.getSize(p.Width, p.Height, this.viewWidth, this.viewHeight), scale = s.Height / p.Height;
var pHeight = this._layBase.height * scale, pWidth = this._layBase.width * scale, pTop = p.Top * scale, pLeft = p.Left * scale;
with(this._view.style){
width = pWidth + "px"; height = pHeight + "px"; top = - pTop + "px "; left = - pLeft + "px";
clip = "rect(" + pTop + "px " + (pLeft + s.Width) + "px " + (pTop + s.Height) + "px " + pLeft + "px)";
}
}
},
setSize: function() {
if(this.width > this._tempImg.width) {
this.width = this._tempImg.width;
}
if(this.height > this._tempImg.height) {
this.height = this._tempImg.height;
}
var s = this.getSize(this._tempImg.width, this._tempImg.height, this.width, this.height);
if(this.options.min && (s.Width <= this.options.minWidth || s.Height <= this.options.minHeight)) {
return false;
}
this._layBase.style.width = this._layCropper.style.width = s.Width + "px";
this._layBase.style.height = this._layCropper.style.height = s.Height + "px";
this._drag.maxRight = s.Width; this._drag.maxBottom = s.Height;
if(this.resize) {
this._container.style.width = this._layBase.style.width; this._container.style.height = this._layBase.style.height;
if(this.setLayHandle) {
this._layHandle.style.left = ((s.Width - this._layHandle.offsetWidth)/2)+"px";
this._layHandle.style.top = ((s.Height - this._layHandle.offsetHeight)/2)+"px";
this.setPos();
this.setLayHandle = false;
}
}
},
getPos: function() {
with(this._layHandle){
return { Top: offsetTop, Left: offsetLeft, Width: offsetWidth, Height: offsetHeight };
}
},
getSize: function(nowWidth, nowHeight, fixWidth, fixHeight) {
var iWidth = nowWidth, iHeight = nowHeight, scale = iWidth / iHeight;
if(fixHeight){ iWidth = (iHeight = fixHeight) * scale; }
if(fixWidth && (!fixHeight || iWidth > fixWidth)){ iHeight = (iWidth = fixWidth) / scale; }
return { Width: iWidth, Height: iHeight }
}
};
ImgCropperResize = function() {
this.options = {
max: false,
container: "",
maxLeft: 0,
maxRight: 9999,
maxTop: 0,
maxBottom: 9999,
min: false,
minWidth: 50,
minHeight: 50,
scale: false,
ratio: 0,
onResize: function(){}
};
this.initialize.apply(this, arguments);
};
ImgCropperResize.prototype = {
initialize: function(resizeObjId, options) {
this.options = Util.setOptions(this.options, options || {});
this._resizeObj = $(resizeObjId);
this._styleWidth = this._styleHeight = this._styleLeft = this._styleTop = 0;
this._sideRight = this._sideDown = this._sideLeft = this._sideUp = 0;
this._fixLeft = this._fixTop = 0;
this._scaleLeft = this._scaleTop = 0;
this._maxSet = function(){};
this._maxRightWidth = this._maxDownHeight = this._maxUpHeight = this._maxLeftWidth = 0;
this._maxScaleWidth = this._maxScaleHeight = 0;
this._fun = function(){};
var _style = Util.currentStyle(this._resizeObj);
this._borderX = (parseInt(_style.borderLeftWidth) || 0) + (parseInt(_style.borderRightWidth) || 0);
this._borderY = (parseInt(_style.borderTopWidth) || 0) + (parseInt(_style.borderBottomWidth) || 0);
this._resizeTranscript = Util.bindApply(this, this.resize);
this._stopTranscript = Util.bindApply(this, this.stop);
this.max = !!this.options.max;
this._container = $(this.options.container) || null;
this.maxLeft = Math.round(this.options.maxLeft);
this.maxRight = Math.round(this.options.maxRight);
this.maxTop = Math.round(this.options.maxTop);
this.maxBottom = Math.round(this.options.maxBottom);
this.min = !!this.options.min;
this.minWidth = Math.round(this.options.minWidth);
this.minHeight = Math.round(this.options.minHeight);
this.scale = !!this.options.scale;
this.ratio = Math.max(this.options.ratio, 0);
this.onResize = this.options.onResize;
this._resizeObj.style.position = "absolute";
!this._container || Util.currentStyle(this._container).position == "relative" || (this._container.style.position = "relative");
},
set: function(resize, side) {
var resize = $(resize), fun;
if(!resize) return;
switch(side.toLowerCase()) {
case "up":
fun = this.up;
break;
case "down":
fun = this.down;
break;
case "left":
fun = this.left;
break;
case "right":
fun = this.right;
break;
case "left-up":
fun = this.leftUp;
break;
case "right-up":
fun = this.rightUp;
break;
case "left-down":
fun = this.leftDown;
break;
case "right-down" :
default:
fun = this.rightDown;
break;
};
Util.addEventHandler(resize, "mousedown", Util.bindApply(this, this.start, fun));
},
start: function(oEvent, fun, touch) {
oEvent.stopPropagation ? oEvent.stopPropagation() : (oEvent.cancelBubble = true);
this._fun = fun;
this._styleWidth = this._resizeObj.clientWidth;
this._styleHeight = this._resizeObj.clientHeight;
this._styleLeft = this._resizeObj.offsetLeft;
this._styleTop = this._resizeObj.offsetTop;
this._sideLeft = oEvent.clientX - this._styleWidth;
this._sideRight = oEvent.clientX + this._styleWidth;
this._sideUp = oEvent.clientY - this._styleHeight;
this._sideDown = oEvent.clientY + this._styleHeight;
this._fixLeft = this._styleLeft + this._styleWidth;
this._fixTop = this._styleTop + this._styleHeight;
if(this.scale) {
this.ratio = Math.max(this.ratio, 0) || this._styleWidth / this._styleHeight;
this._scaleLeft = this._styleLeft + this._styleWidth / 2;
this._scaleTop = this._styleTop + this._styleHeight / 2;
};
if(this.max) {
var maxLeft = this.maxLeft, maxRight = this.maxRight, maxTop = this.maxTop, maxBottom = this.maxBottom;
if(!!this._container){
maxLeft = Math.max(maxLeft, 0);
maxTop = Math.max(maxTop, 0);
maxRight = Math.min(maxRight, this._container.clientWidth);
maxBottom = Math.min(maxBottom, this._container.clientHeight);
};
maxRight = Math.max(maxRight, maxLeft + (this.min ? this.minWidth : 0) + this._borderX);
maxBottom = Math.max(maxBottom, maxTop + (this.min ? this.minHeight : 0) + this._borderY);
this._mxSet = function() {
this._maxRightWidth = maxRight - this._styleLeft - this._borderX;
this._maxDownHeight = maxBottom - this._styleTop - this._borderY;
this._maxUpHeight = Math.max(this._fixTop - maxTop, this.min ? this.minHeight : 0);
this._maxLeftWidth = Math.max(this._fixLeft - maxLeft, this.min ? this.minWidth : 0);
};
this._mxSet();
if(this.scale) {
this._maxScaleWidth = Math.min(this._scaleLeft - maxLeft, maxRight - this._scaleLeft - this._borderX) * 2;
this._maxScaleHeight = Math.min(this._scaleTop - maxTop, maxBottom - this._scaleTop - this._borderY) * 2;
}
}
Util.addEventHandler(document, "mousemove", this._resizeTranscript);
Util.addEventHandler(document, "mouseup", this._stopTranscript);
if(BROWSER.ie){
Util.addEventHandler(this._resizeObj, "losecapture", this._stopTranscript);
this._resizeObj.setCapture();
}else{
Util.addEventHandler(window, "blur", this._stopTranscript);
oEvent.preventDefault();
};
},
resize: function(e) {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
this._fun(e);
if(this.options.min && (this._styleWidth <= this.options.minWidth || this._styleHeight <= this.options.minHeight)) {
return false;
}
with(this._resizeObj.style) {
width = this._styleWidth + "px"; height = this._styleHeight + "px";
top = this._styleTop + "px"; left = this._styleLeft + "px";
}
this.onResize();
},
up: function(e) {
this.repairY(this._sideDown - e.clientY, this._maxUpHeight);
this.repairTop();
this.turnDown(this.down);
},
down: function(e) {
this.repairY(e.clientY - this._sideUp, this._maxDownHeight);
this.turnUp(this.up);
},
right: function(e) {
this.repairX(e.clientX - this._sideLeft, this._maxRightWidth);
this.turnLeft(this.left);
},
left: function(e) {
this.repairX(this._sideRight - e.clientX, this._maxLeftWidth);
this.repairLeft();
this.turnRight(this.right);
},
rightDown: function(e) {
this.repairAngle(
e.clientX - this._sideLeft, this._maxRightWidth,
e.clientY - this._sideUp, this._maxDownHeight
);
this.turnLeft(this.leftDown) || this.scale || this.turnUp(this.rightUp);
},
rightUp: function(e) {
this.repairAngle(
e.clientX - this._sideLeft, this._maxRightWidth,
this._sideDown - e.clientY, this._maxUpHeight
);
this.repairTop();
this.turnLeft(this.leftUp) || this.scale || this.turnDown(this.rightDown);
},
leftDown: function(e) {
this.repairAngle(
this._sideRight - e.clientX, this._maxLeftWidth,
e.clientY - this._sideUp, this._maxDownHeight
);
this.repairLeft();
this.turnRight(this.rightDown) || this.scale || this.turnUp(this.leftUp);
},
leftUp: function(e) {
this.repairAngle(
this._sideRight - e.clientX, this._maxLeftWidth,
this._sideDown - e.clientY, this._maxUpHeight
);
this.repairTop();
this.repairLeft();
this.turnRight(this.rightUp) || this.scale || this.turnDown(this.leftDown);
},
repairX: function(iWidth, maxWidth) {
iWidth = this.repairWidth(iWidth, maxWidth);
if(this.scale){
var iHeight = this.repairScaleHeight(iWidth);
if(this.max && iHeight > this._maxScaleHeight){
iHeight = this._maxScaleHeight;
iWidth = this.repairScaleWidth(iHeight);
}else if(this.min && iHeight < this.minHeight){
var tWidth = this.repairScaleWidth(this.minHeight);
if(tWidth < maxWidth){ iHeight = this.minHeight; iWidth = tWidth; }
}
this._styleHeight = iHeight;
this._styleTop = this._scaleTop - iHeight / 2;
}
this._styleWidth = iWidth;
},
repairY: function(iHeight, maxHeight) {
iHeight = this.repairHeight(iHeight, maxHeight);
if(this.scale){
var iWidth = this.repairScaleWidth(iHeight);
if(this.max && iWidth > this._maxScaleWidth){
iWidth = this._maxScaleWidth;
iHeight = this.repairScaleHeight(iWidth);
}else if(this.min && iWidth < this.minWidth){
var tHeight = this.repairScaleHeight(this.minWidth);
if(tHeight < maxHeight){ iWidth = this.minWidth; iHeight = tHeight; }
}
this._styleWidth = iWidth;
this._styleLeft = this._scaleLeft - iWidth / 2;
}
this._styleHeight = iHeight;
},
repairAngle: function(iWidth, maxWidth, iHeight, maxHeight) {
iWidth = this.repairWidth(iWidth, maxWidth);
if(this.scale) {
iHeight = this.repairScaleHeight(iWidth);
if(this.max && iHeight > maxHeight){
iHeight = maxHeight;
iWidth = this.repairScaleWidth(iHeight);
}else if(this.min && iHeight < this.minHeight){
var tWidth = this.repairScaleWidth(this.minHeight);
if(tWidth < maxWidth){ iHeight = this.minHeight; iWidth = tWidth; }
}
} else {
iHeight = this.repairHeight(iHeight, maxHeight);
}
this._styleWidth = iWidth;
this._styleHeight = iHeight;
},
repairTop: function() {
this._styleTop = this._fixTop - this._styleHeight;
},
repairLeft: function() {
this._styleLeft = this._fixLeft - this._styleWidth;
},
repairHeight: function(iHeight, maxHeight) {
iHeight = Math.min(this.max ? maxHeight : iHeight, iHeight);
iHeight = Math.max(this.min ? this.minHeight : iHeight, iHeight, 0);
return iHeight;
},
repairWidth: function(iWidth, maxWidth) {
iWidth = Math.min(this.max ? maxWidth : iWidth, iWidth);
iWidth = Math.max(this.min ? this.minWidth : iWidth, iWidth, 0);
return iWidth;
},
repairScaleHeight: function(iWidth) {
return Math.max(Math.round((iWidth + this._borderX) / this.ratio - this._borderY), 0);
},
repairScaleWidth: function(iHeight) {
return Math.max(Math.round((iHeight + this._borderY) * this.ratio - this._borderX), 0);
},
turnRight: function(fun) {
if(!(this.min || this._styleWidth)){
this._fun = fun;
this._sideLeft = this._sideRight;
this.max && this._mxSet();
return true;
}
},
turnLeft: function(fun) {
if(!(this.min || this._styleWidth)){
this._fun = fun;
this._sideRight = this._sideLeft;
this._fixLeft = this._styleLeft;
this.max && this._mxSet();
return true;
}
},
turnUp: function(fun) {
if(!(this.min || this._styleHeight)){
this._fun = fun;
this._sideDown = this._sideUp;
this._fixTop = this._styleTop;
this.max && this._mxSet();
return true;
}
},
turnDown: function(fun) {
if(!(this.min || this._styleHeight)){
this._fun = fun;
this._sideUp = this._sideDown;
this.max && this._mxSet();
return true;
}
},
stop: function() {
Util.removeEventHandler(document, "mousemove", this._resizeTranscript);
Util.removeEventHandler(document, "mouseup", this._stopTranscript);
if(BROWSER.ie){
Util.removeEventHandler(this._resizeObj, "losecapture", this._stopTranscript);
this._resizeObj.releaseCapture();
}else{
Util.removeEventHandler(window, "blur", this._stopTranscript);
}
}
};
dzDrag = function() {
this.options = {
handle: '',
limit: false,
maxLeft: 0,
maxRight: 9999,
maxTop: 0,
maxBottom: 9999,
container: '',
lockX: false,
lockY: false,
onDragStart: function(){},
onDragMove: function(){},
onDragEnd: function(){}
};
this.initialize.apply(this, arguments);
};
dzDrag.prototype = {
initialize: function(dragId, options) {
this.options = Util.setOptions(this.options, options || {});
this._dragObj = $(dragId);
this._x = this._y = 0;
this._marginLeft = this._marginTop = 0;
this._handle = $(this.options.handle) || this._dragObj;
this._container = $(this.options.container) || null;
this._dragObj.style.position = "absolute";
this._dragEndTranscript = Util.bindApply(this, this.dragEnd);
this._dragMoveTranscript = Util.bindApply(this, this.dragMove);
Util.addEventHandler(this._handle, "mousedown", Util.bindApply(this, this.dragStart));
},
dragStart: function(event) {
this.setLimit();
this._x = event.clientX - this._dragObj.offsetLeft;
this._y = event.clientY - this._dragObj.offsetTop;
var curStyle = Util.currentStyle(this._dragObj);
this._marginLeft = parseInt(curStyle.marginLeft) || 0;
this._marginTop = parseInt(curStyle.marginTop) || 0;
Util.addEventHandler(document, "mousemove", this._dragMoveTranscript);
Util.addEventHandler(document, "mouseup", this._dragEndTranscript);
if(BROWSER.ie){
Util.addEventHandler(this._handle, "losecapture", this._dragEndTranscript);
this._handle.setCapture();
}else{
Util.addEventHandler(window, "blur", this._dragEndTranscript);
event.preventDefault();
};
this.options.onDragStart();
},
dragMove: function(event) {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
var iLeft = event.clientX - this._x;
var iTop = event.clientY - this._y;
if(this.options.limit) {
var maxLeft = this.options.maxLeft, maxRight = this.options.maxRight, maxTop = this.options.maxTop, maxBottom = this.options.maxBottom;
if(this._container != null){
maxLeft = Math.max(maxLeft, 0);
maxTop = Math.max(maxTop, 0);
maxRight = Math.min(maxRight, this._container.clientWidth);
maxBottom = Math.min(maxBottom, this._container.clientHeight);
};
iLeft = Math.max(Math.min(iLeft, maxRight - this._dragObj.offsetWidth), maxLeft);
iTop = Math.max(Math.min(iTop, maxBottom - this._dragObj.offsetHeight), maxTop);
}
if(!this.options.lockX) { this._dragObj.style.left = iLeft - this._marginLeft + "px"; }
if(!this.options.lockY) { this._dragObj.style.top = iTop - this._marginTop + "px"; }
this.options.onDragMove();
},
dragEnd: function(event) {
Util.removeEventHandler(document, "mousemove", this._dragMoveTranscript);
Util.removeEventHandler(document, "mouseup", this._dragEndTranscript);
if(BROWSER.ie) {
Util.removeEventHandler(this._handle, "losecapture", this._dragEndTranscript);
this._handle.releaseCapture();
} else {
Util.removeEventHandler(window, "blur", this._dragEndTranscript);
}
this.options.onDragEnd();
},
setLimit: function() {
if(this.options.limit) {
this.options.maxRight = Math.max(this.options.maxRight, this.options.maxLeft + this._dragObj.offsetWidth);
this.options.maxBottom = Math.max(this.options.maxBottom, this.options.maxTop + this._dragObj.offsetHeight);
!this._container || Util.currentStyle(this._container).position == "relative" || Util.currentStyle(this._container).position == "absolute" || (this._container.style.position = "relative");
}
}
};
var Util = {
setOptions: function(object, source) {
for(var property in source) {
object[property] = source[property];
}
return object;
},
addEventHandler: function(targetObj, eventType, funHandler) {
if(targetObj.addEventListener) {
targetObj.addEventListener(eventType, funHandler, false);
} else if (targetObj.attachEvent) {
targetObj.attachEvent("on" + eventType, funHandler);
} else {
targetObj["on" + eventType] = funHandler;
}
},
removeEventHandler: function(targetObj, eventType, funHandler) {
if(targetObj.removeEventListener) {
targetObj.removeEventListener(eventType, funHandler, false);
} else if (targetObj.detachEvent) {
targetObj.detachEvent("on" + eventType, funHandler);
} else {
targetObj["on" + eventType] = null;
}
},
bindApply: function(object, fun) {
var args = Array.prototype.slice.call(arguments).slice(2);
return function(event) {
return fun.apply(object, [event || window.event].concat(args));
};
},
currentStyle: function(element){
return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_extra.js 31722 2012-09-25 03:22:12Z zhangguosheng $
*/
function _relatedlinks(rlinkmsgid) {
if(!$(rlinkmsgid) || $(rlinkmsgid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var alink = new Array(), ignore = new Array();
var i = 0;
var msg = $(rlinkmsgid).innerHTML;
msg = msg.replace(/(<ignore_js_op\>[\s|\S]*?<\/ignore_js_op\>)/ig, function($1) {
ignore[i] = $1;
i++;
return '#ignore_js_op '+(i - 1)+'#';
});
var alink_i = 0;
msg = msg.replace(/(<a.*?<\/a\>)/ig, function($1) {
alink[alink_i] = $1;
alink_i++;
return '#alink '+(alink_i - 1)+'#';
});
var relatedid = new Array();
msg = msg.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
for(var j = 0; j < relatedlink.length; j++) {
if(relatedlink[j] && !relatedid[j]) {
if(relatedlink[j]['surl'] != '') {
var ra = '<a href="'+relatedlink[j]['surl']+'" target="_blank" class="relatedlink">'+relatedlink[j]['sname']+'</a>';
alink[alink_i] = ra;
ra = '#alink '+alink_i+'#';
alink_i++;
} else {
var ra = '<strong><font color="#FF0000">'+relatedlink[j]['sname']+'</font></strong>';
}
var $rtmp = $3;
$3 = $3.replace(relatedlink[j]['sname'], ra);
if($3 != $rtmp) {
relatedid[j] = 1;
}
}
}
return $2 + $3;
});
for(var k in alink) {
msg = msg.replace('#alink '+k+'#', alink[k]);
}
for(var l in ignore) {
msg = msg.replace('#ignore_js_op '+l+'#', ignore[l]);
}
$(rlinkmsgid).innerHTML = msg;
}
function _updatesecqaa(idhash) {
if($('secqaa_' + idhash)) {
$('secqaaverify_' + idhash).value = '';
if(secST['qaa_' + idhash]) {
clearTimeout(secST['qaa_' + idhash]);
}
$('checksecqaaverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=secqaa&action=update&idhash=' + idhash, 'secqaa_' + idhash, null, '', '', function() {
secST['qaa_' + idhash] = setTimeout(function() {$('secqaa_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updatesecqaa(\''+idhash+'\')">刷新验证问答</span>';}, 180000);
});
}
}
function _updateseccode(idhash, play) {
if(isUndefined(play)) {
if($('seccode_' + idhash)) {
$('seccodeverify_' + idhash).value = '';
if(secST['code_' + idhash]) {
clearTimeout(secST['code_' + idhash]);
}
$('checkseccodeverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=seccode&action=update&idhash=' + idhash, 'seccode_' + idhash, null, '', '', function() {
secST['code_' + idhash] = setTimeout(function() {$('seccode_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updateseccode(\''+idhash+'\')">刷新验证码</span>';}, 180000);
});
}
} else {
eval('window.document.seccodeplayer_' + idhash + '.SetVariable("isPlay", "1")');
}
}
function _checksec(type, idhash, showmsg, recall) {
var showmsg = !showmsg ? 0 : showmsg;
var secverify = $('sec' + type + 'verify_' + idhash).value;
if(!secverify) {
return;
}
var x = new Ajax('XML', 'checksec' + type + 'verify_' + idhash);
x.loading = '';
$('checksec' + type + 'verify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" />';
x.get('misc.php?mod=sec' + type + '&action=check&inajax=1&&idhash=' + idhash + '&secverify=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(secverify) : secverify), function(s){
var obj = $('checksec' + type + 'verify_' + idhash);
obj.style.display = '';
if(s.substr(0, 7) == 'succeed') {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
if(showmsg) {
recall(1);
}
} else {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_error.gif" width="16" height="16" class="vm" />';
if(showmsg) {
if(type == 'code') {
showError('验证码错误,请重新填写');
} else if(type == 'qaa') {
showError('验证问答错误,请重新填写');
}
recall(0);
}
}
});
}
function _setDoodle(fid, oid, url, tid, from) {
if(tid == null) {
hideWindow(fid);
} else {
$(tid).style.display = '';
$(fid).style.display = 'none';
}
var doodleText = '[img]'+url+'[/img]';
if($(oid) != null) {
if(from == "editor") {
insertImage(url);
} else if(from == "fastpost") {
seditor_insertunit('fastpost', doodleText);
} else if(from == "forumeditor") {
if(wysiwyg) {
insertText('<img src="' + url + '" border="0" alt="" />', false);
} else {
insertText(doodleText, strlen(doodleText), 0);
}
} else {
insertContent(oid, doodleText);
}
}
}
function _showdistrict(container, elems, totallevel, changelevel, containertype) {
var getdid = function(elem) {
var op = elem.options[elem.selectedIndex];
return op['did'] || op.getAttribute('did') || '0';
};
var pid = changelevel >= 1 && elems[0] && $(elems[0]) ? getdid($(elems[0])) : 0;
var cid = changelevel >= 2 && elems[1] && $(elems[1]) ? getdid($(elems[1])) : 0;
var did = changelevel >= 3 && elems[2] && $(elems[2]) ? getdid($(elems[2])) : 0;
var coid = changelevel >= 4 && elems[3] && $(elems[3]) ? getdid($(elems[3])) : 0;
var url = "home.php?mod=misc&ac=ajax&op=district&container="+container+"&containertype="+containertype
+"&province="+elems[0]+"&city="+elems[1]+"&district="+elems[2]+"&community="+elems[3]
+"&pid="+pid + "&cid="+cid+"&did="+did+"&coid="+coid+'&level='+totallevel+'&handlekey='+container+'&inajax=1'+(!changelevel ? '&showdefault=1' : '');
ajaxget(url, container, '');
}
function _copycode(obj) {
if(!obj) return false;
if(window.getSelection) {
var sel = window.getSelection();
if (sel.setBaseAndExtent) {
sel.setBaseAndExtent(obj, 0, obj, 1);
} else {
var rng = document.createRange();
rng.selectNodeContents(obj);
sel.addRange(rng);
}
} else {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.select();
}
setCopy(BROWSER.ie ? obj.innerText.replace(/\r\n\r\n/g, '\r\n') : obj.textContent, '代码已复制到剪贴板');
}
function _setCopy(text, msg){
if(BROWSER.ie) {
var r = clipboardData.setData('Text', text);
if(r) {
if(msg) {
showPrompt(null, null, '<span>' + msg + '</span>', 1500);
}
} else {
showDialog('<div class="c"><div style="width: 200px; text-align: center;">复制失败,请选择“允许访问”</div></div>', 'alert');
}
} else {
var msg = '<div class="c"><div style="width: 200px; text-align: center; text-decoration:underline;">点此复制到剪贴板</div>' +
AC_FL_RunContent('id', 'clipboardswf', 'name', 'clipboardswf', 'devicefont', 'false', 'width', '200', 'height', '40', 'src', STATICURL + 'image/common/clipboard.swf', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true', 'wmode', 'transparent', 'style' , 'margin-top:-20px') + '</div>';
showDialog(msg, 'info');
text = text.replace(/[\xA0]/g, ' ');
CLIPBOARDSWFDATA = text;
}
}
function _showselect(obj, inpid, t, rettype) {
var showselect_row = function (inpid, s, v, notime, rettype) {
if(v >= 0) {
if(!rettype) {
var notime = !notime ? 0 : 1;
var t = today.getTime();
t += 86400000 * v;
var d = new Date();
d.setTime(t);
var month = d.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var day = d.getDate();
day = day < 10 ? '0' + day : day;
var hour = d.getHours();
hour = hour < 10 ? '0' + hour : hour;
var minute = d.getMinutes();
minute = minute < 10 ? '0' + minute : minute;
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + d.getFullYear() + '-' + month + '-' + day + (!notime ? ' ' + hour + ':' + minute: '') + '\'">' + s + '</a>';
} else {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + v + '\'">' + s + '</a>';
}
} else if(v == -1) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').focus()">' + s + '</a>';
} else if(v == -2) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').onclick()">' + s + '</a>';
}
};
if(!obj.id) {
var t = !t ? 0 : t;
var rettype = !rettype ? 0 : rettype;
obj.id = 'calendarexp_' + Math.random();
div = document.createElement('div');
div.id = obj.id + '_menu';
div.style.display = 'none';
div.className = 'p_pop';
$('append_parent').appendChild(div);
s = '';
if(!t) {
s += showselect_row(inpid, '一天', 1, 0, rettype);
s += showselect_row(inpid, '一周', 7, 0, rettype);
s += showselect_row(inpid, '一个月', 30, 0, rettype);
s += showselect_row(inpid, '三个月', 90, 0, rettype);
s += showselect_row(inpid, '自定义', -2);
} else {
if($(t)) {
var lis = $(t).getElementsByTagName('LI');
for(i = 0;i < lis.length;i++) {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = this.innerHTML;$(\''+obj.id+'_menu\').style.display=\'none\'">' + lis[i].innerHTML + '</a>';
}
s += showselect_row(inpid, '自定义', -1);
} else {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'0\'">永久</a>';
s += showselect_row(inpid, '7 天', 7, 1, rettype);
s += showselect_row(inpid, '14 天', 14, 1, rettype);
s += showselect_row(inpid, '一个月', 30, 1, rettype);
s += showselect_row(inpid, '三个月', 90, 1, rettype);
s += showselect_row(inpid, '半年', 182, 1, rettype);
s += showselect_row(inpid, '一年', 365, 1, rettype);
s += showselect_row(inpid, '自定义', -1);
}
}
$(div.id).innerHTML = s;
}
showMenu({'ctrlid':obj.id,'evt':'click'});
if(BROWSER.ie && BROWSER.ie < 7) {
doane(event);
}
}
function _zoom(obj, zimg, nocover, pn, showexif) {
zimg = !zimg ? obj.src : zimg;
showexif = !parseInt(showexif) ? 0 : showexif;
if(!zoomstatus) {
window.open(zimg, '', '');
return;
}
if(!obj.id) obj.id = 'img_' + Math.random();
var faid = !obj.getAttribute('aid') ? 0 : obj.getAttribute('aid');
var menuid = 'imgzoom';
var menu = $(menuid);
var zoomid = menuid + '_zoom';
var imgtitle = !nocover && obj.title ? '<div class="imgzoom_title">' + obj.title + '</div>' +
(showexif ? '<div id="' + zoomid + '_exif" class="imgzoom_exif" onmouseover="this.className=\'imgzoom_exif imgzoom_exif_hover\'" onmouseout="this.className=\'imgzoom_exif\'"></div>' : '')
: '';
var cover = !nocover ? 1 : 0;
var pn = !pn ? 0 : 1;
var maxh = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - 70;
var loadCheck = function (obj) {
if(obj.complete) {
var imgw = loading.width;
var imgh = loading.height;
var r = imgw / imgh;
var w = document.body.clientWidth * 0.95;
w = imgw > w ? w : imgw;
var h = w / r;
if(w < 100 & h < 100) {
$(menuid + '_waiting').style.display = 'none';
hideMenu();
return;
}
if(h > maxh) {
h = maxh;
w = h * r;
}
if($(menuid)) {
$(menuid).removeAttribute('top_');$(menuid).removeAttribute('left_');
clearTimeout($(menuid).getAttribute('timer'));
}
showimage(zimg, w, h, imgw, imgh);
if(showexif && faid) {
var x = new Ajax();
x.get('forum.php?mod=ajax&action=exif&aid=' + faid + '&inajax=1', function(s, x) {
if(s) {
$(zoomid + '_exif').style.display = '';
$(zoomid + '_exif').innerHTML = s;
} else {
$(zoomid + '_exif').style.display = 'none';
}
});
}
} else {
setTimeout(function () { loadCheck(loading); }, 100);
}
};
var showloading = function (zimg, pn) {
if(!pn) {
if(!$(menuid + '_waiting')) {
waiting = document.createElement('img');
waiting.id = menuid + '_waiting';
waiting.src = IMGDIR + '/imageloading.gif';
waiting.style.opacity = '0.8';
waiting.style.filter = 'alpha(opacity=80)';
waiting.style.position = 'absolute';
waiting.style.zIndex = '100000';
$('append_parent').appendChild(waiting);
}
}
$(menuid + '_waiting').style.display = '';
$(menuid + '_waiting').style.left = (document.body.clientWidth - 42) / 2 + 'px';
$(menuid + '_waiting').style.top = ((document.documentElement.clientHeight - 42) / 2 + Math.max(document.documentElement.scrollTop, document.body.scrollTop)) + 'px';
loading = new Image();
setTimeout(function () { loadCheck(loading); }, 100);
if(!pn) {
$(menuid + '_zoomlayer').style.display = 'none';
}
loading.src = zimg;
};
var adjustpn = function(h) {
h = h < 90 ? 90 : h;
if($('zimg_prev')) {
$('zimg_prev').style.height= parseInt(h) + 'px';
}
if($('zimg_next')) {
$('zimg_next').style.height= parseInt(h) + 'px';
}
};
var showimage = function (zimg, w, h, imgw, imgh) {
$(menuid + '_waiting').style.display = 'none';
$(menuid + '_zoomlayer').style.display = '';
$(menuid + '_img').style.width = 'auto';
$(menuid + '_img').style.height = 'auto';
$(menuid).style.width = (w < 300 ? 320 : w + 20) + 'px';
mheight = h + 63;
menu.style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
$(menuid + '_img').innerHTML = '<img id="' + zoomid + '" src="' + zimg + '" width="' + w + '" height="' + h + '" w="' + imgw + '" h="' + imgh + '" />' + imgtitle;
if($(menuid + '_imglink')) {
$(menuid + '_imglink').href = zimg;
}
setMenuPosition('', menuid, '00');
adjustpn(h);
};
var adjustTimer = 0;
var adjustTimerCount = 0;
var wheelDelta = 0;
var clientX = 0;
var clientY = 0;
var adjust = function(e, a) {
if(BROWSER.ie && BROWSER.ie<7) {
} else {
if(adjustTimerCount) {
adjustTimer = (function(){
return setTimeout(function () {
adjustTimerCount++;
adjust(e);
}, 20);
})();
$(menuid).setAttribute('timer', adjustTimer);
if(adjustTimerCount > 17) {
clearTimeout(adjustTimer);
adjustTimerCount = 0;
doane();
}
} else if(!a) {
adjustTimerCount = 1;
if(adjustTimer) {
clearTimeout(adjustTimer);
adjust(e, a);
} else {
adjust(e, a);
}
doane();
}
}
var ele = $(zoomid);
if(!ele) {
return;
}
var imgw = ele.getAttribute('w');
var imgh = ele.getAttribute('h');
if(!a) {
e = e || window.event;
try {
if(e.altKey || e.shiftKey || e.ctrlKey) return;
} catch (e) {
e = {'wheelDelta':wheelDelta, 'clientX':clientX, 'clientY':clientY};
}
var step = 0;
if(e.wheelDelta <= 0 || e.detail > 0) {
if(ele.width - 1 <= 200 || ele.height - 1 <= 200) {
clearTimeout(adjustTimer);
adjustTimerCount = 0;
doane(e);return;
}
step = parseInt(imgw/ele.width)-4;
} else {
if(ele.width + 1 >= imgw*40) {
clearTimeout(adjustTimer);
adjustTimerCount = 0;
doane(e);return;
}
step = 4-parseInt(imgw/ele.width) || 2;
}
if(BROWSER.ie && BROWSER.ie<7) { step *= 5;}
wheelDelta = e.wheelDelta;
clientX = e.clientX;
clientY = e.clientY;
var ratio = 0;
if(imgw > imgh) {
ratio = step/ele.height;
ele.height += step;
ele.width = imgw*(ele.height/imgh);
} else if(imgw < imgh) {
ratio = step/ele.width;
ele.width += step;
ele.height = imgh*(ele.width/imgw);
}
if(BROWSER.ie && BROWSER.ie<7) {
setMenuPosition('', menuid, '00');
} else {
var menutop = parseFloat(menu.getAttribute('top_') || menu.style.top);
var menuleft = parseFloat(menu.getAttribute('left_') || menu.style.left);
var imgY = clientY - menutop - 39;
var imgX = clientX - menuleft - 10;
var newTop = (menutop - imgY*ratio) + 'px';
var newLeft = (menuleft - imgX*ratio) + 'px';
menu.style.top = newTop;
menu.style.left = newLeft;
menu.setAttribute('top_', newTop);
menu.setAttribute('left_', newLeft);
}
} else {
ele.width = imgw;
ele.height = imgh;
}
menu.style.width = (parseInt(ele.width < 300 ? 300 : parseInt(ele.width)) + 20) + 'px';
var mheight = (parseInt(ele.height) + 50);
menu.style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
adjustpn(ele.height);
doane(e);
};
if(!menu && !pn) {
menu = document.createElement('div');
menu.id = menuid;
if(cover) {
menu.innerHTML = '<div class="zoominner" id="' + menuid + '_zoomlayer" style="display:none"><p><span class="y"><a id="' + menuid + '_imglink" class="imglink" target="_blank" title="在新窗口打开">在新窗口打开</a><a id="' + menuid + '_adjust" href="javascipt:;" class="imgadjust" title="实际大小">实际大小</a>' +
'<a href="javascript:;" onclick="hideMenu()" class="imgclose" title="关闭">关闭</a></span>鼠标滚轮缩放图片</p>' +
'<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
} else {
menu.innerHTML = '<div class="popupmenu_popup" id="' + menuid + '_zoomlayer" style="width:auto"><span class="right y"><a href="javascript:;" onclick="hideMenu()" class="flbc" style="width:20px;margin:0 0 2px 0">关闭</a></span>鼠标滚轮缩放图片<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
}
if(BROWSER.ie || BROWSER.chrome){
menu.onmousewheel = adjust;
} else {
menu.addEventListener('DOMMouseScroll', adjust, false);
}
$('append_parent').appendChild(menu);
if($(menuid + '_adjust')) {
$(menuid + '_adjust').onclick = function(e) {adjust(e, 1)};
}
}
showloading(zimg, pn);
picpage = '';
$(menuid + '_picpage').innerHTML = '';
if(typeof zoomgroup == 'object' && zoomgroup[obj.id] && typeof aimgcount == 'object' && aimgcount[zoomgroup[obj.id]]) {
authorimgs = aimgcount[zoomgroup[obj.id]];
var aid = obj.id.substr(5), authorlength = authorimgs.length, authorcurrent = '';
if(authorlength > 1) {
for(i = 0; i < authorlength;i++) {
if(aid == authorimgs[i]) {
authorcurrent = i;
}
}
if(authorcurrent !== '') {
paid = authorcurrent > 0 ? authorimgs[authorcurrent - 1] : authorimgs[authorlength - 1];
picpage += ' <div id="zimg_prev" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'0 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'0 -100px\';" onclick="_zoom_page(\'' + paid + '\', ' + (showexif ? 1 : 0) + ')" class="zimg_prev"><strong>上一张</strong></div> ';
paid = authorcurrent < authorlength - 1 ? authorimgs[authorcurrent + 1] : authorimgs[0];
picpage += ' <div id="zimg_next" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'100% 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'100% -100px\';" onclick="_zoom_page(\'' + paid + '\', ' + (showexif ? 1 : 0) + ')" class="zimg_next"><strong>下一张</strong></div> ';
}
if(picpage) {
$(menuid + '_picpage').innerHTML = picpage;
}
}
}
showMenu({'ctrlid':obj.id,'menuid':menuid,'duration':3,'pos':'00','cover':cover,'drag':menuid,'maxh':''});
}
function _zoom_page(paid, showexif) {
var imagesrc = $('aimg_' + paid).getAttribute('zoomfile') ? $('aimg_' + paid).getAttribute('zoomfile') : $('aimg_' + paid).getAttribute('file');
zoom($('aimg_' + paid), imagesrc, 0, 1, showexif ? 1 : 0);
}
function _switchTab(prefix, current, total, activeclass) {
activeclass = !activeclass ? 'a' : activeclass;
for(var i = 1; i <= total;i++) {
var classname = ' '+$(prefix + '_' + i).className+' ';
$(prefix + '_' + i).className = classname.replace(' '+activeclass+' ','').substr(1);
$(prefix + '_c_' + i).style.display = 'none';
}
$(prefix + '_' + current).className = $(prefix + '_' + current).className + ' '+activeclass;
$(prefix + '_c_' + current).style.display = '';
}
function _initTab(frameId, type) {
if (typeof document['diyform'] == 'object' || $(frameId).className.indexOf('tab') < 0) return false;
type = type || 'click';
var tabs = $(frameId+'_title').childNodes;
var arrTab = [];
for(var i in tabs) {
if (tabs[i]['nodeType'] == 1 && tabs[i]['className'].indexOf('move-span') > -1) {
arrTab.push(tabs[i]);
}
}
var counter = 0;
var tab = document.createElement('ul');
tab.className = 'tb cl';
var len = arrTab.length;
for(var i = 0;i < len; i++) {
var tabId = arrTab[i].id;
if (hasClass(arrTab[i],'frame') || hasClass(arrTab[i],'tab')) {
var arrColumn = [];
for (var j in arrTab[i].childNodes) {
if (typeof arrTab[i].childNodes[j] == 'object' && !hasClass(arrTab[i].childNodes[j],'title')) arrColumn.push(arrTab[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
frameContent.className = hasClass(arrTab[i],'frame') ? 'content cl '+arrTab[i].className.substr(arrTab[i].className.lastIndexOf(' ')+1) : 'content cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
} else {
var frameContent = $(tabId+'_content');
frameContent = frameContent || document.createElement('div');
}
frameContent.style.display = counter ? 'none' : '';
$(frameId+'_content').appendChild(frameContent);
var li = document.createElement('li');
li.id = tabId;
li.className = counter ? '' : 'a';
var reg = new RegExp('style=\"(.*?)\"', 'gi');
var matchs = '', style = '', imgs = '';
while((matchs = reg.exec(arrTab[i].innerHTML))) {
if(matchs[1].substr(matchs[1].length,1) != ';') {
matchs[1] += ';';
}
style += matchs[1];
}
style = style ? ' style="'+style+'"' : '';
reg = new RegExp('(<img.*?>)', 'gi');
while((matchs = reg.exec(arrTab[i].innerHTML))) {
imgs += matchs[1];
}
li.innerHTML = arrTab[i]['innerText'] ? arrTab[i]['innerText'] : arrTab[i]['textContent'];
var a = arrTab[i].getElementsByTagName('a');
var href = a && a[0] ? a[0].href : 'javascript:;';
var onclick = type == 'click' ? ' onclick="return false;"' : '';
li.innerHTML = '<a href="' + href + '"' + onclick + ' onfocus="this.blur();" ' + style + '>' + imgs + li.innerHTML + '</a>';
_attachEvent(li, type, switchTabUl);
tab.appendChild(li);
$(frameId+'_title').removeChild(arrTab[i]);
counter++;
}
$(frameId+'_title').appendChild(tab);
}
function switchTabUl (e) {
e = e || window.event;
var aim = e.target || e.srcElement;
var tabId = aim.id;
var parent = aim.parentNode;
while(parent['nodeName'] != 'UL' && parent['nodeName'] != 'BODY') {
tabId = parent.id;
parent = parent.parentNode;
}
if(parent['nodeName'] == 'BODY') return false;
var tabs = parent.childNodes;
var len2 = tabs.length;
for(var j = 0; j < len2; j++) {
tabs[j].className = (tabs[j].id == tabId) ? 'a' : '';
var content = $(tabs[j].id+'_content');
if (content) content.style.display = tabs[j].id == tabId ? '' : 'none';
}
}
function slideshow(el) {
var obj = this;
if(!el.id) el.id = Math.random();
if(typeof slideshow.entities == 'undefined') {
slideshow.entities = {};
}
this.id = el.id;
if(slideshow.entities[this.id]) return false;
slideshow.entities[this.id] = this;
this.slideshows = [];
this.slidebar = [];
this.slideother = [];
this.slidebarup = '';
this.slidebardown = '';
this.slidenum = 0;
this.slidestep = 0;
this.container = el;
this.imgs = [];
this.imgLoad = [];
this.imgLoaded = 0;
this.imgWidth = 0;
this.imgHeight = 0;
this.getMEvent = function(ele, value) {
value = !value ? 'mouseover' : value;
var mevent = !ele ? '' : ele.getAttribute('mevent');
mevent = (mevent == 'click' || mevent == 'mouseover') ? mevent : value;
return mevent;
};
this.slideshows = $C('slideshow', el);
this.slideshows = this.slideshows.length>0 ? this.slideshows[0].childNodes : null;
this.slidebar = $C('slidebar', el);
this.slidebar = this.slidebar.length>0 ? this.slidebar[0] : null;
this.barmevent = this.getMEvent(this.slidebar);
this.slideother = $C('slideother', el);
this.slidebarup = $C('slidebarup', el);
this.slidebarup = this.slidebarup.length>0 ? this.slidebarup[0] : null;
this.barupmevent = this.getMEvent(this.slidebarup, 'click');
this.slidebardown = $C('slidebardown', el);
this.slidebardown = this.slidebardown.length>0 ? this.slidebardown[0] : null;
this.bardownmevent = this.getMEvent(this.slidebardown, 'click');
this.slidenum = parseInt(this.container.getAttribute('slidenum'));
this.slidestep = parseInt(this.container.getAttribute('slidestep'));
this.timestep = parseInt(this.container.getAttribute('timestep'));
this.timestep = !this.timestep ? 2500 : this.timestep;
this.index = this.length = 0;
this.slideshows = !this.slideshows ? filterTextNode(el.childNodes) : filterTextNode(this.slideshows);
this.length = this.slideshows.length;
for(i=0; i<this.length; i++) {
this.slideshows[i].style.display = "none";
_attachEvent(this.slideshows[i], 'mouseover', function(){obj.stop();});
_attachEvent(this.slideshows[i], 'mouseout', function(){obj.goon();});
}
for(i=0, L=this.slideother.length; i<L; i++) {
for(var j=0;j<this.slideother[i].childNodes.length;j++) {
if(this.slideother[i].childNodes[j].nodeType == 1) {
this.slideother[i].childNodes[j].style.display = "none";
}
}
}
if(!this.slidebar) {
if(!this.slidenum && !this.slidestep) {
this.container.parentNode.style.position = 'relative';
this.slidebar = document.createElement('div');
this.slidebar.className = 'slidebar';
this.slidebar.style.position = 'absolute';
this.slidebar.style.top = '5px';
this.slidebar.style.left = '4px';
this.slidebar.style.display = 'none';
var html = '<ul>';
for(var i=0; i<this.length; i++) {
html += '<li on'+this.barmevent+'="slideshow.entities[' + this.id + '].xactive(' + i + '); return false;">' + (i + 1).toString() + '</li>';
}
html += '</ul>';
this.slidebar.innerHTML = html;
this.container.parentNode.appendChild(this.slidebar);
this.controls = this.slidebar.getElementsByTagName('li');
}
} else {
this.controls = filterTextNode(this.slidebar.childNodes);
for(i=0; i<this.controls.length; i++) {
if(this.slidebarup == this.controls[i] || this.slidebardown == this.controls[i]) continue;
_attachEvent(this.controls[i], this.barmevent, function(){slidexactive()});
_attachEvent(this.controls[i], 'mouseout', function(){obj.goon();});
}
}
if(this.slidebarup) {
_attachEvent(this.slidebarup, this.barupmevent, function(){slidexactive('up')});
}
if(this.slidebardown) {
_attachEvent(this.slidebardown, this.bardownmevent, function(){slidexactive('down')});
}
this.activeByStep = function(index) {
var showindex = 0,i = 0;
if(index == 'down') {
showindex = this.index + 1;
if(showindex > this.length) {
this.runRoll();
} else {
for (i = 0; i < this.slidestep; i++) {
if(showindex >= this.length) showindex = 0;
this.index = this.index - this.slidenum + 1;
if(this.index < 0) this.index = this.length + this.index;
this.active(showindex);
showindex++;
}
}
} else if (index == 'up') {
var tempindex = this.index;
showindex = this.index - this.slidenum;
if(showindex < 0) return false;
for (i = 0; i < this.slidestep; i++) {
if(showindex < 0) showindex = this.length - Math.abs(showindex);
this.active(showindex);
this.index = tempindex = tempindex - 1;
if(this.index <0) this.index = this.length - 1;
showindex--;
}
}
return false;
};
this.active = function(index) {
this.slideshows[this.index].style.display = "none";
this.slideshows[index].style.display = "block";
if(this.controls && this.controls.length > 0) {
this.controls[this.index].className = '';
this.controls[index].className = 'on';
}
for(var i=0,L=this.slideother.length; i<L; i++) {
this.slideother[i].childNodes[this.index].style.display = "none";
this.slideother[i].childNodes[index].style.display = "block";
}
this.index = index;
};
this.xactive = function(index) {
if(!this.slidenum && !this.slidestep) {
this.stop();
if(index == 'down') index = this.index == this.length-1 ? 0 : this.index+1;
if(index == 'up') index = this.index == 0 ? this.length-1 : this.index-1;
this.active(index);
} else {
this.activeByStep(index);
}
};
this.goon = function() {
this.stop();
var curobj = this;
this.timer = setTimeout(function () {
curobj.run();
}, this.timestep);
};
this.stop = function() {
clearTimeout(this.timer);
};
this.run = function() {
var index = this.index + 1 < this.length ? this.index + 1 : 0;
if(!this.slidenum && !this.slidestep) {
this.active(index);
} else {
this.activeByStep('down');
}
var ss = this;
this.timer = setTimeout(function(){
ss.run();
}, this.timestep);
};
this.runRoll = function() {
for(var i = 0; i < this.slidenum; i++) {
if(this.slideshows[i] && typeof this.slideshows[i].style != 'undefined') this.slideshows[i].style.display = 'block';
for(var j=0,L=this.slideother.length; j<L; j++) {
this.slideother[j].childNodes[i].style.display = 'block';
}
}
this.index = this.slidenum - 1;
};
var imgs = this.slideshows.length ? this.slideshows[0].parentNode.getElementsByTagName('img') : [];
for(i=0, L=imgs.length; i<L; i++) {
this.imgs.push(imgs[i]);
this.imgLoad.push(new Image());
this.imgLoad[i].onerror = function (){obj.imgLoaded ++;};
this.imgLoad[i].src = this.imgs[i].src;
}
this.getSize = function () {
if(this.imgs.length == 0) return false;
var img = this.imgs[0];
this.imgWidth = img.width ? parseInt(img.width) : 0;
this.imgHeight = img.height ? parseInt(img.height) : 0;
var ele = img.parentNode;
while ((!this.imgWidth || !this.imgHeight) && !hasClass(ele,'slideshow') && ele != document.body) {
this.imgWidth = ele.style.width ? parseInt(ele.style.width) : 0;
this.imgHeight = ele.style.height ? parseInt(ele.style.height) : 0;
ele = ele.parentNode;
}
return true;
};
this.getSize();
this.checkLoad = function () {
var obj = this;
this.container.style.display = 'block';
for(i = 0;i < this.imgs.length;i++) {
if(this.imgLoad[i].complete && !this.imgLoad[i].status) {
this.imgLoaded++;
this.imgLoad[i].status = 1;
}
}
var percentEle = $(this.id+'_percent');
if(this.imgLoaded < this.imgs.length) {
if (!percentEle) {
var dom = document.createElement('div');
dom.id = this.id+"_percent";
dom.style.width = this.imgWidth ? this.imgWidth+'px' : '150px';
dom.style.height = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.lineHeight = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.backgroundColor = '#ccc';
dom.style.textAlign = 'center';
dom.style.top = '0';
dom.style.left = '0';
dom.style.marginLeft = 'auto';
dom.style.marginRight = 'auto';
this.slideshows[0].parentNode.appendChild(dom);
percentEle = dom;
}
el.parentNode.style.position = 'relative';
percentEle.innerHTML = (parseInt(this.imgLoaded / this.imgs.length * 100)) + '%';
setTimeout(function () {obj.checkLoad();}, 100);
} else {
if (percentEle) percentEle.parentNode.removeChild(percentEle);
if(this.slidebar) this.slidebar.style.display = '';
this.index = this.length - 1 < 0 ? 0 : this.length - 1;
if(this.slideshows.length > 0) {
if(!this.slidenum || !this.slidestep) {
this.run();
} else {
this.runRoll();
}
}
}
};
this.checkLoad();
}
function slidexactive(step) {
var e = getEvent();
var aim = e.target || e.srcElement;
var parent = aim.parentNode;
var xactivei = null, slideboxid = null,currentslideele = null;
currentslideele = hasClass(aim, 'slidebarup') || hasClass(aim, 'slidebardown') || hasClass(parent, 'slidebar') ? aim : null;
while(parent && parent != document.body) {
if(!currentslideele && hasClass(parent, 'slidebar')) {
currentslideele = parent;
}
if(!currentslideele && (hasClass(parent, 'slidebarup') || hasClass(parent, 'slidebardown'))) {
currentslideele = parent;
}
if(hasClass(parent, 'slidebox')) {
slideboxid = parent.id;
break;
}
parent = parent.parentNode;
}
var slidebar = $C('slidebar', parent);
var children = slidebar.length == 0 ? [] : filterTextNode(slidebar[0].childNodes);
if(currentslideele && (hasClass(currentslideele, 'slidebarup') || hasClass(currentslideele, 'slidebardown'))) {
xactivei = step;
} else {
for(var j=0,i=0,L=children.length;i<L;i++){
if(currentslideele && children[i] == currentslideele) {
xactivei = j;
break;
}
if(!hasClass(children[i], 'slidebarup') && !hasClass(children[i], 'slidebardown')) j++;
}
}
if(slideboxid != null && xactivei != null) slideshow.entities[slideboxid].xactive(xactivei);
}
function filterTextNode(list) {
var newlist = [];
for(var i=0; i<list.length; i++) {
if (list[i].nodeType == 1) {
newlist.push(list[i]);
}
}
return newlist;
}
function _runslideshow() {
var slideshows = $C('slidebox');
for(var i=0,L=slideshows.length; i<L; i++) {
new slideshow(slideshows[i]);
}
}
function _showTip(ctrlobj) {
if(!ctrlobj.id) {
ctrlobj.id = 'tip_' + Math.random();
}
menuid = ctrlobj.id + '_menu';
if(!$(menuid)) {
var div = document.createElement('div');
div.id = ctrlobj.id + '_menu';
div.className = 'tip tip_4';
div.style.display = 'none';
div.innerHTML = '<div class="tip_horn"></div><div class="tip_c">' + ctrlobj.getAttribute('tip') + '</div>';
$('append_parent').appendChild(div);
}
$(ctrlobj.id).onmouseout = function () { hideMenu('', 'prompt'); };
showMenu({'mtype':'prompt','ctrlid':ctrlobj.id,'pos':'12!','duration':2,'zindex':JSMENU['zIndex']['prompt']});
}
function _showPrompt(ctrlid, evt, msg, timeout) {
var menuid = ctrlid ? ctrlid + '_pmenu' : 'ntcwin';
var duration = timeout ? 0 : 3;
if($(menuid)) {
$(menuid).parentNode.removeChild($(menuid));
}
var div = document.createElement('div');
div.id = menuid;
div.className = ctrlid ? 'tip tip_js' : 'ntcwin';
div.style.display = 'none';
$('append_parent').appendChild(div);
if(ctrlid) {
msg = '<div id="' + ctrlid + '_prompt"><div class="tip_horn"></div><div class="tip_c">' + msg + '</div>';
} else {
msg = '<table cellspacing="0" cellpadding="0" class="popupcredit"><tr><td class="pc_l"> </td><td class="pc_c"><div class="pc_inner">' + msg +
'</td><td class="pc_r"> </td></tr></table>';
}
div.innerHTML = msg;
if(ctrlid) {
if(!timeout) {
evt = 'click';
}
if($(ctrlid)) {
if($(ctrlid).evt !== false) {
var prompting = function() {
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210'});
};
if(evt == 'click') {
$(ctrlid).onclick = prompting;
} else {
$(ctrlid).onmouseover = prompting;
}
}
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210','duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(ctrlid).unselectable = false;
}
} else {
showMenu({'mtype':'prompt','pos':'00','menuid':menuid,'duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(menuid).style.top = (parseInt($(menuid).style.top) - 100) + 'px';
}
}
function _showCreditPrompt() {
var notice = getcookie('creditnotice').split('D');
var basev = getcookie('creditbase').split('D');
var creditrule = decodeURI(getcookie('creditrule', 1)).replace(String.fromCharCode(9), ' ');
if(!discuz_uid || notice.length < 2 || notice[9] != discuz_uid) {
setcookie('creditnotice', '');
setcookie('creditrule', '');
return;
}
var creditnames = creditnotice.split(',');
var creditinfo = [];
var e;
for(var i = 0; i < creditnames.length; i++) {
e = creditnames[i].split('|');
creditinfo[e[0]] = [e[1], e[2]];
}
creditShow(creditinfo, notice, basev, 0, 1, creditrule);
}
function creditShow(creditinfo, notice, basev, bk, first, creditrule) {
var s = '', check = 0;
for(i = 1; i <= 8; i++) {
v = parseInt(Math.abs(parseInt(notice[i])) / 5) + 1;
if(notice[i] !== '0' && creditinfo[i]) {
s += '<span>' + creditinfo[i][0] + (notice[i] != 0 ? (notice[i] > 0 ? '<em>+' : '<em class="desc">') + notice[i] + '</em>' : '') + creditinfo[i][1] + '</span>';
}
if(notice[i] > 0) {
notice[i] = parseInt(notice[i]) - v;
basev[i] = parseInt(basev[i]) + v;
} else if(notice[i] < 0) {
notice[i] = parseInt(notice[i]) + v;
basev[i] = parseInt(basev[i]) - v;
}
if($('hcredit_' + i)) {
$('hcredit_' + i).innerHTML = basev[i];
}
}
for(i = 1; i <= 8; i++) {
if(notice[i] != 0) {
check = 1;
}
}
if(!s || first) {
setcookie('creditnotice', '');
setcookie('creditbase', '');
setcookie('creditrule', '');
if(!s) {
return;
}
}
if(!$('creditpromptdiv')) {
showPrompt(null, null, '<div id="creditpromptdiv">' + (creditrule ? '<i>' + creditrule + '</i> ' : '') + s + '</div>', 0);
} else {
$('creditpromptdiv').innerHTML = s;
}
setTimeout(function () {hideMenu(1, 'prompt');$('append_parent').removeChild($('ntcwin'));}, 1500);
}
function _showColorBox(ctrlid, layer, k, bgcolor) {
var tag1 = !bgcolor ? 'color' : 'backcolor', tag2 = !bgcolor ? 'forecolor' : 'backcolor';
if(!$(ctrlid + '_menu')) {
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.className = 'p_pop colorbox';
menu.unselectable = true;
menu.style.display = 'none';
var coloroptions = ['Black', 'Sienna', 'DarkOliveGreen', 'DarkGreen', 'DarkSlateBlue', 'Navy', 'Indigo', 'DarkSlateGray', 'DarkRed', 'DarkOrange', 'Olive', 'Green', 'Teal', 'Blue', 'SlateGray', 'DimGray', 'Red', 'SandyBrown', 'YellowGreen', 'SeaGreen', 'MediumTurquoise', 'RoyalBlue', 'Purple', 'Gray', 'Magenta', 'Orange', 'Yellow', 'Lime', 'Cyan', 'DeepSkyBlue', 'DarkOrchid', 'Silver', 'Pink', 'Wheat', 'LemonChiffon', 'PaleGreen', 'PaleTurquoise', 'LightBlue', 'Plum', 'White'];
var colortexts = ['黑色', '赭色', '暗橄榄绿色', '暗绿色', '暗灰蓝色', '海军色', '靛青色', '墨绿色', '暗红色', '暗桔黄色', '橄榄色', '绿色', '水鸭色', '蓝色', '灰石色', '暗灰色', '红色', '沙褐色', '黄绿色', '海绿色', '间绿宝石', '皇家蓝', '紫色', '灰色', '红紫色', '橙色', '黄色', '酸橙色', '青色', '深天蓝色', '暗紫色', '银色', '粉色', '浅黄色', '柠檬绸色', '苍绿色', '苍宝石绿', '亮蓝色', '洋李色', '白色'];
var str = '';
for(var i = 0; i < 40; i++) {
str += '<input type="button" style="background-color: ' + coloroptions[i] + '"' + (typeof setEditorTip == 'function' ? ' onmouseover="setEditorTip(\'' + colortexts[i] + '\')" onmouseout="setEditorTip(\'\')"' : '') + ' onclick="'
+ (typeof wysiwyg == 'undefined' ? 'seditor_insertunit(\'' + k + '\', \'[' + tag1 + '=' + coloroptions[i] + ']\', \'[/' + tag1 + ']\')' : (ctrlid == editorid + '_tbl_param_4' ? '$(\'' + ctrlid + '\').value=\'' + coloroptions[i] + '\';hideMenu(2)' : 'discuzcode(\'' + tag2 + '\', \'' + coloroptions[i] + '\')'))
+ '" title="' + colortexts[i] + '" />' + (i < 39 && (i + 1) % 8 == 0 ? '<br />' : '');
}
menu.innerHTML = str;
$('append_parent').appendChild(menu);
}
showMenu({'ctrlid':ctrlid,'evt':'click','layer':layer});
}
function _toggle_collapse(objname, noimg, complex, lang) {
var obj = $(objname);
if(obj) {
obj.style.display = obj.style.display == '' ? 'none' : '';
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, objname, !obj.style.display);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
}
if(!noimg) {
var img = $(objname + '_img');
if(img.tagName != 'IMG') {
if(img.className.indexOf('_yes') == -1) {
img.className = img.className.replace(/_no/, '_yes');
if(lang) {
img.innerHTML = lang[0];
}
} else {
img.className = img.className.replace(/_yes/, '_no');
if(lang) {
img.innerHTML = lang[1];
}
}
} else {
img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif');
}
img.blur();
}
if(complex) {
var objc = $(objname + '_c');
if(objc) {
objc.className = objc.className == 'umh' ? 'umh umn' : 'umh';
}
}
}
function _extstyle(css) {
if(!$('css_extstyle')) {
loadcss('extstyle');
}
$('css_extstyle').href = css ? css + '/style.css' : STATICURL + 'image/common/extstyle_none.css';
currentextstyle = css;
setcookie('extstyle', css, 86400 * 30);
if($('css_widthauto') && !$('css_widthauto').disabled) {
CSSLOADED['widthauto'] = 0;
loadcss('widthauto');
}
}
function _widthauto(obj) {
if($('css_widthauto')) {
CSSLOADED['widthauto'] = 1;
}
if(!CSSLOADED['widthauto'] || $('css_widthauto').disabled) {
if(!CSSLOADED['widthauto']) {
loadcss('widthauto');
} else {
$('css_widthauto').disabled = false;
}
HTMLNODE.className += ' widthauto';
setcookie('widthauto', 1, 86400 * 30);
obj.innerHTML = '切换到窄版';
} else {
$('css_widthauto').disabled = true;
HTMLNODE.className = HTMLNODE.className.replace(' widthauto', '');
setcookie('widthauto', -1, 86400 * 30);
obj.innerHTML = '切换到宽版';
}
hideMenu();
}
function _showCreditmenu() {
if(!$('extcreditmenu_menu')) {
menu = document.createElement('div');
menu.id = 'extcreditmenu_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
menu.innerHTML = '<div class="p_opt"><img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" /> 请稍候...</div>';
$('append_parent').appendChild(menu);
ajaxget($('extcreditmenu').href, 'extcreditmenu_menu', 'ajaxwaitid');
}
showMenu({'ctrlid':'extcreditmenu','ctrlclass':'a','duration':1});
}
function _showForummenu(fid) {
if(!$('fjump_menu')) {
fid = !fid ? 0 : fid;
menu = document.createElement('div');
menu.id = 'fjump_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
menu.innerHTML = '<div class="p_opt"><img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" /> 请稍候...</div>';
$('append_parent').appendChild(menu);
ajaxget('forum.php?mod=ajax&action=forumjump&jfid=' + fid, 'fjump_menu', 'ajaxwaitid');
}
showMenu({'ctrlid':'fjump','ctrlclass':'a','duration':2});
}
function _imageRotate(imgid, direct) {
var image = $(imgid);
if(!image.getAttribute('deg')) {
var deg = 0;
image.setAttribute('ow', image.width);
image.setAttribute('oh', image.height);
if(BROWSER.ie) {
image.setAttribute('om', parseInt(image.currentStyle.marginBottom));
}
} else {
var deg = parseInt(image.getAttribute('deg'));
}
var ow = image.getAttribute('ow');
var oh = image.getAttribute('oh');
deg = direct == 1 ? deg - 90 : deg + 90;
if(deg > 270) {
deg = 0;
} else if(deg < 0) {
deg = 270;
}
image.setAttribute('deg', deg);
if(BROWSER.ie) {
if(!isNaN(image.getAttribute('om'))) {
image.style.marginBottom = (image.getAttribute('om') + (BROWSER.ie < 8 ? 0 : (deg == 90 || deg == 270 ? Math.abs(ow - oh) : 0))) + 'px';
}
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (deg / 90) + ')';
} else {
switch(deg) {
case 90:var cow = oh, coh = ow, cx = 0, cy = -oh;break;
case 180:var cow = ow, coh = oh, cx = -ow, cy = -oh;break;
case 270:var cow = oh, coh = ow, cx = -ow, cy = 0;break;
}
var canvas = $(image.getAttribute('canvasid'));
if(!canvas) {
var i = document.createElement("canvas");
i.id = 'canva_' + Math.random();
image.setAttribute('canvasid', i.id);
image.parentNode.insertBefore(i, image);
canvas = $(i.id);
}
if(deg) {
var canvasContext = canvas.getContext('2d');
canvas.setAttribute('width', cow);
canvas.setAttribute('height', coh);
canvasContext.rotate(deg * Math.PI / 180);
canvasContext.drawImage(image, cx, cy, ow, oh);
image.style.display = 'none';
canvas.style.display = '';
} else {
image.style.display = '';
canvas.style.display = 'none';
}
}
}
function _createPalette(colorid, id, func) {
var iframe = "<iframe name=\"c"+colorid+"_frame\" src=\"\" frameborder=\"0\" width=\"210\" height=\"148\" scrolling=\"no\"></iframe>";
if (!$("c"+colorid+"_menu")) {
var dom = document.createElement('span');
dom.id = "c"+colorid+"_menu";
dom.style.display = 'none';
dom.innerHTML = iframe;
$('append_parent').appendChild(dom);
}
func = !func ? '' : '|' + func;
window.frames["c"+colorid+"_frame"].location.href = SITEURL+STATICURL+"image/admincp/getcolor.htm?c"+colorid+"|"+id+func;
showMenu({'ctrlid':'c'+colorid});
var iframeid = "c"+colorid+"_menu";
_attachEvent(window, 'scroll', function(){hideMenu(iframeid);});
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_moderate.js 26484 2011-12-14 02:08:03Z svn_project_zhangjie $
*/
function modaction(action, pid, extra, mod) {
if(!action) {
return;
}
var mod = mod ? mod : 'forum.php?mod=topicadmin';
var extra = !extra ? '' : '&' + extra;
if(!pid && in_array(action, ['delpost', 'banpost'])) {
var checked = 0;
var pid = '';
for(var i = 0; i < $('modactions').elements.length; i++) {
if($('modactions').elements[i].name.match('topiclist')) {
checked = 1;
break;
}
}
} else {
var checked = 1;
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('modactions').action = mod + '&action='+ action +'&fid=' + fid + '&tid=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (!pid ? '' : '&topiclist[]=' + pid) + extra + '&r' + Math.random();
showWindow('mods', 'modactions', 'post');
if(BROWSER.ie) {
doane(event);
}
hideMenu();
}
}
function modthreads(optgroup, operation) {
var operation = !operation ? '' : operation;
$('modactions').action = 'forum.php?mod=topicadmin&action=moderate&fid=' + fid + '&moderate[]=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (optgroup != 3 && optgroup != 2 ? '&from=' + tid : '');
$('modactions').optgroup.value = optgroup;
$('modactions').operation.value = operation;
hideWindow('mods');
showWindow('mods', 'modactions', 'post', 0);
if(BROWSER.ie) {
doane(event);
}
}
function pidchecked(obj) {
if(obj.checked) {
try {
var inp = document.createElement('<input name="topiclist[]" />');
} catch(e) {
try {
var inp = document.createElement('input');
inp.name = 'topiclist[]';
} catch(e) {
return;
}
}
inp.id = 'topiclist_' + obj.value;
inp.value = obj.value;
inp.type = 'hidden';
$('modactions').appendChild(inp);
} else {
$('modactions').removeChild($('topiclist_' + obj.value));
}
}
var modclickcount = 0;
function modclick(obj, pid) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var offset = fetchOffset(obj);
$('mdly').style.top = offset['top'] - 65 + 'px';
$('mdly').style.left = offset['left'] - 215 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function resetmodcount() {
modclickcount = 0;
$('mdly').style.display = 'none';
}
function tmodclick(obj) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent).id != 'threadlist') {
top_offset += obj.offsetTop;
}
$('mdly').style.top = top_offset - 7 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function tmodthreads(optgroup, operation) {
var checked = 0;
var operation = !operation ? '' : operation;
for(var i = 0; i < $('moderate').elements.length; i++) {
if($('moderate').elements[i].name.match('moderate') && $('moderate').elements[i].checked) {
checked = 1;
break;
}
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('moderate').optgroup.value = optgroup;
$('moderate').operation.value = operation;
hideWindow('mods');
showWindow('mods', 'moderate', 'post', 0);
}
}
function getthreadclass() {
var fid = $('fid');
if(fid) {
ajaxget('forum.php?mod=ajax&action=getthreadclass&fid=' + fid.value, 'threadclass', null, null, null, showthreadclass);
}
}
function showthreadclass() {
try{
$('append_parent').removeChild($('typeid_ctrl_menu'));
}catch(e) {}
simulateSelect('typeid');
}
loadcss('forum_moderator'); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: seditor.js 28601 2012-03-06 02:49:55Z monkey $
*/
function seditor_showimgmenu(seditorkey) {
var imgurl = $(seditorkey + '_image_param_1').value;
var width = parseInt($(seditorkey + '_image_param_2').value);
var height = parseInt($(seditorkey + '_image_param_3').value);
var extparams = '';
if(width || height) {
extparams = '=' + width + ',' + height
}
seditor_insertunit(seditorkey, '[img' + extparams + ']' + imgurl, '[/img]', null, 1);
$(seditorkey + '_image_param_1').value = '';
hideMenu();
}
function seditor_menu(seditorkey, tag) {
var sel = false;
if(!isUndefined($(seditorkey + 'message').selectionStart)) {
sel = $(seditorkey + 'message').selectionEnd - $(seditorkey + 'message').selectionStart;
} else if(document.selection && document.selection.createRange) {
$(seditorkey + 'message').focus();
var sel = document.selection.createRange();
$(seditorkey + 'message').sel = sel;
sel = sel.text ? true : false;
}
if(sel) {
seditor_insertunit(seditorkey, '[' + tag + ']', '[/' + tag + ']');
return;
}
var ctrlid = seditorkey + tag;
var menuid = ctrlid + '_menu';
if(!$(menuid)) {
switch(tag) {
case 'at':
curatli = 0;
atsubmitid = ctrlid + '_submit';
setTimeout(function() {atFilter('', 'at_list','atListSet');$('atkeyword').focus();}, 100);
str = '请输用户名:<br /><input type="text" id="atkeyword" style="width:240px" value="" class="px" onkeydown="atFilter(this.value, \'at_list\',\'atListSet\',event);" /><div class="p_pop" id="at_list" style="width:250px;"><ul><li>@朋友账号,就能提醒他来看帖子</li></ul></div>';
submitstr = 'seditor_insertunit(\'' + seditorkey + '\', \'@\' + $(\'atkeyword\').value.replace(/<\\/?b>/g, \'\')+\' \'); hideMenu();';
break;
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" sautocomplete="off" style="width: 98%" value="" class="px" />' +
'<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />';
submitstr = "$('" + ctrlid + "_param_2').value !== '' ? seditor_insertunit('" + seditorkey + "', '[url='+seditor_squarestrip($('" + ctrlid + "_param_1').value)+']'+$('" + ctrlid + "_param_2').value, '[/url]', null, 1) : seditor_insertunit('" + seditorkey + "', '[url]'+$('" + ctrlid + "_param_1').value, '[/url]', null, 1);hideMenu();";
break;
case 'code':
case 'quote':
var tagl = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码'};
str = tagl[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[" + tag + "]'+$('" + ctrlid + "_param_1').value, '[/" + tag + "]', null, 1);hideMenu();";
break;
case 'img':
str = '请输入图片地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" onchange="loadimgsize(this.value, \'' + seditorkey + '\',\'' + tag + '\')" />' +
'<p class="mtm">宽(可选): <input type="text" id="' + ctrlid + '_param_2" style="width: 15%" value="" class="px" /> ' +
'高(可选): <input type="text" id="' + ctrlid + '_param_3" style="width: 15%" value="" class="px" /></p>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[img' + ($('" + ctrlid + "_param_2').value !== '' && $('" + ctrlid + "_param_3').value !== '' ? '='+$('" + ctrlid + "_param_2').value+','+$('" + ctrlid + "_param_3').value : '')+']'+seditor_squarestrip($('" + ctrlid + "_param_1').value), '[/img]', null, 1);hideMenu();";
break;
}
var menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = '270px';
$('append_parent').appendChild(menu);
menu.innerHTML = '<span class="y"><a onclick="hideMenu()" class="flbc" href="javascript:;">关闭</a></span><div class="p_opt cl"><form onsubmit="' + submitstr + ';return false;" autocomplete="off"><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button><button type="button" onClick="hideMenu()" class="pn"><em>取消</em></button></div></form></div>';
}
showMenu({'ctrlid':ctrlid,'evt':'click','duration':3,'cache':0,'drag':1});
}
function seditor_squarestrip(str) {
str = str.replace('[', '%5B');
str = str.replace(']', '%5D');
return str;
}
function seditor_insertunit(key, text, textend, moveend, selappend) {
if($(key + 'message')) {
$(key + 'message').focus();
}
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
selappend = isUndefined(selappend) ? 1 : selappend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($(key + 'message').selectionStart)) {
if(selappend) {
var opn = $(key + 'message').selectionStart + 0;
if(textend != '') {
text = text + $(key + 'message').value.substring($(key + 'message').selectionStart, $(key + 'message').selectionEnd) + textend;
}
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
if(!moveend) {
$(key + 'message').selectionStart = opn + strlen(text) - endlen;
$(key + 'message').selectionEnd = opn + strlen(text) - endlen;
}
} else {
text = text + textend;
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(!sel.text.length && $(key + 'message').sel) {
sel = $(key + 'message').sel;
$(key + 'message').sel = null;
}
if(selappend) {
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
sel.text = text + textend;
}
} else {
$(key + 'message').value += text;
}
hideMenu(2);
if(BROWSER.ie) {
doane();
}
}
function seditor_ctlent(event, script) {
if(event.ctrlKey && event.keyCode == 13 || event.altKey && event.keyCode == 83) {
eval(script);
}
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: logging.js 23838 2011-08-11 06:51:58Z monkey $
*/
function lsSubmit(op) {
var op = !op ? 0 : op;
if(op) {
$('lsform').cookietime.value = 2592000;
}
if($('ls_username').value == '' || $('ls_password').value == '') {
showWindow('login', 'member.php?mod=logging&action=login' + (op ? '&cookietime=1' : ''));
} else {
ajaxpost('lsform', 'return_ls', 'return_ls');
}
return false;
}
function errorhandle_ls(str, param) {
if(!param['type']) {
showError(str);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_diy_data.js 24360 2011-09-14 08:38:06Z zhangguosheng $
*/
var drag = new Drag();
drag.extend({
'getBlocksTimer' : '',
'blocks' : [],
'blockDefaultClass' : [],
'frameDefaultClass' : [],
setSampleMenu : function () {
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
},
openBlockEdit : function (e,op) {
e = Util.event(e);
op = (op=='data') ? 'data' : 'block';
var bid = e.aim.id.replace('cmd_portal_block_','');
this.removeMenu();
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op='+op+'&bid='+bid+'&tpl='+document.diyform.template.value, 'get', -1);
},
getBlockData : function (blockname) {
var bid = this.dragObj.id;
var eleid = bid;
if (bid.indexOf('portal_block_') != -1) {
eleid = 0;
}else {
bid = 0;
}
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=block&classname='+blockname+'&bid='+bid+'&eleid='+eleid+'&tpl='+document.diyform.template.value,'get',-1);
drag.initPosition();
this.fn = '';
return true;
},
stopSlide : function (id) {
if (typeof slideshow == 'undefined' || typeof slideshow.entities == 'undefined') return false;
var slidebox = $C('slidebox',$(id));
if(slidebox && slidebox.length > 0) {
if(slidebox[0].id) {
var timer = slideshow.entities[slidebox[0].id].timer;
if(timer) clearTimeout(timer);
slideshow.entities[slidebox[0].id] = '';
}
}
},
init : function (sampleMode) {
this.initCommon();
$('samplepanel').innerHTML = '可直接管理模块数据 [<a href="javascript:;" onclick="spaceDiy.cancel();return false;" class="xi2">退出</a>]';
this.setSampleMode(sampleMode);
this.initSample();
return true;
},
setClose : function () {},
blockForceUpdate : function (e,all) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var bid = id.replace('portal_block_', '');
var bcontent = $(id+'_content');
if (!bcontent) {
bcontent = document.createElement('div');
bcontent.id = id+'_content';
bcontent.className = this.contentClass;
}
this.stopSlide(id);
var height = Util.getFinallyStyle(bcontent, 'height');
bcontent.style.lineHeight = height == 'auto' ? '' : (height == '0px' ? '20px' : height);
var boldcontent = bcontent.innerHTML;
bcontent.innerHTML = '<center>正在加载内容...</center>';
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=getblock&forceupdate=1&inajax=1&bid='+bid+'&tpl='+document.diyform.template.value, function(s) {
if(s.indexOf('errorhandle_') != -1) {
bcontent.innerHTML = boldcontent;
runslideshow();
showDialog('抱歉,您没有权限添加或编辑模块', 'alert');
doane();
} else {
var obj = document.createElement('div');
obj.innerHTML = s;
bcontent.parentNode.removeChild(bcontent);
$(id).innerHTML = obj.childNodes[0].innerHTML;
evalscript(s);
if(s.indexOf('runslideshow()') != -1) {runslideshow();}
drag.initPosition();
if (all) {drag.getBlocks();}
}
});
}
});
var spaceDiy = new DIY();
spaceDiy.init(1);
function succeedhandle_diyform (url, message, values) {
if (values['rejs'] == '1') {
document.diyform.rejs.value = '';
parent.$('preview_form').submit();
}
spaceDiy.enablePreviewButton();
return false;
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editor.js 30755 2012-06-18 06:14:29Z monkey $
*/
var editorcurrentheight = 400, editorminheight = 400, savedataInterval = 30, editbox = null, editwin = null, editdoc = null, editcss = null, savedatat = null, savedatac = 0, autosave = 1, framemObj = null, cursor = -1, stack = [], initialized = false, postSubmited = false, editorcontroltop = false, editorcontrolwidth = false, editorcontrolheight = false, editorisfull = 0, fulloldheight = 0, savesimplodemode = null;
EXTRAFUNC['keydown'] = [];
EXTRAFUNC['keyup'] = [];
EXTRAFUNC['mouseup'] = [];
EXTRAFUNC['showEditorMenu'] = [];
var EXTRASELECTION = '', EXTRASEL = null;
function newEditor(mode, initialtext) {
wysiwyg = parseInt(mode);
if(!(BROWSER.ie || BROWSER.firefox || (BROWSER.opera >= 9))) {
allowswitcheditor = wysiwyg = 0;
}
if(!allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
if(wysiwyg) {
if($(editorid + '_iframe')) {
editbox = $(editorid + '_iframe');
} else {
var iframe = document.createElement('iframe');
iframe.frameBorder = '0';
iframe.tabIndex = 2;
iframe.hideFocus = true;
iframe.style.display = 'none';
editbox = textobj.parentNode.appendChild(iframe);
editbox.id = editorid + '_iframe';
}
editwin = editbox.contentWindow;
editdoc = editwin.document;
writeEditorContents(isUndefined(initialtext) ? textobj.value : initialtext);
} else {
editbox = editwin = editdoc = textobj;
if(!isUndefined(initialtext)) {
writeEditorContents(initialtext);
}
addSnapshot(textobj.value);
}
setEditorEvents();
initEditor();
}
function setEditorTip(s) {
$(editorid + '_tip').innerHTML = ' ' + s;
}
function initEditor() {
if(BROWSER.other) {
$(editorid + '_controls').style.display = 'none';
return;
}
var buttons = $(editorid + '_controls').getElementsByTagName('a');
for(var i = 0; i < buttons.length; i++) {
if(buttons[i].id.indexOf(editorid + '_') != -1) {
buttons[i].href = 'javascript:;';
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'fullswitcher') {
buttons[i].innerHTML = !editorisfull ? '全屏' : '返回';
buttons[i].onmouseover = function(e) {setEditorTip(editorisfull ? '恢复编辑器大小' : '全屏方式编辑');};
buttons[i].onclick = function(e) {editorfull();doane();}
} else if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'simple') {
buttons[i].innerHTML = !simplodemode ? '常用' : '高级';
buttons[i].onclick = function(e) {editorsimple();doane();}
} else {
_attachEvent(buttons[i], 'mouseover', function(e) {setEditorTip(BROWSER.ie ? window.event.srcElement.title : e.target.title);});
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'url') {
buttons[i].onclick = function(e) {discuzcode('unlink');discuzcode('url');doane();};
} else {
if(!buttons[i].getAttribute('init')) {
buttons[i].onclick = function(e) {discuzcode(this.id.substr(this.id.indexOf('_') + 1));doane();};
}
}
}
buttons[i].onmouseout = function(e) {setEditorTip('');};
}
}
setUnselectable($(editorid + '_controls'));
if(editorcontroltop === false && (BROWSER.ie && BROWSER.ie > 6 || !BROWSER.ie)) {
seteditorcontrolpos();
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
editorcontrolwidth = $(editorid + '_controls').clientWidth - 8;
ctrlmObj = document.createElement('div');
ctrlmObj.style.display = 'none';
ctrlmObj.style.height = $(editorid + '_controls').clientHeight + 'px';
ctrlmObj.id = editorid + '_controls_mask';
$(editorid + '_controls').parentNode.insertBefore(ctrlmObj, $(editorid + '_controls'));
_attachEvent(window, 'scroll', function () { editorcontrolpos(); }, document);
}
if($(editorid + '_fullswitcher') && BROWSER.ie && BROWSER.ie < 7) {
$(editorid + '_fullswitcher').onclick = function () {
showDialog('您的浏览器不支持此功能,请升级浏览器版本', 'notice', '友情提示');
};
$(editorid + '_fullswitcher').className = 'xg1';
}
if($(editorid + '_svdsecond') && savedatat === null) {
savedatac = savedataInterval;
autosave = !getcookie('editorautosave_' + editorid) || getcookie('editorautosave_' + editorid) == 1 ? 1 : 0;
savedataTime();
savedatat = setInterval("savedataTime()", 10000);
}
initcstbar();
checkFocus();
}
function initcstbar() {
if(!$(editorid + '_cst')) {
return;
}
$(editorid + '_cst').style.position = 'static';
$(editorid + '_cst').style.width = '44px';
$(editorid + '_cst').style.display = '';
$(editorid + '_cst').style.overflow = 'hidden';
$(editorid + '_cst').onmouseover = function () {
$(editorid + '_cst').hs = $(editorid + '_cst').style.height;
$(editorid + '_cst').style.height = 'auto';
if($(editorid + '_cst').offsetHeight < 50) {
return;
}
pos = fetchOffset($(editorid + '_cst'), 1);
$(editorid + '_cst').style.position = 'absolute';
$(editorid + '_cst').style.left = pos.left + 'px';
$(editorid + '_cst').style.top = pos.top + 'px';
$(editorid + '_cst').style.overflow = 'visible';
$(editorid + '_cst').className = 'b2r cst';
};
$(editorid + '_cst').onmouseout = function () {
$(editorid + '_cst').style.height = $(editorid + '_cst').hs;
$(editorid + '_cst').style.overflow = 'hidden';
$(editorid + '_cst').className = 'b2r cst nbb';
};
}
function savedataTime() {
if(!autosave) {
$(editorid + '_svdsecond').innerHTML = '<a title="点击开启自动保存" href="javascript:;" onclick="setAutosave()">开启自动保存</a> ';
return;
}
if(!savedatac) {
savedatac = savedataInterval;
saveData();
d = new Date();
var h = d.getHours();
var m = d.getMinutes();
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
setEditorTip('数据已于 ' + h + ':' + m + ' 保存');
}
$(editorid + '_svdsecond').innerHTML = '<a title="点击关闭自动保存" href="javascript:;" onclick="setAutosave()">' + savedatac + ' 秒后保存</a> ';
savedatac -= 10;
}
function setAutosave() {
autosave = !autosave;
setEditorTip(autosave ? '数据自动保存已开启' : '数据自动保存已关闭');
setcookie('editorautosave_' + editorid, autosave ? 1 : -1, 2592000);
savedataTime();
}
function unloadAutoSave() {
if(autosave) {
saveData();
}
}
function seteditorcontrolpos() {
var objpos = fetchOffset($(editorid + '_controls'));
editorcontroltop = objpos['top'];
}
function editorcontrolpos() {
if(editorisfull) {
return;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
if(scrollTop > editorcontroltop && editorcurrentheight > editorminheight) {
$(editorid + '_controls').style.position = 'fixed';
$(editorid + '_controls').style.top = '0px';
$(editorid + '_controls').style.width = editorcontrolwidth + 'px';
$(editorid + '_controls_mask').style.display = '';
} else {
$(editorid + '_controls').style.position = $(editorid + '_controls').style.top = $(editorid + '_controls').style.width = '';
$(editorid + '_controls_mask').style.display = 'none';
}
}
function editorsize(op, v) {
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
var editorheight = obj.clientHeight;
if(!v) {
if(op == '+') {
editorheight += 200;
} else{
editorheight -= 200;
}
} else {
editorheight = v;
}
editorcurrentheight = editorheight > editorminheight ? editorheight : editorminheight;
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
if(framemObj) {
framemObj.style.height = editorcurrentheight + 'px';
}
$(editorid + '_textarea').style.height = editorcurrentheight + 'px';
}
var editorsizepos = [];
function editorresize(e, op) {
op = !op ? 1 : op;
e = e ? e : window.event;
if(op == 1) {
if(wysiwyg) {
var objpos = fetchOffset($(editorid + '_iframe'));
framemObj = document.createElement('div');
framemObj.style.width = $(editorid + '_iframe').clientWidth + 'px';
framemObj.style.height = $(editorid + '_iframe').clientHeight + 'px';
framemObj.style.position = 'absolute';
framemObj.style.left = objpos['left'] + 'px';
framemObj.style.top = objpos['top'] + 'px';
$('append_parent').appendChild(framemObj);
} else {
framemObj = null;
}
editorsizepos = [e.clientY, editorcurrentheight, framemObj];
document.onmousemove = function(e) {try{editorresize(e, 2);}catch(err){}};
document.onmouseup = function(e) {try{editorresize(e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && editorsizepos !== []) {
var dragnow = e.clientY;
editorsize('', editorsizepos[1] + dragnow - editorsizepos[0]);
doane(e);
}else if(op == 3) {
if(wysiwyg) {
$('append_parent').removeChild(editorsizepos[2]);
}
editorsizepos = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function editorfull(op) {
var op = !op ? 0 : op, control = $(editorid + '_controls'), area = $(editorid + '_textarea').parentNode, bbar = $(editorid + '_bbar'), iswysiwyg = wysiwyg;
if(op) {
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
return;
}
if(!editorisfull) {
savesimplodemode = 0;
if(simplodemode) {
savesimplodemode = 1;
editorsimple();
}
$(editorid + '_simple').style.visibility = 'hidden';
fulloldheight = editorcurrentheight;
document.body.style.overflow = 'hidden';
document.body.scroll = 'no';
control.style.position = 'fixed';
control.style.top = '0px';
control.style.left = '0px';
control.style.width = '100%';
control.style.minWidth = '800px';
area.style.backgroundColor = $(editorid + '_textarea') ? getCurrentStyle($(editorid + '_textarea'), 'backgroundColor', 'background-color') : '#fff';
$(editorid + '_switcher').style.paddingRight = '10px';
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.left = '0px';
area.style.width = '100%';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
bbar.style.left = '0px';
bbar.style.width = '100%';
control.style.zIndex = '500';
area.style.zIndex = bbar.style.zIndex = '200';
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = 'none';
}
window.onresize = function() { editorfull(1); };
editorisfull = 1;
} else {
if(savesimplodemode) {
editorsimple();
}
$(editorid + '_simple').style.visibility = 'visible';
window.onresize = null;
document.body.style.overflow = 'auto';
document.body.scroll = 'yes';
control.style.position = control.style.top = control.style.left = control.style.width = control.style.minWidth = control.style.zIndex =
area.style.position = area.style.top = area.style.left = area.style.width = area.style.height = area.style.zIndex =
bbar.style.position = bbar.style.top = bbar.style.left = bbar.style.width = bbar.style.zIndex = '';
editorheight = fulloldheight;
$(editorid + '_switcher').style.paddingRight = '0px';
editorsize('', editorheight);
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = '';
}
editorisfull = 0;
editorcontrolpos();
}
$(editorid + '_fullswitcher').innerHTML = editorisfull ? '返回' : '全屏';
initcstbar();
}
function editorsimple() {
if($(editorid + '_body').className == 'edt') {
v = 'none';
$(editorid + '_simple').innerHTML = '高级';
$(editorid + '_body').className = 'edt simpleedt';
$(editorid + '_adv_s1').className = 'b2r';
$(editorid + '_adv_s2').className = 'b2r nbl';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
simplodemode = 1;
} else {
v = '';
$(editorid + '_simple').innerHTML = '常用';
$(editorid + '_body').className = 'edt';
$(editorid + '_adv_s1').className = 'b1r';
$(editorid + '_adv_s2').className = 'b2r nbr nbl';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = '';
}
simplodemode = 0;
}
setcookie('editormode_' + editorid, simplodemode ? 1 : -1, 2592000);
for(i = 1;i <= 9;i++) {
if($(editorid + '_adv_' + i)) {
$(editorid + '_adv_' + i).style.display = v;
}
}
initcstbar();
}
function pasteWord(str) {
var mstest = /<\w[^>]* class="?[MsoNormal|xl]"?/gi;
if(mstest.test(str)){
str = str.replace(/<!--\[if[\s\S]+?<!\[endif\]-->/gi, "");
str = str.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, function ($1, $2, $3, $4) {
var style = '';
re = new RegExp('(^|[;\\s])color:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'color:' + match[2] + ';';
}
re = new RegExp('(^|[;\\s])text-indent:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'text-indent:' + parseInt(parseInt(match[2]) / 10) + 'em;';
}
re = new RegExp('(^|[;\\s])font-size:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'font-size:' + match[2] + ';';
}
if(style) {
style = ' style="' + style + '"';
}
return '<' + $2 + style + $4;
});
str = str.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<\\?\?xml[^>]*>/gi, "");
str = str.replace(/<\/?\w+:[^>]*>/gi, "");
str = str.replace(/ /, " ");
var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)", 'ig');
str = str.replace(re, "<div$2</div>");
if(!wysiwyg) {
str = html2bbcode(str);
}
insertText(str, str.length, 0);
}
}
var ctlent_enable = {8:1,9:1,13:1};
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && editorsubmit) {
if(in_array(editorsubmit.name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate(editorform)) {
doane(event);
return;
}
postSubmited = true;
editorsubmit.disabled = true;
editorform.submit();
return;
}
if(ctlent_enable[13] && event.keyCode == 13 && wysiwyg && $(editorid + '_insertorderedlist').className != 'hover' && $(editorid + '_insertunorderedlist').className != 'hover') {
if(!BROWSER.opera) {
insertText('<br>*', 5, 0);
} else {
insertText('<br> ', 5, 0);
}
keyBackspace();
doane(event);
}
if(ctlent_enable[9] && event.keyCode == 9) {
doane(event);
}
if(ctlent_enable[8] && event.keyCode == 8 && wysiwyg) {
var sel = getSel();
if(sel) {
insertText('', sel.length - 1, 0);
doane(event);
}
}
}
function keyBackspace() {
if(!wysiwyg) {
return;
}
if(BROWSER.ie) {
sel = editdoc.selection.createRange();
sel.moveStart('character', -1);
sel.moveEnd('character', 0);
sel.select();
editdoc.selection.clear();
} else {
editdoc.execCommand('delete', false, true);
}
}
function keyMenu(code, func) {
var km = 'kM' + Math.random();
var hs = '<span id="' + km + '">' + code + '</span>';
if(BROWSER.ie) {
var range = document.selection.createRange();
range.pasteHTML(hs);
range.moveToElementText(editdoc.getElementById(km));
range.moveStart("character");
range.select();
} else {
var selection = editwin.getSelection();
var range = selection.getRangeAt(0);
var fragment = range.createContextualFragment(hs);
range.insertNode(fragment);
var tmp = editdoc.getElementById(km).firstChild;
range.setStart(tmp, 1);
range.setEnd(tmp, 1);
selection.removeAllRanges();
selection.addRange(range);
}
keyMenuObj = editdoc.getElementById(km);
var b = fetchOffset(editbox);
var o = fetchOffset(keyMenuObj);
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
func(b.left + o.left, b.top + o.top - scrollTop);
}
function checkFocus() {
if(wysiwyg) {
try {
editwin.focus();
} catch(e) {
editwin.document.body.focus();
}
} else {
textobj.focus();
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
function setUnselectable(obj) {
if(BROWSER.ie && BROWSER.ie > 4 && typeof obj.tagName != 'undefined') {
if(obj.hasChildNodes()) {
for(var i = 0; i < obj.childNodes.length; i++) {
setUnselectable(obj.childNodes[i]);
}
}
if(obj.tagName != 'INPUT') {
obj.unselectable = 'on';
}
}
}
function writeEditorContents(text) {
if(wysiwyg) {
if(text == '' && (BROWSER.firefox || BROWSER.opera)) {
text = '<p></p>';
}
if(initialized && !(BROWSER.firefox && BROWSER.firefox >= '3' || BROWSER.opera)) {
editdoc.body.innerHTML = text;
} else {
text = '<!DOCTYPE html PUBLIC "-/' + '/W3C/' + '/DTD XHTML 1.0 Transitional/' + '/EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
'<html><head id="editorheader"><meta http-equiv="Content-Type" content="text/html; charset=' + charset + '" />' +
(BROWSER.ie && BROWSER.ie > 7 ? '<meta http-equiv="X-UA-Compatible" content="IE=7" />' : '' ) +
'<link rel="stylesheet" type="text/css" href="data/cache/style_' + STYLEID + '_wysiwyg.css?' + VERHASH + '" />' +
(BROWSER.ie ? '<script>window.onerror = function() { return true; }</script>' : '') +
'</head><body>' + text + '</body></html>';
editdoc.designMode = allowhtml ? 'on' : 'off';
editdoc = editwin.document;
editdoc.open('text/html', 'replace');
editdoc.write(text);
editdoc.close();
if(!BROWSER.ie) {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.text = 'window.onerror = function() { return true; }';
editdoc.getElementById('editorheader').appendChild(scriptNode);
}
editdoc.body.contentEditable = true;
editdoc.body.spellcheck = false;
initialized = true;
if(BROWSER.safari) {
editdoc.onclick = safariSel;
}
}
} else {
textobj.value = text;
}
setEditorStyle();
}
function safariSel(e) {
e = e.target;
if(e.tagName.match(/(img|embed)/i)) {
var sel = editwin.getSelection(),rng= editdoc.createRange(true);
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function getEditorContents() {
return wysiwyg ? editdoc.body.innerHTML : editdoc.value;
}
function setEditorStyle() {
if(wysiwyg) {
textobj.style.display = 'none';
editbox.style.display = '';
editbox.className = textobj.className;
if(BROWSER.ie) {
editdoc.body.style.border = '0px';
editdoc.body.addBehavior('#default#userData');
try{$('subject').focus();} catch(e) {editwin.focus();}
}
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
} else {
var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
if(iframe) {
textobj.style.display = '';
iframe.style.display = 'none';
}
if(BROWSER.ie) {
try{
$('subject').focus();
} catch(e) {}
}
}
if($('at_menu')) {
$('at_menu').style.display = 'none';
}
}
function setEditorEvents() {
if(BROWSER.firefox || BROWSER.opera) {
editdoc.addEventListener('mouseup', function(e) {mouseUp(e)}, true);
editdoc.addEventListener('keyup', function(e) {keyUp(e)}, true);
editwin.addEventListener('keydown', function(e) {keyDown(e)}, true);
} else if(editdoc.attachEvent) {
try{
editdoc.body.attachEvent('onmouseup', mouseUp);
editdoc.body.attachEvent('onkeyup', keyUp);
editdoc.body.attachEvent('onkeydown', keyDown);
} catch(e) {}
}
}
function mouseUp(event) {
if(wysiwyg) {
setContext();
}
for(i in EXTRAFUNC['mouseup']) {
EXTRAEVENT = event;
try {
eval(EXTRAFUNC['mouseup'][i] + '()');
} catch(e) {}
}
}
function keyUp(event) {
if(wysiwyg) {
setContext();
}
for(i in EXTRAFUNC['keyup']) {
EXTRAEVENT = event;
try {
eval(EXTRAFUNC['keyup'][i] + '()');
} catch(e) {}
}
}
function keyDown(event) {
ctlent(event);
for(i in EXTRAFUNC['keydown']) {
EXTRAEVENT = event;
try {
eval(EXTRAFUNC['keydown'][i] + '()');
} catch(e) {}
}
}
function wrapTags(tagname, useoption, selection) {
if(isUndefined(selection)) {
var selection = getSel();
if(selection === false) {
selection = '';
} else {
selection += '';
}
}
if(useoption !== false) {
var opentag = '[' + tagname + '=' + useoption + ']';
} else {
var opentag = '[' + tagname + ']';
}
var closetag = '[/' + tagname + ']';
var text = opentag + selection + closetag;
insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);
}
function applyFormat(cmd, dialog, argument) {
if(wysiwyg) {
editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
return;
}
switch(cmd) {
case 'bold':
case 'italic':
case 'underline':
case 'strikethrough':
wrapTags(cmd.substr(0, 1), false);
break;
case 'inserthorizontalrule':
insertText('[hr]', 4, 0);
break;
case 'justifyleft':
case 'justifycenter':
case 'justifyright':
wrapTags('align', cmd.substr(7));
break;
case 'fontname':
wrapTags('font', argument);
break;
case 'fontsize':
wrapTags('size', argument);
break;
case 'forecolor':
wrapTags('color', argument);
break;
case 'hilitecolor':
case 'backcolor':
wrapTags('backcolor', argument);
break;
}
}
function getCaret() {
if(wysiwyg) {
var obj = editdoc.body;
var s = document.selection.createRange();
s.setEndPoint('StartToStart', obj.createTextRange());
var matches1 = s.htmlText.match(/<\/p>/ig);
var matches2 = s.htmlText.match(/<br[^\>]*>/ig);
var fix = (matches1 ? matches1.length - 1 : 0) + (matches2 ? matches2.length : 0);
var pos = s.text.replace(/\r?\n/g, ' ').length;
if(matches3 = s.htmlText.match(/<img[^\>]*>/ig)) pos += matches3.length;
if(matches4 = s.htmlText.match(/<\/tr|table>/ig)) pos += matches4.length;
return [pos, fix];
} else {
checkFocus();
var sel = document.selection.createRange();
editbox.sel = sel;
editdoc._selectionStart = editdoc.selectionStart;
editdoc._selectionEnd = editdoc.selectionEnd;
}
}
function setCaret(pos) {
var obj = wysiwyg ? editdoc.body : editbox;
var r = obj.createTextRange();
r.moveStart('character', pos);
r.collapse(true);
r.select();
}
function isEmail(email) {
return email.length > 6 && /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(email);
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
if(wysiwyg) {
insertText(txt, false);
} else {
insertText(txt, strlen(txt), 0);
}
}
function insertAttachimgTag(aid) {
if(wysiwyg) {
insertText('<img src="' + $('image_' + aid).src + '" border="0" aid="attachimg_' + aid + '" alt="" />', false);
} else {
var txt = '[attachimg]' + aid + '[/attachimg]';
insertText(txt, strlen(txt), 0);
}
}
function insertSmiley(smilieid) {
checkFocus();
var src = $('smilie_' + smilieid).src;
var code = $('smilie_' + smilieid).alt;
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" />', false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
function discuzcode(cmd, arg) {
if(cmd != 'redo') {
addSnapshot(getEditorContents());
}
checkFocus();
if(in_array(cmd, ['sml', 'url', 'quote', 'code', 'free', 'hide', 'aud', 'vid', 'fls', 'attach', 'image', 'pasteword']) || typeof EXTRAFUNC['showEditorMenu'][cmd] != 'undefined' || cmd == 'tbl' || in_array(cmd, ['fontname', 'fontsize', 'forecolor', 'backcolor']) && !arg) {
showEditorMenu(cmd);
return;
} else if(cmd.substr(0, 3) == 'cst') {
showEditorMenu(cmd.substr(5), cmd.substr(3, 1));
return;
} else if(wysiwyg && cmd == 'inserthorizontalrule') {
insertText('<hr class="l">', 14);
} else if(cmd == 'autotypeset') {
autoTypeset();
return;
} else if(!wysiwyg && cmd == 'removeformat') {
var simplestrip = new Array('b', 'i', 'u');
var complexstrip = new Array('font', 'color', 'backcolor', 'size');
var str = getSel();
if(str === false) {
return;
}
for(var tag in simplestrip) {
str = stripSimple(simplestrip[tag], str);
}
for(var tag in complexstrip) {
str = stripComplex(complexstrip[tag], str);
}
insertText(str);
} else if(cmd == 'undo') {
addSnapshot(getEditorContents());
moveCursor(-1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(cmd == 'redo') {
moveCursor(1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
var listtype = cmd == 'insertorderedlist' ? '1' : '';
var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
var closetag = '[/list]';
if(txt = getSel()) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
while(listvalue = prompt('输入一个列表项目.\r\n留空或者点击取消完成此列表.', '')) {
if(BROWSER.opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertText(listvalue, strlen(listvalue) + 1, 0);
} else {
listvalue = '[*]' + listvalue + '\n';
insertText(listvalue, strlen(listvalue), 0);
}
}
}
} else if(!wysiwyg && cmd == 'unlink') {
var sel = getSel();
sel = stripSimple('url', sel);
sel = stripComplex('url', sel);
insertText(sel);
} else if(cmd == 'floatleft' || cmd == 'floatright') {
var arg = cmd == 'floatleft' ? 'left' : 'right';
if(wysiwyg) {
if(txt = getSel()) {
argm = arg == 'left' ? 'right' : 'left';
insertText('<br style="clear: both"><table class="float" style="float: ' + arg + '; margin-' + argm + ': 5px;"><tbody><tr><td>' + txt + '</td></tr></tbody></table>', true);
}
} else {
var opentag = '[float=' + arg + ']';
var closetag = '[/float]';
if(txt = getSel()) {
txt = opentag + txt + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
}
}
} else if(cmd == 'rst') {
loadData();
setEditorTip('数据已恢复');
} else if(cmd == 'svd') {
saveData();
setEditorTip('数据已保存');
} else if(cmd == 'chck') {
checklength(editorform);
} else if(cmd == 'tpr') {
if(confirm('您确认要清除所有内容吗?')) {
clearContent();
}
} else if(cmd == 'downremoteimg') {
showDialog('<div id="remotedowninfo"><p class="mbn">正在下载远程附件,请稍等……</p><p><img src="' + STATICURL + 'image/common/uploading.gif" alt="" /></p></div>', 'notice', '', null, 1);
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!editorform.parseurloff.checked ? parseurl(editorform.message.value) : editorform.message.value);
var oldValidate = editorform.onsubmit;
var oldAction = editorform.action;
editorform.onsubmit = '';
editorform.action = 'forum.php?mod=ajax&action=downremoteimg&fid='+fid+'&wysiwyg='+(wysiwyg ? 1 : 0);
editorform.target = "ajaxpostframe";
editorform.message.value = message;
editorform.submit();
editorform.onsubmit = oldValidate;
editorform.action = oldAction;
editorform.target = "";
} else {
var formatcmd = cmd == 'backcolor' && !BROWSER.ie ? 'hilitecolor' : cmd;
try {
var ret = applyFormat(formatcmd, false, (isUndefined(arg) ? true : arg));
} catch(e) {
var ret = false;
}
}
if(cmd != 'undo') {
addSnapshot(getEditorContents());
}
if(wysiwyg) {
setContext(cmd);
}
if(in_array(cmd, ['bold', 'italic', 'underline', 'strikethrough', 'inserthorizontalrule', 'fontname', 'fontsize', 'forecolor', 'backcolor', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'floatleft', 'floatright', 'removeformat', 'unlink', 'undo', 'redo'])) {
hideMenu();
}
doane();
return ret;
}
function setContext(cmd) {
var cmd = !cmd ? '' : cmd;
var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
for(var i in contextcontrols) {
var controlid = contextcontrols[i];
var obj = $(editorid + '_' + controlid);
if(obj != null) {
if(cmd == 'clear') {
obj.className = '';
continue;
}
try {
var state = editdoc.queryCommandState(contextcontrols[i]);
} catch(e) {
var state = false;
}
if(isUndefined(obj.state)) {
obj.state = false;
}
if(obj.state != state) {
obj.state = state;
buttonContext(obj, state ? 'mouseover' : 'mouseout');
}
}
}
try {
var fs = editdoc.queryCommandValue('fontname');
} catch(e) {
fs = null;
}
if(fs == '' && !BROWSER.ie && window.getComputedStyle) {
fs = editdoc.body.style.fontFamily;
} else if(fs == null) {
fs = '';
}
fs = fs && cmd != 'clear' ? fs : '字体';
if(fs != $(editorid + '_font').fontstate) {
thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
$(editorid + '_font').innerHTML = thingy;
$(editorid + '_font').fontstate = fs;
}
try {
var ss = editdoc.queryCommandValue('fontsize');
if(ss == null || ss == '' || cmd == 'clear') {
ss = formatFontsize(editdoc.body.style.fontSize);
} else {
var ssu = ss.substr(-2);
if(ssu == 'px' || ssu == 'pt') {
ss = formatFontsize(ss);
}
}
} catch(e) {
ss = '大小';
}
if(ss != $(editorid + '_size').sizestate) {
if($(editorid + '_size').sizestate == null) {
$(editorid + '_size').sizestate = '';
}
$(editorid + '_size').innerHTML = ss;
$(editorid + '_size').sizestate = ss;
}
}
function buttonContext(obj, state) {
if(state == 'mouseover') {
obj.style.cursor = 'pointer';
var mode = obj.state ? 'down' : 'hover';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = 'hover';
}
} else {
var mode = obj.state ? 'selected' : 'normal';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = mode == 'selected' ? 'hover' : '';
}
}
}
function formatFontsize(csssize) {
switch(csssize) {
case '7.5pt':
case '10px': return 1;
case '13px':
case '10pt': return 2;
case '16px':
case '12pt': return 3;
case '18px':
case '14pt': return 4;
case '24px':
case '18pt': return 5;
case '32px':
case '24pt': return 6;
case '48px':
case '36pt': return 7;
default: return '大小';
}
}
function showEditorMenu(tag, params) {
var sel, selection;
var str = '', strdialog = 0, stitle = '';
var ctrlid = editorid + (params ? '_cst' + params + '_' : '_') + tag;
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
var menu = $(ctrlid + '_menu');
var pos = [0, 0];
var menuwidth = 270;
var menupos = '43!';
var menutype = 'menu';
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
pos = getCaret();
}
selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
if(menu) {
if($(ctrlid).getAttribute('menupos') !== null) {
menupos = $(ctrlid).getAttribute('menupos');
}
if($(ctrlid).getAttribute('menuwidth') !== null) {
menu.style.width = $(ctrlid).getAttribute('menuwidth') + 'px';
}
if(menupos == '00') {
menu.className = 'fwinmask';
if($(editorid + '_' + tag + '_menu').style.visibility == 'hidden') {
$(editorid + '_' + tag + '_menu').style.visibility = 'visible';
} else {
showMenu({'ctrlid':ctrlid,'mtype':'win','evt':'click','pos':menupos,'timeout':250,'duration':3,'drag':ctrlid + '_ctrl'});
}
} else {
showMenu({'ctrlid':ctrlid,'evt':'click','pos':menupos,'timeout':250,'duration':in_array(tag, ['fontname', 'fontsize', 'sml']) ? 2 : 3,'drag':1});
}
} else {
switch(tag) {
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" />'+
(selection ? '' : '<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />');
break;
case 'forecolor':
showColorBox(ctrlid, 1);
return;
case 'backcolor':
showColorBox(ctrlid, 1, '', 1);
return;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'hide':
case 'free':
if(selection) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var lang = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码', 'hide' : '请输入要隐藏的信息内容', 'free' : '如果您设置了帖子售价,请输入购买前免费可见的信息内容'};
str += lang[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>' +
(tag == 'hide' ? '<br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_1" class="pc" checked="checked" />只有当浏览者回复本帖时才显示</label><br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_2" class="pc" />只有当浏览者积分高于</label> <input type="text" size="3" id="' + ctrlid + '_param_2" class="px pxs" /> 时才显示<br /><br /><label>有效天数:</label> <input type="text" size="3" id="' + ctrlid + '_param_3" class="px pxs" /> <br />距离发帖日期大于这个天数时标签自动失效' : '');
break;
case 'tbl':
str = '<p class="pbn">表格行数: <input type="text" id="' + ctrlid + '_param_1" size="2" value="2" class="px" /> 表格列数: <input type="text" id="' + ctrlid + '_param_2" size="2" value="2" class="px" /></p><p class="pbn">表格宽度: <input type="text" id="' + ctrlid + '_param_3" size="2" value="" class="px" /> 背景颜色: <input type="text" id="' + ctrlid + '_param_4" size="2" class="px" onclick="showColorBox(this.id, 2)" /></p><p class="xg2 pbn" style="cursor:pointer" onclick="showDialog($(\'tbltips_msg\').innerHTML, \'notice\', \'小提示\', null, 0)"><img id="tbltips" title="小提示" class="vm" src="' + IMGDIR + '/info_small.gif"> 快速书写表格提示</p>';
str += '<div id="tbltips_msg" style="display: none">“[tr=颜色]” 定义行背景<br />“[td=宽度]” 定义列宽<br />“[td=列跨度,行跨度,宽度]” 定义行列跨度<br /><br />快速书写表格范例:<div class=\'xs0\' style=\'margin:0 5px\'>[table]<br />Name:|Discuz!<br />Version:|X1<br />[/table]</div>用“|”分隔每一列,表格中如有“|”用“\\|”代替,换行用“\\n”代替。</div>';
break;
case 'aud':
str = '<p class="pbn">请输入音乐文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="xg2 pbn">支持 wma mp3 ra rm 等音乐格式<br />示例: http://server/audio.wma</p>';
break;
case 'vid':
str = '<p class="pbn">请输入视频地址:</p><p class="pbn"><input type="text" value="" id="' + ctrlid + '_param_1" style="width: 220px;" class="px" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="500" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="375" class="px" /></p><p class="xg2 pbn">支持优酷、土豆、56、酷6等视频站的视频网址<br />支持 wmv avi rmvb mov swf flv 等视频格式<br />示例: http://server/movie.wmv</p>';
break;
case 'fls':
str = '<p class="pbn">请输入 Flash 文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="" class="px" /></p><p class="xg2 pbn">支持 swf flv 等 Flash 网址<br />示例: http://server/flash.swf</p>';
break;
case 'pasteword':
stitle = '从 Word 粘贴内容';
str = '<p class="px" style="height:300px"><iframe id="' + ctrlid + '_param_1" frameborder="0" style="width:100%;height:100%" onload="this.contentWindow.document.body.style.width=\'550px\';this.contentWindow.document.body.contentEditable=true;this.contentWindow.document.body.focus();this.onload=null"></iframe></p><p class="xg2 pbn">请通过快捷键(Ctrl+V)把 Word 文件中的内容粘贴到上方</p>';
menuwidth = 600;
menupos = '00';
menutype = 'win';
break;
default:
for(i in EXTRAFUNC['showEditorMenu']) {
EXTRASELECTION = selection;
EXTRASEL = sel;
try {
eval('str = ' + EXTRAFUNC['showEditorMenu'][i] + '(\'' + tag + '\', 0)');
} catch(e) {}
}
if(!str) {
str = '';
var haveSel = selection == null || selection == false || in_array(trim(selection), ['', 'null', 'undefined', 'false']) ? 0 : 1;
if(params == 1 && haveSel) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var promptlang = custombbcodes[tag]['prompt'].split("\t");
for(var i = 1; i <= params; i++) {
if(i != params || !haveSel) {
str += (promptlang[i - 1] ? promptlang[i - 1] : '请输入第 ' + i + ' 个参数:') + '<br /><input type="text" id="' + ctrlid + '_param_' + i + '" style="width: 98%" value="" class="px" />' + (i < params ? '<br />' : '');
}
}
}
break;
}
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = menuwidth + 'px';
if(menupos == '00') {
menu.className = 'fwinmask';
s = '<table width="100%" cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c">'
+ '<h3 class="flb"><em>' + stitle + '</em><span><a onclick="hideMenu(\'\', \'win\');return false;" class="flbc" href="javascript:;">关闭</a></span></h3><div class="c">' + str + '</div>'
+ '<p class="o pns"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></p>'
+ '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
} else {
s = '<div class="p_opt cl"><span class="y" style="margin:-10px -10px 0 0"><a onclick="hideMenu();return false;" class="flbc" href="javascript:;">关闭</a></span><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></div></div>';
}
menu.innerHTML = s;
$(editorid + '_editortoolbar').appendChild(menu);
showMenu({'ctrlid':ctrlid,'mtype':menutype,'evt':'click','duration':3,'cache':0,'drag':1,'pos':menupos});
}
try {
if($(ctrlid + '_param_1')) {
$(ctrlid + '_param_1').focus();
}
} catch(e) {}
var objs = menu.getElementsByTagName('*');
for(var i = 0; i < objs.length; i++) {
_attachEvent(objs[i], 'keydown', function(e) {
e = e ? e : event;
obj = BROWSER.ie ? event.srcElement : e.target;
if((obj.type == 'text' && e.keyCode == 13) || (obj.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
if($(ctrlid + '_submit') && tag != 'image') $(ctrlid + '_submit').click();
doane(e);
} else if(e.keyCode == 27) {
hideMenu();
doane(e);
}
});
}
if($(ctrlid + '_submit')) $(ctrlid + '_submit').onclick = function() {
checkFocus();
if(BROWSER.ie && wysiwyg) {
setCaret(pos[0]);
}
switch(tag) {
case 'url':
var href = $(ctrlid + '_param_1').value;
href = (isEmail(href) ? 'mailto:' : '') + href;
if(href != '') {
var v = selection ? selection : ($(ctrlid + '_param_2').value ? $(ctrlid + '_param_2').value : href);
str = wysiwyg ? ('<a href="' + href + '">' + v + '</a>') : '[url=' + squarestrip(href) + ']' + v + '[/url]';
if(wysiwyg) insertText(str, str.length - v.length, 0, (selection ? true : false), sel);
else insertText(str, str.length - v.length - 6, 6, (selection ? true : false), sel);
}
break;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'hide':
case 'free':
if(tag == 'hide') {
var mincredits = parseInt($(ctrlid + '_param_2').value);
var expire = parseInt($(ctrlid + '_param_3').value);
if(expire > 0 || (mincredits > 0 && $(ctrlid + '_radio_2').checked)) {
opentag = '[hide=';
if(expire > 0) {
opentag += 'd'+expire;
}
if(mincredits > 0 && $(ctrlid + '_radio_2').checked) {
opentag += (expire > 0 ? ',' : '')+mincredits;
}
opentag += ']';
} else {
opentag = '[hide]';
}
}
str = $(ctrlid + '_param_1') && $(ctrlid + '_param_1').value ? $(ctrlid + '_param_1').value : (selection ? selection : '');
if(wysiwyg) {
str = preg_replace(['<', '>'], ['<', '>'], str);
str = str.replace(/\r?\n/g, '<br />');
}
str = opentag + str + closetag;
insertText(str, strlen(opentag), strlen(closetag), false, sel);
break;
case 'tbl':
var rows = $(ctrlid + '_param_1').value;
var columns = $(ctrlid + '_param_2').value;
var width = $(ctrlid + '_param_3').value;
var bgcolor = $(ctrlid + '_param_4').value;
rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
bgcolor = /[\(\)%,#\w]+/.test(bgcolor) ? bgcolor : '';
if(wysiwyg) {
str = '<table cellspacing="0" cellpadding="0" style="width:' + (width ? width : '50%') + '" class="t_table"' + (bgcolor ? ' bgcolor="' + bgcolor + '"' : '') + '>';
for (var row = 0; row < rows; row++) {
str += '<tr>\n';
for (col = 0; col < columns; col++) {
str += '<td> </td>\n';
}
str += '</tr>\n';
}
str += '</table>\n';
} else {
str = '[table=' + (width ? width : '50%') + (bgcolor ? ',' + bgcolor : '') + ']\n';
for (var row = 0; row < rows; row++) {
str += '[tr]';
for (col = 0; col < columns; col++) {
str += '[td] [/td]';
}
str += '[/tr]\n';
}
str += '[/table]\n';
}
insertText(str, str.length, 0, false, sel);
break;
case 'aud':
insertText('[audio]' + $(ctrlid + '_param_1').value + '[/audio]', 7, 8, false, sel);
break;
case 'fls':
if($(ctrlid + '_param_2').value && $(ctrlid + '_param_3').value) {
insertText('[flash=' + parseInt($(ctrlid + '_param_2').value) + ',' + parseInt($(ctrlid + '_param_3').value) + ']' + squarestrip($(ctrlid + '_param_1').value) + '[/flash]', 7, 8, false, sel);
} else {
insertText('[flash]' + squarestrip($(ctrlid + '_param_1').value) + '[/flash]', 7, 8, false, sel);
}
break;
case 'vid':
var mediaUrl = $(ctrlid + '_param_1').value;
var auto = '';
var ext = mediaUrl.lastIndexOf('.') == -1 ? '' : mediaUrl.substr(mediaUrl.lastIndexOf('.') + 1, mb_strlen(mediaUrl)).toLowerCase();
ext = in_array(ext, ['mp3', 'wma', 'ra', 'rm', 'ram', 'mid', 'asx', 'wmv', 'avi', 'mpg', 'mpeg', 'rmvb', 'asf', 'mov', 'flv', 'swf']) ? ext : 'x';
if(ext == 'x') {
if(/^mms:\/\//.test(mediaUrl)) {
ext = 'mms';
} else if(/^(rtsp|pnm):\/\//.test(mediaUrl)) {
ext = 'rtsp';
}
}
var str = '[media=' + ext + ',' + $(ctrlid + '_param_2').value + ',' + $(ctrlid + '_param_3').value + ']' + squarestrip(mediaUrl) + '[/media]';
insertText(str, str.length, 0, false, sel);
break;
case 'image':
var width = parseInt($(ctrlid + '_param_2').value);
var height = parseInt($(ctrlid + '_param_3').value);
var src = $(ctrlid + '_param_1').value;
var style = '';
if(wysiwyg) {
style += width ? ' width=' + width : '';
style += height ? ' height=' + height : '';
var str = '<img src=' + src + style + ' border=0 />';
insertText(str, str.length, 0, false, sel);
} else {
style += width || height ? '=' + width + ',' + height : '';
insertText('[img' + style + ']' + squarestrip(src) + '[/img]', 0, 0, false, sel);
}
hideMenu('', 'win');
$(ctrlid + '_param_1').value = '';
break;
case 'pasteword':
pasteWord($(ctrlid + '_param_1').contentWindow.document.body.innerHTML);
hideMenu('', 'win');
break;
default:
for(i in EXTRAFUNC['showEditorMenu']) {
EXTRASELECTION= selection;
try {
eval('str = ' + EXTRAFUNC['showEditorMenu'][i] + '(\'' + tag + '\', 1)');
} catch(e) {}
}
if(!str) {
str = '';
var first = $(ctrlid + '_param_1').value;
if($(ctrlid + '_param_2')) var second = $(ctrlid + '_param_2').value;
if($(ctrlid + '_param_3')) var third = $(ctrlid + '_param_3').value;
if((params == 1 && first) || (params == 2 && first && (haveSel || second)) || (params == 3 && first && second && (haveSel || third))) {
if(params == 1) {
str = first;
} else if(params == 2) {
str = haveSel ? selection : second;
opentag = '[' + tag + '=' + first + ']';
} else {
str = haveSel ? selection : third;
opentag = '[' + tag + '=' + first + ',' + second + ']';
}
insertText((opentag + str + closetag), strlen(opentag), strlen(closetag), true, sel);
}
}
break;
}
hideMenu();
};
}
function autoTypeset() {
var sel;
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
}
var selection = sel ? (wysiwyg ? sel.htmlText.replace(/<\/?p>/ig, '<br />') : sel.text) : getSel();
selection = trim(selection);
selection = wysiwyg ? selection.replace(/<br( \/)?>(<br( \/)?>)+/ig, '</p>\n<p style="line-height: 30px; text-indent: 2em;">') : selection.replace(/\n\n+/g, '[/p]\n[p=30, 2, left]');
opentag = wysiwyg ? '<p style="line-height: 30px; text-indent: 2em;">' : '[p=30, 2, left]';
var s = opentag + selection + (wysiwyg ? '</p>' : '[/p]');
insertText(s, strlen(opentag), 4, false, sel);
hideMenu();
}
function getSel() {
if(wysiwyg) {
try {
selection = editwin.getSelection();
checkFocus();
range = selection ? selection.getRangeAt(0) : editdoc.createRange();
return readNodes(range.cloneContents(), false);
} catch(e) {
try {
var range = editdoc.selection.createRange();
if(range.htmlText && range.text) {
return range.htmlText;
} else {
var htmltext = '';
for(var i = 0; i < range.length; i++) {
htmltext += range.item(i).outerHTML;
}
return htmltext;
}
} catch(e) {
return '';
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
}
function insertText(text, movestart, moveend, select, sel) {
checkFocus();
if(wysiwyg) {
try {
editdoc.execCommand('insertHTML', false, text);
} catch(e) {
if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
movestart = false;
editdoc.selection.clear();
}
if(isUndefined(sel)) {
sel = editdoc.selection.createRange();
}
sel.pasteHTML(text);
if(text.indexOf('\n') == -1) {
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) + movestart);
sel.moveEnd('character', -moveend);
} else if(movestart != false) {
sel.moveStart('character', -strlen(text));
}
if(!isUndefined(select) && select) {
sel.select();
}
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
if(editdoc._selectionStart) {
editdoc.selectionStart = editdoc._selectionStart;
editdoc.selectionEnd = editdoc._selectionEnd;
editdoc._selectionStart = 0;
editdoc._selectionEnd = 0;
}
var opn = editdoc.selectionStart + 0;
editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
if(!isUndefined(movestart)) {
editdoc.selectionStart = opn + movestart;
editdoc.selectionEnd = opn + strlen(text) - moveend;
} else if(movestart !== false) {
editdoc.selectionStart = opn;
editdoc.selectionEnd = opn + strlen(text);
}
} else if(document.selection && document.selection.createRange) {
if(isUndefined(sel)) {
sel = document.selection.createRange();
}
if(editbox.sel) {
sel = editbox.sel;
editbox.sel = null;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) +movestart);
sel.moveEnd('character', -moveend);
} else if(movestart !== false) {
sel.moveStart('character', -strlen(text));
}
sel.select();
} else {
editdoc.value += text;
}
}
checkFocus();
}
function stripSimple(tag, str, iterations) {
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
}
return str;
}
function readNodes(root, toptag) {
var html = "";
var moz_check = /_moz/i;
switch(root.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
var closed;
if(toptag) {
closed = !root.hasChildNodes();
html = '<' + root.tagName.toLowerCase();
var attr = root.attributes;
for(var i = 0; i < attr.length; ++i) {
var a = attr.item(i);
if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
continue;
}
html += " " + a.name.toLowerCase() + '="' + a.value + '"';
}
html += closed ? " />" : ">";
}
for(var i = root.firstChild; i; i = i.nextSibling) {
html += readNodes(i, true);
}
if(toptag && !closed) {
html += "</" + root.tagName.toLowerCase() + ">";
}
break;
case Node.TEXT_NODE:
html = htmlspecialchars(root.data);
break;
}
return html;
}
function stripComplex(tag, str, iterations) {
var opentag = '[' + tag + '=';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var openend = stripos(str, ']', startindex);
if(openend !== false && openend > startindex && openend < stopindex) {
var text = str.substr(openend + 1, stopindex - openend - 1);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
} else {
break;
}
}
return str;
}
function stripos(haystack, needle, offset) {
if(isUndefined(offset)) {
offset = 0;
}
var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return (index == -1 ? false : index);
}
function switchEditor(mode) {
if(mode == wysiwyg || !allowswitcheditor) {
return;
}
if(!mode) {
var controlbar = $(editorid + '_controls');
var controls = [];
var buttons = controlbar.getElementsByTagName('a');
var buttonslength = buttons.length;
for(var i = 0; i < buttonslength; i++) {
if(buttons[i].id) {
controls[controls.length] = buttons[i].id;
}
}
var controlslength = controls.length;
for(var i = 0; i < controlslength; i++) {
var control = $(controls[i]);
if(control.id.indexOf(editorid + '_') != -1) {
control.state = false;
control.mode = 'normal';
} else if(control.id.indexOf(editorid + '_popup_') != -1) {
control.state = false;
}
}
setContext('clear');
}
cursor = -1;
stack = [];
var parsedtext = getEditorContents();
parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
wysiwyg = mode;
$(editorid + '_mode').value = mode;
newEditor(mode, parsedtext);
setEditorStyle();
editwin.focus();
setCaretAtEnd();
}
function setCaretAtEnd() {
if(wysiwyg) {
editdoc.body.innerHTML += '';
} else {
editdoc.value += '';
}
}
function moveCursor(increment) {
var test = cursor + increment;
if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
cursor += increment;
}
}
function addSnapshot(str) {
if(stack[cursor] == str) {
return;
} else {
cursor++;
stack[cursor] = str;
if(!isUndefined(stack[cursor + 1])) {
stack[cursor + 1] = null;
}
}
}
function getSnapshot() {
if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
return stack[cursor];
} else {
return false;
}
}
function squarestrip(str) {
str = str.replace('[', '%5B');
str = str.replace(']', '%5D');
return str;
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
}
if(typeof jsloaded == 'function') {
jsloaded('editor');
} | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: space_diy.js 23838 2011-08-11 06:51:58Z monkey $
*/
var drag = new Drag();
drag.extend({
setDefalutMenu : function () {
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
},
removeBlock : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
id = e.aim.id.replace('cmd_','');
} else {
id = e;
}
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
$(id).parentNode.removeChild($(id));
var el = $('chk'+id);
if (el != null) el.className = '';
this.initPosition();
this.initChkBlock();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.className = 'activity';
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
toggleBlock : function (blockname) {
var el = $('chk'+blockname);
if (el != null) {
if (el.className == '') {
this.getBlockData(blockname);
el.className = 'activity';
} else {
this.removeBlock(blockname);
this.initPosition();
}
this.setClose();
}
},
getBlockData : function (blockname) {
var el = $(blockname);
if (el != null) {
Util.show(blockname);
} else {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=index&op=getblock&blockname='+blockname+'&inajax=1',function(s) {
if (s) {
el = document.createElement("div");
el.className = drag.blockClass + ' ' + drag.moveableObject;
el.id = blockname;
s = s.replace(/\<script.*\<\/script\>/ig,'<font color="red"> [javascript脚本保存后显示] </font>');
el.innerHTML = s;
var id = drag.data['diypage'][0]['columns']['frame1_left']['children'][0]['name'];
$('frame1_left').insertBefore(el,$(id));
drag.initPosition();
}
});
}
},
openBlockEdit : function (e) {
e = Util.event(e);
var blockname = e.aim.id.replace('cmd_','');
this.removeMenu();
showWindow('showblock', 'home.php?mod=spacecp&ac=index&op=edit&blockname='+blockname,'get',0);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save:function () {
drag.clearClose();
document.diyform.spacecss.value = this.getSpacecssStr();
document.diyform.style.value = this.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.currentlayout.value = this.currentLayout;
document.diyform.submit();
},
getdiy : function (type) {
var type_ = type == 'image' ? 'diy' : type;
if (type_) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
}
}
$('nav'+type_).className = 'current';
var para = '&op='+type;
if (arguments.length > 1) {
for (i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'image' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('home.php?mod=spacecp&ac=index'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s) {
if (s) {
drag.deleteFrame(['pb', 'bpb', 'tpb', 'lpb']);
if (type == 'image') {
$('diyimages').innerHTML = s;
} else {
$('controlcontent').innerHTML = s;
x.showId = 'controlcontent';
}
if (type_ == 'block') {
drag.initPosition();
drag.initChkBlock();
} else if (type_ == 'layout') {
$('layout'+spaceDiy.currentLayout).className = 'activity';
} else if (type_ == 'diy' && type != 'image') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
},
menuChange : function (tabs, menu) {
var tabobj = $(tabs);
var aobj = tabobj.getElementsByTagName("li");
for(i=0; i<aobj.length; i++) {
aobj[i].className = '';
$(aobj[i].id+'_content').style.display = 'none';
}
$(menu).className = 'a';
$(menu+'_content').style.display="block";
doane(null);
},
delIframe : function (){
drag.deleteFrame(['m_ctc', 'm_bc', 'm_fc']);
},
showEditSpaceInfo : function () {
$('spaceinfoshow').style.display='none';
if (!$('spaceinfoedit')) {
var dom = document.createElement('h2');
dom.id = 'spaceinfoedit';
Util.insertBefore(dom, $('spaceinfoshow'));
}
ajaxget('home.php?mod=spacecp&ac=index&op=getspaceinfo','spaceinfoedit');
},
spaceInfoCancel : function () {
if ($('spaceinfoedit')) $('spaceinfoedit').style.display = 'none';
if ($('spaceinfoshow')) $('spaceinfoshow').style.display = 'inline';
},
spaceInfoSave : function () {
ajaxpost('savespaceinfo','spaceinfoshow');
},
init : function () {
drag.init();
this.style = document.diyform.style.value;
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
this.initSpaceInfo();
},
initSpaceInfo : function () {
this.spaceInfoCancel();
if ($('spaceinfoshow')) {
if (!$('infoedit')) {
var dom = document.createElement('em');
dom.id = 'infoedit';
dom.innerHTML = '编辑';
$('spacename').appendChild(dom);
}
$('spaceinfoshow').onmousedown = function () {spaceDiy.showEditSpaceInfo();};
}
if ($('nv')) {
if(!$('nv').getElementsByTagName('li').length) {
$('nv').getElementsByTagName('ul')[0].className = 'mininv';
}
$('nv').onmouseover = function () {spaceDiy.showEditNvInfo();};
$('nv').onmouseout = function () {spaceDiy.hideEditNvInfo();};
}
},
showEditNvInfo : function () {
var nv = $('editnvinfo');
if(!nv) {
var dom = document.createElement('div');
dom.innerHTML = '<span id="editnvinfo" class="edit" style="background-color:#336699;" onclick="spaceDiy.opNvEditInfo();">设置</span>';
$('nv').appendChild(dom.childNodes[0]);
} else {
nv.style.display = '';
}
},
hideEditNvInfo : function () {
var nv = $('editnvinfo');
if(nv) {
nv.style.display = 'none';
}
},
opNvEditInfo : function () {
showWindow('showpersonalnv', 'home.php?mod=spacecp&ac=index&op=editnv','get',0);
},
getPersonalNv : function (show) {
var x = new Ajax();
show = !show ? '' : '&show=1';
x.get('home.php?mod=spacecp&ac=index&op=getpersonalnv&inajax=1'+show, function(s) {
if($('nv')) {
$('hd').removeChild($('nv'));
}
var dom = document.createElement('div');
dom.innerHTML = !s ? ' ' : s;
$('hd').appendChild(dom.childNodes[0]);
spaceDiy.initSpaceInfo();
});
}
});
spaceDiy.init(); | JavaScript |
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: google.js 23838 2011-08-11 06:51:58Z monkey $
*/
document.writeln('<script type="text/javascript">');
document.writeln('function validate_google(theform) {');
document.writeln(' if(theform.site.value == 1) {');
document.writeln(' theform.q.value = \'site:' + google_host + ' \' + theform.q.value;');
document.writeln(' }');
document.writeln('}');
document.writeln('function submitFormWithChannel(channelname) {');
document.writeln(' document.gform.channel.value=channelname;');
document.writeln(' document.gform.submit();');
document.writeln(' return;');
document.writeln('}');
document.writeln('</script>');
document.writeln('<form name="gform" id="gform" method="get" autocomplete="off" action="http://www.google.com/search?" target="_blank" onSubmit="validate_google(this);">');
document.writeln('<input type="hidden" name="client" value="' + (!google_client ? 'aff-discuz' : google_client) + '" />');
document.writeln('<input type="hidden" name="ie" value="' + google_charset + '" />');
document.writeln('<input type="hidden" name="oe" value="UTF-8" />');
document.writeln('<input type="hidden" name="hl" value="' + google_hl + '" />');
document.writeln('<input type="hidden" name="lr" value="' + google_lr + '" />');
document.writeln('<input type="hidden" name="channel" value="search" />');
document.write('<div onclick="javascript:submitFormWithChannel(\'logo\')" style="cursor:pointer;float: left;width:70px;height:23px;background: url(' + STATICURL + 'image/common/Google_small.png) !important;background: none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + STATICURL+ 'image/common/Google_small.png\', sizingMethod=\'scale\')"><img src="' + STATICURL + 'image/common/none.gif" border="0" alt="Google" /></div>');
document.writeln(' <input type="text" class="txt" size="20" name="q" id="q" maxlength="255" value=""></input>');
document.writeln('<select name="site">');
document.writeln('<option value="0"' + google_default_0 + '>网页搜索</option>');
document.writeln('<option value="1"' + google_default_1 + '>站内搜索</option>');
document.writeln('</select>');
document.writeln(' <button type="submit" name="sa" value="true">搜索</button>');
document.writeln('</form>'); | JavaScript |
function uploadEdit(obj) {
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
edit_save();
upload();
}
function edit_save() {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status == 'code') {
$('uchome-ttHtmlEditor').value = p.document.getElementById('sourceEditor').value;
} else if(status == 'text') {
if(BROWSER.ie) {
obj.document.body.innerText = p.document.getElementById('dvtext').value;
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
} else {
obj.document.body.textContent = p.document.getElementById('dvtext').value;
var sOutText = obj.document.body.innerHTML;
$('uchome-ttHtmlEditor').value = sOutText.replace(/\r\n|\n/g,"<br>");
}
} else {
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
}
backupContent($('uchome-ttHtmlEditor').value);
}
function relatekw() {
edit_save();
var subject = cnCode($('subject').value);
var message = cnCode($('uchome-ttHtmlEditor').value);
if(message) {
message = message.substr(0, 500);
}
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=relatekw&inajax=1&subjectenc=' + subject + '&messageenc=' + message, function(s){
$('tag').value = s;
});
}
function downRemoteFile() {
edit_save();
var formObj = $("articleform");
var oldAction = formObj.action;
formObj.action = "portal.php?mod=portalcp&ac=upload&op=downremotefile";
formObj.onSubmit = "";
formObj.target = "uploadframe";
formObj.submit();
formObj.action = oldAction;
formObj.target = "";
}
function backupContent(sHTML) {
if(sHTML.length > 11) {
var obj = $('uchome-ttHtmlEditor').form;
if(!obj) return;
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject' || el.name == 'title') {
subject = trim(elvalue);
} else if(el.name == 'message' || el.name == 'content') {
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message) {
return;
}
saveUserdata('home', data);
}
}
function edit_insert(html) {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status != 'html') {
alert('本操作只在多媒体编辑模式下才有效');
return;
}
obj.focus();
if(BROWSER.ie){
var f = obj.document.selection.createRange();
f.pasteHTML(html);
f.collapse(false);
f.select();
} else {
obj.document.execCommand('insertHTML', false, html);
}
}
function insertImage(image, url, width, height) {
url = typeof url == 'undefined' || url === null ? image : url;
width = typeof width == 'undefined' || width === null ? 0 : parseInt(width);
height = typeof height == 'undefined' || height === null ? 0 : parseInt(height);
var html = '<p><a href="' + url + '" target="_blank"><img src="'+image+'"'+(width?' width="'+width+'"':'')+(height?' height="'+height+'"':'')+'></a></p>';
edit_insert(html);
}
function insertFile(file, url) {
url = typeof url == 'undefined' || url === null ? image : url;
var html = '<p><a href="' + url + '" target="_blank" class="attach">' + file + '</a></p>';
edit_insert(html);
}
function createImageBox(fn) {
if(typeof fn == 'function' && !fn()) {
return false;
}
var menu = $('icoImg_image_menu');
if(menu) {
if(menu.style.visibility == 'hidden') {
menu.style.visibility = 'visible';
} else {
menu.style.width = '600px';
showMenu({'ctrlid':'icoImg_image','mtype':'win','evt':'click','pos':'00','timeout':250,'duration':3,'drag':'icoImg_image_ctrl'});
}
}
}
function createAttachBox(fn) {
if(typeof fn == 'function' && !fn()) {
return false;
}
var menu = $('icoAttach_attach_menu');
if(menu) {
if(menu.style.visibility == 'hidden') {
menu.style.visibility = 'visible';
} else {
menu.style.width = '600px';
showMenu({'ctrlid':'icoAttach_attach','mtype':'win','evt':'click','pos':'00','timeout':250,'duration':3,'drag':'icoAttach_attach_ctrl'});
}
}
}
function switchButton(btn, type) {
var btnpre = 'icoImg_btn_';
if(!$(btnpre + btn) || !$('icoImg_' + btn)) {
return;
}
var tabs = $('icoImg_' + type + '_ctrl').getElementsByTagName('LI');
$(btnpre + btn).style.display = '';
$('icoImg_' + btn).style.display = '';
$(btnpre + btn).className = 'current';
var btni = '';
for(i = 0;i < tabs.length;i++) {
if(tabs[i].id.indexOf(btnpre) !== -1) {
btni = tabs[i].id.substr(btnpre.length);
}
if(btni != btn) {
if(!$('icoImg_' + btni) || !$('icoImg_btn_' + btni)) {
continue;
}
$('icoImg_' + btni).style.display = 'none';
$('icoImg_btn_' + btni).className = '';
}
}
}
function changeEditFull(flag) {
var ifrHtmlEditor = $('uchome-ifrHtmlEditor');
var editor = ifrHtmlEditor.parentNode;
if(flag) {
document.body.scroll = 'no';
document.body.style.overflow = 'hidden';
window.resize = function(){changeEditFull(1)};
editor.style.top = '0';
editor.style.left = '0';
editor.style.position = 'fixed';
editor.style.width = '100%';
editor.setAttribute('srcheight', editor.style.height);
editor.style.height = '100%';
editor.style.minWidth = '800px';
editor.style.zIndex = '300';
ifrHtmlEditor.style.height = '100%';
ifrHtmlEditor.style.zoom = ifrHtmlEditor.style.zoom=="1"?"100%":"1";
} else {
document.body.scroll = 'yes';
document.body.style.overflow = 'auto';
window.resize = null;
editor.style.position = '';
editor.style.width = '';
editor.style.height = editor.getAttribute('srcheight');
}
doane();
}
function showInnerNav(){
var navtitle = $('innernavele');
var pagetitle = $('pagetitle');
if(navtitle && navtitle.style.display == 'none') {
navtitle.style.display = '';
}
if(pagetitle && pagetitle.style.display == 'none') {
pagetitle.style.display = '';
}
} | JavaScript |
var gSetColorType = "";
var gIsIE = document.all;
var gIEVer = fGetIEVer();
var gLoaded = false;
var ev = null;
var gIsHtml = true;
var pos = 0;
var sLength = 0;
function fGetEv(e){
ev = e;
}
function fGetIEVer(){
var iVerNo = 0;
var sVer = navigator.userAgent;
if(sVer.indexOf("MSIE")>-1){
var sVerNo = sVer.split(";")[1];
sVerNo = sVerNo.replace("MSIE","");
iVerNo = parseFloat(sVerNo);
}
return iVerNo;
}
function fSetEditable(){
var f = window.frames["HtmlEditor"];
f.document.designMode="on";
if(!gIsIE)
f.document.execCommand("useCSS",false, true);
}
function renewContent() {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
if(window.confirm('您确定要恢复上次保存?')) {
var data = loadUserdata('home');
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
parent.showDialog('没有可以恢复的数据!');
return;
}
var data = data.split(/\x09\x09/);
if(parent.$('subject')) {
var formObj = parent.$('subject').form;
} else if(parent.$('title')) {
var formObj = parent.$('title').form;
} else {
return;
}
for(var i = 0; i < formObj.elements.length; i++) {
var el = formObj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message' || ele[0] == 'content') {
var f = window.frames["HtmlEditor"];
f.document.body.innerHTML = elvalue;
} else {
el.value = elvalue;
}
}
break
}
}
}
}
}
}
function fSetFrmClick(){
var f = window.frames["HtmlEditor"];
f.document.onclick = function(){
fHideMenu();
}
if(gIsIE) {
f.document.attachEvent("onkeydown", listenKeyDown);
} else {
f.addEventListener('keydown', function(e) {listenKeyDown(e);}, true);
}
}
function listenKeyDown(event) {
parent.gIsEdited = true;
parent.ctrlEnter(event, 'issuance');
}
window.onload = function(){
try{
gLoaded = true;
fSetEditable();
fSetFrmClick();
}catch(e){
}
}
window.onbeforeunload = parent.edit_save;
function fSetColor(){
var dvForeColor =$("dvForeColor");
if(dvForeColor.getElementsByTagName("TABLE").length == 1){
dvForeColor.innerHTML = drawCube() + dvForeColor.innerHTML;
}
}
document.onmousemove = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var tdView = $("tdView");
var tdColorCode = $("tdColorCode");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
tdView.bgColor = el.parentNode.bgColor;
tdColorCode.innerHTML = el.parentNode.bgColor
}
}catch(e){}
}
}
function fInObj(el, id){
if(el){
if(el.id == id){
return true;
}else{
if(el.parentNode){
return fInObj(el.parentNode, id);
}else{
return false;
}
}
}
}
function fDisplayObj(id){
var o = $(id);
if(o) o.style.display = "";
}
document.onclick = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var dvForeColor =$("dvForeColor");
var dvPortrait =$("dvPortrait");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
format(gSetColorType, el.parentNode.bgColor);
dvForeColor.style.display = "none";
return;
}
}catch(e){}
try{
if(fInObj(el, "dvPortrait")){
format("InsertImage", el.src);
dvPortrait.style.display = "none";
return;
}
}catch(e){}
}
try{
if(fInObj(el, "createUrl") || fInObj(el, "createImg") || fInObj(el, "createSwf") || fInObj(el, "createPage")){
return;
}
}catch(e){}
fHideMenu();
var hideId = "";
if(arrMatch[el.id]){
hideId = arrMatch[el.id];
fDisplayObj(hideId);
}
}
var arrMatch = {
imgFontface:"fontface",
imgFontsize:"fontsize",
imgFontColor:"dvForeColor",
imgBackColor:"dvForeColor",
imgFace:"dvPortrait",
imgAlign:"divAlign",
imgList:"divList",
imgInOut:"divInOut",
faceBox:"editFaceBox",
icoUrl:"createUrl",
icoSwf:"createSwf",
icoPage:"createPage"
}
function format(type, para){
var f = window.frames["HtmlEditor"];
var sAlert = "";
if(!gIsIE){
switch(type){
case "Cut":
sAlert = "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成";
break;
case "Copy":
sAlert = "您的浏览器安全设置不允许编辑器自动执行拷贝操作,请使用键盘快捷键(Ctrl+C)来完成";
break;
case "Paste":
sAlert = "您的浏览器安全设置不允许编辑器自动执行粘贴操作,请使用键盘快捷键(Ctrl+V)来完成";
break;
}
}
if(sAlert != ""){
alert(sAlert);
return;
}
f.focus();
if(!para){
if(gIsIE){
f.document.execCommand(type);
}else{
f.document.execCommand(type,false,false);
}
}else{
if(type == 'insertHTML') {
try{
f.document.execCommand('insertHTML', false, para);
}catch(exp){
var obj = f.document.selection.createRange();
obj.pasteHTML(para);
obj.collapse(false);
obj.select();
}
} else {
try{
f.document.execCommand(type,false,para);
}catch(exp){}
}
}
f.focus();
}
function setMode(bStatus){
var sourceEditor = $("sourceEditor");
var HtmlEditor = $("HtmlEditor");
var divEditor = $("divEditor");
var f = window.frames["HtmlEditor"];
var body = f.document.getElementsByTagName("BODY")[0];
if(bStatus){
sourceEditor.style.display = "block";
divEditor.style.display = "none";
sourceEditor.value = body.innerHTML;
$('uchome-editstatus').value = 'code';
}else{
sourceEditor.style.display = "none";
divEditor.style.display = "";
body.innerHTML = sourceEditor.value;
$('uchome-editstatus').value = 'html';
}
}
function foreColor(e) {
fDisplayColorBoard(e);
gSetColorType = "foreColor";
}
function faceBox(e) {
if(gIsIE){
var e = window.event;
}
var dvFaceBox = $("editFaceBox");
var iX = e.clientX;
var iY = e.clientY;
dvFaceBox.style.display = "";
dvFaceBox.style.left = (iX-140) + "px";
dvFaceBox.style.top = 33 + "px";
dvFaceBox.innerHTML = "";
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + parent.STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertImg(this.src);" class="cur1" />';
faceul.appendChild(faceli);
}
dvFaceBox.appendChild(faceul);
return true;
}
function insertImg(src) {
format("insertHTML", '<img src="' + src + '"/>');
}
function doodleBox(event, id) {
if(parent.$('uchome-ttHtmlEditor') != null) {
parent.showWindow(id, 'home.php?mod=magic&mid=doodle&showid=blog_doodle&target=uchome-ttHtmlEditor&from=editor');
} else {
alert("找不到涂鸦板初始化数据");
}
}
function backColor(e){
var sColor = fDisplayColorBoard(e);
if(gIsIE)
gSetColorType = "backcolor";
else
gSetColorType = "backcolor";
}
function fDisplayColorBoard(e){
if(gIsIE){
var e = window.event;
}
if(gIEVer<=5.01 && gIsIE){
var arr = showModalDialog("ColorSelect.htm", "", "font-family:Verdana; font-size:12; status:no; dialogWidth:21em; dialogHeight:21em");
if (arr != null) return arr;
return;
}
var dvForeColor =$("dvForeColor");
var iX = e.clientX;
var iY = e.clientY;
dvForeColor.style.display = "";
dvForeColor.style.left = (iX-30) + "px";
dvForeColor.style.top = 33 + "px";
return true;
}
function createLink(e, show) {
if(typeof show == 'undefined') {
var urlObj = $('insertUrl');
var sURL = urlObj.value;
if ((sURL!=null) && (sURL!="http://")){
setCaret();
format("CreateLink", sURL);
}
fHide($('createUrl'));
urlObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvUrlBox = $("createUrl");
var iX = e.clientX;
var iY = e.clientY;
dvUrlBox.style.display = "";
dvUrlBox.style.left = (iX-300) + "px";
dvUrlBox.style.top = 33 + "px";
}
}
function getCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var ran = window.frames["HtmlEditor"].document.selection.createRange();
pos = ran.getBookmark();
}
}
function setCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var range = window.frames["HtmlEditor"].document.body.createTextRange();
range.moveToBookmark(pos);
range.select();
pos = null;
}
}
function clearLink() {
format("Unlink", false);
}
function createImg(e, show) {
if(typeof show == 'undefined') {
var imgObj = $('imgUrl');
var sPhoto = imgObj.value;
if ((sPhoto!=null) && (sPhoto!="http://")){
setCaret();
format("InsertImage", sPhoto);
}
fHide($('createImg'));
imgObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvImgBox = $("createImg");
var iX = e.clientX;
var iY = e.clientY;
dvImgBox.style.display = "";
dvImgBox.style.left = (iX-300) + "px";
dvImgBox.style.top = 33 + "px";
}
}
function createFlash(e, show) {
if(typeof show == 'undefined') {
var flashtag = '';
var vObj = $('videoUrl');
var sFlash = vObj.value;
if ((sFlash!=null) && (sFlash!="http://")){
setCaret();
var sFlashType = $('vtype').value;
if(sFlashType==1) {
flashtag = '[flash=media]';
} else if(sFlashType==2) {
flashtag = '[flash=real]';
} else if(sFlashType==3) {
flashtag = '[flash=mp3]';
} else {
flashtag = '[flash]';
}
format("insertHTML", flashtag + sFlash + '[/flash]');
}
fHide($('createSwf'));
vObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createSwf");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-350) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function fSetBorderMouseOver(obj) {
obj.style.borderRight="1px solid #aaa";
obj.style.borderBottom="1px solid #aaa";
obj.style.borderTop="1px solid #fff";
obj.style.borderLeft="1px solid #fff";
}
function fSetBorderMouseOut(obj) {
obj.style.border="none";
}
function fSetBorderMouseDown(obj) {
obj.style.borderRight="1px #F3F8FC solid";
obj.style.borderBottom="1px #F3F8FC solid";
obj.style.borderTop="1px #cccccc solid";
obj.style.borderLeft="1px #cccccc solid";
}
function fDisplayElement(element,displayValue) {
if(gIEVer<=5.01 && gIsIE){
alert('只支持IE 5.01以上版本');
return;
}
fHideMenu();
if ( typeof element == "string" )
element = $(element);
if (element == null) return;
element.style.display = displayValue;
if(gIsIE){
var e = event;
var target = e.srcElement;
}else{
var e = ev;
var target = e.target;
}
var iX = f_GetX(target);
element.style.display = "";
element.style.left = (iX) + "px";
element.style.top = 33 + "px";
return true;
}
function fSetModeTip(obj){
var x = f_GetX(obj);
var y = f_GetY(obj);
var dvModeTip = $("dvModeTip");
if(!dvModeTip){
var dv = document.createElement("DIV");
dv.style.position = "absolute";
dv.style.top = 33 + "px";
dv.style.left = (x-40) + "px";
dv.style.zIndex = "999";
dv.style.fontSize = "12px";
dv.id = "dvModeTip";
dv.style.padding = "2px";
dv.style.border = "1px #000000 solid";
dv.style.backgroundColor = "#FFFFCC";
dv.innerHTML = "编辑源码";
document.body.appendChild(dv);
}else{
dvModeTip.style.display = "";
}
}
function fHideTip(){
$("dvModeTip").style.display = "none";
}
function f_GetX(e)
{
var l=e.offsetLeft;
while(e=e.offsetParent){
l+=e.offsetLeft;
}
return l;
}
function f_GetY(e)
{
var t=e.offsetTop;
while(e=e.offsetParent){
t+=e.offsetTop;
}
return t;
}
function fHideMenu(){
try{
var arr = ["fontface", "fontsize", "dvForeColor", "dvPortrait", "divAlign", "divList" ,"divInOut", "editFaceBox", "createUrl", "createImg", "createSwf", "createPage"];
for(var i=0;i<arr.length;i++){
var obj = $(arr[i]);
if(obj){
obj.style.display = "none";
}
}
try{
parent.LetterPaper.control(window, "hide");
}catch(exp){}
}catch(exp){}
}
function $(id){
return document.getElementById(id);
}
function fHide(obj){
obj.style.display="none";
}
function pageBreak(e, show) {
if(!show) {
var obj = $('pageTitle');
var title = obj ? obj.value : '';
if(obj) {
obj.value = '';
}
var insertText = title ? '[title='+title+']': '';
setCaret();
format("insertHTML", '<br /><strong>##########NextPage'+insertText+'##########</strong><br /><br />');
if(parent.showInnerNav && typeof parent.showInnerNav == 'function') {
parent.showInnerNav();
}
fHide($('createPage'));
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createPage");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-300) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
function changeEditType(flag, ev){
gIsHtml = flag;
try{
var mod = parent.MM["compose"];
mod.html = flag;
}catch(exp){}
try{
var dvhtml = $("dvhtml");
var dvtext = $("dvtext");
var HtmlEditor = window.frames["HtmlEditor"];
var ifmHtmlEditor = $("HtmlEditor");
var sourceEditor = $("sourceEditor");
var switchMode = $("switchMode");
var sourceEditor = $("sourceEditor");
var dvHtmlLnk = $("dvHtmlLnk");
var dvToolbar = $('dvToolbar');
if(flag){
dvhtml.style.display = "";
dvtext.style.display = "none";
dvToolbar.className = 'toobar';
if(switchMode.checked){
sourceEditor.value = dvtext.value;
$('uchome-editstatus').value = 'code';
}else{
if(document.all){
HtmlEditor.document.body.innerText = dvtext.value;
} else {
HtmlEditor.document.body.innerHTML = dvtext.value.unescapeHTML();
}
$('uchome-editstatus').value = 'html';
}
}else{
function sub1(){
dvhtml.style.display = "none";
dvtext.style.display = "";
dvToolbar.className = 'toobarmini';
if(switchMode.checked){
dvtext.value = sourceEditor.value.unescapeHTML();
}else{
if(document.all){
dvtext.value = HtmlEditor.document.body.innerText;
}else{
dvtext.value = HtmlEditor.document.body.innerHTML.unescapeHTML();
}
}
}
ev = ev || event;
if(ev){
if(window.confirm("转换为纯文本时将会遗失某些格式。\n您确定要继续吗?")){
$('uchome-editstatus').value = 'text';
sub1();
}else{
return;
}
}
}
}catch(exp){
}
}
function changeEditFull(flag, ev) {
if(parent.changeEditFull) {
parent.changeEditFull(flag);
ev = ev || event;
var ele = ev.target || ev.srcElement;
ele.innerHTML = flag ? '返回' : '全屏';
ele.onclick = function() {changeEditFull(!flag, ev)};
}
}
String.prototype.stripTags = function(){
return this.replace(/<\/?[^>]+>/gi, '');
};
String.prototype.unescapeHTML = function(){
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0].nodeValue;
};
var s = "";
var hex = new Array(6)
hex[0] = "FF"
hex[1] = "CC"
hex[2] = "99"
hex[3] = "66"
hex[4] = "33"
hex[5] = "00"
function drawCell(red, green, blue) {
var color = '#' + red + green + blue;
if(color == "#000066") color = "#000000";
s += '<TD BGCOLOR="' + color + '" style="height:12px;width:12px;" >';
s += '<IMG '+ ((document.all)?"":"src='editor_none.gif'") +' HEIGHT=12 WIDTH=12>';
s += '</TD>';
}
function drawRow(red, blue) {
s += '<TR>';
for (var i = 0; i < 6; ++i) {
drawCell(red, hex[i], blue)
}
s += '</TR>';
}
function drawTable(blue) {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0>';
for (var i = 0; i < 6; ++i) {
drawRow(hex[i], blue)
}
s += '</TABLE>';
}
function drawCube() {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 style="border:1px #888888 solid"><TR>';
for (var i = 0; i < 2; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR><TR>';
for (var i = 2; i < 4; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR></TABLE>';
return s;
}
function EV(){}
EV.getTarget = fGetTarget;
EV.getEvent = fGetEvent;
EV.stopEvent = fStopEvent;
EV.stopPropagation = fStopPropagation;
EV.preventDefault = fPreventDefault;
function fGetTarget(ev, resolveTextNode){
if(!ev) ev = this.getEvent();
var t = ev.target || ev.srcElement;
if (resolveTextNode && t && "#text" == t.nodeName) {
return t.parentNode;
} else {
return t;
}
}
function fGetEvent (e) {
var ev = e || window.event;
if (!ev) {
var c = this.getEvent.caller;
while (c) {
ev = c.arguments[0];
if (ev && Event == ev.constructor) {
break;
}
c = c.caller;
}
}
return ev;
}
function fStopEvent(ev) {
if(!ev) ev = this.getEvent();
this.stopPropagation(ev);
this.preventDefault(ev);
}
function fStopPropagation(ev) {
if(!ev) ev = this.getEvent();
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
}
function fPreventDefault(ev) {
if(!ev) ev = this.getEvent();
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function checkURL(obj, mod) {
if(mod) {
if(obj.value == 'http://') {
obj.value = '';
}
} else {
if(obj.value == '') {
obj.value = 'http://';
}
}
} | JavaScript |
function submitForm() {
if (dialogHtml == '') {
dialogHtml = $('siteInfo').innerHTML;
$('siteInfo').innerHTML = '';
}
showWindow('open_cloud', dialogHtml, 'html');
$('fwin_open_cloud').style.top = '80px';
$('cloud_api_ip').value = cloudApiIp;
return false;
}
function dealHandle(msg) {
getMsg = true;
if (msg['status'] == 'error') {
$('loadinginner').innerHTML = '<font color="red">' + msg['content'] + '</font>';
return;
}
$('loading').style.display = 'none';
$('mainArea').style.display = '';
if(cloudStatus == 'upgrade') {
$('title').innerHTML = msg['cloudIntroduction']['upgrade_title'];
$('msg').innerHTML = msg['cloudIntroduction']['upgrade_content'];
} else {
$('title').innerHTML = msg['cloudIntroduction']['open_title'];
$('msg').innerHTML = msg['cloudIntroduction']['open_content'];
}
if (msg['navSteps']) {
$('nav_steps').innerHTML = msg['navSteps'];
}
if (msg['protocalUrl']) {
$('protocal_url').href = msg['protocalUrl'];
}
if (msg['cloudApiIp']) {
cloudApiIp = msg['cloudApiIp'];
}
if (msg['manyouUpdateTips']) {
$('manyou_update_tips').innerHTML = msg['manyouUpdateTips'];
}
}
function expiration() {
if(!getMsg) {
$('loadinginner').innerHTML = '<font color="red">' + expirationText + '</font>';
clearTimeout(expirationTimeout);
}
} | JavaScript |
var cloudj = jQuery.noConflict();
if (typeof disallowfloat == 'undefined' || disallowfloat === null) {
var disallowfloat = '';
}
var currentNormalEditDisplay = 0;
cloudj(document).ready(function() {
ajaxGetSearchResultThreads();
cloudj('#previewForm').submit(function() {
return previewFormSubmit();
});
});
function previewFormSubmit() {
saveAllThread();
if (!selectedTopicId) {
alert('请推送头条信息');
return false;
}
if (selectedNormalIds.length < 1) {
alert('请至少推送一条信息到列表区域');
return false;
}
var i = 1;
for (var k = 1; k <= 5; k++) {
var input_displayorder = cloudj('#normal_thread_' + k).find('.preview_displayorder');
if (input_displayorder.size()) {
input_displayorder.val(i);
i++;
}
}
return true;
}
function initSelect() {
var initTopicObj = cloudj('#search_result .qqqun_op .qqqun_op_topon');
initTopicObj.addClass('qqqun_op_top');
initTopicObj.removeClass('qqqun_op_topon');
var initNormalObj = cloudj('#search_result .qqqun_op .qqqun_op_liston');
initNormalObj.addClass('qqqun_op_list');
initNormalObj.removeClass('qqqun_op_liston');
selectedTopicId = parseInt(selectedTopicId);
if (selectedTopicId) {
cloudj('#thread_addtop_' + selectedTopicId).addClass('qqqun_op_topon');
cloudj('#thread_addtop_' + selectedTopicId).removeClass('qqqun_op_top');
}
cloudj.each(selectedNormalIds, function(k, v) {
v = parseInt(v);
if (v) {
cloudj('#thread_addlist_' + v).addClass('qqqun_op_liston');
cloudj('#thread_addlist_' + v).removeClass('qqqun_op_list');
}
});
}
function ajaxChangeSearch() {
cloudj('#srchtid').val('');
ajaxGetSearchResultThreads();
}
function ajaxGetSearchResultThreads() {
cloudj('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
qqgroupajaxpost('search_form', 'search_result', 'search_result', null, null, function() {initSelect(); return false});
return false;
}
function ajaxGetPageResultThreads(page, mpurl) {
cloudj('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
if (typeof page == 'undefined' || page === null) {
page = 1;
}
if (typeof mpurl == 'undefined' || !mpurl) {
return false;
}
ajaxget(mpurl + '&page=' + page, 'search_result', null, null, null, function() {initSelect();} );
}
function addMiniportalTop(tid) {
tid = parseInt(tid);
if (cloudj.inArray(tid, selectedNormalIds) > -1) {
removeNormalThreadByTid(tid);
}
addMiniportalTopId(tid);
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=' + tid, 'topicDiv', null, null, null, function() { clickTopicEditor(); });
}
function addMiniportalTopId(tid) {
selectedTopicId = tid;
}
function showPreviewEditor(topic, hideall) {
if (hideall) {
cloudj('.qqqun_list .qqqun_editor').hide();
cloudj('.qqqun_list .qqqun_xl li').removeClass('current');
cloudj('.qqqun_list').removeClass('qqqun_list_editor');
cloudj('.qqqun_top .qqqun_editor').hide();
cloudj('.qqqun_top').removeClass('qqqun_top_editor');
} else {
if (topic) {
cloudj('.qqqun_list .qqqun_editor').hide();
cloudj('.qqqun_list .qqqun_xl li').removeClass('current');
cloudj('.qqqun_list').removeClass('qqqun_list_editor');
cloudj('.qqqun_top .qqqun_editor').show();
cloudj('.qqqun_top').addClass('qqqun_top_editor');
} else {
cloudj('.qqqun_list .qqqun_editor').show();
cloudj('.qqqun_list').addClass('qqqun_list_editor');
cloudj('.qqqun_list .qqqun_xl li').removeClass('current');
cloudj('.qqqun_top .qqqun_editor').hide();
cloudj('.qqqun_top').removeClass('qqqun_top_editor');
}
}
}
function clickTopicEditor(topicFocus) {
if (typeof topicFocus == 'undefined') {
var topicFocus = 'title';
}
showPreviewEditor(true, false);
if (topicFocus == 'title') {
cloudj('#topic-editor-input-title').addClass('pt_focus');
cloudj('#topic-editor-input-title').focus();
} else if (topicFocus == 'content') {
cloudj('#topic-editor-textarea-content').addClass('pt_focus');
cloudj('#topic-editor-textarea-content').focus();
}
currentNormalEditDisplay = 0;
}
function blurTopic(obj) {
var thisobj = cloudj(obj);
thisobj.removeClass('pt_focus');
}
function clickNormalEditor(obj) {
var thisobj = cloudj(obj);
showPreviewEditor(false, false);
thisobj.addClass('pt_focus');
thisobj.focus();
currentNormalEditDisplay = parseInt(thisobj.parent().attr('displayorder'));
}
function blurNormalTextarea(obj) {
var thisobj = cloudj(obj);
liObj = thisobj.parent();
var displayorder = parseInt(liObj.attr('displayorder'));
if (displayorder == currentNormalEditDisplay) {
liObj.addClass('current');
}
cloudj('.qqqun_list .qqqun_xl textarea').removeClass('pt_focus');
}
function addMiniportalList(tid) {
tid = parseInt(tid);
if (cloudj.inArray(tid, selectedNormalIds) > -1) {
return false;
}
if (selectedNormalIds.length >= 5) {
alert('推送帖子已达到5条,请在右侧取消一些再重试。');
return false;
}
if (tid == selectedTopicId) {
selectedTopicId = 0;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=0', 'topicDiv');
}
addMiniportalListId(tid);
initSelect();
var insertPos = 'normal_thread_' + selectedNormalIds.length;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getNormalThread&tid=' + tid, insertPos, null, null, null, function() { clickNormalEditor(cloudj('#' + insertPos).find('textarea')); });
}
function addMiniportalListId(tid) {
selectedNormalIds.push(tid);
}
function editNormalThread() {
var threadLi = cloudj('#normal_thread_' + currentNormalEditDisplay);
clickNormalEditor(threadLi.find('textarea'));
}
function saveAllThread() {
showPreviewEditor(false, true);
currentNormalEditDisplay = 0;
}
function moveNormalThread(up) {
var displayorder = currentNormalEditDisplay;
var threadLi = cloudj('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
var newDisplayorder = 0;
if (up) {
newDisplayorder = displayorder - 1;
} else {
newDisplayorder = displayorder + 1;
}
if (newDisplayorder < 1 || newDisplayorder > 5) {
return false;
}
var newLiId = 'normal_thread_' + newDisplayorder;
var newThreadLi = cloudj('#' + newLiId);
if (!newThreadLi.find('textarea').size()) {
return false;
}
var tmpHtml = newThreadLi.html();
newThreadLi.html(threadLi.html());
threadLi.html(tmpHtml);
newThreadLi.addClass('current');
threadLi.removeClass('current');
currentNormalEditDisplay = newDisplayorder;
}
function removeTopicThread(tid) {
tid = parseInt(tid);
selectedTopicId = 0;
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread', 'topicDiv', null, null, null, function() { showPreviewEditor(false, true)});
}
function removeNormalThread() {
var displayorder = currentNormalEditDisplay;
var removeTid = parseInt(cloudj('#normal_thread_' + displayorder).find('.normal_thread_tid').val());
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, true);
}
function removeNormalThreadByTid(tid) {
tid = parseInt(tid);
var threadInput = cloudj('.qqqun_list .qqqun_xl .normal_thread_tid[value="' + tid + '"]');
if (threadInput.size()) {
var displayorder = threadInput.parent().attr('displayorder');
var removeTid = tid;
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, false);
}
}
function removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, inNormalEditor) {
displayorder = parseInt(displayorder);
removeTid = parseInt(removeTid);
var threadLi = cloudj('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
threadLi.removeClass('current');
var index = cloudj.inArray(removeTid, selectedNormalIds);
if (index != -1) {
selectedNormalIds.splice(index, 1);
}
initSelect();
if (typeof inNormalEditor == 'udefined') {
var inNormalEditor = false;
}
threadLi.slideUp(100, function() { removeNormalThreadRecall(displayorder, inNormalEditor)});
}
function removeNormalThreadRecall(displayorder, inNormalEditor) {
for (var i = displayorder; i <= 5; i++) {
var currentDisplayorder = i;
var nextDisplayorder = i + 1;
var currentLiId = 'normal_thread_' + currentDisplayorder;
var currentThreadLi = cloudj('#' + currentLiId);
var nextLiId = 'normal_thread_' + nextDisplayorder;
var nextThreadLi = cloudj('#' + nextLiId);
if (nextThreadLi.find('textarea').size()) {
currentThreadLi.html(nextThreadLi.html());
currentThreadLi.show();
} else {
currentThreadLi.html('');
currentThreadLi.hide();
break;
}
}
var threadLi = cloudj('#normal_thread_' + displayorder);
var prevDisplayorder = displayorder - 1;
if (threadLi.find('textarea').size()) {
if (inNormalEditor) {
threadLi.addClass('current');
}
currentNormalEditDisplay = displayorder;
} else if (prevDisplayorder) {
var prevThreadLi = cloudj('#normal_thread_' + prevDisplayorder);
if (inNormalEditor) {
prevThreadLi.addClass('current');
}
currentNormalEditDisplay = prevDisplayorder;
} else {
var firstThreadLi = cloudj('#normal_thread_1');
if (inNormalEditor) {
saveAllThread();
}
firstThreadLi.html('<div class="tips">点击左侧 <img src="static/image/admincp/cloud/qun_op_list.png" align="absmiddle" /> 将信息推送到列表</div>');
firstThreadLi.show();
}
}
function ajaxUploadQQGroupImage() {
cloudj('#uploadImageResult').parent().show();
cloudj('#uploadImageResult').text('图片上传中,请稍后...');
qqgroupajaxpost('uploadImage', 'uploadImageResult', 'uploadImageResult', null, null, 'uploadRecall()');
}
function uploadRecall() {
if(cloudj('#uploadImageResult').find('#upload_msg_success').size()) {
cloudj('#uploadImageResult').parent().show();
var debug_rand = Math.random();
var imagePath = cloudj('#uploadImageResult #upload_msg_imgpath').text();
var imageUrl = cloudj('#uploadImageResult #upload_msg_imgurl').text();
cloudj('#topic_image_value').val(imagePath);
cloudj('#topic_editor_thumb').attr('src', imageUrl + '?' + debug_rand);
cloudj('#topic_preview_thumb').attr('src', imageUrl + '?' + debug_rand);
setTimeout(function() {hideWindow('uploadImgWin');}, 2000);
}
}
function qqgroupajaxpost(formid, showid, waitid, showidclass, submitbtn, recall) {
var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');
var showidclass = !showidclass ? '' : showidclass;
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
var formtarget = $(formid).target;
var handleResult = function() {
var s = '';
var evaled = false;
showloading('none');
ajaxResponse = cloudj('#' + ajaxframeid).contents().text();
var regex = /<\!\[CDATA\[(.*)\]\]>/;
var regexed = regex.exec(ajaxResponse);
if (regexed && regexed[1]) {
s = regexed[1];
} else {
s = ajaxResponse;
}
if (!s) {
s = '内部错误,无法显示此内容';
}
if(s != '' && s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(showidclass) {
if(showidclass != 'onerror') {
cloudj(showid).addClass(showidclass);
} else {
showError(s);
ajaxerror = true;
}
}
if(submitbtn) {
cloudj(submitbtn).attr('disabled', false);
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
ajaxinnerhtml($(showid), s);
}
ajaxerror = null;
cloudj('#' + formid).attr('target', formtarget);
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
if(!evaled) evalscript(s);
ajaxframe.loading = 0;
cloudj(ajaxframe.parentNode).remove();
};
if(!ajaxframe) {
var div = cloudj('<div>');
div.css('display', 'none');
div.html('<iframe name="' + ajaxframeid + '" id="' + ajaxframeid + '" loading="1">');
cloudj('#append_parent').append(div);
ajaxframe = $(ajaxframeid);
} else if(ajaxframe.loading) {
return false;
}
_attachEvent(ajaxframe, 'load', handleResult);
showloading();
cloudj('#' + formid).attr('target', ajaxframeid);
var action = cloudj('#' + formid).attr('action');
action = hostconvert(action);
cloudj('#' + formid).attr('action', action.replace(/\&inajax\=1/g, '')+'&inajax=1');
$(formid).submit();
if(submitbtn) {
cloudj(submitbtn).attr('disabled', true);
}
doane();
return false;
} | JavaScript |
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function $(id) {
return document.getElementById(id);
}
Array.prototype.push = function(value) {
this[this.length] = value;
return this.length;
}
function getcookie(name) {
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
seconds = seconds ? seconds : 8400000;
var expires = new Date();
expires.setTime(expires.getTime() + seconds);
document.cookie = escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function _cancelBubble(e, returnValue) {
if(!e) return ;
if(is_ie) {
if(!returnValue) e.returnValue = false;
e.cancelBubble = true;
} else {
e.stopPropagation();
if(!returnValue) e.preventDefault();
}
}
function checkall(name) {
var e = is_ie ? event : checkall.caller.arguments[0];
obj = is_ie ? e.srcElement : e.target;
var arr = document.getElementsByName(name);
var k = arr.length;
for(var i=0; i<k; i++) {
arr[i].checked = obj.checked;
}
}
function getposition(obj) {
var r = new Array();
r['x'] = obj.offsetLeft;
r['y'] = obj.offsetTop;
while(obj = obj.offsetParent) {
r['x'] += obj.offsetLeft;
r['y'] += obj.offsetTop;
}
return r;
}
function addMouseEvent(obj){
var checkbox,atr,ath,i;
atr=obj.getElementsByTagName("tr");
for(i=0;i<atr.length;i++){
atr[i].onclick=function(){
ath=this.getElementsByTagName("th");
checkbox=this.getElementsByTagName("input")[0];
if(!ath.length && checkbox.getAttribute("type")=="checkbox"){
if(this.className!="currenttr"){
this.className="currenttr";
checkbox.checked=true;
}else{
this.className="";
checkbox.checked=false;
}
}
}
}
}
// editor.js
if(is_ie) document.documentElement.addBehavior("#default#userdata");
function setdata(key, value){
if(is_ie){
document.documentElement.load(key);
document.documentElement.setAttribute("value", value);
document.documentElement.save(key);
return document.documentElement.getAttribute("value");
} else {
sessionStorage.setItem(key,value);
}
}
function getdata(key){
if(is_ie){
document.documentElement.load(key);
return document.documentElement.getAttribute("value");
} else {
return sessionStorage.getItem(key) && sessionStorage.getItem(key).toString().length == 0 ? '' : (sessionStorage.getItem(key) == null ? '' : sessionStorage.getItem(key));
}
}
function form_option_selected(obj, value) {
for(var i=0; i<obj.options.length; i++) {
if(obj.options[i].value == value) {
obj.options[i].selected = true;
}
}
}
function switchcredit(obj, value) {
var creditsettings = credit[value];
var s = '<select name="credit' + obj + '">';
for(var i in creditsettings) {
s += '<option value="' + creditsettings[i][0] + '">' + creditsettings[i][1] + '</option>';
}
s += '</select>';
$(obj).innerHTML = s;
}
function setselect(selectobj, value) {
var len = selectobj.options.length;
for(i = 0;i < len;i++) {
if(selectobj.options[i].value == value) {
selectobj.options[i].selected = true;
}
}
}
function show(id, display) {
if(!$(id)) return false;
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
} | JavaScript |
//Common
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function $(id) {
return document.getElementById(id);
}
function fetchOffset(obj) {
var left_offset = obj.offsetLeft;
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
return { 'left' : left_offset, 'top' : top_offset };
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function strlen(str) {
return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
//Menu
var menus = new menu_handler();
function menu_handler() {
this.menu = Array();
}
function menuitems() {
this.ctrlobj = null,
this.menuobj = null;
this.parentids = Array();
this.allowhide = 1;
this.hidelock = 0;
this.clickstatus = 0;
}
function menuobjpos(id, offset) {
if(!menus.menu[id]) {
return;
}
if(!offset) {
offset = 0;
}
var showobj = menus.menu[id].ctrlobj;
var menuobj = menus.menu[id].menuobj;
showobj.pos = fetchOffset(showobj);
showobj.X = showobj.pos['left'];
showobj.Y = showobj.pos['top'];
showobj.w = showobj.offsetWidth;
showobj.h = showobj.offsetHeight;
menuobj.w = menuobj.offsetWidth;
menuobj.h = menuobj.offsetHeight;
if(offset < 3) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';
menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > document.documentElement.scrollTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');
} else if(offset == 3) {
menuobj.style.left = (document.body.clientWidth - menuobj.clientWidth) / 2 + document.body.scrollLeft + 'px';
menuobj.style.top = (document.body.clientHeight - menuobj.clientHeight) / 2 + document.body.scrollTop + 'px';
} else if(offset == 4) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + showobj.w + 'px';
menuobj.style.top = showobj.Y + 'px';
}
if(menuobj.style.clip && !is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function showmenu(event, id, click, position) {
if(isUndefined(click)) click = false;
if(!menus.menu[id]) {
menus.menu[id] = new menuitems();
menus.menu[id].ctrlobj = $(id);
if(!menus.menu[id].ctrlobj.getAttribute('parentmenu')) {
menus.menu[id].parentids = Array();
} else {
menus.menu[id].parentids = menus.menu[id].ctrlobj.getAttribute('parentmenu').split(',');
}
menus.menu[id].menuobj = $(id + '_menu');
menus.menu[id].menuobj.style.position = 'absolute';
if(event.type == 'mouseover') {
_attachEvent(menus.menu[id].ctrlobj, 'mouseout', function() { setTimeout(function() {hidemenu(id)}, 100); });
_attachEvent(menus.menu[id].menuobj, 'mouseover', function() { lockmenu(id, 0); });
_attachEvent(menus.menu[id].menuobj, 'mouseout', function() { lockmenu(id, 1);setTimeout(function() {hidemenu(id)}, 100); });
} else if(click || event.type == 'click') {
menus.menu[id].clickstatus = 1;
lockmenu(id, 0);
}
} else if(menus.menu[id].clickstatus == 1) {
lockmenu(id, 1);
hidemenu(id);
menus.menu[id].clickstatus = 0;
return;
}
menuobjpos(id, position);
menus.menu[id].menuobj.style.display = '';
}
function hidemenu(id) {
if(!menus.menu[id] || !menus.menu[id].allowhide || menus.menu[id].hidelock) {
return;
}
menus.menu[id].menuobj.style.display = 'none';
}
function lockmenu(id, value) {
if(!menus.menu[id]) {
return;
}
for(i = 0;i < menus.menu[id].parentids.length;i++) {
menus.menu[menus.menu[id].parentids[i]].hidelock = value == 0 ? 1 : 0;
}
menus.menu[id].allowhide = value;
}
//Editor
var lang = new Array();
function insertunit(text, textend, moveend) {
$('pm_textarea').focus();
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($('pm_textarea').selectionStart)) {
var opn = $('pm_textarea').selectionStart + 0;
if(textend != '') {
text = text + $('pm_textarea').value.substring($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd) + textend;
}
$('pm_textarea').value = $('pm_textarea').value.substr(0, $('pm_textarea').selectionStart) + text + $('pm_textarea').value.substr($('pm_textarea').selectionEnd);
if(!moveend) {
$('pm_textarea').selectionStart = opn + strlen(text) - endlen;
$('pm_textarea').selectionEnd = opn + strlen(text) - endlen;
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
$('pm_textarea').value += text;
}
}
function getSel() {
if(!isUndefined($('pm_textarea').selectionStart)) {
return $('pm_textarea').value.substr($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd - $('pm_textarea').selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
function insertlist(type) {
txt = getSel();
type = isUndefined(type) ? '' : '=' + type;
if(txt) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = '[list' + type + ']\n' + txt.replace(regex, '$1[*]') + '\n' + '[/list]';
insertunit(txt);
} else {
insertunit('[list' + type + ']\n', '[/list]');
while(listvalue = prompt(lang['pm_prompt_list'], '')) {
if(is_opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertunit(listvalue);
} else {
listvalue = '[*]' + listvalue + '\n';
insertunit(listvalue);
}
}
}
}
function inserttag(tag, type) {
txt = getSel();
type = isUndefined(type) ? 0 : type;
if(!type) {
if(!txt) {
txt = prompt(lang['pm_prompt_' + tag], '')
}
if(txt) {
insertunit('[' + tag + ']' + txt + '[/' + tag + ']');
}
} else {
txt1 = prompt(lang['pm_prompt_' + tag], '');
if(!txt) {
txt = txt1;
}
if(txt1) {
insertunit('[' + tag + '=' + txt1 + ']' + txt + '[/' + tag + ']');
}
}
} | JavaScript |
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute;z-index:100;" onclick="_cancelBubble(event)">';
s += '<iframe id="calendariframe" frameborder="0" style="height:200px; z-index: 110; position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<div style="padding:5px; width: 210px; border: 1px solid #B5CFD9; background:#F2F9FD; position: absolute; z-index: 120">';
s += '<table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;" class="table1">';
s += '<thead>';
s += '<tr align="center" id="calendar_week">';
s += '<th><a href="###" onclick="refreshcalendar(yy, mm-1)" title="上一月">《</a></th>';
s += '<th colspan="5" style="text-align: center"><a href="###" onclick="showdiv(\'year\');_cancelBubble(event)" title="点击选择年份" id="year"></a> - <a id="month" title="点击选择月份" href="###" onclick="showdiv(\'month\');_cancelBubble(event)"></a></th>';
s += '<th><A href="###" onclick="refreshcalendar(yy, mm+1)" title="下一月">》</A></th>';
s += '</tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
s += '</thead>';
s += '<tbody>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="2" value="" id="hour" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="2" value="" id="minute" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td></tr>';
s += '</tbody>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="_cancelBubble(event)" style="display: none; z-index: 130;" class="calendarmenu"><div class="col" style="float: left; margin-right: 5px;">';
for(var k = 1930; k <= 2019; k++) {
s += k != 1930 && k % 10 == 0 ? '</div><div style="float: left; margin-right: 5px;">' : '';
s += '<a href="###" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="bold"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="_cancelBubble(event)" style="display: none; padding: 3px; z-index: 140" class="calendarmenu">';
for(var k = 1; k <= 12; k++) {
s += '<a href="###" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'; "><span' + (today.getMonth()+1 == k ? ' class="bold"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
var div = document.createElement('div');
div.innerHTML = s;
$('append').appendChild(div);
_attachEvent(document, 'click', function() {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
});
$('calendar').onclick = function(e) {
e = is_ie ? event : e;
_cancelBubble(e);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function showcalendar(addtime1, startdate1, enddate1) {
e = is_ie ? event : showcalendar.caller.arguments[0];
controlid1 = is_ie ? e.srcElement : e.target;
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = getposition(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['x']+'px';
$('calendar').style.top = (p['y'] + 20)+'px';
_cancelBubble(e);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = '';
$('calendar_year_' + today.getFullYear()).className = 'bold';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = '';
$('calendar_month_' + (today.getMonth() + 1)).className = 'bold';
}
$('calendar_year_' + currday.getFullYear()).className = 'error bold';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'error bold';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'grey';
} else {
dd.className = '';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'bold';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'error bold';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = getposition($(id));
$('calendar_' + id).style.left = p['x']+'px';
$('calendar_' + id).style.top = (p['y'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
window.onload = function() {
loadcalendar();
} | JavaScript |
var Ajaxs = new Array();
function Ajax(waitId) {
var aj = new Object();
aj.waitId = waitId ? $(waitId) : null;
aj.targetUrl = '';
aj.sendString = '';
aj.resultHandle = null;
aj.loading = '<img src="image/common/loading.gif" style="margin: 3px; vertical-align: middle" />Loading... ';
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) request.overrideMimeType('text/xml');
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) return request;
} catch(e) {/*alert(e.message);*/}
}
}
return request;
}
aj.request = aj.createXMLHttpRequest();
if(aj.waitId) {
aj.waitId.orgdisplay = aj.waitId.style.display;
aj.waitId.style.display = '';
aj.waitId.innerHTML = aj.loading;
}
aj.processHandle = function() {
if(aj.request.readyState == 4 && aj.request.status == 200) {
for(k in Ajaxs) {
if(Ajaxs[k] == aj.targetUrl) Ajaxs[k] = null;
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
aj.waitId.style.display = aj.waitId.orgdisplay;
}
aj.resultHandle(aj.request.responseXML.lastChild.firstChild.nodeValue);
}
}
aj.get = function(targetUrl, resultHandle) {
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
if(window.XMLHttpRequest) {
aj.request.open('GET', aj.targetUrl);
aj.request.send(null);
} else {
aj.request.open("GET", targetUrl, true);
aj.request.send();
}
}
/* aj.post = function(targetUrl, sendString, resultHandle) {
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.request.open('POST', targetUrl);
aj.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.request.send(aj.sendString);
}*/
return aj;
}
function show(id, display) {
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
}
/*
ajaxget('www.baidu.com', 'showid', 'waitid', 'display(\'showid\', 1)');
*/
function ajaxget(url, showId, waitId, display, recall) {
e = is_ie ? event : ajaxget.caller.arguments[0];
ajaxget2(e, url, showId, waitId, display, recall);
_cancelBubble(e);
}
function ajaxget2(e, url, showId, waitId, display, recall) {
target = e ? (is_ie ? e.srcElement : e.target) : null;
display = display ? display : '';
var x = new Ajax(waitId);
x.showId = showId;
x.display = display;
var sep = url.indexOf('?') != -1 ? '&' : '?';
x.target = target;
x.recall = recall;
x.get(url+sep+'inajax=1', function(s) {
if(x.display == 'auto' && x.target) {
x.target.onclick = newfunc('show', x.showId, 'auto');
}
show(x.showId, x.display);
$(x.showId).innerHTML = s;
evalscript(s);
if(x.recall)eval(x.recall);
});
_cancelBubble(e);
}
/*
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}*/
var evalscripts = new Array();
function evalscript(s) {
if(!s || s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\x00]+?)\"[^\>]*( reload=\"1\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2]);
p = /<script[^\>]*?( reload=\"1\")?>([^\x00]+?)<\/script>/ig;
while(arr = p.exec(s)) appendscript('', arr[2], arr[1]);
return s;
}
function appendscript(src, text, reload) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
if(src) {
scriptNode.src = src;
} else if(text){
scriptNode.text = text;
}
$('append').appendChild(scriptNode);
}
// 得到一个定长的 hash 值, 依赖于 stringxor()
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function in_array(needle, haystack) {
for(var i in haystack) {if(haystack[i] == needle) return true;}
return false;
}
function newfunc(func){
var args = new Array();
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(e){
window[func].apply(window, args);
_cancelBubble(is_ie ? event : e);
}
}
function ajaxmenu(url, position) {
e = is_ie ? event : ajaxmenu.caller.arguments[0];
controlid = is_ie ? e.srcElement : e.target;
var menuid = hash(url);// 使每个 url 对应一个弹出层,避免重复请求
createmenu(menuid);
showmenu2(e, menuid, position, controlid);
if(!$(menuid).innerHTML) {
ajaxget2(e, url, menuid, menuid, '', "setposition('" + menuid + "', '" + position + "', '" + controlid + "')");
} else {
//alert(menuid.innerHTML);
}
_cancelBubble(e);
}
var ajaxpostHandle = null;
function ajaxpost(formid, showid, recall) {
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
if(ajaxframe == null) {
if (is_ie) {
ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");
} else {
ajaxframe = document.createElement("iframe");
ajaxframe.name = ajaxframeid;
ajaxframe.id = ajaxframeid;
}
ajaxframe.style.display = 'none';
$('append').appendChild(ajaxframe);
}
$(formid).target = ajaxframeid;
ajaxpostHandle = [formid, showid, ajaxframeid, recall];
_attachEvent(ajaxframe, 'load', ajaxpost_load);
$(formid).submit();
return false;
}
function ajaxpost_load() {
var s = (is_ie && $(ajaxpostHandle[2])) ? $(ajaxpostHandle[2]).contentWindow.document.XMLDocument.text : $(ajaxpostHandle[2]).contentWindow.document.documentElement.firstChild.nodeValue;
evalscript(s);
if(s) {
// setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);
$(ajaxpostHandle[1]).innerHTML = s;
if(ajaxpostHandle[3]) {
eval(ajaxpostHandle[3]);
}
// setTimeout("hideMenu()", 3000);
}
// $(ajaxpostHandle[2]).target = ajaxpostHandle[3];
// ajaxpostHandle = null;
}
| JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: soso_smilies.js 32519 2013-02-04 08:21:44Z liudongdong $
*/
var sosojs = document.createElement('script');
sosojs.type = 'text/javascript';
sosojs.charset = "utf-8";
sosojs.src = 'http://bq.soso.com/js/sosoexp_platform.js';
var sosolo = document.getElementsByTagName('script')[0];
sosolo.parentNode.insertBefore(sosojs, sosolo);
function bbcode2html_sososmilies(sososmilieid, getsrc) {
var imgsrc = '';
sososmilieid = String(sososmilieid);
if(sososmilieid.indexOf('_') >= 0) {
if (sososmilieid.indexOf('_') == 0) {
sososmilieid = sososmilieid.substr(1);
}
var imgid = 'soso__' + sososmilieid;
var realsmilieid = sososmilieid.substr(0, sososmilieid.length-2);
var serverid = sososmilieid.substr(sososmilieid.length-1);
imgsrc = "http://soso"+serverid+".gtimg.cn/sosopic_f/0/"+realsmilieid+"/0";
} else {
var imgid = 'soso_' + sososmilieid;
imgsrc = "http://cache.soso.com/img/img/"+sososmilieid+".gif";
}
if(!isUndefined(getsrc)) {
return imgsrc;
}
return '<img src="'+imgsrc+'" smilieid="'+imgid+'" border="0" alt="" />';
}
function html2bbcode_sososmilies(htmlsmilies) {
if(htmlsmilies) {
htmlsmilies = htmlsmilies.replace(/<img[^>]+smilieid=(["']?)soso_(\w+)(\1)[^>]*>/ig, function($1, $2, $3) { return sososmileycode($3);});
}
return htmlsmilies;
}
function sososmileycode(sososmilieid) {
if(sososmilieid) {
return "{:soso_"+sososmilieid+":}";
}
}
function sososmiliesurl2id(sosourl) {
var sososmilieid = '';
if(sosourl && sosourl.length > 30) {
var url = sosourl.substr(0, sosourl.lastIndexOf('/'));
var idindex = url.lastIndexOf('/');
if (sosourl.indexOf('http://soso') == 0) {
var serverid = url.substr(11, 1);
var realsmilieid = url.substr(idindex+1);
sososmilieid = '_'+realsmilieid+'_'+serverid;
} else if (sosourl.indexOf('http://cache.soso.com') == 0) {
sososmilieid = sosourl.substring(sosourl.lastIndexOf('/')+1, sosourl.length-4);
}
return sososmilieid;
}
}
function insertsosoSmiley(sosourl) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
var src = bbcode2html_sososmilies(sososmilieid, true);
checkFocus();
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText(bbcode2html_sososmilies(sososmilieid), false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
}
function insertfastpostSmiley(sosourl, textareaid) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
seditor_insertunit(textareaid, code);
}
}
var TimeCounter = 0;
function SOSO_EXP_CHECK(textareaid) {
TimeCounter++;
if(typeof editorid!='undefined' && textareaid == 'newthread') {
var eExpBtn = $(editorid + '_sml'),
eEditBox = $(editorid + '_textarea');
eExpBtn.setAttribute('init', 1);
fFillEditBox = function(editbox, url) {
insertsosoSmiley(url);
};
} else if(in_array(textareaid, ['post', 'fastpost', 'pm', 'send', 'reply', 'sightml'])) {
var eExpBtn = $(textareaid+"sml"),
eEditBox = $(textareaid+"message"),
fFillEditBox = function(editbox, url) {
insertfastpostSmiley(url, textareaid);
};
} else {
return false;
}
if(typeof SOSO_EXP != "undefined" && typeof SOSO_EXP.Register == "function" && eExpBtn && eEditBox) {
var pos = 'bottom';
if(in_array(textareaid, ['fastpost', 'pm', 'reply'])) {
pos = 'top';
}
eExpBtn.onclick = function() { return null; };
SOSO_EXP.Register(60001, 'discuz', eExpBtn, pos, eEditBox, fFillEditBox);
if(typeof editdoc != "undefined" && editdoc && editdoc.body) {
editdoc.body.onclick = extrafunc_soso_showmenu;
document.body.onclick = extrafunc_soso_showmenu;
}
return true;
} else if(TimeCounter<15) {
setTimeout(function () { SOSO_EXP_CHECK(textareaid) ; }, 2000);
return false;
} else if(typeof SOSO_EXP == "undefined" || typeof SOSO_EXP.Register != "function") {
return false;
} else {
return false;
}
}
if(typeof EXTRAFUNC['bbcode2html'] != "undefined") {
EXTRAFUNC['bbcode2html']['soso'] = 'extrafunc_soso_bbcode2html';
EXTRAFUNC['html2bbcode']['soso'] = 'extrafunc_soso_html2bbcode';
if(typeof editdoc != "undefined") {
EXTRAFUNC['showmenu']['soso'] = 'extrafunc_soso_showmenu';
}
}
function extrafunc_soso_showmenu() {
SOSO_EXP.Platform.hideBox();
}
function extrafunc_soso_bbcode2html() {
if(!fetchCheckbox('smileyoff') && allowsmilies) {
EXTRASTR = EXTRASTR.replace(/\{\:soso_(\w+)\:\}/ig, function($1, $2) { return bbcode2html_sososmilies($2);});
}
return EXTRASTR;
}
function extrafunc_soso_html2bbcode() {
if((allowhtml && fetchCheckbox('htmlon')) || (!fetchCheckbox('bbcodeoff') && allowbbcode)) {
EXTRASTR = html2bbcode_sososmilies(EXTRASTR);
}
return EXTRASTR;
} | JavaScript |
{
properties: {
'label': {
valueType: "item"
},
'ACCTID': {
valueType: "item"
},
'UNIQUEID': {
valueType: "item"
},
'accountGroup': {
valueType: "item"
},
'FITID': {
valueType: "item"
},
'DTTRADE': {
valueType: "date"
},
'DTASOF': {
valueType: "date"
},
'DTPRICEASOF': {
valueType: "date"
},
'dayasof': {
valueType: "date"
},
'AVAILCASH': {
valueType: "number"
},
'moneymrkt': {
valueType: "number"
},
'MKTVAL': {
valueType: "number"
},
'mktval': {
valueType: "number"
},
'mKTVAL': {
valueType: "number"
},
'UNITS': {
valueType: "number"
},
'units': {
valueType: "number"
},
'UNITPRICE': {
valueType: "number"
},
'TOTAL': {
valueType: "number"
},
'TRNAMT': {
valueType: "number"
}
}
}
| JavaScript |
var date_selector =
{
frm:null,
init:function(frm1)
{
this.frm=frm1;
var dt = new Date();
year = dt.getFullYear();
month = dt.getMonth();
month = (month+1)+"";
month = (month.length == 1 ? "0"+month : month);
day = dt.getDate()+"";
day = (day.length == 1 ? "0"+day : day);
this.frm.minimumDate.value="01/01/"+year
this.frm.maximumDate.value=month+"/"+day+"/"+year;
},
getMonthTable:function(year, month, date)
{
var tableText = "";
var months =
[
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
month = (month == null || isNaN(month) ? null : month);
if(year == null || isNaN(year) || month == null || isNaN(month))
{
var dt = new Date();
year = dt.getFullYear();
month = dt.getMonth();
date = dt.getDate();
}
date = (date == null || isNaN(date) ? null : date);
var previousMonth = new Date(year, month-1, 1);
var nextMonth = new Date(year, month+1, 1);
tableText =
(
"<table align=\"center\" id=\"dateSelector_sample\" \
style=\"border-collapse:collapse;\" \
cellpadding=\"1\" cellspacing=\"0\">\
<tr>\
<th style=\"cursor:pointer;text-align:left;\" \
onclick=\"date_selector.updateDateSelectorPane("
+previousMonth.getFullYear()+", "+previousMonth.getMonth()
+");\">←</th>\
<th style=\"text-align:center;\" colspan=\"4\">"+months[month]
+", "+year+"</th>\
<th style=\"cursor:pointer;text-align:right;\" \
onclick=\"date_selector.updateDateSelectorPane("
+nextMonth.getFullYear()+", "+nextMonth.getMonth()+");\">→</th>\
<th style=\"text-align:right;cursor:pointer;\" \
onclick=\"date_selector.updateDateElement();\">X</th>\
</tr>"
);
for(var i=0; i<days.length; i++)
{
tableText += "<th>"+days[i]+"</th>";
}
tableText += "</tr>";
var tempDate;
for(var i=1-(new Date(year, month, 1)).getDay();; i++)
{
tempDate = new Date(year, month, i);
if(tempDate.getDay() == 0)
{
tableText += "<tr>";
}
tableText +=
(
"<td"+(tempDate.getMonth() == month ? " \
onclick=\"date_selector.updateDateElement("
+tempDate.getFullYear()+", "+
tempDate.getMonth()+", "+tempDate.getDate()+");\""+
(tempDate.getDate() == date
? " style=\"border:solid 2px black;font-weight:bold;\"" : "")
: " \
style=\"color:silver;cursor:default;\"")+">"+
tempDate.getDate()+
"</td>"
);
if(tempDate.getDay() == 6)
{
tableText += "</tr>";
}
tempDate = new Date(year, month, i+1);
if(tempDate.getMonth() != month && tempDate.getDay() == 0)
{
break;
}
}
tableText += "</table>";
return tableText;
},
updateDateSelectorPane:function(year, month, day)
{
var d = document.getElementById("dateSelectorPane");
d.innerHTML = this.getMonthTable(year, month, day);
d.style.display = "block";
},
showDateSelector:function(elementName)
{
if(elementName == null)
{
this.updateDateSelectorPane();
}
else
{
this.dateElementToUpdate = elementName;
var e = this.frm.elements[elementName];
e = e.value.split("/");
try
{
e[0] = parseInt(e[0], 10);
e[1] = parseInt(e[1], 10);
e[2] = parseInt(e[2], 10);
this.updateDateSelectorPane(e[2], e[0]-1, e[1]);
}
catch(e)
{
this.updateDateSelectorPane();
}
}
},
updateDateElement:function(year, month, day)
{
document.getElementById("dateSelectorPane").style.display="none";
if(year != null && month != null && day != null)
{
month = (month+1)+"";
day += "";
month = (month.length == 1 ? "0"+month : month);
day = (day.length == 1 ? "0"+day : day);
this.frm.elements[this.dateElementToUpdate].value
= (month+"/"+day+"/"+year);
}
this.dateElementToUpdate = null;
},
dateElementToUpdate:null
};
function printDateRange()
{
var frm = date_selector.frm;
window.alert
(
'This Popup summarizes the date range you entered.\n\n'
+'Minimum Date: '+frm.minimumDate.value
+'\n\nMaximum Date: '+frm.maximumDate.value
);
}
| JavaScript |
{
properties: {
'label': {
valueType: "item",
},
'ACCTID': {
valueType: "item",
},
'UNIQUEID': {
valueType: "item",
},
'accountGroup': {
valueType: "item",
},
'FITID': {
valueType: "item",
},
'DTTRADE': {
valueType: "date",
},
'DTASOF': {
valueType: "date",
},
'MKTVAL': {
valueType: "number",
},
'UNITS': {
valueType: "number",
},
'UNITPRICE': {
valueType: "number",
},
'TOTAL': {
valueType: "number",
}
}
}
| JavaScript |
{
properties: {
'label': {
valueType: "item"
},
'ACCTID': {
valueType: "item"
},
'UNIQUEID': {
valueType: "item"
},
'accountGroup': {
valueType: "item"
},
'FITID': {
valueType: "item"
},
'DTTRADE': {
valueType: "date"
},
'DTASOF': {
valueType: "date"
},
'DTPRICEASOF': {
valueType: "date"
},
'dayasof': {
valueType: "date"
},
'AVAILCASH': {
valueType: "number"
},
'moneymrkt': {
valueType: "number"
},
'MKTVAL': {
valueType: "number"
},
'mktval': {
valueType: "number"
},
'mKTVAL': {
valueType: "number"
},
'UNITS': {
valueType: "number"
},
'units': {
valueType: "number"
},
'UNITPRICE': {
valueType: "number"
},
'TOTAL': {
valueType: "number"
},
'TRNAMT': {
valueType: "number"
}
}
}
| JavaScript |
addComment = {
moveForm : function(commId, parentId, respondId, postId) {
var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID');
if ( ! comm || ! respond || ! cancel || ! parent )
return;
t.respondId = respondId;
postId = postId || false;
if ( ! t.I('wp-temp-form-div') ) {
div = document.createElement('div');
div.id = 'wp-temp-form-div';
div.style.display = 'none';
respond.parentNode.insertBefore(div, respond);
}
comm.parentNode.insertBefore(respond, comm.nextSibling);
if ( post && postId )
post.value = postId;
parent.value = parentId;
cancel.style.display = '';
cancel.onclick = function() {
var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId);
if ( ! temp || ! respond )
return;
t.I('comment_parent').value = '0';
temp.parentNode.insertBefore(respond, temp);
temp.parentNode.removeChild(temp);
this.style.display = 'none';
this.onclick = null;
return false;
}
try { t.I('comment').focus(); }
catch(e) {}
return false;
},
I : function(e) {
return document.getElementById(e);
}
}
| JavaScript |
var wpLink;
(function($){
var inputs = {}, rivers = {}, ed, River, Query;
wpLink = {
timeToTriggerRiver: 150,
minRiverAJAXDuration: 200,
riverBottomThreshold: 5,
keySensitivity: 100,
lastSearch: '',
textarea: '',
init : function() {
inputs.dialog = $('#wp-link');
inputs.submit = $('#wp-link-submit');
// URL
inputs.url = $('#url-field');
inputs.nonce = $('#_ajax_linking_nonce');
// Secondary options
inputs.title = $('#link-title-field');
// Advanced Options
inputs.openInNewTab = $('#link-target-checkbox');
inputs.search = $('#search-field');
// Build Rivers
rivers.search = new River( $('#search-results') );
rivers.recent = new River( $('#most-recent-results') );
rivers.elements = $('.query-results', inputs.dialog);
// Bind event handlers
inputs.dialog.keydown( wpLink.keydown );
inputs.dialog.keyup( wpLink.keyup );
inputs.submit.click( function(e){
e.preventDefault();
wpLink.update();
});
$('#wp-link-cancel').click( function(e){
e.preventDefault();
wpLink.close();
});
$('#internal-toggle').click( wpLink.toggleInternalLinking );
rivers.elements.bind('river-select', wpLink.updateFields );
inputs.search.keyup( wpLink.searchInternalLinks );
inputs.dialog.bind('wpdialogrefresh', wpLink.refresh);
inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen);
inputs.dialog.bind('wpdialogclose', wpLink.onClose);
},
beforeOpen : function() {
wpLink.range = null;
if ( ! wpLink.isMCE() && document.selection ) {
wpLink.textarea.focus();
wpLink.range = document.selection.createRange();
}
},
open : function() {
if ( !wpActiveEditor )
return;
this.textarea = $('#'+wpActiveEditor).get(0);
// Initialize the dialog if necessary (html mode).
if ( ! inputs.dialog.data('wpdialog') ) {
inputs.dialog.wpdialog({
title: wpLinkL10n.title,
width: 480,
height: 'auto',
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
inputs.dialog.wpdialog('open');
},
isMCE : function() {
return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden();
},
refresh : function() {
// Refresh rivers (clear links, check visibility)
rivers.search.refresh();
rivers.recent.refresh();
if ( wpLink.isMCE() )
wpLink.mceRefresh();
else
wpLink.setDefaultValues();
// Focus the URL field and highlight its contents.
// If this is moved above the selection changes,
// IE will show a flashing cursor over the dialog.
inputs.url.focus()[0].select();
// Load the most recent results if this is the first time opening the panel.
if ( ! rivers.recent.ul.children().length )
rivers.recent.ajax();
},
mceRefresh : function() {
var e;
ed = tinyMCEPopup.editor;
tinyMCEPopup.restoreSelection();
// If link exists, select proper values.
if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) {
// Set URL and description.
inputs.url.val( ed.dom.getAttrib(e, 'href') );
inputs.title.val( ed.dom.getAttrib(e, 'title') );
// Set open in new tab.
if ( "_blank" == ed.dom.getAttrib(e, 'target') )
inputs.openInNewTab.prop('checked', true);
// Update save prompt.
inputs.submit.val( wpLinkL10n.update );
// If there's no link, set the default values.
} else {
wpLink.setDefaultValues();
}
tinyMCEPopup.storeSelection();
},
close : function() {
if ( wpLink.isMCE() )
tinyMCEPopup.close();
else
inputs.dialog.wpdialog('close');
},
onClose: function() {
if ( ! wpLink.isMCE() ) {
wpLink.textarea.focus();
if ( wpLink.range ) {
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
}
}
},
getAttrs : function() {
return {
href : inputs.url.val(),
title : inputs.title.val(),
target : inputs.openInNewTab.prop('checked') ? '_blank' : ''
};
},
update : function() {
if ( wpLink.isMCE() )
wpLink.mceUpdate();
else
wpLink.htmlUpdate();
},
htmlUpdate : function() {
var attrs, html, begin, end, cursor,
textarea = wpLink.textarea;
if ( ! textarea )
return;
attrs = wpLink.getAttrs();
// If there's no href, return.
if ( ! attrs.href || attrs.href == 'http://' )
return;
// Build HTML
html = '<a href="' + attrs.href + '"';
if ( attrs.title )
html += ' title="' + attrs.title + '"';
if ( attrs.target )
html += ' target="' + attrs.target + '"';
html += '>';
// Insert HTML
if ( document.selection && wpLink.range ) {
// IE
// Note: If no text is selected, IE will not place the cursor
// inside the closing tag.
textarea.focus();
wpLink.range.text = html + wpLink.range.text + '</a>';
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
wpLink.range = null;
} else if ( typeof textarea.selectionStart !== 'undefined' ) {
// W3C
begin = textarea.selectionStart;
end = textarea.selectionEnd;
selection = textarea.value.substring( begin, end );
html = html + selection + '</a>';
cursor = begin + html.length;
// If no next is selected, place the cursor inside the closing tag.
if ( begin == end )
cursor -= '</a>'.length;
textarea.value = textarea.value.substring( 0, begin )
+ html
+ textarea.value.substring( end, textarea.value.length );
// Update cursor position
textarea.selectionStart = textarea.selectionEnd = cursor;
}
wpLink.close();
textarea.focus();
},
mceUpdate : function() {
var ed = tinyMCEPopup.editor,
attrs = wpLink.getAttrs(),
e, b;
tinyMCEPopup.restoreSelection();
e = ed.dom.getParent(ed.selection.getNode(), 'A');
// If the values are empty, unlink and return
if ( ! attrs.href || attrs.href == 'http://' ) {
if ( e ) {
tinyMCEPopup.execCommand("mceBeginUndoLevel");
b = ed.selection.getBookmark();
ed.dom.remove(e, 1);
ed.selection.moveToBookmark(b);
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
}
return;
}
tinyMCEPopup.execCommand("mceBeginUndoLevel");
if (e == null) {
ed.getDoc().execCommand("unlink", false, null);
tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1});
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
e = n;
ed.dom.setAttribs(e, attrs);
}
});
// Sometimes WebKit lets a user create a link where
// they shouldn't be able to. In this case, CreateLink
// injects "#mce_temp_url#" into their content. Fix it.
if ( $(e).text() == '#mce_temp_url#' ) {
ed.dom.remove(e);
e = null;
}
} else {
ed.dom.setAttribs(e, attrs);
}
// Don't move caret if selection was image
if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) {
ed.focus();
ed.selection.select(e);
ed.selection.collapse(0);
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
},
updateFields : function( e, li, originalEvent ) {
inputs.url.val( li.children('.item-permalink').val() );
inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() );
if ( originalEvent && originalEvent.type == "click" )
inputs.url.focus();
},
setDefaultValues : function() {
// Set URL and description to defaults.
// Leave the new tab setting as-is.
inputs.url.val('http://');
inputs.title.val('');
// Update save prompt.
inputs.submit.val( wpLinkL10n.save );
},
searchInternalLinks : function() {
var t = $(this), waiting,
search = t.val();
if ( search.length > 2 ) {
rivers.recent.hide();
rivers.search.show();
// Don't search if the keypress didn't change the title.
if ( wpLink.lastSearch == search )
return;
wpLink.lastSearch = search;
waiting = t.siblings('img.waiting').show();
rivers.search.change( search );
rivers.search.ajax( function(){ waiting.hide(); });
} else {
rivers.search.hide();
rivers.recent.show();
}
},
next : function() {
rivers.search.next();
rivers.recent.next();
},
prev : function() {
rivers.search.prev();
rivers.recent.prev();
},
keydown : function( event ) {
var fn, key = $.ui.keyCode;
switch( event.which ) {
case key.UP:
fn = 'prev';
case key.DOWN:
fn = fn || 'next';
clearInterval( wpLink.keyInterval );
wpLink[ fn ]();
wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
break;
default:
return;
}
event.preventDefault();
},
keyup: function( event ) {
var key = $.ui.keyCode;
switch( event.which ) {
case key.ESCAPE:
event.stopImmediatePropagation();
if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) )
wpLink.close();
return false;
break;
case key.UP:
case key.DOWN:
clearInterval( wpLink.keyInterval );
break;
default:
return;
}
event.preventDefault();
},
delayedCallback : function( func, delay ) {
var timeoutTriggered, funcTriggered, funcArgs, funcContext;
if ( ! delay )
return func;
setTimeout( function() {
if ( funcTriggered )
return func.apply( funcContext, funcArgs );
// Otherwise, wait.
timeoutTriggered = true;
}, delay);
return function() {
if ( timeoutTriggered )
return func.apply( this, arguments );
// Otherwise, wait.
funcArgs = arguments;
funcContext = this;
funcTriggered = true;
};
},
toggleInternalLinking : function( event ) {
var panel = $('#search-panel'),
widget = inputs.dialog.wpdialog('widget'),
// We're about to toggle visibility; it's currently the opposite
visible = !panel.is(':visible'),
win = $(window);
$(this).toggleClass('toggle-arrow-active', visible);
inputs.dialog.height('auto');
panel.slideToggle( 300, function() {
setUserSetting('wplink', visible ? '1' : '0');
inputs[ visible ? 'search' : 'url' ].focus();
// Move the box if the box is now expanded, was opened in a collapsed state,
// and if it needs to be moved. (Judged by bottom not being positive or
// bottom being smaller than top.)
var scroll = win.scrollTop(),
top = widget.offset().top,
bottom = top + widget.outerHeight(),
diff = bottom - win.height();
if ( diff > scroll ) {
widget.animate({'top': diff < top ? top - diff : scroll }, 200);
}
});
event.preventDefault();
}
}
River = function( element, search ) {
var self = this;
this.element = element;
this.ul = element.children('ul');
this.waiting = element.find('.river-waiting');
this.change( search );
this.refresh();
element.scroll( function(){ self.maybeLoad(); });
element.delegate('li', 'click', function(e){ self.select( $(this), e ); });
};
$.extend( River.prototype, {
refresh: function() {
this.deselect();
this.visible = this.element.is(':visible');
},
show: function() {
if ( ! this.visible ) {
this.deselect();
this.element.show();
this.visible = true;
}
},
hide: function() {
this.element.hide();
this.visible = false;
},
// Selects a list item and triggers the river-select event.
select: function( li, event ) {
var liHeight, elHeight, liTop, elTop;
if ( li.hasClass('unselectable') || li == this.selected )
return;
this.deselect();
this.selected = li.addClass('selected');
// Make sure the element is visible
liHeight = li.outerHeight();
elHeight = this.element.height();
liTop = li.position().top;
elTop = this.element.scrollTop();
if ( liTop < 0 ) // Make first visible element
this.element.scrollTop( elTop + liTop );
else if ( liTop + liHeight > elHeight ) // Make last visible element
this.element.scrollTop( elTop + liTop - elHeight + liHeight );
// Trigger the river-select event
this.element.trigger('river-select', [ li, event, this ]);
},
deselect: function() {
if ( this.selected )
this.selected.removeClass('selected');
this.selected = false;
},
prev: function() {
if ( ! this.visible )
return;
var to;
if ( this.selected ) {
to = this.selected.prev('li');
if ( to.length )
this.select( to );
}
},
next: function() {
if ( ! this.visible )
return;
var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element);
if ( to.length )
this.select( to );
},
ajax: function( callback ) {
var self = this,
delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
response = wpLink.delayedCallback( function( results, params ) {
self.process( results, params );
if ( callback )
callback( results, params );
}, delay );
this.query.ajax( response );
},
change: function( search ) {
if ( this.query && this._search == search )
return;
this._search = search;
this.query = new Query( search );
this.element.scrollTop(0);
},
process: function( results, params ) {
var list = '', alt = true, classes = '',
firstPage = params.page == 1;
if ( !results ) {
if ( firstPage ) {
list += '<li class="unselectable"><span class="item-title"><em>'
+ wpLinkL10n.noMatchesFound
+ '</em></span></li>';
}
} else {
$.each( results, function() {
classes = alt ? 'alternate' : '';
classes += this['title'] ? '' : ' no-title';
list += classes ? '<li class="' + classes + '">' : '<li>';
list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />';
list += '<span class="item-title">';
list += this['title'] ? this['title'] : wpLinkL10n.noTitle;
list += '</span><span class="item-info">' + this['info'] + '</span></li>';
alt = ! alt;
});
}
this.ul[ firstPage ? 'html' : 'append' ]( list );
},
maybeLoad: function() {
var self = this,
el = this.element,
bottom = el.scrollTop() + el.height();
if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold )
return;
setTimeout(function() {
var newTop = el.scrollTop(),
newBottom = newTop + el.height();
if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold )
return;
self.waiting.show();
el.scrollTop( newTop + self.waiting.outerHeight() );
self.ajax( function() { self.waiting.hide(); });
}, wpLink.timeToTriggerRiver );
}
});
Query = function( search ) {
this.page = 1;
this.allLoaded = false;
this.querying = false;
this.search = search;
};
$.extend( Query.prototype, {
ready: function() {
return !( this.querying || this.allLoaded );
},
ajax: function( callback ) {
var self = this,
query = {
action : 'wp-link-ajax',
page : this.page,
'_ajax_linking_nonce' : inputs.nonce.val()
};
if ( this.search )
query.search = this.search;
this.querying = true;
$.post( ajaxurl, query, function(r) {
self.page++;
self.querying = false;
self.allLoaded = !r;
callback( r, query );
}, "json" );
}
});
$(document).ready( wpLink.init );
})(jQuery);
| JavaScript |
if ( typeof wp === 'undefined' )
var wp = {};
(function( exports, $ ){
var api = wp.customize,
Loader;
$.extend( $.support, {
history: !! ( window.history && history.pushState ),
hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7)
});
Loader = $.extend( {}, api.Events, {
initialize: function() {
this.body = $( document.body );
// Ensure the loader is supported.
// Check for settings, postMessage support, and whether we require CORS support.
if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) {
return;
}
this.window = $( window );
this.element = $( '<div id="customize-container" />' ).appendTo( this.body );
this.bind( 'open', this.overlay.show );
this.bind( 'close', this.overlay.hide );
$('#wpbody').on( 'click', '.load-customize', function( event ) {
event.preventDefault();
// Load the theme.
Loader.open( $(this).attr('href') );
});
// Add navigation listeners.
if ( $.support.history )
this.window.on( 'popstate', Loader.popstate );
if ( $.support.hashchange ) {
this.window.on( 'hashchange', Loader.hashchange );
this.window.triggerHandler( 'hashchange' );
}
},
popstate: function( e ) {
var state = e.originalEvent.state;
if ( state && state.customize )
Loader.open( state.customize );
else if ( Loader.active )
Loader.close();
},
hashchange: function( e ) {
var hash = window.location.toString().split('#')[1];
if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) )
Loader.open( Loader.settings.url + '?' + hash );
if ( ! hash && ! $.support.history )
Loader.close();
},
open: function( src ) {
var hash;
if ( this.active )
return;
// Load the full page on mobile devices.
if ( Loader.settings.browser.mobile )
return window.location = src;
this.active = true;
this.body.addClass('customize-loading');
this.iframe = $( '<iframe />', { src: src }).appendTo( this.element );
this.iframe.one( 'load', this.loaded );
// Create a postMessage connection with the iframe.
this.messenger = new api.Messenger({
url: src,
channel: 'loader',
targetWindow: this.iframe[0].contentWindow
});
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );
});
this.messenger.bind( 'close', function() {
if ( $.support.history )
history.back();
else if ( $.support.hashchange )
window.location.hash = '';
else
Loader.close();
});
this.messenger.bind( 'activated', function( location ) {
if ( location )
window.location = location;
});
hash = src.split('?')[1];
// Ensure we don't call pushState if the user hit the forward button.
if ( $.support.history && window.location.href !== src )
history.pushState( { customize: src }, '', src );
else if ( ! $.support.history && $.support.hashchange && hash )
window.location.hash = 'wp_customize=on&' + hash;
this.trigger( 'open' );
},
opened: function() {
Loader.body.addClass( 'customize-active full-overlay-active' );
},
close: function() {
if ( ! this.active )
return;
this.active = false;
this.trigger( 'close' );
},
closed: function() {
Loader.iframe.remove();
Loader.messenger.destroy();
Loader.iframe = null;
Loader.messenger = null;
Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' );
},
loaded: function() {
Loader.body.removeClass('customize-loading');
},
overlay: {
show: function() {
this.element.fadeIn( 200, Loader.opened );
},
hide: function() {
this.element.fadeOut( 200, Loader.closed );
}
}
});
$( function() {
Loader.settings = _wpCustomizeLoaderSettings;
Loader.initialize();
});
// Expose the API to the world.
api.Loader = Loader;
})( wp, jQuery );
| JavaScript |
/*
Cookie Plug-in
This plug in automatically gets all the cookies for this site and adds them to the post_params.
Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params.
The cookies will override any other post params with the same name.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.prototype.initSettings = function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point
};
}(SWFUpload.prototype.initSettings);
// refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True
SWFUpload.prototype.refreshCookies = function (sendToFlash) {
if (sendToFlash === undefined) {
sendToFlash = true;
}
sendToFlash = !!sendToFlash;
// Get the post_params object
var postParams = this.settings.post_params;
// Get the cookies
var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value;
for (i = 0; i < caLength; i++) {
c = cookieArray[i];
// Left Trim spaces
while (c.charAt(0) === " ") {
c = c.substring(1, c.length);
}
eqIndex = c.indexOf("=");
if (eqIndex > 0) {
name = c.substring(0, eqIndex);
value = c.substring(eqIndex + 1);
postParams[name] = value;
}
}
if (sendToFlash) {
this.setPostParams(postParams);
}
};
}
| JavaScript |
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}
| JavaScript |
/*
SWFUpload.SWFObject Plugin
Summary:
This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading.
This plugin replaces the Graceful Degradation plugin.
Features:
* swfupload_load_failed_hander event
* swfupload_pre_load_handler event
* minimum_flash_version setting (default: "9.0.28")
* SWFUpload.onload event for early loading
Usage:
Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading
in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker
that was seen using the Graceful Degradation plugin.
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
swfu = new SWFUpload({
minimum_flash_version: "9.0.28",
swfupload_pre_load_handler: swfuploadPreLoad,
swfupload_load_failed_handler: swfuploadLoadFailed
});
};
</script>
Notes:
You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8.
The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs
or corrupt Flash Player installations will not trigger this event.
The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can
be used to prepare the SWFUploadUI and hide alternate content.
swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser.
Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made.
*/
// SWFObject v2.1 must be loaded
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.onload = function () {};
swfobject.addDomLoadEvent(function () {
if (typeof(SWFUpload.onload) === "function") {
setTimeout(function(){SWFUpload.onload.call(window);}, 200);
}
});
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
this.ensureDefault("minimum_flash_version", "9.0.28");
this.ensureDefault("swfupload_pre_load_handler", null);
this.ensureDefault("swfupload_load_failed_handler", null);
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.loadFlash = function (oldLoadFlash) {
return function () {
var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version);
if (hasFlash) {
this.queueEvent("swfupload_pre_load_handler");
if (typeof(oldLoadFlash) === "function") {
oldLoadFlash.call(this);
}
} else {
this.queueEvent("swfupload_load_failed_handler");
}
};
}(SWFUpload.prototype.loadFlash);
SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) {
return function () {
if (typeof(oldDisplayDebugInfo) === "function") {
oldDisplayDebugInfo.call(this);
}
this.debug(
[
"SWFUpload.SWFObject Plugin settings:", "\n",
"\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n",
"\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n",
"\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n",
].join("")
);
};
}(SWFUpload.prototype.displayDebugInfo);
}
| JavaScript |
/*
Speed Plug-in
Features:
*Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc.
- currentSpeed -- String indicating the upload speed, bytes per second
- averageSpeed -- Overall average upload speed, bytes per second
- movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second
- timeRemaining -- Estimated remaining upload time in seconds
- timeElapsed -- Number of seconds passed for this upload
- percentUploaded -- Percentage of the file uploaded (0 to 100)
- sizeUploaded -- Formatted size uploaded so far, bytes
*Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed.
*Adds several Formatting functions for formatting that values provided on the file object.
- SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps)
- SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S)
- SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B )
- SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %)
- SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean)
- Formats a number using the division array to determine how to apply the labels in the Label Array
- factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed)
or as several numbers labeled with units (time)
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.speed = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// List used to keep the speed stats for the files we are tracking
this.fileSpeedStats = {};
this.speedSettings = {};
this.ensureDefault("moving_average_history_size", "10");
this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler;
this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler;
this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler;
this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler;
this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler;
this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler;
this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler;
this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler;
this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler;
this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler;
this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler;
this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler;
delete this.ensureDefault;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.speed.fileQueuedHandler = function (file) {
if (typeof this.speedSettings.user_file_queued_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queued_handler.call(this, file);
}
};
SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) {
if (typeof this.speedSettings.user_file_queue_error_handler === "function") {
file = SWFUpload.speed.extendFile(file);
return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadStartHandler = function (file) {
if (typeof this.speedSettings.user_upload_start_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_start_handler.call(this, file);
}
};
SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_error_handler === "function") {
return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message);
}
};
SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) {
this.updateTracking(file, bytesComplete);
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_progress_handler === "function") {
return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal);
}
};
SWFUpload.speed.uploadSuccessHandler = function (file, serverData) {
if (typeof this.speedSettings.user_upload_success_handler === "function") {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
return this.speedSettings.user_upload_success_handler.call(this, file, serverData);
}
};
SWFUpload.speed.uploadCompleteHandler = function (file) {
file = SWFUpload.speed.extendFile(file, this.fileSpeedStats);
SWFUpload.speed.removeTracking(file, this.fileSpeedStats);
if (typeof this.speedSettings.user_upload_complete_handler === "function") {
return this.speedSettings.user_upload_complete_handler.call(this, file);
}
};
// Private: extends the file object with the speed plugin values
SWFUpload.speed.extendFile = function (file, trackingList) {
var tracking;
if (trackingList) {
tracking = trackingList[file.id];
}
if (tracking) {
file.currentSpeed = tracking.currentSpeed;
file.averageSpeed = tracking.averageSpeed;
file.movingAverageSpeed = tracking.movingAverageSpeed;
file.timeRemaining = tracking.timeRemaining;
file.timeElapsed = tracking.timeElapsed;
file.percentUploaded = tracking.percentUploaded;
file.sizeUploaded = tracking.bytesUploaded;
} else {
file.currentSpeed = 0;
file.averageSpeed = 0;
file.movingAverageSpeed = 0;
file.timeRemaining = 0;
file.timeElapsed = 0;
file.percentUploaded = 0;
file.sizeUploaded = 0;
}
return file;
};
// Private: Updates the speed tracking object, or creates it if necessary
SWFUpload.prototype.updateTracking = function (file, bytesUploaded) {
var tracking = this.fileSpeedStats[file.id];
if (!tracking) {
this.fileSpeedStats[file.id] = tracking = {};
}
// Sanity check inputs
bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0;
if (bytesUploaded < 0) {
bytesUploaded = 0;
}
if (bytesUploaded > file.size) {
bytesUploaded = file.size;
}
var tickTime = (new Date()).getTime();
if (!tracking.startTime) {
tracking.startTime = (new Date()).getTime();
tracking.lastTime = tracking.startTime;
tracking.currentSpeed = 0;
tracking.averageSpeed = 0;
tracking.movingAverageSpeed = 0;
tracking.movingAverageHistory = [];
tracking.timeRemaining = 0;
tracking.timeElapsed = 0;
tracking.percentUploaded = bytesUploaded / file.size;
tracking.bytesUploaded = bytesUploaded;
} else if (tracking.startTime > tickTime) {
this.debug("When backwards in time");
} else {
// Get time and deltas
var now = (new Date()).getTime();
var lastTime = tracking.lastTime;
var deltaTime = now - lastTime;
var deltaBytes = bytesUploaded - tracking.bytesUploaded;
if (deltaBytes === 0 || deltaTime === 0) {
return tracking;
}
// Update tracking object
tracking.lastTime = now;
tracking.bytesUploaded = bytesUploaded;
// Calculate speeds
tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000);
tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000);
// Calculate moving average
tracking.movingAverageHistory.push(tracking.currentSpeed);
if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) {
tracking.movingAverageHistory.shift();
}
tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory);
// Update times
tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed;
tracking.timeElapsed = (now - tracking.startTime) / 1000;
// Update percent
tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100);
}
return tracking;
};
SWFUpload.speed.removeTracking = function (file, trackingList) {
try {
trackingList[file.id] = null;
delete trackingList[file.id];
} catch (ex) {
}
};
SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
var i, unit, unitDivisor, unitLabel;
if (baseNumber === 0) {
return "0 " + unitLabels[unitLabels.length - 1];
}
if (singleFractional) {
unit = baseNumber;
unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
for (i = 0; i < unitDivisors.length; i++) {
if (baseNumber >= unitDivisors[i]) {
unit = (baseNumber / unitDivisors[i]).toFixed(2);
unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
break;
}
}
return unit + unitLabel;
} else {
var formattedStrings = [];
var remainder = baseNumber;
for (i = 0; i < unitDivisors.length; i++) {
unitDivisor = unitDivisors[i];
unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
unit = remainder / unitDivisor;
if (i < unitDivisors.length -1) {
unit = Math.floor(unit);
} else {
unit = unit.toFixed(2);
}
if (unit > 0) {
remainder = remainder % unitDivisor;
formattedStrings.push(unit + unitLabel);
}
}
return formattedStrings.join(" ");
}
};
SWFUpload.speed.formatBPS = function (baseNumber) {
var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);
};
SWFUpload.speed.formatTime = function (baseNumber) {
var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false);
};
SWFUpload.speed.formatBytes = function (baseNumber) {
var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);
};
SWFUpload.speed.formatPercent = function (baseNumber) {
return baseNumber.toFixed(2) + " %";
};
SWFUpload.speed.calculateMovingAverage = function (history) {
var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0;
var i;
var mSum = 0, mCount = 0;
size = history.length;
// Check for sufficient data
if (size >= 8) {
// Clone the array and Calculate sum of the values
for (i = 0; i < size; i++) {
vals[i] = history[i];
sum += vals[i];
}
mean = sum / size;
// Calculate variance for the set
for (i = 0; i < size; i++) {
varianceTemp += Math.pow((vals[i] - mean), 2);
}
variance = varianceTemp / size;
standardDev = Math.sqrt(variance);
//Standardize the Data
for (i = 0; i < size; i++) {
vals[i] = (vals[i] - mean) / standardDev;
}
// Calculate the average excluding outliers
var deviationRange = 2.0;
for (i = 0; i < size; i++) {
if (vals[i] <= deviationRange && vals[i] >= -deviationRange) {
mCount++;
mSum += history[i];
}
}
} else {
// Calculate the average (not enough data points to remove outliers)
mCount = size;
for (i = 0; i < size; i++) {
mSum += history[i];
}
}
return mSum / mCount;
};
} | JavaScript |
var topWin = window.dialogArguments || opener || parent || top;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
// Collapse a single item
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.describe-toggle-on').show();
jQuery('.describe-toggle-off').hide();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + post_id + '"><div class="progress"><div class="bar"></div></div><div class="filename original"><span class="percent"></span> ' + fileObj.name + '</div></div>');
// Display the progress div
jQuery('.progress', '#media-item-' + fileObj.id).show();
// Disable submit and enable cancel
jQuery('#insert-gallery').prop('disabled', true);
jQuery('#cancel-upload').prop('disabled', false);
}
function uploadStart(fileObj) {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(fileObj, bytesDone, bytesTotal) {
// Lengthen the progress bar
var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id);
jQuery('.bar', item).width( w * bytesDone / bytesTotal );
jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' );
if ( bytesDone == bytesTotal )
jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>');
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
// Move the progress bar to 100%
jQuery('.bar', item).remove();
jQuery('.progress', item).hide();
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
// Old style: Append the HTML returned by the server -- thumbnail and form inputs
if ( isNaN(serverData) || !serverData ) {
item.append(serverData);
prepareMediaItemInit(fileObj);
}
// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
else {
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Also bind toggle to the links
jQuery('a.toggle', item).click(function(){
jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){
var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b;
if ( w && t && h ) {
b = t + h;
if ( b > w && (h + 48) < w )
window.scrollBy(0, b - w + 13);
else if ( b > w )
window.scrollTo(0, t - 36);
}
});
jQuery(this).siblings('.toggle').andSelf().toggle();
jQuery(this).siblings('a.toggle').focus();
return false;
});
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('a.describe-toggle-on, .menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle();
}
function itemAjaxError(id, html) {
var item = jQuery('#media-item-' + id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ html
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function updateMediaForm() {
var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( one.length == 1 ) {
jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
// Only show Gallery button when there are at least two files.
if ( items.length > 1 )
jQuery('.insert-gallery').show();
else
jQuery('.insert-gallery').hide();
}
function uploadSuccess(fileObj, serverData) {
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match('media-upload-error') ) {
jQuery('#media-item-' + fileObj.id).html(serverData);
return;
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function uploadComplete(fileObj) {
// If no more uploads queued, enable the submit button
if ( swfu.getStats().files_queued == 0 ) {
jQuery('#cancel-upload').prop('disabled', true);
jQuery('#insert-gallery').prop('disabled', false);
}
}
// wp-specific error handlers
// generic message
function wpQueueError(message) {
jQuery('#media-upload-error').show().text(message);
}
// file-specific message
function wpFileError(fileObj, message) {
var item = jQuery('#media-item-' + fileObj.id);
var filename = jQuery('.filename', item).text();
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>'
+ '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />'
+ message
+ '</div>');
item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})});
}
function fileQueueError(fileObj, error_code, message) {
// Handle this error separately because we don't want to create a FileProgress element for it.
if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) {
wpQueueError(swfuploadL10n.queue_limit_exceeded);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.zero_byte_file);
}
else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) {
fileQueued(fileObj);
wpFileError(fileObj, swfuploadL10n.invalid_filetype);
}
else {
wpQueueError(swfuploadL10n.default_error);
}
}
function fileDialogComplete(num_files_queued) {
try {
if (num_files_queued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
}
function switchUploader(s) {
var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id);
if ( s ) {
f.style.display = 'block';
h.style.display = 'none';
} else {
f.style.display = 'none';
h.style.display = 'block';
}
}
function swfuploadPreLoad() {
if ( !uploaderMode ) {
switchUploader(1);
} else {
switchUploader(0);
}
}
function swfuploadLoadFailed() {
switchUploader(0);
jQuery('.upload-html-bypass').hide();
}
function uploadError(fileObj, errorCode, message) {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
wpFileError(fileObj, swfuploadL10n.missing_upload_url);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded);
break;
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
wpQueueError(swfuploadL10n.http_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
wpQueueError(swfuploadL10n.upload_failed);
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
wpQueueError(swfuploadL10n.io_error);
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
wpQueueError(swfuploadL10n.security_error);
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;
default:
wpFileError(fileObj, swfuploadL10n.default_error);
}
}
function cancelUpload() {
swfu.cancelQueue();
}
// remember the last used image size, alignment and url
jQuery(document).ready(function($){
$('input[type="radio"]', '#media-items').live('click', function(){
var tr = $(this).closest('tr');
if ( $(tr).hasClass('align') )
setUserSetting('align', $(this).val());
else if ( $(tr).hasClass('image-size') )
setUserSetting('imgsize', $(this).val());
});
$('button.button', '#media-items').live('click', function(){
var c = this.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
$(this).siblings('.urlfield').val( $(this).attr('title') );
}
});
});
| JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* 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 David Spurr nor the names of its 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.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});
| JavaScript |
if ( typeof wp === 'undefined' )
var wp = {};
(function( exports, $ ) {
var Uploader;
if ( typeof _wpPluploadSettings === 'undefined' )
return;
/*
* An object that helps create a WordPress uploader using plupload.
*
* @param options - object - The options passed to the new plupload instance.
* Requires the following parameters:
* - container - The id of uploader container.
* - browser - The id of button to trigger the file select.
* - dropzone - The id of file drop target.
* - plupload - An object of parameters to pass to the plupload instance.
* - params - An object of parameters to pass to $_POST when uploading the file.
* Extends this.plupload.multipart_params under the hood.
*
* @param attributes - object - Attributes and methods for this specific instance.
*/
Uploader = function( options ) {
var self = this,
elements = {
container: 'container',
browser: 'browse_button',
dropzone: 'drop_element'
},
key;
this.supports = {
upload: Uploader.browser.supported
};
this.supported = this.supports.upload;
if ( ! this.supported )
return;
// Use deep extend to ensure that multipart_params and other objects are cloned.
this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
this.container = document.body; // Set default container.
// Extend the instance with options
//
// Use deep extend to allow options.plupload to override individual
// default plupload keys.
$.extend( true, this, options );
// Proxy all methods so this always refers to the current instance.
for ( key in this ) {
if ( $.isFunction( this[ key ] ) )
this[ key ] = $.proxy( this[ key ], this );
}
// Ensure all elements are jQuery elements and have id attributes
// Then set the proper plupload arguments to the ids.
for ( key in elements ) {
if ( ! this[ key ] )
continue;
this[ key ] = $( this[ key ] ).first();
if ( ! this[ key ].length ) {
delete this[ key ];
continue;
}
if ( ! this[ key ].prop('id') )
this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
this.plupload[ elements[ key ] ] = this[ key ].prop('id');
}
// If the uploader has neither a browse button nor a dropzone, bail.
if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) )
return;
this.uploader = new plupload.Uploader( this.plupload );
delete this.plupload;
// Set default params and remove this.params alias.
this.param( this.params || {} );
delete this.params;
this.uploader.init();
this.supports.dragdrop = this.uploader.features.dragdrop && ! Uploader.browser.mobile;
// Generate drag/drop helper classes.
(function( dropzone, supported ) {
var sensitivity = 50,
active;
if ( ! dropzone )
return;
dropzone.toggleClass( 'supports-drag-drop', !! supported );
if ( ! supported )
return dropzone.unbind('.wp-uploader');
// 'dragenter' doesn't fire correctly,
// simulate it with a limited 'dragover'
dropzone.bind( 'dragover.wp-uploader', function(){
if ( active )
return;
dropzone.addClass('drag-over');
active = true;
});
dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function(){
active = false;
dropzone.removeClass('drag-over');
});
}( this.dropzone, this.supports.dragdrop ));
if ( this.browser ) {
this.browser.on( 'mouseenter', this.refresh );
} else {
this.uploader.disableBrowse( true );
// If HTML5 mode, hide the auto-created file container.
$('#' + this.uploader.id + '_html5_container').hide();
}
this.uploader.bind( 'UploadProgress', this.progress );
this.uploader.bind( 'FileUploaded', function( up, file, response ) {
try {
response = JSON.parse( response.response );
} catch ( e ) {
return self.error( pluploadL10n.default_error, e );
}
if ( ! response || ! response.type || ! response.data )
return self.error( pluploadL10n.default_error );
if ( 'error' === response.type )
return self.error( response.data.message, response.data );
if ( 'success' === response.type )
return self.success( response.data );
});
this.uploader.bind( 'Error', function( up, error ) {
var message = pluploadL10n.default_error,
key;
// Check for plupload errors.
for ( key in Uploader.errorMap ) {
if ( error.code === plupload[ key ] ) {
message = Uploader.errorMap[ key ];
break;
}
}
self.error( message, error );
up.refresh();
});
this.uploader.bind( 'FilesAdded', function( up, files ) {
$.each( files, function() {
self.added( this );
});
up.refresh();
up.start();
});
this.init();
};
// Adds the 'defaults' and 'browser' properties.
$.extend( Uploader, _wpPluploadSettings );
Uploader.uuid = 0;
Uploader.errorMap = {
'FAILED': pluploadL10n.upload_failed,
'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype,
// 'FILE_SIZE_ERROR': '',
'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image,
'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded,
'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
'GENERIC_ERROR': pluploadL10n.upload_failed,
'IO_ERROR': pluploadL10n.io_error,
'HTTP_ERROR': pluploadL10n.http_error,
'SECURITY_ERROR': pluploadL10n.security_error
};
$.extend( Uploader.prototype, {
/**
* Acts as a shortcut to extending the uploader's multipart_params object.
*
* param( key )
* Returns the value of the key.
*
* param( key, value )
* Sets the value of a key.
*
* param( map )
* Sets values for a map of data.
*/
param: function( key, value ) {
if ( arguments.length === 1 && typeof key === 'string' )
return this.uploader.settings.multipart_params[ key ];
if ( arguments.length > 1 ) {
this.uploader.settings.multipart_params[ key ] = value;
} else {
$.extend( this.uploader.settings.multipart_params, key );
}
},
init: function() {},
error: function() {},
success: function() {},
added: function() {},
progress: function() {},
complete: function() {},
refresh: function() {
this.uploader.refresh();
}
});
exports.Uploader = Uploader;
})( wp, jQuery );
| JavaScript |
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
var items = jQuery('#media-items').children(), postid = post_id || 0;
// Collapse a single item
if ( items.length == 1 ) {
items.removeClass('open').find('.slidetoggle').slideUp(200);
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + postid + '"><div class="progress"><div class="percent">0%</div><div class="bar"></div></div><div class="filename original"> ' + fileObj.name + '</div></div>');
// Disable submit
jQuery('#insert-gallery').prop('disabled', true);
}
function uploadStart() {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(up, file) {
var item = jQuery('#media-item-' + file.id);
jQuery('.bar', item).width( (200 * file.loaded) / file.size );
jQuery('.percent', item).html( file.percent + '%' );
}
// check to see if a large file failed to upload
function fileUploading(up, file) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
if ( max > hundredmb && file.size > hundredmb ) {
setTimeout(function(){
var done;
if ( file.status < 3 && file.loaded == 0 ) { // not uploading
wpFileError(file, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
up.stop(); // stops the whole queue
up.removeFile(file);
up.start(); // restart the queue
}
}, 10000); // wait for 10 sec. for the file to start uploading
}
}
function updateMediaForm() {
var items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( items.length == 1 ) {
items.addClass('open').find('.slidetoggle').show();
jQuery('.insert-gallery').hide();
} else if ( items.length > 1 ) {
items.removeClass('open');
// Only show Gallery button when there are at least two files.
jQuery('.insert-gallery').show();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
}
function uploadSuccess(fileObj, serverData) {
var item = jQuery('#media-item-' + fileObj.id);
// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match(/media-upload-error|error-div/) ) {
item.html(serverData);
return;
} else {
jQuery('.percent', item).html( pluploadL10n.crunching );
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( post_id && item.hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function setResize(arg) {
if ( arg ) {
if ( uploader.features.jpgresize )
uploader.settings['resize'] = { width: resize_width, height: resize_height, quality: 100 };
else
uploader.settings.multipart_params.image_resize = true;
} else {
delete(uploader.settings.resize);
delete(uploader.settings.multipart_params.image_resize);
}
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
item.append(serverData);
prepareMediaItemInit(fileObj);
} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('.menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
}
// generic error message
function wpQueueError(message) {
jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
}
// file-specific error messages
function wpFileError(fileObj, message) {
itemAjaxError(fileObj.id, message);
}
function itemAjaxError(id, message) {
var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
if ( last_err == id ) // prevent firing an error for the same file twice
return;
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>'
+ '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> '
+ message
+ '</div>').data('last-err', id);
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function uploadComplete() {
jQuery('#insert-gallery').prop('disabled', false);
}
function switchUploader(s) {
if ( s ) {
deleteUserSetting('uploader');
jQuery('.media-upload-form').removeClass('html-uploader');
if ( typeof(uploader) == 'object' )
uploader.refresh();
} else {
setUserSetting('uploader', '1'); // 1 == html uploader
jQuery('.media-upload-form').addClass('html-uploader');
}
}
function dndHelper(s) {
var d = document.getElementById('dnd-helper');
if ( s ) {
d.style.display = 'block';
} else {
d.style.display = 'none';
}
}
function uploadError(fileObj, errorCode, message, uploader) {
var hundredmb = 100 * 1024 * 1024, max;
switch (errorCode) {
case plupload.FAILED:
wpFileError(fileObj, pluploadL10n.upload_failed);
break;
case plupload.FILE_EXTENSION_ERROR:
wpFileError(fileObj, pluploadL10n.invalid_filetype);
break;
case plupload.FILE_SIZE_ERROR:
uploadSizeError(uploader, fileObj);
break;
case plupload.IMAGE_FORMAT_ERROR:
wpFileError(fileObj, pluploadL10n.not_an_image);
break;
case plupload.IMAGE_MEMORY_ERROR:
wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
break;
case plupload.IMAGE_DIMENSIONS_ERROR:
wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
break;
case plupload.GENERIC_ERROR:
wpQueueError(pluploadL10n.upload_failed);
break;
case plupload.IO_ERROR:
max = parseInt(uploader.settings.max_file_size, 10);
if ( max > hundredmb && fileObj.size > hundredmb )
wpFileError(fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
else
wpQueueError(pluploadL10n.io_error);
break;
case plupload.HTTP_ERROR:
wpQueueError(pluploadL10n.http_error);
break;
case plupload.INIT_ERROR:
jQuery('.media-upload-form').addClass('html-uploader');
break;
case plupload.SECURITY_ERROR:
wpQueueError(pluploadL10n.security_error);
break;
/* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
case plupload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;*/
default:
wpFileError(fileObj, pluploadL10n.default_error);
}
}
function uploadSizeError( up, file, over100mb ) {
var message;
if ( over100mb )
message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
else
message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
up.removeFile(file);
}
jQuery(document).ready(function($){
$('.media-upload-form').bind('click.uploader', function(e) {
var target = $(e.target), tr, c;
if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
tr = target.closest('tr');
if ( tr.hasClass('align') )
setUserSetting('align', target.val());
else if ( tr.hasClass('image-size') )
setUserSetting('imgsize', target.val());
} else if ( target.is('button.button') ) { // remember the last used image link url
c = e.target.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
target.siblings('.urlfield').val( target.data('link-url') );
}
} else if ( target.is('a.dismiss') ) {
target.parents('.media-item').fadeOut(200, function(){
$(this).remove();
});
} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
switchUploader(0);
e.preventDefault();
} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
$('#media-items, p.submit, span.big-file-warning').css('display', '');
switchUploader(1);
e.preventDefault();
} else if ( target.is('a.describe-toggle-on') ) { // Show
target.parent().addClass('open');
target.siblings('.slidetoggle').fadeIn(250, function(){
var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
if ( H && top && h ) {
b = top + h;
B = S + H;
if ( b > B ) {
if ( b - B < top - S )
window.scrollBy(0, (b - B) + 10);
else
window.scrollBy(0, top - S - 40);
}
}
});
e.preventDefault();
} else if ( target.is('a.describe-toggle-off') ) { // Hide
target.siblings('.slidetoggle').fadeOut(250, function(){
target.parent().removeClass('open');
});
e.preventDefault();
}
});
// init and set the uploader
uploader_init = function() {
uploader = new plupload.Uploader(wpUploaderInit);
$('#image_resize').bind('change', function() {
var arg = $(this).prop('checked');
setResize( arg );
if ( arg )
setUserSetting('upload_resize', '1');
else
deleteUserSetting('upload_resize');
});
uploader.bind('Init', function(up) {
var uploaddiv = $('#plupload-upload-ui');
setResize( getUserSetting('upload_resize', false) );
if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
uploaddiv.addClass('drag-drop');
$('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
uploaddiv.addClass('drag-over');
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
$('#media-upload-error').html('');
uploadStart();
plupload.each(files, function(file){
if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' )
uploadSizeError( up, file, true );
else
fileQueued(file);
});
up.refresh();
up.start();
});
uploader.bind('BeforeUpload', function(up, file) {
// something
});
uploader.bind('UploadFile', function(up, file) {
fileUploading(up, file);
});
uploader.bind('UploadProgress', function(up, file) {
uploadProgress(up, file);
});
uploader.bind('Error', function(up, err) {
uploadError(err.file, err.code, err.message, up);
up.refresh();
});
uploader.bind('FileUploaded', function(up, file, response) {
uploadSuccess(file, response.response);
});
uploader.bind('UploadComplete', function(up, files) {
uploadComplete();
});
}
if ( typeof(wpUploaderInit) == 'object' )
uploader_init();
});
| JavaScript |
/**
* jquery.Jcrop.js v0.9.8
* jQuery Image Cropping Plugin
* @author Kelly Hallman <khallman@gmail.com>
* Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* }}}
*/
(function($) {
$.Jcrop = function(obj,opt)
{
// Initialization {{{
// Sanitize some options {{{
var obj = obj, opt = opt;
if (typeof(obj) !== 'object') obj = $(obj)[0];
if (typeof(opt) !== 'object') opt = { };
// Some on-the-fly fixes for MSIE...sigh
if (!('trackDocument' in opt))
{
opt.trackDocument = $.browser.msie ? false : true;
if ($.browser.msie && $.browser.version.split('.')[0] == '8')
opt.trackDocument = true;
}
if (!('keySupport' in opt))
opt.keySupport = $.browser.msie ? false : true;
// }}}
// Extend the default options {{{
var defaults = {
// Basic Settings
trackDocument: false,
baseClass: 'jcrop',
addClass: null,
// Styling Options
bgColor: 'black',
bgOpacity: .6,
borderOpacity: .4,
handleOpacity: .5,
handlePad: 5,
handleSize: 9,
handleOffset: 5,
edgeMargin: 14,
aspectRatio: 0,
keySupport: true,
cornerHandles: true,
sideHandles: true,
drawBorders: true,
dragEdges: true,
boxWidth: 0,
boxHeight: 0,
boundary: 8,
animationDelay: 20,
swingSpeed: 3,
allowSelect: true,
allowMove: true,
allowResize: true,
minSelect: [ 0, 0 ],
maxSize: [ 0, 0 ],
minSize: [ 0, 0 ],
// Callbacks / Event Handlers
onChange: function() { },
onSelect: function() { }
};
var options = defaults;
setOptions(opt);
// }}}
// Initialize some jQuery objects {{{
var $origimg = $(obj);
var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
presize($img,options.boxWidth,options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $('<div />')
.width(boundx).height(boundy)
.addClass(cssClass('holder'))
.css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
;
if (options.addClass) $div.addClass(options.addClass);
//$img.wrap($div);
var $img2 = $('<img />')/*{{{*/
.attr('src',$img.attr('src'))
.css('position','absolute')
.width(boundx).height(boundy)
;/*}}}*/
var $img_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
})
.append($img2)
;/*}}}*/
var $hdl_holder = $('<div />')/*{{{*/
.width(pct(100)).height(pct(100))
.css('zIndex',320);
/*}}}*/
var $sel = $('<div />')/*{{{*/
.css({
position: 'absolute',
zIndex: 300
})
.insertBefore($img)
.append($img_holder,$hdl_holder)
;/*}}}*/
var bound = options.boundary;
var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
.css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
.mousedown(newSelection);
/* }}} */
// Set more variables {{{
var xlimit, ylimit, xmin, ymin;
var xscale, yscale, enabled = true;
var docOffset = getPos($img),
// Internal states
btndown, lastcurs, dimmed, animating,
shift_down;
// }}}
// }}}
// Internal Modules {{{
var Coords = function()/*{{{*/
{
var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;
function setPressed(pos)/*{{{*/
{
var pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
};
/*}}}*/
function setCurrent(pos)/*{{{*/
{
var pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
};
/*}}}*/
function getOffset()/*{{{*/
{
return [ ox, oy ];
};
/*}}}*/
function moveOffset(offset)/*{{{*/
{
var ox = offset[0], oy = offset[1];
if (0 > x1 + ox) ox -= ox + x1;
if (0 > y1 + oy) oy -= oy + y1;
if (boundy < y2 + oy) oy += boundy - (y2 + oy);
if (boundx < x2 + ox) ox += boundx - (x2 + ox);
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
};
/*}}}*/
function getCorner(ord)/*{{{*/
{
var c = getFixed();
switch(ord)
{
case 'ne': return [ c.x2, c.y ];
case 'nw': return [ c.x, c.y ];
case 'se': return [ c.x2, c.y2 ];
case 'sw': return [ c.x, c.y2 ];
}
};
/*}}}*/
function getFixed()/*{{{*/
{
if (!options.aspectRatio) return getRect();
// This function could use some optimization I think...
var aspect = options.aspectRatio,
min_x = options.minSize[0]/xscale,
min_y = options.minSize[1]/yscale,
max_x = options.maxSize[0]/xscale,
max_y = options.maxSize[1]/yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx, yy
;
if (max_x == 0) { max_x = boundx * 10 }
if (max_y == 0) { max_y = boundy * 10 }
if (real_ratio < aspect)
{
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0)
{
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h: h + y1;
}
else if (xx > boundx)
{
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
}
else
{
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0)
{
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
}
else if (yy > boundy)
{
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
// Magic %-)
if(xx > x1) { // right side
if(xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if(yy > y1) {
yy = y1 + (xx - x1)/aspect;
} else {
yy = y1 - (xx - x1)/aspect;
}
} else if (xx < x1) { // left side
if(x1 - xx < min_x) {
xx = x1 - min_x
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if(yy > y1) {
yy = y1 + (x1 - xx)/aspect;
} else {
yy = y1 - (x1 - xx)/aspect;
}
}
if(xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if(yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return last = makeObj(flipCoords(x1,y1,xx,yy));
};
/*}}}*/
function rebound(p)/*{{{*/
{
if (p[0] < 0) p[0] = 0;
if (p[1] < 0) p[1] = 0;
if (p[0] > boundx) p[0] = boundx;
if (p[1] > boundy) p[1] = boundy;
return [ p[0], p[1] ];
};
/*}}}*/
function flipCoords(x1,y1,x2,y2)/*{{{*/
{
var xa = x1, xb = x2, ya = y1, yb = y2;
if (x2 < x1)
{
xa = x2;
xb = x1;
}
if (y2 < y1)
{
ya = y2;
yb = y1;
}
return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
};
/*}}}*/
function getRect()/*{{{*/
{
var xsize = x2 - x1;
var ysize = y2 - y1;
if (xlimit && (Math.abs(xsize) > xlimit))
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
if (ylimit && (Math.abs(ysize) > ylimit))
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
if (ymin && (Math.abs(ysize) < ymin))
y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
if (xmin && (Math.abs(xsize) < xmin))
x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);
if (x1 < 0) { x2 -= x1; x1 -= x1; }
if (y1 < 0) { y2 -= y1; y1 -= y1; }
if (x2 < 0) { x1 -= x2; x2 -= x2; }
if (y2 < 0) { y1 -= y2; y2 -= y2; }
if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }
return makeObj(flipCoords(x1,y1,x2,y2));
};
/*}}}*/
function makeObj(a)/*{{{*/
{
return { x: a[0], y: a[1], x2: a[2], y2: a[3],
w: a[2] - a[0], h: a[3] - a[1] };
};
/*}}}*/
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed
};
}();
/*}}}*/
var Selection = function()/*{{{*/
{
var start, end, dragmode, awake, hdep = 370;
var borders = { };
var handle = { };
var seehandles = false;
var hhs = options.handleOffset;
/* Insert draggable elements {{{*/
// Insert border divs for outline
if (options.drawBorders) {
borders = {
top: insertBorder('hline')
.css('top',$.browser.msie?px(-1):px(0)),
bottom: insertBorder('hline'),
left: insertBorder('vline'),
right: insertBorder('vline')
};
}
// Insert handles on edges
if (options.dragEdges) {
handle.t = insertDragbar('n');
handle.b = insertDragbar('s');
handle.r = insertDragbar('e');
handle.l = insertDragbar('w');
}
// Insert side handles
options.sideHandles &&
createHandles(['n','s','e','w']);
// Insert corner handles
options.cornerHandles &&
createHandles(['sw','nw','ne','se']);
/*}}}*/
// Private Methods
function insertBorder(type)/*{{{*/
{
var jq = $('<div />')
.css({position: 'absolute', opacity: options.borderOpacity })
.addClass(cssClass(type));
$img_holder.append(jq);
return jq;
};
/*}}}*/
function dragDiv(ord,zi)/*{{{*/
{
var jq = $('<div />')
.mousedown(createDragger(ord))
.css({
cursor: ord+'-resize',
position: 'absolute',
zIndex: zi
})
;
$hdl_holder.append(jq);
return jq;
};
/*}}}*/
function insertHandle(ord)/*{{{*/
{
return dragDiv(ord,hdep++)
.css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
.addClass(cssClass('handle'));
};
/*}}}*/
function insertDragbar(ord)/*{{{*/
{
var s = options.handleSize,
o = hhs,
h = s, w = s,
t = o, l = o;
switch(ord)
{
case 'n': case 's': w = pct(100); break;
case 'e': case 'w': h = pct(100); break;
}
return dragDiv(ord,hdep++).width(w).height(h)
.css({ top: px(-t+1), left: px(-l+1)});
};
/*}}}*/
function createHandles(li)/*{{{*/
{
for(i in li) handle[li[i]] = insertHandle(li[i]);
};
/*}}}*/
function moveHandles(c)/*{{{*/
{
var midvert = Math.round((c.h / 2) - hhs),
midhoriz = Math.round((c.w / 2) - hhs),
north = west = -hhs+1,
east = c.w - hhs,
south = c.h - hhs,
x, y;
'e' in handle &&
handle.e.css({ top: px(midvert), left: px(east) }) &&
handle.w.css({ top: px(midvert) }) &&
handle.s.css({ top: px(south), left: px(midhoriz) }) &&
handle.n.css({ left: px(midhoriz) });
'ne' in handle &&
handle.ne.css({ left: px(east) }) &&
handle.se.css({ top: px(south), left: px(east) }) &&
handle.sw.css({ top: px(south) });
'b' in handle &&
handle.b.css({ top: px(south) }) &&
handle.r.css({ left: px(east) });
};
/*}}}*/
function moveto(x,y)/*{{{*/
{
$img2.css({ top: px(-y), left: px(-x) });
$sel.css({ top: px(y), left: px(x) });
};
/*}}}*/
function resize(w,h)/*{{{*/
{
$sel.width(w).height(h);
};
/*}}}*/
function refresh()/*{{{*/
{
var c = Coords.getFixed();
Coords.setPressed([c.x,c.y]);
Coords.setCurrent([c.x2,c.y2]);
updateVisible();
};
/*}}}*/
// Internal Methods
function updateVisible()/*{{{*/
{ if (awake) return update(); };
/*}}}*/
function update()/*{{{*/
{
var c = Coords.getFixed();
resize(c.w,c.h);
moveto(c.x,c.y);
options.drawBorders &&
borders['right'].css({ left: px(c.w-1) }) &&
borders['bottom'].css({ top: px(c.h-1) });
seehandles && moveHandles(c);
awake || show();
options.onChange(unscale(c));
};
/*}}}*/
function show()/*{{{*/
{
$sel.show();
$img.css('opacity',options.bgOpacity);
awake = true;
};
/*}}}*/
function release()/*{{{*/
{
disableHandles();
$sel.hide();
$img.css('opacity',1);
awake = false;
};
/*}}}*/
function showHandles()//{{{
{
if (seehandles)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
}
};
//}}}
function enableHandles()/*{{{*/
{
seehandles = true;
if (options.allowResize)
{
moveHandles(Coords.getFixed());
$hdl_holder.show();
return true;
}
};
/*}}}*/
function disableHandles()/*{{{*/
{
seehandles = false;
$hdl_holder.hide();
};
/*}}}*/
function animMode(v)/*{{{*/
{
(animating = v) ? disableHandles(): enableHandles();
};
/*}}}*/
function done()/*{{{*/
{
animMode(false);
refresh();
};
/*}}}*/
var $track = newTracker().mousedown(createDragger('move'))
.css({ cursor: 'move', position: 'absolute', zIndex: 360 })
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
setCursor: function (cursor) { $track.css('cursor',cursor); },
enableHandles: enableHandles,
enableOnly: function() { seehandles = true; },
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
done: done
};
}();
/*}}}*/
var Tracker = function()/*{{{*/
{
var onMove = function() { },
onDone = function() { },
trackDoc = options.trackDocument;
if (!trackDoc)
{
$trk
.mousemove(trackMove)
.mouseup(trackUp)
.mouseout(trackUp)
;
}
function toFront()/*{{{*/
{
$trk.css({zIndex:450});
if (trackDoc)
{
$(document)
.mousemove(trackMove)
.mouseup(trackUp)
;
}
}
/*}}}*/
function toBack()/*{{{*/
{
$trk.css({zIndex:290});
if (trackDoc)
{
$(document)
.unbind('mousemove',trackMove)
.unbind('mouseup',trackUp)
;
}
}
/*}}}*/
function trackMove(e)/*{{{*/
{
onMove(mouseAbs(e));
};
/*}}}*/
function trackUp(e)/*{{{*/
{
e.preventDefault();
e.stopPropagation();
if (btndown)
{
btndown = false;
onDone(mouseAbs(e));
options.onSelect(unscale(Coords.getFixed()));
toBack();
onMove = function() { };
onDone = function() { };
}
return false;
};
/*}}}*/
function activateHandlers(move,done)/* {{{ */
{
btndown = true;
onMove = move;
onDone = done;
toFront();
return false;
};
/* }}} */
function setCursor(t) { $trk.css('cursor',t); };
$img.before($trk);
return {
activateHandlers: activateHandlers,
setCursor: setCursor
};
}();
/*}}}*/
var KeyManager = function()/*{{{*/
{
var $keymgr = $('<input type="radio" />')
.css({ position: 'absolute', left: '-30px' })
.keypress(parseKey)
.blur(onBlur),
$keywrap = $('<div />')
.css({
position: 'absolute',
overflow: 'hidden'
})
.append($keymgr)
;
function watchKeys()/*{{{*/
{
if (options.keySupport)
{
$keymgr.show();
$keymgr.focus();
}
};
/*}}}*/
function onBlur(e)/*{{{*/
{
$keymgr.hide();
};
/*}}}*/
function doNudge(e,x,y)/*{{{*/
{
if (options.allowMove) {
Coords.moveOffset([x,y]);
Selection.updateVisible();
};
e.preventDefault();
e.stopPropagation();
};
/*}}}*/
function parseKey(e)/*{{{*/
{
if (e.ctrlKey) return true;
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch(e.keyCode)
{
case 37: doNudge(e,-nudge,0); break;
case 39: doNudge(e,nudge,0); break;
case 38: doNudge(e,0,-nudge); break;
case 40: doNudge(e,0,nudge); break;
case 27: Selection.release(); break;
case 9: return true;
}
return nothing(e);
};
/*}}}*/
if (options.keySupport) $keywrap.insertBefore($img);
return {
watchKeys: watchKeys
};
}();
/*}}}*/
// }}}
// Internal Methods {{{
function px(n) { return '' + parseInt(n) + 'px'; };
function pct(n) { return '' + parseInt(n) + '%'; };
function cssClass(cl) { return options.baseClass + '-' + cl; };
function getPos(obj)/*{{{*/
{
// Updated in v0.9.4 to use built-in dimensions plugin
var pos = $(obj).offset();
return [ pos.left, pos.top ];
};
/*}}}*/
function mouseAbs(e)/*{{{*/
{
return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
};
/*}}}*/
function myCursor(type)/*{{{*/
{
if (type != lastcurs)
{
Tracker.setCursor(type);
//Handles.xsetCursor(type);
lastcurs = type;
}
};
/*}}}*/
function startDragMode(mode,pos)/*{{{*/
{
docOffset = getPos($img);
Tracker.setCursor(mode=='move'?mode:mode+'-resize');
if (mode == 'move')
return Tracker.activateHandlers(createMover(pos), doneSelect);
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
};
/*}}}*/
function dragmodeHandler(mode,f)/*{{{*/
{
return function(pos) {
if (!options.aspectRatio) switch(mode)
{
case 'e': pos[1] = f.y2; break;
case 'w': pos[1] = f.y2; break;
case 'n': pos[0] = f.x2; break;
case 's': pos[0] = f.x2; break;
}
else switch(mode)
{
case 'e': pos[1] = f.y+1; break;
case 'w': pos[1] = f.y+1; break;
case 'n': pos[0] = f.x+1; break;
case 's': pos[0] = f.x+1; break;
}
Coords.setCurrent(pos);
Selection.update();
};
};
/*}}}*/
function createMover(pos)/*{{{*/
{
var lloc = pos;
KeyManager.watchKeys();
return function(pos)
{
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
};
/*}}}*/
function oppLockCorner(ord)/*{{{*/
{
switch(ord)
{
case 'n': return 'sw';
case 's': return 'nw';
case 'e': return 'nw';
case 'w': return 'ne';
case 'ne': return 'sw';
case 'nw': return 'se';
case 'se': return 'nw';
case 'sw': return 'ne';
};
};
/*}}}*/
function createDragger(ord)/*{{{*/
{
return function(e) {
if (options.disabled) return false;
if ((ord == 'move') && !options.allowMove) return false;
btndown = true;
startDragMode(ord,mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
};
/*}}}*/
function presize($obj,w,h)/*{{{*/
{
var nw = $obj.width(), nh = $obj.height();
if ((nw > w) && w > 0)
{
nw = w;
nh = (w/$obj.width()) * $obj.height();
}
if ((nh > h) && h > 0)
{
nh = h;
nw = (h/$obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
};
/*}}}*/
function unscale(c)/*{{{*/
{
return {
x: parseInt(c.x * xscale), y: parseInt(c.y * yscale),
x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale),
w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
};
};
/*}}}*/
function doneSelect(pos)/*{{{*/
{
var c = Coords.getFixed();
if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
{
Selection.enableHandles();
Selection.done();
}
else
{
Selection.release();
}
Tracker.setCursor( options.allowSelect?'crosshair':'default' );
};
/*}}}*/
function newSelection(e)/*{{{*/
{
if (options.disabled) return false;
if (!options.allowSelect) return false;
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
myCursor('crosshair');
var pos = mouseAbs(e);
Coords.setPressed(pos);
Tracker.activateHandlers(selectDrag,doneSelect);
KeyManager.watchKeys();
Selection.update();
e.stopPropagation();
e.preventDefault();
return false;
};
/*}}}*/
function selectDrag(pos)/*{{{*/
{
Coords.setCurrent(pos);
Selection.update();
};
/*}}}*/
function newTracker()
{
var trk = $('<div></div>').addClass(cssClass('tracker'));
$.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
return trk;
};
// }}}
// API methods {{{
function animateTo(a)/*{{{*/
{
var x1 = a[0] / xscale,
y1 = a[1] / yscale,
x2 = a[2] / xscale,
y2 = a[3] / yscale;
if (animating) return;
var animto = Coords.flipCoords(x1,y1,x2,y2);
var c = Coords.getFixed();
var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
var interv = options.animationDelay;
var x = animat[0];
var y = animat[1];
var x2 = animat[2];
var y2 = animat[3];
var ix1 = animto[0] - initcr[0];
var iy1 = animto[1] - initcr[1];
var ix2 = animto[2] - initcr[2];
var iy2 = animto[3] - initcr[3];
var pcent = 0;
var velocity = options.swingSpeed;
Selection.animMode(true);
var animator = function()
{
return function()
{
pcent += (100 - pcent) / velocity;
animat[0] = x + ((pcent / 100) * ix1);
animat[1] = y + ((pcent / 100) * iy1);
animat[2] = x2 + ((pcent / 100) * ix2);
animat[3] = y2 + ((pcent / 100) * iy2);
if (pcent < 100) animateStart();
else Selection.done();
if (pcent >= 99.8) pcent = 100;
setSelectRaw(animat);
};
}();
function animateStart()
{ window.setTimeout(animator,interv); };
animateStart();
};
/*}}}*/
function setSelect(rect)//{{{
{
setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
};
//}}}
function setSelectRaw(l) /*{{{*/
{
Coords.setPressed([l[0],l[1]]);
Coords.setCurrent([l[2],l[3]]);
Selection.update();
};
/*}}}*/
function setOptions(opt)/*{{{*/
{
if (typeof(opt) != 'object') opt = { };
options = $.extend(options,opt);
if (typeof(options.onChange)!=='function')
options.onChange = function() { };
if (typeof(options.onSelect)!=='function')
options.onSelect = function() { };
};
/*}}}*/
function tellSelect()/*{{{*/
{
return unscale(Coords.getFixed());
};
/*}}}*/
function tellScaled()/*{{{*/
{
return Coords.getFixed();
};
/*}}}*/
function setOptionsNew(opt)/*{{{*/
{
setOptions(opt);
interfaceUpdate();
};
/*}}}*/
function disableCrop()//{{{
{
options.disabled = true;
Selection.disableHandles();
Selection.setCursor('default');
Tracker.setCursor('default');
};
//}}}
function enableCrop()//{{{
{
options.disabled = false;
interfaceUpdate();
};
//}}}
function cancelCrop()//{{{
{
Selection.done();
Tracker.activateHandlers(null,null);
};
//}}}
function destroy()//{{{
{
$div.remove();
$origimg.show();
};
//}}}
function interfaceUpdate(alt)//{{{
// This method tweaks the interface based on options object.
// Called when options are changed and at end of initialization.
{
options.allowResize ?
alt?Selection.enableOnly():Selection.enableHandles():
Selection.disableHandles();
Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
Selection.setCursor( options.allowMove? 'move': 'default' );
$div.css('backgroundColor',options.bgColor);
if ('setSelect' in options) {
setSelect(opt.setSelect);
Selection.done();
delete(options.setSelect);
}
if ('trueSize' in options) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if ('outerImage' in options)
{
$img.attr('src',options.outerImage);
delete(options.outerImage);
}
Selection.refresh();
};
//}}}
// }}}
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
focus: KeyManager.watchKeys,
getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
getWidgetSize: function() { return [ boundx, boundy ]; },
release: Selection.release,
destroy: destroy
};
$origimg.data('Jcrop',api);
return api;
};
$.fn.Jcrop = function(options)/*{{{*/
{
function attachWhenDone(from)/*{{{*/
{
var loadsrc = options.useImg || from.src;
var img = new Image();
img.onload = function() { $.Jcrop(from,options); };
img.src = loadsrc;
};
/*}}}*/
if (typeof(options) !== 'object') options = { };
// Iterate over each object, attach Jcrop
this.each(function()
{
// If we've already attached to this object
if ($(this).data('Jcrop'))
{
// The API can be requested this way (undocumented)
if (options == 'api') return $(this).data('Jcrop');
// Otherwise, we just reset the options...
else $(this).data('Jcrop').setOptions(options);
}
// If we haven't been attached, preload and attach
else attachWhenDone(this);
});
// Return "this" so we're chainable a la jQuery plugin-style!
return this;
};
/*}}}*/
})(jQuery);
| JavaScript |
(function($) {
var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList;
wpList = {
settings: {
url: ajaxurl, type: 'POST',
response: 'ajax-response',
what: '',
alt: 'alternate', altOffset: 0,
addColor: null, delColor: null, dimAddColor: null, dimDelColor: null,
confirm: null,
addBefore: null, addAfter: null,
delBefore: null, delAfter: null,
dimBefore: null, dimAfter: null
},
nonce: function(e,s) {
var url = wpAjax.unserialize(e.attr('href'));
return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0;
},
parseClass: function(e,t) {
var c = [], cl;
try {
cl = $(e).attr('class') || '';
cl = cl.match(new RegExp(t+':[\\S]+'));
if ( cl )
c = cl[0].split(':');
} catch(r) {}
return c;
},
pre: function(e,s,a) {
var bg, r;
s = $.extend( {}, this.wpList.settings, {
element: null,
nonce: 0,
target: e.get(0)
}, s || {} );
if ( $.isFunction( s.confirm ) ) {
if ( 'add' != a ) {
bg = $('#' + s.element).css('backgroundColor');
$('#' + s.element).css('backgroundColor', '#FF9966');
}
r = s.confirm.call(this, e, s, a, bg);
if ( 'add' != a )
$('#' + s.element).css('backgroundColor', bg );
if ( !r )
return false;
}
return s;
},
ajaxAdd: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'add'), es, valid, formData, res, rres;
s = wpList.pre.call( list, e, s, 'add' );
s.element = cls[2] || e.attr( 'id' ) || s.element || null;
if ( cls[3] )
s.addColor = '#' + cls[3];
else
s.addColor = s.addColor || '#FFFF33';
if ( !s )
return false;
if ( !e.is('[id="' + s.what + '-add-submit"]') )
return !wpList.add.call( list, e, s );
if ( !s.element )
return true;
s.action = 'add-' + s.what;
s.nonce = wpList.nonce(e,s);
es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]');
valid = wpAjax.validateForm( '#' + s.element );
if ( !valid )
return false;
s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( cls[4] || '' ) ) );
formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize();
if ( formData )
s.data += '&' + formData;
if ( $.isFunction(s.addBefore) ) {
s = s.addBefore( s );
if ( !s )
return true;
}
if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors )
return false;
if ( true === res )
return true;
jQuery.each( res.responses, function() {
wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue
pos: this.position || 0,
id: this.id || 0,
oldId: this.oldId || null
} ) );
} );
list.wpList.recolor();
$(list).trigger( 'wpListAddEnd', [ s, list.wpList ] );
wpList.clear.call(list,'#' + s.element);
};
s.complete = function(x, st) {
if ( $.isFunction(s.addAfter) ) {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.addAfter( rres, _s );
}
};
$.ajax( s );
return false;
},
ajaxDel: function( e, s ) {
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'delete'), element, res, rres;
s = wpList.pre.call( list, e, s, 'delete' );
s.element = cls[2] || s.element || null;
if ( cls[3] )
s.delColor = '#' + cls[3];
else
s.delColor = s.delColor || '#faa';
if ( !s || !s.element )
return false;
s.action = 'delete-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce },
wpAjax.unserialize( cls[4] || '' )
);
if ( $.isFunction(s.delBefore) ) {
s = s.delBefore( s, list );
if ( !s )
return true;
}
if ( !s.data._ajax_nonce )
return true;
element = $('#' + s.element);
if ( 'none' != s.delColor ) {
element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
});
} else {
list.wpList.recolor();
$(list).trigger( 'wpListDelEnd', [ s, list.wpList ] );
}
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.delAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.delAfter( rres, _s );
}).dequeue();
}
}
$.ajax( s );
return false;
},
ajaxDim: function( e, s ) {
if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys
return false;
e = $(e);
s = s || {};
var list = this, cls = wpList.parseClass(e,'dim'), element, isClass, color, dimColor, res, rres;
s = wpList.pre.call( list, e, s, 'dim' );
s.element = cls[2] || s.element || null;
s.dimClass = cls[3] || s.dimClass || null;
if ( cls[4] )
s.dimAddColor = '#' + cls[4];
else
s.dimAddColor = s.dimAddColor || '#FFFF33';
if ( cls[5] )
s.dimDelColor = '#' + cls[5];
else
s.dimDelColor = s.dimDelColor || '#FF3333';
if ( !s || !s.element || !s.dimClass )
return true;
s.action = 'dim-' + s.what;
s.nonce = wpList.nonce(e,s);
s.data = $.extend(
{ action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce },
wpAjax.unserialize( cls[6] || '' )
);
if ( $.isFunction(s.dimBefore) ) {
s = s.dimBefore( s );
if ( !s )
return true;
}
element = $('#' + s.element);
isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass);
color = wpList.getColor( element );
element.toggleClass( s.dimClass );
dimColor = isClass ? s.dimAddColor : s.dimDelColor;
if ( 'none' != dimColor ) {
element
.animate( { backgroundColor: dimColor }, 'fast' )
.queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } )
.animate( { backgroundColor: color }, { complete: function() {
$(this).css( 'backgroundColor', '' );
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
});
} else {
$(list).trigger( 'wpListDimEnd', [ s, list.wpList ] );
}
if ( !s.data._ajax_nonce )
return true;
s.success = function(r) {
res = wpAjax.parseAjaxResponse(r, s.response, s.element);
rres = r;
if ( !res || res.errors ) {
element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } );
return false;
}
};
s.complete = function(x, st) {
if ( $.isFunction(s.dimAfter) ) {
element.queue( function() {
var _s = $.extend( { xml: x, status: st, parsed: res }, s );
s.dimAfter( rres, _s );
}).dequeue();
}
};
$.ajax( s );
return false;
},
getColor: function( el ) {
var color = jQuery(el).css('backgroundColor');
return color || '#ffffff';
},
add: function( e, s ) {
e = $(e);
var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color;
if ( 'string' == typeof s )
s = { what: s };
s = $.extend(_s, this.wpList.settings, s);
if ( !e.size() || !s.what )
return false;
if ( s.oldId )
old = $('#' + s.what + '-' + s.oldId);
if ( s.id && ( s.id != s.oldId || !old || !old.size() ) )
$('#' + s.what + '-' + s.id).remove();
if ( old && old.size() ) {
old.before(e);
old.remove();
} else if ( isNaN(s.pos) ) {
ba = 'after';
if ( '-' == s.pos.substr(0,1) ) {
s.pos = s.pos.substr(1);
ba = 'before';
}
ref = list.find( '#' + s.pos );
if ( 1 === ref.size() )
ref[ba](e);
else
list.append(e);
} else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) {
if ( s.pos < 0 ) {
list.prepend(e);
} else {
list.append(e);
}
}
if ( s.alt ) {
if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); }
else { e.addClass( s.alt ); }
}
if ( 'none' != s.addColor ) {
color = wpList.getColor( e );
e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } );
}
list.each( function() { this.wpList.process( e ); } );
return e;
},
clear: function(e) {
var list = this, t, tag;
e = $(e);
if ( list.wpList && e.parents( '#' + list.id ).size() )
return;
e.find(':input').each( function() {
if ( $(this).parents('.form-no-clear').size() )
return;
t = this.type.toLowerCase();
tag = this.tagName.toLowerCase();
if ( 'text' == t || 'password' == t || 'textarea' == tag )
this.value = '';
else if ( 'checkbox' == t || 'radio' == t )
this.checked = false;
else if ( 'select' == tag )
this.selectedIndex = null;
});
},
process: function(el) {
var list = this,
$el = $(el || document);
$el.delegate( 'form[class^="add:' + list.id + ':"]', 'submit', function(){
return list.wpList.add(this);
});
$el.delegate( 'a[class^="add:' + list.id + ':"], input[class^="add:' + list.id + ':"]', 'click', function(){
return list.wpList.add(this);
});
$el.delegate( '[class^="delete:' + list.id + ':"]', 'click', function(){
return list.wpList.del(this);
});
$el.delegate( '[class^="dim:' + list.id + ':"]', 'click', function(){
return list.wpList.dim(this);
});
},
recolor: function() {
var list = this, items, eo;
if ( !list.wpList.settings.alt )
return;
items = $('.list-item:visible', list);
if ( !items.size() )
items = $(list).children(':visible');
eo = [':even',':odd'];
if ( list.wpList.settings.altOffset % 2 )
eo.reverse();
items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt);
},
init: function() {
var lists = this;
lists.wpList.process = function(a) {
lists.each( function() {
this.wpList.process(a);
} );
};
lists.wpList.recolor = function() {
lists.each( function() {
this.wpList.recolor();
} );
};
}
};
$.fn.wpList = function( settings ) {
this.each( function() {
var _this = this;
this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseClass(this,'list')[1] || '' }, settings ) };
$.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } );
} );
wpList.init.call(this);
this.wpList.process();
return this;
};
})(jQuery);
| JavaScript |
// script.aculo.us unittest.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2009 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;";
this.mark.style.borderLeft = "1px solid red;";
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};
var Test = {};
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary');
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test";
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests";
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
};
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
};
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertInspect: function(expected, actual) {
var message = arguments[2] || "assertInspect";
try { (expected == actual.inspect()) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull';
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
};
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}
this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
var makeAssertion = function(assertion, args, object) {
this[assertion].apply(this,(args || []).concat([object]));
};
Test.BDDMethods = {};
$H(METHODMAP).each(function(pair) {
Test.BDDMethods[pair.key] = function() {
var args = $A(arguments);
var scope = args.shift();
makeAssertion.apply(scope, [pair.value, args, this]); };
});
[Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
};
Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
}; | JavaScript |
// script.aculo.us slider.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Marty Haught, Thomas Fuchs
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if (!Control) var Control = { };
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider = Class.create({
initialize: function(handle, track, options) {
var slider = this;
if (Object.isArray(handle)) {
this.handles = handle.collect( function(e) { return $(e) });
} else {
this.handles = [$(handle)];
}
this.track = $(track);
this.options = options || { };
this.axis = this.options.axis || 'horizontal';
this.increment = this.options.increment || 1;
this.step = parseInt(this.options.step || '1');
this.range = this.options.range || $R(0,1);
this.value = 0; // assure backwards compat
this.values = this.handles.map( function() { return 0 });
this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
this.options.startSpan = $(this.options.startSpan || null);
this.options.endSpan = $(this.options.endSpan || null);
this.restricted = this.options.restricted || false;
this.maximum = this.options.maximum || this.range.end;
this.minimum = this.options.minimum || this.range.start;
// Will be used to align the handle onto the track, if necessary
this.alignX = parseInt(this.options.alignX || '0');
this.alignY = parseInt(this.options.alignY || '0');
this.trackLength = this.maximumOffset() - this.minimumOffset();
this.handleLength = this.isVertical() ?
(this.handles[0].offsetHeight != 0 ?
this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
(this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
this.handles[0].style.width.replace(/px$/,""));
this.active = false;
this.dragging = false;
this.disabled = false;
if (this.options.disabled) this.setDisabled();
// Allowed values array
this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
if (this.allowedValues) {
this.minimum = this.allowedValues.min();
this.maximum = this.allowedValues.max();
}
this.eventMouseDown = this.startDrag.bindAsEventListener(this);
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.update.bindAsEventListener(this);
// Initialize handles in reverse (make sure first handle is active)
this.handles.each( function(h,i) {
i = slider.handles.length-1-i;
slider.setValue(parseFloat(
(Object.isArray(slider.options.sliderValue) ?
slider.options.sliderValue[i] : slider.options.sliderValue) ||
slider.range.start), i);
h.makePositioned().observe("mousedown", slider.eventMouseDown);
});
this.track.observe("mousedown", this.eventMouseDown);
document.observe("mouseup", this.eventMouseUp);
document.observe("mousemove", this.eventMouseMove);
this.initialized = true;
},
dispose: function() {
var slider = this;
Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
this.handles.each( function(h) {
Event.stopObserving(h, "mousedown", slider.eventMouseDown);
});
},
setDisabled: function(){
this.disabled = true;
},
setEnabled: function(){
this.disabled = false;
},
getNearestValue: function(value){
if (this.allowedValues){
if (value >= this.allowedValues.max()) return(this.allowedValues.max());
if (value <= this.allowedValues.min()) return(this.allowedValues.min());
var offset = Math.abs(this.allowedValues[0] - value);
var newValue = this.allowedValues[0];
this.allowedValues.each( function(v) {
var currentOffset = Math.abs(v - value);
if (currentOffset <= offset){
newValue = v;
offset = currentOffset;
}
});
return newValue;
}
if (value > this.range.end) return this.range.end;
if (value < this.range.start) return this.range.start;
return value;
},
setValue: function(sliderValue, handleIdx){
if (!this.active) {
this.activeHandleIdx = handleIdx || 0;
this.activeHandle = this.handles[this.activeHandleIdx];
this.updateStyles();
}
handleIdx = handleIdx || this.activeHandleIdx || 0;
if (this.initialized && this.restricted) {
if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
sliderValue = this.values[handleIdx-1];
if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
sliderValue = this.values[handleIdx+1];
}
sliderValue = this.getNearestValue(sliderValue);
this.values[handleIdx] = sliderValue;
this.value = this.values[0]; // assure backwards compat
this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] =
this.translateToPx(sliderValue);
this.drawSpans();
if (!this.dragging || !this.event) this.updateFinished();
},
setValueBy: function(delta, handleIdx) {
this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta,
handleIdx || this.activeHandleIdx || 0);
},
translateToPx: function(value) {
return Math.round(
((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) *
(value - this.range.start)) + "px";
},
translateToValue: function(offset) {
return ((offset/(this.trackLength-this.handleLength) *
(this.range.end-this.range.start)) + this.range.start);
},
getRange: function(range) {
var v = this.values.sortBy(Prototype.K);
range = range || 0;
return $R(v[range],v[range+1]);
},
minimumOffset: function(){
return(this.isVertical() ? this.alignY : this.alignX);
},
maximumOffset: function(){
return(this.isVertical() ?
(this.track.offsetHeight != 0 ? this.track.offsetHeight :
this.track.style.height.replace(/px$/,"")) - this.alignY :
(this.track.offsetWidth != 0 ? this.track.offsetWidth :
this.track.style.width.replace(/px$/,"")) - this.alignX);
},
isVertical: function(){
return (this.axis == 'vertical');
},
drawSpans: function() {
var slider = this;
if (this.spans)
$R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
if (this.options.startSpan)
this.setSpan(this.options.startSpan,
$R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
if (this.options.endSpan)
this.setSpan(this.options.endSpan,
$R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
},
setSpan: function(span, range) {
if (this.isVertical()) {
span.style.top = this.translateToPx(range.start);
span.style.height = this.translateToPx(range.end - range.start + this.range.start);
} else {
span.style.left = this.translateToPx(range.start);
span.style.width = this.translateToPx(range.end - range.start + this.range.start);
}
},
updateStyles: function() {
this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
Element.addClassName(this.activeHandle, 'selected');
},
startDrag: function(event) {
if (Event.isLeftClick(event)) {
if (!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if (track==this.track) {
var offsets = this.track.cumulativeOffset();
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
if (this.handles.indexOf(handle)!=-1) {
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = this.activeHandle.cumulativeOffset();
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
}
Event.stop(event);
}
},
update: function(event) {
if (this.active) {
if (!this.dragging) this.dragging = true;
this.draw(event);
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var offsets = this.track.cumulativeOffset();
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if (this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
endDrag: function(event) {
if (this.active && this.dragging) {
this.finishDrag(event, true);
Event.stop(event);
}
this.active = false;
this.dragging = false;
},
finishDrag: function(event, success) {
this.active = false;
this.dragging = false;
this.updateFinished();
},
updateFinished: function() {
if (this.initialized && this.options.onChange)
this.options.onChange(this.values.length>1 ? this.values : this.value, this);
this.event = null;
}
}); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.