code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts for the fck_select.html page. */ function Select( combo ) { var iIndex = combo.selectedIndex ; oListText.selectedIndex = iIndex ; oListValue.selectedIndex = iIndex ; var oTxtText = document.getElementById( "txtText" ) ; var oTxtValue = document.getElementById( "txtValue" ) ; oTxtText.value = oListText.value ; oTxtValue.value = oListValue.value ; } function Add() { var oTxtText = document.getElementById( "txtText" ) ; var oTxtValue = document.getElementById( "txtValue" ) ; AddComboOption( oListText, oTxtText.value, oTxtText.value ) ; AddComboOption( oListValue, oTxtValue.value, oTxtValue.value ) ; oListText.selectedIndex = oListText.options.length - 1 ; oListValue.selectedIndex = oListValue.options.length - 1 ; oTxtText.value = '' ; oTxtValue.value = '' ; oTxtText.focus() ; } function Modify() { var iIndex = oListText.selectedIndex ; if ( iIndex < 0 ) return ; var oTxtText = document.getElementById( "txtText" ) ; var oTxtValue = document.getElementById( "txtValue" ) ; oListText.options[ iIndex ].innerHTML = HTMLEncode( oTxtText.value ) ; oListText.options[ iIndex ].value = oTxtText.value ; oListValue.options[ iIndex ].innerHTML = HTMLEncode( oTxtValue.value ) ; oListValue.options[ iIndex ].value = oTxtValue.value ; oTxtText.value = '' ; oTxtValue.value = '' ; oTxtText.focus() ; } function Move( steps ) { ChangeOptionPosition( oListText, steps ) ; ChangeOptionPosition( oListValue, steps ) ; } function Delete() { RemoveSelectedOptions( oListText ) ; RemoveSelectedOptions( oListValue ) ; } function SetSelectedValue() { var iIndex = oListValue.selectedIndex ; if ( iIndex < 0 ) return ; var oTxtValue = document.getElementById( "txtSelValue" ) ; oTxtValue.value = oListValue.options[ iIndex ].value ; } // Moves the selected option by a number of steps (also negative) function ChangeOptionPosition( combo, steps ) { var iActualIndex = combo.selectedIndex ; if ( iActualIndex < 0 ) return ; var iFinalIndex = iActualIndex + steps ; if ( iFinalIndex < 0 ) iFinalIndex = 0 ; if ( iFinalIndex > ( combo.options.length - 1 ) ) iFinalIndex = combo.options.length - 1 ; if ( iActualIndex == iFinalIndex ) return ; var oOption = combo.options[ iActualIndex ] ; var sText = HTMLDecode( oOption.innerHTML ) ; var sValue = oOption.value ; combo.remove( iActualIndex ) ; oOption = AddComboOption( combo, sText, sValue, null, iFinalIndex ) ; oOption.selected = true ; } // Remove all selected options from a SELECT object function RemoveSelectedOptions(combo) { // Save the selected index var iSelectedIndex = combo.selectedIndex ; var oOptions = combo.options ; // Remove all selected options for ( var i = oOptions.length - 1 ; i >= 0 ; i-- ) { if (oOptions[i].selected) combo.remove(i) ; } // Reset the selection based on the original selected index if ( combo.options.length > 0 ) { if ( iSelectedIndex >= combo.options.length ) iSelectedIndex = combo.options.length - 1 ; combo.selectedIndex = iSelectedIndex ; } } // Add a new option to a SELECT object (combo or list) function AddComboOption( combo, optionText, optionValue, documentObject, index ) { var oOption ; if ( documentObject ) oOption = documentObject.createElement("OPTION") ; else oOption = document.createElement("OPTION") ; if ( index != null ) combo.options.add( oOption, index ) ; else combo.options.add( oOption ) ; oOption.innerHTML = optionText.length > 0 ? HTMLEncode( optionText ) : '&nbsp;' ; oOption.value = optionValue ; return oOption ; } function HTMLEncode( text ) { if ( !text ) return '' ; text = text.replace( /&/g, '&amp;' ) ; text = text.replace( /</g, '&lt;' ) ; text = text.replace( />/g, '&gt;' ) ; return text ; } function HTMLDecode( text ) { if ( !text ) return '' ; text = text.replace( /&gt;/g, '>' ) ; text = text.replace( /&lt;/g, '<' ) ; text = text.replace( /&amp;/g, '&' ) ; return text ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Link dialog window (see fck_link.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKRegexLib = oEditor.FCKRegexLib ; var FCKTools = oEditor.FCKTools ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', FCKLang.DlgLnkInfoTab ) ; if ( !FCKConfig.LinkDlgHideTarget ) dialog.AddTab( 'Target', FCKLang.DlgLnkTargetTab, true ) ; if ( FCKConfig.LinkUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload, true ) ; if ( !FCKConfig.LinkDlgHideAdvanced ) dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divTarget' , ( tabCode == 'Target' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAttribs' , ( tabCode == 'Advanced' ) ) ; dialog.SetAutoSize( true ) ; } //#### Regular Expressions library. var oRegex = new Object() ; oRegex.UriProtocol = /^(((http|https|ftp|news):\/\/)|mailto:)/gi ; oRegex.UrlOnChangeProtocol = /^(http|https|ftp|news):\/\/(?=.)/gi ; oRegex.UrlOnChangeTestOther = /^((javascript:)|[#\/\.])/gi ; oRegex.ReserveTarget = /^_(blank|self|top|parent)$/i ; oRegex.PopupUri = /^javascript:void\(\s*window.open\(\s*'([^']+)'\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*\)\s*$/ ; // Accessible popups oRegex.OnClickPopup = /^\s*on[cC]lick="\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*"$/ ; oRegex.PopupFeatures = /(?:^|,)([^=]+)=(\d+|yes|no)/gi ; //#### Parser Functions var oParser = new Object() ; // This method simply returns the two inputs in numerical order. You can even // provide strings, as the method would parseInt() the values. oParser.SortNumerical = function(a, b) { return parseInt( a, 10 ) - parseInt( b, 10 ) ; } oParser.ParseEMailParams = function(sParams) { // Initialize the oEMailParams object. var oEMailParams = new Object() ; oEMailParams.Subject = '' ; oEMailParams.Body = '' ; var aMatch = sParams.match( /(^|^\?|&)subject=([^&]+)/i ) ; if ( aMatch ) oEMailParams.Subject = decodeURIComponent( aMatch[2] ) ; aMatch = sParams.match( /(^|^\?|&)body=([^&]+)/i ) ; if ( aMatch ) oEMailParams.Body = decodeURIComponent( aMatch[2] ) ; return oEMailParams ; } // This method returns either an object containing the email info, or FALSE // if the parameter is not an email link. oParser.ParseEMailUri = function( sUrl ) { // Initializes the EMailInfo object. var oEMailInfo = new Object() ; oEMailInfo.Address = '' ; oEMailInfo.Subject = '' ; oEMailInfo.Body = '' ; var aLinkInfo = sUrl.match( /^(\w+):(.*)$/ ) ; if ( aLinkInfo && aLinkInfo[1] == 'mailto' ) { // This seems to be an unprotected email link. var aParts = aLinkInfo[2].match( /^([^\?]+)\??(.+)?/ ) ; if ( aParts ) { // Set the e-mail address. oEMailInfo.Address = aParts[1] ; // Look for the optional e-mail parameters. if ( aParts[2] ) { var oEMailParams = oParser.ParseEMailParams( aParts[2] ) ; oEMailInfo.Subject = oEMailParams.Subject ; oEMailInfo.Body = oEMailParams.Body ; } } return oEMailInfo ; } else if ( aLinkInfo && aLinkInfo[1] == 'javascript' ) { // This may be a protected email. // Try to match the url against the EMailProtectionFunction. var func = FCKConfig.EMailProtectionFunction ; if ( func != null ) { try { // Escape special chars. func = func.replace( /([\/^$*+.?()\[\]])/g, '\\$1' ) ; // Define the possible keys. var keys = new Array('NAME', 'DOMAIN', 'SUBJECT', 'BODY') ; // Get the order of the keys (hold them in the array <pos>) and // the function replaced by regular expression patterns. var sFunc = func ; var pos = new Array() ; for ( var i = 0 ; i < keys.length ; i ++ ) { var rexp = new RegExp( keys[i] ) ; var p = func.search( rexp ) ; if ( p >= 0 ) { sFunc = sFunc.replace( rexp, '\'([^\']*)\'' ) ; pos[pos.length] = p + ':' + keys[i] ; } } // Sort the available keys. pos.sort( oParser.SortNumerical ) ; // Replace the excaped single quotes in the url, such they do // not affect the regexp afterwards. aLinkInfo[2] = aLinkInfo[2].replace( /\\'/g, '###SINGLE_QUOTE###' ) ; // Create the regexp and execute it. var rFunc = new RegExp( '^' + sFunc + '$' ) ; var aMatch = rFunc.exec( aLinkInfo[2] ) ; if ( aMatch ) { var aInfo = new Array(); for ( var i = 1 ; i < aMatch.length ; i ++ ) { var k = pos[i-1].match(/^\d+:(.+)$/) ; aInfo[k[1]] = aMatch[i].replace(/###SINGLE_QUOTE###/g, '\'') ; } // Fill the EMailInfo object that will be returned oEMailInfo.Address = aInfo['NAME'] + '@' + aInfo['DOMAIN'] ; oEMailInfo.Subject = decodeURIComponent( aInfo['SUBJECT'] ) ; oEMailInfo.Body = decodeURIComponent( aInfo['BODY'] ) ; return oEMailInfo ; } } catch (e) { } } // Try to match the email against the encode protection. var aMatch = aLinkInfo[2].match( /^(?:void\()?location\.href='mailto:'\+(String\.fromCharCode\([\d,]+\))\+'(.*)'\)?$/ ) ; if ( aMatch ) { // The link is encoded oEMailInfo.Address = eval( aMatch[1] ) ; if ( aMatch[2] ) { var oEMailParams = oParser.ParseEMailParams( aMatch[2] ) ; oEMailInfo.Subject = oEMailParams.Subject ; oEMailInfo.Body = oEMailParams.Body ; } return oEMailInfo ; } } return false; } oParser.CreateEMailUri = function( address, subject, body ) { // Switch for the EMailProtection setting. switch ( FCKConfig.EMailProtection ) { case 'function' : var func = FCKConfig.EMailProtectionFunction ; if ( func == null ) { if ( FCKConfig.Debug ) { alert('EMailProtection alert!\nNo function defined. Please set "FCKConfig.EMailProtectionFunction"') ; } return ''; } // Split the email address into name and domain parts. var aAddressParts = address.split( '@', 2 ) ; if ( aAddressParts[1] == undefined ) { aAddressParts[1] = '' ; } // Replace the keys by their values (embedded in single quotes). func = func.replace(/NAME/g, "'" + aAddressParts[0].replace(/'/g, '\\\'') + "'") ; func = func.replace(/DOMAIN/g, "'" + aAddressParts[1].replace(/'/g, '\\\'') + "'") ; func = func.replace(/SUBJECT/g, "'" + encodeURIComponent( subject ).replace(/'/g, '\\\'') + "'") ; func = func.replace(/BODY/g, "'" + encodeURIComponent( body ).replace(/'/g, '\\\'') + "'") ; return 'javascript:' + func ; case 'encode' : var aParams = [] ; var aAddressCode = [] ; if ( subject.length > 0 ) aParams.push( 'subject='+ encodeURIComponent( subject ) ) ; if ( body.length > 0 ) aParams.push( 'body=' + encodeURIComponent( body ) ) ; for ( var i = 0 ; i < address.length ; i++ ) aAddressCode.push( address.charCodeAt( i ) ) ; return 'javascript:void(location.href=\'mailto:\'+String.fromCharCode(' + aAddressCode.join( ',' ) + ')+\'?' + aParams.join( '&' ) + '\')' ; } // EMailProtection 'none' var sBaseUri = 'mailto:' + address ; var sParams = '' ; if ( subject.length > 0 ) sParams = '?subject=' + encodeURIComponent( subject ) ; if ( body.length > 0 ) { sParams += ( sParams.length == 0 ? '?' : '&' ) ; sParams += 'body=' + encodeURIComponent( body ) ; } return sBaseUri + sParams ; } //#### Initialization Code // oLink: The actual selected link in the editor. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; if ( oLink ) FCK.Selection.SelectNode( oLink ) ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Fill the Anchor Names and Ids combos. LoadAnchorNamesAndIds() ; // Load the selected link information (if any). LoadSelection() ; // Update the dialog box. SetLinkType( GetE('cmbLinkType').value ) ; // Show/Hide the "Browse Server" button. GetE('divBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ; // Show the initial dialog content. GetE('divInfo').style.display = '' ; // Set the actual uploader URL. if ( FCKConfig.LinkUpload ) GetE('frmUpload').action = FCKConfig.LinkUploadURL ; // Set the default target (from configuration). SetDefaultTarget() ; // Activate the "OK" button. dialog.SetOkButton( true ) ; // Select the first field. switch( GetE('cmbLinkType').value ) { case 'url' : SelectField( 'txtUrl' ) ; break ; case 'email' : SelectField( 'txtEMailAddress' ) ; break ; case 'anchor' : if ( GetE('divSelAnchor').style.display != 'none' ) SelectField( 'cmbAnchorName' ) ; else SelectField( 'cmbLinkType' ) ; } } var bHasAnchors ; function LoadAnchorNamesAndIds() { // Since version 2.0, the anchors are replaced in the DOM by IMGs so the user see the icon // to edit them. So, we must look for that images now. var aAnchors = new Array() ; var i ; var oImages = oEditor.FCK.EditorDocument.getElementsByTagName( 'IMG' ) ; for( i = 0 ; i < oImages.length ; i++ ) { if ( oImages[i].getAttribute('_fckanchor') ) aAnchors[ aAnchors.length ] = oEditor.FCK.GetRealElement( oImages[i] ) ; } // Add also real anchors var oLinks = oEditor.FCK.EditorDocument.getElementsByTagName( 'A' ) ; for( i = 0 ; i < oLinks.length ; i++ ) { if ( oLinks[i].name && ( oLinks[i].name.length > 0 ) ) aAnchors[ aAnchors.length ] = oLinks[i] ; } var aIds = FCKTools.GetAllChildrenIds( oEditor.FCK.EditorDocument.body ) ; bHasAnchors = ( aAnchors.length > 0 || aIds.length > 0 ) ; for ( i = 0 ; i < aAnchors.length ; i++ ) { var sName = aAnchors[i].name ; if ( sName && sName.length > 0 ) FCKTools.AddSelectOption( GetE('cmbAnchorName'), sName, sName ) ; } for ( i = 0 ; i < aIds.length ; i++ ) { FCKTools.AddSelectOption( GetE('cmbAnchorId'), aIds[i], aIds[i] ) ; } ShowE( 'divSelAnchor' , bHasAnchors ) ; ShowE( 'divNoAnchor' , !bHasAnchors ) ; } function LoadSelection() { if ( !oLink ) return ; var sType = 'url' ; // Get the actual Link href. var sHRef = oLink.getAttribute( '_fcksavedurl' ) ; if ( sHRef == null ) sHRef = oLink.getAttribute( 'href' , 2 ) || '' ; // Look for a popup javascript link. var oPopupMatch = oRegex.PopupUri.exec( sHRef ) ; if( oPopupMatch ) { GetE('cmbTarget').value = 'popup' ; sHRef = oPopupMatch[1] ; FillPopupFields( oPopupMatch[2], oPopupMatch[3] ) ; SetTarget( 'popup' ) ; } // Accessible popups, the popup data is in the onclick attribute if ( !oPopupMatch ) { var onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ; if ( onclick ) { // Decode the protected string onclick = decodeURIComponent( onclick ) ; oPopupMatch = oRegex.OnClickPopup.exec( onclick ) ; if( oPopupMatch ) { GetE( 'cmbTarget' ).value = 'popup' ; FillPopupFields( oPopupMatch[1], oPopupMatch[2] ) ; SetTarget( 'popup' ) ; } } } // Search for the protocol. var sProtocol = oRegex.UriProtocol.exec( sHRef ) ; // Search for a protected email link. var oEMailInfo = oParser.ParseEMailUri( sHRef ); if ( oEMailInfo ) { sType = 'email' ; GetE('txtEMailAddress').value = oEMailInfo.Address ; GetE('txtEMailSubject').value = oEMailInfo.Subject ; GetE('txtEMailBody').value = oEMailInfo.Body ; } else if ( sProtocol ) { sProtocol = sProtocol[0].toLowerCase() ; GetE('cmbLinkProtocol').value = sProtocol ; // Remove the protocol and get the remaining URL. var sUrl = sHRef.replace( oRegex.UriProtocol, '' ) ; sType = 'url' ; GetE('txtUrl').value = sUrl ; } else if ( sHRef.substr(0,1) == '#' && sHRef.length > 1 ) // It is an anchor link. { sType = 'anchor' ; GetE('cmbAnchorName').value = GetE('cmbAnchorId').value = sHRef.substr(1) ; } else // It is another type of link. { sType = 'url' ; GetE('cmbLinkProtocol').value = '' ; GetE('txtUrl').value = sHRef ; } if ( !oPopupMatch ) { // Get the target. var sTarget = oLink.target ; if ( sTarget && sTarget.length > 0 ) { if ( oRegex.ReserveTarget.test( sTarget ) ) { sTarget = sTarget.toLowerCase() ; GetE('cmbTarget').value = sTarget ; } else GetE('cmbTarget').value = 'frame' ; GetE('txtTargetFrame').value = sTarget ; } } // Get Advances Attributes GetE('txtAttId').value = oLink.id ; GetE('txtAttName').value = oLink.name ; GetE('cmbAttLangDir').value = oLink.dir ; GetE('txtAttLangCode').value = oLink.lang ; GetE('txtAttAccessKey').value = oLink.accessKey ; GetE('txtAttTabIndex').value = oLink.tabIndex <= 0 ? '' : oLink.tabIndex ; GetE('txtAttTitle').value = oLink.title ; GetE('txtAttContentType').value = oLink.type ; GetE('txtAttCharSet').value = oLink.charset ; var sClass ; if ( oEditor.FCKBrowserInfo.IsIE ) { sClass = oLink.getAttribute('className',2) || '' ; // Clean up temporary classes for internal use: sClass = sClass.replace( FCKRegexLib.FCK_Class, '' ) ; GetE('txtAttStyle').value = oLink.style.cssText ; } else { sClass = oLink.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oLink.getAttribute('style',2) || '' ; } GetE('txtAttClasses').value = sClass ; // Update the Link type combo. GetE('cmbLinkType').value = sType ; } //#### Link type selection. function SetLinkType( linkType ) { ShowE('divLinkTypeUrl' , (linkType == 'url') ) ; ShowE('divLinkTypeAnchor' , (linkType == 'anchor') ) ; ShowE('divLinkTypeEMail' , (linkType == 'email') ) ; if ( !FCKConfig.LinkDlgHideTarget ) dialog.SetTabVisibility( 'Target' , (linkType == 'url') ) ; if ( FCKConfig.LinkUpload ) dialog.SetTabVisibility( 'Upload' , (linkType == 'url') ) ; if ( !FCKConfig.LinkDlgHideAdvanced ) dialog.SetTabVisibility( 'Advanced' , (linkType != 'anchor' || bHasAnchors) ) ; if ( linkType == 'email' ) dialog.SetAutoSize( true ) ; } //#### Target type selection. function SetTarget( targetType ) { GetE('tdTargetFrame').style.display = ( targetType == 'popup' ? 'none' : '' ) ; GetE('tdPopupName').style.display = GetE('tablePopupFeatures').style.display = ( targetType == 'popup' ? '' : 'none' ) ; switch ( targetType ) { case "_blank" : case "_self" : case "_parent" : case "_top" : GetE('txtTargetFrame').value = targetType ; break ; case "" : GetE('txtTargetFrame').value = '' ; break ; } if ( targetType == 'popup' ) dialog.SetAutoSize( true ) ; } //#### Called while the user types the URL. function OnUrlChange() { var sUrl = GetE('txtUrl').value ; var sProtocol = oRegex.UrlOnChangeProtocol.exec( sUrl ) ; if ( sProtocol ) { sUrl = sUrl.substr( sProtocol[0].length ) ; GetE('txtUrl').value = sUrl ; GetE('cmbLinkProtocol').value = sProtocol[0].toLowerCase() ; } else if ( oRegex.UrlOnChangeTestOther.test( sUrl ) ) { GetE('cmbLinkProtocol').value = '' ; } } //#### Called while the user types the target name. function OnTargetNameChange() { var sFrame = GetE('txtTargetFrame').value ; if ( sFrame.length == 0 ) GetE('cmbTarget').value = '' ; else if ( oRegex.ReserveTarget.test( sFrame ) ) GetE('cmbTarget').value = sFrame.toLowerCase() ; else GetE('cmbTarget').value = 'frame' ; } // Accessible popups function BuildOnClickPopup() { var sWindowName = "'" + GetE('txtPopupName').value.replace(/\W/gi, "") + "'" ; var sFeatures = '' ; var aChkFeatures = document.getElementsByName( 'chkFeature' ) ; for ( var i = 0 ; i < aChkFeatures.length ; i++ ) { if ( i > 0 ) sFeatures += ',' ; sFeatures += aChkFeatures[i].value + '=' + ( aChkFeatures[i].checked ? 'yes' : 'no' ) ; } if ( GetE('txtPopupWidth').value.length > 0 ) sFeatures += ',width=' + GetE('txtPopupWidth').value ; if ( GetE('txtPopupHeight').value.length > 0 ) sFeatures += ',height=' + GetE('txtPopupHeight').value ; if ( GetE('txtPopupLeft').value.length > 0 ) sFeatures += ',left=' + GetE('txtPopupLeft').value ; if ( GetE('txtPopupTop').value.length > 0 ) sFeatures += ',top=' + GetE('txtPopupTop').value ; if ( sFeatures != '' ) sFeatures = sFeatures + ",status" ; return ( "window.open(this.href," + sWindowName + ",'" + sFeatures + "'); return false" ) ; } //#### Fills all Popup related fields. function FillPopupFields( windowName, features ) { if ( windowName ) GetE('txtPopupName').value = windowName ; var oFeatures = new Object() ; var oFeaturesMatch ; while( ( oFeaturesMatch = oRegex.PopupFeatures.exec( features ) ) != null ) { var sValue = oFeaturesMatch[2] ; if ( sValue == ( 'yes' || '1' ) ) oFeatures[ oFeaturesMatch[1] ] = true ; else if ( ! isNaN( sValue ) && sValue != 0 ) oFeatures[ oFeaturesMatch[1] ] = sValue ; } // Update all features check boxes. var aChkFeatures = document.getElementsByName('chkFeature') ; for ( var i = 0 ; i < aChkFeatures.length ; i++ ) { if ( oFeatures[ aChkFeatures[i].value ] ) aChkFeatures[i].checked = true ; } // Update position and size text boxes. if ( oFeatures['width'] ) GetE('txtPopupWidth').value = oFeatures['width'] ; if ( oFeatures['height'] ) GetE('txtPopupHeight').value = oFeatures['height'] ; if ( oFeatures['left'] ) GetE('txtPopupLeft').value = oFeatures['left'] ; if ( oFeatures['top'] ) GetE('txtPopupTop').value = oFeatures['top'] ; } //#### The OK button was hit. function Ok() { var sUri, sInnerHtml ; oEditor.FCKUndo.SaveUndoStep() ; switch ( GetE('cmbLinkType').value ) { case 'url' : sUri = GetE('txtUrl').value ; if ( sUri.length == 0 ) { alert( FCKLang.DlnLnkMsgNoUrl ) ; return false ; } sUri = GetE('cmbLinkProtocol').value + sUri ; break ; case 'email' : sUri = GetE('txtEMailAddress').value ; if ( sUri.length == 0 ) { alert( FCKLang.DlnLnkMsgNoEMail ) ; return false ; } sUri = oParser.CreateEMailUri( sUri, GetE('txtEMailSubject').value, GetE('txtEMailBody').value ) ; break ; case 'anchor' : var sAnchor = GetE('cmbAnchorName').value ; if ( sAnchor.length == 0 ) sAnchor = GetE('cmbAnchorId').value ; if ( sAnchor.length == 0 ) { alert( FCKLang.DlnLnkMsgNoAnchor ) ; return false ; } sUri = '#' + sAnchor ; break ; } // If no link is selected, create a new one (it may result in more than one link creation - #220). var aLinks = oLink ? [ oLink ] : oEditor.FCK.CreateLink( sUri, true ) ; // If no selection, no links are created, so use the uri as the link text (by dom, 2006-05-26) var aHasSelection = ( aLinks.length > 0 ) ; if ( !aHasSelection ) { sInnerHtml = sUri; // Built a better text for empty links. switch ( GetE('cmbLinkType').value ) { // anchor: use old behavior --> return true case 'anchor': sInnerHtml = sInnerHtml.replace( /^#/, '' ) ; break ; // url: try to get path case 'url': var oLinkPathRegEx = new RegExp("//?([^?\"']+)([?].*)?$") ; var asLinkPath = oLinkPathRegEx.exec( sUri ) ; if (asLinkPath != null) sInnerHtml = asLinkPath[1]; // use matched path break ; // mailto: try to get email address case 'email': sInnerHtml = GetE('txtEMailAddress').value ; break ; } // Create a new (empty) anchor. aLinks = [ oEditor.FCK.InsertElement( 'a' ) ] ; } for ( var i = 0 ; i < aLinks.length ; i++ ) { oLink = aLinks[i] ; if ( aHasSelection ) sInnerHtml = oLink.innerHTML ; // Save the innerHTML (IE changes it if it is like an URL). oLink.href = sUri ; SetAttribute( oLink, '_fcksavedurl', sUri ) ; var onclick; // Accessible popups if( GetE('cmbTarget').value == 'popup' ) { onclick = BuildOnClickPopup() ; // Encode the attribute onclick = encodeURIComponent( " onclick=\"" + onclick + "\"" ) ; SetAttribute( oLink, 'onclick_fckprotectedatt', onclick ) ; } else { // Check if the previous onclick was for a popup: // In that case remove the onclick handler. onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ; if ( onclick ) { // Decode the protected string onclick = decodeURIComponent( onclick ) ; if( oRegex.OnClickPopup.test( onclick ) ) SetAttribute( oLink, 'onclick_fckprotectedatt', '' ) ; } } oLink.innerHTML = sInnerHtml ; // Set (or restore) the innerHTML // Target if( GetE('cmbTarget').value != 'popup' ) SetAttribute( oLink, 'target', GetE('txtTargetFrame').value ) ; else SetAttribute( oLink, 'target', null ) ; // Let's set the "id" only for the first link to avoid duplication. if ( i == 0 ) SetAttribute( oLink, 'id', GetE('txtAttId').value ) ; // Advances Attributes SetAttribute( oLink, 'name' , GetE('txtAttName').value ) ; SetAttribute( oLink, 'dir' , GetE('cmbAttLangDir').value ) ; SetAttribute( oLink, 'lang' , GetE('txtAttLangCode').value ) ; SetAttribute( oLink, 'accesskey', GetE('txtAttAccessKey').value ) ; SetAttribute( oLink, 'tabindex' , ( GetE('txtAttTabIndex').value > 0 ? GetE('txtAttTabIndex').value : null ) ) ; SetAttribute( oLink, 'title' , GetE('txtAttTitle').value ) ; SetAttribute( oLink, 'type' , GetE('txtAttContentType').value ) ; SetAttribute( oLink, 'charset' , GetE('txtAttCharSet').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { var sClass = GetE('txtAttClasses').value ; // If it's also an anchor add an internal class if ( GetE('txtAttName').value.length != 0 ) sClass += ' FCK__AnchorC' ; SetAttribute( oLink, 'className', sClass ) ; oLink.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( oLink, 'class', GetE('txtAttClasses').value ) ; SetAttribute( oLink, 'style', GetE('txtAttStyle').value ) ; } } // Select the (first) link. oEditor.FCKSelection.SelectNode( aLinks[0] ); return true ; } function BrowseServer() { OpenFileBrowser( FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ; } function SetUrl( url ) { GetE('txtUrl').value = url ; OnUrlChange() ; dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.LinkUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.LinkUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.LinkUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.LinkUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; } function SetDefaultTarget() { var target = FCKConfig.DefaultLinkTarget || '' ; if ( oLink || target.length == 0 ) return ; switch ( target ) { case '_blank' : case '_self' : case '_parent' : case '_top' : GetE('cmbTarget').value = target ; break ; default : GetE('cmbTarget').value = 'frame' ; break ; } GetE('txtTargetFrame').value = target ; }
JavaScript
//////////////////////////////////////////////////// // wordWindow object //////////////////////////////////////////////////// function wordWindow() { // private properties this._forms = []; // private methods this._getWordObject = _getWordObject; //this._getSpellerObject = _getSpellerObject; this._wordInputStr = _wordInputStr; this._adjustIndexes = _adjustIndexes; this._isWordChar = _isWordChar; this._lastPos = _lastPos; // public properties this.wordChar = /[a-zA-Z]/; this.windowType = "wordWindow"; this.originalSpellings = new Array(); this.suggestions = new Array(); this.checkWordBgColor = "pink"; this.normWordBgColor = "white"; this.text = ""; this.textInputs = new Array(); this.indexes = new Array(); //this.speller = this._getSpellerObject(); // public methods this.resetForm = resetForm; this.totalMisspellings = totalMisspellings; this.totalWords = totalWords; this.totalPreviousWords = totalPreviousWords; //this.getTextObjectArray = getTextObjectArray; this.getTextVal = getTextVal; this.setFocus = setFocus; this.removeFocus = removeFocus; this.setText = setText; //this.getTotalWords = getTotalWords; this.writeBody = writeBody; this.printForHtml = printForHtml; } function resetForm() { if( this._forms ) { for( var i = 0; i < this._forms.length; i++ ) { this._forms[i].reset(); } } return true; } function totalMisspellings() { var total_words = 0; for( var i = 0; i < this.textInputs.length; i++ ) { total_words += this.totalWords( i ); } return total_words; } function totalWords( textIndex ) { return this.originalSpellings[textIndex].length; } function totalPreviousWords( textIndex, wordIndex ) { var total_words = 0; for( var i = 0; i <= textIndex; i++ ) { for( var j = 0; j < this.totalWords( i ); j++ ) { if( i == textIndex && j == wordIndex ) { break; } else { total_words++; } } } return total_words; } //function getTextObjectArray() { // return this._form.elements; //} function getTextVal( textIndex, wordIndex ) { var word = this._getWordObject( textIndex, wordIndex ); if( word ) { return word.value; } } function setFocus( textIndex, wordIndex ) { var word = this._getWordObject( textIndex, wordIndex ); if( word ) { if( word.type == "text" ) { word.focus(); word.style.backgroundColor = this.checkWordBgColor; } } } function removeFocus( textIndex, wordIndex ) { var word = this._getWordObject( textIndex, wordIndex ); if( word ) { if( word.type == "text" ) { word.blur(); word.style.backgroundColor = this.normWordBgColor; } } } function setText( textIndex, wordIndex, newText ) { var word = this._getWordObject( textIndex, wordIndex ); var beginStr; var endStr; if( word ) { var pos = this.indexes[textIndex][wordIndex]; var oldText = word.value; // update the text given the index of the string beginStr = this.textInputs[textIndex].substring( 0, pos ); endStr = this.textInputs[textIndex].substring( pos + oldText.length, this.textInputs[textIndex].length ); this.textInputs[textIndex] = beginStr + newText + endStr; // adjust the indexes on the stack given the differences in // length between the new word and old word. var lengthDiff = newText.length - oldText.length; this._adjustIndexes( textIndex, wordIndex, lengthDiff ); word.size = newText.length; word.value = newText; this.removeFocus( textIndex, wordIndex ); } } function writeBody() { var d = window.document; var is_html = false; d.open(); // iterate through each text input. for( var txtid = 0; txtid < this.textInputs.length; txtid++ ) { var end_idx = 0; var begin_idx = 0; d.writeln( '<form name="textInput'+txtid+'">' ); var wordtxt = this.textInputs[txtid]; this.indexes[txtid] = []; if( wordtxt ) { var orig = this.originalSpellings[txtid]; if( !orig ) break; //!!! plain text, or HTML mode? d.writeln( '<div class="plainText">' ); // iterate through each occurrence of a misspelled word. for( var i = 0; i < orig.length; i++ ) { // find the position of the current misspelled word, // starting at the last misspelled word. // and keep looking if it's a substring of another word do { begin_idx = wordtxt.indexOf( orig[i], end_idx ); end_idx = begin_idx + orig[i].length; // word not found? messed up! if( begin_idx == -1 ) break; // look at the characters immediately before and after // the word. If they are word characters we'll keep looking. var before_char = wordtxt.charAt( begin_idx - 1 ); var after_char = wordtxt.charAt( end_idx ); } while ( this._isWordChar( before_char ) || this._isWordChar( after_char ) ); // keep track of its position in the original text. this.indexes[txtid][i] = begin_idx; // write out the characters before the current misspelled word for( var j = this._lastPos( txtid, i ); j < begin_idx; j++ ) { // !!! html mode? make it html compatible d.write( this.printForHtml( wordtxt.charAt( j ))); } // write out the misspelled word. d.write( this._wordInputStr( orig[i] )); // if it's the last word, write out the rest of the text if( i == orig.length-1 ){ d.write( printForHtml( wordtxt.substr( end_idx ))); } } d.writeln( '</div>' ); } d.writeln( '</form>' ); } //for ( var j = 0; j < d.forms.length; j++ ) { // alert( d.forms[j].name ); // for( var k = 0; k < d.forms[j].elements.length; k++ ) { // alert( d.forms[j].elements[k].name + ": " + d.forms[j].elements[k].value ); // } //} // set the _forms property this._forms = d.forms; d.close(); } // return the character index in the full text after the last word we evaluated function _lastPos( txtid, idx ) { if( idx > 0 ) return this.indexes[txtid][idx-1] + this.originalSpellings[txtid][idx-1].length; else return 0; } function printForHtml( n ) { return n ; // by FredCK /* var htmlstr = n; if( htmlstr.length == 1 ) { // do simple case statement if it's just one character switch ( n ) { case "\n": htmlstr = '<br/>'; break; case "<": htmlstr = '&lt;'; break; case ">": htmlstr = '&gt;'; break; } return htmlstr; } else { htmlstr = htmlstr.replace( /</g, '&lt' ); htmlstr = htmlstr.replace( />/g, '&gt' ); htmlstr = htmlstr.replace( /\n/g, '<br/>' ); return htmlstr; } */ } function _isWordChar( letter ) { if( letter.search( this.wordChar ) == -1 ) { return false; } else { return true; } } function _getWordObject( textIndex, wordIndex ) { if( this._forms[textIndex] ) { if( this._forms[textIndex].elements[wordIndex] ) { return this._forms[textIndex].elements[wordIndex]; } } return null; } function _wordInputStr( word ) { var str = '<input readonly '; str += 'class="blend" type="text" value="' + word + '" size="' + word.length + '">'; return str; } function _adjustIndexes( textIndex, wordIndex, lengthDiff ) { for( var i = wordIndex + 1; i < this.originalSpellings[textIndex].length; i++ ) { this.indexes[textIndex][i] = this.indexes[textIndex][i] + lengthDiff; } }
JavaScript
//////////////////////////////////////////////////// // controlWindow object //////////////////////////////////////////////////// function controlWindow( controlForm ) { // private properties this._form = controlForm; // public properties this.windowType = "controlWindow"; // this.noSuggestionSelection = "- No suggestions -"; // by FredCK this.noSuggestionSelection = FCKLang.DlgSpellNoSuggestions ; // set up the properties for elements of the given control form this.suggestionList = this._form.sugg; this.evaluatedText = this._form.misword; this.replacementText = this._form.txtsugg; this.undoButton = this._form.btnUndo; // public methods this.addSuggestion = addSuggestion; this.clearSuggestions = clearSuggestions; this.selectDefaultSuggestion = selectDefaultSuggestion; this.resetForm = resetForm; this.setSuggestedText = setSuggestedText; this.enableUndo = enableUndo; this.disableUndo = disableUndo; } function resetForm() { if( this._form ) { this._form.reset(); } } function setSuggestedText() { var slct = this.suggestionList; var txt = this.replacementText; var str = ""; if( (slct.options[0].text) && slct.options[0].text != this.noSuggestionSelection ) { str = slct.options[slct.selectedIndex].text; } txt.value = str; } function selectDefaultSuggestion() { var slct = this.suggestionList; var txt = this.replacementText; if( slct.options.length == 0 ) { this.addSuggestion( this.noSuggestionSelection ); } else { slct.options[0].selected = true; } this.setSuggestedText(); } function addSuggestion( sugg_text ) { var slct = this.suggestionList; if( sugg_text ) { var i = slct.options.length; var newOption = new Option( sugg_text, 'sugg_text'+i ); slct.options[i] = newOption; } } function clearSuggestions() { var slct = this.suggestionList; for( var j = slct.length - 1; j > -1; j-- ) { if( slct.options[j] ) { slct.options[j] = null; } } } function enableUndo() { if( this.undoButton ) { if( this.undoButton.disabled == true ) { this.undoButton.disabled = false; } } } function disableUndo() { if( this.undoButton ) { if( this.undoButton.disabled == false ) { this.undoButton.disabled = true; } } }
JavaScript
//////////////////////////////////////////////////// // spellChecker.js // // spellChecker object // // This file is sourced on web pages that have a textarea object to evaluate // for spelling. It includes the implementation for the spellCheckObject. // //////////////////////////////////////////////////// // constructor function spellChecker( textObject ) { // public properties - configurable // this.popUpUrl = '/speller/spellchecker.html'; // by FredCK this.popUpUrl = 'fck_spellerpages/spellerpages/spellchecker.html'; // by FredCK this.popUpName = 'spellchecker'; // this.popUpProps = "menu=no,width=440,height=350,top=70,left=120,resizable=yes,status=yes"; // by FredCK this.popUpProps = null ; // by FredCK // this.spellCheckScript = '/speller/server-scripts/spellchecker.php'; // by FredCK //this.spellCheckScript = '/cgi-bin/spellchecker.pl'; // values used to keep track of what happened to a word this.replWordFlag = "R"; // single replace this.ignrWordFlag = "I"; // single ignore this.replAllFlag = "RA"; // replace all occurances this.ignrAllFlag = "IA"; // ignore all occurances this.fromReplAll = "~RA"; // an occurance of a "replace all" word this.fromIgnrAll = "~IA"; // an occurance of a "ignore all" word // properties set at run time this.wordFlags = new Array(); this.currentTextIndex = 0; this.currentWordIndex = 0; this.spellCheckerWin = null; this.controlWin = null; this.wordWin = null; this.textArea = textObject; // deprecated this.textInputs = arguments; // private methods this._spellcheck = _spellcheck; this._getSuggestions = _getSuggestions; this._setAsIgnored = _setAsIgnored; this._getTotalReplaced = _getTotalReplaced; this._setWordText = _setWordText; this._getFormInputs = _getFormInputs; // public methods this.openChecker = openChecker; this.startCheck = startCheck; this.checkTextBoxes = checkTextBoxes; this.checkTextAreas = checkTextAreas; this.spellCheckAll = spellCheckAll; this.ignoreWord = ignoreWord; this.ignoreAll = ignoreAll; this.replaceWord = replaceWord; this.replaceAll = replaceAll; this.terminateSpell = terminateSpell; this.undo = undo; // set the current window's "speller" property to the instance of this class. // this object can now be referenced by child windows/frames. window.speller = this; } // call this method to check all text boxes (and only text boxes) in the HTML document function checkTextBoxes() { this.textInputs = this._getFormInputs( "^text$" ); this.openChecker(); } // call this method to check all textareas (and only textareas ) in the HTML document function checkTextAreas() { this.textInputs = this._getFormInputs( "^textarea$" ); this.openChecker(); } // call this method to check all text boxes and textareas in the HTML document function spellCheckAll() { this.textInputs = this._getFormInputs( "^text(area)?$" ); this.openChecker(); } // call this method to check text boxe(s) and/or textarea(s) that were passed in to the // object's constructor or to the textInputs property function openChecker() { this.spellCheckerWin = window.open( this.popUpUrl, this.popUpName, this.popUpProps ); if( !this.spellCheckerWin.opener ) { this.spellCheckerWin.opener = window; } } function startCheck( wordWindowObj, controlWindowObj ) { // set properties from args this.wordWin = wordWindowObj; this.controlWin = controlWindowObj; // reset properties this.wordWin.resetForm(); this.controlWin.resetForm(); this.currentTextIndex = 0; this.currentWordIndex = 0; // initialize the flags to an array - one element for each text input this.wordFlags = new Array( this.wordWin.textInputs.length ); // each element will be an array that keeps track of each word in the text for( var i=0; i<this.wordFlags.length; i++ ) { this.wordFlags[i] = []; } // start this._spellcheck(); return true; } function ignoreWord() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } if( !this.wordWin.getTextVal( ti, wi )) { alert( 'Error: "Not in dictionary" text is missing.' ); return false; } // set as ignored if( this._setAsIgnored( ti, wi, this.ignrWordFlag )) { this.currentWordIndex++; this._spellcheck(); } return true; } function ignoreAll() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } // get the word that is currently being evaluated. var s_word_to_repl = this.wordWin.getTextVal( ti, wi ); if( !s_word_to_repl ) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } // set this word as an "ignore all" word. this._setAsIgnored( ti, wi, this.ignrAllFlag ); // loop through all the words after this word for( var i = ti; i < this.wordWin.textInputs.length; i++ ) { for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == ti && j > wi ) || i > ti ) { // future word: set as "from ignore all" if // 1) do not already have a flag and // 2) have the same value as current word if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl ) && ( !this.wordFlags[i][j] )) { this._setAsIgnored( i, j, this.fromIgnrAll ); } } } } // finally, move on this.currentWordIndex++; this._spellcheck(); return true; } function replaceWord() { var wi = this.currentWordIndex; var ti = this.currentTextIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } if( !this.wordWin.getTextVal( ti, wi )) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } if( !this.controlWin.replacementText ) { return false ; } var txt = this.controlWin.replacementText; if( txt.value ) { var newspell = new String( txt.value ); if( this._setWordText( ti, wi, newspell, this.replWordFlag )) { this.currentWordIndex++; this._spellcheck(); } } return true; } function replaceAll() { var ti = this.currentTextIndex; var wi = this.currentWordIndex; if( !this.wordWin ) { alert( 'Error: Word frame not available.' ); return false; } var s_word_to_repl = this.wordWin.getTextVal( ti, wi ); if( !s_word_to_repl ) { alert( 'Error: "Not in dictionary" text is missing' ); return false; } var txt = this.controlWin.replacementText; if( !txt.value ) return false; var newspell = new String( txt.value ); // set this word as a "replace all" word. this._setWordText( ti, wi, newspell, this.replAllFlag ); // loop through all the words after this word for( var i = ti; i < this.wordWin.textInputs.length; i++ ) { for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == ti && j > wi ) || i > ti ) { // future word: set word text to s_word_to_repl if // 1) do not already have a flag and // 2) have the same value as s_word_to_repl if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl ) && ( !this.wordFlags[i][j] )) { this._setWordText( i, j, newspell, this.fromReplAll ); } } } } // finally, move on this.currentWordIndex++; this._spellcheck(); return true; } function terminateSpell() { // called when we have reached the end of the spell checking. var msg = ""; // by FredCK var numrepl = this._getTotalReplaced(); if( numrepl == 0 ) { // see if there were no misspellings to begin with if( !this.wordWin ) { msg = ""; } else { if( this.wordWin.totalMisspellings() ) { // msg += "No words changed."; // by FredCK msg += FCKLang.DlgSpellNoChanges ; // by FredCK } else { // msg += "No misspellings found."; // by FredCK msg += FCKLang.DlgSpellNoMispell ; // by FredCK } } } else if( numrepl == 1 ) { // msg += "One word changed."; // by FredCK msg += FCKLang.DlgSpellOneChange ; // by FredCK } else { // msg += numrepl + " words changed."; // by FredCK msg += FCKLang.DlgSpellManyChanges.replace( /%1/g, numrepl ) ; } if( msg ) { // msg += "\n"; // by FredCK alert( msg ); } if( numrepl > 0 ) { // update the text field(s) on the opener window for( var i = 0; i < this.textInputs.length; i++ ) { // this.textArea.value = this.wordWin.text; if( this.wordWin ) { if( this.wordWin.textInputs[i] ) { this.textInputs[i].value = this.wordWin.textInputs[i]; } } } } // return back to the calling window // this.spellCheckerWin.close(); // by FredCK if ( typeof( this.OnFinished ) == 'function' ) // by FredCK this.OnFinished(numrepl) ; // by FredCK return true; } function undo() { // skip if this is the first word! var ti = this.currentTextIndex; var wi = this.currentWordIndex; if( this.wordWin.totalPreviousWords( ti, wi ) > 0 ) { this.wordWin.removeFocus( ti, wi ); // go back to the last word index that was acted upon do { // if the current word index is zero then reset the seed if( this.currentWordIndex == 0 && this.currentTextIndex > 0 ) { this.currentTextIndex--; this.currentWordIndex = this.wordWin.totalWords( this.currentTextIndex )-1; if( this.currentWordIndex < 0 ) this.currentWordIndex = 0; } else { if( this.currentWordIndex > 0 ) { this.currentWordIndex--; } } } while ( this.wordWin.totalWords( this.currentTextIndex ) == 0 || this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromIgnrAll || this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromReplAll ); var text_idx = this.currentTextIndex; var idx = this.currentWordIndex; var preReplSpell = this.wordWin.originalSpellings[text_idx][idx]; // if we got back to the first word then set the Undo button back to disabled if( this.wordWin.totalPreviousWords( text_idx, idx ) == 0 ) { this.controlWin.disableUndo(); } var i, j, origSpell ; // examine what happened to this current word. switch( this.wordFlags[text_idx][idx] ) { // replace all: go through this and all the future occurances of the word // and revert them all to the original spelling and clear their flags case this.replAllFlag : for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) { for( j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == text_idx && j >= idx ) || i > text_idx ) { origSpell = this.wordWin.originalSpellings[i][j]; if( origSpell == preReplSpell ) { this._setWordText ( i, j, origSpell, undefined ); } } } } break; // ignore all: go through all the future occurances of the word // and clear their flags case this.ignrAllFlag : for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) { for( j = 0; j < this.wordWin.totalWords( i ); j++ ) { if(( i == text_idx && j >= idx ) || i > text_idx ) { origSpell = this.wordWin.originalSpellings[i][j]; if( origSpell == preReplSpell ) { this.wordFlags[i][j] = undefined; } } } } break; // replace: revert the word to its original spelling case this.replWordFlag : this._setWordText ( text_idx, idx, preReplSpell, undefined ); break; } // For all four cases, clear the wordFlag of this word. re-start the process this.wordFlags[text_idx][idx] = undefined; this._spellcheck(); } } function _spellcheck() { var ww = this.wordWin; // check if this is the last word in the current text element if( this.currentWordIndex == ww.totalWords( this.currentTextIndex) ) { this.currentTextIndex++; this.currentWordIndex = 0; // keep going if we're not yet past the last text element if( this.currentTextIndex < this.wordWin.textInputs.length ) { this._spellcheck(); return; } else { this.terminateSpell(); return; } } // if this is after the first one make sure the Undo button is enabled if( this.currentWordIndex > 0 ) { this.controlWin.enableUndo(); } // skip the current word if it has already been worked on if( this.wordFlags[this.currentTextIndex][this.currentWordIndex] ) { // increment the global current word index and move on. this.currentWordIndex++; this._spellcheck(); } else { var evalText = ww.getTextVal( this.currentTextIndex, this.currentWordIndex ); if( evalText ) { this.controlWin.evaluatedText.value = evalText; ww.setFocus( this.currentTextIndex, this.currentWordIndex ); this._getSuggestions( this.currentTextIndex, this.currentWordIndex ); } } } function _getSuggestions( text_num, word_num ) { this.controlWin.clearSuggestions(); // add suggestion in list for each suggested word. // get the array of suggested words out of the // three-dimensional array containing all suggestions. var a_suggests = this.wordWin.suggestions[text_num][word_num]; if( a_suggests ) { // got an array of suggestions. for( var ii = 0; ii < a_suggests.length; ii++ ) { this.controlWin.addSuggestion( a_suggests[ii] ); } } this.controlWin.selectDefaultSuggestion(); } function _setAsIgnored( text_num, word_num, flag ) { // set the UI this.wordWin.removeFocus( text_num, word_num ); // do the bookkeeping this.wordFlags[text_num][word_num] = flag; return true; } function _getTotalReplaced() { var i_replaced = 0; for( var i = 0; i < this.wordFlags.length; i++ ) { for( var j = 0; j < this.wordFlags[i].length; j++ ) { if(( this.wordFlags[i][j] == this.replWordFlag ) || ( this.wordFlags[i][j] == this.replAllFlag ) || ( this.wordFlags[i][j] == this.fromReplAll )) { i_replaced++; } } } return i_replaced; } function _setWordText( text_num, word_num, newText, flag ) { // set the UI and form inputs this.wordWin.setText( text_num, word_num, newText ); // keep track of what happened to this word: this.wordFlags[text_num][word_num] = flag; return true; } function _getFormInputs( inputPattern ) { var inputs = new Array(); for( var i = 0; i < document.forms.length; i++ ) { for( var j = 0; j < document.forms[i].elements.length; j++ ) { if( document.forms[i].elements[j].type.match( inputPattern )) { inputs[inputs.length] = document.forms[i].elements[j]; } } } return inputs; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Useful functions used by almost all dialog window pages. * Dialogs should link to this file as the very first script on the page. */ // Automatically detect the correct document.domain (#123). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.parent.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; // Attention: FCKConfig must be available in the page. function GetCommonDialogCss( prefix ) { // CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt). return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}' ; } // Gets a element by its Id. Used for shorter coding. function GetE( elementId ) { return document.getElementById( elementId ) ; } function ShowE( element, isVisible ) { if ( typeof( element ) == 'string' ) element = GetE( element ) ; element.style.display = isVisible ? '' : 'none' ; } function SetAttribute( element, attName, attValue ) { if ( attValue == null || attValue.length == 0 ) element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive else element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive } function GetAttribute( element, attName, valueIfNull ) { var oAtt = element.attributes[attName] ; if ( oAtt == null || !oAtt.specified ) return valueIfNull ? valueIfNull : '' ; var oValue = element.getAttribute( attName, 2 ) ; if ( oValue == null ) oValue = oAtt.nodeValue ; return ( oValue == null ? valueIfNull : oValue ) ; } function SelectField( elementId ) { var element = GetE( elementId ) ; element.focus() ; // element.select may not be available for some fields (like <select>). if ( element.select ) element.select() ; } // Functions used by text fields to accept numbers only. var IsDigit = ( function() { var KeyIdentifierMap = { End : 35, Home : 36, Left : 37, Right : 39, 'U+00007F' : 46 // Delete } ; return function ( e ) { if ( !e ) e = event ; var iCode = ( e.keyCode || e.charCode ) ; if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) ) iCode = KeyIdentifierMap[ e.keyIdentifier ] ; return ( ( iCode >= 48 && iCode <= 57 ) // Numbers || (iCode >= 35 && iCode <= 40) // Arrows, Home, End || iCode == 8 // Backspace || iCode == 46 // Delete || iCode == 9 // Tab ) ; } } )() ; String.prototype.Trim = function() { return this.replace( /(^\s*)|(\s*$)/g, '' ) ; } String.prototype.StartsWith = function( value ) { return ( this.substr( 0, value.length ) == value ) ; } String.prototype.Remove = function( start, length ) { var s = '' ; if ( start > 0 ) s = this.substring( 0, start ) ; if ( start + length < this.length ) s += this.substring( start + length , this.length ) ; return s ; } String.prototype.ReplaceAll = function( searchArray, replaceArray ) { var replaced = this ; for ( var i = 0 ; i < searchArray.length ; i++ ) { replaced = replaced.replace( searchArray[i], replaceArray[i] ) ; } return replaced ; } function OpenFileBrowser( url, width, height ) { // oEditor must be defined. var iLeft = ( oEditor.FCKConfig.ScreenWidth - width ) / 2 ; var iTop = ( oEditor.FCKConfig.ScreenHeight - height ) / 2 ; var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ; sOptions += ",width=" + width ; sOptions += ",height=" + height ; sOptions += ",left=" + iLeft ; sOptions += ",top=" + iTop ; window.open( url, 'FCKBrowseWindow', sOptions ) ; } /** Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around It also allows to change the name or other special attributes in an existing node oEditor : instance of FCKeditor where the element will be created oOriginal : current element being edited or null if it has to be created nodeName : string with the name of the element to create oAttributes : Hash object with the attributes that must be set at creation time in IE Those attributes will be set also after the element has been created for any other browser to avoid redudant code */ function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes ) { var oNewNode ; // IE doesn't allow easily to change properties of an existing object, // so remove the old and force the creation of a new one. var oldNode = null ; if ( oOriginal && oEditor.FCKBrowserInfo.IsIE ) { // Force the creation only if some of the special attributes have changed: var bChanged = false; for( var attName in oAttributes ) bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ; if ( bChanged ) { oldNode = oOriginal ; oOriginal = null ; } } // If the node existed (and it's not IE), then we just have to update its attributes if ( oOriginal ) { oNewNode = oOriginal ; } else { // #676, IE doesn't play nice with the name or type attribute if ( oEditor.FCKBrowserInfo.IsIE ) { var sbHTML = [] ; sbHTML.push( '<' + nodeName ) ; for( var prop in oAttributes ) { sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ; } sbHTML.push( '>' ) ; if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] ) sbHTML.push( '</' + nodeName + '>' ) ; oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ; // Check if we are just changing the properties of an existing node: copy its properties if ( oldNode ) { CopyAttributes( oldNode, oNewNode, oAttributes ) ; oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ; oldNode.parentNode.removeChild( oldNode ) ; oldNode = null ; if ( oEditor.FCK.Selection.SelectionData ) { // Trick to refresh the selection object and avoid error in // fckdialog.html Selection.EnsureSelection var oSel = oEditor.FCK.EditorDocument.selection ; oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation } } oNewNode = oEditor.FCK.InsertElement( oNewNode ) ; // FCK.Selection.SelectionData is broken by now since we've // deleted the previously selected element. So we need to reassign it. if ( oEditor.FCK.Selection.SelectionData ) { var range = oEditor.FCK.EditorDocument.body.createControlRange() ; range.add( oNewNode ) ; oEditor.FCK.Selection.SelectionData = range ; } } else { oNewNode = oEditor.FCK.InsertElement( nodeName ) ; } } // Set the basic attributes for( var attName in oAttributes ) oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive return oNewNode ; } // Copy all the attributes from one node to the other, kinda like a clone // But oSkipAttributes is an object with the attributes that must NOT be copied function CopyAttributes( oSource, oDest, oSkipAttributes ) { var aAttributes = oSource.attributes ; for ( var n = 0 ; n < aAttributes.length ; n++ ) { var oAttribute = aAttributes[n] ; if ( oAttribute.specified ) { var sAttName = oAttribute.nodeName ; // We can set the type only once, so do it with the proper value, not copying it. if ( sAttName in oSkipAttributes ) continue ; var sAttValue = oSource.getAttribute( sAttName, 2 ) ; if ( sAttValue == null ) sAttValue = oAttribute.nodeValue ; oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive } } // The style: if ( oSource.style.cssText !== '' ) oDest.style.cssText = oSource.style.cssText ; } /** * Replaces a tag with another one, keeping its contents: * for example TD --> TH, and TH --> TD. * input: the original node, and the new tag name * http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-renameNode */ function RenameNode( oNode , newTag ) { // TODO: if the browser natively supports document.renameNode call it. // does any browser currently support it in order to test? // Only rename element nodes. if ( oNode.nodeType != 1 ) return null ; // If it's already correct exit here. if ( oNode.nodeName == newTag ) return oNode ; var oDoc = oNode.ownerDocument ; // Create the new node var newNode = oDoc.createElement( newTag ) ; // Copy all attributes CopyAttributes( oNode, newNode, {} ) ; // Move children to the new node FCKDomTools.MoveChildren( oNode, newNode ) ; // Finally replace the node and return the new one oNode.parentNode.replaceChild( newNode, oNode ) ; return newNode ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Image dialog window (see fck_image.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKDebug = oEditor.FCKDebug ; var FCKTools = oEditor.FCKTools ; var bImageButton = ( document.location.search.length > 0 && document.location.search.substr(1) == 'ImageButton' ) ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', FCKLang.DlgImgInfoTab ) ; if ( !bImageButton && !FCKConfig.ImageDlgHideLink ) dialog.AddTab( 'Link', FCKLang.DlgImgLinkTab ) ; if ( FCKConfig.ImageUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.ImageDlgHideAdvanced ) dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divLink' , ( tabCode == 'Link' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected image (if available). var oImage = dialog.Selection.GetSelectedElement() ; if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) ) oImage = null ; // Get the active link. var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ; var oImageOriginal ; function UpdateOriginal( resetSize ) { if ( !eImgPreview ) return ; if ( GetE('txtUrl').value.length == 0 ) { oImageOriginal = null ; return ; } oImageOriginal = document.createElement( 'IMG' ) ; // new Image() ; if ( resetSize ) { oImageOriginal.onload = function() { this.onload = null ; ResetSizes() ; } } oImageOriginal.src = eImgPreview.src ; } var bPreviewInitialized ; window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; GetE('btnLockSizes').title = FCKLang.DlgImgLockRatio ; GetE('btnResetSize').title = FCKLang.DlgBtnResetSize ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.ImageBrowser ? '' : 'none' ; GetE('divLnkBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ; UpdateOriginal() ; // Set the actual uploader URL. if ( FCKConfig.ImageUpload ) GetE('frmUpload').action = FCKConfig.ImageUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oImage ) return ; var sUrl = oImage.getAttribute( '_fcksavedurl' ) ; if ( sUrl == null ) sUrl = GetAttribute( oImage, 'src', '' ) ; GetE('txtUrl').value = sUrl ; GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ; GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ; GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ; GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ; GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ; var iWidth, iHeight ; var regexSize = /^\s*(\d+)px\s*$/i ; if ( oImage.style.width ) { var aMatchW = oImage.style.width.match( regexSize ) ; if ( aMatchW ) { iWidth = aMatchW[1] ; oImage.style.width = '' ; SetAttribute( oImage, 'width' , iWidth ) ; } } if ( oImage.style.height ) { var aMatchH = oImage.style.height.match( regexSize ) ; if ( aMatchH ) { iHeight = aMatchH[1] ; oImage.style.height = '' ; SetAttribute( oImage, 'height', iHeight ) ; } } GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ; GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ; // Get Advances Attributes GetE('txtAttId').value = oImage.id ; GetE('cmbAttLangDir').value = oImage.dir ; GetE('txtAttLangCode').value = oImage.lang ; GetE('txtAttTitle').value = oImage.title ; GetE('txtLongDesc').value = oImage.longDesc ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oImage.className || '' ; GetE('txtAttStyle').value = oImage.style.cssText ; } else { GetE('txtAttClasses').value = oImage.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oImage.getAttribute('style',2) ; } if ( oLink ) { var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ; if ( sLinkUrl == null ) sLinkUrl = oLink.getAttribute('href',2) ; GetE('txtLnkUrl').value = sLinkUrl ; GetE('cmbLnkTarget').value = oLink.target ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( FCKLang.DlgImgAlertUrl ) ; return false ; } var bHasImage = ( oImage != null ) ; if ( bHasImage && bImageButton && oImage.tagName == 'IMG' ) { if ( confirm( 'Do you want to transform the selected image on a image button?' ) ) oImage = null ; } else if ( bHasImage && !bImageButton && oImage.tagName == 'INPUT' ) { if ( confirm( 'Do you want to transform the selected image button on a simple image?' ) ) oImage = null ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !bHasImage ) { if ( bImageButton ) { oImage = FCK.EditorDocument.createElement( 'input' ) ; oImage.type = 'image' ; oImage = FCK.InsertElement( oImage ) ; } else oImage = FCK.InsertElement( 'img' ) ; } UpdateImage( oImage ) ; var sLnkUrl = GetE('txtLnkUrl').value.Trim() ; if ( sLnkUrl.length == 0 ) { if ( oLink ) FCK.ExecuteNamedCommand( 'Unlink' ) ; } else { if ( oLink ) // Modifying an existent link. oLink.href = sLnkUrl ; else // Creating a new link. { if ( !bHasImage ) oEditor.FCKSelection.SelectNode( oImage ) ; oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ; if ( !bHasImage ) { oEditor.FCKSelection.SelectNode( oLink ) ; oEditor.FCKSelection.Collapse( false ) ; } } SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ; SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ; } return true ; } function UpdateImage( e, skipId ) { e.src = GetE('txtUrl').value ; SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ; SetAttribute( e, "alt" , GetE('txtAlt').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; SetAttribute( e, "vspace", GetE('txtVSpace').value ) ; SetAttribute( e, "hspace", GetE('txtHSpace').value ) ; SetAttribute( e, "border", GetE('txtBorder').value ) ; SetAttribute( e, "align" , GetE('cmbAlign').value ) ; // Advances Attributes if ( ! skipId ) SetAttribute( e, 'id', GetE('txtAttId').value ) ; SetAttribute( e, 'dir' , GetE('cmbAttLangDir').value ) ; SetAttribute( e, 'lang' , GetE('txtAttLangCode').value ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; SetAttribute( e, 'longDesc' , GetE('txtLongDesc').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { e.className = GetE('txtAttClasses').value ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class' , GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var eImgPreview ; var eImgPreviewLink ; function SetPreviewElements( imageElement, linkElement ) { eImgPreview = imageElement ; eImgPreviewLink = linkElement ; UpdatePreview() ; UpdateOriginal() ; bPreviewInitialized = true ; } function UpdatePreview() { if ( !eImgPreview || !eImgPreviewLink ) return ; if ( GetE('txtUrl').value.length == 0 ) eImgPreviewLink.style.display = 'none' ; else { UpdateImage( eImgPreview, true ) ; if ( GetE('txtLnkUrl').value.Trim().length > 0 ) eImgPreviewLink.href = 'javascript:void(null);' ; else SetAttribute( eImgPreviewLink, 'href', '' ) ; eImgPreviewLink.style.display = '' ; } } var bLockRatio = true ; function SwitchLock( lockButton ) { bLockRatio = !bLockRatio ; lockButton.className = bLockRatio ? 'BtnLocked' : 'BtnUnlocked' ; lockButton.title = bLockRatio ? 'Lock sizes' : 'Unlock sizes' ; if ( bLockRatio ) { if ( GetE('txtWidth').value.length > 0 ) OnSizeChanged( 'Width', GetE('txtWidth').value ) ; else OnSizeChanged( 'Height', GetE('txtHeight').value ) ; } } // Fired when the width or height input texts change function OnSizeChanged( dimension, value ) { // Verifies if the aspect ration has to be maintained if ( oImageOriginal && bLockRatio ) { var e = dimension == 'Width' ? GetE('txtHeight') : GetE('txtWidth') ; if ( value.length == 0 || isNaN( value ) ) { e.value = '' ; return ; } if ( dimension == 'Width' ) value = value == 0 ? 0 : Math.round( oImageOriginal.height * ( value / oImageOriginal.width ) ) ; else value = value == 0 ? 0 : Math.round( oImageOriginal.width * ( value / oImageOriginal.height ) ) ; if ( !isNaN( value ) ) e.value = value ; } UpdatePreview() ; } // Fired when the Reset Size button is clicked function ResetSizes() { if ( ! oImageOriginal ) return ; if ( oEditor.FCKBrowserInfo.IsGecko && !oImageOriginal.complete ) { setTimeout( ResetSizes, 50 ) ; return ; } GetE('txtWidth').value = oImageOriginal.width ; GetE('txtHeight').value = oImageOriginal.height ; UpdatePreview() ; } function BrowseServer() { OpenServerBrowser( 'Image', FCKConfig.ImageBrowserURL, FCKConfig.ImageBrowserWindowWidth, FCKConfig.ImageBrowserWindowHeight ) ; } function LnkBrowseServer() { OpenServerBrowser( 'Link', FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ; } function OpenServerBrowser( type, url, width, height ) { sActualBrowser = type ; OpenFileBrowser( url, width, height ) ; } var sActualBrowser ; function SetUrl( url, width, height, alt ) { if ( sActualBrowser == 'Link' ) { GetE('txtLnkUrl').value = url ; UpdatePreview() ; } else { GetE('txtUrl').value = url ; GetE('txtWidth').value = width ? width : '' ; GetE('txtHeight').value = height ? height : '' ; if ( alt ) GetE('txtAlt').value = alt; UpdatePreview() ; UpdateOriginal( true ) ; } dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } sActualBrowser = '' ; SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.ImageUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.ImageUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.ImageUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.ImageUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Flash dialog window (see fck_flash.html). */ var dialog = window.parent ; var oEditor = dialog.InnerDialogLoaded() ; var FCK = oEditor.FCK ; var FCKLang = oEditor.FCKLang ; var FCKConfig = oEditor.FCKConfig ; var FCKTools = oEditor.FCKTools ; //#### Dialog Tabs // Set the dialog tabs. dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ; if ( FCKConfig.FlashUpload ) dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ; if ( !FCKConfig.FlashDlgHideAdvanced ) dialog.AddTab( 'Advanced', oEditor.FCKLang.DlgAdvancedTag ) ; // Function called when a dialog tag is selected. function OnDialogTabChange( tabCode ) { ShowE('divInfo' , ( tabCode == 'Info' ) ) ; ShowE('divUpload' , ( tabCode == 'Upload' ) ) ; ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ; } // Get the selected flash embed (if available). var oFakeImage = dialog.Selection.GetSelectedElement() ; var oEmbed ; if ( oFakeImage ) { if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') ) oEmbed = FCK.GetRealElement( oFakeImage ) ; else oFakeImage = null ; } window.onload = function() { // Translate the dialog box texts. oEditor.FCKLanguageManager.TranslatePage(document) ; // Load the selected element information (if any). LoadSelection() ; // Show/Hide the "Browse Server" button. GetE('tdBrowse').style.display = FCKConfig.FlashBrowser ? '' : 'none' ; // Set the actual uploader URL. if ( FCKConfig.FlashUpload ) GetE('frmUpload').action = FCKConfig.FlashUploadURL ; dialog.SetAutoSize( true ) ; // Activate the "OK" button. dialog.SetOkButton( true ) ; SelectField( 'txtUrl' ) ; } function LoadSelection() { if ( ! oEmbed ) return ; GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ; GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ; GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ; // Get Advances Attributes GetE('txtAttId').value = oEmbed.id ; GetE('chkAutoPlay').checked = GetAttribute( oEmbed, 'play', 'true' ) == 'true' ; GetE('chkLoop').checked = GetAttribute( oEmbed, 'loop', 'true' ) == 'true' ; GetE('chkMenu').checked = GetAttribute( oEmbed, 'menu', 'true' ) == 'true' ; GetE('cmbScale').value = GetAttribute( oEmbed, 'scale', '' ).toLowerCase() ; GetE('txtAttTitle').value = oEmbed.title ; if ( oEditor.FCKBrowserInfo.IsIE ) { GetE('txtAttClasses').value = oEmbed.getAttribute('className') || '' ; GetE('txtAttStyle').value = oEmbed.style.cssText ; } else { GetE('txtAttClasses').value = oEmbed.getAttribute('class',2) || '' ; GetE('txtAttStyle').value = oEmbed.getAttribute('style',2) || '' ; } UpdatePreview() ; } //#### The OK button was hit. function Ok() { if ( GetE('txtUrl').value.length == 0 ) { dialog.SetSelectedTab( 'Info' ) ; GetE('txtUrl').focus() ; alert( oEditor.FCKLang.DlgAlertUrl ) ; return false ; } oEditor.FCKUndo.SaveUndoStep() ; if ( !oEmbed ) { oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ; oFakeImage = null ; } UpdateEmbed( oEmbed ) ; if ( !oFakeImage ) { oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ; oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ; oFakeImage = FCK.InsertElement( oFakeImage ) ; } oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ; return true ; } function UpdateEmbed( e ) { SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ; SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, "width" , GetE('txtWidth').value ) ; SetAttribute( e, "height", GetE('txtHeight').value ) ; // Advances Attributes SetAttribute( e, 'id' , GetE('txtAttId').value ) ; SetAttribute( e, 'scale', GetE('cmbScale').value ) ; SetAttribute( e, 'play', GetE('chkAutoPlay').checked ? 'true' : 'false' ) ; SetAttribute( e, 'loop', GetE('chkLoop').checked ? 'true' : 'false' ) ; SetAttribute( e, 'menu', GetE('chkMenu').checked ? 'true' : 'false' ) ; SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ; if ( oEditor.FCKBrowserInfo.IsIE ) { SetAttribute( e, 'className', GetE('txtAttClasses').value ) ; e.style.cssText = GetE('txtAttStyle').value ; } else { SetAttribute( e, 'class', GetE('txtAttClasses').value ) ; SetAttribute( e, 'style', GetE('txtAttStyle').value ) ; } } var ePreview ; function SetPreviewElement( previewEl ) { ePreview = previewEl ; if ( GetE('txtUrl').value.length > 0 ) UpdatePreview() ; } function UpdatePreview() { if ( !ePreview ) return ; while ( ePreview.firstChild ) ePreview.removeChild( ePreview.firstChild ) ; if ( GetE('txtUrl').value.length == 0 ) ePreview.innerHTML = '&nbsp;' ; else { var oDoc = ePreview.ownerDocument || ePreview.document ; var e = oDoc.createElement( 'EMBED' ) ; SetAttribute( e, 'src', GetE('txtUrl').value ) ; SetAttribute( e, 'type', 'application/x-shockwave-flash' ) ; SetAttribute( e, 'width', '100%' ) ; SetAttribute( e, 'height', '100%' ) ; ePreview.appendChild( e ) ; } } // <embed id="ePreview" src="fck_flash/claims.swf" width="100%" height="100%" style="visibility:hidden" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> function BrowseServer() { OpenFileBrowser( FCKConfig.FlashBrowserURL, FCKConfig.FlashBrowserWindowWidth, FCKConfig.FlashBrowserWindowHeight ) ; } function SetUrl( url, width, height ) { GetE('txtUrl').value = url ; if ( width ) GetE('txtWidth').value = width ; if ( height ) GetE('txtHeight').value = height ; UpdatePreview() ; dialog.SetSelectedTab( 'Info' ) ; } function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg ) { // Remove animation window.parent.Throbber.Hide() ; GetE( 'divUpload' ).style.display = '' ; switch ( errorNumber ) { case 0 : // No errors alert( 'Your file has been successfully uploaded' ) ; break ; case 1 : // Custom error alert( customMsg ) ; return ; case 101 : // Custom warning alert( customMsg ) ; break ; case 201 : alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ; break ; case 202 : alert( 'Invalid file type' ) ; return ; case 203 : alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ; return ; case 500 : alert( 'The connector is disabled' ) ; break ; default : alert( 'Error on file upload. Error number: ' + errorNumber ) ; return ; } SetUrl( fileUrl ) ; GetE('frmUpload').reset() ; } var oUploadAllowedExtRegex = new RegExp( FCKConfig.FlashUploadAllowedExtensions, 'i' ) ; var oUploadDeniedExtRegex = new RegExp( FCKConfig.FlashUploadDeniedExtensions, 'i' ) ; function CheckUpload() { var sFile = GetE('txtUploadFile').value ; if ( sFile.length == 0 ) { alert( 'Please select a file to upload' ) ; return false ; } if ( ( FCKConfig.FlashUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) || ( FCKConfig.FlashUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) ) { OnUploadCompleted( 202 ) ; return false ; } // Show animation window.parent.Throbber.Show( 100 ) ; GetE( 'divUpload' ).style.display = 'none' ; return true ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Plugin to insert "Placeholders" in the editor. */ // Register the related command. FCKCommands.RegisterCommand( 'Placeholder', new FCKDialogCommand( 'Placeholder', FCKLang.PlaceholderDlgTitle, FCKPlugins.Items['placeholder'].Path + 'fck_placeholder.html', 340, 160 ) ) ; // Create the "Plaholder" toolbar button. var oPlaceholderItem = new FCKToolbarButton( 'Placeholder', FCKLang.PlaceholderBtn ) ; oPlaceholderItem.IconPath = FCKPlugins.Items['placeholder'].Path + 'placeholder.gif' ; FCKToolbarItems.RegisterItem( 'Placeholder', oPlaceholderItem ) ; // The object used for all Placeholder operations. var FCKPlaceholders = new Object() ; // Add a new placeholder at the actual selection. FCKPlaceholders.Add = function( name ) { var oSpan = FCK.InsertElement( 'span' ) ; this.SetupSpan( oSpan, name ) ; } FCKPlaceholders.SetupSpan = function( span, name ) { span.innerHTML = '[[ ' + name + ' ]]' ; span.style.backgroundColor = '#ffff00' ; span.style.color = '#000000' ; if ( FCKBrowserInfo.IsGecko ) span.style.cursor = 'default' ; span._fckplaceholder = name ; span.contentEditable = false ; // To avoid it to be resized. span.onresizestart = function() { FCK.EditorWindow.event.returnValue = false ; return false ; } } // On Gecko we must do this trick so the user select all the SPAN when clicking on it. FCKPlaceholders._SetupClickListener = function() { FCKPlaceholders._ClickListener = function( e ) { if ( e.target.tagName == 'SPAN' && e.target._fckplaceholder ) FCKSelection.SelectNode( e.target ) ; } FCK.EditorDocument.addEventListener( 'click', FCKPlaceholders._ClickListener, true ) ; } // Open the Placeholder dialog on double click. FCKPlaceholders.OnDoubleClick = function( span ) { if ( span.tagName == 'SPAN' && span._fckplaceholder ) FCKCommands.GetCommand( 'Placeholder' ).Execute() ; } FCK.RegisterDoubleClickHandler( FCKPlaceholders.OnDoubleClick, 'SPAN' ) ; // Check if a Placholder name is already in use. FCKPlaceholders.Exist = function( name ) { var aSpans = FCK.EditorDocument.getElementsByTagName( 'SPAN' ) ; for ( var i = 0 ; i < aSpans.length ; i++ ) { if ( aSpans[i]._fckplaceholder == name ) return true ; } return false ; } if ( FCKBrowserInfo.IsIE ) { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var aPlaholders = FCK.EditorDocument.body.innerText.match( /\[\[[^\[\]]+\]\]/g ) ; if ( !aPlaholders ) return ; var oRange = FCK.EditorDocument.body.createTextRange() ; for ( var i = 0 ; i < aPlaholders.length ; i++ ) { if ( oRange.findText( aPlaholders[i] ) ) { var sName = aPlaholders[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; oRange.pasteHTML( '<span style="color: #000000; background-color: #ffff00" contenteditable="false" _fckplaceholder="' + sName + '">' + aPlaholders[i] + '</span>' ) ; } } } } else { FCKPlaceholders.Redraw = function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; var oInteractor = FCK.EditorDocument.createTreeWalker( FCK.EditorDocument.body, NodeFilter.SHOW_TEXT, FCKPlaceholders._AcceptNode, true ) ; var aNodes = new Array() ; while ( ( oNode = oInteractor.nextNode() ) ) { aNodes[ aNodes.length ] = oNode ; } for ( var n = 0 ; n < aNodes.length ; n++ ) { var aPieces = aNodes[n].nodeValue.split( /(\[\[[^\[\]]+\]\])/g ) ; for ( var i = 0 ; i < aPieces.length ; i++ ) { if ( aPieces[i].length > 0 ) { if ( aPieces[i].indexOf( '[[' ) == 0 ) { var sName = aPieces[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ; var oSpan = FCK.EditorDocument.createElement( 'span' ) ; FCKPlaceholders.SetupSpan( oSpan, sName ) ; aNodes[n].parentNode.insertBefore( oSpan, aNodes[n] ) ; } else aNodes[n].parentNode.insertBefore( FCK.EditorDocument.createTextNode( aPieces[i] ) , aNodes[n] ) ; } } aNodes[n].parentNode.removeChild( aNodes[n] ) ; } FCKPlaceholders._SetupClickListener() ; } FCKPlaceholders._AcceptNode = function( node ) { if ( /\[\[[^\[\]]+\]\]/.test( node.nodeValue ) ) return NodeFilter.FILTER_ACCEPT ; else return NodeFilter.FILTER_SKIP ; } } FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKPlaceholders.Redraw ) ; // We must process the SPAN tags to replace then with the real resulting value of the placeholder. FCKXHtml.TagProcessors['span'] = function( node, htmlNode ) { if ( htmlNode._fckplaceholder ) node = FCKXHtml.XML.createTextNode( '[[' + htmlNode._fckplaceholder + ']]' ) ; else FCKXHtml._AppendChildNodes( node, htmlNode, false ) ; return node ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placholder Italian language file. */ FCKLang.PlaceholderBtn = 'Aggiungi/Modifica Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Proprietà del Placeholder' ; FCKLang.PlaceholderDlgName = 'Nome del Placeholder' ; FCKLang.PlaceholderErrNoName = 'Digitare il nome del placeholder' ; FCKLang.PlaceholderErrNameInUse = 'Il nome inserito è già in uso' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placholder German language file. */ FCKLang.PlaceholderBtn = 'Einfügen/editieren Platzhalter' ; FCKLang.PlaceholderDlgTitle = 'Platzhalter Eigenschaften' ; FCKLang.PlaceholderDlgName = 'Platzhalter Name' ; FCKLang.PlaceholderErrNoName = 'Bitte den Namen des Platzhalters schreiben' ; FCKLang.PlaceholderErrNameInUse = 'Der angegebene Namen ist schon in Gebrauch' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placholder Polish language file. */ FCKLang.PlaceholderBtn = 'Wstaw/Edytuj nagłówek' ; FCKLang.PlaceholderDlgTitle = 'Właśności nagłówka' ; FCKLang.PlaceholderDlgName = 'Nazwa nagłówka' ; FCKLang.PlaceholderErrNoName = 'Proszę wprowadzić nazwę nagłówka' ; FCKLang.PlaceholderErrNameInUse = 'Podana nazwa jest już w użyciu' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placeholder French language file. */ FCKLang.PlaceholderBtn = "Insérer/Modifier l'Espace réservé" ; FCKLang.PlaceholderDlgTitle = "Propriétés de l'Espace réservé" ; FCKLang.PlaceholderDlgName = "Nom de l'Espace réservé" ; FCKLang.PlaceholderErrNoName = "Veuillez saisir le nom de l'Espace réservé" ; FCKLang.PlaceholderErrNameInUse = "Ce nom est déjà utilisé" ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placholder English language file. */ FCKLang.PlaceholderBtn = 'Insert/Edit Placeholder' ; FCKLang.PlaceholderDlgTitle = 'Placeholder Properties' ; FCKLang.PlaceholderDlgName = 'Placeholder Name' ; FCKLang.PlaceholderErrNoName = 'Please type the placeholder name' ; FCKLang.PlaceholderErrNameInUse = 'The specified name is already in use' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Placholder Spanish language file. */ FCKLang.PlaceholderBtn = 'Insertar/Editar contenedor' ; FCKLang.PlaceholderDlgTitle = 'Propiedades del contenedor ' ; FCKLang.PlaceholderDlgName = 'Nombre de contenedor' ; FCKLang.PlaceholderErrNoName = 'Por favor escriba el nombre de contenedor' ; FCKLang.PlaceholderErrNameInUse = 'El nombre especificado ya esta en uso' ;
JavaScript
var FCKDragTableHandler = { "_DragState" : 0, "_LeftCell" : null, "_RightCell" : null, "_MouseMoveMode" : 0, // 0 - find candidate cells for resizing, 1 - drag to resize "_ResizeBar" : null, "_OriginalX" : null, "_MinimumX" : null, "_MaximumX" : null, "_LastX" : null, "_TableMap" : null, "_doc" : document, "_IsInsideNode" : function( w, domNode, pos ) { var myCoords = FCKTools.GetWindowPosition( w, domNode ) ; var xMin = myCoords.x ; var yMin = myCoords.y ; var xMax = parseInt( xMin, 10 ) + parseInt( domNode.offsetWidth, 10 ) ; var yMax = parseInt( yMin, 10 ) + parseInt( domNode.offsetHeight, 10 ) ; if ( pos.x >= xMin && pos.x <= xMax && pos.y >= yMin && pos.y <= yMax ) return true; return false; }, "_GetBorderCells" : function( w, tableNode, tableMap, mouse ) { // Enumerate all the cells in the table. var cells = [] ; for ( var i = 0 ; i < tableNode.rows.length ; i++ ) { var r = tableNode.rows[i] ; for ( var j = 0 ; j < r.cells.length ; j++ ) cells.push( r.cells[j] ) ; } if ( cells.length < 1 ) return null ; // Get the cells whose right or left border is nearest to the mouse cursor's x coordinate. var minRxDist = null ; var lxDist = null ; var minYDist = null ; var rbCell = null ; var lbCell = null ; for ( var i = 0 ; i < cells.length ; i++ ) { var pos = FCKTools.GetWindowPosition( w, cells[i] ) ; var rightX = pos.x + parseInt( cells[i].clientWidth, 10 ) ; var rxDist = mouse.x - rightX ; var yDist = mouse.y - ( pos.y + ( cells[i].clientHeight / 2 ) ) ; if ( minRxDist == null || ( Math.abs( rxDist ) <= Math.abs( minRxDist ) && ( minYDist == null || Math.abs( yDist ) <= Math.abs( minYDist ) ) ) ) { minRxDist = rxDist ; minYDist = yDist ; rbCell = cells[i] ; } } /* var rowNode = FCKTools.GetElementAscensor( rbCell, "tr" ) ; var cellIndex = rbCell.cellIndex + 1 ; if ( cellIndex >= rowNode.cells.length ) return null ; lbCell = rowNode.cells.item( cellIndex ) ; */ var rowIdx = rbCell.parentNode.rowIndex ; var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, rbCell ) ; var colSpan = isNaN( rbCell.colSpan ) ? 1 : rbCell.colSpan ; lbCell = tableMap[rowIdx][colIdx + colSpan] ; if ( ! lbCell ) return null ; // Abort if too far from the border. lxDist = mouse.x - FCKTools.GetWindowPosition( w, lbCell ).x ; if ( lxDist < 0 && minRxDist < 0 && minRxDist < -2 ) return null ; if ( lxDist > 0 && minRxDist > 0 && lxDist > 3 ) return null ; return { "leftCell" : rbCell, "rightCell" : lbCell } ; }, "_GetResizeBarPosition" : function() { var row = FCKTools.GetElementAscensor( this._RightCell, "tr" ) ; return FCKTableHandler._GetCellIndexSpan( this._TableMap, row.rowIndex, this._RightCell ) ; }, "_ResizeBarMouseDownListener" : function( evt ) { if ( FCKDragTableHandler._LeftCell ) FCKDragTableHandler._MouseMoveMode = 1 ; if ( FCKBrowserInfo.IsIE ) FCKDragTableHandler._ResizeBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50 ; else FCKDragTableHandler._ResizeBar.style.opacity = 0.5 ; FCKDragTableHandler._OriginalX = evt.clientX ; // Calculate maximum and minimum x-coordinate delta. var borderIndex = FCKDragTableHandler._GetResizeBarPosition() ; var offset = FCKDragTableHandler._GetIframeOffset(); var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ); var minX = null ; var maxX = null ; for ( var r = 0 ; r < FCKDragTableHandler._TableMap.length ; r++ ) { var leftCell = FCKDragTableHandler._TableMap[r][borderIndex - 1] ; var rightCell = FCKDragTableHandler._TableMap[r][borderIndex] ; var leftPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, leftCell ) ; var rightPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, rightCell ) ; var leftPadding = FCKDragTableHandler._GetCellPadding( table, leftCell ) ; var rightPadding = FCKDragTableHandler._GetCellPadding( table, rightCell ) ; if ( minX == null || leftPosition.x + leftPadding > minX ) minX = leftPosition.x + leftPadding ; if ( maxX == null || rightPosition.x + rightCell.clientWidth - rightPadding < maxX ) maxX = rightPosition.x + rightCell.clientWidth - rightPadding ; } FCKDragTableHandler._MinimumX = minX + offset.x ; FCKDragTableHandler._MaximumX = maxX + offset.x ; FCKDragTableHandler._LastX = null ; if (evt.preventDefault) evt.preventDefault(); else evt.returnValue = false; }, "_ResizeBarMouseUpListener" : function( evt ) { FCKDragTableHandler._MouseMoveMode = 0 ; FCKDragTableHandler._HideResizeBar() ; if ( FCKDragTableHandler._LastX == null ) return ; // Calculate the delta value. var deltaX = FCKDragTableHandler._LastX - FCKDragTableHandler._OriginalX ; // Then, build an array of current column width values. // This algorithm can be very slow if the cells have insane colSpan values. (e.g. colSpan=1000). var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ) ; var colArray = [] ; var tableMap = FCKDragTableHandler._TableMap ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; var width = FCKDragTableHandler._GetCellWidth( table, cell ) ; var colSpan = isNaN( cell.colSpan) ? 1 : cell.colSpan ; if ( colArray.length <= j ) colArray.push( { width : width / colSpan, colSpan : colSpan } ) ; else { var guessItem = colArray[j] ; if ( guessItem.colSpan > colSpan ) { guessItem.width = width / colSpan ; guessItem.colSpan = colSpan ; } } } } // Find out the equivalent column index of the two cells selected for resizing. colIndex = FCKDragTableHandler._GetResizeBarPosition() ; // Note that colIndex must be at least 1 here, so it's safe to subtract 1 from it. colIndex-- ; // Modify the widths in the colArray according to the mouse coordinate delta value. colArray[colIndex].width += deltaX ; colArray[colIndex + 1].width -= deltaX ; // Clear all cell widths, delete all <col> elements from the table. for ( var r = 0 ; r < table.rows.length ; r++ ) { var row = table.rows.item( r ) ; for ( var c = 0 ; c < row.cells.length ; c++ ) { var cell = row.cells.item( c ) ; cell.width = "" ; cell.style.width = "" ; } } var colElements = table.getElementsByTagName( "col" ) ; for ( var i = colElements.length - 1 ; i >= 0 ; i-- ) colElements[i].parentNode.removeChild( colElements[i] ) ; // Set new cell widths. var processedCells = [] ; for ( var i = 0 ; i < tableMap.length ; i++ ) { for ( var j = 0 ; j < tableMap[i].length ; j++ ) { var cell = tableMap[i][j] ; if ( cell._Processed ) continue ; if ( tableMap[i][j-1] != cell ) cell.width = colArray[j].width ; else cell.width = parseInt( cell.width, 10 ) + parseInt( colArray[j].width, 10 ) ; if ( tableMap[i][j+1] != cell ) { processedCells.push( cell ) ; cell._Processed = true ; } } } for ( var i = 0 ; i < processedCells.length ; i++ ) { if ( FCKBrowserInfo.IsIE ) processedCells[i].removeAttribute( '_Processed' ) ; else delete processedCells[i]._Processed ; } FCKDragTableHandler._LastX = null ; }, "_ResizeBarMouseMoveListener" : function( evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, // Calculate the padding of a table cell. // It returns the value of paddingLeft + paddingRight of a table cell. // This function is used, in part, to calculate the width parameter that should be used for setting cell widths. // The equation in question is clientWidth = paddingLeft + paddingRight + width. // So that width = clientWidth - paddingLeft - paddingRight. // The return value of this function must be pixel accurate acorss all supported browsers, so be careful if you need to modify it. "_GetCellPadding" : function( table, cell ) { var attrGuess = parseInt( table.cellPadding, 10 ) * 2 ; var cssGuess = null ; if ( typeof( window.getComputedStyle ) == "function" ) { var styleObj = window.getComputedStyle( cell, null ) ; cssGuess = parseInt( styleObj.getPropertyValue( "padding-left" ), 10 ) + parseInt( styleObj.getPropertyValue( "padding-right" ), 10 ) ; } else cssGuess = parseInt( cell.currentStyle.paddingLeft, 10 ) + parseInt (cell.currentStyle.paddingRight, 10 ) ; var cssRuntime = cell.style.padding ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) * 2 ; else { cssRuntime = cell.style.paddingLeft ; if ( isFinite( cssRuntime ) ) cssGuess = parseInt( cssRuntime, 10 ) ; cssRuntime = cell.style.paddingRight ; if ( isFinite( cssRuntime ) ) cssGuess += parseInt( cssRuntime, 10 ) ; } attrGuess = parseInt( attrGuess, 10 ) ; cssGuess = parseInt( cssGuess, 10 ) ; if ( isNaN( attrGuess ) ) attrGuess = 0 ; if ( isNaN( cssGuess ) ) cssGuess = 0 ; return Math.max( attrGuess, cssGuess ) ; }, // Calculate the real width of the table cell. // The real width of the table cell is the pixel width that you can set to the width attribute of the table cell and after // that, the table cell should be of exactly the same width as before. // The real width of a table cell can be calculated as: // width = clientWidth - paddingLeft - paddingRight. "_GetCellWidth" : function( table, cell ) { var clientWidth = cell.clientWidth ; if ( isNaN( clientWidth ) ) clientWidth = 0 ; return clientWidth - this._GetCellPadding( table, cell ) ; }, "MouseMoveListener" : function( FCK, evt ) { if ( FCKDragTableHandler._MouseMoveMode == 0 ) return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; else return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; }, "_MouseFindHandler" : function( FCK, evt ) { if ( FCK.MouseDownFlag ) return ; var node = evt.srcElement || evt.target ; try { if ( ! node || node.nodeType != 1 ) { this._HideResizeBar() ; return ; } } catch ( e ) { this._HideResizeBar() ; return ; } // Since this function might be called from the editing area iframe or the outer fckeditor iframe, // the mouse point coordinates from evt.clientX/Y can have different reference points. // We need to resolve the mouse pointer position relative to the editing area iframe. var mouseX = evt.clientX ; var mouseY = evt.clientY ; if ( FCKTools.GetElementDocument( node ) == document ) { var offset = this._GetIframeOffset() ; mouseX -= offset.x ; mouseY -= offset.y ; } if ( this._ResizeBar && this._LeftCell ) { var leftPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._LeftCell ) ; var rightPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._RightCell ) ; var rxDist = mouseX - ( leftPos.x + this._LeftCell.clientWidth ) ; var lxDist = mouseX - rightPos.x ; var inRangeFlag = false ; if ( lxDist >= 0 && rxDist <= 0 ) inRangeFlag = true ; else if ( rxDist > 0 && lxDist <= 3 ) inRangeFlag = true ; else if ( lxDist < 0 && rxDist >= -2 ) inRangeFlag = true ; if ( inRangeFlag ) { this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; return ; } } var tagName = node.tagName.toLowerCase() ; if ( tagName != "table" && tagName != "td" && tagName != "th" ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; return ; } node = FCKTools.GetElementAscensor( node, "table" ) ; var tableMap = FCKTableHandler._CreateTableMap( node ) ; var cellTuple = this._GetBorderCells( FCK.EditorWindow, node, tableMap, { "x" : mouseX, "y" : mouseY } ) ; if ( cellTuple == null ) { if ( this._LeftCell ) this._LeftCell = this._RightCell = this._TableMap = null ; this._HideResizeBar() ; } else { this._LeftCell = cellTuple["leftCell"] ; this._RightCell = cellTuple["rightCell"] ; this._TableMap = tableMap ; this._ShowResizeBar( FCK.EditorWindow, FCKTools.GetElementAscensor( this._LeftCell, "table" ), { "x" : mouseX, "y" : mouseY } ) ; } }, "_MouseDragHandler" : function( FCK, evt ) { var mouse = { "x" : evt.clientX, "y" : evt.clientY } ; // Convert mouse coordinates in reference to the outer iframe. var node = evt.srcElement || evt.target ; if ( FCKTools.GetElementDocument( node ) == FCK.EditorDocument ) { var offset = this._GetIframeOffset() ; mouse.x += offset.x ; mouse.y += offset.y ; } // Calculate the mouse position delta and see if we've gone out of range. if ( mouse.x >= this._MaximumX - 5 ) mouse.x = this._MaximumX - 5 ; if ( mouse.x <= this._MinimumX + 5 ) mouse.x = this._MinimumX + 5 ; var docX = mouse.x + FCKTools.GetScrollPosition( window ).X ; this._ResizeBar.style.left = ( docX - this._ResizeBar.offsetWidth / 2 ) + "px" ; this._LastX = mouse.x ; }, "_ShowResizeBar" : function( w, table, mouse ) { if ( this._ResizeBar == null ) { this._ResizeBar = this._doc.createElement( "div" ) ; var paddingBar = this._ResizeBar ; var paddingStyles = { 'position' : 'absolute', 'cursor' : 'e-resize' } ; if ( FCKBrowserInfo.IsIE ) paddingStyles.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=10,enabled=true)" ; else paddingStyles.opacity = 0.10 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; this._avoidStyles( paddingBar ); paddingBar.setAttribute('_fcktemp', true); this._doc.body.appendChild( paddingBar ) ; FCKTools.AddEventListener( paddingBar, "mousemove", this._ResizeBarMouseMoveListener ) ; FCKTools.AddEventListener( paddingBar, "mousedown", this._ResizeBarMouseDownListener ) ; FCKTools.AddEventListener( document, "mouseup", this._ResizeBarMouseUpListener ) ; FCKTools.AddEventListener( FCK.EditorDocument, "mouseup", this._ResizeBarMouseUpListener ) ; // IE doesn't let the tranparent part of the padding block to receive mouse events unless there's something inside. // So we need to create a spacer image to fill the block up. var filler = this._doc.createElement( "img" ) ; filler.setAttribute('_fcktemp', true); filler.border = 0 ; filler.src = FCKConfig.BasePath + "images/spacer.gif" ; filler.style.position = "absolute" ; paddingBar.appendChild( filler ) ; // Disable drag and drop, and selection for the filler image. var disabledListener = function( evt ) { if ( evt.preventDefault ) evt.preventDefault() ; else evt.returnValue = false ; } FCKTools.AddEventListener( filler, "dragstart", disabledListener ) ; FCKTools.AddEventListener( filler, "selectstart", disabledListener ) ; } var paddingBar = this._ResizeBar ; var offset = this._GetIframeOffset() ; var tablePos = this._GetTablePosition( w, table ) ; var barHeight = table.offsetHeight ; var barTop = offset.y + tablePos.y ; // Do not let the resize bar intrude into the toolbar area. if ( tablePos.y < 0 ) { barHeight += tablePos.y ; barTop -= tablePos.y ; } var bw = parseInt( table.border, 10 ) ; if ( isNaN( bw ) ) bw = 0 ; var cs = parseInt( table.cellSpacing, 10 ) ; if ( isNaN( cs ) ) cs = 0 ; var barWidth = Math.max( bw+100, cs+100 ) ; var paddingStyles = { 'top' : barTop + 'px', 'height' : barHeight + 'px', 'width' : barWidth + 'px', 'left' : ( offset.x + mouse.x + FCKTools.GetScrollPosition( w ).X - barWidth / 2 ) + 'px' } ; if ( FCKBrowserInfo.IsIE ) paddingBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 10 ; else paddingStyles.opacity = 0.1 ; FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; var filler = paddingBar.getElementsByTagName( "img" )[0] ; FCKDomTools.SetElementStyles( filler, { width : paddingBar.offsetWidth + 'px', height : barHeight + 'px' } ) ; barWidth = Math.max( bw, cs, 3 ) ; var visibleBar = null ; if ( paddingBar.getElementsByTagName( "div" ).length < 1 ) { visibleBar = this._doc.createElement( "div" ) ; this._avoidStyles( visibleBar ); visibleBar.setAttribute('_fcktemp', true); paddingBar.appendChild( visibleBar ) ; } else visibleBar = paddingBar.getElementsByTagName( "div" )[0] ; FCKDomTools.SetElementStyles( visibleBar, { position : 'absolute', backgroundColor : 'blue', width : barWidth + 'px', height : barHeight + 'px', left : '50px', top : '0px' } ) ; }, "_HideResizeBar" : function() { if ( this._ResizeBar ) // IE bug: display : none does not hide the resize bar for some reason. // so set the position to somewhere invisible. FCKDomTools.SetElementStyles( this._ResizeBar, { top : '-100000px', left : '-100000px' } ) ; }, "_GetIframeOffset" : function () { return FCKTools.GetDocumentPosition( window, FCK.EditingArea.IFrame ) ; }, "_GetTablePosition" : function ( w, table ) { return FCKTools.GetWindowPosition( w, table ) ; }, "_avoidStyles" : function( element ) { FCKDomTools.SetElementStyles( element, { padding : '0', backgroundImage : 'none', border : '0' } ) ; }, "Reset" : function() { FCKDragTableHandler._LeftCell = FCKDragTableHandler._RightCell = FCKDragTableHandler._TableMap = null ; } }; FCK.Events.AttachEvent( "OnMouseMove", FCKDragTableHandler.MouseMoveListener ) ; FCK.Events.AttachEvent( "OnAfterSetHTML", FCKDragTableHandler.Reset ) ;
JavaScript
FCKLang['DlgSyntaxHighLighterTitle'] = '插入语法高亮代码'; FCKLang['DlgSyntaxHighLighterProperty'] = '语法高亮代码属性'; FCKLang['DlgSyntaxHighLighterSelectLang'] = '语言'; FCKLang['DlgSyntaxHighLighterCoding'] = '代码'; FCKLang['DlgSyntaxHighLighterErrLang'] = '请选择一种语言'; FCKLang['DlgSyntaxHighLighterErrEmpty'] = '代码不能为空';
JavaScript
FCKLang['DlgSyntaxHighLighterTitle'] = 'Insert highLight code'; FCKLang['DlgSyntaxHighLighterProperty'] = 'HighLight Properties'; FCKLang['DlgSyntaxHighLighterSelectLang'] = 'Lang'; FCKLang['DlgSyntaxHighLighterCoding'] = 'Code'; FCKLang['DlgSyntaxHighLighterErrLang'] = 'Please select a language'; FCKLang['DlgSyntaxHighLighterErrEmpty'] = 'Coding can\'t empty';
JavaScript
window.onload = function () { dp.SyntaxHighlighter.ClipboardSwf = 'Scripts/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code'); }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Plugin: automatically resizes the editor until a configurable maximun * height (FCKConfig.AutoGrowMax), based on its contents. */ var FCKAutoGrow = { MIN_HEIGHT : window.frameElement.offsetHeight, Check : function() { var delta = FCKAutoGrow.GetHeightDelta() ; if ( delta != 0 ) { var newHeight = window.frameElement.offsetHeight + delta ; newHeight = FCKAutoGrow.GetEffectiveHeight( newHeight ) ; if ( newHeight != window.frameElement.height ) { window.frameElement.style.height = newHeight + "px" ; // Gecko browsers use an onresize handler to update the innermost // IFRAME's height. If the document is modified before the onresize // is triggered, the plugin will miscalculate the new height. Thus, // forcibly trigger onresize. #1336 if ( typeof window.onresize == 'function' ) { window.onresize() ; } } } }, CheckEditorStatus : function( sender, status ) { if ( status == FCK_STATUS_COMPLETE ) FCKAutoGrow.Check() ; }, GetEffectiveHeight : function( height ) { if ( height < FCKAutoGrow.MIN_HEIGHT ) height = FCKAutoGrow.MIN_HEIGHT; else { var max = FCKConfig.AutoGrowMax; if ( max && max > 0 && height > max ) height = max; } return height; }, GetHeightDelta : function() { var oInnerDoc = FCK.EditorDocument ; var iFrameHeight ; var iInnerHeight ; if ( FCKBrowserInfo.IsIE ) { iFrameHeight = FCK.EditorWindow.frameElement.offsetHeight ; iInnerHeight = oInnerDoc.body.scrollHeight ; } else { iFrameHeight = FCK.EditorWindow.innerHeight ; iInnerHeight = oInnerDoc.body.offsetHeight + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-top' ), 10 ) || 0 ) + ( parseInt( FCKDomTools.GetCurrentElementStyle( oInnerDoc.body, 'margin-bottom' ), 10 ) || 0 ) ; } return iInnerHeight - iFrameHeight ; }, SetListeners : function() { if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ) return ; FCK.EditorWindow.attachEvent( 'onscroll', FCKAutoGrow.Check ) ; FCK.EditorDocument.attachEvent( 'onkeyup', FCKAutoGrow.Check ) ; } }; FCK.AttachToOnSelectionChange( FCKAutoGrow.Check ) ; if ( FCKBrowserInfo.IsIE ) FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKAutoGrow.SetListeners ) ; FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow.CheckEditorStatus ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is a sample implementation for a custom Data Processor for basic BBCode. */ FCK.DataProcessor = { /* * Returns a string representing the HTML format of "data". The returned * value will be loaded in the editor. * The HTML must be from <html> to </html>, eventually including * the DOCTYPE. * @param {String} data The data to be converted in the * DataProcessor specific format. */ ConvertToHtml : function( data ) { // Convert < and > to their HTML entities. data = data.replace( /</g, '&lt;' ) ; data = data.replace( />/g, '&gt;' ) ; // Convert line breaks to <br>. data = data.replace( /(?:\r\n|\n|\r)/g, '<br>' ) ; // [url] data = data.replace( /\[url\](.+?)\[\/url]/gi, '<a href="$1">$1</a>' ) ; data = data.replace( /\[url\=([^\]]+)](.+?)\[\/url]/gi, '<a href="$1">$2</a>' ) ; // [b] data = data.replace( /\[b\](.+?)\[\/b]/gi, '<b>$1</b>' ) ; // [i] data = data.replace( /\[i\](.+?)\[\/i]/gi, '<i>$1</i>' ) ; // [u] data = data.replace( /\[u\](.+?)\[\/u]/gi, '<u>$1</u>' ) ; return '<html><head><title></title></head><body>' + data + '</body></html>' ; }, /* * Converts a DOM (sub-)tree to a string in the data format. * @param {Object} rootNode The node that contains the DOM tree to be * converted to the data format. * @param {Boolean} excludeRoot Indicates that the root node must not * be included in the conversion, only its children. * @param {Boolean} format Indicates that the data must be formatted * for human reading. Not all Data Processors may provide it. */ ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format ) { var data = rootNode.innerHTML ; // Convert <br> to line breaks. data = data.replace( /<br(?=[ \/>]).*?>/gi, '\r\n') ; // [url] data = data.replace( /<a .*?href=(["'])(.+?)\1.*?>(.+?)<\/a>/gi, '[url=$2]$3[/url]') ; // [b] data = data.replace( /<(?:b|strong)>/gi, '[b]') ; data = data.replace( /<\/(?:b|strong)>/gi, '[/b]') ; // [i] data = data.replace( /<(?:i|em)>/gi, '[i]') ; data = data.replace( /<\/(?:i|em)>/gi, '[/i]') ; // [u] data = data.replace( /<u>/gi, '[u]') ; data = data.replace( /<\/u>/gi, '[/u]') ; // Remove remaining tags. data = data.replace( /<[^>]+>/g, '') ; return data ; }, /* * Makes any necessary changes to a piece of HTML for insertion in the * editor selection position. * @param {String} html The HTML to be fixed. */ FixHtml : function( html ) { return html ; } } ; // This Data Processor doesn't support <p>, so let's use <br>. FCKConfig.EnterMode = 'br' ; // To avoid pasting invalid markup (which is discarded in any case), let's // force pasting to plain text. FCKConfig.ForcePasteAsPlainText = true ; // Rename the "Source" buttom to "BBCode". FCKToolbarItems.RegisterItem( 'Source', new FCKToolbarButton( 'Source', 'BBCode', null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ) ; // Let's enforce the toolbar to the limits of this Data Processor. A custom // toolbar set may be defined in the configuration file with more or less entries. FCKConfig.ToolbarSets["Default"] = [ ['Source'], ['Bold','Italic','Underline','-','Link'], ['About'] ] ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Sample custom configuration settings used by the BBCode plugin. It simply * loads the plugin. All the rest is done by the plugin itself. */ // Add the BBCode plugin. FCKConfig.Plugins.Add( 'bbcode' ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This plugin register the required Toolbar items to be able to insert the * table commands in the toolbar. */ FCKToolbarItems.RegisterItem( 'TableInsertRowAfter' , new FCKToolbarButton( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, null, null, null, true, 62 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteRows' , new FCKToolbarButton( 'TableDeleteRows' , FCKLang.DeleteRows, null, null, null, true, 63 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertColumnAfter' , new FCKToolbarButton( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, null, null, null, true, 64 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteColumns' , new FCKToolbarButton( 'TableDeleteColumns', FCKLang.DeleteColumns, null, null, null, true, 65 ) ) ; FCKToolbarItems.RegisterItem( 'TableInsertCellAfter' , new FCKToolbarButton( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, null, null, null, true, 58 ) ) ; FCKToolbarItems.RegisterItem( 'TableDeleteCells' , new FCKToolbarButton( 'TableDeleteCells' , FCKLang.DeleteCells, null, null, null, true, 59 ) ) ; FCKToolbarItems.RegisterItem( 'TableMergeCells' , new FCKToolbarButton( 'TableMergeCells' , FCKLang.MergeCells, null, null, null, true, 60 ) ) ; FCKToolbarItems.RegisterItem( 'TableHorizontalSplitCell' , new FCKToolbarButton( 'TableHorizontalSplitCell' , FCKLang.SplitCell, null, null, null, true, 61 ) ) ; FCKToolbarItems.RegisterItem( 'TableCellProp' , new FCKToolbarButton( 'TableCellProp' , FCKLang.CellProperties, null, null, null, true, 57 ) ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This plugin register Toolbar items for the combos modifying the style to * not show the box. */ FCKToolbarItems.RegisterItem( 'SourceSimple' , new FCKToolbarButton( 'Source', FCKLang.Source, null, FCK_TOOLBARITEM_ONLYICON, true, true, 1 ) ) ; FCKToolbarItems.RegisterItem( 'StyleSimple' , new FCKToolbarStyleCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontNameSimple' , new FCKToolbarFontsCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontSizeSimple' , new FCKToolbarFontSizeCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ; FCKToolbarItems.RegisterItem( 'FontFormatSimple', new FCKToolbarFontFormatCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Common objects and functions shared by all pages that compose the * File Browser dialog window. */ // Automatically detect the correct document.domain (#1919). (function() { var d = document.domain ; while ( true ) { // Test if we can access a parent property. try { var test = window.top.opener.document.domain ; break ; } catch( e ) {} // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... d = d.replace( /.*?(?:\.|$)/, '' ) ; if ( d.length == 0 ) break ; // It was not able to detect the domain. try { document.domain = d ; } catch (e) { break ; } } })() ; function AddSelectOption( selectElement, optionText, optionValue ) { var oOption = document.createElement("OPTION") ; oOption.text = optionText ; oOption.value = optionValue ; selectElement.options.add(oOption) ; return oOption ; } var oConnector = window.parent.oConnector ; var oIcons = window.parent.oIcons ; function StringBuilder( value ) { this._Strings = new Array( value || '' ) ; } StringBuilder.prototype.Append = function( value ) { if ( value ) this._Strings.push( value ) ; } StringBuilder.prototype.ToString = function() { return this._Strings.join( '' ) ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Defines the FCKXml object that is used for XML data calls * and XML processing. * * This script is shared by almost all pages that compose the * File Browser frameset. */ var FCKXml = function() {} FCKXml.prototype.GetHttpRequest = function() { // Gecko / IE7 try { return new XMLHttpRequest(); } catch(e) {} // IE6 try { return new ActiveXObject( 'Msxml2.XMLHTTP' ) ; } catch(e) {} // IE5 try { return new ActiveXObject( 'Microsoft.XMLHTTP' ) ; } catch(e) {} return null ; } FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer ) { var oFCKXml = this ; var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ; var oXmlHttp = this.GetHttpRequest() ; oXmlHttp.open( "GET", urlToCall, bAsync ) ; if ( bAsync ) { oXmlHttp.onreadystatechange = function() { if ( oXmlHttp.readyState == 4 ) { var oXml ; try { // this is the same test for an FF2 bug as in fckxml_gecko.js // but we've moved the responseXML assignment into the try{} // so we don't even have to check the return status codes. var test = oXmlHttp.responseXML.firstChild ; oXml = oXmlHttp.responseXML ; } catch ( e ) { try { oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ; } catch ( e ) {} } if ( !oXml || !oXml.firstChild || oXml.firstChild.nodeName == 'parsererror' ) { alert( 'The server didn\'t send back a proper XML response. Please contact your system administrator.\n\n' + 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')\n\n' + 'Requested URL:\n' + urlToCall + '\n\n' + 'Response text:\n' + oXmlHttp.responseText ) ; return ; } oFCKXml.DOMDocument = oXml ; asyncFunctionPointer( oFCKXml ) ; } } } oXmlHttp.send( null ) ; if ( ! bAsync ) { if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ) this.DOMDocument = oXmlHttp.responseXML ; else { alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; } } } FCKXml.prototype.SelectNodes = function( xpath ) { if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE return this.DOMDocument.selectNodes( xpath ) ; else // Gecko { var aNodeArray = new Array(); var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ; if ( xPathResult ) { var oNode = xPathResult.iterateNext() ; while( oNode ) { aNodeArray[aNodeArray.length] = oNode ; oNode = xPathResult.iterateNext(); } } return aNodeArray ; } } FCKXml.prototype.SelectSingleNode = function( xpath ) { if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE return this.DOMDocument.selectSingleNode( xpath ) ; else // Gecko { var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null); if ( xPathResult && xPathResult.singleNodeValue ) return xPathResult.singleNodeValue ; else return null ; } }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is the integration file for JavaScript. * * It defines the FCKeditor class that can be used to create editor * instances in a HTML page in the client side. For server side * operations, use the specific integration system. */ // FCKeditor Class var FCKeditor = function( instanceName, width, height, toolbarSet, value ) { // Properties this.InstanceName = instanceName ; this.Width = width || '100%' ; this.Height = height || '200' ; this.ToolbarSet = toolbarSet || 'Default' ; this.Value = value || '' ; this.BasePath = FCKeditor.BasePath ; this.CheckBrowser = true ; this.DisplayErrors = true ; this.Config = new Object() ; // Events this.OnError = null ; // function( source, errorNumber, errorDescription ) } /** * This is the default BasePath used by all editor instances. */ FCKeditor.BasePath = '/fckeditor/' ; /** * The minimum height used when replacing textareas. */ FCKeditor.MinHeight = 200 ; /** * The minimum width used when replacing textareas. */ FCKeditor.MinWidth = 750 ; FCKeditor.prototype.Version = '2.6.5' ; FCKeditor.prototype.VersionBuild = '23959' ; FCKeditor.prototype.Create = function() { document.write( this.CreateHtml() ) ; } FCKeditor.prototype.CreateHtml = function() { // Check for errors if ( !this.InstanceName || this.InstanceName.length == 0 ) { this._ThrowError( 701, 'You must specify an instance name.' ) ; return '' ; } var sHtml = '' ; if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) { sHtml += '<input type="hidden" id="' + this.InstanceName + '" name="' + this.InstanceName + '" value="' + this._HTMLEncode( this.Value ) + '" style="display:none" />' ; sHtml += this._GetConfigHtml() ; sHtml += this._GetIFrameHtml() ; } else { var sWidth = this.Width.toString().indexOf('%') > 0 ? this.Width : this.Width + 'px' ; var sHeight = this.Height.toString().indexOf('%') > 0 ? this.Height : this.Height + 'px' ; sHtml += '<textarea name="' + this.InstanceName + '" rows="4" cols="40" style="width:' + sWidth + ';height:' + sHeight ; if ( this.TabIndex ) sHtml += '" tabindex="' + this.TabIndex ; sHtml += '">' + this._HTMLEncode( this.Value ) + '<\/textarea>' ; } return sHtml ; } FCKeditor.prototype.ReplaceTextarea = function() { if ( document.getElementById( this.InstanceName + '___Frame' ) ) return ; if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) { // We must check the elements firstly using the Id and then the name. var oTextarea = document.getElementById( this.InstanceName ) ; var colElementsByName = document.getElementsByName( this.InstanceName ) ; var i = 0; while ( oTextarea || i == 0 ) { if ( oTextarea && oTextarea.tagName.toLowerCase() == 'textarea' ) break ; oTextarea = colElementsByName[i++] ; } if ( !oTextarea ) { alert( 'Error: The TEXTAREA with id or name set to "' + this.InstanceName + '" was not found' ) ; return ; } oTextarea.style.display = 'none' ; if ( oTextarea.tabIndex ) this.TabIndex = oTextarea.tabIndex ; this._InsertHtmlBefore( this._GetConfigHtml(), oTextarea ) ; this._InsertHtmlBefore( this._GetIFrameHtml(), oTextarea ) ; } } FCKeditor.prototype._InsertHtmlBefore = function( html, element ) { if ( element.insertAdjacentHTML ) // IE element.insertAdjacentHTML( 'beforeBegin', html ) ; else // Gecko { var oRange = document.createRange() ; oRange.setStartBefore( element ) ; var oFragment = oRange.createContextualFragment( html ); element.parentNode.insertBefore( oFragment, element ) ; } } FCKeditor.prototype._GetConfigHtml = function() { var sConfig = '' ; for ( var o in this.Config ) { if ( sConfig.length > 0 ) sConfig += '&amp;' ; sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.Config[o] ) ; } return '<input type="hidden" id="' + this.InstanceName + '___Config" value="' + sConfig + '" style="display:none" />' ; } FCKeditor.prototype._GetIFrameHtml = function() { var sFile = 'fckeditor.html' ; try { if ( (/fcksource=true/i).test( window.top.location.search ) ) sFile = 'fckeditor.original.html' ; } catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ } var sLink = this.BasePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.InstanceName ) ; if (this.ToolbarSet) sLink += '&amp;Toolbar=' + this.ToolbarSet ; var html = '<iframe id="' + this.InstanceName + '___Frame" src="' + sLink + '" width="' + this.Width + '" height="' + this.Height ; if ( this.TabIndex ) html += '" tabindex="' + this.TabIndex ; html += '" frameborder="0" scrolling="no"></iframe>' ; return html ; } FCKeditor.prototype._IsCompatibleBrowser = function() { return FCKeditor_IsCompatibleBrowser() ; } FCKeditor.prototype._ThrowError = function( errorNumber, errorDescription ) { this.ErrorNumber = errorNumber ; this.ErrorDescription = errorDescription ; if ( this.DisplayErrors ) { document.write( '<div style="COLOR: #ff0000">' ) ; document.write( '[ FCKeditor Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ; document.write( '</div>' ) ; } if ( typeof( this.OnError ) == 'function' ) this.OnError( this, errorNumber, errorDescription ) ; } FCKeditor.prototype._HTMLEncode = function( text ) { if ( typeof( text ) != "string" ) text = text.toString() ; text = text.replace( /&/g, "&amp;").replace( /"/g, "&quot;").replace( /</g, "&lt;").replace( />/g, "&gt;") ; return text ; } ;(function() { var textareaToEditor = function( textarea ) { var editor = new FCKeditor( textarea.name ) ; editor.Width = Math.max( textarea.offsetWidth, FCKeditor.MinWidth ) ; editor.Height = Math.max( textarea.offsetHeight, FCKeditor.MinHeight ) ; return editor ; } /** * Replace all <textarea> elements available in the document with FCKeditor * instances. * * // Replace all <textarea> elements in the page. * FCKeditor.ReplaceAllTextareas() ; * * // Replace all <textarea class="myClassName"> elements in the page. * FCKeditor.ReplaceAllTextareas( 'myClassName' ) ; * * // Selectively replace <textarea> elements, based on custom assertions. * FCKeditor.ReplaceAllTextareas( function( textarea, editor ) * { * // Custom code to evaluate the replace, returning false if it * // must not be done. * // It also passes the "editor" parameter, so the developer can * // customize the instance. * } ) ; */ FCKeditor.ReplaceAllTextareas = function() { var textareas = document.getElementsByTagName( 'textarea' ) ; for ( var i = 0 ; i < textareas.length ; i++ ) { var editor = null ; var textarea = textareas[i] ; var name = textarea.name ; // The "name" attribute must exist. if ( !name || name.length == 0 ) continue ; if ( typeof arguments[0] == 'string' ) { // The textarea class name could be passed as the function // parameter. var classRegex = new RegExp( '(?:^| )' + arguments[0] + '(?:$| )' ) ; if ( !classRegex.test( textarea.className ) ) continue ; } else if ( typeof arguments[0] == 'function' ) { // An assertion function could be passed as the function parameter. // It must explicitly return "false" to ignore a specific <textarea>. editor = textareaToEditor( textarea ) ; if ( arguments[0]( textarea, editor ) === false ) continue ; } if ( !editor ) editor = textareaToEditor( textarea ) ; editor.ReplaceTextarea() ; } } })() ; function FCKeditor_IsCompatibleBrowser() { var sAgent = navigator.userAgent.toLowerCase() ; // Internet Explorer 5.5+ if ( /*@cc_on!@*/false && sAgent.indexOf("mac") == -1 ) { var sBrowserVersion = navigator.appVersion.match(/MSIE (.\..)/)[1] ; return ( sBrowserVersion >= 5.5 ) ; } // Gecko (Opera 9 tries to behave like Gecko at this point). if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 && !( typeof(opera) == 'object' && opera.postError ) ) return true ; // Opera 9.50+ if ( window.opera && window.opera.version && parseFloat( window.opera.version() ) >= 9.5 ) return true ; // Adobe AIR // Checked before Safari because AIR have the WebKit rich text editor // features from Safari 3.0.4, but the version reported is 420. if ( sAgent.indexOf( ' adobeair/' ) != -1 ) return ( sAgent.match( / adobeair\/(\d+)/ )[1] >= 1 ) ; // Build must be at least v1 // Safari 3+ if ( sAgent.indexOf( ' applewebkit/' ) != -1 ) return ( sAgent.match( / applewebkit\/(\d+)/ )[1] >= 522 ) ; // Build must be at least 522 (v3) return false ; }
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/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.Plugins.Add( 'highlighter', 'zh-cn,en' ) ; FCKConfig.AutoGrowMax = 400 ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.EMailProtection = 'none' ; // none | encode | function FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'],['HighLighter'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 84 /*T*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ CTRL + 45 /*INS*/, true ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ SHIFT + 32 /*SPACE*/, 'Nbsp' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.BrowserContextMenu = false ; FCKConfig.EnableMoreFontColors = true ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ; FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'WSC' ; // 'WSC' | 'SCAYT' | 'SpellerPages' | 'ieSpell' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; // Attributes that will be removed FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'strong', Overrides : 'b' }, 'Italic' : { Element : 'em', Overrides : 'i' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }, 'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following two lines. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ; FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one FCKConfig.ImageUpload = true ; FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 210 ; FCKConfig.BackgroundBlockerColor = '#ffffff' ; FCKConfig.BackgroundBlockerOpacity = 0.50 ; FCKConfig.MsWebBrowserControlCompat = false ; FCKConfig.PreventSubmitHandler = false ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Sample custom configuration settings used in the plugin sample page (sample06). */ // Set our sample toolbar. FCKConfig.ToolbarSets['PluginTest'] = [ ['SourceSimple'], ['My_Find','My_Replace','-','Placeholder'], ['StyleSimple','FontFormatSimple','FontNameSimple','FontSizeSimple'], ['Table','-','TableInsertRowAfter','TableDeleteRows','TableInsertColumnAfter','TableDeleteColumns','TableInsertCellAfter','TableDeleteCells','TableMergeCells','TableHorizontalSplitCell','TableCellProp'], ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink'], '/', ['My_BigStyle','-','Smiley','-','About'] ] ; // Change the default plugin path. FCKConfig.PluginsPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + '_samples/_plugins/' ; // Add our plugin to the plugins list. // FCKConfig.Plugins.Add( pluginName, availableLanguages ) // pluginName: The plugin name. The plugin directory must match this name. // availableLanguages: a list of available language files for the plugin (separated by a comma). FCKConfig.Plugins.Add( 'findreplace', 'en,fr,it' ) ; FCKConfig.Plugins.Add( 'samples' ) ; // If you want to use plugins found on other directories, just use the third parameter. var sOtherPluginPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + 'editor/plugins/' ; FCKConfig.Plugins.Add( 'placeholder', 'de,en,es,fr,it,pl', sOtherPluginPath ) ; FCKConfig.Plugins.Add( 'tablecommands', null, sOtherPluginPath ) ; FCKConfig.Plugins.Add( 'simplecommands', null, sOtherPluginPath ) ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'b' } ; FCKConfig.CoreStyles.Italic = { Element : 'i' } ; FCKConfig.CoreStyles.Underline = { Element : 'u' } ; FCKConfig.CoreStyles.StrikeThrough = { Element : 'strike' } ; /** * Font face */ // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'font', Attributes : { 'face' : '#("Font")' } } ; /** * Font sizes. */ FCKConfig.FontSizes = '1/xx-small;2/x-small;3/small;4/medium;5/large;6/x-large;7/xx-large' ; FCKConfig.CoreStyles.Size = { Element : 'font', Attributes : { 'size' : '#("Size")' } } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = true ; FCKConfig.CoreStyles.Color = { Element : 'font', Attributes : { 'color' : '#("Color")' } } ; FCKConfig.CoreStyles.BackColor = { Element : 'font', Styles : { 'background-color' : '#("Color","color")' } } ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { 'Computer Code' : { Element : 'code' }, 'Keyboard Phrase' : { Element : 'kbd' }, 'Sample Text' : { Element : 'samp' }, 'Variable' : { Element : 'var' }, 'Deleted Text' : { Element : 'del' }, 'Inserted Text' : { Element : 'ins' }, 'Cited Work' : { Element : 'cite' }, 'Inline Quotation' : { Element : 'q' } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'b' } ; FCKConfig.CoreStyles.Italic = { Element : 'i' } ; FCKConfig.CoreStyles.Underline = { Element : 'u' } ; /** * Font face */ // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'font', Attributes : { 'face' : '#("Font")' } } ; /** * Font sizes. * The CSS part of the font sizes isn't used by Flash, it is there to get the * font rendered correctly in FCKeditor. */ FCKConfig.FontSizes = '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px' ; FCKConfig.CoreStyles.Size = { Element : 'font', Attributes : { 'size' : '#("Size")' }, Styles : { 'font-size' : '#("Size","fontSize")' } } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = true ; FCKConfig.CoreStyles.Color = { Element : 'font', Attributes : { 'color' : '#("Color")' } } ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { } ; /** * Toolbar set for Flash HTML editing. */ FCKConfig.ToolbarSets['Flash'] = [ ['Source','-','Bold','Italic','Underline','-','UnorderedList','-','Link','Unlink'], ['FontName','FontSize','-','About'] ] ; /** * Flash specific formatting settings. */ FCKConfig.EditorAreaStyles = 'p, ol, ul {margin-top: 0px; margin-bottom: 0px;}' ; FCKConfig.FormatSource = false ; FCKConfig.FormatOutput = false ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration settings used by the XHTML 1.1 sample page (sample14.html). */ // Our intention is force all formatting features to use CSS classes or // semantic aware elements. // Load our custom CSS files for this sample. // We are using "BasePath" just for this sample convenience. In normal // situations it would be just pointed to the file directly, // like "/css/myfile.css". FCKConfig.EditorAreaCSS = FCKConfig.BasePath + '../_samples/html/assets/sample14.styles.css' ; /** * Core styles. */ FCKConfig.CoreStyles.Bold = { Element : 'span', Attributes : { 'class' : 'Bold' } } ; FCKConfig.CoreStyles.Italic = { Element : 'span', Attributes : { 'class' : 'Italic' } } ; FCKConfig.CoreStyles.Underline = { Element : 'span', Attributes : { 'class' : 'Underline' } } ; FCKConfig.CoreStyles.StrikeThrough = { Element : 'span', Attributes : { 'class' : 'StrikeThrough' } } ; /** * Font face */ // List of fonts available in the toolbar combo. Each font definition is // separated by a semi-colon (;). We are using class names here, so each font // is defined by {Class Name}/{Combo Label}. FCKConfig.FontNames = 'FontComic/Comic Sans MS;FontCourier/Courier New;FontTimes/Times New Roman' ; // Define the way font elements will be applied to the document. The "span" // element will be used. When a font is selected, the font name defined in the // above list is passed to this definition with the name "Font", being it // injected in the "class" attribute. // We must also instruct the editor to replace span elements that are used to // set the font (Overrides). FCKConfig.CoreStyles.FontFace = { Element : 'span', Attributes : { 'class' : '#("Font")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Comic|Courier|Times)$/ } } ] } ; /** * Font sizes. */ FCKConfig.FontSizes = 'FontSmaller/Smaller;FontLarger/Larger;FontSmall/8pt;FontBig/14pt;FontDouble/Double Size' ; FCKConfig.CoreStyles.Size = { Element : 'span', Attributes : { 'class' : '#("Size")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Smaller|Larger|Small|Big|Double)$/ } } ] } ; /** * Font colors. */ FCKConfig.EnableMoreFontColors = false ; FCKConfig.FontColors = 'ff9900/FontColor1,0066cc/FontColor2,ff0000/FontColor3' ; FCKConfig.CoreStyles.Color = { Element : 'span', Attributes : { 'class' : '#("Color")' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)$/ } } ] } ; FCKConfig.CoreStyles.BackColor = { Element : 'span', Attributes : { 'class' : '#("Color")BG' }, Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)BG$/ } } ] } ; /** * Indentation. */ FCKConfig.IndentClasses = [ 'Indent1', 'Indent2', 'Indent3' ] ; /** * Paragraph justification. */ FCKConfig.JustifyClasses = [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull' ] ; /** * Styles combo. */ FCKConfig.StylesXmlPath = '' ; FCKConfig.CustomStyles = { 'Strong Emphasis' : { Element : 'strong' }, 'Emphasis' : { Element : 'em' }, 'Computer Code' : { Element : 'code' }, 'Keyboard Phrase' : { Element : 'kbd' }, 'Sample Text' : { Element : 'samp' }, 'Variable' : { Element : 'var' }, 'Deleted Text' : { Element : 'del' }, 'Inserted Text' : { Element : 'ins' }, 'Cited Work' : { Element : 'cite' }, 'Inline Quotation' : { Element : 'q' } } ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is the sample plugin definition file. */ // Register the related commands. FCKCommands.RegisterCommand( 'My_Find' , new FCKDialogCommand( FCKLang['DlgMyFindTitle'] , FCKLang['DlgMyFindTitle'] , FCKConfig.PluginsPath + 'findreplace/find.html' , 340, 170 ) ) ; FCKCommands.RegisterCommand( 'My_Replace' , new FCKDialogCommand( FCKLang['DlgMyReplaceTitle'], FCKLang['DlgMyReplaceTitle'] , FCKConfig.PluginsPath + 'findreplace/replace.html', 340, 200 ) ) ; // Create the "Find" toolbar button. var oFindItem = new FCKToolbarButton( 'My_Find', FCKLang['DlgMyFindTitle'] ) ; oFindItem.IconPath = FCKConfig.PluginsPath + 'findreplace/find.gif' ; FCKToolbarItems.RegisterItem( 'My_Find', oFindItem ) ; // 'My_Find' is the name used in the Toolbar config. // Create the "Replace" toolbar button. var oReplaceItem = new FCKToolbarButton( 'My_Replace', FCKLang['DlgMyReplaceTitle'] ) ; oReplaceItem.IconPath = FCKConfig.PluginsPath + 'findreplace/replace.gif' ; FCKToolbarItems.RegisterItem( 'My_Replace', oReplaceItem ) ; // 'My_Replace' is the name used in the Toolbar config.
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Italian language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Sostituisci' ; FCKLang['DlgMyReplaceFindLbl'] = 'Trova:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Sostituisci con:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Maiuscole/minuscole' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Sostituisci' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Sostituisci tutto' ; FCKLang['DlgMyReplaceWordChk'] = 'Parola intera' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Cerca' ; FCKLang['DlgMyFindFindBtn'] = 'Cerca' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * French language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Remplacer' ; FCKLang['DlgMyReplaceFindLbl'] = 'Chercher:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Remplacer par:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Respecter la casse' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Remplacer' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Remplacer Tout' ; FCKLang['DlgMyReplaceWordChk'] = 'Mot entier' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Chercher' ; FCKLang['DlgMyFindFindBtn'] = 'Chercher' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * English language file for the sample plugin. */ FCKLang['DlgMyReplaceTitle'] = 'Plugin - Replace' ; FCKLang['DlgMyReplaceFindLbl'] = 'Find what:' ; FCKLang['DlgMyReplaceReplaceLbl'] = 'Replace with:' ; FCKLang['DlgMyReplaceCaseChk'] = 'Match case' ; FCKLang['DlgMyReplaceReplaceBtn'] = 'Replace' ; FCKLang['DlgMyReplaceReplAllBtn'] = 'Replace All' ; FCKLang['DlgMyReplaceWordChk'] = 'Match whole word' ; FCKLang['DlgMyFindTitle'] = 'Plugin - Find' ; FCKLang['DlgMyFindFindBtn'] = 'Find' ;
JavaScript
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * This is a sample plugin definition file. */ // Here we define our custom Style combo, with custom widths. var oMyBigStyleCombo = new FCKToolbarStyleCombo() ; oMyBigStyleCombo.FieldWidth = 250 ; oMyBigStyleCombo.PanelWidth = 300 ; FCKToolbarItems.RegisterItem( 'My_BigStyle', oMyBigStyleCombo ) ; // ##### Defining a custom context menu entry. // ## 1. Define the command to be executed when selecting the context menu item. var oMyCMCommand = new Object() ; oMyCMCommand.Name = 'OpenImage' ; // This is the standard function used to execute the command (called when clicking in the context menu item). oMyCMCommand.Execute = function() { // This command is called only when an image element is selected (IMG). // Get image URL (src). var sUrl = FCKSelection.GetSelectedElement().src ; // Open the URL in a new window. window.top.open( sUrl ) ; } // This is the standard function used to retrieve the command state (it could be disabled for some reason). oMyCMCommand.GetState = function() { // Let's make it always enabled. return FCK_TRISTATE_OFF ; } // ## 2. Register our custom command. FCKCommands.RegisterCommand( 'OpenImage', oMyCMCommand ) ; // ## 3. Define the context menu "listener". var oMyContextMenuListener = new Object() ; // This is the standard function called right before sowing the context menu. oMyContextMenuListener.AddItems = function( contextMenu, tag, tagName ) { // Let's show our custom option only for images. if ( tagName == 'IMG' ) { contextMenu.AddSeparator() ; contextMenu.AddItem( 'OpenImage', 'Open image in a new window (Custom)' ) ; } } // ## 4. Register our context menu listener. FCK.ContextMenu.RegisterListener( oMyContextMenuListener ) ;
JavaScript
<!-- '下拉框检查' Function Check_ListBox(Value,ErrMsg) If value<1 Then Check_ListBox=ErrMsg Else Check_ListBox="" End If End Function '单/复选框检查' Function Check_SelectBox(RadioObject,ErrMsg) Dim Radio,blCheck blCheck=False For Each Radio in RadioObject If Radio.checked=True Then blCheck=True End if Next If blCheck=False Then Check_SelectBox=ErrMsg Else Check_SelectBox="" End If End Function '字符长度验证' Function CharLen(Value,MinLen,MaxLen,ErrMsg) If Len(value)<MinLen Or Len(value)>MaxLen Then CharLen=ErrMsg Else CharLen="" End If End Function '数字验证' Function IsNum(Value,MinValue,MaxValue,ErrMsg) If isNumeric(Value)=false Then IsNum=ErrMsg Else If CCur(Value)>=CCur(MinValue) and CCur(Value)<=CCur(MaxValue) Then IsNum="" Else IsNum=ErrMsg End IF End If End Function '日期验证' Function IsDateTime(Value,MinValue,MaxValue,ErrMsg) If isDate(Value)=false Then IsDateTime=ErrMsg Else IsDateTime="" End If End Function '邮箱验证' Function IsMail(Value,MinLen,MaxLen,ErrMsg) Dim Regu,Re,Matches,InfoCout Regu="^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$" Set Re = new RegExp Re.Pattern =Regu Re.Global = True '设置全局可用性。' Set Matches = Re.Execute(Value) '执行搜索。' InfoCout=Matches.count If InfoCout =0 Then IsMail=ErrMsg Else IsMail="" End If Set Re =Nothing End Function sub MinClassBox(strMinValue,SpanID,SelectName,FieldValue) If strMinValue="" Then SpanID.innerHTML="" Exit Sub End IF Dim ArrMinClass,MinClass,strSelect,strSelected ArrMinClass=Split(strMinValue,",") For Each MinClass in ArrMinClass IF FieldValue=Split(MinClass,"|")(0) Then strSelected="selected=""selected""" else strSelected="" End IF strSelect=strSelect & "<option " & strSelected & " value=""" & Split(MinClass,"|")(0) & """>" & Split(MinClass,"|")(1) & "</option>" Next SpanID.innerHTML=" 小类:<select name=""" & SelectName & """ >" & strSelect & "</select>" End sub -->
JavaScript
function atCalendarControl(){ var calendar=this; this.calendarPad=null; this.prevMonth=null; this.nextMonth=null; this.prevYear=null; this.nextYear=null; this.goToday=null; this.calendarClose=null; this.calendarAbout=null; this.head=null; this.body=null; this.today=[]; this.currentDate=[]; this.sltDate; this.target; this.source; /************** 加入日历底板及阴影 *********************/ this.addCalendarPad=function(){ document.write("<div id='divCalendarpad' style='position:absolute;top:100;left:0;width:255;height:187;display:none;'>"); document.write("<iframe frameborder=0 height=189 width=250></iframe>"); document.write("<div style='position:absolute;top:2;left:2;width:250;height:187;background-color:#336699;'></div>"); document.write("</div>"); calendar.calendarPad=document.all.divCalendarpad; } /************** 加入日历面板 *********************/ this.addCalendarBoard=function(){ var BOARD=this; var divBoard=document.createElement("div"); calendar.calendarPad.insertAdjacentElement("beforeEnd",divBoard); divBoard.style.cssText="position:absolute;top:0;left:0;width:250;height:187;border:0 outset;background-color:buttonface;"; var tbBoard=document.createElement("table"); divBoard.insertAdjacentElement("beforeEnd",tbBoard); tbBoard.style.cssText="position:absolute;top:2;left:2;width:248;height:10;font-size:9pt;"; tbBoard.cellPadding=0; tbBoard.cellSpacing=1; /************** 设置各功能按钮的功能 *********************/ /*********** Calendar About Button ***************/ trRow = tbBoard.insertRow(0); calendar.calendarAbout=calendar.insertTbCell(trRow,0,"-","center"); calendar.calendarAbout.title="帮助 快捷键:H"; calendar.calendarAbout.onclick=function(){calendar.about();} /*********** Calendar Head ***************/ tbCell=trRow.insertCell(1); tbCell.colSpan=5; tbCell.bgColor="#99CCFF"; tbCell.align="center"; tbCell.style.cssText = "cursor:default"; calendar.head=tbCell; /*********** Calendar Close Button ***************/ tbCell=trRow.insertCell(2); calendar.calendarClose = calendar.insertTbCell(trRow,2,"x","center"); calendar.calendarClose.title="关闭 快捷键:ESC或X"; calendar.calendarClose.onclick=function(){calendar.hide();} /*********** Calendar PrevYear Button ***************/ trRow = tbBoard.insertRow(1); calendar.prevYear = calendar.insertTbCell(trRow,0,"<<","center"); calendar.prevYear.title="上一年 快捷键:↑"; calendar.prevYear.onmousedown=function(){ calendar.currentDate[0]--; calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar PrevMonth Button ***************/ calendar.prevMonth = calendar.insertTbCell(trRow,1,"<","center"); calendar.prevMonth.title="上一月 快捷键:←"; calendar.prevMonth.onmousedown=function(){ calendar.currentDate[1]--; if(calendar.currentDate[1]==0){ calendar.currentDate[1]=12; calendar.currentDate[0]--; } calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar Today Button ***************/ calendar.goToday = calendar.insertTbCell(trRow,2,"今天","center",3); calendar.goToday.title="选择今天 快捷键:T"; calendar.goToday.onclick=function(){ if(calendar.returnTime) calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2])+" "+calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4]) else calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]); calendar.target.value=calendar.sltDate; calendar.hide(); //calendar.show(calendar.target,calendar.today[0]+"-"+calendar.today[1]+"-"+calendar.today[2],calendar.source); } /*********** Calendar NextMonth Button ***************/ calendar.nextMonth = calendar.insertTbCell(trRow,3,">","center"); calendar.nextMonth.title="下一月 快捷键:→"; calendar.nextMonth.onmousedown=function(){ calendar.currentDate[1]++; if(calendar.currentDate[1]==13){ calendar.currentDate[1]=1; calendar.currentDate[0]++; } calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar NextYear Button ***************/ calendar.nextYear = calendar.insertTbCell(trRow,4,">>","center"); calendar.nextYear.title="下一年 快捷键:↓"; calendar.nextYear.onmousedown=function(){ calendar.currentDate[0]++; calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } trRow = tbBoard.insertRow(2); var cnDateName = new Array("日","一","二","三","四","五","六"); for (var i = 0; i < 7; i++) { tbCell=trRow.insertCell(i) tbCell.innerText=cnDateName[i]; tbCell.align="center"; tbCell.width=35; tbCell.style.cssText="cursor:default;border:1 solid #99CCCC;background-color:#99CCCC;"; } /*********** Calendar Body ***************/ trRow = tbBoard.insertRow(3); tbCell=trRow.insertCell(0); tbCell.colSpan=7; tbCell.height=97; tbCell.vAlign="top"; tbCell.bgColor="#F0F0F0"; var tbBody=document.createElement("table"); tbCell.insertAdjacentElement("beforeEnd",tbBody); tbBody.style.cssText="position:relative;top:0;left:0;width:245;height:103;font-size:9pt;" tbBody.cellPadding=0; tbBody.cellSpacing=1; calendar.body=tbBody; /*********** Time Body ***************/ trRow = tbBoard.insertRow(4); tbCell=trRow.insertCell(0); calendar.prevHours = calendar.insertTbCell(trRow,0,"-","center"); calendar.prevHours.title="小时调整 快捷键:Home"; calendar.prevHours.onmousedown=function(){ calendar.currentDate[3]--; if(calendar.currentDate[3]==-1) calendar.currentDate[3]=23; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(1); calendar.nextHours = calendar.insertTbCell(trRow,1,"+","center"); calendar.nextHours.title="小时调整 快捷键:End"; calendar.nextHours.onmousedown=function(){ calendar.currentDate[3]++; if(calendar.currentDate[3]==24) calendar.currentDate[3]=0; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(2); tbCell.colSpan=3; tbCell.bgColor="#99CCFF"; tbCell.align="center"; tbCell.style.cssText = "cursor:default"; calendar.bottom=tbCell; tbCell=trRow.insertCell(3); calendar.prevMinutes = calendar.insertTbCell(trRow,3,"-","center"); calendar.prevMinutes.title="分钟调整 快捷键:PageUp"; calendar.prevMinutes.onmousedown=function(){ calendar.currentDate[4]--; if(calendar.currentDate[4]==-1) calendar.currentDate[4]=59; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(4); calendar.nextMinutes = calendar.insertTbCell(trRow,4,"+","center"); calendar.nextMinutes.title="分钟调整 快捷键:PageDown"; calendar.nextMinutes.onmousedown=function(){ calendar.currentDate[4]++; if(calendar.currentDate[4]==60) calendar.currentDate[4]=0; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } } /************** 加入功能按钮公共样式 *********************/ this.insertTbCell=function(trRow,cellIndex,TXT,trAlign,tbColSpan){ var tbCell=trRow.insertCell(cellIndex); if(tbColSpan!=undefined) tbCell.colSpan=tbColSpan; var btnCell=document.createElement("button"); tbCell.insertAdjacentElement("beforeEnd",btnCell); btnCell.value=TXT; btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;"; btnCell.onmouseover=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;"; } btnCell.onmouseout=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;"; } // btnCell.onmousedown=function(){ // btnCell.style.cssText="width:100%;border:1 inset;background-color:#F0F0F0;"; // } btnCell.onmouseup=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;"; } btnCell.onclick=function(){ btnCell.blur(); } return btnCell; } this.setDefaultDate=function(){ var dftDate=new Date(); calendar.today[0]=dftDate.getYear(); calendar.today[1]=dftDate.getMonth()+1; calendar.today[2]=dftDate.getDate(); calendar.today[3]=dftDate.getHours(); calendar.today[4]=dftDate.getMinutes(); } /****************** Show Calendar *********************/ this.show=function(targetObject,returnTime,defaultDate,sourceObject){ if(targetObject==undefined) { alert("未设置目标对象. \n方法: ATCALENDAR.show(obj 目标对象,boolean 是否返回时间,string 默认日期,obj 点击对象);\n\n目标对象:接受日期返回值的对象.\n默认日期:格式为\"yyyy-mm-dd\",缺省为当前日期.\n点击对象:点击这个对象弹出calendar,默认为目标对象.\n"); return false; } else calendar.target=targetObject; if(sourceObject==undefined) calendar.source=calendar.target; else calendar.source=sourceObject; if(returnTime) calendar.returnTime=true; else calendar.returnTime=false; var firstDay; var Cells=new Array(); if((defaultDate==undefined) || (defaultDate=="")){ var theDate=new Array(); calendar.head.innerText = calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]); calendar.bottom.innerText = calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4]); theDate[0]=calendar.today[0]; theDate[1]=calendar.today[1]; theDate[2]=calendar.today[2]; theDate[3]=calendar.today[3]; theDate[4]=calendar.today[4]; } else{ var Datereg=/^\d{4}-\d{1,2}-\d{2}$/ var DateTimereg=/^(\d{1,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})$/ if((!defaultDate.match(Datereg)) && (!defaultDate.match(DateTimereg))){ alert("默认日期(时间)的格式不正确!\t\n\n默认可接受格式为:\n1、yyyy-mm-dd \n2、yyyy-mm-dd hh:mm\n3、(空)"); calendar.setDefaultDate(); return; } if(defaultDate.match(Datereg)) defaultDate=defaultDate+" "+calendar.today[3]+":"+calendar.today[4]; var strDateTime=defaultDate.match(DateTimereg); var theDate=new Array(4) theDate[0]=strDateTime[1]; theDate[1]=strDateTime[2]; theDate[2]=strDateTime[3]; theDate[3]=strDateTime[4]; theDate[4]=strDateTime[5]; calendar.head.innerText = theDate[0]+"-"+calendar.formatTime(theDate[1])+"-"+calendar.formatTime(theDate[2]); calendar.bottom.innerText = calendar.formatTime(theDate[3])+":"+calendar.formatTime(theDate[4]); } calendar.currentDate[0]=theDate[0]; calendar.currentDate[1]=theDate[1]; calendar.currentDate[2]=theDate[2]; calendar.currentDate[3]=theDate[3]; calendar.currentDate[4]=theDate[4]; theFirstDay=calendar.getFirstDay(theDate[0],theDate[1]); theMonthLen=theFirstDay+calendar.getMonthLen(theDate[0],theDate[1]); //calendar.setEventKey(); calendar.calendarPad.style.display=""; var theRows = Math.ceil((theMonthLen)/7); //清除旧的日历; while (calendar.body.rows.length > 0) { calendar.body.deleteRow(0) } //建立新的日历; var n=0;day=0; for(i=0;i<theRows;i++){ theRow=calendar.body.insertRow(i); for(j=0;j<7;j++){ n++; if(n>theFirstDay && n<=theMonthLen){ day=n-theFirstDay; calendar.insertBodyCell(theRow,j,day); } else{ var theCell=theRow.insertCell(j); theCell.style.cssText="background-color:#F0F0F0;cursor:default;"; } } } //****************调整日历位置**************// var offsetPos=calendar.getAbsolutePos(calendar.source);//计算对象的位置; if((document.body.offsetHeight-(offsetPos.y+calendar.source.offsetHeight-document.body.scrollTop))<calendar.calendarPad.style.pixelHeight){ var calTop=offsetPos.y-calendar.calendarPad.style.pixelHeight; } else{ var calTop=offsetPos.y+calendar.source.offsetHeight; } if((document.body.offsetWidth-(offsetPos.x+calendar.source.offsetWidth-document.body.scrollLeft))>calendar.calendarPad.style.pixelWidth){ var calLeft=offsetPos.x; } else{ var calLeft=calendar.source.offsetLeft+calendar.source.offsetWidth; } //alert(offsetPos.x); calendar.calendarPad.style.pixelLeft=calLeft; calendar.calendarPad.style.pixelTop=calTop; } /****************** 计算对象的位置 *************************/ this.getAbsolutePos = function(el) { var r = { x: el.offsetLeft, y: el.offsetTop }; if (el.offsetParent) { var tmp = calendar.getAbsolutePos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; //************* 插入日期单元格 **************/ this.insertBodyCell=function(theRow,j,day,targetObject){ var theCell=theRow.insertCell(j); if(j==0) var theBgColor="#FF9999"; else var theBgColor="#FFFFFF"; if(day==calendar.currentDate[2]) var theBgColor="#CCCCCC"; if(day==calendar.today[2]) var theBgColor="#99FFCC"; theCell.bgColor=theBgColor; theCell.innerText=day; theCell.align="center"; theCell.width=35; theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;"; theCell.onmouseover=function(){ theCell.bgColor="#FFFFCC"; theCell.style.cssText="border:1 outset;cursor:hand;"; } theCell.onmouseout=function(){ theCell.bgColor=theBgColor; theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;"; } theCell.onmousedown=function(){ theCell.bgColor="#FFFFCC"; theCell.style.cssText="border:1 inset;cursor:hand;"; } theCell.onclick=function(){ if(calendar.returnTime) calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day)+" "+calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]) else calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day); calendar.target.value=calendar.sltDate; calendar.hide(); } } /************** 取得月份的第一天为星期几 *********************/ this.getFirstDay=function(theYear, theMonth){ var firstDate = new Date(theYear,theMonth-1,1); return firstDate.getDay(); } /************** 取得月份共有几天 *********************/ this.getMonthLen=function(theYear, theMonth) { theMonth--; var oneDay = 1000 * 60 * 60 * 24; var thisMonth = new Date(theYear, theMonth, 1); var nextMonth = new Date(theYear, theMonth + 1, 1); var len = Math.ceil((nextMonth.getTime() - thisMonth.getTime())/oneDay); return len; } /************** 隐藏日历 *********************/ this.hide=function(){ //calendar.clearEventKey(); calendar.calendarPad.style.display="none"; } /************** 从这里开始 *********************/ this.setup=function(defaultDate){ calendar.addCalendarPad(); calendar.addCalendarBoard(); calendar.setDefaultDate(); } /************** 格式化时间 *********************/ this.formatTime = function(str) { str = ("00"+str); return str.substr(str.length-2); } /************** 关于AgetimeCalendar *********************/ this.about=function(){ var strAbout = "\nWeb 日历选择输入控件操作说明:\n\n"; strAbout+="-\t: 关于\n"; strAbout+="x\t: 隐藏\n"; strAbout+="<<\t: 上一年\n"; strAbout+="<\t: 上一月\n"; strAbout+="今日\t: 返回当天日期\n"; strAbout+=">\t: 下一月\n"; strAbout+="<<\t: 下一年\n"; strAbout+="\nWeb日历选择输入控件\tVer:v1.0\t\nDesigned By:wxb \t\t2004.11.22\t\n"; alert(strAbout); } document.onkeydown=function(){ if(calendar.calendarPad.style.display=="none"){ window.event.returnValue= true; return true ; } switch(window.event.keyCode){ case 27 : calendar.hide(); break; //ESC case 37 : calendar.prevMonth.onmousedown(); break;//← case 38 : calendar.prevYear.onmousedown();break; //↑ case 39 : calendar.nextMonth.onmousedown(); break;//→ case 40 : calendar.nextYear.onmousedown(); break;//↓ case 84 : calendar.goToday.onclick(); break;//T case 88 : calendar.hide(); break; //X case 72 : calendar.about(); break; //H case 36 : calendar.prevHours.onmousedown(); break;//Home case 35 : calendar.nextHours.onmousedown(); break;//End case 33 : calendar.prevMinutes.onmousedown();break; //PageUp case 34 : calendar.nextMinutes.onmousedown(); break;//PageDown } window.event.keyCode = 0; window.event.returnValue= false; } calendar.setup(); } var CalendarWebControl = new atCalendarControl();
JavaScript
<!-- NS4 = (document.layers) ? 1 : 0; IE4 = (document.all) ? 1 : 0; ver4 = (NS4 || IE4) ? 1 : 0; function expandIt(index){//----------------------------------------- var menuitem=new Array() menuitem[1]=System_Child_1 menuitem[2]=System_Child_2 menuitem[3]=System_Child_3 if (menuitem[index].style.display=="block"){ displayall() } else { displayall() menuitem[index].style.display="block" } } function displayall(){//----------------------------------------------------------- System_Child_1.style .display ="none" System_Child_2.style .display ="none" System_Child_3.style .display ="none" } function arrange() { nextY = document.layers[firstInd].pageY +document.layers[firstInd].document.height; for (i=firstInd+1; i<document.layers.length; i++) { whichEl = document.layers[i]; if (whichEl.visibility != "hide") { whichEl.pageY = nextY; nextY += whichEl.document.height; } } } function initIt(){ if (!ver4) return; if (NS4) { for (i=0; i<document.layers.length; i++) { whichEl = document.layers[i]; if (whichEl.id.indexOf("Child") != -1) whichEl.visibility = "hide"; } arrange(); } else { divColl = document.all.tags("DIV"); for (i=0; i<divColl.length; i++) { whichEl = divColl(i); if (whichEl.className == "child") whichEl.style.display = "none"; } } } onload = initIt; //-->
JavaScript
<!-- /** * Calendar * @param beginYear 1990 * @param endYear 2010 * @param language 0(zh_cn)|1(en_us)|2(en_en)|3(zh_tw) * @param patternDelimiter "-" * @param date2StringPattern "yyyy-MM-dd" * @param string2DatePattern "ymd" * @version 1.0 build 2006-04-01 * @version 1.1 build 2006-12-17 * @author KimSoft (jinqinghua [at] gmail.com) * NOTE! you can use it free, but keep the copyright please * IMPORTANT:you must include this script file inner html body elment */ function Calendar(beginYear, endYear, language, patternDelimiter, date2StringPattern, string2DatePattern) { this.beginYear = beginYear || 1990; this.endYear = endYear || 2020; this.language = language || 0; this.patternDelimiter = patternDelimiter || "-"; this.date2StringPattern = date2StringPattern || Calendar.language["date2StringPattern"][this.language].replace(/\-/g, this.patternDelimiter); this.string2DatePattern = string2DatePattern || Calendar.language["string2DatePattern"][this.language]; this.dateControl = null; this.panel = this.getElementById("__calendarPanel"); this.iframe = window.frames["__calendarIframe"]; this.form = null; this.date = new Date(); this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.colors = {"bg_cur_day":"#00CC33","bg_over":"#EFEFEF","bg_out":"#FFCC00"} }; Calendar.language = { "year" : ["\u5e74", "", "", "\u5e74"], "months" : [ ["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"], ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"], ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"], ["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"] ], "weeks" : [["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"], ["Sun","Mon","Tur","Wed","Thu","Fri","Sat"], ["Sun","Mon","Tur","Wed","Thu","Fri","Sat"], ["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"] ], "clear" : ["\u6e05\u7a7a", "Clear", "Clear", "\u6e05\u7a7a"], "today" : ["\u4eca\u5929", "Today", "Today", "\u4eca\u5929"], "close" : ["\u5173\u95ed", "Close", "Close", "\u95dc\u9589"], "date2StringPattern" : ["yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd"], "string2DatePattern" : ["ymd","ymd", "ymd", "ymd"] }; Calendar.prototype.draw = function() { calendar = this; var _cs = []; _cs[_cs.length] = '<form id="__calendarForm" name="__calendarForm" method="post">'; _cs[_cs.length] = '<table id="__calendarTable" width="100%" border="0" cellpadding="3" cellspacing="1" align="center">'; _cs[_cs.length] = ' <tr>'; _cs[_cs.length] = ' <th><input class="l" name="goPrevMonthButton" type="button" id="goPrevMonthButton" value="&lt;" \/><\/th>'; _cs[_cs.length] = ' <th colspan="5"><select class="year" name="yearSelect" id="yearSelect"><\/select><select class="month" name="monthSelect" id="monthSelect"><\/select><\/th>'; _cs[_cs.length] = ' <th><input class="r" name="goNextMonthButton" type="button" id="goNextMonthButton" value="&gt;" \/><\/th>'; _cs[_cs.length] = ' <\/tr>'; _cs[_cs.length] = ' <tr>'; for(var i = 0; i < 7; i++) { _cs[_cs.length] = '<th class="theader">'; _cs[_cs.length] = Calendar.language["weeks"][this.language][i]; _cs[_cs.length] = '<\/th>'; } _cs[_cs.length] = '<\/tr>'; for(var i = 0; i < 6; i++){ _cs[_cs.length] = '<tr align="center">'; for(var j = 0; j < 7; j++) { switch (j) { case 0: _cs[_cs.length] = '<td class="sun">&nbsp;<\/td>'; break; case 6: _cs[_cs.length] = '<td class="sat">&nbsp;<\/td>'; break; default:_cs[_cs.length] = '<td class="normal">&nbsp;<\/td>'; break; } } _cs[_cs.length] = '<\/tr>'; } _cs[_cs.length] = ' <tr>'; _cs[_cs.length] = ' <th colspan="2"><input type="button" class="b" name="clearButton" id="clearButton" \/><\/th>'; _cs[_cs.length] = ' <th colspan="3"><input type="button" class="b" name="selectTodayButton" id="selectTodayButton" \/><\/th>'; _cs[_cs.length] = ' <th colspan="2"><input type="button" class="b" name="closeButton" id="closeButton" \/><\/th>'; _cs[_cs.length] = ' <\/tr>'; _cs[_cs.length] = '<\/table>'; _cs[_cs.length] = '<\/form>'; this.iframe.document.body.innerHTML = _cs.join(""); this.form = this.iframe.document.forms["__calendarForm"]; this.form.clearButton.value = Calendar.language["clear"][this.language]; this.form.selectTodayButton.value = Calendar.language["today"][this.language]; this.form.closeButton.value = Calendar.language["close"][this.language]; this.form.goPrevMonthButton.onclick = function () {calendar.goPrevMonth(this);} this.form.goNextMonthButton.onclick = function () {calendar.goNextMonth(this);} this.form.yearSelect.onchange = function () {calendar.update(this);} this.form.monthSelect.onchange = function () {calendar.update(this);} this.form.clearButton.onclick = function () {calendar.dateControl.value = "";calendar.hide();} this.form.closeButton.onclick = function () {calendar.hide();} this.form.selectTodayButton.onclick = function () { var today = new Date(); calendar.date = today; calendar.year = today.getFullYear(); calendar.month = today.getMonth(); calendar.dateControl.value = today.format(calendar.date2StringPattern); calendar.hide(); } }; Calendar.prototype.bindYear = function() { var ys = this.form.yearSelect; ys.length = 0; for (var i = this.beginYear; i <= this.endYear; i++){ ys.options[ys.length] = new Option(i + Calendar.language["year"][this.language], i); } }; Calendar.prototype.bindMonth = function() { var ms = this.form.monthSelect; ms.length = 0; for (var i = 0; i < 12; i++){ ms.options[ms.length] = new Option(Calendar.language["months"][this.language][i], i); } }; Calendar.prototype.goPrevMonth = function(e){ if (this.year == this.beginYear && this.month == 0){return;} this.month--; if (this.month == -1) { this.year--; this.month = 11; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); }; Calendar.prototype.goNextMonth = function(e){ if (this.year == this.endYear && this.month == 11){return;} this.month++; if (this.month == 12) { this.year++; this.month = 0; } this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); }; Calendar.prototype.changeSelect = function() { var ys = this.form.yearSelect; var ms = this.form.monthSelect; for (var i= 0; i < ys.length; i++){ if (ys.options[i].value == this.date.getFullYear()){ ys[i].selected = true; break; } } for (var i= 0; i < ms.length; i++){ if (ms.options[i].value == this.date.getMonth()){ ms[i].selected = true; break; } } }; Calendar.prototype.update = function (e){ this.year = e.form.yearSelect.options[e.form.yearSelect.selectedIndex].value; this.month = e.form.monthSelect.options[e.form.monthSelect.selectedIndex].value; this.date = new Date(this.year, this.month, 1); this.changeSelect(); this.bindData(); }; Calendar.prototype.bindData = function () { var calendar = this; var dateArray = this.getMonthViewDateArray(this.date.getFullYear(), this.date.getMonth()); var tds = this.getElementsByTagName("td", this.getElementById("__calendarTable", this.iframe.document)); for(var i = 0; i < tds.length; i++) { tds[i].style.backgroundColor = calendar.colors["bg_over"]; tds[i].onclick = null; tds[i].onmouseover = null; tds[i].onmouseout = null; tds[i].innerHTML = dateArray[i] || "&nbsp;"; if (i > dateArray.length - 1) continue; if (dateArray[i]){ tds[i].onclick = function () { if (calendar.dateControl){ calendar.dateControl.value = new Date(calendar.date.getFullYear(), calendar.date.getMonth(), this.innerHTML).format(calendar.date2StringPattern); } calendar.hide(); } tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];} tds[i].onmouseout = function () {this.style.backgroundColor = calendar.colors["bg_over"];} var today = new Date(); if (today.getFullYear() == calendar.date.getFullYear()) { if (today.getMonth() == calendar.date.getMonth()) { if (today.getDate() == dateArray[i]) { tds[i].style.backgroundColor = calendar.colors["bg_cur_day"]; tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];} tds[i].onmouseout = function () {this.style.backgroundColor = calendar.colors["bg_cur_day"];} } } } }//end if }//end for }; Calendar.prototype.getMonthViewDateArray = function (y, m) { var dateArray = new Array(42); var dayOfFirstDate = new Date(y, m, 1).getDay(); var dateCountOfMonth = new Date(y, m + 1, 0).getDate(); for (var i = 0; i < dateCountOfMonth; i++) { dateArray[i + dayOfFirstDate] = i + 1; } return dateArray; }; Calendar.prototype.show = function (dateControl, popuControl) { if (this.panel.style.visibility == "visible") { this.panel.style.visibility = "hidden"; } if (!dateControl){ throw new Error("arguments[0] is necessary!") } this.dateControl = dateControl; popuControl = popuControl || dateControl; this.draw(); this.bindYear(); this.bindMonth(); if (dateControl.value.length > 0){ this.date = new Date(dateControl.value.toDate(this.patternDelimiter, this.string2DatePattern)); this.year = this.date.getFullYear(); this.month = this.date.getMonth(); } this.changeSelect(); this.bindData(); var xy = this.getAbsPoint(popuControl); this.panel.style.left = xy.x + "px"; this.panel.style.top = (xy.y + dateControl.offsetHeight) + "px"; this.panel.style.visibility = "visible"; }; Calendar.prototype.hide = function() { this.panel.style.visibility = "hidden"; }; Calendar.prototype.getElementById = function(id, object){ object = object || document; return document.getElementById ? object.getElementById(id) : document.all(id); }; Calendar.prototype.getElementsByTagName = function(tagName, object){ object = object || document; return document.getElementsByTagName ? object.getElementsByTagName(tagName) : document.all.tags(tagName); }; Calendar.prototype.getAbsPoint = function (e){ var x = e.offsetLeft; var y = e.offsetTop; while(e = e.offsetParent){ x += e.offsetLeft; y += e.offsetTop; } return {"x": x, "y": y}; }; /** * @param d the delimiter * @param p the pattern of your date * @author meizz * @author kimsoft add w+ pattern */ Date.prototype.format = function(style) { var o = { "M+" : this.getMonth() + 1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "w+" : "\u65e5\u4e00\u4e8c\u4e09\u56db\u4e94\u516d".charAt(this.getDay()), //week "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter "S" : this.getMilliseconds() //millisecond } if (/(y+)/.test(style)) { style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for(var k in o){ if (new RegExp("("+ k +")").test(style)){ style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return style; }; /** * @param d the delimiter * @param p the pattern of your date * @rebuilder kimsoft * @version build 2006.12.15 */ String.prototype.toDate = function(delimiter, pattern) { delimiter = delimiter || "-"; pattern = pattern || "ymd"; var a = this.split(delimiter); var y = parseInt(a[pattern.indexOf("y")], 10); //remember to change this next century ;) if(y.toString().length <= 2) y += 2000; if(isNaN(y)) y = new Date().getFullYear(); var m = parseInt(a[pattern.indexOf("m")], 10) - 1; var d = parseInt(a[pattern.indexOf("d")], 10); if(isNaN(d)) d = 1; return new Date(y, m, d); }; document.writeln('<div id="__calendarPanel" style="position:absolute;visibility:hidden;z-index:9999;background-color:#FFFFFF;border:1px solid #666666;width:200px;height:216px;">'); document.writeln('<iframe name="__calendarIframe" id="__calendarIframe" width="100%" height="100%" scrolling="no" frameborder="0" style="margin:0px;"><\/iframe>'); var __ci = window.frames['__calendarIframe']; __ci.document.writeln('<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD XHTML 1.0 Transitional\/\/EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd">'); __ci.document.writeln('<html xmlns="http:\/\/www.w3.org\/1999\/xhtml">'); __ci.document.writeln('<head>'); __ci.document.writeln('<meta http-equiv="Content-Type" content="text\/html; charset=utf-8" \/>'); __ci.document.writeln('<title>Web Calendar(UTF-8) Written By KimSoft<\/title>'); __ci.document.writeln('<style type="text\/css">'); __ci.document.writeln('<!--'); __ci.document.writeln('body {font-size:12px;margin:0px;text-align:center;}'); __ci.document.writeln('form {margin:0px;}'); __ci.document.writeln('select {font-size:12px;background-color:#EFEFEF;}'); __ci.document.writeln('table {border:0px solid #CCCCCC;background-color:#FFFFFF}'); __ci.document.writeln('th {font-size:12px;font-weight:normal;background-color:#FFFFFF;}'); __ci.document.writeln('th.theader {font-weight:normal;background-color:#666666;color:#FFFFFF;width:24px;}'); __ci.document.writeln('select.year {width:64px;}'); __ci.document.writeln('select.month {width:60px;}'); __ci.document.writeln('td {font-size:12px;text-align:center;}'); __ci.document.writeln('td.sat {color:#0000FF;background-color:#EFEFEF;}'); __ci.document.writeln('td.sun {color:#FF0000;background-color:#EFEFEF;}'); __ci.document.writeln('td.normal {background-color:#EFEFEF;}'); __ci.document.writeln('input.l {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}'); __ci.document.writeln('input.r {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}'); __ci.document.writeln('input.b {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:100%;height:20px;}'); __ci.document.writeln('-->'); __ci.document.writeln('<\/style>'); __ci.document.writeln('<\/head>'); __ci.document.writeln('<body>'); __ci.document.writeln('<\/body>'); __ci.document.writeln('<\/html>'); __ci.document.close(); document.writeln('<\/div>'); var calendar = new Calendar(); //-->
JavaScript
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ ;var 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;}}};}(); /* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";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};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};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);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","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;this.settings.return_upload_start_handler=this.returnUploadStart;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_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("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()}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.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_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.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&amp;uploadURL=",encodeURIComponent(this.settings.upload_url),"&amp;useQueryString=",encodeURIComponent(this.settings.use_query_string),"&amp;requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&amp;httpSuccess=",encodeURIComponent(a),"&amp;assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&amp;params=",encodeURIComponent(b),"&amp;filePostName=",encodeURIComponent(this.settings.file_post_name),"&amp;fileTypes=",encodeURIComponent(this.settings.file_types),"&amp;fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&amp;fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&amp;fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&amp;fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&amp;debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&amp;buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&amp;buttonWidth=",encodeURIComponent(this.settings.button_width),"&amp;buttonHeight=",encodeURIComponent(this.settings.button_height),"&amp;buttonText=",encodeURIComponent(this.settings.button_text),"&amp;buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&amp;buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&amp;buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&amp;buttonAction=",encodeURIComponent(this.settings.button_action),"&amp;buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&amp;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 c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&amp;")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}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(d){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","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_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_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_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"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}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(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}}; /* Uploadify v3.1.1 Copyright (c) 2012 Reactive Apps, Ronnie Garcia Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ (function($) { // These methods can be called by adding them as the first argument in the uploadify plugin call var methods = { init : function(options, swfUploadOptions) { return this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this); // Clone the original DOM object var $clone = $this.clone(); // Setup the default options var settings = $.extend({ // Required Settings id : $this.attr('id'), // The ID of the DOM object swf : 'uploadify.swf', // The path to the uploadify SWF file uploader : 'uploadify.php', // The path to the server-side upload script // Options auto : true, // Automatically upload files when added to the queue buttonClass : '', // A class name to add to the browse button DOM object buttonCursor : 'hand', // The cursor to use with the browse button buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button buttonText : 'SELECT FILES', // The text to use for the browse button checkExisting : false, // The path to a server-side script that checks for existing files on the server debug : false, // Turn on swfUpload debugging mode fileObjName : 'Filedata', // The name of the file object to use in your server-side script fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit) fileTypeDesc : 'All Files', // The description for file types in the browse dialog fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used) height : 30, // The height of the browse button method : 'post', // The method to use when sending files to the server-side upload script multi : true, // Allow multiple file selection in the browse dialog formData : {}, // An object with additional data to send to the server-side upload script with every file upload preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters) progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload queueID : false, // The ID of the DOM object to use as a file queue (without the #) queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time removeCompleted : true, // Remove queue items from the queue when they are done uploading removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true requeueErrors : false, // Keep errored files in the queue and keep trying to upload them successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading uploadLimit : 0, // The maximum number of files you can upload width : 120, // The width of the browse button // Events overrideEvents : [] // (Array) A list of default event handlers to skip /* onCancel // Triggered when a file is cancelled from the queue onClearQueue // Triggered during the 'clear queue' method onDestroy // Triggered when the uploadify object is destroyed onDialogClose // Triggered when the browse dialog is closed onDialogOpen // Triggered when the browse dialog is opened onDisable // Triggered when the browse button gets disabled onEnable // Triggered when the browse button gets enabled onFallback // Triggered is Flash is not detected onInit // Triggered when Uploadify is initialized onQueueComplete // Triggered when all files in the queue have been uploaded onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.) onSelect // Triggered for each file that is selected onSWFReady // Triggered when the SWF button is loaded onUploadComplete // Triggered when a file upload completes (success or error) onUploadError // Triggered when a file upload returns an error onUploadSuccess // Triggered when a file is uploaded successfully onUploadProgress // Triggered every time a file progress is updated onUploadStart // Triggered immediately before a file upload starts */ }, options); // Prepare settings for SWFUpload var swfUploadSettings = { assume_success_timeout : settings.successTimeout, button_placeholder_id : settings.id, button_width : settings.width, button_height : settings.height, button_text : null, button_text_style : null, button_text_top_padding : 0, button_text_left_padding : 0, button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE), button_disabled : false, button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND), button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, debug : settings.debug, requeue_on_error : settings.requeueErrors, file_post_name : settings.fileObjName, file_size_limit : settings.fileSizeLimit, file_types : settings.fileTypeExts, file_types_description : settings.fileTypeDesc, file_queue_limit : settings.queueSizeLimit, file_upload_limit : settings.uploadLimit, flash_url : settings.swf, prevent_swf_caching : settings.preventCaching, post_params : settings.formData, upload_url : settings.uploader, use_query_string : (settings.method == 'get'), // Event Handlers file_dialog_complete_handler : handlers.onDialogClose, file_dialog_start_handler : handlers.onDialogOpen, file_queued_handler : handlers.onSelect, file_queue_error_handler : handlers.onSelectError, swfupload_loaded_handler : settings.onSWFReady, upload_complete_handler : handlers.onUploadComplete, upload_error_handler : handlers.onUploadError, upload_progress_handler : handlers.onUploadProgress, upload_start_handler : handlers.onUploadStart, upload_success_handler : handlers.onUploadSuccess } // Merge the user-defined options with the defaults if (swfUploadOptions) { swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions); } // Add the user-defined settings to the swfupload object swfUploadSettings = $.extend(swfUploadSettings, settings); // Detect if Flash is available var playerVersion = swfobject.getFlashPlayerVersion(); var flashInstalled = (playerVersion.major >= 9); if (flashInstalled) { // Create the swfUpload instance window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings); var swfuploadify = window['uploadify_' + settings.id]; // Add the SWFUpload object to the elements data object $this.data('uploadify', swfuploadify); // Wrap the instance var $wrapper = $('<div />', { 'id' : settings.id, 'class' : 'uploadify', 'css' : { 'height' : settings.height + 'px', 'width' : settings.width + 'px' } }); $('#' + swfuploadify.movieName).wrap($wrapper); // Recreate the reference to wrapper $wrapper = $('#' + settings.id); // Add the data object to the wrapper $wrapper.data('uploadify', swfuploadify); // Create the button var $button = $('<div />', { 'id' : settings.id + '-button', 'class' : 'uploadify-button ' + settings.buttonClass }); if (settings.buttonImage) { $button.css({ 'background-image' : "url('" + settings.buttonImage + "')", 'text-indent' : '-9999px' }); } $button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>') .css({ 'height' : settings.height + 'px', 'line-height' : settings.height + 'px', 'width' : settings.width + 'px' }); // Append the button to the wrapper $wrapper.append($button); // Adjust the styles of the movie $('#' + swfuploadify.movieName).css({ 'position' : 'absolute', 'z-index' : 1 }); // Create the file queue if (!settings.queueID) { var $queue = $('<div />', { 'id' : settings.id + '-queue', 'class' : 'uploadify-queue' }); $wrapper.after($queue); swfuploadify.settings.queueID = settings.id + '-queue'; swfuploadify.settings.defaultQueue = true; } // Create some queue related objects and variables swfuploadify.queueData = { files : {}, // The files in the queue filesSelected : 0, // The number of files selected in the last select operation filesQueued : 0, // The number of files added to the queue in the last select operation filesReplaced : 0, // The number of files replaced in the last select operation filesCancelled : 0, // The number of files that were cancelled instead of replaced filesErrored : 0, // The number of files that caused error in the last select operation uploadsSuccessful : 0, // The number of files that were successfully uploaded uploadsErrored : 0, // The number of files that returned errors during upload averageSpeed : 0, // The average speed of the uploads in KB queueLength : 0, // The number of files in the queue queueSize : 0, // The size in bytes of the entire queue uploadSize : 0, // The size in bytes of the upload queue queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue uploadQueue : [], // The files currently to be uploaded errorMsg : 'Some files were not added to the queue:' }; // Save references to all the objects swfuploadify.original = $clone; swfuploadify.wrapper = $wrapper; swfuploadify.button = $button; swfuploadify.queue = $queue; // Call the user-defined init event handler if (settings.onInit) settings.onInit.call($this, swfuploadify); } else { // Call the fallback function if (settings.onFallback) settings.onFallback.call($this); } }); }, // Stop a file upload and remove it from the queue cancel : function(fileID, supressEvent) { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings, delay = -1; if (args[0]) { // Clear the queue if (args[0] == '*') { var queueItemCount = swfuploadify.queueData.queueLength; $('#' + settings.queueID).find('.uploadify-queue-item').each(function() { delay++; if (args[1] === true) { swfuploadify.cancelUpload($(this).attr('id'), false); } else { swfuploadify.cancelUpload($(this).attr('id')); } $(this).find('.data').removeClass('data').html(' - Cancelled'); $(this).find('.uploadify-progress-bar').remove(); $(this).delay(1000 + 100 * delay).fadeOut(500, function() { $(this).remove(); }); }); swfuploadify.queueData.queueSize = 0; swfuploadify.queueData.queueLength = 0; // Trigger the onClearQueue event if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount); } else { for (var n = 0; n < args.length; n++) { swfuploadify.cancelUpload(args[n]); $('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled'); $('#' + args[n]).find('.uploadify-progress-bar').remove(); $('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() { $(this).remove(); }); } } } else { var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0); $item = $(item); swfuploadify.cancelUpload($item.attr('id')); $item.find('.data').removeClass('data').html(' - Cancelled'); $item.find('.uploadify-progress-bar').remove(); $item.delay(1000).fadeOut(500, function() { $(this).remove(); }); } }); }, // Revert the DOM object back to its original state destroy : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Destroy the SWF object and swfuploadify.destroy(); // Destroy the queue if (settings.defaultQueue) { $('#' + settings.queueID).remove(); } // Reload the original DOM element $('#' + settings.id).replaceWith(swfuploadify.original); // Call the user-defined event handler if (settings.onDestroy) settings.onDestroy.call(this); delete swfuploadify; }); }, // Disable the select button disable : function(isDisabled) { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Call the user-defined event handlers if (isDisabled) { swfuploadify.button.addClass('disabled'); if (settings.onDisable) settings.onDisable.call(this); } else { swfuploadify.button.removeClass('disabled'); if (settings.onEnable) settings.onEnable.call(this); } // Enable/disable the browse button swfuploadify.setButtonDisabled(isDisabled); }); }, // Get or set the settings data settings : function(name, value, resetObjects) { var args = arguments; var returnValue = value; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; if (typeof(args[0]) == 'object') { for (var n in value) { setData(n,value[n]); } } if (args.length === 1) { returnValue = settings[name]; } else { switch (name) { case 'uploader': swfuploadify.setUploadURL(value); break; case 'formData': if (!resetObjects) { value = $.extend(settings.formData, value); } swfuploadify.setPostParams(settings.formData); break; case 'method': if (value == 'get') { swfuploadify.setUseQueryString(true); } else { swfuploadify.setUseQueryString(false); } break; case 'fileObjName': swfuploadify.setFilePostName(value); break; case 'fileTypeExts': swfuploadify.setFileTypes(value, settings.fileTypeDesc); break; case 'fileTypeDesc': swfuploadify.setFileTypes(settings.fileTypeExts, value); break; case 'fileSizeLimit': swfuploadify.setFileSizeLimit(value); break; case 'uploadLimit': swfuploadify.setFileUploadLimit(value); break; case 'queueSizeLimit': swfuploadify.setFileQueueLimit(value); break; case 'buttonImage': swfuploadify.button.css('background-image', settingValue); break; case 'buttonCursor': if (value == 'arrow') { swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW); } else { swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND); } break; case 'buttonText': $('#' + settings.id + '-button').find('.uploadify-button-text').html(value); break; case 'width': swfuploadify.setButtonDimensions(value, settings.height); break; case 'height': swfuploadify.setButtonDimensions(settings.width, value); break; case 'multi': if (value) { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES); } else { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE); } break; } settings[name] = value; } }); if (args.length === 1) { return returnValue; } }, // Stop the current uploads and requeue what is in progress stop : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; swfuploadify.stopUpload(); }); }, // Start uploading files in the queue upload : function() { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; // Upload the files if (args[0]) { if (args[0] == '*') { swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize; swfuploadify.queueData.uploadQueue.push('*'); swfuploadify.startUpload(); } else { for (var n = 0; n < args.length; n++) { swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size; swfuploadify.queueData.uploadQueue.push(args[n]); } swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift()); } } else { swfuploadify.startUpload(); } }); } } // These functions handle all the events that occur with the file uploader var handlers = { // Triggered when the file dialog is opened onDialogOpen : function() { // Load the swfupload settings var settings = this.settings; // Reset some queue info this.queueData.errorMsg = 'Some files were not added to the queue:'; this.queueData.filesReplaced = 0; this.queueData.filesCancelled = 0; // Call the user-defined event handler if (settings.onDialogOpen) settings.onDialogOpen.call(this); }, // Triggered when the browse dialog is closed onDialogClose : function(filesSelected, filesQueued, queueLength) { // Load the swfupload settings var settings = this.settings; // Update the queue information this.queueData.filesErrored = filesSelected - filesQueued; this.queueData.filesSelected = filesSelected; this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled; this.queueData.queueLength = queueLength; // Run the default event handler if ($.inArray('onDialogClose', settings.overrideEvents) < 0) { if (this.queueData.filesErrored > 0) { alert(this.queueData.errorMsg); } } // Call the user-defined event handler if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData); // Upload the files if auto is true if (settings.auto) $('#' + settings.id).uploadify('upload', '*'); }, // Triggered once for each file added to the queue onSelect : function(file) { // Load the swfupload settings var settings = this.settings; // Check if a file with the same name exists in the queue var queuedFile = {}; for (var n in this.queueData.files) { queuedFile = this.queueData.files[n]; if (queuedFile.uploaded != true && queuedFile.name == file.name) { var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?'); if (!replaceQueueItem) { this.cancelUpload(file.id); this.queueData.filesCancelled++; return false; } else { $('#' + queuedFile.id).remove(); this.cancelUpload(queuedFile.id); this.queueData.filesReplaced++; } } } // Get the size of the file var fileSize = Math.round(file.size / 1024); var suffix = 'KB'; if (fileSize > 1000) { fileSize = Math.round(fileSize / 1000); suffix = 'MB'; } var fileSizeParts = fileSize.toString().split('.'); fileSize = fileSizeParts[0]; if (fileSizeParts.length > 1) { fileSize += '.' + fileSizeParts[1].substr(0,2); } fileSize += suffix; // Truncate the filename if it's too long var fileName = file.name; if (fileName.length > 25) { fileName = fileName.substr(0,25) + '...'; } // Run the default event handler if ($.inArray('onSelect', settings.overrideEvents) < 0) { // Add the file item to the queue $('#' + settings.queueID).append('<div id="' + file.id + '" class="uploadify-queue-item">\ <div class="cancel">\ <a href="javascript:$(\'#' + settings.id + '\').uploadify(\'cancel\', \'' + file.id + '\')">X</a>\ </div>\ <span class="fileName">' + fileName + ' (' + fileSize + ')</span><span class="data"></span>\ <div class="uploadify-progress">\ <div class="uploadify-progress-bar"><!--Progress Bar--></div>\ </div>\ </div>'); } this.queueData.queueSize += file.size; this.queueData.files[file.id] = file; // Call the user-defined event handler if (settings.onSelect) settings.onSelect.apply(this, arguments); }, // Triggered when a file is not added to the queue onSelectError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Run the default event handler if ($.inArray('onSelectError', settings.overrideEvents) < 0) { switch(errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: if (settings.queueSizeLimit > errorMsg) { this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').'; } else { this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').'; } break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').'; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.'; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').'; break; } } if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { delete this.queueData.files[file.id]; } // Call the user-defined event handler if (settings.onSelectError) settings.onSelectError.apply(this, arguments); }, // Triggered when all the files in the queue have been processed onQueueComplete : function() { if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData); }, // Triggered when a file upload successfully completes onUploadComplete : function(file) { // Load the swfupload settings var settings = this.settings, swfuploadify = this; // Check if all the files have completed uploading var stats = this.getStats(); this.queueData.queueLength = stats.files_queued; if (this.queueData.uploadQueue[0] == '*') { if (this.queueData.queueLength > 0) { this.startUpload(); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } else { if (this.queueData.uploadQueue.length > 0) { this.startUpload(this.queueData.uploadQueue.shift()); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } // Call the default event handler if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) { if (settings.removeCompleted) { switch (file.filestatus) { case SWFUpload.FILE_STATUS.COMPLETE: setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id] $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); break; case SWFUpload.FILE_STATUS.ERROR: if (!settings.requeueErrors) { setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id]; $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); } break; } } else { file.uploaded = true; } } // Call the user-defined event handler if (settings.onUploadComplete) settings.onUploadComplete.call(this, file); }, // Triggered when a file upload returns an error onUploadError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Set the error string var errorString = 'Error'; switch(errorCode) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: errorString = 'HTTP Error (' + errorMsg + ')'; break; case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: errorString = 'Missing Upload URL'; break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: errorString = 'IO Error'; break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: errorString = 'Security Error'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: alert('The upload limit has been reached (' + errorMsg + ').'); errorString = 'Exceeds Upload Limit'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: errorString = 'Failed'; break; case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: errorString = 'Validation Error'; break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: errorString = 'Cancelled'; this.queueData.queueSize -= file.size; this.queueData.queueLength -= 1; if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) { this.queueData.uploadSize -= file.size; } // Trigger the onCancel event if (settings.onCancel) settings.onCancel.call(this, file); delete this.queueData.files[file.id]; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: errorString = 'Stopped'; break; } // Call the default event handler if ($.inArray('onUploadError', settings.overrideEvents) < 0) { if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) { $('#' + file.id).addClass('uploadify-error'); } // Reset the progress bar $('#' + file.id).find('.uploadify-progress-bar').css('width','1px'); // Add the error message to the queue item if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) { $('#' + file.id).find('.data').html(' - ' + errorString); } } var stats = this.getStats(); this.queueData.uploadsErrored = stats.upload_errors; // Call the user-defined event handler if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString); }, // Triggered periodically during a file upload onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) { // Load the swfupload settings var settings = this.settings; // Setup all the variables var timer = new Date(); var newTime = timer.getTime(); var lapsedTime = newTime - this.timer; if (lapsedTime > 500) { this.timer = newTime; } var lapsedBytes = fileBytesLoaded - this.bytesLoaded; this.bytesLoaded = fileBytesLoaded; var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded; var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100); // Calculate the average speed var suffix = 'KB/s'; var mbs = 0; var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000); kbs = Math.floor(kbs * 10) / 10; if (this.queueData.averageSpeed > 0) { this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2); } else { this.queueData.averageSpeed = Math.floor(kbs); } if (kbs > 1000) { mbs = (kbs * .001); this.queueData.averageSpeed = Math.floor(mbs); suffix = 'MB/s'; } // Call the default event handler if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) { if (settings.progressData == 'percentage') { $('#' + file.id).find('.data').html(' - ' + percentage + '%'); } else if (settings.progressData == 'speed' && lapsedTime > 500) { $('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix); } $('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%'); } // Call the user-defined event handler if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize); }, // Triggered right before a file is uploaded onUploadStart : function(file) { // Load the swfupload settings var settings = this.settings; var timer = new Date(); this.timer = timer.getTime(); this.bytesLoaded = 0; if (this.queueData.uploadQueue.length == 0) { this.queueData.uploadSize = file.size; } if (settings.checkExisting) { $.ajax({ type : 'POST', async : false, url : settings.checkExisting, data : {filename: file.name}, success : function(data) { if (data == 1) { var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?'); if (!overwrite) { this.cancelUpload(file.id); $('#' + file.id).remove(); if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) { if (this.queueData.uploadQueue[0] == '*') { this.startUpload(); } else { this.startUpload(this.queueData.uploadQueue.shift()); } } } } } }); } // Call the user-defined event handler if (settings.onUploadStart) settings.onUploadStart.call(this, file); }, // Triggered when a file upload returns a successful code onUploadSuccess : function(file, data, response) { // Load the swfupload settings var settings = this.settings; var stats = this.getStats(); this.queueData.uploadsSuccessful = stats.successful_uploads; this.queueData.queueBytesUploaded += file.size; // Call the default event handler if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) { $('#' + file.id).find('.data').html(' - Complete'); } // Call the user-defined event handler if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response); } } $.fn.uploadify = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('The method ' + method + ' does not exist in $.uploadify'); } } })($);
JavaScript
// JavaScript Document function confirmDel(str) { return confirm(str); } //date参照时间, n表示天数 //返回参照时间n天之后的日期 function showdate(datestr,n) { if(datestr=="") { var uom = new Date(); } else { var r= datestr.replace("-","/"); var uom = new Date(""+r); } uom.setDate(uom.getDate()+n); uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate()+ " "+uom.getHours()+":"+uom.getMinutes()+":"+uom.getSeconds(); return uom; } function Match(str,pattern,flag){ var flagv; if(flag=="") { flagv="i";//忽略大小写 } re = new RegExp(pattern,flagv); // 创建正则表达式对象。 r = str.match(re); // 在字符串 s 中查找匹配。 return(r); // 返回匹配结果。 } //图片等比例缩放 function DrawImage(ImgD,widthn,heightn,altstr){ //用法<img src="" onload=javascript:DrawImage(this,widthn,heightn,altstr);> var image=new Image(); image.src=ImgD.src; if(image.width>0 && image.height>0){ flag=true; if(image.width/image.height>= widthn/heightn){ if(image.width>widthn){ ImgD.width=widthn; ImgD.height=(image.height*widthn)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } ImgD.alt= altstr; } else{ if(image.height>heightn){ ImgD.height=heightn; ImgD.width=(image.width*heightn)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } ImgD.alt=altstr; } } } //显示一个隐藏了的标签 function showele(str) { document.getElementById(str).style.display=""; } //隐藏一个标签内容 function hiddenele(str) { document.getElementById(str).style.display="none"; } //验证表单项的写法,不成功返回false,成功不返回操作 function nzeletype(elename,altstr,type) { var temp=document.getElementById(elename).value; //验证整型数字 if(type=="int") { if(!temp.match(/^[\d]+$/)|| temp=="") { alert(altstr); document.getElementById(elename).value=""; document.getElementById(elename).focus(); return false; } } //验证浮点数字 if(type=="float") { if(!temp.match(/^[\d\.]+$/)|| temp=="") { alert(altstr); document.getElementById(elename).value=""; document.getElementById(elename).focus(); return false; } } //验证字符串不能为空 if(type=="string") { if(temp=="") { alert(altstr); document.getElementById(elename).focus(); return false; } } //验证电子邮件 if(type=="email") { if(!temp.match(/^[\w\-\.]+@[\w\-\.]+\.[\w]+$/)) { alert(altstr); document.getElementById(elename).value=""; document.getElementById(elename).focus(); return false; } } if(type=="date"){ temt=document.getElementById(elename).value; if(!temt.match(/^[\d]{2,4}\-[\d]{1,2}\-[\d]{1,2}/)){ alert(altstr); document.getElementById(elename).value=""; document.getElementById(elename).focus(); return false; } } return true; } //骊一个小数进行四舍五入,fractionDigits为保留的位数 function round2(number,fractionDigits){ with(Math){ return round(number*pow(10,fractionDigits))/pow(10,fractionDigits); } } //常规的表单提交时的检查是否符合条件 当不符合正则的表达式时返回false 符合则返回true /* altstr 提示信息 eid 文档里的id zhence 正则表达式 */ function checkfromOption(altstr,eid,zhence) { temp=document.getElementById(eid).value; if(!temp.match(zhence)) { alert(altstr); document.getElementById(eid).focus(); return false; } return true; } //弹出隐藏层 function chen_ShowDiv(show_div,bg_div){ document.getElementById(show_div).style.display='block'; document.getElementById(bg_div).style.display='block' ; var bgdiv = document.getElementById(bg_div); bgdiv.style.width = document.body.scrollWidth; // bgdiv.style.height = $(document).height(); $("#"+bg_div).height($(document).height()); }; //关闭弹出层 function chen_CloseDiv(show_div,bg_div) { document.getElementById(show_div).style.display='none'; document.getElementById(bg_div).style.display='none'; }; //用正则获取第一个括号里的内容 function getkuohaostr(str,patter) { if(str=="") return ""; temp=str.match(patter) if(temp!=null){ if(temp.length>0){ return temp[0].replace(patter,"$1"); } } return ""; } function addCookie(objName,objValue,objHours){//添加cookie var str = objName + "=" + escape(objValue); if(objHours > 0){//为0时不设定过期时间,浏览器关闭时cookie自动消失 var date = new Date(); var ms = objHours*3600*1000; date.setTime(date.getTime() + ms); str += "; expires=" + date.toGMTString(); } document.cookie = str; } function getCookie(objName){//获取指定名称的cookie的值 var arrStr = document.cookie.split("; "); for(var i = 0;i < arrStr.length;i ++){ var temp = arrStr[i].split("="); if(temp[0] == objName) return unescape(temp[1]); } } //用cookie的方式判断会员是否登陆 function isuserlogin(altstr) { uchome_auth=getCookie("uchome_auth"); return (uchome_auth)?true:false; }
JavaScript
jQuery.fn.extend({ jsRightMenu: function(options) { options = $.extend({ menuList: [] }, options); return this.each(function() { if ($("#div_RightMenu", $(this)).size() == 0) { var menuCount = options.menuList.length; if (menuCount > 0) { var divMenuList = "<div id=\"div_RightMenu\" class=\"div_RightMenu\">"; for (var i = 0; i < menuCount; i++) { divMenuList += "<div class=\"divMenuItem\" id='divMenuItem_"+i+"' onclick=\"" + options.menuList[i].clickEvent + "\" >" + options.menuList[i].menuName + "</div><hr size=1>"; $("#divMenuItem_"+i).bind("onmouseover",function(){ document.getElementById("divMenuItem_"+i).style.backgroundColor = "#6EC447"; }); } divMenuList += "</div>"; $(this).append(divMenuList); var objM = $(".divMenuItem"); $("#div_RightMenu").hide(); objM.bind("mouseover", function() { //this.style.backgroundColor = "#316ac5"; //this.style.paddingLeft = "30px"; }); objM.bind("mouseout", function() { //this.style.backgroundColor = '#EAEAEA'; }); } } this.oncontextmenu = function() { var objMenu = $("#div_RightMenu"); if (objMenu.size() > 0) { objMenu.hide(); var event = arguments[0] || window.event; var clientX = event.clientX; var clientY = event.clientY; var redge = document.body.clientWidth - clientX; var bedge = document.body.clientHeight - clientY; var menu = objMenu.get(0); var menuLeft = 0; var menuTop = 0; if (redge < menu.offsetWidth) menuLeft = document.body.scrollLeft + clientX - menu.offsetWidth; else menuLeft = document.body.scrollLeft + clientX; if (bedge < menu.offsetHeight) menuTop = document.body.scrollTop + clientY - menu.offsetHeight; else menuTop = document.body.scrollTop + clientY; objMenu.css({ top: menuTop + "px", left: menuLeft + "px" }); objMenu.show(); return false; } } document.onclick = function() { var objMenu = $("#div_RightMenu"); if (objMenu.size() > 0) objMenu.hide(); } }); } }); function setdiv(i) { document.getElementById("divMenuItem_"+i).style.backgroundColor = "#6EC447"; }
JavaScript
/* 图片延迟加载 使用方法 如: $(".switch_textarea").lazyload(); 详细出处参考:http://www.jb51.net/article/25706.htm * Lazy Load - jQuery plugin for lazy loading images * * Copyright (c) 2007-2009 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://www.appelsiini.net/projects/lazyload * * Version: 1.5.0 * * Modify by @cnbaiying * Modify time: 2010-12-16 */ (function($) { $.fn.lazyload = function(options) { var settings = { threshold : 0, //阀值 failurelimit : 0, event : "scroll", effect : "show", container : window }; if(options) { $.extend(settings, options); } /* Fire one scroll event per scroll. Not one scroll event per image. */ var elements = this; if ("scroll" == settings.event) { $(settings.container).bind("scroll", function(event) { var counter = 0; elements.each(function() { if ($.abovethetop($(this).parent(), settings) || $.leftofbegin($(this).parent(), settings)) { /* Nothing. */ } else if (!$.belowthefold($(this).parent(), settings) && !$.rightoffold($(this).parent(), settings)) { $(this).trigger("appear"); } else { if (counter++ > settings.failurelimit) { return false; } } }); /* Remove image from array so it is not looped next time. */ var temp = $.grep(elements, function(element) { return !element.loaded; }); elements = $(temp); }); } this.each(function() { var self = this; /* When appear is triggered load original image. */ $(self).one("appear", function() { if (!this.loaded) { //alert($(self).parent().html($(self).html())); var tmp_str = $(self).html(); tmp_str = tmp_str.replace("<", "<"); tmp_str = tmp_str.replace(">", ">"); $(self).parent().append(tmp_str); self.loaded = true; } }); /* When wanted event is triggered load original image */ /* by triggering appear. */ if ("scroll" != settings.event) { $(self).bind(settings.event, function(event) { if (!self.loaded) { $(self).trigger("appear"); } }); } }); /* Force initial check if images should appear. */ $(settings.container).trigger(settings.event); return this; }; /* Convenience methods in jQuery namespace. */ /* Use as $.belowthefold(element, {threshold : 100, container : window}) */ $.belowthefold = function(element, settings) { if (settings.container === undefined || settings.container === window) { var fold = $(window).height() + $(window).scrollTop(); } else { var fold = $(settings.container).offset().top + $(settings.container).height(); } return fold <= $(element).offset().top - settings.threshold; }; $.rightoffold = function(element, settings) { if (settings.container === undefined || settings.container === window) { var fold = $(window).width() + $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left + $(settings.container).width(); } return fold <= $(element).offset().left - settings.threshold; }; $.abovethetop = function(element, settings) { if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollTop(); } else { var fold = $(settings.container).offset().top; } return fold >= $(element).offset().top + settings.threshold + $(element).height(); }; $.leftofbegin = function(element, settings) { if (settings.container === undefined || settings.container === window) { var fold = $(window).scrollLeft(); } else { var fold = $(settings.container).offset().left; } return fold >= $(element).offset().left + settings.threshold + $(element).width(); }; /* Custom selectors for your convenience. */ /* Use as $("img:below-the-fold").something() */ $.extend($.expr[':'], { "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})", "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})", "right-of-fold" : "$.rightoffold(a, {threshold : 0, container: window})", "left-of-fold" : "!$.rightoffold(a, {threshold : 0, container: window})" }); })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/* * ContextMenu - jQuery plugin for right-click context menus * * Author: Chris Domigan * Contributors: Dan G. Switzer, II * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: r2 * Date: 16 July 2007 * * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/ * */ (function($) { var menu, shadow, trigger, content, hash, currentTarget; var defaults = { menuStyle: { listStyle: 'none', padding: '1px', margin: '0px', backgroundColor: '#fff', border: '1px solid #999', width: '100px' }, itemStyle: { margin: '0px', color: '#000', display: 'block', cursor: 'default', padding: '3px', border: '1px solid #fff', backgroundColor: 'transparent' }, itemHoverStyle: { border: '1px solid #0a246a', backgroundColor: '#b6bdd2' }, eventPosX: 'pageX', eventPosY: 'pageY', shadow : true, onContextMenu: null, onShowMenu: null }; $.fn.contextMenu = function(id, options) { if (!menu) { // Create singleton menu menu = $('<div id="jqContextMenu"></div>') .hide() .css({position:'absolute', zIndex:'500'}) .appendTo('body') .bind('click', function(e) { e.stopPropagation(); }); } if (!shadow) { shadow = $('<div></div>') .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499}) .appendTo('body') .hide(); } hash = hash || []; hash.push({ id : id, menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}), itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}), itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}), bindings: options.bindings || {}, shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow, onContextMenu: options.onContextMenu || defaults.onContextMenu, onShowMenu: options.onShowMenu || defaults.onShowMenu, eventPosX: options.eventPosX || defaults.eventPosX, eventPosY: options.eventPosY || defaults.eventPosY }); var index = hash.length - 1; $(this).bind('contextmenu', function(e) { // Check if onContextMenu() defined var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true; if (bShowContext) display(index, this, e, options); return false; }); return this; }; function display(index, trigger, e, options) { var cur = hash[index]; content = $('#'+cur.id).find('ul:first').clone(true); content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover( function() { $(this).css(cur.itemHoverStyle); }, function(){ $(this).css(cur.itemStyle); } ).find('img').css({verticalAlign:'middle',paddingRight:'2px'}); // Send the content to the menu menu.html(content); // if there's an onShowMenu, run it now -- must run after content has been added // if you try to alter the content variable before the menu.html(), IE6 has issues // updating the content if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu); $.each(cur.bindings, function(id, func) { $('#'+id, menu).bind('click', function(e) { hide(); func(trigger, currentTarget); }); }); menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show(); if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show(); $(document).one('click', hide); } function hide() { menu.hide(); shadow.hide(); } // Apply defaults $.contextMenu = { defaults : function(userDefaults) { $.each(userDefaults, function(i, val) { if (typeof val == 'object' && defaults[i]) { $.extend(defaults[i], val); } else defaults[i] = val; }); } }; })(jQuery); $(function() { $('div.contextMenu').hide(); });
JavaScript
tmsgname=""; tdialogname=""; twidthnum="";//模似对话宽宽度 theightnum="";//模似对话框高度 /*参数为一个数组 //CsArr["title"]为显示标题 CsArr["msg"]为显示内容 CsArr["msgname"]父页面中div的id 显示对话框窗口 CsArr["dialogname"]父页面中div的id 显示对话框窗口 CsArr["heightnum"] 对话框的距离屏幕顶端高度 CsArr["widthnum"]//对话框的距离屏幕顶端宽度 */ function show(CsArr) { if(CsArr["heightnum"]=="") { CsArr["heightnum"]="300";//若没有定义默认为300 } if(CsArr["widthnum"]=="") { CsArr["widthnum"]="300";//若没有定义默认为300 } tmsgname=CsArr["msgname"]; tdialogname=CsArr["dialogname"]; theightnum=CsArr["heightnum"]; twidthnum=CsArr["widthnum"]; var d_mask=document.getElementById(CsArr["msgname"]); var d_dialog =document.getElementById(CsArr["dialogname"]); d_mask.style.width = document.body.clientWidth ; d_mask.style.height=document.body.clientHeight; d_dialog.style.top = document.body.clientHeight / 2 -CsArr["heightnum"]; d_dialog.style.left =document.body.clientWidth / 2 -CsArr["widthnum"]; var Inner = "<input type='button' value='Close' onclick='DialogClose()'/>" var info = "<table cellspacing='0' width='100%' height='100%'>"+ "<tr class='dgtitle'><td>" +CsArr['title'] +"</td><td align='right'><input type='button' value='Close' onclick='DialogClose()'class='formButton'/></td></tr>" +"<tr><td colspan='2' valign='top'>" +CsArr['msg'] +"</td></tr>" +"<tr class='dgfooter'><td></td><td>" +"</td></tr>" +"</table>"; d_dialog.innerHTML =info; d_mask.style.visibility='visible'; d_dialog.style.visibility='visible'; } function Icon_Close_Over(obj) { obj.src='close.gif'; } function Icon_Close_Out(obj) { obj.src='close1.gif' } function DialogClose() { var d_mask=document.getElementById(tmsgname); var d_dialog = document.getElementById(tdialogname); //parent.getifheight();//当记录没有时或很少时还原其框架在原来的页面中的高度 enableSelect() d_mask.style.visibility='hidden'; d_dialog.style.visibility='hidden'; } function disableSelect() { for(i=0;i<document.all.length;i++) if(document.all(i).tagName=="SELECT") document.all(i).disabled = true; } function enableSelect() { for(i=0;i<document.all.length;i++){ if(document.all(i).tagName=="SELECT") { document.all(i).disabled = false; } } } function divBlock_event_mousedown() { var e, obj, temp; obj=document.getElementById(tdialogname); e=window.event?window.event:e; obj.startX=e.clientX-obj.offsetLeft; obj.startY=e.clientY-obj.offsetTop; document.onmousemove=document_event_mousemove; temp=document.attachEvent?document.attachEvent('onmouseup',document_event_mouseup):document.addEventListener('mouseup',document_event_mouseup,''); } function document_event_mousemove(e) { var e, obj; obj=document.getElementById(tdialogname); e=window.event?window.event:e; with(obj.style){ position='absolute'; left=e.clientX-obj.startX+'px'; top=e.clientY-obj.startY+'px'; } } function document_event_mouseup(e) { var temp; document.onmousemove=''; temp=document.detachEvent?parent.detachEvent('onmouseup',document_event_mouseup):document.removeEventListener('mouseup',document_event_mouseup,''); } window.onresize = function() { var d_mask=document.getElementById(tmsgname); var d_dialog = document.getElementById(tdialogname); d_mask.style.width = document.body.clientWidth ; d_mask.style.height=document.body.clientHeight; } /* 使用说明 1、首先在周用页面引入此js页面 这里的#dialog根据div名称而定 2、添加css样式, <style type='text/css'> .#dialog{ visibility: hidden; background-color: #f7fcfe; z-index: 100; width: 300px; position: absolute; height: 200px; } </style> 3、在定义一个函数 给相关的项赋值,如: //CsArr["title"]为显示标题 CsArr["msg"]为显示内容 CsArr["msgname"]父页面中div的id 显示对话框窗口 CsArr["dialogname"]父页面中div的id 显示对话框窗口 CsArr["heightnum"] 对话框的距离屏幕顶端高度 CsArr["widthnum"]//对话框的距离屏幕顶端宽度 4、在父页面里的相关标签调用函数"show(CsArr)" */
JavaScript
/* // ClearBox Config File (JavaScript) */ var // CB layout: CB_WindowColor='transparent', // color of the CB window (note: you have to change the rounded-corner PNGs too!), transparent is also working CB_MinWidth=120, // minimum (only at images) or initial width of CB window CB_MinHeight=120, // initial heigth of CB window CB_WinPadd=25, // padding of the CB window from sides of the browser CB_RoundPix=0, // change this setting only if you are generating new PNGs for rounded corners CB_ImgBorder=0, // border size around the picture in CB window CB_ImgBorderColor='#ddd', // border color around the picture in CB window CB_Padd=3, // padding around inside the CB window CB_BodyMarginLeft=0, // CB_BodyMarginRight=0, // if you set margin to <body>, CB_BodyMarginTop=0, // please change these settings! CB_BodyMarginBottom=0, // CB_ShowThumbnails='auto', // it tells CB how to show the thumbnails ('auto', 'always' or 'off') thumbnails are only in picture-mode! CB_ThumbsBGColor='#000', // color of the thumbnail layer CB_ThumbsBGOpacity=.75, // opacity of the thumbnail layer CB_ActThumbOpacity=.5, // thumbnail opacity of the current viewed image CB_SlideShowBarColor='#000', // color of the slideshow bar CB_SlideShowBarOpacity=.5, // opacity of the slideshow bar CB_SlideShowBarPadd=2, // padding of the slideshow bar (left and right) CB_SlideShowBarTop=2, // position of the slideshow bar from the top of the picture CB_SimpleDesign='off', // if it's 'on', CB doesn't show the frame but only the content - really nice ;) CB_CloseBtnTop=-14, // vertical position of the close button in picture mode CB_CloseBtnRight=-27, // horizontal position of the close button in picture mode CB_CloseBtn2Top=-14, // vertical position of the close button in content mode CB_CloseBtn2Right=-27, // horizontal position of the close button in content mode CB_OSD='on', // turns on OSD // CB font, text and navigation (at the bottom of CB window) settings: CB_FontT='Verdana', // CB_FontSizeT=12, // these variables are referring to the title or caption line CB_FontColorT='#ddd', // CB_FontWeightT='normal', // CB_FontC='arial', // CB_FontSizeC=11, // these variables are referring to CB_FontColorC='#aaa', // comment lines under the title CB_FontWeightC='normal', // CB_TextAlignC='justify', // CB_TxtHMax=42, // maximum height of the comment box in pixels CB_FontG='arial', // CB_FontSizeG=11, // these variables are referring to the gallery name CB_FontColorG='#777', // CB_FontWeightG='normal', // CB_TextH=35, // default height of the text area under the content in CB window (adding a comment will modify this setting), if you change the font sizes, you maybe have to change this setting CB_PadT=10, // space in pixels between the content and the title or caption line CB_ShowURL='off', // it shows the url of the content if no title or caption is given CB_ItemNum='on', // it shows the ordinal number of the content in galleries CB_ItemNumBracket='()', // whatever you want ;) CB_ShowGalName='on', // it shows gallery name CB_TextNav='on', // it shows previous and next navigation CB_NavTextImgPrvNxt='on', // it shows previous and next buttons instead of text CB_ShowDL='on', // it shows download controls CB_NavTextImgDL='on', // it shows download buttons instead of text CB_ImgRotation='on', // it shows the image rotation controls CB_NavTextImgRot='on', // it shows the image rotation buttons instead of text // Settings of the document-hiding layer: CB_HideColor='#000', // color of the layer CB_HideOpacity=.9, // opacity (0 is invisible, 1 is 100% color) of the layer CB_HideOpacitySpeed=400, // speed of fading CB_CloseOnH='on', // CB will close, if you click on background // CB animation settings: CB_Animation='grow', // 'double', 'normal', 'off', 'grow' or 'warp' (high cpu usage) CB_ImgOpacitySpeed=450, // speed of content fading (in ms) CB_TextOpacitySpeed=350, // speed of text fading under the picture (in ms) CB_AnimSpeed=400, // speed of the resizing animation of CB window (in ms) CB_ImgTextFade='on', // turns on or off the fading of content and text CB_FlashHide='off', // it hides flash animations on the page before CB starts CB_SelectsHide='on', // it hides select boxes on the page before CB starts CB_SlShowTime=7, // default speed of the slideshow (in sec) CB_Preload='on', // preload neighbour pictures in galleries // Images using by CB settings: CB_PictureStart='start.png', // CB_PicturePause='pause.png', // CB_PictureClose='close.png', // filenames of some images using by clearbox CB_PictureNext='next.png', // (there are other images specified in clearbox.css!) CB_PicturePrev='prev.png', // // CB professional settings: CB_PicDir=CB_ScriptDir+'/config/'+CB_Config+'/pic', // CHANGE ONLY IF YOU CHANGED THE DEFAULT DIRECTORY-STRUCTURE OF CB! CB_AllowedToRun='on', // if 'off', CB won't start (you can change this variable without reload!) CB_AllowExtFunctLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionLoad(); every time after a new content has loaded (useful for audit, etc) CB_AllowExtFunctPageLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionPageLoad(); after your page has fully loaded CB_AllowExtFunctCBClose='off' // if 'on', CB will run a function named CB_ExternalFunctionCBClose(); after CB window has closed ;
JavaScript
/* // ClearBox Config File (JavaScript) */ var // CB layout: CB_WindowColor='#fff', // color of the CB window (note: you have to change the rounded-corner PNGs too!), transparent is also working CB_MinWidth=120, // minimum (only at images) or initial width of CB window CB_MinHeight=120, // initial heigth of CB window CB_WinPadd=15, // padding of the CB window from sides of the browser CB_RoundPix=12, // change this setting only if you are generating new PNGs for rounded corners CB_ImgBorder=0, // border size around the picture in CB window CB_ImgBorderColor='#ddd', // border color around the picture in CB window CB_Padd=4, // padding around inside the CB window CB_BodyMarginLeft=5, // CB_BodyMarginRight=5, // if you set margin to <body>, CB_BodyMarginTop=0, // please change these settings! CB_BodyMarginBottom=0, // CB_ShowThumbnails='auto', // it tells CB how to show the thumbnails ('auto', 'always' or 'off') thumbnails are only in picture-mode! CB_ThumbsBGColor='#000', // color of the thumbnail layer CB_ThumbsBGOpacity=.35, // opacity of the thumbnail layer CB_ActThumbOpacity=.65, // thumbnail opacity of the current viewed image CB_SlideShowBarColor='#fff', // color of the slideshow bar CB_SlideShowBarOpacity=.5, // opacity of the slideshow bar CB_SlideShowBarPadd=17, // padding of the slideshow bar (left and right) CB_SlideShowBarTop=2, // position of the slideshow bar from the top of the picture CB_SimpleDesign='off', // if it's 'on', CB doesn't show the frame but only the content - really nice ;) CB_CloseBtnTop=-10, // vertical position of the close button in picture mode CB_CloseBtnRight=-14, // horizontal position of the close button in picture mode CB_CloseBtn2Top=-20, // vertical position of the close button in content mode CB_CloseBtn2Right=-30, // horizontal position of the close button in content mode CB_OSD='on', // turns on OSD // CB font, text and navigation (at the bottom of CB window) settings: CB_FontT='Verdana', // CB_FontSizeT=12, // these variables are referring to the title or caption line CB_FontColorT='#777', // CB_FontWeightT='normal', // CB_FontC='arial', // CB_FontSizeC=11, // these variables are referring to CB_FontColorC='#aaa', // comment lines under the title CB_FontWeightC='normal', // CB_TextAlignC='justify', // CB_TxtHMax=42, // maximum height of the comment box in pixels CB_FontG='arial', // CB_FontSizeG=11, // these variables are referring to the gallery name CB_FontColorG='#999', // CB_FontWeightG='normal', // CB_TextH=35, // default height of the text area under the content in CB window (adding a comment will modify this setting), if you change the font sizes, you maybe have to change this setting CB_PadT=10, // space in pixels between the content and the title or caption line CB_ShowURL='off', // it shows the url of the content if no title or caption is given CB_ItemNum='on', // it shows the ordinal number of the content in galleries CB_ItemNumBracket='()', // whatever you want ;) CB_ShowGalName='on', // it shows gallery name CB_TextNav='on', // it shows previous and next navigation CB_NavTextImgPrvNxt='on', // it shows previous and next buttons instead of text CB_ShowDL='on', // it shows download controls CB_NavTextImgDL='on', // it shows download buttons instead of text CB_ImgRotation='on', // it shows the image rotation controls CB_NavTextImgRot='on', // it shows the image rotation buttons instead of text // Settings of the document-hiding layer: CB_HideColor='#000', // color of the layer CB_HideOpacity=.85, // opacity (0 is invisible, 1 is 100% color) of the layer CB_HideOpacitySpeed=400, // speed of fading CB_CloseOnH='on', // CB will close, if you click on background // CB animation settings: CB_Animation='double', // 'double', 'normal', 'off', 'grow' or 'warp' (high cpu usage) CB_ImgOpacitySpeed=450, // speed of content fading (in ms) CB_TextOpacitySpeed=350, // speed of text fading under the picture (in ms) CB_AnimSpeed=400, // speed of the resizing animation of CB window (in ms) CB_ImgTextFade='on', // turns on or off the fading of content and text CB_FlashHide='off', // it hides flash animations on the page before CB starts CB_SelectsHide='on', // it hides select boxes on the page before CB starts CB_SlShowTime=5, // default speed of the slideshow (in sec) CB_Preload='on', // preload neighbour pictures in galleries // Images using by CB settings: CB_PictureStart='start.png', // CB_PicturePause='pause.png', // CB_PictureClose='close.png', // filenames of some images using by clearbox CB_PictureNext='next.png', // (there are other images specified in clearbox.css!) CB_PicturePrev='prev.png', // // CB professional settings: CB_PicDir=CB_ScriptDir+'/config/'+CB_Config+'/pic', // CHANGE ONLY IF YOU CHANGED THE DEFAULT DIRECTORY-STRUCTURE OF CB! CB_AllowedToRun='on', // if 'off', CB won't start (you can change this variable without reload!) CB_AllowExtFunctLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionLoad(); every time after a new content has loaded (useful for audit, etc) CB_AllowExtFunctPageLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionPageLoad(); after your page has fully loaded CB_AllowExtFunctCBClose='off' // if 'on', CB will run a function named CB_ExternalFunctionCBClose(); after CB window has closed ;
JavaScript
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='previous', // text of previous image CB_NavTextNxt='next', // text of next image CB_NavTextFull='full size', // text of original size (only at pictures) CB_NavTextOpen='open in new browser window', // text of open in a new browser window CB_NavTextDL='download', // text of download picture or any other content CB_NavTextClose='close clearbox', // text of close CB CB_NavTextStart='start slideshow', // text of start slideshow CB_NavTextStop='stop slideshow', // text of stop slideshow CB_NavTextRotR='rotate image right by 90 degrees', // text of rotation right CB_NavTextRotL='rotate image left by 90 degrees' // text of rotation left ;
JavaScript
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='上一张', // text of previous image CB_NavTextNxt='下一张', // text of next image CB_NavTextFull='', // text of original size (only at pictures) CB_NavTextOpen='Open to new Page', // text of open in a new browser window CB_NavTextDL='Download', // text of download picture or any other content CB_NavTextClose='Close', // text of close CB CB_NavTextStart='', // text of start slideshow CB_NavTextStop='停止幻灯片', // text of stop slideshow CB_NavTextRotR='向右旋转90', // text of rotation right CB_NavTextRotL='向左旋转90' // text of rotation left ;
JavaScript
/* // ClearBox Config File (JavaScript) */ var // CB layout: CB_WindowColor='transparent', // color of the CB window (note: you have to change the rounded-corner PNGs too!), transparent is also working CB_MinWidth=120, // minimum (only at images) or initial width of CB window CB_MinHeight=120, // initial heigth of CB window CB_WinPadd=25, // padding of the CB window from sides of the browser CB_RoundPix=0, // change this setting only if you are generating new PNGs for rounded corners CB_ImgBorder=0, // border size around the picture in CB window CB_ImgBorderColor='#ddd', // border color around the picture in CB window CB_Padd=3, // padding around inside the CB window CB_BodyMarginLeft=0, // CB_BodyMarginRight=0, // if you set margin to <body>, CB_BodyMarginTop=0, // please change these settings! CB_BodyMarginBottom=0, // CB_ShowThumbnails='auto', // it tells CB how to show the thumbnails ('auto', 'always' or 'off') thumbnails are only in picture-mode! CB_ThumbsBGColor='#000', // color of the thumbnail layer CB_ThumbsBGOpacity=.75, // opacity of the thumbnail layer CB_ActThumbOpacity=.5, // thumbnail opacity of the current viewed image CB_SlideShowBarColor='#000', // color of the slideshow bar CB_SlideShowBarOpacity=.5, // opacity of the slideshow bar CB_SlideShowBarPadd=2, // padding of the slideshow bar (left and right) CB_SlideShowBarTop=2, // position of the slideshow bar from the top of the picture CB_SimpleDesign='off', // if it's 'on', CB doesn't show the frame but only the content - really nice ;) CB_CloseBtnTop=-14, // vertical position of the close button in picture mode CB_CloseBtnRight=-27, // horizontal position of the close button in picture mode CB_CloseBtn2Top=-14, // vertical position of the close button in content mode CB_CloseBtn2Right=-27, // horizontal position of the close button in content mode CB_OSD='on', // turns on OSD // CB font, text and navigation (at the bottom of CB window) settings: CB_FontT='Verdana', // CB_FontSizeT=12, // these variables are referring to the title or caption line CB_FontColorT='#ddd', // CB_FontWeightT='normal', // CB_FontC='arial', // CB_FontSizeC=11, // these variables are referring to CB_FontColorC='#aaa', // comment lines under the title CB_FontWeightC='normal', // CB_TextAlignC='justify', // CB_TxtHMax=42, // maximum height of the comment box in pixels CB_FontG='arial', // CB_FontSizeG=11, // these variables are referring to the gallery name CB_FontColorG='#777', // CB_FontWeightG='normal', // CB_TextH=35, // default height of the text area under the content in CB window (adding a comment will modify this setting), if you change the font sizes, you maybe have to change this setting CB_PadT=10, // space in pixels between the content and the title or caption line CB_ShowURL='off', // it shows the url of the content if no title or caption is given CB_ItemNum='on', // it shows the ordinal number of the content in galleries CB_ItemNumBracket='()', // whatever you want ;) CB_ShowGalName='on', // it shows gallery name CB_TextNav='on', // it shows previous and next navigation CB_NavTextImgPrvNxt='on', // it shows previous and next buttons instead of text CB_ShowDL='on', // it shows download controls CB_NavTextImgDL='on', // it shows download buttons instead of text CB_ImgRotation='on', // it shows the image rotation controls CB_NavTextImgRot='on', // it shows the image rotation buttons instead of text // Settings of the document-hiding layer: CB_HideColor='#000', // color of the layer CB_HideOpacity=.9, // opacity (0 is invisible, 1 is 100% color) of the layer CB_HideOpacitySpeed=400, // speed of fading CB_CloseOnH='on', // CB will close, if you click on background // CB animation settings: CB_Animation='grow', // 'double', 'normal', 'off', 'grow' or 'warp' (high cpu usage) CB_ImgOpacitySpeed=450, // speed of content fading (in ms) CB_TextOpacitySpeed=350, // speed of text fading under the picture (in ms) CB_AnimSpeed=400, // speed of the resizing animation of CB window (in ms) CB_ImgTextFade='on', // turns on or off the fading of content and text CB_FlashHide='off', // it hides flash animations on the page before CB starts CB_SelectsHide='on', // it hides select boxes on the page before CB starts CB_SlShowTime=7, // default speed of the slideshow (in sec) CB_Preload='on', // preload neighbour pictures in galleries // Images using by CB settings: CB_PictureStart='start.png', // CB_PicturePause='pause.png', // CB_PictureClose='close.png', // filenames of some images using by clearbox CB_PictureNext='next.png', // (there are other images specified in clearbox.css!) CB_PicturePrev='prev.png', // // CB professional settings: CB_PicDir=CB_ScriptDir+'/config/'+CB_Config+'/pic', // CHANGE ONLY IF YOU CHANGED THE DEFAULT DIRECTORY-STRUCTURE OF CB! CB_AllowedToRun='on', // if 'off', CB won't start (you can change this variable without reload!) CB_AllowExtFunctLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionLoad(); every time after a new content has loaded (useful for audit, etc) CB_AllowExtFunctPageLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionPageLoad(); after your page has fully loaded CB_AllowExtFunctCBClose='off' // if 'on', CB will run a function named CB_ExternalFunctionCBClose(); after CB window has closed ;
JavaScript
/* // ClearBox Config File (JavaScript) */ var // CB layout: CB_WindowColor='#fff', // color of the CB window (note: you have to change the rounded-corner PNGs too!), transparent is also working CB_MinWidth=120, // minimum (only at images) or initial width of CB window CB_MinHeight=120, // initial heigth of CB window CB_WinPadd=15, // padding of the CB window from sides of the browser CB_RoundPix=12, // change this setting only if you are generating new PNGs for rounded corners CB_ImgBorder=0, // border size around the picture in CB window CB_ImgBorderColor='#ddd', // border color around the picture in CB window CB_Padd=4, // padding around inside the CB window CB_BodyMarginLeft=0, // CB_BodyMarginRight=0, // if you set margin to <body>, CB_BodyMarginTop=0, // please change these settings! CB_BodyMarginBottom=0, // CB_ShowThumbnails='auto', // it tells CB how to show the thumbnails ('auto', 'always' or 'off') thumbnails are only in picture-mode! CB_ThumbsBGColor='#000', // color of the thumbnail layer CB_ThumbsBGOpacity=.35, // opacity of the thumbnail layer CB_ActThumbOpacity=.65, // thumbnail opacity of the current viewed image CB_SlideShowBarColor='#fff', // color of the slideshow bar CB_SlideShowBarOpacity=.5, // opacity of the slideshow bar CB_SlideShowBarPadd=17, // padding of the slideshow bar (left and right) CB_SlideShowBarTop=2, // position of the slideshow bar from the top of the picture CB_SimpleDesign='off', // if it's 'on', CB doesn't show the frame but only the content - really nice ;) CB_CloseBtnTop=-10, // vertical position of the close button in picture mode CB_CloseBtnRight=-14, // horizontal position of the close button in picture mode CB_CloseBtn2Top=-20, // vertical position of the close button in content mode CB_CloseBtn2Right=-30, // horizontal position of the close button in content mode CB_OSD='on', // turns on OSD // CB font, text and navigation (at the bottom of CB window) settings: CB_FontT='Verdana', // CB_FontSizeT=12, // these variables are referring to the title or caption line CB_FontColorT='#777', // CB_FontWeightT='normal', // CB_FontC='arial', // CB_FontSizeC=11, // these variables are referring to CB_FontColorC='#aaa', // comment lines under the title CB_FontWeightC='normal', // CB_TextAlignC='justify', // CB_TxtHMax=42, // maximum height of the comment box in pixels CB_FontG='arial', // CB_FontSizeG=11, // these variables are referring to the gallery name CB_FontColorG='#999', // CB_FontWeightG='normal', // CB_TextH=35, // default height of the text area under the content in CB window (adding a comment will modify this setting), if you change the font sizes, you maybe have to change this setting CB_PadT=10, // space in pixels between the content and the title or caption line CB_ShowURL='off', // it shows the url of the content if no title or caption is given CB_ItemNum='on', // it shows the ordinal number of the content in galleries CB_ItemNumBracket='()', // whatever you want ;) CB_ShowGalName='on', // it shows gallery name CB_TextNav='on', // it shows previous and next navigation CB_NavTextImgPrvNxt='on', // it shows previous and next buttons instead of text CB_ShowDL='on', // it shows download controls CB_NavTextImgDL='on', // it shows download buttons instead of text CB_ImgRotation='on', // it shows the image rotation controls CB_NavTextImgRot='on', // it shows the image rotation buttons instead of text // Settings of the document-hiding layer: CB_HideColor='#000', // color of the layer CB_HideOpacity=.85, // opacity (0 is invisible, 1 is 100% color) of the layer CB_HideOpacitySpeed=400, // speed of fading CB_CloseOnH='on', // CB will close, if you click on background // CB animation settings: CB_Animation='double', // 'double', 'normal', 'off', 'grow' or 'warp' (high cpu usage) CB_ImgOpacitySpeed=450, // speed of content fading (in ms) CB_TextOpacitySpeed=350, // speed of text fading under the picture (in ms) CB_AnimSpeed=400, // speed of the resizing animation of CB window (in ms) CB_ImgTextFade='on', // turns on or off the fading of content and text CB_FlashHide='off', // it hides flash animations on the page before CB starts CB_SelectsHide='on', // it hides select boxes on the page before CB starts CB_SlShowTime=5, // default speed of the slideshow (in sec) CB_Preload='on', // preload neighbour pictures in galleries // Images using by CB settings: CB_PictureStart='start.png', // CB_PicturePause='pause.png', // CB_PictureClose='close.png', // filenames of some images using by clearbox CB_PictureNext='next.png', // (there are other images specified in clearbox.css!) CB_PicturePrev='prev.png', // // CB professional settings: CB_PicDir=CB_ScriptDir+'/config/'+CB_Config+'/pic', // CHANGE ONLY IF YOU CHANGED THE DEFAULT DIRECTORY-STRUCTURE OF CB! CB_AllowedToRun='on', // if 'off', CB won't start (you can change this variable without reload!) CB_AllowExtFunctLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionLoad(); every time after a new content has loaded (useful for audit, etc) CB_AllowExtFunctPageLoad='off', // if 'on', CB will run a function named CB_ExternalFunctionPageLoad(); after your page has fully loaded CB_AllowExtFunctCBClose='off' // if 'on', CB will run a function named CB_ExternalFunctionCBClose(); after CB window has closed ;
JavaScript
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='previous', // text of previous image CB_NavTextNxt='next', // text of next image CB_NavTextFull='full size', // text of original size (only at pictures) CB_NavTextOpen='open in new browser window', // text of open in a new browser window CB_NavTextDL='download', // text of download picture or any other content CB_NavTextClose='close clearbox', // text of close CB CB_NavTextStart='start slideshow', // text of start slideshow CB_NavTextStop='stop slideshow', // text of stop slideshow CB_NavTextRotR='rotate image right by 90 degrees', // text of rotation right CB_NavTextRotL='rotate image left by 90 degrees' // text of rotation left ;
JavaScript
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='上一张', // text of previous image CB_NavTextNxt='下一张', // text of next image CB_NavTextFull='全尺寸', // text of original size (only at pictures) CB_NavTextOpen='在新的窗口中打开', // text of open in a new browser window CB_NavTextDL='下载', // text of download picture or any other content CB_NavTextClose='关闭窗口', // text of close CB CB_NavTextStart='幻灯片', // text of start slideshow CB_NavTextStop='停止幻灯片', // text of stop slideshow CB_NavTextRotR='向右旋转90', // text of rotation right CB_NavTextRotL='向左旋转90' // text of rotation left ;
JavaScript
var CB_ScriptDir='/jsLibrary/clearbox/clearbox'; var CB_Language='cn'; // // ClearBox load: // var CB_Scripts = document.getElementsByTagName('script'); for(i=0;i<CB_Scripts.length;i++){ if (CB_Scripts[i].getAttribute('src')){ var q=CB_Scripts[i].getAttribute('src'); if(q.match('clearbox.js')){ var url = q.split('clearbox.js'); var path = url[0]; var query = url[1].substring(1); var pars = query.split('&'); for(j=0; j<pars.length; j++) { par = pars[j].split('='); switch(par[0]) { case 'config': { CB_Config = par[1]; break; } case 'dir': { CB_ScriptDir = par[1]; break; } case 'lng': { CB_Language = par[1]; break; } } } } } } if(!CB_Config){ var CB_Config='default'; } document.write('<link rel="stylesheet" type="text/css" href="'+CB_ScriptDir+'/config/'+CB_Config+'/cb_style.css" />'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/config/'+CB_Config+'/cb_config.js"></script>'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/language/'+CB_Language+'/cb_language.js"></script>'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/core/cb_core.js"></script>');
JavaScript
// JavaScript Document function show(title,msg) { var d_mask=document.getElementById('mask'); var d_dialog =document.getElementById('dialog'); d_mask.style.width = document.body.clientWidth ; d_mask.style.height=document.body.clientHeight; d_dialog.style.top = document.body.clientHeight / 2 -260; d_dialog.style.left =document.body.clientWidth / 2 -100; var Inner = "<input type='button' value='Close' onclick='DialogClose()'/>" var info = "<table cellspacing='0' width='100%' height='100%'>"+ "<tr class='dgtitle'><td>" +title +"</td><td align='right'><input type='button' value='Close' onclick='DialogClose()'class='formButton'/></td></tr>" +"<tr><td colspan='2'>" +msg +"</td></tr>" +"<tr class='dgfooter'><td></td><td>" +"</td></tr>" +"</table>"; d_dialog.innerHTML =info; disableSelect() d_mask.style.visibility='visible'; d_dialog.style.visibility='visible'; } function Icon_Close_Over(obj) { obj.src='close.gif'; } function Icon_Close_Out(obj) { obj.src='close1.gif' } function DialogClose() { var d_mask=document.getElementById('mask'); var d_dialog = document.getElementById('dialog'); parent.getifheight();//当记录没有时或很少时还原其框架在原来的页面中的高度 enableSelect() d_mask.style.visibility='hidden'; d_dialog.style.visibility='hidden'; } function disableSelect() { for(i=0;i<document.all.length;i++) if(document.all(i).tagName=="SELECT") document.all(i).disabled = true; } function enableSelect() { for(i=0;i<document.all.length;i++){ if(document.all(i).tagName=="SELECT") { document.all(i).disabled = false; } } } function divBlock_event_mousedown() { var e, obj, temp; obj=document.getElementById('dialog'); e=window.event?window.event:e; obj.startX=e.clientX-obj.offsetLeft; obj.startY=e.clientY-obj.offsetTop; document.onmousemove=document_event_mousemove; temp=document.attachEvent?document.attachEvent('onmouseup',document_event_mouseup):document.addEventListener('mouseup',document_event_mouseup,''); } function document_event_mousemove(e) { var e, obj; obj=document.getElementById('dialog'); e=window.event?window.event:e; with(obj.style){ position='absolute'; left=e.clientX-obj.startX+'px'; top=e.clientY-obj.startY+'px'; } } function document_event_mouseup(e) { var temp; document.onmousemove=''; temp=document.detachEvent?parent.detachEvent('onmouseup',document_event_mouseup):document.removeEventListener('mouseup',document_event_mouseup,''); } window.onresize = function() { var d_mask=document.getElementById('mask'); var d_dialog = document.getElementById('dialog'); d_mask.style.width = document.body.clientWidth ; d_mask.style.height=document.body.clientHeight; }
JavaScript
/* clearbox by pyro script home: http://www.clearbox.hu email: clearboxjs(at)gmail(dot)com MSN: pyro(at)radiomax(dot)hu support forum 1: http://www.sg.hu/listazas.php3?id=1172325655 */ var CB_ScriptDir='/jsLibrary/clearbox'; var CB_Language='cn'; // // ClearBox load: // var CB_Scripts = document.getElementsByTagName('script'); for(i=0;i<CB_Scripts.length;i++){ if (CB_Scripts[i].getAttribute('src')){ var q=CB_Scripts[i].getAttribute('src'); if(q.match('clearbox.js')){ var url = q.split('clearbox.js'); var path = url[0]; var query = url[1].substring(1); var pars = query.split('&'); for(j=0; j<pars.length; j++) { par = pars[j].split('='); switch(par[0]) { case 'config': { CB_Config = par[1]; break; } case 'dir': { CB_ScriptDir = par[1]; break; } case 'lng': { CB_Language = par[1]; break; } } } } } } if(!CB_Config){ var CB_Config='default'; } document.write('<link rel="stylesheet" type="text/css" href="'+CB_ScriptDir+'/config/'+CB_Config+'/cb_style.css" />'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/config/'+CB_Config+'/cb_config.js"></script>'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/language/'+CB_Language+'/cb_language.js"></script>'); document.write('<script type="text/javascript" src="'+CB_ScriptDir+'/core/cb_core.js"></script>');
JavaScript
$.TE.plugin("bold",{ title:"标题", cmd:"bold", click:function(){ this.editor.pasteHTML("sdfdf"); }, bold:function(){ alert('sdfsdf'); }, noRight:function(e){ if(e.type=="click"){ alert('noright'); } }, init:function(){ }, event:"click mouseover mouseout", mouseover:function(e){ this.$btn.css("color","red"); }, mouseout:function(e){ this.$btn.css("color","#000") } });
JavaScript
function te_upload_interface() { //初始化参数 var _args = arguments, _fn = _args.callee, _data = ''; if( _args[0] == 'reg' ) { //注册回调 _data = _args[1]; _fn.curr = _data['callid']; _fn.data = _data; jQuery('#temaxsize').val(_data['maxsize']); } else if( _args[0] == 'get' ) { //获取配置 return _fn.data || false; } else if( _args[0] == 'call' ) { //处理回调与实例不一致 if( _args[1] != _fn.curr ) { alert( '上传出错,请不要同时打开多个上传弹窗' ); return false; } //上传成功 if( _args[2] == 'success' ) { _fn.data['callback']( _args[3] ); } //上传失败 else if( _args[2] == 'failure' ) { alert( '[上传失败]\n错误信息:'+_args[3] ); } //文件类型检测错误 else if( _args[2] == 'filetype' ) { alert( '[上传失败]\n错误信息:您上传的文件类型有误' ); } //处理状态改变 else if( _args[2] == 'change' ) { // TODO 更细致的回调实现,此处返回true自动提交 return true; } } } //用户选择文件时 function checkTypes(id){ //校验文件类型 var filename = document.getElementById( 'teupload' ).value, filetype = document.getElementById( 'tefiletype' ).value.split( ',' ); currtype = filename.split( '.' ).pop(), checktype = false; if( filetype[0] == '*' ) { checktype = true; } else { for(var i=0; i<filetype.length; i++) { if( currtype == filetype[i] ) { checktype = true; break; } } } if( !checktype ) { alert( '[上传失败]\n错误信息:您上传的文件类型有误' ); return false; } else { //校验通过,提交 jQuery('#'+id).submit() } }
JavaScript
// 系统自带插件 ( function ( $ ) { //全屏 $.TE.plugin( "fullscreen", { fullscreen:function(e){ var $btn = this.$btn, opt = this.editor.opt; if($btn.is("."+opt.cssname.fulled)){ //取消全屏 this.editor.$main.removeAttr("style"); this.editor.$bottom.find("div").show(); this.editor.resize(opt.width,opt.height); $("html,body").css("overflow","auto"); $btn.removeClass(opt.cssname.fulled); $(window).scrollTop(this.scrolltop); }else{ //全屏 this.scrolltop=$(window).scrollTop(); this.editor.$main.attr("style","z-index:900000;position:absolute;left:0;top:0px"); $(window).scrollTop(0); $("html,body").css("overflow","hidden");//隐藏滚蛋条 this.editor.$bottom.find("div").hide();//隐藏底部的调整大小控制块 this.editor.resize($(window).width(),$(window).height()); $btn.addClass(opt.cssname.fulled); } } } ); //切换源码 $.TE.plugin( "source", { source:function(e){ var $btn = this.$btn, $area = this.editor.$area, $frame = this.editor.$frame, opt = this.editor.opt, _self = this; if($btn.is("."+opt.cssname.sourceMode)){ //切换到可视化 _self.editor.core.updateFrame(); $area.hide(); $frame.show(); $btn.removeClass(opt.cssname.sourceMode); }else{ //切换到源码 _self.editor.core.updateTextArea(); $area.show(); $frame.hide(); $btn.addClass(opt.cssname.sourceMode); } setTimeout(function(){_self.editor.refreshBtn()},100); } } ); //剪切 $.TE.plugin( 'cut', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+X快捷键完成操作。'); } else { this.exec(); } } }); //复制 $.TE.plugin( 'copy', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+C快捷键完成操作。'); } else { this.exec(); } } }); //粘贴 $.TE.plugin( 'paste', { click: function() { if( $.browser.mozilla ) { alert('您的浏览器安全设置不支持该操作,请使用Ctrl/Cmd+V快捷键完成操作。'); } else { this.exec(); } } }); //创建链接 $.TE.plugin( "link", { click:function(e){ var _self = this; var $html = $( '<div class="te_dialog_link Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">创建链接</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">链接地址:</span>'+ ' <div class="Lfll">'+ ' <input id="te_dialog_url" name="" type="text" class="Lfll input1" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); if( _self.isie6() ) { window.selectionCache = [ /* 暂存选区对象 */ _self.editor.doc.selection.createRange(), /* 选区html内容 */ _self.editor.doc.selection.createRange().htmlText, /* 选区文本用来计算差值 */ _self.editor.doc.selection.createRange().text ]; } this.createDialog({ body:$html, ok:function(){ _self.value=$html.find("#te_dialog_url").val(); if( _self.isie6() ) { var _sCache = window.selectionCache, str1 = '<a href="'+_self.value+'">'+_sCache[1]+'</a>', str2 = '<a href="'+_self.value+'">'+_sCache[2]+'</a>'; _sCache[0].pasteHTML( str1 ); _sCache[0].moveStart( 'character', -_self.strlen( str2 ) + ( str2.length - _sCache[2].length ) ); _sCache[0].moveEnd( 'character', -0 ); _sCache[0].select(); //置空暂存对象 window.selectionCache = _sCache = null; } else { _self.exec(); } _self.hideDialog(); } }); }, strlen : function ( str ) { return window.ActiveXObject && str.indexOf("\n") != -1 ? str.replace(/\r?\n/g, "_").length : str.length; }, isie6 : function () { return $.browser.msie && $.browser.version == '6.0' ? true : false; } } ); $.TE.plugin( 'print', { click: function(e) { var _win = this.editor.core.$frame[0].contentWindow; if($.browser.msie) { this.exec(); } else if(_win.print) { _win.print(); } else { alert('您的系统不支持打印接口'); } } } ); $.TE.plugin( 'pagebreak', { exec: function() { var _self = this; _self.editor.pasteHTML('<div style="page-break-after: always;zoom:1; height:0px; clear:both; display:block; overflow:hidden; border-top:2px dotted #CCC;">&nbsp;</div><p>&nbsp;</p>'); } } ); $.TE.plugin( 'pastetext', { exec: function() { var _self = this, _html = ''; clipData = window.clipboardData ? window.clipboardData.getData('text') : false; if( clipData ) { _self.editor.pasteHTML( clipData.replace( /\r\n/g, '<br />' ) ); } else { _html = $( '<div class="te_dialog_pasteText">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">贴粘文本</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="pasteText">'+ ' <span class="tips Lmt5">请使用键盘快捷键(Ctrl/Cmd+V)把内容粘贴到下面的方框里。</span>'+ ' <textarea id="pasteText" name="" class="tarea1 Lmt5" rows="10" cols="30"></textarea>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : _html, ok : function(){ _self.editor.pasteHTML(_html.find('#pasteText').val().replace(/\n/g, '<br />')); _self.hideDialog(); } }); } } } ); $.TE.plugin( 'table', { exec : function (e) { var _self = this, _html = ''; _html = $( '<div class="te_dialog_table">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入表格</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertTable">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">行数:</span>'+ ' <input type="text" id="te_tab_rows" class="input1 Lfll" value="3" />'+ ' <span class="ltext Lfll">列数:</span>'+ ' <input type="text" id="te_tab_cols" class="input1 Lfll" value="2" />'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">宽度:</span>'+ ' <input type="text" id="te_tab_width" class="input1 Lfll" value="500" />'+ ' <span class="ltext Lfll">高度:</span>'+ ' <input type="text" id="te_tab_height" class="input1 Lfll" />'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">边框:</span>'+ ' <input type="text" id="te_tab_border" class="input1 Lfll" value="1" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : _html, ok : function () { //获取参数 var rows = parseInt(_html.find('#te_tab_rows').val()), cols = parseInt(_html.find('#te_tab_cols').val()), width = parseInt(_html.find('#te_tab_width').val()), height = parseInt(_html.find('#te_tab_height').val()), border = parseInt(_html.find('#te_tab_border').val()), tab_html = '<table width="'+width+'" border="'+border+'"'; if(height) tab_html += ' height="'+height+'"'; tab_html += '>'; for(var i=0; i<rows; i++) { tab_html += '<tr>'; for(var j=0; j<cols; j++) { tab_html += '<td>&nbsp;</td>'; } tab_html += '</tr>'; } tab_html += '</table>'; _self.editor.pasteHTML( tab_html ); _self.hideDialog(); } }); } } ); $.TE.plugin( 'blockquote', { exec : function () { var _self = this, _doc = _self.editor.doc, elem = '', //当前对象 isquote = false, //是否已被引用 node = '', child = false; //找到的引用对象 //取得当前对象 node = elem = this.getElement(); //判断是否已被引用 while( node !== _doc.body ) { if( node.nodeName.toLowerCase() == 'blockquote' ){ isquote = true; break; } node = node.parentNode; } if( isquote ) { //如果存在引用,则清理 if( node === _doc.body ) { node.innerHTML = elem.parentNode.innerHTML; } else { while (child = node.firstChild) { node.parentNode.insertBefore(child, node); } node.parentNode.removeChild(node); } } else { //不存在引用,创建引用 if( $.browser.msie ) { if( elem === _doc.body ) { elem.innerHTML = '<blockquote>' + elem.innerHTML + '</blockquote>'; } else { elem.outerHTML = '<blockquote>' + elem.outerHTML + '</blockquote>'; } } else { _doc.execCommand( 'formatblock', false, '<blockquote>' ) } } }, getElement : function () { var ret = false; if( $.browser.msie ) { ret = this.editor.doc.selection.createRange().parentElement(); } else { ret = this.editor.$frame.get( 0 ).contentWindow.getSelection().getRangeAt( 0 ).startContainer; } return ret; } } ); $.TE.plugin( 'image', { upid : 'te_image_upload', uptype : [ 'jpg', 'jpeg', 'gif', 'png', 'bmp' ], //文件大小 maxsize : 1024*1024*1024*2, // 2MB exec : function() { var _self = this, //上传地址 updir = _self.editor.opt.uploadURL, //传给上传页的参数 parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date()); if(updir && updir!='about:blank'){ if( updir.indexOf('?') > -1 ) { updir += '&' + parame; } else { updir += '?' + parame; } //弹出窗内容 var $html = $( '<div class="te_dialog_image">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="#" class="cstyle">插入图片</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertimage Lmt20 Lpb10">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">图片地址:</span>'+ ' <div class="Lfll Lovh">'+ ' <input type="text" id="te_image_url" class="imageurl input1 Lfll Lmr5" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">上传图片:</span>'+ ' <div class="Lfll Lovh">'+ ' <form id="form_img" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+ ' <div class="filebox">'+ ' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_img\');" class="upinput" type="file" hidefocus="true" />'+ ' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+ ' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+ ' <span class="upbtn">上传</span>'+ ' </div>'+ ' </form>'+ ' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">图片宽度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_image_width" name="" type="text" class="input2" />'+ ' </div>'+ ' <span class="ltext Lfll">图片高度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_image_height" name="" type="text" class="input2" />'+ ' </div>'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ), _upcall = function(path) { //获取上传的值 $html.find( '#te_image_url' ).val(path); // 刷新iframe上传页 //var _url = $html.find( 'iframe' ).attr( 'src' ); //_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) ); $html.find( 'iframe' ).attr( 'src', 'about:blank' ); } //注册通信 te_upload_interface( 'reg', { 'callid' : this.upid+this.editor.guid, 'filetype': this.uptype, 'maxsize' : this.maxsize, 'callback': _upcall } ); //创建对话框 this.createDialog( { body : $html, ok : function() { var _src = $html.find('#te_image_url').val(), _width = parseInt($html.find('#te_image_width').val()), _height = parseInt($html.find('#te_image_height').val()); _src = _APP+_src; var _insertHTML = '<img src="'+(_src||'http://www.baidu.com/img/baidu_sylogo1.gif')+'" '; if( _width ) _insertHTML += 'width="'+_width+'" '; if( _height ) _insertHTML += 'height="'+_height+'" '; _insertHTML += '/>'; _self.editor.pasteHTML( _insertHTML ); _self.hideDialog(); } } ); }else{ alert('请配置上传处理路径!'); } } } ); $.TE.plugin( 'flash', { upid : 'te_flash_upload', uptype : [ 'swf' ], //文件大小 maxsize : 1024*1024*1024*2, // 2MB exec : function() { var _self = this, //上传地址 updir = _self.editor.opt.uploadURL, //传给上传页的参数 parame = 'callback='+this.upid+this.editor.guid+'&rands='+(+new Date()); if(updir && updir!='about:blank'){ if( updir.indexOf('?') > -1 ) { updir += '&' + parame; } else { updir += '?' + parame; } //弹出窗内容 var $html = $( '<div class="te_dialog_flash">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入flash动画</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="insertflash Lmt20 Lpb10">'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">flash地址:</span>'+ ' <div class="Lfll Lovh">'+ ' <input id="te_flash_url" type="text" class="imageurl input1 Lfll Lmr5" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">上传flash:</span>'+ ' <div class="Lfll Lovh">'+ ' <form id="form_swf" enctype="multipart/form-data" action="'+updir+'" method="POST" target="upifrem">'+ ' <div class="filebox">'+ ' <input id="teupload" name="teupload" size="1" onchange="checkTypes(\'form_swf\');" class="upinput" type="file" hidefocus="true" />'+ ' <input id="tefiletype" name="tefiletype" type="hidden" value="'+this.uptype+'" />'+ ' <input id="temaxsize" name="temaxsize" type="hidden" value="'+this.maxsize+'" />'+ ' <span class="upbtn">上传</span>'+ ' </div>'+ ' </form>'+ ' <iframe name="upifrem" id="upifrem" width="70" height="22" class="Lfll" scrolling="no" frameborder="0"></iframe>'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">宽度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_width" name="" type="text" class="input2" value="200" />'+ ' </div>'+ ' <span class="ltext Lfll">高度:</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_height" name="" type="text" class="input2" value="60" />'+ ' </div>'+ ' </div>'+ ' <div class="item Lovh">'+ ' <span class="ltext Lfll">&nbsp;</span>'+ ' <div class="Lfll">'+ ' <input id="te_flash_wmode" name="" type="checkbox" class="input3" />'+ ' <label for="te_flash_wmode" class="labeltext">开启背景透明</label>'+ ' </div>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ), _upcall = function(path) { //获取上传的值 $html.find( '#te_flash_url' ).val(path); // 刷新iframe上传页 //var _url = $html.find( 'iframe' ).attr( 'src' ); //_url = _url.replace( /rands=[^&]+/, 'rands=' + (+ new Date()) ); $html.find( 'iframe' ).attr( 'src', 'about:blank' ); } //注册通信 te_upload_interface( 'reg', { 'callid' : this.upid+this.editor.guid, 'filetype': this.uptype, 'maxsize' : this.maxsize, 'callback': _upcall } ); //创建对话框 this.createDialog( { body : $html, ok : function() { var _src = $html.find('#te_flash_url').val(), _width = parseInt($html.find('#te_flash_width').val()), _height = parseInt($html.find('#te_flash_height').val()); _wmode = !!$html.find('#te_flash_wmode').attr('checked'); if( _src == '' ) { alert('请输入flash地址,或者从本地选择文件上传'); return true; } if( isNaN(_width) || isNaN(_height) ) { alert('请输入宽高'); return true; } _src = _APP+_src; var _data = "{'src':'"+_src+"','width':'"+_width+"','height':'"+_height+"','wmode':"+(_wmode)+"}"; var _insertHTML = '<img src="'+$.TE.basePath()+'skins/'+_self.editor.opt.skins+'/img/spacer.gif" class="_flash_position" style="'; if( _width ) _insertHTML += 'width:'+_width+'px;'; if( _height ) _insertHTML += 'height:'+_height+'px;'; _insertHTML += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:'+_height+'px;" '; _insertHTML += '_data="'+_data+'"'; _insertHTML += ' alt="flash占位符" />'; _self.editor.pasteHTML( _insertHTML ); _self.hideDialog(); } } ) }else{ alert('请配置上传处理路径!'); } } } ); $.TE.plugin( 'face', { exec: function() { var _self = this, //表情路径 _fp = _self.editor.opt.face_path, //弹出窗同容 $html = $( '<div class="te_dialog_face Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入表情</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="insertFace" style="background-image:url('+$.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'.gif'+');">'+ '<span face_num="0">&nbsp;</span>'+ '<span face_num="1">&nbsp;</span>'+ '<span face_num="2">&nbsp;</span>'+ '<span face_num="3">&nbsp;</span>'+ '<span face_num="4">&nbsp;</span>'+ '<span face_num="5">&nbsp;</span>'+ '<span face_num="6">&nbsp;</span>'+ '<span face_num="7">&nbsp;</span>'+ '<span face_num="8">&nbsp;</span>'+ '<span face_num="9">&nbsp;</span>'+ '<span face_num="10">&nbsp;</span>'+ '<span face_num="11">&nbsp;</span>'+ '<span face_num="12">&nbsp;</span>'+ '<span face_num="13">&nbsp;</span>'+ '<span face_num="14">&nbsp;</span>'+ '<span face_num="15">&nbsp;</span>'+ '<span face_num="16">&nbsp;</span>'+ '<span face_num="17">&nbsp;</span>'+ '<span face_num="18">&nbsp;</span>'+ '<span face_num="19">&nbsp;</span>'+ '<span face_num="20">&nbsp;</span>'+ '<span face_num="21">&nbsp;</span>'+ '<span face_num="22">&nbsp;</span>'+ '<span face_num="23">&nbsp;</span>'+ '<span face_num="24">&nbsp;</span>'+ '<span face_num="25">&nbsp;</span>'+ '<span face_num="26">&nbsp;</span>'+ '<span face_num="27">&nbsp;</span>'+ '<span face_num="28">&nbsp;</span>'+ '<span face_num="29">&nbsp;</span>'+ '<span face_num="30">&nbsp;</span>'+ '<span face_num="31">&nbsp;</span>'+ '<span face_num="32">&nbsp;</span>'+ '<span face_num="33">&nbsp;</span>'+ '<span face_num="34">&nbsp;</span>'+ '<span face_num="35">&nbsp;</span>'+ '<span face_num="36">&nbsp;</span>'+ '<span face_num="37">&nbsp;</span>'+ '<span face_num="38">&nbsp;</span>'+ '<span face_num="39">&nbsp;</span>'+ '<span face_num="40">&nbsp;</span>'+ '<span face_num="41">&nbsp;</span>'+ '<span face_num="42">&nbsp;</span>'+ '<span face_num="43">&nbsp;</span>'+ '<span face_num="44">&nbsp;</span>'+ '<span face_num="45">&nbsp;</span>'+ '<span face_num="46">&nbsp;</span>'+ '<span face_num="47">&nbsp;</span>'+ '<span face_num="48">&nbsp;</span>'+ '<span face_num="49">&nbsp;</span>'+ '<span face_num="50">&nbsp;</span>'+ '<span face_num="51">&nbsp;</span>'+ '<span face_num="52">&nbsp;</span>'+ '<span face_num="53">&nbsp;</span>'+ '<span face_num="54">&nbsp;</span>'+ '<span face_num="55">&nbsp;</span>'+ '<span face_num="56">&nbsp;</span>'+ '<span face_num="57">&nbsp;</span>'+ '<span face_num="58">&nbsp;</span>'+ '<span face_num="59">&nbsp;</span>'+ '<span face_num="60">&nbsp;</span>'+ '<span face_num="61">&nbsp;</span>'+ '<span face_num="62">&nbsp;</span>'+ '<span face_num="63">&nbsp;</span>'+ '<span face_num="64">&nbsp;</span>'+ '<span face_num="65">&nbsp;</span>'+ '<span face_num="66">&nbsp;</span>'+ '<span face_num="67">&nbsp;</span>'+ '<span face_num="68">&nbsp;</span>'+ '<span face_num="69">&nbsp;</span>'+ '<span face_num="70">&nbsp;</span>'+ '<span face_num="71">&nbsp;</span>'+ '<span face_num="72">&nbsp;</span>'+ '<span face_num="73">&nbsp;</span>'+ '<span face_num="74">&nbsp;</span>'+ '<span face_num="75">&nbsp;</span>'+ '<span face_num="76">&nbsp;</span>'+ '<span face_num="77">&nbsp;</span>'+ '<span face_num="78">&nbsp;</span>'+ '<span face_num="79">&nbsp;</span>'+ '<span face_num="80">&nbsp;</span>'+ '<span face_num="81">&nbsp;</span>'+ '<span face_num="82">&nbsp;</span>'+ '<span face_num="83">&nbsp;</span>'+ '<span face_num="84">&nbsp;</span>'+ '<span face_num="85">&nbsp;</span>'+ '<span face_num="86">&nbsp;</span>'+ '<span face_num="87">&nbsp;</span>'+ '<span face_num="88">&nbsp;</span>'+ '<span face_num="89">&nbsp;</span>'+ '<span face_num="90">&nbsp;</span>'+ '<span face_num="91">&nbsp;</span>'+ '<span face_num="92">&nbsp;</span>'+ '<span face_num="93">&nbsp;</span>'+ '<span face_num="94">&nbsp;</span>'+ '<span face_num="95">&nbsp;</span>'+ '<span face_num="96">&nbsp;</span>'+ '<span face_num="97">&nbsp;</span>'+ '<span face_num="98">&nbsp;</span>'+ '<span face_num="99">&nbsp;</span>'+ '<span face_num="100">&nbsp;</span>'+ '<span face_num="101">&nbsp;</span>'+ '<span face_num="102">&nbsp;</span>'+ '<span face_num="103">&nbsp;</span>'+ '<span face_num="104">&nbsp;</span>'+ '</div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); $html.find('.insertFace span').click(function( e ) { var _url = $.TE.basePath()+'skins/'+_fp[1]+'/'+_fp[0]+'_'+$( this ).attr( 'face_num' )+'.gif', _insertHtml = '<img src="'+_url+'" />'; _self.editor.pasteHTML( _insertHtml ); _self.hideDialog(); }); this.createDialog( { body : $html } ); } } ); $.TE.plugin( 'code', { exec: function() { var _self = this, $html = $( '<div class="te_dialog_code Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">插入代码</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="Lmt10 Lml10">'+ ' <span>选择语言:</span>'+ ' <select id="langType" name="">'+ ' <option value="None">其它类型</option>'+ ' <option value="PHP">PHP</option>'+ ' <option value="HTML">HTML</option>'+ ' <option value="JS">JS</option>'+ ' <option value="CSS">CSS</option>'+ ' <option value="SQL">SQL</option>'+ ' <option value="C#">C#</option>'+ ' <option value="JAVA">JAVA</option>'+ ' <option value="VBS">VBS</option>'+ ' <option value="VB">VB</option>'+ ' <option value="XML">XML</option>'+ ' </select>'+ ' </div>'+ ' <textarea id="insertCode" name="" rows="10" class="tarea1 Lmt10" cols="30"></textarea>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="确定" class="te_ok" />'+ ' <input type="button" value="取消" class="te_close" />'+ ' </div>'+ '</div>' ); this.createDialog({ body : $html, ok : function(){ var _code = $html.find('#insertCode').val(), _type = $html.find('#langType').val(), _html = ''; _code = _code.replace( /</g, '&lt;' ); _code = _code.replace( />/g, '&gt;' ); _code = _code.split('\n'); _html += '<pre style="overflow-x:auto; padding:10px; color:blue; border:1px dotted #2BC1FF; background-color:#EEFAFF;" _syntax="'+_type+'">' _html += '语言类型:'+_type; _html += '<ol style="list-stype-type:decimal;">'; for(var i=0; i<_code.length; i++) { _html += '<li>'+_code[i].replace( /^(\t+)/g, function( $1 ) {return $1.replace(/\t/g, ' ');} );+'</li>'; } _html += '</ol></pre><p>&nbsp;</p>'; _self.editor.pasteHTML( _html ); _self.hideDialog(); } }); } } ); $.TE.plugin( 'style', { click: function() { var _self = this, $html = $( '<div class="te_dialog_style Lovh">'+ ' <div class="centbox">'+ ' <h1 title="设置当前内容为一级标题"><a href="###">一级标题</a></h1>'+ ' <h2 title="设置当前内容为二级标题"><a href="###">二级标题</a></h2>'+ ' <h3 title="设置当前内容为三级标题"><a href="###">三级标题</a></h3>'+ ' <h4 title="设置当前内容为四级标题"><a href="###">四级标题</a></h4>'+ ' <h5 title="设置当前内容为五级标题"><a href="###">五级标题</a></h5>'+ ' <h6 title="设置当前内容为六级标题"><a href="###">六级标题</a></h6>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.nodeName; _self.value= _value; _self.exec(); //_self.hideDialog(); }; $html.find( '>.centbox>*' ).click( _call ); this.createDialog( { body: $html } ); }, exec: function() { var _self = this, _html = '<'+_self.value+'>'+_self.editor.selectedHTML()+'</'+_self.value+'>'; _self.editor.pasteHTML( _html ); } } ); $.TE.plugin( 'font', { click: function() { var _self = this; $html = $( '<div class="te_dialog_font Lovh">'+ ' <div class="centbox">'+ ' <div><a href="###" style="font-family:\'宋体\',\'SimSun\'">宋体</a></div>'+ ' <div><a href="###" style="font-family:\'楷体\',\'楷体_GB2312\',\'SimKai\'">楷体</a></div>'+ ' <div><a href="###" style="font-family:\'隶书\',\'SimLi\'">隶书</a></div>'+ ' <div><a href="###" style="font-family:\'黑体\',\'SimHei\'">黑体</a></div>'+ ' <div><a href="###" style="font-family:\'微软雅黑\'">微软雅黑</a></div>'+ ' <span>------</span>'+ ' <div><a href="###" style="font-family:arial,helvetica,sans-serif;">Arial</a></div>'+ ' <div><a href="###" style="font-family:comic sans ms,cursive;">Comic Sans Ms</a></div>'+ ' <div><a href="###" style="font-family:courier new,courier,monospace;">Courier New</a></div>'+ ' <div><a href="###" style="font-family:georgia,serif;">Georgia</a></div>'+ ' <div><a href="###" style="font-family:lucida sans unicode,lucida grande,sans-serif;">Lucida Sans Unicode</a></div>'+ ' <div><a href="###" style="font-family:tahoma,geneva,sans-serif;">Tahoma</a></div>'+ ' <div><a href="###" style="font-family:times new roman,times,serif;">Times New Roman</a></div>'+ ' <div><a href="###" style="font-family:trebuchet ms,helvetica,sans-serif;">Trebuchet Ms</a></div>'+ ' <div><a href="###" style="font-family:verdana,geneva,sans-serif;">Verdana</a></div>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.fontFamily; _self.value= _value; _self.exec(); }; $html.find( '>.centbox a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'fontsize', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontsize Lovh">'+ ' <div class="centbox">'+ ' <div><a href="#" style="font-size:10px">10</a></div>'+ ' <div><a href="#" style="font-size:12px">12</a></div>'+ ' <div><a href="#" style="font-size:14px">14</a></div>'+ ' <div><a href="#" style="font-size:16px">16</a></div>'+ ' <div><a href="#" style="font-size:18px">18</a></div>'+ ' <div><a href="#" style="font-size:20px">20</a></div>'+ ' <div><a href="#" style="font-size:22px">22</a></div>'+ ' <div><a href="#" style="font-size:24px">24</a></div>'+ ' <div><a href="#" style="font-size:36px">36</a></div>'+ ' <div><a href="#" style="font-size:48px">48</a></div>'+ ' <div><a href="#" style="font-size:60px">60</a></div>'+ ' <div><a href="#" style="font-size:72px">72</a></div>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.fontSize; _self.value= _value; _self.exec(); }; $html.find( '>.centbox a' ).click( _call ); this.createDialog( { body: $html } ); }, exec: function() { var _self = this, _html = '<span style="font-size:'+_self.value+'">'+_self.editor.selectedText()+'</span>'; _self.editor.pasteHTML( _html ); } } ); $.TE.plugin( 'fontcolor', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontcolor Lovh">'+ ' <div class="colorsel">'+ ' <!--第一列-->'+ ' <a href="###" style="background-color:#FF0000">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFA900">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF00">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#00FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#00AAFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#0055FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#5500FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#AA00FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FF007F">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFFF">&nbsp;</a>'+ ' <!--第二列-->'+ ' <a href="###" style="background-color:#FFE5E5">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFF2D9">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#EEFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFE0">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9F2FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9E6FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#F2D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFD9ED">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D9D9">&nbsp;</a>'+ ' <!--第三列-->'+ ' <a href="###" style="background-color:#E68A8A">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6C78A">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF99">&nbsp;</a>'+ ' <a href="###" style="background-color:#BFE673">&nbsp;</a>'+ ' <a href="###" style="background-color:#99EEA0">&nbsp;</a>'+ ' <a href="###" style="background-color:#A1E6E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#99DDFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#8AA8E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#998AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#C78AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#E68AB9">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第四列-->'+ ' <a href="###" style="background-color:#CC5252">&nbsp;</a>'+ ' <a href="###" style="background-color:#CCA352">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D957">&nbsp;</a>'+ ' <a href="###" style="background-color:#A7CC39">&nbsp;</a>'+ ' <a href="###" style="background-color:#57CE6D">&nbsp;</a>'+ ' <a href="###" style="background-color:#52CCCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#52A3CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#527ACC">&nbsp;</a>'+ ' <a href="###" style="background-color:#6652CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#A352CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#CC5291">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第五列-->'+ ' <a href="###" style="background-color:#991F1F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99701F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99991F">&nbsp;</a>'+ ' <a href="###" style="background-color:#59800D">&nbsp;</a>'+ ' <a href="###" style="background-color:#0F9932">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F9999">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F7099">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F4799">&nbsp;</a>'+ ' <a href="###" style="background-color:#471F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#701F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#991F5E">&nbsp;</a>'+ ' <a href="###" style="background-color:#404040">&nbsp;</a>'+ ' <!--第六列-->'+ ' <a href="###" style="background-color:#660000">&nbsp;</a>'+ ' <a href="###" style="background-color:#664B14">&nbsp;</a>'+ ' <a href="###" style="background-color:#666600">&nbsp;</a>'+ ' <a href="###" style="background-color:#3B5900">&nbsp;</a>'+ ' <a href="###" style="background-color:#005916">&nbsp;</a>'+ ' <a href="###" style="background-color:#146666">&nbsp;</a>'+ ' <a href="###" style="background-color:#144B66">&nbsp;</a>'+ ' <a href="###" style="background-color:#143066">&nbsp;</a>'+ ' <a href="###" style="background-color:#220066">&nbsp;</a>'+ ' <a href="###" style="background-color:#301466">&nbsp;</a>'+ ' <a href="###" style="background-color:#66143F">&nbsp;</a>'+ ' <a href="###" style="background-color:#000000">&nbsp;</a>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.backgroundColor; _self.value= _value; _self.exec(); }; $html.find( '>.colorsel a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'backcolor', { click: function() { var _self = this, $html = $( '<div class="te_dialog_fontcolor Lovh">'+ ' <div class="colorsel">'+ ' <!--第一列-->'+ ' <a href="###" style="background-color:#FF0000">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFA900">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF00">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#99E600">&nbsp;</a>'+ ' <a href="###" style="background-color:#00FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#00AAFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#0055FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#5500FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#AA00FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FF007F">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFFF">&nbsp;</a>'+ ' <!--第二列-->'+ ' <a href="###" style="background-color:#FFE5E5">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFF2D9">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#EEFFCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFE0">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9FFFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9F2FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9E6FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#F2D9FF">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFD9ED">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D9D9">&nbsp;</a>'+ ' <!--第三列-->'+ ' <a href="###" style="background-color:#E68A8A">&nbsp;</a>'+ ' <a href="###" style="background-color:#E6C78A">&nbsp;</a>'+ ' <a href="###" style="background-color:#FFFF99">&nbsp;</a>'+ ' <a href="###" style="background-color:#BFE673">&nbsp;</a>'+ ' <a href="###" style="background-color:#99EEA0">&nbsp;</a>'+ ' <a href="###" style="background-color:#A1E6E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#99DDFF">&nbsp;</a>'+ ' <a href="###" style="background-color:#8AA8E6">&nbsp;</a>'+ ' <a href="###" style="background-color:#998AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#C78AE6">&nbsp;</a>'+ ' <a href="###" style="background-color:#E68AB9">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第四列-->'+ ' <a href="###" style="background-color:#CC5252">&nbsp;</a>'+ ' <a href="###" style="background-color:#CCA352">&nbsp;</a>'+ ' <a href="###" style="background-color:#D9D957">&nbsp;</a>'+ ' <a href="###" style="background-color:#A7CC39">&nbsp;</a>'+ ' <a href="###" style="background-color:#57CE6D">&nbsp;</a>'+ ' <a href="###" style="background-color:#52CCCC">&nbsp;</a>'+ ' <a href="###" style="background-color:#52A3CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#527ACC">&nbsp;</a>'+ ' <a href="###" style="background-color:#6652CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#A352CC">&nbsp;</a>'+ ' <a href="###" style="background-color:#CC5291">&nbsp;</a>'+ ' <a href="###" style="background-color:#B3B3B3">&nbsp;</a>'+ ' <!--第五列-->'+ ' <a href="###" style="background-color:#991F1F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99701F">&nbsp;</a>'+ ' <a href="###" style="background-color:#99991F">&nbsp;</a>'+ ' <a href="###" style="background-color:#59800D">&nbsp;</a>'+ ' <a href="###" style="background-color:#0F9932">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F9999">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F7099">&nbsp;</a>'+ ' <a href="###" style="background-color:#1F4799">&nbsp;</a>'+ ' <a href="###" style="background-color:#471F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#701F99">&nbsp;</a>'+ ' <a href="###" style="background-color:#991F5E">&nbsp;</a>'+ ' <a href="###" style="background-color:#404040">&nbsp;</a>'+ ' <!--第六列-->'+ ' <a href="###" style="background-color:#660000">&nbsp;</a>'+ ' <a href="###" style="background-color:#664B14">&nbsp;</a>'+ ' <a href="###" style="background-color:#666600">&nbsp;</a>'+ ' <a href="###" style="background-color:#3B5900">&nbsp;</a>'+ ' <a href="###" style="background-color:#005916">&nbsp;</a>'+ ' <a href="###" style="background-color:#146666">&nbsp;</a>'+ ' <a href="###" style="background-color:#144B66">&nbsp;</a>'+ ' <a href="###" style="background-color:#143066">&nbsp;</a>'+ ' <a href="###" style="background-color:#220066">&nbsp;</a>'+ ' <a href="###" style="background-color:#301466">&nbsp;</a>'+ ' <a href="###" style="background-color:#66143F">&nbsp;</a>'+ ' <a href="###" style="background-color:#000000">&nbsp;</a>'+ ' </div>'+ '</div>' ), _call = function(e) { var _value = this.style.backgroundColor; _self.value= _value; _self.exec(); }; $html.find( '>.colorsel a' ).click( _call ); this.createDialog( { body: $html } ); } } ); $.TE.plugin( 'about', { 'click': function() { var _self = this, $html = $( '<div class="te_dialog_about Lovh">'+ ' <div class="seltab">'+ ' <div class="links Lovh">'+ ' <a href="###" class="cstyle">关于ThinkEditor</a>'+ ' </div>'+ ' <div class="bdb">&nbsp;</div>'+ ' </div>'+ ' <div class="centbox">'+ ' <div class="aboutcontent">'+ ' <p>ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业级应用开发而诞生的。拥有众多的优秀功能和特性,经历了三年多发展的同时,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,众多的典型案例确保可以稳定用于商业以及门户级的开发。</p>'+ ' <p>ThinkPHP借鉴了国外很多优秀的框架和模式,使用面向对象的开发结构和MVC模式,采用单一入口模式等,融合了Struts的Action思想和JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,在项目配置、类库导入、模版引擎、查询语言、自动验证、视图模型、项目编译、缓存机制、SEO支持、分布式数据库、多数据库连接和切换、认证机制和扩展性方面均有独特的表现。</p>'+ ' <p>使用ThinkPHP,你可以更方便和快捷的开发和部署应用。当然不仅仅是企业级应用,任何PHP应用开发都可以从ThinkPHP的简单和快速的特性中受益。ThinkPHP本身具有很多的原创特性,并且倡导大道至简,开发由我的开发理念,用最少的代码完成更多的功能,宗旨就是让WEB应用开发更简单、更快速。为此ThinkPHP会不断吸收和融入更好的技术以保证其新鲜和活力,提供WEB应用开发的最佳实践!</p>'+ ' <p>ThinkPHP遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。 </p>'+ ' </div>'+ ' </div>'+ ' <div class="btnarea">'+ ' <input type="button" value="关闭" class="te_close" />'+ ' </div>'+ '</div>' ); _self.createDialog( { body: $html } ); } } ); //$.TE.plugin( 'eq', { // 'click': function() { // var _self = this, // $html = $( // '<div class="te_dialog_about Lovh">'+ // ' <div class="seltab">'+ // ' <div class="links Lovh">'+ // ' <a href="###" class="cstyle">关于ThinkEditor</a>'+ // ' </div>'+ // ' <div class="bdb">&nbsp;</div>'+ // ' </div>'+ // ' <div class="centbox">'+ // ' <div class="eqcontent">'+ // ' <label for="eq_name">名称</label>'+ // ' <input type="text" name="eq_name" id="eq_name"/></br>'+ // ' <label for="eq_name">值</label>'+ // ' <input type="text" name="eq_val" id="eq_val"/></br>'+ // ' <textarea name="eq_content" id="eq_content" cols="30" rows="2"></textarea>'+ // ' </div>'+ // ' </div>'+ // ' <div class="btnarea">'+ // ' <input type="button" value="确定" class="te_ok" />'+ // ' <input type="button" value="关闭" class="te_close" />'+ // ' </div>'+ // '</div>' // ); // // _self.createDialog({ // body: $html, // ok : function(){ // var _name = $html.find('#eq_name').val(), // _val = $html.find('#eq_val').val(), // _content = $html.find('#eq_content').val(), // _html = ''; // _html += '<eq name="' + _name +'" value="' + _val +'">'+ // _content + // '</eq>'; // _self.editor.pasteHTML( _html ); // _self.hideDialog(); // } // }); // // } //}); } )( jQuery );
JavaScript
(function ($) { var ie = $.browser.msie, iOS = /iphone|ipad|ipod/i.test(navigator.userAgent); $.TE = { version:'1.0', // 版本号 debug: 1, //调试开关 timeOut: 3000, //加载单个文件超时时间,单位为毫秒。 defaults: { //默认参数controls,noRigths,plugins,定义加载插件 controls: "source,|,undo,redo,|,cut,copy,paste,pastetext,selectAll,blockquote,|,image,flash,table,hr,pagebreak,face,code,|,link,unlink,|,print,fullscreen,|,eq,|,style,font,fontsize,|,fontcolor,backcolor,|,bold,italic,underline,strikethrough,unformat,|,leftalign,centeralign,rightalign,blockjustify,|,orderedlist,unorderedlist,indent,outdent,|,subscript,superscript", //noRights:"underline,strikethrough,superscript", width: 740, height: 500, skins: "default", resizeType: 2, face_path: ['qq_face', 'qq_face'], minHeight: 200, minWidth: 500, uploadURL: 'about:blank', theme: 'default' }, buttons: { //按钮属性 //eq: {title: '等于',cmd: 'bold'}, bold: { title: "加粗", cmd: "bold" }, pastetext: { title: "粘贴无格式", cmd: "bold" }, pastefromword: { title: "粘贴word格式", cmd: "bold" }, selectAll: { title: "全选", cmd: "selectall" }, blockquote: { title: "引用" }, find: { title: "查找", cmd: "bold" }, flash: { title: "插入flash", cmd: "bold" }, media: { title: "插入多媒体", cmd: "bold" }, table: { title: "插入表格" }, pagebreak: { title: "插入分页符" }, face: { title: "插入表情", cmd: "bold" }, code: { title: "插入源码", cmd: "bold" }, print: { title: "打印", cmd: "print" }, about: { title: "关于", cmd: "bold" }, fullscreen: { title: "全屏", cmd: "fullscreen" }, source: { title: "HTML代码", cmd: "source" }, undo: { title: "后退", cmd: "undo" }, redo: { title: "前进", cmd: "redo" }, cut: { title: "剪贴", cmd: "cut" }, copy: { title: "复制", cmd: "copy" }, paste: { title: "粘贴", cmd: "paste" }, hr: { title: "插入横线", cmd: "inserthorizontalrule" }, link: { title: "创建链接", cmd: "createlink" }, unlink: { title: "删除链接", cmd: "unlink" }, italic: { title: "斜体", cmd: "italic" }, underline: { title: "下划线", cmd: "underline" }, strikethrough: { title: "删除线", cmd: "strikethrough" }, unformat: { title: "清除格式", cmd: "removeformat" }, subscript: { title: "下标", cmd: "subscript" }, superscript: { title: "上标", cmd: "superscript" }, orderedlist: { title: "有序列表", cmd: "insertorderedlist" }, unorderedlist: { title: "无序列表", cmd: "insertunorderedlist" }, indent: { title: "增加缩进", cmd: "indent" }, outdent: { title: "减少缩进", cmd: "outdent" }, leftalign: { title: "左对齐", cmd: "justifyleft" }, centeralign: { title: "居中对齐", cmd: "justifycenter" }, rightalign: { title: "右对齐", cmd: "justifyright" }, blockjustify: { title: "两端对齐", cmd: "justifyfull" }, font: { title: "字体", cmd: "fontname", value: "微软雅黑" }, fontsize: { title: "字号", cmd: "fontsize", value: "4" }, style: { title: "段落标题", cmd: "formatblock", value: "" }, fontcolor: { title: "前景颜色", cmd: "forecolor", value: "#ff6600" }, backcolor: { title: "背景颜色", cmd: "hilitecolor", value: "#ff6600" }, image: { title: "插入图片", cmd: "insertimage", value: "" } }, defaultEvent: { event: "click mouseover mouseout", click: function (e) { this.exec(e); }, mouseover: function (e) { var opt = this.editor.opt; this.$btn.addClass(opt.cssname.mouseover); }, mouseout: function (e) { }, noRight: function (e) { }, init: function (e) { }, exec: function () { this.editor.restoreRange(); //执行命令 if ($.isFunction(this[this.cmd])) { this[this.cmd](); //如果有已当前cmd为名的方法,则执行 } else { this.editor.doc.execCommand(this.cmd, 0, this.value || null); } this.editor.focus(); this.editor.refreshBtn(); this.editor.hideDialog(); }, createDialog: function (v) { //创建对话框 var editor = this.editor, opt = editor.opt, $btn = this.$btn, _self = this; var defaults = { body: "", //对话框内容 closeBtn: opt.cssname.dialogCloseBtn, okBtn: opt.cssname.dialogOkBtn, ok: function () { //点击ok按钮后执行函数 }, setDialog: function ($dialog) { //设置对话框(位置) var y = $btn.offset().top + $btn.outerHeight(); var x = $btn.offset().left; $dialog.offset({ top: y, left: x }); } }; var options = $.extend(defaults, v); //初始化对话框 editor.$dialog.empty(); //加入内容 $body = $.type(options.body) == "string" ? $(options.body) : options.body; $dialog = $body.appendTo(editor.$dialog); $dialog.find("." + options.closeBtn).click(function () { _self.hideDialog(); }); $dialog.find("." + options.okBtn).click(options.ok); //设置对话框 editor.$dialog.show(); options.setDialog(editor.$dialog); }, hideDialog: function () { this.editor.hideDialog(); } //getEnable:function(){return false}, //disable:function(e){alert('disable')} }, plugin: function (name, v) { //新增或修改插件。 $.TE.buttons[name] = $.extend($.TE.buttons[name], v); }, config: function (name, value) { var _fn = arguments.callee; if (!_fn.conf) _fn.conf = {}; if (value) { _fn.conf[name] = value; return true; } else { return name == 'default' ? $.TE.defaults : _fn.conf[name]; } }, systemPlugins: ['system', 'upload_interface'], //系统自带插件 basePath: function () { var jsFile = "ThinkEditor.js"; var src = $("script[src$='" + jsFile + "']").attr("src"); return src.substr(0, src.length - jsFile.length); } }; $.fn.extend({ //调用插件 ThinkEditor: function (v) { //配置处理 var conf = '', temp = ''; conf = v ? $.extend($.TE.config(v.theme ? v.theme : 'default'), v) : $.TE.config('default'); v = conf; //配置处理完成 //载入皮肤 var skins = v.skins || $.TE.defaults.skins; //获得皮肤参数 var skinsDir = $.TE.basePath() + "skins/" + skins + "/", jsFile = "@" + skinsDir + "config.js", cssFile = "@" + skinsDir + "style.css"; var _self = this; //加载插件 if ($.defined(v.plugins)) { var myPlugins = $.type(v.plugins) == "string" ? [v.plugins] : v.plugins; var files = $.merge($.merge([], $.TE.systemPlugins), myPlugins); } else { var files = $.TE.systemPlugins; } $.each(files, function (i, v) { files[i] = v + ".js"; }) files.push(jsFile, cssFile); files.push("@" + skinsDir + "dialog/css/base.css"); files.push("@" + skinsDir + "dialog/css/te_dialog.css"); $.loadFile(files, function () { //设置css参数 v.cssname = $.extend({}, TECSS, v.cssname); //创建编辑器,存储对象 $(_self).each(function (idx, elem) { var data = $(elem).data("editorData"); if (!data) { data = new ThinkEditor(elem, v); $(elem).data("editorData", data); } }); }); } }); //编辑器对象。 function ThinkEditor(area, v) { //添加随机序列数防冲突 var _fn = arguments.callee; this.guid = !_fn.guid ? _fn.guid = 1 : _fn.guid += 1; //生成参数 var opt = this.opt = $.extend({}, $.TE.defaults, v); var _self = this; //结构:主层,工具层,分组层,按钮层,底部,dialog层 var $main = this.$main = $("<div></div>").addClass(opt.cssname.main), $toolbar_box = $('<div></div>').addClass(opt.cssname.toolbar_box).appendTo($main), $toolbar = this.$toolbar = $("<div></div>").addClass(opt.cssname.toolbar).appendTo($toolbar_box), /*$toolbar=this.$toolbar=$("<div></div>").addClass(opt.cssname.toolbar).appendTo($main),*/ $group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar), $bottom = this.$bottom = $("<div></div>").addClass(opt.cssname.bottom), $dialog = this.$dialog = $("<div></div>").addClass(opt.cssname.dialog), $area = $(area).hide(), $frame = $('<iframe frameborder="0"></iframe>'); opt.noRights = opt.noRights || ""; var noRights = opt.noRights.split(","); //调整结构 $main.insertBefore($area) .append($area); //加入frame $frame.appendTo($main); //加入bottom if (opt.resizeType != 0) { //拖动改变编辑器高度 $("<div></div>").addClass(opt.cssname.resizeCenter).mousedown(function (e) { var y = e.pageY, x = e.pageX, height = _self.$main.height(), width = _self.$main.width(); $(document).add(_self.doc).mousemove(function (e) { var mh = e.pageY - y; _self.resize(width, height + mh); }); $(document).add(_self.doc).mouseup(function (e) { $(document).add(_self.doc).unbind("mousemove"); $(document).add(_self.doc).unbind("mousemup"); }); }).appendTo($bottom); } if (opt.resizeType == 2) { //拖动改变编辑器高度和宽度 $("<div></div>").addClass(opt.cssname.resizeLeft).mousedown(function (e) { var y = e.pageY, x = e.pageX, height = _self.$main.height(), width = _self.$main.width(); $(document).add(_self.doc).mousemove(function (e) { var mh = e.pageY - y, mw = e.pageX - x; _self.resize(width + mw, height + mh); }); $(document).add(_self.doc).mouseup(function (e) { $(document).add(_self.doc).unbind("mousemove"); $(document).add(_self.doc).unbind("mousemup"); }); }).appendTo($bottom); } $bottom.appendTo($main); $dialog.appendTo($main); //循环按钮处理。 //TODO 默认参数处理 $.each(opt.controls.split(","), function (idx, bname) { var _fn = arguments.callee; if (_fn.count == undefined) { _fn.count = 0; } //处理分组 if (bname == "|") { //设定分组宽 if (_fn.count) { $toolbar.find('.' + opt.cssname.group + ':last').css('width', (opt.cssname.btnWidth * _fn.count + opt.cssname.lineWidth) + 'px'); _fn.count = 0; } //分组宽结束 $group = $("<div></div>").addClass(opt.cssname.group).appendTo($toolbar); $("<div>&nbsp;</div>").addClass(opt.cssname.line).appendTo($group); } else { //更新统计数 _fn.count += 1; //获取按钮属性 var btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[bname]); //标记无权限 var noRightCss = "", noRightTitle = ""; if ($.inArray(bname, noRights) != -1) { noRightCss = " " + opt.cssname.noRight; noRightTitle = "(无权限)"; } $btn = $("<div></div>").addClass(opt.cssname.btn + " " + opt.cssname.btnpre + bname + noRightCss) .data("bname", bname) .attr("title", btn.title + noRightTitle) .appendTo($group) .bind(btn.event, function (e) { //不可用触发 if ($(this).is("." + opt.cssname.disable)) { if ($.isFunction(btn.disable)) btn.disable.call(btn, e); return false; } //判断权限和是否可用 if ($(this).is("." + opt.cssname.noRight)) { //点击时触发无权限说明 btn['noRight'].call(btn, e); return false; } if ($.isFunction(btn[e.type])) { //触发事件 btn[e.type].call(btn, e); //TODO 刷新按钮 } }); if ($.isFunction(btn.init)) btn.init.call(btn); //初始化 if (ie) $btn.attr("unselectable", "on"); btn.editor = _self; btn.$btn = $btn; } }); //调用核心 this.core = new editorCore($frame, $area); this.doc = this.core.doc; this.$frame = this.core.$frame; this.$area = this.core.$area; this.restoreRange = this.core.restoreRange; this.selectedHTML = function () { return this.core.selectedHTML(); } this.selectedText = function () { return this.core.selectedText(); } this.pasteHTML = function (v) { this.core.pasteHTML(v); } this.sourceMode = this.core.sourceMode; this.focus = this.core.focus; //监控变化 $(this.core.doc).click(function () { //隐藏对话框 _self.hideDialog(); }).bind("keyup mouseup", function () { _self.refreshBtn(); }) this.refreshBtn(); //调整大小 this.resize(opt.width, opt.height); //获取DOM层级 this.core.focus(); } //end ThinkEditor ThinkEditor.prototype.resize = function (w, h) { //最小高度和宽度 var opt = this.opt, h = h < opt.minHeight ? opt.minHeight : h, w = w < opt.minWidth ? opt.minWidth : w; this.$main.width(w).height(h); var height = h - (this.$toolbar.parent().outerHeight() + this.$bottom.height()); this.$frame.height(height).width("100%"); this.$area.height(height).width("100%"); }; //隐藏对话框 ThinkEditor.prototype.hideDialog = function () { var opt = this.opt; $("." + opt.cssname.dialog).hide(); }; //刷新按钮 ThinkEditor.prototype.refreshBtn = function () { var sourceMode = this.sourceMode(); // 标记状态。 var opt = this.opt; if (!iOS && $.browser.webkit && !this.focused) { this.$frame[0].contentWindow.focus(); window.focus(); this.focused = true; } var queryObj = this.doc; if (ie) queryObj = this.core.getRange(); //循环按钮 //TODO undo,redo等判断 this.$toolbar.find("." + opt.cssname.btn + ":not(." + opt.cssname.noRight + ")").each(function () { var enabled = true, btnName = $(this).data("bname"), btn = $.extend({}, $.TE.defaultEvent, $.TE.buttons[btnName]), command = btn.cmd; if (sourceMode && btnName != "source") { enabled = false; } else if ($.isFunction(btn.getEnable)) { enabled = btn.getEnable.call(btn); } else if ($.isFunction(btn[command])) { enabled = true; //如果命令为自定义命令,默认为可用 } else { if (!ie || btn.cmd != "inserthtml") { try { enabled = queryObj.queryCommandEnabled(command); $.debug(enabled.toString(), "命令:" + command); } catch (err) { enabled = false; } } //判断该功能是否有实现 @TODO 代码胶着 if ($.TE.buttons[btnName]) enabled = true; } if (enabled) { $(this).removeClass(opt.cssname.disable); } else { $(this).addClass(opt.cssname.disable); } }); }; //core code start function editorCore($frame, $area, v) { //TODO 参数改为全局的。 var defaults = { docType: '<!DOCTYPE HTML>', docCss: "", bodyStyle: "margin:4px; font:10pt Arial,Verdana; cursor:text", focusExt: function (editor) { //触发编辑器获得焦点时执行,比如刷新按钮 }, //textarea内容更新到iframe的处理函数 updateFrame: function (code) { //翻转flash为占位符 code = code.replace(/(<embed[^>]*?type="application\/x-shockwave-flash" [^>]*?>)/ig, function ($1) { var ret = '<img class="_flash_position" src="' + $.TE.basePath() + 'skins/default/img/spacer.gif" style="', _width = $1.match(/width="(\d+)"/), _height = $1.match(/height="(\d+)"/), _src = $1.match(/src="([^"]+)"/), _wmode = $1.match(/wmode="(\w+)"/), _data = ''; _width = _width && _width[1] ? parseInt(_width[1]) : 0; _height = _height && _height[1] ? parseInt(_height[1]) : 0; _src = _src && _src[1] ? _src[1] : ''; _wmode = _wmode && _wmode[1] ? true : false; _data = "{'src':'" + _src + "','width':'" + _width + "','height':'" + _height + "','wmode':" + (_wmode) + "}"; if (_width) ret += 'width:' + _width + 'px;'; if (_height) ret += 'height:' + _height + 'px;'; ret += 'border:1px solid #DDD; display:inline-block;text-align:center;line-height:' + _height + 'px;" '; ret += '_data="' + _data + '"'; ret += ' alt="flash占位符" />'; return ret; }); return code; }, //iframe更新到text的, TODO 去掉 updateTextArea: function (html) { //翻转占位符为flash html = html.replace(/(<img[^>]*?class=(?:"|)_flash_position(?:"|)[^>]*?>)/ig, function ($1) { var ret = '', data = $1.match(/_data="([^"]*)"/); if (data && data[1]) { data = eval('(' + data + ')'); } ret += '<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" '; ret += 'src="' + data.src + '" '; ret += 'width="' + data.width + '" '; ret += 'height="' + data.height + '" '; if (data.wmode) ret += 'wmode="transparent" '; ret += '/>'; return ret; }); return html; } }; options = $.extend({}, defaults, v); //存储属性 this.opt = options; this.$frame = $frame; this.$area = $area; var contentWindow = $frame[0].contentWindow, doc = this.doc = contentWindow.document, $doc = $(doc); var _self = this; //初始化 doc.open(); doc.write( options.docType + '<html>' + ((options.docCss === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCss + '" /></head>') + '<body style="' + options.bodyStyle + '"></body></html>' ); doc.close(); //设置frame编辑模式 try { if (ie) { doc.body.contentEditable = true; } else { doc.designMode = "on"; } } catch (err) { $.debug(err, "创建编辑模式错误"); } //统一 IE FF 等的 execCommand 行为 try { this.e.execCommand("styleWithCSS", 0, 0) } catch (e) { try { this.e.execCommand("useCSS", 0, 1); } catch (e) { } } //监听 if (ie) $doc.click(function () { _self.focus(); }); this.updateFrame(); //更新内容 if (ie) { $doc.bind("beforedeactivate beforeactivate selectionchange keypress", function (e) { if (e.type == "beforedeactivate") _self.inactive = true; else if (e.type == "beforeactivate") { if (!_self.inactive && _self.range && _self.range.length > 1) _self.range.shift(); delete _self.inactive; } else if (!_self.inactive) { if (!_self.range) _self.range = []; _self.range.unshift(_self.getRange()); while (_self.range.length > 2) _self.range.pop(); } }); // Restore the text range when the iframe gains focus $frame.focus(function () { _self.restoreRange(); }); } ($.browser.mozilla ? $doc : $(contentWindow)).blur(function () { _self.updateTextArea(true); }); this.$area.blur(function () { // Update the iframe when the textarea loses focus _self.updateFrame(true); }); /* * //自动添加p标签 * $doc.keydown(function(e){ * if(e.keyCode == 13){ * //_self.pasteHTML('<p>&nbsp;</p>'); * //this.execCommand( 'formatblock', false, '<p>' ); * } * }); */ } //是否为源码模式 editorCore.prototype.sourceMode = function () { return this.$area.is(":visible"); }; //编辑器获得焦点 editorCore.prototype.focus = function () { var opt = this.opt; if (this.sourceMode()) { this.$area.focus(); } else { this.$frame[0].contentWindow.focus(); } if ($.isFunction(opt.focusExt)) opt.focusExt(this); }; //textarea内容更新到iframe editorCore.prototype.updateFrame = function (checkForChange) { var code = this.$area.val(), options = this.opt, updateFrameCallback = options.updateFrame, $body = $(this.doc.body); //判断是否已经修改 if (updateFrameCallback) { var sum = checksum(code); if (checkForChange && this.areaChecksum == sum) return; this.areaChecksum = sum; } //回调函数处理 var html = updateFrameCallback ? updateFrameCallback(code) : code; // 禁止script标签 html = html.replace(/<(?=\/?script)/ig, "&lt;"); // TODO,判断是否有作用 if (options.updateTextArea) this.frameChecksum = checksum(html); if (html != $body.html()) { $body.html(html); } }; editorCore.prototype.getRange = function () { if (ie) return this.getSelection().createRange(); return this.getSelection().getRangeAt(0); }; editorCore.prototype.getSelection = function () { if (ie) return this.doc.selection; return this.$frame[0].contentWindow.getSelection(); }; editorCore.prototype.restoreRange = function () { if (ie && this.range) this.range[0].select(); }; editorCore.prototype.selectedHTML = function () { this.restoreRange(); var range = this.getRange(); if (ie) return range.htmlText; var layer = $("<layer>")[0]; layer.appendChild(range.cloneContents()); var html = layer.innerHTML; layer = null; return html; }; editorCore.prototype.selectedText = function () { this.restoreRange(); if (ie) return this.getRange().text; return this.getSelection().toString(); }; editorCore.prototype.pasteHTML = function (value) { this.restoreRange(); if (ie) { this.getRange().pasteHTML(value); } else { this.doc.execCommand("inserthtml", 0, value || null); } //获得焦点 this.$frame[0].contentWindow.focus(); } editorCore.prototype.updateTextArea = function (checkForChange) { var html = $(this.doc.body).html(), options = this.opt, updateTextAreaCallback = options.updateTextArea, $area = this.$area; if (updateTextAreaCallback) { var sum = checksum(html); if (checkForChange && this.frameChecksum == sum) return; this.frameChecksum = sum; } var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html; // TODO 判断是否有必要 if (options.updateFrame) this.areaChecksum = checksum(code); if (code != $area.val()) { $area.val(code); } }; function checksum(text) { var a = 1, b = 0; for (var index = 0; index < text.length; ++index) { a = (a + text.charCodeAt(index)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } $.extend({ teExt: { //扩展配置 }, debug: function (msg, group) { //判断是否有console对象 if ($.TE.debug && window.console !== undefined) { //分组开始 if (group) console.group(group); if ($.type(msg) == "string") { //是否为执行特殊函数,用双冒号隔开 if (msg.indexOf("::") != -1) { var arr = msg.split("::"); eval("console." + arr[0] + "('" + arr[1] + "')"); } else { console.debug(msg); } } else { if ($(msg).html() == null) { console.dir(msg); //输出对象或数组 } else { console.dirxml($(msg)[0]); //输出dom对象 } } //记录trace信息 if ($.TE.debug == 2) { console.group("trace 信息:"); console.trace(); console.groupEnd(); } //分组结束 if (group) console.groupEnd(); } }, //end debug defined: function (variable) { return $.type(variable) == "undefined" ? false : true; }, isTag: function (tn) { if (!tn) return false; return $(this)[0].tagName.toLowerCase() == tn ? true : false; }, //end istag include: function (file) { if (!$.defined($.TE.loadUrl)) $.TE.loadUrl = {}; //定义皮肤路径和插件路径。 var basePath = $.TE.basePath(), skinsDir = basePath + "skins/", pluginDir = basePath + "plugins/"; var files = $.type(file) == "string" ? [file] : file; for (var i = 0; i < files.length; i++) { var loadurl = name = $.trim(files[i]); //判断是否已经加载过 if ($.TE.loadUrl[loadurl]) { continue; } //判断是否有@ var at = false; if (name.indexOf("@") != -1) { at = true; name = name.substr(1); } var att = name.split('.'); var ext = att[att.length - 1].toLowerCase(); if (ext == "css") { //加载css var filepath = at ? name : skinsDir + name; var newNode = document.createElement("link"); newNode.setAttribute('type', 'text/css'); newNode.setAttribute('rel', 'stylesheet'); newNode.setAttribute('href', filepath); $.TE.loadUrl[loadurl] = 1; } else { var filepath = at ? name : pluginDir + name; //$("<scri"+"pt>"+"</scr"+"ipt>").attr({src:filepath,type:'text/javascript'}).appendTo('head'); var newNode = document.createElement("script"); newNode.type = "text/javascript"; newNode.src = filepath; newNode.id = loadurl; //实现批量加载 newNode.onload = function () { $.TE.loadUrl[this.id] = 1; }; newNode.onreadystatechange = function () { //针对ie if ((newNode.readyState == 'loaded' || newNode.readyState == 'complete')) { $.TE.loadUrl[this.id] = 1; } }; } $("head")[0].appendChild(newNode); } }, //end include loadedFile: function (file) { //判断是否加载 if (!$.defined($.TE.loadUrl)) return false; var files = $.type(file) == "string" ? [file] : file, result = true; $.each(files, function (i, name) { if (!$.TE.loadUrl[name]) result = false; //alert(name+':'+result); }); return result; }, //end loaded loadFile: function (file, fun) { //加载文件,加载完毕后执行fun函数。 $.include(file); var time = 0; var check = function () { //alert($.loadedFile(file)); if ($.loadedFile(file)) { if ($.isFunction(fun)) fun(); } else { //alert(time); if (time >= $.TE.timeOut) { // TODO 细化哪些文件加载失败。 $.debug(file, "文件加载失败"); } else { //alert('time:'+time); setTimeout(check, 50); time += 50; } } }; check(); } //end loadFile }); })(jQuery); jQuery.TE.config( 'mini', { 'controls' : 'font,fontsize,fontcolor,backcolor,bold,italic,underline,unformat,leftalign,centeralign,rightalign,orderedlist,unorderedlist', 'width':498, 'height':400, 'resizeType':1 } );
JavaScript
//interval :D表示查询精确到天数的之差 //interval :H表示查询精确到小时之差 //interval :M表示查询精确到分钟之差 //interval :S表示查询精确到秒之差 //interval :T表示查询精确到毫秒之差 //使用方法: //alert(dateDiff('D', '2007-4-1', '2007/04/19')); //时间差的计算方法 function dateDiff(interval, date1, date2) { var objInterval = {'D':1000 * 60 * 60 * 24,'H':1000 * 60 * 60,'M':1000 * 60,'S':1000,'T':1}; interval = interval.toUpperCase(); var dt1 = new Date(Date.parse(date1.replace(/-/g, '/'))); var dt2 = new Date(Date.parse(date2.replace(/-/g, '/'))); try { return (Math.round(dt2- dt1) / (1000 * 60 * 60 * 24)); } catch (e) { return e.message; } }
JavaScript
// 获取宽度 function getWidth() { var strWidth,clientWidth,bodyWidth; clientWidth = document.documentElement.clientWidth; bodyWidth = document.body.clientWidth; if(bodyWidth > clientWidth){ strWidth = bodyWidth + 20; } else { strWidth = clientWidth; } return strWidth; } //获取高度 function getHeight() { var strHeight,clientHeight,bodyHeight; clientHeight = document.documentElement.clientHeight; bodyHeight = document.body.clientHeight; if(bodyHeight > clientHeight){ strHeight = bodyHeight + 30; } else { strHeight = clientHeight; } return strHeight+1000; } // 锁屏 function showScreen(div1,div2,clientWidth) { var div1=div1; var div2=div2; var Msg = document.getElementById(div1); var Bg = document.getElementById(div2); Bg.style.width = getWidth()+'px'; Bg.style.height = getHeight()+'px'; document.getElementById(div1).style.left=clientWidth+"px"; //document.body.clientWidth / 2 表示居中 document.getElementById(div1).style.top=screen.height/2-300+"px"; Msg.style.display = 'block'; Bg.style.display = 'block'; } //解屏 function hideScreen(div1,div2) { var div1=div1; var div2=div2; var Msg = document.getElementById(div1); var Bg = document.getElementById(div2); Msg.style.display = 'none'; Bg.style.display = 'none'; } /*dfdfads 使用方法 此功能一共需要使用三个文件 1本js文件 2 lockscreen.css文件 3所以html调用的页面 调用: showScreen(div1,div2) div1和div2是两个层的div名 注意css文件里的样式名要和div的名称对应 例如: <div id="Message" style="border:#00BFFF solid 1px; background:#FFFFFF; width:400px; height:100px"><span style="cursor:pointer;" onclick="javascript:hideScreen('Message','Screen',距屏幕左边的像素);">关闭</span> <div id="Screen"></div> <p><span style="cursor:pointer;" onclick="javascript:showScreen('Message','Screen');">锁屏</span></p> dsdsd*/
JavaScript
function MinClassBox(strMinValue,SpanID,SelectName,FieldValue) { if(strMinValue=="") { SpanID.innerHTML=""; return; } var ArrMinClass,MinClass,strSelect,strSelected; strSelected=""; strSelect=""; if(strMinValue.indexOf(",")>0) { ArrMinClass=strMinValue.split(","); } else { var ArrMinClass=new Array(1); ArrMinClass[0]=strMinValue; } for(i=0;i<ArrMinClass.length;i++) { FieldValue_arr= ArrMinClass[i].split("|"); if(FieldValue==FieldValue_arr[0]) { strSelected="selected='selected'"; } else { strSelected=""; } strSelect=strSelect + "<option " + strSelected + " value='" + FieldValue_arr[0]+ "'>" + FieldValue_arr[1] + "</option>"; } SpanID.innerHTML=" <select name='"+SelectName +"' >" +strSelect + "</select>"; }
JavaScript
function atCalendarControl(){ var calendar=this; this.calendarPad=null; this.prevMonth=null; this.nextMonth=null; this.prevYear=null; this.nextYear=null; this.goToday=null; this.calendarClose=null; this.calendarAbout=null; this.head=null; this.body=null; this.today=[]; this.currentDate=[]; this.sltDate; this.target; this.source; /************** 加入日历底板及阴影 *********************/ this.addCalendarPad=function(){ document.write("<div id='divCalendarpad' style='position:absolute;top:100;left:0;width:255;height:187;display:none;'>"); document.write("<iframe frameborder=0 height=189 width=250></iframe>"); document.write("<div style='position:absolute;top:2;left:2;width:250;height:187;background-color:#336699;'></div>"); document.write("</div>"); calendar.calendarPad=document.all.divCalendarpad; } /************** 加入日历面板 *********************/ this.addCalendarBoard=function(){ var BOARD=this; var divBoard=document.createElement("div"); calendar.calendarPad.insertAdjacentElement("beforeEnd",divBoard); divBoard.style.cssText="position:absolute;top:0;left:0;width:250;height:187;border:0 outset;background-color:buttonface;"; var tbBoard=document.createElement("table"); divBoard.insertAdjacentElement("beforeEnd",tbBoard); tbBoard.style.cssText="position:absolute;top:2;left:2;width:248;height:10;font-size:9pt;"; tbBoard.cellPadding=0; tbBoard.cellSpacing=1; /************** 设置各功能按钮的功能 *********************/ /*********** Calendar About Button ***************/ trRow = tbBoard.insertRow(0); calendar.calendarAbout=calendar.insertTbCell(trRow,0,"-","center"); calendar.calendarAbout.title="帮助 快捷键:H"; calendar.calendarAbout.onclick=function(){calendar.about();} /*********** Calendar Head ***************/ tbCell=trRow.insertCell(1); tbCell.colSpan=5; tbCell.bgColor="#99CCFF"; tbCell.align="center"; tbCell.style.cssText = "cursor:default"; calendar.head=tbCell; /*********** Calendar Close Button ***************/ tbCell=trRow.insertCell(2); calendar.calendarClose = calendar.insertTbCell(trRow,2,"x","center"); calendar.calendarClose.title="关闭 快捷键:ESC或X"; calendar.calendarClose.onclick=function(){calendar.hide();} /*********** Calendar PrevYear Button ***************/ trRow = tbBoard.insertRow(1); calendar.prevYear = calendar.insertTbCell(trRow,0,"<<","center"); calendar.prevYear.title="上一年 快捷键:↑"; calendar.prevYear.onmousedown=function(){ calendar.currentDate[0]--; calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar PrevMonth Button ***************/ calendar.prevMonth = calendar.insertTbCell(trRow,1,"<","center"); calendar.prevMonth.title="上一月 快捷键:←"; calendar.prevMonth.onmousedown=function(){ calendar.currentDate[1]--; if(calendar.currentDate[1]==0){ calendar.currentDate[1]=12; calendar.currentDate[0]--; } calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar Today Button ***************/ calendar.goToday = calendar.insertTbCell(trRow,2,"今天","center",3); calendar.goToday.title="选择今天 快捷键:T"; calendar.goToday.onclick=function(){ if(calendar.returnTime) calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2])+" "+calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4]) else calendar.sltDate=calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]); calendar.target.value=calendar.sltDate; calendar.hide(); //calendar.show(calendar.target,calendar.today[0]+"-"+calendar.today[1]+"-"+calendar.today[2],calendar.source); } /*********** Calendar NextMonth Button ***************/ calendar.nextMonth = calendar.insertTbCell(trRow,3,">","center"); calendar.nextMonth.title="下一月 快捷键:→"; calendar.nextMonth.onmousedown=function(){ calendar.currentDate[1]++; if(calendar.currentDate[1]==13){ calendar.currentDate[1]=1; calendar.currentDate[0]++; } calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } /*********** Calendar NextYear Button ***************/ calendar.nextYear = calendar.insertTbCell(trRow,4,">>","center"); calendar.nextYear.title="下一年 快捷键:↓"; calendar.nextYear.onmousedown=function(){ calendar.currentDate[0]++; calendar.show(calendar.target,calendar.returnTime,calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(calendar.currentDate[2]),calendar.source); } trRow = tbBoard.insertRow(2); var cnDateName = new Array("日","一","二","三","四","五","六"); for (var i = 0; i < 7; i++) { tbCell=trRow.insertCell(i) tbCell.innerText=cnDateName[i]; tbCell.align="center"; tbCell.width=35; tbCell.style.cssText="cursor:default;border:1 solid #99CCCC;background-color:#99CCCC;"; } /*********** Calendar Body ***************/ trRow = tbBoard.insertRow(3); tbCell=trRow.insertCell(0); tbCell.colSpan=7; tbCell.height=97; tbCell.vAlign="top"; tbCell.bgColor="#F0F0F0"; var tbBody=document.createElement("table"); tbCell.insertAdjacentElement("beforeEnd",tbBody); tbBody.style.cssText="position:relative;top:0;left:0;width:245;height:103;font-size:9pt;" tbBody.cellPadding=0; tbBody.cellSpacing=1; calendar.body=tbBody; /*********** Time Body ***************/ trRow = tbBoard.insertRow(4); tbCell=trRow.insertCell(0); calendar.prevHours = calendar.insertTbCell(trRow,0,"-","center"); calendar.prevHours.title="小时调整 快捷键:Home"; calendar.prevHours.onmousedown=function(){ calendar.currentDate[3]--; if(calendar.currentDate[3]==-1) calendar.currentDate[3]=23; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(1); calendar.nextHours = calendar.insertTbCell(trRow,1,"+","center"); calendar.nextHours.title="小时调整 快捷键:End"; calendar.nextHours.onmousedown=function(){ calendar.currentDate[3]++; if(calendar.currentDate[3]==24) calendar.currentDate[3]=0; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(2); tbCell.colSpan=3; tbCell.bgColor="#99CCFF"; tbCell.align="center"; tbCell.style.cssText = "cursor:default"; calendar.bottom=tbCell; tbCell=trRow.insertCell(3); calendar.prevMinutes = calendar.insertTbCell(trRow,3,"-","center"); calendar.prevMinutes.title="分钟调整 快捷键:PageUp"; calendar.prevMinutes.onmousedown=function(){ calendar.currentDate[4]--; if(calendar.currentDate[4]==-1) calendar.currentDate[4]=59; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } tbCell=trRow.insertCell(4); calendar.nextMinutes = calendar.insertTbCell(trRow,4,"+","center"); calendar.nextMinutes.title="分钟调整 快捷键:PageDown"; calendar.nextMinutes.onmousedown=function(){ calendar.currentDate[4]++; if(calendar.currentDate[4]==60) calendar.currentDate[4]=0; calendar.bottom.innerText=calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]); } } /************** 加入功能按钮公共样式 *********************/ this.insertTbCell=function(trRow,cellIndex,TXT,trAlign,tbColSpan){ var tbCell=trRow.insertCell(cellIndex); if(tbColSpan!=undefined) tbCell.colSpan=tbColSpan; var btnCell=document.createElement("button"); tbCell.insertAdjacentElement("beforeEnd",btnCell); btnCell.value=TXT; btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;"; btnCell.onmouseover=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;"; } btnCell.onmouseout=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:buttonface;"; } // btnCell.onmousedown=function(){ // btnCell.style.cssText="width:100%;border:1 inset;background-color:#F0F0F0;"; // } btnCell.onmouseup=function(){ btnCell.style.cssText="width:100%;border:1 outset;background-color:#F0F0F0;"; } btnCell.onclick=function(){ btnCell.blur(); } return btnCell; } this.setDefaultDate=function(){ var dftDate=new Date(); calendar.today[0]=dftDate.getYear(); calendar.today[1]=dftDate.getMonth()+1; calendar.today[2]=dftDate.getDate(); calendar.today[3]=dftDate.getHours(); calendar.today[4]=dftDate.getMinutes(); } /****************** Show Calendar *********************/ this.show=function(targetObject,returnTime,defaultDate,sourceObject){ if(targetObject==undefined) { alert("未设置目标对象. \n方法: ATCALENDAR.show(obj 目标对象,boolean 是否返回时间,string 默认日期,obj 点击对象);\n\n目标对象:接受日期返回值的对象.\n默认日期:格式为\"yyyy-mm-dd\",缺省为当前日期.\n点击对象:点击这个对象弹出calendar,默认为目标对象.\n"); return false; } else calendar.target=targetObject; if(sourceObject==undefined) calendar.source=calendar.target; else calendar.source=sourceObject; if(returnTime) calendar.returnTime=true; else calendar.returnTime=false; var firstDay; var Cells=new Array(); if((defaultDate==undefined) || (defaultDate=="")){ var theDate=new Array(); calendar.head.innerText = calendar.today[0]+"-"+calendar.formatTime(calendar.today[1])+"-"+calendar.formatTime(calendar.today[2]); calendar.bottom.innerText = calendar.formatTime(calendar.today[3])+":"+calendar.formatTime(calendar.today[4]); theDate[0]=calendar.today[0]; theDate[1]=calendar.today[1]; theDate[2]=calendar.today[2]; theDate[3]=calendar.today[3]; theDate[4]=calendar.today[4]; } else{ var Datereg=/^\d{4}-\d{1,2}-\d{2}$/ var DateTimereg=/^(\d{1,4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})$/ if((!defaultDate.match(Datereg)) && (!defaultDate.match(DateTimereg))){ alert("默认日期(时间)的格式不正确!\t\n\n默认可接受格式为:\n1、yyyy-mm-dd \n2、yyyy-mm-dd hh:mm\n3、(空)"); calendar.setDefaultDate(); return; } if(defaultDate.match(Datereg)) defaultDate=defaultDate+" "+calendar.today[3]+":"+calendar.today[4]; var strDateTime=defaultDate.match(DateTimereg); var theDate=new Array(4) theDate[0]=strDateTime[1]; theDate[1]=strDateTime[2]; theDate[2]=strDateTime[3]; theDate[3]=strDateTime[4]; theDate[4]=strDateTime[5]; calendar.head.innerText = theDate[0]+"-"+calendar.formatTime(theDate[1])+"-"+calendar.formatTime(theDate[2]); calendar.bottom.innerText = calendar.formatTime(theDate[3])+":"+calendar.formatTime(theDate[4]); } calendar.currentDate[0]=theDate[0]; calendar.currentDate[1]=theDate[1]; calendar.currentDate[2]=theDate[2]; calendar.currentDate[3]=theDate[3]; calendar.currentDate[4]=theDate[4]; theFirstDay=calendar.getFirstDay(theDate[0],theDate[1]); theMonthLen=theFirstDay+calendar.getMonthLen(theDate[0],theDate[1]); //calendar.setEventKey(); calendar.calendarPad.style.display=""; var theRows = Math.ceil((theMonthLen)/7); //清除旧的日历; while (calendar.body.rows.length > 0) { calendar.body.deleteRow(0) } //建立新的日历; var n=0;day=0; for(i=0;i<theRows;i++){ theRow=calendar.body.insertRow(i); for(j=0;j<7;j++){ n++; if(n>theFirstDay && n<=theMonthLen){ day=n-theFirstDay; calendar.insertBodyCell(theRow,j,day); } else{ var theCell=theRow.insertCell(j); theCell.style.cssText="background-color:#F0F0F0;cursor:default;"; } } } //****************调整日历位置**************// var offsetPos=calendar.getAbsolutePos(calendar.source);//计算对象的位置; if((document.body.offsetHeight-(offsetPos.y+calendar.source.offsetHeight-document.body.scrollTop))<calendar.calendarPad.style.pixelHeight){ var calTop=offsetPos.y-calendar.calendarPad.style.pixelHeight; } else{ var calTop=offsetPos.y+calendar.source.offsetHeight; } if((document.body.offsetWidth-(offsetPos.x+calendar.source.offsetWidth-document.body.scrollLeft))>calendar.calendarPad.style.pixelWidth){ var calLeft=offsetPos.x; } else{ var calLeft=calendar.source.offsetLeft+calendar.source.offsetWidth; } //alert(offsetPos.x); calendar.calendarPad.style.pixelLeft=calLeft; calendar.calendarPad.style.pixelTop=calTop; } /****************** 计算对象的位置 *************************/ this.getAbsolutePos = function(el) { var r = { x: el.offsetLeft, y: el.offsetTop }; if (el.offsetParent) { var tmp = calendar.getAbsolutePos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }; //************* 插入日期单元格 **************/ this.insertBodyCell=function(theRow,j,day,targetObject){ var theCell=theRow.insertCell(j); if(j==0) var theBgColor="#FF9999"; else var theBgColor="#FFFFFF"; if(day==calendar.currentDate[2]) var theBgColor="#CCCCCC"; if(day==calendar.today[2]) var theBgColor="#99FFCC"; theCell.bgColor=theBgColor; theCell.innerText=day; theCell.align="center"; theCell.width=35; theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;"; theCell.onmouseover=function(){ theCell.bgColor="#FFFFCC"; theCell.style.cssText="border:1 outset;cursor:hand;"; } theCell.onmouseout=function(){ theCell.bgColor=theBgColor; theCell.style.cssText="border:1 solid #CCCCCC;cursor:hand;"; } theCell.onmousedown=function(){ theCell.bgColor="#FFFFCC"; theCell.style.cssText="border:1 inset;cursor:hand;"; } theCell.onclick=function(){ if(calendar.returnTime) calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day)+" "+calendar.formatTime(calendar.currentDate[3])+":"+calendar.formatTime(calendar.currentDate[4]) else calendar.sltDate=calendar.currentDate[0]+"-"+calendar.formatTime(calendar.currentDate[1])+"-"+calendar.formatTime(day); calendar.target.value=calendar.sltDate; calendar.hide(); } } /************** 取得月份的第一天为星期几 *********************/ this.getFirstDay=function(theYear, theMonth){ var firstDate = new Date(theYear,theMonth-1,1); return firstDate.getDay(); } /************** 取得月份共有几天 *********************/ this.getMonthLen=function(theYear, theMonth) { theMonth--; var oneDay = 1000 * 60 * 60 * 24; var thisMonth = new Date(theYear, theMonth, 1); var nextMonth = new Date(theYear, theMonth + 1, 1); var len = Math.ceil((nextMonth.getTime() - thisMonth.getTime())/oneDay); return len; } /************** 隐藏日历 *********************/ this.hide=function(){ //calendar.clearEventKey(); calendar.calendarPad.style.display="none"; } /************** 从这里开始 *********************/ this.setup=function(defaultDate){ calendar.addCalendarPad(); calendar.addCalendarBoard(); calendar.setDefaultDate(); } /************** 格式化时间 *********************/ this.formatTime = function(str) { str = ("00"+str); return str.substr(str.length-2); } /************** 关于AgetimeCalendar *********************/ this.about=function(){ var strAbout = "\nWeb 日历选择输入控件操作说明:\n\n"; strAbout+="-\t: 关于\n"; strAbout+="x\t: 隐藏\n"; strAbout+="<<\t: 上一年\n"; strAbout+="<\t: 上一月\n"; strAbout+="今日\t: 返回当天日期\n"; strAbout+=">\t: 下一月\n"; strAbout+="<<\t: 下一年\n"; strAbout+="\nWeb日历选择输入控件\tVer:v1.0\t\nDesigned By:wxb \t\t2004.11.22\t\n"; alert(strAbout); } document.onkeydown=function(){ if(calendar.calendarPad.style.display=="none"){ window.event.returnValue= true; return true ; } switch(window.event.keyCode){ case 27 : calendar.hide(); break; //ESC case 37 : calendar.prevMonth.onmousedown(); break;//← case 38 : calendar.prevYear.onmousedown();break; //↑ case 39 : calendar.nextMonth.onmousedown(); break;//→ case 40 : calendar.nextYear.onmousedown(); break;//↓ case 84 : calendar.goToday.onclick(); break;//T case 88 : calendar.hide(); break; //X case 72 : calendar.about(); break; //H case 36 : calendar.prevHours.onmousedown(); break;//Home case 35 : calendar.nextHours.onmousedown(); break;//End case 33 : calendar.prevMinutes.onmousedown();break; //PageUp case 34 : calendar.nextMinutes.onmousedown(); break;//PageDown } window.event.keyCode = 0; window.event.returnValue= false; } calendar.setup(); } var CalendarWebControl = new atCalendarControl(); //<input type="text" name="" onFocus="javascript:CalendarWebControl.show(this,false,this.value);">
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var tb_pathToImage = "/wp-content/images/tool/loadingAnimation.gif"; /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init $(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ $(domChunk).click(function(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; }); } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 $("body","html").css({height: "100%", width: "100%"}); $("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page $('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = $("a[@rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); $("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);} $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } $("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } $("#TB_next").click(goNext); } document.onkeydown = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } else if(keycode == 190){ // display previous image if(!(TB_NextHTML == "")){ document.onkeydown = ""; goNext(); } } else if(keycode == 188){ // display next image if(!(TB_PrevHTML == "")){ document.onkeydown = ""; goPrev(); } } }; tb_position(); $("#TB_load").remove(); $("#TB_ImageOff").click(tb_remove); $("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; $("#TB_window").css('top', mouseY); $("#TB_load").css('top', mouseY); if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); $("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>"); }else{//iframe modal $("#TB_overlay").unbind(); $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>"); } }else{// not an iframe, ajax if($("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal $("#TB_overlay").unbind(); $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; $("#TB_ajaxContent")[0].scrollTop = 0; $("#TB_ajaxWindowTitle").html(caption); } } $("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ $("#TB_ajaxContent").append($('#' + params['inlineId']).children()); $("#TB_window").unload(function () { $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); $("#TB_load").remove(); $("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if($.browser.safari){//safari needs help because it will not fire iframe onload $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } }else{ $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); $("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); $("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ document.onkeyup = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } }; } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } function tb_remove() { $("#TB_imageOff").unbind("click"); $("#TB_closeWindowButton").unbind("click"); $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); $("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 $("body","html").css({height: "auto", width: "auto"}); $("html").css("overflow",""); } document.onkeydown = ""; document.onkeyup = ""; return false; } function tb_position() { $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6 $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
/* Name: ImageFlow Version: 1.3.0 (March 9 2010) Author: Finn Rudolph Support: http://finnrudolph.de/ImageFlow License: ImageFlow is licensed under a Creative Commons Attribution-Noncommercial 3.0 Unported License (http://creativecommons.org/licenses/by-nc/3.0/). You are free: + to Share - to copy, distribute and transmit the work + to Remix - to adapt the work Under the following conditions: + Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). + Noncommercial. You may not use this work for commercial purposes. + For any reuse or distribution, you must make clear to others the license terms of this work. + Any of the above conditions can be waived if you get permission from the copyright holder. + Nothing in this license impairs or restricts the author's moral rights. Credits: This script is based on Michael L. Perrys Cover flow in Javascript [1]. The reflections are generated server-sided by a slightly hacked version of Richard Daveys easyreflections [2] written in PHP. The mouse wheel support is an implementation of Adomas Paltanavicius JavaScript mouse wheel code [3]. It also uses the domReadyEvent from Tanny O'Haley [4]. [1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981 [2] http://reflection.corephp.co.uk/v2.php [3] http://adomas.org/javascript-mouse-wheel/ [4] http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-v */ /* ImageFlow constructor */ function ImageFlow () { /* Setting option defaults */ this.defaults = { animationSpeed: 50, /* Animation speed in ms */ aspectRatio: 1.0, /* Aspect ratio of the ImageFlow container (width divided by height) */ buttons: false, /* Toggle navigation buttons */ captions: true, /* Toggle captions */ circular: true, /* Toggle circular rotation */ imageCursor: 'default', /* Cursor type for all images - default is 'default' */ ImageFlowID: 'imageflow', /* Default id of the ImageFlow container */ imageFocusM: 1.0, /* Multiplicator for the focussed image size in percent */ imageFocusMax: 3, /* Max number of images on each side of the focussed one */ imagePath: '', /* Path to the images relative to the reflect_.php script */ imageScaling: true, /* Toggle image scaling */ imagesHeight: 0.3, /* Height of the images div container in percent */ imagesM: 1.3, /* Multiplicator for all images in percent */ onClick: function() { document.location = this.url; }, /* Onclick behaviour */ opacity: false, /* Toggle image opacity */ opacityArray: [10,8,6,4,2], /* Image opacity (range: 0 to 10) first value is for the focussed image */ percentLandscape: 100, /* Scale landscape format */ percentOther: 100, /* Scale portrait and square format */ preloadImages: true, /* Toggles loading bar (false: requires img attributes height and width) */ reflections: true, /* Toggle reflections */ reflectionGET: '', /* Pass variables via the GET method to the reflect_.php script */ reflectionP: 0.5, /* Height of the reflection in percent of the source image */ reflectionPNG: true, /* Toggle reflect2.php or reflect3.php */ reflectPath: '%%reflectPath%%/', /* Path to the reflect_.php script */ scrollbarP: 0.6, /* Width of the scrollbar in percent */ slider: true, /* Toggle slider */ sliderCursor: 'e-resize', /* Slider cursor type - default is 'default' */ sliderWidth: 14, /* Width of the slider in px */ slideshow: false, /* Toggle slideshow */ slideshowSpeed: 1500, /* Time between slides in ms */ slideshowAutoplay: false, /* Toggle automatic slideshow play on startup */ startID: 1, /* Image ID to begin with */ glideToStartID: true, /* Toggle glide animation to start ID */ startAnimation: false, /* Animate images moving in from the right on startup */ xStep: 150 /* Step width on the x-axis in px */ }; /* Closure for this */ var my = this; /* Initiate ImageFlow */ this.init = function (options) { /* Evaluate options */ for(var name in my.defaults) { this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name]; } /* Try to get ImageFlow div element */ var ImageFlowDiv = document.getElementById(my.ImageFlowID); if(ImageFlowDiv) { /* Set it global within the ImageFlow scope */ ImageFlowDiv.style.visibility = 'visible'; this.ImageFlowDiv = ImageFlowDiv; /* Try to create XHTML structure */ if(this.createStructure()) { this.imagesDiv = document.getElementById(my.ImageFlowID+'_images'); this.captionDiv = document.getElementById(my.ImageFlowID+'_caption'); this.navigationDiv = document.getElementById(my.ImageFlowID+'_navigation'); this.scrollbarDiv = document.getElementById(my.ImageFlowID+'_scrollbar'); this.sliderDiv = document.getElementById(my.ImageFlowID+'_slider'); this.buttonNextDiv = document.getElementById(my.ImageFlowID+'_next'); this.buttonPreviousDiv = document.getElementById(my.ImageFlowID+'_previous'); this.buttonSlideshow = document.getElementById(my.ImageFlowID+'_slideshow'); this.indexArray = []; this.current = 0; this.imageID = 0; this.target = 0; this.memTarget = 0; this.firstRefresh = true; this.firstCheck = true; this.busy = false; /* Set height of the ImageFlow container and center the loading bar */ var width = this.ImageFlowDiv.offsetWidth; var height = Math.round(width / my.aspectRatio); document.getElementById(my.ImageFlowID+'_loading_txt').style.paddingTop = ((height * 0.5) -22) + 'px'; ImageFlowDiv.style.height = height + 'px'; /* Init loading progress */ this.loadingProgress(); } } }; /* Create HTML Structure */ this.createStructure = function() { /* Create images div container */ var imagesDiv = my.Helper.createDocumentElement('div','images'); /* Shift all images into the images div */ var node, version, src, imageNode; var max = my.ImageFlowDiv.childNodes.length; for(var index = 0; index < max; index++) { node = my.ImageFlowDiv.childNodes[index]; if (node && node.nodeType == 1 && node.nodeName == 'IMG') { /* Add 'reflect.php?img=' */ if(my.reflections === true) { version = (my.reflectionPNG) ? '3' : '2'; src = my.imagePath+node.getAttribute('src',2); src = my.reflectPath+'reflect'+version+'.php?img='+src+my.reflectionGET; node.setAttribute('src',src); } /* Clone image nodes and append them to the images div */ imageNode = node.cloneNode(true); imagesDiv.appendChild(imageNode); } } /* Clone some more images to make a circular animation possible */ if(my.circular) { /* Create temporary elements to hold the cloned images */ var first = my.Helper.createDocumentElement('div','images'); var last = my.Helper.createDocumentElement('div','images'); /* Make sure, that there are enough images to use circular mode */ max = imagesDiv.childNodes.length; if(max < my.imageFocusMax) { my.imageFocusMax = max; } /* Do not clone anything if there is only one image */ if(max > 1) { /* Clone the first and last images */ var i; for(i = 0; i < max; i++) { /* Number of clones on each side equals the imageFocusMax */ node = imagesDiv.childNodes[i]; if(i < my.imageFocusMax) { imageNode = node.cloneNode(true); first.appendChild(imageNode); } if(max-i < my.imageFocusMax+1) { imageNode = node.cloneNode(true); last.appendChild(imageNode); } } /* Sort the image nodes in the following order: last | originals | first */ for(i = 0; i < max; i++) { node = imagesDiv.childNodes[i]; imageNode = node.cloneNode(true); last.appendChild(imageNode); } for(i = 0; i < my.imageFocusMax; i++) { node = first.childNodes[i]; imageNode = node.cloneNode(true); last.appendChild(imageNode); } /* Overwrite the imagesDiv with the new order */ imagesDiv = last; } } /* Create slideshow button div and append it to the images div */ if(my.slideshow) { var slideshowButton = my.Helper.createDocumentElement('div','slideshow'); imagesDiv.appendChild(slideshowButton); } /* Create loading text container */ var loadingP = my.Helper.createDocumentElement('p','loading_txt'); var loadingText = document.createTextNode(' '); loadingP.appendChild(loadingText); /* Create loading div container */ var loadingDiv = my.Helper.createDocumentElement('div','loading'); /* Create loading bar div container inside the loading div */ var loadingBarDiv = my.Helper.createDocumentElement('div','loading_bar'); loadingDiv.appendChild(loadingBarDiv); /* Create captions div container */ var captionDiv = my.Helper.createDocumentElement('div','caption'); /* Create slider and button div container inside the scrollbar div */ var scrollbarDiv = my.Helper.createDocumentElement('div','scrollbar'); var sliderDiv = my.Helper.createDocumentElement('div','slider'); scrollbarDiv.appendChild(sliderDiv); if(my.buttons) { var buttonPreviousDiv = my.Helper.createDocumentElement('div','previous', 'button'); var buttonNextDiv = my.Helper.createDocumentElement('div','next', 'button'); scrollbarDiv.appendChild(buttonPreviousDiv); scrollbarDiv.appendChild(buttonNextDiv); } /* Create navigation div container beneath images div */ var navigationDiv = my.Helper.createDocumentElement('div','navigation'); navigationDiv.appendChild(captionDiv); navigationDiv.appendChild(scrollbarDiv); /* Update document structure and return true on success */ var success = false; if (my.ImageFlowDiv.appendChild(imagesDiv) && my.ImageFlowDiv.appendChild(loadingP) && my.ImageFlowDiv.appendChild(loadingDiv) && my.ImageFlowDiv.appendChild(navigationDiv)) { /* Remove image nodes outside the images div */ max = my.ImageFlowDiv.childNodes.length; for(index = 0; index < max; index++) { node = my.ImageFlowDiv.childNodes[index]; if (node && node.nodeType == 1 && node.nodeName == 'IMG') { my.ImageFlowDiv.removeChild(node); } } success = true; } return success; }; /* Manage loading progress and call the refresh function */ this.loadingProgress = function() { var p = my.loadingStatus(); if((p < 100 || my.firstCheck) && my.preloadImages) { /* Insert a short delay if the browser loads rapidly from its cache */ if(my.firstCheck && p == 100) { my.firstCheck = false; window.setTimeout(my.loadingProgress, 100); } else { window.setTimeout(my.loadingProgress, 40); } } else { /* Hide loading elements */ document.getElementById(my.ImageFlowID+'_loading_txt').style.display = 'none'; document.getElementById(my.ImageFlowID+'_loading').style.display = 'none'; /* Refresh ImageFlow on window resize - delay adding this event for the IE */ window.setTimeout(my.Helper.addResizeEvent, 1000); /* Call refresh once on startup to display images */ my.refresh(); /* Only initialize navigation elements if there is more than one image */ if(my.max > 1) { /* Initialize mouse, touch and key support */ my.MouseWheel.init(); my.MouseDrag.init(); my.Touch.init(); my.Key.init(); /* Toggle slideshow */ if(my.slideshow) { my.Slideshow.init(); } /* Toggle scrollbar visibility */ if(my.slider) { my.scrollbarDiv.style.visibility = 'visible'; } } } }; /* Return loaded images in percent, set loading bar width and loading text */ this.loadingStatus = function() { var max = my.imagesDiv.childNodes.length; var i = 0, completed = 0; var image = null; for(var index = 0; index < max; index++) { image = my.imagesDiv.childNodes[index]; if(image && image.nodeType == 1 && image.nodeName == 'IMG') { if(image.complete) { completed++; } i++; } } var finished = Math.round((completed/i)*100); var loadingBar = document.getElementById(my.ImageFlowID+'_loading_bar'); loadingBar.style.width = finished+'%'; /* Do not count the cloned images */ if(my.circular) { i = i - (my.imageFocusMax*2); completed = (finished < 1) ? 0 : Math.round((i/100)*finished); } var loadingP = document.getElementById(my.ImageFlowID+'_loading_txt'); var loadingTxt = document.createTextNode('loading images '+completed+'/'+i); loadingP.replaceChild(loadingTxt,loadingP.firstChild); return finished; }; /* Cache EVERYTHING that only changes on refresh or resize of the window */ this.refresh = function() { /* Cache global variables */ this.imagesDivWidth = my.imagesDiv.offsetWidth+my.imagesDiv.offsetLeft; this.maxHeight = Math.round(my.imagesDivWidth / my.aspectRatio); this.maxFocus = my.imageFocusMax * my.xStep; this.size = my.imagesDivWidth * 0.5; this.sliderWidth = my.sliderWidth * 0.5; this.scrollbarWidth = (my.imagesDivWidth - ( Math.round(my.sliderWidth) * 2)) * my.scrollbarP; this.imagesDivHeight = Math.round(my.maxHeight * my.imagesHeight); /* Change imageflow div properties */ my.ImageFlowDiv.style.height = my.maxHeight + 'px'; /* Change images div properties */ my.imagesDiv.style.height = my.imagesDivHeight + 'px'; /* Change images div properties */ my.navigationDiv.style.height = (my.maxHeight - my.imagesDivHeight) + 'px'; /* Change captions div properties */ my.captionDiv.style.width = my.imagesDivWidth + 'px'; my.captionDiv.style.paddingTop = Math.round(my.imagesDivWidth * 0.02) + 'px'; /* Change scrollbar div properties */ my.scrollbarDiv.style.width = my.scrollbarWidth + 'px'; my.scrollbarDiv.style.marginTop = Math.round(my.imagesDivWidth * 0.02) + 'px'; my.scrollbarDiv.style.marginLeft = Math.round(my.sliderWidth + ((my.imagesDivWidth - my.scrollbarWidth)/2)) + 'px'; /* Set slider attributes */ my.sliderDiv.style.cursor = my.sliderCursor; my.sliderDiv.onmousedown = function () { my.MouseDrag.start(this); return false;}; if(my.buttons) { my.buttonPreviousDiv.onclick = function () { my.MouseWheel.handle(1); }; my.buttonNextDiv.onclick = function () { my.MouseWheel.handle(-1); }; } /* Set the reflection multiplicator */ var multi = (my.reflections === true) ? my.reflectionP + 1 : 1; /* Set image attributes */ var max = my.imagesDiv.childNodes.length; var i = 0; var image = null; for (var index = 0; index < max; index++) { image = my.imagesDiv.childNodes[index]; if(image !== null && image.nodeType == 1 && image.nodeName == 'IMG') { this.indexArray[i] = index; /* Set image attributes to store values */ image.url = image.getAttribute('longdesc'); image.xPosition = (-i * my.xStep); image.i = i; /* Add width and height as attributes only once */ if(my.firstRefresh) { if(image.getAttribute('width') !== null && image.getAttribute('height') !== null) { image.w = image.getAttribute('width'); image.h = image.getAttribute('height') * multi; } else{ image.w = image.width; image.h = image.height; } } /* Check source image format. Get image height minus reflection height! */ if((image.w) > (image.h / (my.reflectionP + 1))) { /* Landscape format */ image.pc = my.percentLandscape; image.pcMem = my.percentLandscape; } else { /* Portrait and square format */ image.pc = my.percentOther; image.pcMem = my.percentOther; } /* Change image positioning */ if(my.imageScaling === false) { image.style.position = 'relative'; image.style.display = 'inline'; } /* Set image cursor type */ image.style.cursor = my.imageCursor; i++; } } this.max = my.indexArray.length; /* Override dynamic sizes based on the first image */ if(my.imageScaling === false) { image = my.imagesDiv.childNodes[my.indexArray[0]]; /* Set left padding for the first image */ this.totalImagesWidth = image.w * my.max; image.style.paddingLeft = (my.imagesDivWidth/2) + (image.w/2) + 'px'; /* Override images and navigation div height */ my.imagesDiv.style.height = image.h + 'px'; my.navigationDiv.style.height = (my.maxHeight - image.h) + 'px'; } /* Handle startID on the first refresh */ if(my.firstRefresh) { /* Reset variable */ my.firstRefresh = false; /* Set imageID to the startID */ my.imageID = my.startID-1; if (my.imageID < 0 ) { my.imageID = 0; } /* Map image id range in cicular mode (ignore the cloned images) */ if(my.circular) { my.imageID = my.imageID + my.imageFocusMax; } /* Make sure, that the id is smaller than the image count */ maxId = (my.circular) ? (my.max-(my.imageFocusMax))-1 : my.max-1; if (my.imageID > maxId) { my.imageID = maxId; } /* Toggle glide animation to start ID */ if(my.glideToStartID === false) { my.moveTo(-my.imageID * my.xStep); } /* Animate images moving in from the right */ if(my.startAnimation) { my.moveTo(5000); } } /* Only animate if there is more than one image */ if(my.max > 1) { my.glideTo(my.imageID); } /* Display images in current order */ my.moveTo(my.current); }; /* Main animation function */ this.moveTo = function(x) { this.current = x; this.zIndex = my.max; /* Main loop */ for (var index = 0; index < my.max; index++) { var image = my.imagesDiv.childNodes[my.indexArray[index]]; var currentImage = index * -my.xStep; /* Enabled image scaling */ if(my.imageScaling) { /* Don't display images that are not conf_focussed */ if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget) { image.style.visibility = 'hidden'; image.style.display = 'none'; } else { var z = (Math.sqrt(10000 + x * x) + 100) * my.imagesM; var xs = x / z * my.size + my.size; /* Still hide images until they are processed, but set display style to block */ image.style.display = 'block'; /* Process new image height and width */ var newImageH = (image.h / image.w * image.pc) / z * my.size; var newImageW = 0; switch (newImageH > my.maxHeight) { case false: newImageW = image.pc / z * my.size; break; default: newImageH = my.maxHeight; newImageW = image.w * newImageH / image.h; break; } var newImageTop = (my.imagesDivHeight - newImageH) + ((newImageH / (my.reflectionP + 1)) * my.reflectionP); /* Set new image properties */ image.style.left = xs - (image.pc / 2) / z * my.size + 'px'; if(newImageW && newImageH) { image.style.height = newImageH + 'px'; image.style.width = newImageW + 'px'; image.style.top = newImageTop + 'px'; } image.style.visibility = 'visible'; /* Set image layer through zIndex */ switch ( x < 0 ) { case true: this.zIndex++; break; default: this.zIndex = my.zIndex - 1; break; } /* Change zIndex and onclick function of the focussed image */ switch ( image.i == my.imageID ) { case false: image.onclick = function() { my.glideTo(this.i);}; break; default: this.zIndex = my.zIndex + 1; if(image.url !== '') { image.onclick = my.onClick; } break; } image.style.zIndex = my.zIndex; } } /* Disabled image scaling */ else { if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget) { image.style.visibility = 'hidden'; } else { image.style.visibility = 'visible'; /* Change onclick function of the focussed image */ switch ( image.i == my.imageID ) { case false: image.onclick = function() { my.glideTo(this.i);}; break; default: if(image.url !== '') { image.onclick = my.onClick; } break; } } my.imagesDiv.style.marginLeft = (x - my.totalImagesWidth) + 'px'; } x += my.xStep; } }; /* Initializes image gliding animation */ this.glideTo = function(imageID) { /* Check for jumppoints */ var jumpTarget, clonedImageID; if(my.circular) { /* Trigger left jumppoint */ if(imageID+1 === my.imageFocusMax) { /* Set jump target to the same cloned image on the right */ clonedImageID = my.max - my.imageFocusMax; jumpTarget = -clonedImageID * my.xStep; /* Set the imageID to the last image */ imageID = clonedImageID-1 ; } /* Trigger right jumppoint */ if(imageID === (my.max - my.imageFocusMax)) { /* Set jump target to the same cloned image on the left */ clonedImageID = my.imageFocusMax-1; jumpTarget = -clonedImageID * my.xStep; /* Set the imageID to the first image */ imageID = clonedImageID+1; } } /* Calculate new image position target */ var x = -imageID * my.xStep; this.target = x; this.memTarget = x; this.imageID = imageID; /* Display new caption */ var caption = my.imagesDiv.childNodes[imageID].getAttribute('alt'); if (caption === '' || my.captions === false) { caption = '&nbsp;'; } my.captionDiv.innerHTML = caption; /* Set scrollbar slider to new position */ if (my.MouseDrag.busy === false) { if(my.circular) { this.newSliderX = ((imageID-my.imageFocusMax) * my.scrollbarWidth) / (my.max-(my.imageFocusMax*2)-1) - my.MouseDrag.newX; } else { this.newSliderX = (imageID * my.scrollbarWidth) / (my.max-1) - my.MouseDrag.newX; } my.sliderDiv.style.marginLeft = (my.newSliderX - my.sliderWidth) + 'px'; } /* Only process if opacity or a multiplicator for the focussed image has been set */ if(my.opacity === true || my.imageFocusM !== my.defaults.imageFocusM) { /* Set opacity for centered image */ my.Helper.setOpacity(my.imagesDiv.childNodes[imageID], my.opacityArray[0]); my.imagesDiv.childNodes[imageID].pc = my.imagesDiv.childNodes[imageID].pc * my.imageFocusM; /* Set opacity for the other images that are displayed */ var opacityValue = 0; var rightID = 0; var leftID = 0; var last = my.opacityArray.length; for (var i = 1; i < (my.imageFocusMax+1); i++) { if((i+1) > last) { opacityValue = my.opacityArray[last-1]; } else { opacityValue = my.opacityArray[i]; } rightID = imageID + i; leftID = imageID - i; if (rightID < my.max) { my.Helper.setOpacity(my.imagesDiv.childNodes[rightID], opacityValue); my.imagesDiv.childNodes[rightID].pc = my.imagesDiv.childNodes[rightID].pcMem; } if (leftID >= 0) { my.Helper.setOpacity(my.imagesDiv.childNodes[leftID], opacityValue); my.imagesDiv.childNodes[leftID].pc = my.imagesDiv.childNodes[leftID].pcMem; } } } /* Move the images to the jump target */ if(jumpTarget) { my.moveTo(jumpTarget); } /* Animate gliding to new x position */ if (my.busy === false) { my.busy = true; my.animate(); } }; /* Animates image gliding */ this.animate = function() { switch (my.target < my.current-1 || my.target > my.current+1) { case true: my.moveTo(my.current + (my.target-my.current)/3); window.setTimeout(my.animate, my.animationSpeed); my.busy = true; break; default: my.busy = false; break; } }; /* Used by user events to call the glideTo function */ this.glideOnEvent = function(imageID) { /* Interrupt slideshow on mouse wheel, keypress, touch and mouse drag */ if(my.slideshow) { my.Slideshow.interrupt(); } /* Glide to new imageID */ my.glideTo(imageID); }; /* Slideshow function */ this.Slideshow = { direction: 1, init: function() { /* Call start() if autoplay is enabled, stop() if it is disabled */ (my.slideshowAutoplay) ? my.Slideshow.start() : my.Slideshow.stop(); }, interrupt: function() { /* Remove interrupt event */ my.Helper.removeEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt); /* Interrupt the slideshow */ my.Slideshow.stop(); }, addInterruptEvent: function() { /* A click anywhere inside the ImageFlow div interrupts the slideshow */ my.Helper.addEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt); }, start: function() { /* Set button style to pause */ my.Helper.setClassName(my.buttonSlideshow, 'slideshow pause'); /* Set onclick behaviour to stop */ my.buttonSlideshow.onclick = function () { my.Slideshow.stop(); }; /* Set slide interval */ my.Slideshow.action = window.setInterval(my.Slideshow.slide, my.slideshowSpeed); /* Allow the user to always interrupt the slideshow */ window.setTimeout(my.Slideshow.addInterruptEvent, 100); }, stop: function() { /* Set button style to play */ my.Helper.setClassName(my.buttonSlideshow, 'slideshow play'); /* Set onclick behaviour to start */ my.buttonSlideshow.onclick = function () { my.Slideshow.start(); }; /* Clear slide interval */ window.clearInterval(my.Slideshow.action); }, slide: function() { var newImageID = my.imageID + my.Slideshow.direction; var reverseDirection = false; /* Reverse direction at the last image on the right */ if(newImageID === my.max) { my.Slideshow.direction = -1; reverseDirection = true; } /* Reverse direction at the last image on the left */ if(newImageID < 0) { my.Slideshow.direction = 1; reverseDirection = true; } /* If direction is reversed recall this method, else call the glideTo method */ (reverseDirection) ? my.Slideshow.slide() : my.glideTo(newImageID); } }; /* Mouse Wheel support */ this.MouseWheel = { init: function() { /* Init mouse wheel listener */ if(window.addEventListener) { my.ImageFlowDiv.addEventListener('DOMMouseScroll', my.MouseWheel.get, false); } my.Helper.addEvent(my.ImageFlowDiv,'mousewheel',my.MouseWheel.get); }, get: function(event) { var delta = 0; if (!event) { event = window.event; } if (event.wheelDelta) { delta = event.wheelDelta / 120; } else if (event.detail) { delta = -event.detail / 3; } if (delta) { my.MouseWheel.handle(delta); } my.Helper.suppressBrowserDefault(event); }, handle: function(delta) { var change = false; var newImageID = 0; if(delta > 0) { if(my.imageID >= 1) { newImageID = my.imageID -1; change = true; } } else { if(my.imageID < (my.max-1)) { newImageID = my.imageID +1; change = true; } } /* Glide to next (mouse wheel down) / previous (mouse wheel up) image */ if(change) { my.glideOnEvent(newImageID); } } }; /* Mouse Dragging */ this.MouseDrag = { object: null, objectX: 0, mouseX: 0, newX: 0, busy: false, /* Init mouse event listener */ init: function() { my.Helper.addEvent(my.ImageFlowDiv,'mousemove',my.MouseDrag.drag); my.Helper.addEvent(my.ImageFlowDiv,'mouseup',my.MouseDrag.stop); my.Helper.addEvent(document,'mouseup',my.MouseDrag.stop); /* Avoid text and image selection while dragging */ my.ImageFlowDiv.onselectstart = function () { var selection = true; if (my.MouseDrag.busy) { selection = false; } return selection; }; }, start: function(o) { my.MouseDrag.object = o; my.MouseDrag.objectX = my.MouseDrag.mouseX - o.offsetLeft + my.newSliderX; }, stop: function() { my.MouseDrag.object = null; my.MouseDrag.busy = false; }, drag: function(e) { var posx = 0; if (!e) { e = window.event; } if (e.pageX) { posx = e.pageX; } else if (e.clientX) { posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; } my.MouseDrag.mouseX = posx; if(my.MouseDrag.object !== null) { var newX = (my.MouseDrag.mouseX - my.MouseDrag.objectX) + my.sliderWidth; /* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */ if(newX < ( - my.newSliderX)) { newX = - my.newSliderX; } if(newX > (my.scrollbarWidth - my.newSliderX)) { newX = my.scrollbarWidth - my.newSliderX; } /* Set new slider position */ var step, imageID; if(my.circular) { step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-(my.imageFocusMax*2)-1)); imageID = Math.round(step)+my.imageFocusMax; } else { step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-1)); imageID = Math.round(step); } my.MouseDrag.newX = newX; my.MouseDrag.object.style.left = newX + 'px'; if(my.imageID !== imageID) { my.glideOnEvent(imageID); } my.MouseDrag.busy = true; } } }; /* Safari touch events on the iPhone and iPod Touch */ this.Touch = { x: 0, startX: 0, stopX: 0, busy: false, first: true, /* Init touch event listener */ init: function() { my.Helper.addEvent(my.navigationDiv,'touchstart',my.Touch.start); my.Helper.addEvent(document,'touchmove',my.Touch.handle); my.Helper.addEvent(document,'touchend',my.Touch.stop); }, isOnNavigationDiv: function(e) { var state = false; if(e.touches) { var target = e.touches[0].target; if(target === my.navigationDiv || target === my.sliderDiv || target === my.scrollbarDiv) { state = true; } } return state; }, getX: function(e) { var x = 0; if(e.touches) { x = e.touches[0].pageX; } return x; }, start: function(e) { my.Touch.startX = my.Touch.getX(e); my.Touch.busy = true; my.Helper.suppressBrowserDefault(e); }, isBusy: function() { var busy = false; if(my.Touch.busy) { busy = true; } return busy; }, /* Handle touch event position within the navigation div */ handle: function(e) { if(my.Touch.isBusy && my.Touch.isOnNavigationDiv(e)) { var max = (my.circular) ? (my.max-(my.imageFocusMax*2)-1) : (my.max-1); if(my.Touch.first) { my.Touch.stopX = (max - my.imageID) * (my.imagesDivWidth / max); my.Touch.first = false; } var newX = -(my.Touch.getX(e) - my.Touch.startX - my.Touch.stopX); /* Map x-axis touch coordinates in range of the ImageFlow width */ if(newX < 0) { newX = 0; } if(newX > my.imagesDivWidth) { newX = my.imagesDivWidth; } my.Touch.x = newX; var imageID = Math.round(newX / (my.imagesDivWidth / max)); imageID = max - imageID; if(my.imageID !== imageID) { if(my.circular) { imageID = imageID + my.imageFocusMax; } my.glideOnEvent(imageID); } my.Helper.suppressBrowserDefault(e); } }, stop: function() { my.Touch.stopX = my.Touch.x; my.Touch.busy = false; } }; /* Key support */ this.Key = { /* Init key event listener */ init: function() { document.onkeydown = function(event){ my.Key.handle(event); }; }, /* Handle the arrow keys */ handle: function(event) { var charCode = my.Key.get(event); switch (charCode) { /* Right arrow key */ case 39: my.MouseWheel.handle(-1); break; /* Left arrow key */ case 37: my.MouseWheel.handle(1); break; } }, /* Get the current keycode */ get: function(event) { event = event || window.event; return event.keyCode; } }; /* Helper functions */ this.Helper = { /* Add events */ addEvent: function(obj, type, fn) { if(obj.addEventListener) { obj.addEventListener(type, fn, false); } else if(obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }; obj.attachEvent( "on"+type, obj[type+fn] ); } }, /* Remove events */ removeEvent: function( obj, type, fn ) { if (obj.removeEventListener) { obj.removeEventListener( type, fn, false ); } else if (obj.detachEvent) { /* The IE breaks if you're trying to detach an unattached event http://msdn.microsoft.com/en-us/library/ms536411(VS.85).aspx */ if(obj[type+fn] === undefined) { alert('Helper.removeEvent » Pointer to detach event is undefined - perhaps you are trying to detach an unattached event?'); } obj.detachEvent( 'on'+type, obj[type+fn] ); obj[type+fn] = null; obj['e'+type+fn] = null; } }, /* Set image opacity */ setOpacity: function(object, value) { if(my.opacity === true) { object.style.opacity = value/10; object.style.filter = 'alpha(opacity=' + value*10 + ')'; } }, /* Create HTML elements */ createDocumentElement: function(type, id, optionalClass) { var element = document.createElement(type); element.setAttribute('id', my.ImageFlowID+'_'+id); if(optionalClass !== undefined) { id += ' '+optionalClass; } my.Helper.setClassName(element, id); return element; }, /* Set CSS class */ setClassName: function(element, className) { if(element) { element.setAttribute('class', className); element.setAttribute('className', className); } }, /* Suppress default browser behaviour to avoid image/text selection while dragging */ suppressBrowserDefault: function(e) { if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return false; }, /* Add functions to the window.onresize event - can not be done by addEvent */ addResizeEvent: function() { var otherFunctions = window.onresize; if(typeof window.onresize != 'function') { window.onresize = function() { my.refresh(); }; } else { window.onresize = function(){ if (otherFunctions) { otherFunctions(); } my.refresh(); }; } } }; } /* DOMContentLoaded event handler - by Tanny O'Haley [4] */ var domReadyEvent = { name: "domReadyEvent", /* Array of DOMContentLoaded event handlers.*/ events: {}, domReadyID: 1, bDone: false, DOMContentLoadedCustom: null, /* Function that adds DOMContentLoaded listeners to the array.*/ add: function(handler) { /* Assign each event handler a unique ID. If the handler has an ID, it has already been added to the events object or been run.*/ if (!handler.$$domReadyID) { handler.$$domReadyID = this.domReadyID++; /* If the DOMContentLoaded event has happened, run the function. */ if(this.bDone) { handler(); } /* store the event handler in the hash table */ this.events[handler.$$domReadyID] = handler; } }, remove: function(handler) { /* Delete the event handler from the hash table */ if (handler.$$domReadyID) { delete this.events[handler.$$domReadyID]; } }, /* Function to process the DOMContentLoaded events array. */ run: function() { /* quit if this function has already been called */ if (this.bDone) { return; } /* Flag this function so we don't do the same thing twice */ this.bDone = true; /* iterates through array of registered functions */ for (var i in this.events) { this.events[i](); } }, schedule: function() { /* Quit if the init function has already been called*/ if (this.bDone) { return; } /* First, check for Safari or KHTML.*/ if(/KHTML|WebKit/i.test(navigator.userAgent)) { if(/loaded|complete/.test(document.readyState)) { this.run(); } else { /* Not ready yet, wait a little more.*/ setTimeout(this.name + ".schedule()", 100); } } else if(document.getElementById("__ie_onload")) { /* Second, check for IE.*/ return true; } /* Check for custom developer provided function.*/ if(typeof this.DOMContentLoadedCustom === "function") { /* if DOM methods are supported, and the body element exists (using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section) */ if(typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) { /* Call custom function. */ if(this.DOMContentLoadedCustom()) { this.run(); } else { /* Not ready yet, wait a little more. */ setTimeout(this.name + ".schedule()", 250); } } } return true; }, init: function() { /* If addEventListener supports the DOMContentLoaded event.*/ if(document.addEventListener) { document.addEventListener("DOMContentLoaded", function() { domReadyEvent.run(); }, false); } /* Schedule to run the init function.*/ setTimeout("domReadyEvent.schedule()", 100); function run() { domReadyEvent.run(); } /* Just in case window.onload happens first, add it to onload using an available method.*/ if(typeof addEvent !== "undefined") { addEvent(window, "load", run); } else if(document.addEventListener) { document.addEventListener("load", run, false); } else if(typeof window.onload === "function") { var oldonload = window.onload; window.onload = function() { domReadyEvent.run(); oldonload(); }; } else { window.onload = run; } /* for Internet Explorer */ /*@cc_on @if (@_win32 || @_win64) document.write("<script id=__ie_onload defer src=\"//:\"><\/script>"); var script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") { domReadyEvent.run(); // call the onload handler } }; @end @*/ } }; var domReady = function(handler) { domReadyEvent.add(handler); }; domReadyEvent.init(); /* Create ImageFlow instances when the DOM structure has been loaded */ domReady(function() { var instanceOne = new ImageFlow(); instanceOne.init({ ImageFlowID:'myImageFlow' }); });
JavaScript
// For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232509 (function () { "use strict"; WinJS.Binding.optimizeBindingReferences = true; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll()); } }; app.oncheckpoint = function (args) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // args.setPromise(). }; app.start(); })();
JavaScript
AJAX_SUCCESS = false; var httpRequest = function( options ){ var default_options = { type : "GET", host : "", port : 80, uri : "/", useragent : "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US)", headers : "", getdata : "", postdata : "", resolveTimeout : 10000, connectTimeout : 10000, sendTimeout : 10000, receiveTimeout : 10000 } for( var key in options ){ if( options.hasOwnProperty(key) && ( key in default_options ) ){ default_options[key] = options[key]; } } return document.getElementById("simplehttpobj").http( default_options.type ,default_options.host ,default_options.port ,default_options.uri ,default_options.useragent ,default_options.headers ,default_options.getdata ,default_options.postdata ,default_options.resolveTimeout ,default_options.connectTimeout ,default_options.sendTimeout ,default_options.receiveTimeout ); } var ajax = function( url,handler ){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = handler; xhr.open("GET", url, true); xhr.send(null); ajax.abort = function(){xhr.abort();}; }; chrome.extension.onRequest.addListener(function( request,sender,sendResponse ){ if( request.action != "geturl" || !request.urloption ){ sendResponse({code:-1,message:"无效请求",data:null}); }else{ var response; var localHttpFailed = false; try{ console.log( "local request -> " + "http://"+request.urloption.host+request.urloption.uri+request.urloption.getdata ) response = httpRequest( request.urloption ); console.log( response ); }catch( err ){//dll出错 localHttpFailed = true; } if(/^\d+$/.test(response)){ localHttpFailed = true; } if(!localHttpFailed){//本地加载数据成功 try{ var jsonData = JSON.parse(response); sendResponse({code:0,message:"成功",data:jsonData}); }catch( err ){ sendResponse({code:-3,message:"数据解析失败",data:_this.status}); } }else{//从网络加载 var proxy = "http://hellohtml5.com/simple", url = "http://"+request.urloption.host+request.urloption.uri+request.urloption.getdata; request_url = proxy + "/" + url; console.log("ajax->"+request_url); ajax(request_url,function(){ var _this = this; if( _this.readyState == 4 && _this.status==200 ){ AJAX_SUCCESS = true; var responseText = _this.responseText.replace(/^[^\{]+/,'').replace(/[^\}]+$/,''); console.log(responseText); try{ var jsonData = JSON.parse(responseText); sendResponse({code:0,message:"成功",data:jsonData}); }catch( err ){ sendResponse({code:-3,message:"数据解析失败",data:_this.status}); } }else if( _this.readyState == 4 && _this.status != 200 ){ AJAX_SUCCESS = true; sendResponse({code:-2,message:"http状态错误",data:_this.status}); } }); setTimeout(function(){//20秒后发送超时消息 if(!AJAX_SUCCESS){ ajax.abort(); sendResponse({code:-5,message:"超时,请重试"}); } },20*1000); } } });
JavaScript
(function(){ var downloadlinks = document.querySelector(".download-box > .btn-wrap"), hasdownloadlink = downloadlinks && downloadlinks.length > 0, pickcode = /https?:\/\/115\.com\/file\/([a-zA-Z0-9]+)/.exec(document.location.href), pickcode = pickcode ? pickcode[1] : null, CRLF = "\r\n"; if(/*!hasdownloadlink && */pickcode){ var mainWrapper = document.createElement("div"); var main = document.createElement("div"); var loading = document.createElement("div"); var loadingTitle = document.createElement("div"); var loadingStatus = document.createElement("div"); var loadingPicURL = chrome.extension.getURL("imgs/loading.gif"); var successPicURL = chrome.extension.getURL("imgs/success.png"); var failPicURL = chrome.extension.getURL("imgs/error.png"); var warningPicURL = chrome.extension.getURL("imgs/warning.png"); var closePicURL = chrome.extension.getURL("imgs/close.png"); //越狱相关函数 var jailbreakMessage = function( title,result ){ loadingTitle.innerHTML = title; loadingStatus.innerHTML = result; } var jailbreakSuccess = function( result ){ jailbreakMessage("越狱成功",result); loading.style.backgroundImage="url(\""+successPicURL+"\")"; showCloseBtn(); } var jailbreakFail = function( result ){ jailbreakMessage("越狱失败",result); loading.style.backgroundImage="url(\""+failPicURL+"\")"; showCloseBtn(); } var jailbreakWarning = function( result ){ jailbreakMessage("仍在进行",result); loading.style.backgroundImage="url(\""+warningPicURL+"\")"; showCloseBtn(); } var jailbreaking = function( status ){ jailbreakMessage("越狱中",status); } var showCloseBtn = function(){ var close = mydialog.getCloseBtn(); close.style.display="block"; close.style.opacity="0"; setTimeout(function(){ close.style.opacity="1"; },0); } var initCloseBtn = function(){ mydialog.getCloseBtn().style.backgroundImage="url(\""+closePicURL+"\")"; } mainWrapper.setAttribute( "style", "width:276px;height:132px;-webkit-border-radius:8px;background:-webkit-gradient(linear,left top,left bottom,from(#dfe1e7),to(#babfcb));border-top:1px solid #6b6b6b;border-left:1px solid #585858;border-bottom:1px solid #424242;border-right:1px solid #595959;-webkit-box-shadow:1px 1px 6px #000;"); main.setAttribute( "style", "width:270px;height:126px;position:relative;top:3px;left:3px;-webkit-border-radius:8px;background:#1c2c54;" ); main.setAttribute("class","dialogmain"); loading.setAttribute( "style", "width:100%;height:100%;font-family:'Microsoft YaHei';text-align:center;background:url('"+loadingPicURL+"') no-repeat 50% 75%" ); loadingTitle.setAttribute( "style", "width:100%;height:48px;line-height:48px;font-size:16px;color:#fff;" ); loadingStatus.setAttribute( "style", "width:100%;height:16px;line-height:16px;font-size:12px;color:#999;position:relative;top:-5px;" ); loading.appendChild(loadingTitle); loading.appendChild(loadingStatus); main.appendChild(loading); mainWrapper.appendChild(main); mydialog = new dialog(document.body,{contentdom:mainWrapper,modal:true}); mydialog.show(); initCloseBtn(); window.addEventListener("resize",function(){ mydialog.update(); },false); //获取实际下载链接地址 jailbreaking("请稍候..."); var responseReceived = false; // setTimeout(function(){//5秒正常时间超时提示 if(!responseReceived){ jailbreakWarning("超过正常需要的时间..."); } },5*1000); // chrome.extension.sendRequest({action:"geturl",urloption:{ host:"u.115.com", uri :"/?", headers : "Cookie: "+ "OOFL=115jailbreak; OOFA=%250D%250ETV_V%2508%250C%2506%2506%250D%2508W%250BZP%2540%255D%2507%250F%2503%2506%2507Q%2507TV%255CZXxBD%2519%2502%2509%250BX%2500%2505%2507%2505%2508Z%250FR%2506%2503%2508%250A%255E%255C%2509VUQ%2501%2504T%255D%2502%2504%250D%250B%2500%2504W%2505VWTTTS%2509U%2506%2507%2506%2506P" + CRLF + CRLF, getdata:"ct=upload_api&ac=get_pick_code_info&pickcode="+pickcode+"&version=1176", host: "uapi.115.com", useragent: "115UDownClient 2.1.11.126" }},function(response){ responseReceived = true; //开始处理 if( response.code != 0 ){ //插件内部错误 responseReceived = true; var errormessage = response.message || ""; errormessage += !!errormessage?",":""; errormessage += "请尝试<a href=\"https://chrome.google.com/extensions/detail/aiiloiffkhndoefjpciepoldngggnblb\">更新插件</a>或<a href=\"http://t.qq.com/mmplayer\">联系作者</a>解决"; jailbreakFail(errormessage); return; } //end if var response = response.data; var state = response.State || response.state; var message = response.Message || response.message; var urls = response.DownloadUrl; if( state && urls ){//成功 var download_html = "<div class=\"downloadlinks\">"; var ISPlist = ["电信下载","网通下载","备份下载"] for(var i=0,l=urls.length;i<l;i++){ download_html +="<a href=\""; download_html +=urls[i].Url; download_html +="\">"; download_html +=ISPlist[i]?ISPlist[i]:"其它下载"; download_html +="</a>"; } download_html+="</div>"; jailbreakSuccess(download_html); }else{//失败 jailbreakFail(message); } }); }//end if })();
JavaScript
/********************************************************** * Dialog Module * **********************************************************/ (function(){ var uid = 0;//dialog uid /******************Paper******************/ var paper = function( wrapper ){ var _this = this; _this.mask = document.createElement("div"); _this.wrapper = wrapper; //遮罩样式 _this.mask.setAttribute( "style","position:absolute;" + "width:100%;"+ "height:100%;"+ "left:0;"+ "top:0;"+ "z-index:99999;"+ "opacity:0;"+ "-webkit-user-select:none;"+ "background:black;"+ "-webkit-transition-property:opacity;"+ "-webkit-transition-duration:800ms;"); wrapper.appendChild(_this.mask); } paper.prototype = { show : function(){ this.mask.style.opacity = '.8'; }, hide : function(){ this.mask.style.opacity = '0'; }, remove : function(){ this.wrapper.removeChild(this.mask); }, setBackground : function( v ){ this.mask.style.background = v; }, setWidth : function( v ){ this.mask.style.width = v + 'px'; }, setHeight : function( v ){ this.mask.style.height = v + 'px'; }, addEventListener : function( eventname,handler,capture ){ this.mask.addEventListener(eventname,handler,capture); }, removeEventListener : function( eventname,handler,capture ){ this.mask.removeEventListener(eventname,handler,capture); } } /******************Content******************/ var content = function( wrapper ){ var _this = this; _this.container = document.createElement('div'); _this.wrapper = wrapper; _this.container.setAttribute( "style","position:absolute;"+ "background:white;"+ "opacity:1;"+ "z-index:100000;"+ //"-webkit-box-shadow:0px 0px 8px #333;"+ "-webkit-border-radius:15px;"+/*最大边角*/ "-webkit-transform:scale(0);"+ "-webkit-transform-origin:50% 50%;"+ "-webkit-transition-property:-webkit-transform,width,height;"+ "-webkit-transition-duration:300ms,700ms,700ms;"+ "-webkit-transition-delay:0ms,800ms,800ms;"+ "-webkit-user-select:none;"); var close = document.createElement("a"); close.setAttribute('style',"z-index:999999;display:block;position:absolute;width:29px;height:29px;overflow:hidden;display:none;-webkit-transition-property:opacity;-webkit-transition-duration:800ms;") close.setAttribute('href','javascirpt:;'); _this.close = close; _this.container.appendChild(_this.close); _this.wrapper.appendChild(_this.container); } content.prototype = { show : function(){ this.container.style.webkitTransform = "scale(1)"; }, hide : function(){ this.container.style.opacity = "0"; }, remove : function(){ this.wrapper.removeChild(this.container); }, setX : function(v){ this.container.style.left = v+"px"; }, setY : function(v){ this.container.style.top = v+"px"; }, setWidth : function(v){ this.container.style.width = v+"px"; }, setHeight : function(v){ this.container.style.height = v+"px"; }, addEventListener : function( eventname,handler,capture ){ this.container.addEventListener(eventname,handler,capture); }, getCloseBtn:function(){ return this.close; }, setContent: function(v){ if( v && v.nodeName ){ this.container.appendChild(v); }else{ alert('set dialog content failed.'); } } }; /******************Dialog******************/ var dialog = function( el,opts ){ var _this = this; el = el || document.body; _this.uid = ++uid; _this.baseElement = ( typeof el == 'object' && el.nodeName ) ? el : document.getElementById(el); _this.options = { modal : false, contentdom : document.createElement("div"), } if( "modal" in opts ){ _this.options.modal = opts.modal; } if( "contentdom" in opts ){ _this.options.contentdom = opts.contentdom; } _this.dPaper = new paper(_this.baseElement); _this.dContent = new content(_this.baseElement); _this.dContent.setContent(_this.options.contentdom); _this.update(); _this.dContent.getCloseBtn().onclick = function(){ _this.dispose(); } _this.dPaper.addEventListener("mouseup",_this,false); } dialog.prototype = { handleEvent : function(e){ switch(e.type){ case "mouseup": e.stopPropagation(); if(!!!this.options.modal){ this.dispose(); } break; } }, getCloseBtn : function(){ return this.dContent.getCloseBtn(); }, update : function(){ //content相对paper居中 var paperWidth = this.dPaper.mask.clientWidth, paperHeight = this.dPaper.mask.clientHeight, contentWidth = this.dContent.container.clientWidth, contentHeight = this.dContent.container.clientHeight; var r1 = paperWidth - 200; this.dPaper.setBackground("-webkit-gradient(radial, center center, "+ 0 +",center center, "+ r1 +", from(rgba(0,0,0,0)),color-stop(25%,rgba(0,0,0,.3)),to(rgba(0,0,0,1)))"); this.dContent.getCloseBtn().style.left=contentWidth-32/2+"px"; this.dContent.getCloseBtn().style.top=-24/2+"px"; this.dContent.setX((paperWidth-contentWidth)/2); this.dContent.setY((paperHeight-contentHeight)/2); }, show : function(){ var _this = this; setTimeout(function(){//动画效果必须放在timeout中,原因未知 _this.dPaper.show(); _this.dContent.show(); },0); }, dispose : function(){ var _this = this; this.dPaper.hide(); this.dContent.hide(); this.dPaper.addEventListener("webkitTransitionEnd",function(e){ _this.dPaper.remove(); _this.dPaper.removeEventListener("mouseup",_this,false); },false); this.dContent.addEventListener("webkitTransitionEnd",function(e){ _this.dContent.remove(); },false); } } window.dialog = dialog; })();
JavaScript
(function ($) { $.extend($.fx.step, { backgroundPosition: function (fx) { if (fx.state === 0 && typeof fx.end == 'string') { var start = $.curCSS(fx.elem, 'backgroundPosition'); start = toArray(start); fx.start = [start[0], start[2]]; var end = toArray(fx.end); fx.end = [end[0], end[2]]; fx.unit = [end[1], end[3]]; } var nowPosX = []; nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0]; nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1]; fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1]; function toArray(strg) { strg = strg.replace(/left|top/g, '0px'); strg = strg.replace(/right|bottom/g, '100%'); strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2"); var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/); return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]]; } } }); })(jQuery);
JavaScript
 games.game5 = { //breakout init: function () { $("#gamezone").html("<p style='font-size:18pt;padding:30px;'><strong style='font-size:20pt;'>Snowball Breakout</strong><br/>Use <span style='color:#939'>left</span> and <span style='color:#393'>right</span> to control the paddle</p><canvas id='game5-breakout' width='400' height='400' style='border:1px solid #000;margin:150px 50px;float:right;'></canvas>"); this.breakout($("#game5-breakout"), 400, 400); }, breakout: function (element, h, w) { engine = { h: 0, w: 0, gameBoard: undefined, keysDown: new Array(), engineloop: undefined, keyloop: undefined, init: function (gameBoard, h, w) { this.gameBoard = gameBoard; this.h = h; this.w = w; var that = this; this.world.init(that, this.h, this.w, function () { clearInterval(that.engineloop); clearInterval(that.keyloop); }); document.onkeydown = function (e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; return that.handleKeyDown(KeyID); } document.onkeyup = function (e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; return that.handleKeyUp(KeyID); } alert("are you ready... left and right"); this.engineloop = setInterval(function () { that.tick(); }, 1); this.keyloop = setInterval(function () { that.handleKeys(); }, 1); }, handleKeys: function () { if (this.keysDown[39]) { //right this.world.internalPlayer.moveRight(); } if (this.keysDown[37]) { //left this.world.internalPlayer.moveLeft(); } if (!(this.keysDown[39] & this.keysDown[37])) { } }, handleKeyUp: function (keyId) { this.keysDown[keyId] = false; return !(keyId == 37 | keyId == 39); }, handleKeyDown: function (keyId) { this.keysDown[keyId] = true; return !(keyId == 37 | keyId == 39); }, player: { x: 0, y: 390, h: 10, w: 100, color: '#000', max: 0, min: 0, speed: 2, moveRight: function () { this.x = this.x + this.w > this.max ? this.x : this.x + this.speed; }, moveLeft: function () { this.x = this.x < this.min ? this.x : this.x - this.speed; }, render: function (ctx) { ctx.fillStyle = this.color; // blue ctx.strokeStyle = '#000'; // red ctx.fillRect(this.x, this.y, this.w, this.h); ctx.fillRect(this.x, this.y, this.w, this.h); } }, target: function (x, y, h, w, row) { this.x = x; this.y = y; this.h = h; this.w = w; this.destroy = false; this.getRowColour = function (row) { switch (row) { case 0: return '#f00'; case 1: return '#ff0'; case 2: return '#0f0'; case 3: return '#0ff'; case 4: return '#00f'; case 5: return '#fff'; case 6: return '#000'; case 7: return '#f00'; case 8: return '#ff0'; case 9: return '#0f0'; case 10: return '#0ff'; case 11: return '#00f'; case 12: return '#fff'; case 13: return '#000'; default: return '#ccc'; } } this.color = this.getRowColour(row); this.render = function (ctx) { if (this.destroy) { return; } ctx.fillStyle = this.color; // blue ctx.strokeStyle = '#000'; // red ctx.fillRect(this.x, this.y, this.w, this.h); ctx.strokeRect(this.x, this.y, this.w, this.h); } }, ball: { x: 0, y: 0, h: 10, w: 10, angle: 0, color: '#fff', max: 0, min: 0, xinc: false, yinc: false, speed: 2, adjust: function () { var xDiff = Math.sin(this.angle * Math.PI / 180) * this.speed; var yDiff = Math.cos(this.angle * Math.PI / 180) * this.speed; this.x = this.xinc ? this.x + xDiff : this.x - xDiff; this.y = this.yinc ? this.y + yDiff : this.y - yDiff; }, render: function (ctx) { ctx.strokeStyle = '#000'; // red ctx.fillStyle = this.color; // blue ctx.beginPath(); ctx.arc(this.x, this.y, this.w, 0, Math.PI * 2, true); ctx.stroke(); ctx.fill(); ctx.closePath(); } }, world: { internalPlayer: undefined, internalBall: undefined, internalBlocks: [], h: 0, w: 0, killCallback: undefined, init: function (that, h, w, killCallback) { for (var i = 0; i < 6; i++) { //y for (var k = 0; k < 6; k++) { //x var spaceBetweenBlocks = 10; var target = new that.target(k * 10 + k * spaceBetweenBlocks + k * 50, i * 10, 5, 50, i); this.internalBlocks[this.internalBlocks.length] = target; } } this.internalPlayer = that.player; this.internalBall = that.ball; this.internalPlayer.max = h; this.internalPlayer.min = 0; this.internalBall.max = h; this.internalBall.min = 0; this.h = h; this.w = w; this.internalBall.y = games.helper.getRandomNumber(h / 4, (h / 4) * 3); this.internalBall.x = games.helper.getRandomNumber(h / 4, (h / 4) * 3); this.killCallback = killCallback; }, render: function (ctx) { this.internalPlayer.render(ctx); this.internalBall.render(ctx); var destroyed = 0; for (var i = 0; i < this.internalBlocks.length; i++) { destroyed += !this.internalBlocks[i].destroy ? 1 : 0; this.internalBlocks[i].render(ctx); } if (destroyed == 0) { if (this.killCallback != undefined) { this.killCallback(); } alert("Wll done! you won!"); } }, adjust: function () { this.internalBall.adjust(); /*## collision detection algo starts here :( ##*/ //is ball inside the world? if (this.internalBall.x - this.internalBall.w < 0) { this.internalBall.xinc = true; } if (this.internalBall.y - this.internalBall.h < 0) { this.internalBall.yinc = true; } if (this.internalBall.x + this.internalBall.w > this.w) { this.internalBall.xinc = false; } if (this.internalBall.y + this.internalBall.h > this.h) { if (this.killCallback != undefined) { this.killCallback(); } alert("Uh oh, you died... but well done!"); } //has ball hit paddle if (this.internalBall.y + this.internalBall.h > this.internalPlayer.y) { if (this.internalBall.x > this.internalPlayer.x) { if (this.internalBall.x < this.internalPlayer.x + this.internalPlayer.w) { this.internalBall.yinc = false; var newAngle = (this.internalBall.x - this.internalPlayer.x) * 1.4 - 70; this.internalBall.xinc = newAngle > 0; this.internalBall.angle = newAngle < 0 ? newAngle * -1 : newAngle; } } } for (var i = 0; i < this.internalBlocks.length; i++) { var currentBlock = this.internalBlocks[i]; if (!currentBlock.destroy) { if (currentBlock.y < this.internalBall.y + this.internalBall.h) { if (currentBlock.y + currentBlock.h > this.internalBall.y - this.internalBall.h) { if (currentBlock.x < this.internalBall.x + this.internalBall.w) { if (currentBlock.x > this.internalBall.x - this.internalBall.w) { this.internalBall.xinc = false; currentBlock.destroy = true; } } if (currentBlock.x + currentBlock.w < this.internalBall.x + this.internalBall.w) { if (currentBlock.x + currentBlock.w > this.internalBall.x - this.internalBall.w) { this.internalBall.xinc = true; currentBlock.destroy = true; } } } } if (currentBlock.x < this.internalBall.x + this.internalBall.w) { if (currentBlock.x + currentBlock.w > this.internalBall.x - this.internalBall.w) { if (currentBlock.y < this.internalBall.y + this.internalBall.h) { if (currentBlock.y > this.internalBall.y - this.internalBall.h) { this.internalBall.yinc = false; currentBlock.destroy = true; } } if (currentBlock.y + currentBlock.h < this.internalBall.y + this.internalBall.h) { if (currentBlock.y + currentBlock.h > this.internalBall.y - this.internalBall.h) { this.internalBall.yinc = true; currentBlock.destroy = true; } } } } } } } }, tick: function () { this.gameBoard.clearRect(0, 0, 400, 400); this.world.render(this.gameBoard); this.world.adjust(); } } gameBoard = element[0].getContext('2d'); engine.init(gameBoard, h, w); } };
JavaScript
 games.game6 = { firstChosenCard: undefined, secondChosenCard: undefined, matches: 0, init: function () { games.game6.firstChosenCard = undefined; games.game6.secondChosenCard = undefined; games.game6.matches = 0; var grid = "0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7".split(","); this.randomiseArray(grid); var html = "<ul id='game6-pairs'>"; for (var i = 0; i < grid.length; i++) { html += "<li><a href='#' class='card" + grid[i] + "' id='game6-pairs-card" + i + "'>&nbsp;</li>"; } html += "</ul>"; $("#gamezone").html(html); $("#gamezone ul#game6-pairs li a").click(function () { $(this).css("background-image", "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/" + $(this).attr("class") + ".jpg)"); if (games.game6.firstChosenCard == undefined) { games.game6.firstChosenCard = $(this); } else if (games.game6.secondChosenCard == undefined) { games.game6.secondChosenCard = $(this); if (games.game6.firstChosenCard.attr("class") == games.game6.secondChosenCard.attr("class") && games.game6.firstChosenCard.attr("id") != games.game6.secondChosenCard.attr("id")) { games.game6.firstChosenCard.unbind('click'); games.game6.secondChosenCard.unbind('click'); games.game6.firstChosenCard = undefined; games.game6.secondChosenCard = undefined; games.game6.matches++; if (games.game6.matches == 32) { alert("YAY!!!! you did it! Come back tomorow for another game! Or click the date again at the top to reset"); } } else { setTimeout(function () { var resetBackground = "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/back-of-card.png)"; games.game6.firstChosenCard.css("background-image", resetBackground); games.game6.secondChosenCard.css("background-image", resetBackground); games.game6.firstChosenCard = undefined; games.game6.secondChosenCard = undefined; }, 500); } } }); }, randomiseArray: function (myArray) { var i = myArray.length; if (i == 0) return false; while (--i) { var j = Math.floor(Math.random() * (i + 1)); var tempi = myArray[i]; var tempj = myArray[j]; myArray[i] = tempj; myArray[j] = tempi; } } };
JavaScript
 games.game8 = { //hangman words: "paris,newyork,london,frankfurt,harjit,dilshini,may,february,september,germany,paddington,plumstead,ealing,georgia,jackson,starbucks".split(","), currentWord: "", usedLetters: "", guesses: 0, errors: 0, init: function () { this.playRound(); $(document).keyup(function (event) { var alphaKey = String.fromCharCode(event.keyCode).toLowerCase(); if ("abcdefghijklmnopqrstuvwxyz".indexOf(alphaKey) > -1) { if (games.game8.usedLetters.indexOf(alphaKey) < 0) { games.game8.guesses++; games.game8.usedLetters += alphaKey; $("#game8-hangman span span").each(function () { var thisLetter = $(this).text(); if (thisLetter == alphaKey) { $(this).css("visibility", "visible"); } }); if (games.game8.currentWord.indexOf(alphaKey) < 0) { games.game8.errors++; } var remaining = 0; $("#game8-hangman span span").each(function () { remaining = remaining + ($(this).css("visibility") == "hidden" ? 1 : 0); }); if (remaining == 0) { alert("well done, selecting another word"); games.game8.playRound(); } if (games.game8.errors >= 10) { alert("You loose, the word was..." + games.game8.currentWord + ". Never mind, play again!"); games.game8.playRound(); } var livesBox = ""; for (var i = 0; i < games.game8.guesses - (games.game8.currentWord.length - remaining); i++) { livesBox += " X"; } $("#game8-hangman .lives").text(livesBox); $("#game8-hangman .guesses").text(games.game8.usedLetters); } } }); }, playRound: function () { games.game8.usedLetters = ""; games.game8.guesses = 0; games.game8.errors = 0; games.game8.currentWord = games.game3.words[games.helper.getRandomNumber(0, games.game3.words.length)]; var html = ""; html += "<div id='game8-hangman'><h1>Hang Man</h1>"; for (var i = 0; i < games.game8.currentWord.length; i++) { html += "<span><span style='visibility:hidden'>{0}</span></span>".replace("{0}", games.game8.currentWord[i]); } html += "<div class='lives'></div>"; html += "<div class='guesses'></div>"; html += "</div>"; $("#gamezone").html(html); } };
JavaScript
games.game10 = { //asteroid init: function () { $("#gamezone").html('<table align="center" id="game10-asteroid"><tr><td align="center"><h4>[^]feed deer | [<]anti-clock | [>]clock-wise | [V]dead stop | [SPACE]drop | [c]steermode | [q]weapons</h4></td></tr><tr><td align="center" valign="middle"><canvas id="game10-asteroid-canvas" width="750" height="700"></canvas></td></tr></table>'); Asteroid("game10-asteroid-canvas"); } };
JavaScript
var todaysDate = 25; todaysDate = (new Date()).getDate(); todaysDate = todaysDate >= 25 ? 24 : todaysDate; var kn = new Konami(); kn.code = function() { alert("unlocked all days"); todaysDate = 24; games.gamezone.bind(); }; kn.load() $(document).ready(function () { games.gamezone.bind(); });
JavaScript
games.game7 = { //snakes and ladders //Render big 10x10 table init: function () { var html = "<table id='game7-snakes-ladders'>"; html += "<tr><td colspan='10'><h1>Roll Dice</h1><div class='dice-value'>?</div><div class='piece-holder'></div></td></td>"; for (var i = 9; i >= 0; i--) { html += "<tr>"; var maxNo = 0; for (var k = 9; k >= 0; k--) { var rowVal = (i * 10) + (k == 10 ? 0 : k) + 1; maxNo = rowVal % 10 == 0 ? rowVal : maxNo; rowVal = i % 2 == 0 ? ((rowVal * (-1)) + (-9) + (maxNo * 2)) : rowVal; html += "<td class='cell{0}'>&nbsp;</td>".replace("{0}", rowVal); } html += "</tr>"; } html += "</table>"; $("#gamezone").html(html); $(".piece-holder").append($("<img src='http://12-games-of-christmas.googlecode.com/svn/trunk/assets/player1.png' style='float:left;' class='player'/>")); $(".piece-holder").append($("<img src='http://12-games-of-christmas.googlecode.com/svn/trunk/assets/player2.png' style='float:left;' class='npc'/>")); $("#game7-snakes-ladders h1").click(function () { if (games.game7.userLockOut) return; games.game7.userLockOut = true; var diceValue = games.game7.rollDice(); games.game7.player[1] += diceValue; games.game7.movePiece(); setTimeout(function () { games.game7.npcRoll(); }, diceValue * 300); }); }, userLockOut: false, npcRoll: function () { games.game7.npc[1] += games.game7.rollDice(); games.game7.movePiece(); games.game7.userLockOut = false; }, rollDice: function () { games.game7.diceValue = games.helper.getRandomNumber(1, 6); $("#game7-snakes-ladders .dice-value").text(games.game7.diceValue); return games.game7.diceValue; }, isPlayersGo: true, moveTicker: undefined, diceValue: 0, player: [1, 1], npc: [1, 1], isActionCell: function (cellNo, element, playerCoords) { cellNo--; switch (cellNo) { case 1: //promote to 38 $(".cell{0}".replace("{0}", 38)).append(element); playerCoords[0] = 38; playerCoords[1] = 38; break; case 4: //promote to 14 $(".cell{0}".replace("{0}", 14)).append(element); playerCoords[0] = 14; playerCoords[1] = 14; break; case 9: //promote to 31 $(".cell{0}".replace("{0}", 31)).append(element); playerCoords[0] = 31; playerCoords[1] = 31; break; case 28: //promote to 84 $(".cell{0}".replace("{0}", 84)).append(element); playerCoords[0] = 84; playerCoords[1] = 84; break; case 21: //promote to 42 $(".cell{0}".replace("{0}", 42)).append(element); playerCoords[0] = 42; playerCoords[1] = 42; break; case 51: //promote to 67 $(".cell{0}".replace("{0}", 67)).append(element); playerCoords[0] = 67; playerCoords[1] = 67; break; case 71: //promote to 91 $(".cell{0}".replace("{0}", 91)).append(element); playerCoords[0] = 91; playerCoords[1] = 91; break; case 80: //promote to 100 $(".cell{0}".replace("{0}", 100)).append(element); playerCoords[0] = 100; playerCoords[1] = 100; break; case 17: //relegate to 38 $(".cell{0}".replace("{0}", 7)).append(element); playerCoords[0] = 7; playerCoords[1] = 7; break; case 62: //relegate to 14 $(".cell{0}".replace("{0}", 19)).append(element); playerCoords[0] = 19; playerCoords[1] = 19; break; case 87: //relegate to 31 $(".cell{0}".replace("{0}", 24)).append(element); playerCoords[0] = 24; playerCoords[1] = 24; break; case 54: //relegate to 84 $(".cell{0}".replace("{0}", 34)).append(element); playerCoords[0] = 34; playerCoords[1] = 34; break; case 64: //relegate to 42 $(".cell{0}".replace("{0}", 60)).append(element); playerCoords[0] = 60; playerCoords[1] = 60; break; case 93: //relegate to 67 $(".cell{0}".replace("{0}", 73)).append(element); playerCoords[0] = 73; playerCoords[1] = 73; break; case 95: //relegate to 91 $(".cell{0}".replace("{0}", 75)).append(element); playerCoords[0] = 75; playerCoords[1] = 75; break; case 98: //relegate to 100 $(".cell{0}".replace("{0}", 79)).append(element); playerCoords[0] = 79; playerCoords[1] = 79; break; } }, movePiece: function () { games.game7.moveTicker = setInterval(function () { if (games.game7.isPlayersGo) { if (games.game7.player[0] == games.game7.player[1]) { clearInterval(games.game7.moveTicker); games.game7.isActionCell(games.game7.player[0], $("#game7-snakes-ladders .player"), games.game7.player); if (games.game7.player[0] == 100) { setInterval(function () { clearInterval(games.game7.moveTicker); }, 1); alert("You WON!!!!! Come back tomorow for some more."); } games.game7.isPlayersGo = false; } else { $(".cell{0}".replace("{0}", games.game7.player[0]++)).append($("#game7-snakes-ladders .player")); games.game7.player[0] = games.game7.player[0] == 100 ? 100 : games.game7.player[0]; games.game7.player[1] = games.game7.player[1] == 100 ? 100 : games.game7.player[1]; } } else { if (games.game7.npc[0] == games.game7.npc[1]) { setInterval(function () { clearInterval(games.game7.moveTicker); }, 1); games.game7.isActionCell(games.game7.npc[0], $("#game7-snakes-ladders .npc"), games.game7.npc); if (games.game7.npc[0] == 100) { setInterval(function () { clearInterval(games.game7.moveTicker); }, 1); alert("You loose, why not try again."); } games.game7.isPlayersGo = true; } else { $(".cell{0}".replace("{0}", games.game7.npc[0]++)).append($("#game7-snakes-ladders .npc")); games.game7.npc[0] = games.game7.npc[0] == 100 ? 100 : games.game7.npc[0]; games.game7.npc[1] = games.game7.npc[1] == 100 ? 100 : games.game7.npc[1]; } } }, 250); } };
JavaScript
function Asteroid(boardIdin, scrCallBack) { function GameLoader(boardId) { var canvas = document.getElementById(boardId); var ctx = canvas.getContext("2d"); this.ScoreCallBack = scrCallBack; this.boardX = 750; this.boardY = 700; this.levelUp = true; this.level = 0; this.rocks = new Array(); this.noRocks = 0; this.score = 0; this.RenderHud = function() { ctx.fillStyle = "rgb(128,128,32)"; ctx.font = "20pt Arial"; ctx.fillText("Level: " + this.level, 50, 25); ctx.fillText("Lives: " + this.Ship.life, 180, 25); ctx.fillText("Score: " + this.score, 310, 25); if (this.Ship.maxNukes > 0) { ctx.fillText("Nukes: " + this.Ship.maxNukes, 440, 25); } ctx.fillText("Weapons mode:", 50, 50); ctx.fillText(this.Ship.getWeaponsType(), 300, 50); ctx.fillText("Steering mode:", 50, 75); ctx.fillText(this.Ship.getSteeringType(), 300, 75); //ctx.font = "20pt Arial"; + this.Ship.fireType //ctx.fillText(("Score: " + this.score), 0, 30); } this.Ship = new function() { //starboard = right, port = left this.steeringType = 1; this.bullets = new Array(); this.noBullets = 0; this.shipLength = 50; this.shipWidth = 30; this.bowDeg = 0; this.thrustDeg = 0; this.shipX = 350; this.shipY = 400; this.shipDeg = 0; this.thrust = 0; this.rotation = 0; this.life = 3; this.fireType = 0; this.maxNukes = 0; this.die = function() { this.shipX = window.GameLoaderAsteroid.boardX / 2; this.shipY = window.GameLoaderAsteroid.boardY / 2; this.dead = true; this.thrust = 0; this.bowDeg = 0; this.life--; } this.getWeaponsType = function() { switch (this.fireType) { case 0: return "Canon"; case 1: return "Mine"; case 2: return "Laser"; case 3: return "Nuke"; } } this.getSteeringType = function() { switch (this.steeringType) { case 0: return "Zero-G"; case 1: return "Classic"; } } this.toggleArms = function(intlevel) { this.fireType++; document.title = intlevel; if (intlevel > 9) { this.fireType = this.fireType > 3 ? 0 : this.fireType; //nuke (unlimited) } else if (intlevel > 6) { this.fireType = this.fireType > 2 ? 0 : this.fireType; //laser (unlimited) } else if (intlevel > 3) { this.fireType = this.fireType > 1 ? 0 : this.fireType; //mine (unlimited) } else { this.fireType = 0; //canon (unlimited) } } this.draw = function() { if ((this.shipX < 0 | this.shipX > window.GameLoaderAsteroid.boardX) | (this.shipY < 0 | this.shipY > window.GameLoaderAsteroid.boardY)) { if (this.shipX < 0) { this.shipX = window.GameLoaderAsteroid.boardX; } if (this.shipX > window.GameLoaderAsteroid.boardX) { this.shipX = 0; } if (this.shipY < 0) { this.shipY = window.GameLoaderAsteroid.boardY; } if (this.shipY > window.GameLoaderAsteroid.boardY) { this.shipY = 0; } } this.shipDeg += this.rotation; this.thrust = this.thrust > 20 ? 20 : this.thrust; this.thrust = this.thrust < 0 ? 0 : this.thrust; var steerDegree = 0; switch (this.steeringType) { case 0: this.shipX = this.shipX + Math.sin(this.thrustDeg * Math.PI / 180) * this.thrust; this.shipY = this.shipY - Math.cos(this.thrustDeg * Math.PI / 180) * this.thrust; break; case 1: this.shipX = this.shipX + Math.sin(this.shipDeg * Math.PI / 180) * this.thrust; this.shipY = this.shipY - Math.cos(this.shipDeg * Math.PI / 180) * this.thrust; break; } var bowX = Math.sin(this.shipDeg * Math.PI / 180) * (this.shipLength / 2) + (this.shipX); var bowY = this.shipY - Math.cos(this.shipDeg * Math.PI / 180) * (this.shipWidth / 2); var shipimage = new Image(); shipimage.src = 'http://12-games-of-christmas.googlecode.com/svn/trunk/assets/ship.gif'; ctx.translate(bowX, bowY); ctx.rotate(this.shipDeg * Math.PI / 180); ctx.drawImage(shipimage, (-this.shipWidth / 2), (-this.shipLength / 2), this.shipWidth, this.shipLength); ctx.rotate(-this.shipDeg * Math.PI / 180); ctx.translate(-bowX, -bowY); document.title = ""; for (var i = 0; i < this.noBullets; i++) { if (this.bullets[i].inAction == true) { ctx.fillStyle = "rgb(200,0,0)"; this.bullets[i].draw(); } } }; this.fire = function() { this.bullets[this.noBullets] = new function() { this.type = window.GameLoaderAsteroid.Ship.fireType; this.range = 10; this.inAction = true; this.bulletHeading = window.GameLoaderAsteroid.Ship.shipDeg; this.baseX = window.GameLoaderAsteroid.Ship.shipX; this.baseY = window.GameLoaderAsteroid.Ship.shipY; this.boxX = window.GameLoaderAsteroid.Ship.shipX; this.boxY = window.GameLoaderAsteroid.Ship.shipY; this.w = 0; this.h = 0; this.checkColision = function(x, y, w, h) { var colided = false; switch (this.type) { case 0: case 1: case 3: //boxes if (x > this.boxX & x < this.boxX + this.w) { if (y > this.boxY & y < this.boxY + this.h) { colided = true; } } if (this.boxX > x & this.boxX < x + w) { if (this.boxY > y & this.boxY < y + h) { colided = true; } } break; case 2: //lasers for (var i = 0; i < this.range; i++) { var laserTestX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * i; var laserTestY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * i; if (x < laserTestX & (x + w) > laserTestX) { if (y < laserTestY & (y + h) > laserTestY) { colided = true; } } } break; } if (colided & this.type != 3) { this.inAction = false; } return colided; } this.draw = function() { switch (this.type) { case 0: //canon this.w = 5; this.h = 5; this.boxX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * this.range; this.boxY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * this.range; ctx.fillRect(this.boxX, this.boxY, this.w, this.h); break; case 1: //mine this.w = 10; this.h = 10; this.boxX = this.baseX; this.boxY = this.baseY; ctx.fillRect(this.boxX, this.boxY, this.w, this.h); break; case 2: //laser ctx.beginPath(); this.boxX = this.baseX + Math.sin(this.bulletHeading * Math.PI / 180) * this.range; this.boxY = this.baseY - Math.cos(this.bulletHeading * Math.PI / 180) * this.range; ctx.lineWidth = 2; ctx.moveTo(this.baseX, this.baseY); // give the (x,y) coordinates ctx.lineTo(this.boxX, this.boxY); ctx.lineTo(this.baseX, this.baseY); ctx.strokeStyle = "#f00"; ctx.stroke(); ctx.closePath(); break; case 3: //nuke this.w = window.GameLoaderAsteroid.boardX; this.h = window.GameLoaderAsteroid.boardY; this.boxX = 0; this.boxY = 0; ctx.fillStyle = "rgba(200,0,0," + (this.range / 300) + ")"; ctx.fillRect(this.boxX, this.boxY, this.w, this.h); this.range += 40; break; } this.range += 10; if (this.range > 300) { this.inAction = false; } } } this.noBullets++; }; }; this.tick = function() { window.GameLoaderAsteroid.tickCounter++; if (window.GameLoaderAsteroid.Ship.dead == true) { if (window.GameLoaderAsteroid.Ship.life == 0) { ctx.fillStyle = "rgb(128,128,32)"; ctx.font = "40pt Arial"; ctx.fillText("Game Over", this.boardX / 2, this.boardY / 2); ctx.font = "20pt Arial"; ctx.fillText(("Score - " + this.score), this.boardX / 2, this.boardY / 2 + 30); return; } ctx.clearRect(0, 0, this.boardX, this.boardY); window.GameLoaderAsteroid.Ship.dead = false; ctx.fillStyle = "rgb(128,128,32)"; ctx.font = "40pt Arial"; ctx.fillText("Lost a life", this.boardX / 2, this.boardY / 2); ctx.fillText("Get Ready", this.boardX / 2, this.boardY / 2 + 50); setTimeout("window.GameLoaderAsteroid.tick()", 1000); return; } if (this.levelUp) { this.noBullets = 0; if(this.level%10 ==0){ window.GameLoaderAsteroid.Ship.life++; window.GameLoaderAsteroid.Ship.maxNukes++; } window.GameLoaderAsteroid.Ship.maxNukes = this.level - 8; this.level++; this.levelUp = false; this.noRocks = this.level * 1; for (var i = 0; i < this.noRocks; i++) { this.rocks[i] = new function() { this.rockHeading = Math.floor(Math.random() * 361); this.rockDistance = Math.floor(Math.random() * 200) + 50; this.baseX = Math.floor(Math.random() * window.GameLoaderAsteroid.boardX); this.baseY = Math.floor(Math.random() * window.GameLoaderAsteroid.boardY); this.rockX = this.baseX + Math.sin(this.rockHeading * Math.PI / 180) * this.rockDistance; this.rockY = this.baseY - Math.cos(this.rockHeading * Math.PI / 180) * this.rockDistance; this.width = 20+(window.GameLoaderAsteroid.level * 5); this.height = 20+(window.GameLoaderAsteroid.level * 5); this.destroyed = false; this.draw = function() { this.rockX = this.baseX + Math.sin(this.rockHeading * Math.PI / 180) * this.rockDistance; this.rockY = this.baseY - Math.cos(this.rockHeading * Math.PI / 180) * this.rockDistance; this.rockHeading += 5; var rockimage = new Image(); rockimage.src = 'http://12-games-of-christmas.googlecode.com/svn/trunk/assets/asteroid2.gif'; ctx.drawImage(rockimage, this.rockX, this.rockY, this.width, this.height); //ctx.fillRect(this.rockX, this.rockY, 30, 30); } } } ctx.fillStyle = "rgb(128,32,32)"; ctx.font = "20pt Arial"; ctx.fillText("Level: " + window.GameLoaderAsteroid.level, window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2); ctx.fillText("Get Ready", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 50); if (this.level == 4) { ctx.fillText("Upgrade weapons: mine", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 100); } else if (this.level == 1) { ctx.fillText("Upgrade weapons: canon", window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 100); } var bonus = ((30)*this.level)-window.GameLoaderAsteroid.tickCounter; if (bonus > 0){ window.GameLoaderAsteroid.score +=bonus; ctx.fillText("Time Bonus: "+bonus, window.GameLoaderAsteroid.boardX / 2, window.GameLoaderAsteroid.boardY / 2 + 150); } window.GameLoaderAsteroid.tickCounter = 0; setTimeout("window.GameLoaderAsteroid.tick()", 2000); return; } ctx.clearRect(0, 0, this.boardX, this.boardY); window.GameLoaderAsteroid.RenderHud(); for (var i = 0; i < this.noRocks; i++) { var rock = this.rocks[i]; var ship = window.GameLoaderAsteroid.Ship; if (rock.rockX < ship.shipX & (rock.rockX + rock.width) > ship.shipX) { if (rock.rockY < ship.shipY & (rock.rockY + rock.height) > ship.shipY) { if (!rock.destroyed) { rock.destroyed = true; ship.die(); setTimeout("window.GameLoaderAsteroid.tick()", 40); return; } } } if (!this.rocks[i].destroyed) { for (var j = 0; j < window.GameLoaderAsteroid.Ship.noBullets; j++) { if (window.GameLoaderAsteroid.Ship.bullets[j].inAction) { var blt = window.GameLoaderAsteroid.Ship.bullets[j]; if (blt.checkColision(rock.rockX, rock.rockY, rock.width, rock.height)) { rock.destroyed = true; this.score++; } } } } } var noRocksLeft = 0; for (var i = 0; i < this.noRocks; i++) { if (!this.rocks[i].destroyed) { ctx.fillStyle = "rgb(64,64,64)"; this.rocks[i].draw(); noRocksLeft++; } } this.levelUp = (noRocksLeft == 0); this.Ship.draw(); if (this.ScoreCallBack != undefined) { this.ScoreCallBack(this.level, this.score, window.GameLoaderAsteroid.Ship.life); } setTimeout("window.GameLoaderAsteroid.tick()", 100); }; canvas.onclick = function () { canvas.onclick = function () { }; this.style.backgroundImage = "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/space.jpg)"; document.onkeyup = function (e) { var charCode = this.KeyID = (window.event) ? event.keyCode : e.keyCode; switch (charCode) { case 32: if (!(window.GameLoaderAsteroid.Ship.maxNukes == 0 && window.GameLoaderAsteroid.Ship.fireType == 3)) { window.GameLoaderAsteroid.Ship.fire(); if (window.GameLoaderAsteroid.Ship.fireType == 3) { window.GameLoaderAsteroid.Ship.maxNukes--; } } break; case 81: window.GameLoaderAsteroid.Ship.toggleArms(window.GameLoaderAsteroid.level); if (window.GameLoaderAsteroid.Ship.maxNukes == 0) { if (window.GameLoaderAsteroid.Ship.fireType == 3) { window.GameLoaderAsteroid.Ship.fireType = 0; } } break; case 39: window.GameLoaderAsteroid.Ship.rotation = 0; break; case 37: window.GameLoaderAsteroid.Ship.rotation = 0; break; case 67: window.GameLoaderAsteroid.Ship.steeringType = window.GameLoaderAsteroid.Ship.steeringType == 0 ? 1 : 0; break; } if (charCode == 81 || charCode == 39 || charCode == 37 || charCode == 67 || charCode == 32) { return false; } }; document.onkeydown = function (e) { var charCode = this.KeyID = (window.event) ? event.keyCode : e.keyCode; switch (charCode) { case 39: window.GameLoaderAsteroid.Ship.rotation = 10; break; case 37: window.GameLoaderAsteroid.Ship.rotation = -10; break; case 38: if (window.GameLoaderAsteroid.Ship.thrustDeg != window.GameLoaderAsteroid.Ship.shipDeg) { window.GameLoaderAsteroid.Ship.thrust -= 5; } if (window.GameLoaderAsteroid.Ship.thrust < 1) { window.GameLoaderAsteroid.Ship.thrustDeg = window.GameLoaderAsteroid.Ship.shipDeg; } window.GameLoaderAsteroid.Ship.thrust += 3; break; case 40: window.GameLoaderAsteroid.Ship.thrust = 0; break; } if (charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40) { return false; } }; window.GameLoaderAsteroid.tick(); } } window.GameLoaderAsteroid = new GameLoader(boardIdin, scrCallBack); }
JavaScript
games.game2 = { played: new Array(), colors: "red,blue,green,yellow".split(","), clickIndex: 0, init: function () { var html = "<ul id='game2-pattern'>"; for (var i = 0; i < this.colors.length; i++) { html += "<li><a href='#' class='" + this.colors[i] + "'>&nbsp;</li>"; } html += "</ul>"; $("#gamezone").html(html); games.game2.clickIndex = 0; this.played = new Array(); setTimeout(function () { games.game2.playColours(); }, 1000); }, handlerUser: function () { games.game2.flashElement(0, $("#gamezone ul#game2-pattern li a." + $(this).attr("class")), false); if ($(this).attr("class") == games.game2.played[games.game2.clickIndex]) { games.game2.clickIndex++; if (games.game2.clickIndex == games.game2.played.length) { games.game2.clickIndex = 0; setTimeout(function () { games.game2.playColours(); }, 1000); } } else { alert("lost with a score of " + games.game2.played.length + ", resetting the game so you can try again. "); games.game2.init(); } }, playColours: function () { $("#gamezone ul#game2-pattern li a").unbind("click"); this.played[this.played.length] = this.colors[games.helper.getRandomNumber(0, 4)]; for (var i = 0; i < this.played.length; i++) { this.flashElement(i, $("#gamezone ul#game2-pattern li a." + this.played[i]), false); } this.flashElement(i + 1, $("<span>"), true); }, flashElement: function (timeout, element, enableClick) { setTimeout(function () { element.addClass("play"); setTimeout(function () { element.removeClass("play"); }, 150); if (enableClick) { $("#gamezone ul#game2-pattern li a").click(games.game2.handlerUser); } }, 500 * timeout); } };
JavaScript
 games.game12 = { //snakes init: function () { $("#gamezone").html("<p style='font-size:18pt;padding:30px;'><strong style='font-size:20pt;'>Snakes</strong><br/>Use <span style='color:#933'>up</span>, <span style='color:#939'>down</span>, <span style='color:#339'>left</span> and <span style='color:#393'>right</span> to control the paddle</p><canvas id='game12-snakes' width='400' height='400' style='border:1px solid #000;margin:50px 50px;float:right;'></canvas>"); this.breakout($("#game12-snakes"), 400, 400); }, breakout: function (element, h, w) { engine = { h: 0, w: 0, gameBoard: undefined, keysDown: new Array(), engineloop: undefined, keyloop: undefined, init: function (gameBoard, h, w) { this.gameBoard = gameBoard; this.h = h; this.w = w; var that = this; this.world.init(that, this.h, this.w, function () { clearInterval(that.engineloop); clearInterval(that.keyloop); }); document.onkeydown = function (e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; return that.handleKeyDown(KeyID); } document.onkeyup = function (e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; return that.handleKeyUp(KeyID); } alert("are you ready... left and right"); this.engineloop = setInterval(function () { that.tick(); }, 100); this.keyloop = setInterval(function () { that.handleKeys(); }, 1); }, handleKeys: function () { if (this.keysDown[39]) { this.world.internalPlayer.moveRight(); } if (this.keysDown[37]) { this.world.internalPlayer.moveLeft(); } if (this.keysDown[40]) { this.world.internalPlayer.moveDown(); } if (this.keysDown[38]) { this.world.internalPlayer.moveUp(); } }, handleKeyUp: function (keyId) { this.keysDown[keyId] = false; return !(keyId == 37 | keyId == 39 | keyId == 38 | keyId == 40); }, handleKeyDown: function (keyId) { this.keysDown[keyId] = true; return !(keyId == 37 | keyId == 39 | keyId == 38 | keyId == 40); }, player: { limbs: [{ x: 0, y: 390, color: '#fff'}], x: 0, y: 390, h: 10, w: 10, l: 5, max: 0, min: 0, speed: 2, facing: 'e', score: 0, moveRight: function () { this.facing = this.facing == 'w' ? 'w' : 'e'; }, moveLeft: function () { this.facing = this.facing == 'e' ? 'e' : 'w'; }, moveUp: function () { this.facing = this.facing == 's' ? 's' : 'n'; }, moveDown: function () { this.facing = this.facing == 'n' ? 'n' : 's'; }, grow: function (growBy, newx, newy) { var letters = '0369cf'.split(''); var color = '#'; for (var i = 0; i < 3; i++) { color += letters[Math.round(Math.random() * 6)]; } this.limbs[this.limbs.length] = { x: newx, y: newy, color: color }; }, render: function (ctx) { ctx.fillStyle = '#000'; ctx.font = "bold 150px sans-serif"; ctx.fillText(this.score, 150, 225); ctx.strokeColor = '#000'; for (l in this.limbs) { ctx.fillStyle = this.limbs[l].color; ctx.fillRect(this.limbs[l].x, this.limbs[l].y, this.w, this.h); ctx.strokeRect(this.limbs[l].x, this.limbs[l].y, this.w, this.h); } } }, target: { x: undefined, y: undefined, h: 10, w: 10, init: function (x, y) { this.x = x; this.y = y; }, color: '#f00', render: function (ctx) { if (this.x == undefined && this.y == undefined) { return; } ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.w, this.h); } }, world: { internalPlayer: undefined, internalApple: undefined, h: 0, w: 0, killCallback: undefined, init: function (that, h, w, killCallback) { this.h = h; this.w = w; this.killCallback = killCallback; this.internalPlayer = that.player; this.internalApple = that.target; this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10); this.internalPlayer.max = h; this.internalPlayer.min = 0; }, render: function (ctx) { ctx.clearRect(0, 0, this.h, this.w); this.internalPlayer.render(ctx); this.internalApple.render(ctx); }, adjust: function () { var tailx = this.internalPlayer.limbs[this.internalPlayer.limbs.length - 1].x; var taily = this.internalPlayer.limbs[this.internalPlayer.limbs.length - 1].y; var headx = this.internalPlayer.limbs[0].x; var heady = this.internalPlayer.limbs[0].y; switch (this.internalPlayer.facing) { case 'n': this.internalPlayer.limbs[0].y -= this.internalPlayer.h; break; case 's': this.internalPlayer.limbs[0].y += this.internalPlayer.h; break; case 'e': this.internalPlayer.limbs[0].x += this.internalPlayer.w; break; case 'w': this.internalPlayer.limbs[0].x -= this.internalPlayer.w; break; } for (var i = 1; i < this.internalPlayer.limbs.length; i++) { var headxtemp = this.internalPlayer.limbs[i].x; var headytemp = this.internalPlayer.limbs[i].y; if (headxtemp == this.internalApple.x && headytemp == this.internalApple.y) { this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10); this.internalPlayer.l += 4; } if (this.internalPlayer.limbs[0].x == headxtemp && this.internalPlayer.limbs[0].y == headytemp && i > 2) { if (this.killCallback != undefined) { this.killCallback(); } alert("Uh oh, you died!"); return false; } this.internalPlayer.limbs[i].x = headx; this.internalPlayer.limbs[i].y = heady; headx = headxtemp; heady = headytemp; } if (this.internalPlayer.limbs[0].x == this.internalApple.x && this.internalPlayer.limbs[0].y == this.internalApple.y) { this.internalApple.init(games.helper.getRandomNumber(0, this.w / 10) * 10, games.helper.getRandomNumber(0, this.h / 10) * 10); this.internalPlayer.l += 4; this.internalPlayer.score++; } if (this.internalPlayer.l > 0) { this.internalPlayer.l--; this.internalPlayer.grow(1, tailx, taily); } if (this.internalPlayer.limbs[0].x > this.w - this.internalPlayer.w || this.internalPlayer.limbs[0].y > this.h - this.internalPlayer.h || this.internalPlayer.limbs[0].x < 0 || this.internalPlayer.limbs[0].y < 0) { if (this.killCallback != undefined) { this.killCallback(); } alert("Uh oh, you died!"); return false; } return true; } }, tick: function () { if (this.world.adjust()) this.world.render(this.gameBoard); } } gameBoard = element[0].getContext('2d'); engine.init(gameBoard, h, w); } };
JavaScript
 games.game4 = { //bomberman worldmap: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], renderloop: undefined, npcRenderLoop: undefined, npcThinkLoop: undefined, stopGame: function () { window.clearInterval(this.renderloop); window.clearInterval(this.npcRenderLoop); window.clearInterval(this.npcThinkLoop); }, init: function () { var html = ""; html += "<table id='game4-bomberman'>"; html += "<tr><td colspan='30'>you are the red box, up, down, left, right to move. x to lay a mine, and x again to blow the mine.</td></tr>"; for (var i = 0; i < this.worldmap.length; i++) { var worldmapRow = this.worldmap[i]; html += "<tr class='row{0}'>".replace("{0}", i); for (var k = 0; k < worldmapRow.length; k++) { var worldmapCol = worldmapRow[k]; html += "<td class='col{1} {0}'>&nbsp;</td>".replace("{1}", k).replace("{0}", (worldmapCol == 0 ? "wall" : worldmapCol == 1 ? "floor" : "obstacle")); } html += "</tr>"; } html += "</table>"; $("#gamezone").html(html); $(document).keyup(function (event) { games.game4.player.handleKey(event.keyCode, true); games.game4.player.handleKey(event.keyCode, false); return false; }); this.renderloop = setInterval(function () { games.game4.player.draw($("#game4-bomberman")); $("#game4-bomberman .npc").removeClass("npc"); for (var i = 0; i < games.game4.npcs.length; i++) { if (i < games.game4.npcs.length) { var coords = games.game4.npcs[i]; games.game4.npc.draw(coords); } } }, 10); this.npcThinkLoop = setInterval(function () { for (var i = 0; i < games.game4.npcs.length; i++) { if (i < games.game4.npcs.length) { var coords = games.game4.npcs[i]; if (coords[0] > 0 && coords[1] > 0) { coords = games.game4.npc.think(coords) } } } }, 250); this.npcRenderLoop = setInterval(function () { games.game4.npcs[games.game4.npcs.length] = [games.helper.getRandomNumber(10, 20), games.helper.getRandomNumber(10, 20)]; games.game4.npc.timeOfBirth -= 100; if (games.game4.npc.timeOfBirth < 1000) { games.game4.npc.timeOfBirth = 1000 } }, games.game4.npc.timeOfBirth); }, bombHelper: { explode: function (x, y) { $("#game4-bomberman .row{0} .col{1}".replace("{0}", x).replace("{1}", y)).removeClass("bomb"); for (var ix = -1; ix <= 1; ix++) { for (var iy = -1; iy <= 1; iy++) { $("#game4-bomberman .row{0} .col{1}".replace("{0}", ix + x).replace("{1}", iy + y)).addClass("explosion"); for (var i = 0; i < games.game4.npcs.length; i++) { var coords = games.game4.npcs[i]; if ((coords[1] == ix + x && coords[0] == iy + y)) { games.game4.npcs[i] = [-1, -1]; games.game4.player.score++; } } } } setTimeout(function () { games.game4.bombHelper.implode(x, y); }, 125); }, implode: function (x, y) { for (var ix = -1; ix <= 1; ix++) { for (var iy = -1; iy <= 1; iy++) { if (ix != 0 && iy != 0) $("#game4-bomberman .row{0} .col{1}".replace("{0}", ix + x).replace("{1}", iy + y)).removeClass("explosion"); for (var i = 0; i < games.game4.npcs.length; i++) { var coords = games.game4.npcs[i]; if ((coords[1] == ix + x && coords[0] == iy + y)) { games.game4.npcs[i] = [-1, -1]; games.game4.player.score++; } } } } setTimeout(function () { games.game4.bombHelper.vanish(x, y); }, 250); }, vanish: function (x, y) { for (var ix = -1; ix <= 1; ix++) { for (var iy = -1; iy <= 1; iy++) { $("#game4-bomberman .row{0} .col{1}".replace("{0}", ix + x).replace("{1}", iy + y)).removeClass("explosion"); for (var i = 0; i < games.game4.npcs.length; i++) { var coords = games.game4.npcs[i]; if ((coords[1] == ix + x && coords[0] == iy + y)) { games.game4.npcs[i] = [-1, -1]; games.game4.player.score++; } } } } } }, npcs: new Array(), npc: { timeOfBirth: 5000, think: function (coords) { //decide new co-ords var choice = games.helper.getRandomNumber(0, 100); var x = coords[0]; var y = coords[1]; if (choice < 25) { x--; } else if (choice < 50) { y--; } else if (choice < 75) { x++; } else if (choice < 100) { y++; } var wallHit = $("#game4-bomberman .row{0} .col{1}".replace("{0}", y).replace("{1}", x)).hasClass("wall"); if (!wallHit) { coords[0] = x; coords[1] = y; } return coords; }, draw: function (coords) { $("#game4-bomberman .row{0} .col{1}".replace("{0}", coords[1]).replace("{1}", coords[0])).addClass("npc"); } }, player: { score: 0, coords: [1, 1], bombPosition: undefined, handleKey: function (charCode, isUp) { //81 drop bomb blow up bomb if (isUp) { //fire only switch (charCode) { case 88: if (games.game4.player.bombPosition == undefined) { games.game4.player.bombPosition = new Array(); games.game4.player.bombPosition[0] = games.game4.player.coords[0]; games.game4.player.bombPosition[1] = games.game4.player.coords[1]; } else { games.game4.bombHelper.explode(games.game4.player.bombPosition[1], games.game4.player.bombPosition[0]); games.game4.player.bombPosition = undefined; } break; } } else { var x = games.game4.player.coords[0]; var y = games.game4.player.coords[1]; switch (charCode) { case 37: x--; break; case 38: y--; break; case 39: x++; break; case 40: y++; break; } var wallHit = $("#game4-bomberman .row{0} .col{1}".replace("{0}", y).replace("{1}", x)).hasClass("wall"); if (!wallHit) { games.game4.player.coords[0] = x; games.game4.player.coords[1] = y; } } if (charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 88) { return false; } }, draw: function (table) { $("#game4-bomberman td").removeClass("player") $("#game4-bomberman .row{0} .col{1}".replace("{0}", this.coords[1]).replace("{1}", this.coords[0])).addClass("player"); for (var i = 0; i < games.game4.npcs.length; i++) { var npcCoords = games.game4.npcs[i]; if (npcCoords[0] == this.coords[0] && npcCoords[1] == this.coords[1]) { $("#game4-bomberman td").removeClass("player") alert("uh oh, you didn't make it. Score was " + this.score); games.game4.stopGame(); } } if (this.bombPosition != undefined) { $("#game4-bomberman .row{0} .col{1}".replace("{0}", this.bombPosition[1]).replace("{1}", this.bombPosition[0])).addClass("bomb"); } //games.game4.player.bombPosition } } };
JavaScript
 games.game9 = { //goblin game worldmap: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], renderloop: undefined, npcRenderLoop: undefined, npcThinkLoop: undefined, stopGame: function () { window.clearInterval(this.renderloop); window.clearInterval(this.npcRenderLoop); window.clearInterval(this.npcThinkLoop); }, init: function () { var html = ""; html += "<table id='game9-goblin'>"; for (var i = 0; i < this.worldmap.length; i++) { var worldmapRow = this.worldmap[i]; html += "<tr class='row{0}'>".replace("{0}", i); for (var k = 0; k < worldmapRow.length; k++) { var worldmapCol = worldmapRow[k]; html += "<td class='col{1} {0}'>&nbsp;</td>".replace("{1}", k).replace("{0}", (worldmapCol == 0 ? "wall" : worldmapCol == 1 ? "floor" : "obstacle")); } html += "</tr>"; } html += "</table>"; $("#gamezone").html(html); $(document).keyup(function (event) { games.game9.player.handleKey(event.keyCode, true); games.game9.player.handleKey(event.keyCode, false); return false; }); this.renderloop = setInterval(function () { games.game9.player.draw(); $("#game9-goblin .npc").removeClass("npc"); for (var i = 0; i < games.game9.npcs.length; i++) { if (i < games.game9.npcs.length) { var coords = games.game9.npcs[i]; games.game9.npc.draw(coords); } } }, 10); this.npcThinkLoop = setInterval(function () { for (var i = 0; i < games.game9.npcs.length; i++) { if (i < games.game9.npcs.length) { var coords = games.game9.npcs[i]; if (coords[0] > 0 && coords[1] > 0) { coords = games.game9.npc.think(coords) } } } }, 250); this.npcRenderLoop = setInterval(function () { games.game9.npcs[games.game9.npcs.length] = [games.helper.getRandomNumber(10, 20), games.helper.getRandomNumber(10, 20)]; games.game9.npc.timeOfBirth -= 100; if (games.game9.npc.timeOfBirth < 1000) { games.game9.npc.timeOfBirth = 1000 } }, games.game9.npc.timeOfBirth); }, npcs: new Array(), npc: { timeOfBirth: 5000, think: function (coords) { //decide new co-ords var choice = games.helper.getRandomNumber(0, 100); var x = coords[0]; var y = coords[1]; if (choice < 25) { x--; } else if (choice < 50) { y--; } else if (choice < 75) { x++; } else if (choice < 100) { y++; } var wallHit = $("#game9-goblin .row{0} .col{1}".replace("{0}", y).replace("{1}", x)).hasClass("wall"); if (!wallHit) { coords[0] = x; coords[1] = y; } return coords; }, draw: function (coords) { $("#game9-goblin .row{0} .col{1}".replace("{0}", coords[1]).replace("{1}", coords[0])).addClass("npc"); } }, player: { score: 0, coords: [1, 1], lastDirection: "d", isAttacking: false, handleKey: function (charCode, isUp) { //81 drop bomb blow up bomb if (isUp) { switch (charCode) { case 88: games.game9.player.attack(); break; } } else { // if (!games.game9.player.isAttacking) { var x = games.game9.player.coords[0]; var y = games.game9.player.coords[1]; switch (charCode) { case 37: x--; games.game9.player.lastDirection = "l"; break; case 38: y--; games.game9.player.lastDirection = "u"; break; case 39: x++; games.game9.player.lastDirection = "r"; break; case 40: y++; games.game9.player.lastDirection = "d"; break; } var wallHit = $("#game9-goblin .row{0} .col{1}".replace("{0}", y).replace("{1}", x)).hasClass("wall"); if (!wallHit) { games.game9.player.coords[0] = x; games.game9.player.coords[1] = y; } } if (charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 88) { return false; } }, attack: function () { games.game9.player.isAttacking = true; setTimeout(function () { games.game9.player.isAttacking = false; }, 1000); }, draw: function () { $("#game9-goblin td").removeClass("player") $("#game9-goblin td").removeClass("sword") $("#game9-goblin .row{0} .col{1}".replace("{0}", this.coords[1]).replace("{1}", this.coords[0])).addClass("player"); if (this.isAttacking) { var x = this.coords[0]; var y = this.coords[1]; switch (this.lastDirection) { case "l": x--; break; case "u": y--; break; case "r": x++; break; case "d": y++; break; } $("#game9-goblin .row{0} .col{1}".replace("{0}", y).replace("{1}", x)).addClass("sword"); if ($("#game9-goblin .sword").hasClass("npc")) { for (var i = 0; i < games.game9.npcs.length; i++) { var coords = games.game9.npcs[i]; if ((coords[0] == x && coords[1] == y)) { $("#game9-goblin .sword").removeClass("npc"); games.game9.npcs[i] = [-1, -1]; games.game9.player.score++; } } } } for (var i = 0; i < games.game9.npcs.length; i++) { var npcCoords = games.game9.npcs[i]; if (npcCoords[0] == this.coords[0] && npcCoords[1] == this.coords[1]) { $("#game9-goblin td").removeClass("player") alert("uh oh, you didn't make it. Score was " + this.score); games.game9.stopGame(); } } //games.game9.player.bombPosition } } };
JavaScript
games.game1 = { firstChosenCard: undefined, secondChosenCard: undefined, matches: 0, init: function () { games.game1.firstChosenCard = undefined; games.game1.secondChosenCard = undefined; games.game1.matches = 0; var grid = "0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7".split(","); this.randomiseArray(grid); var html = "<ul id='game1-pairs'>"; for (var i = 0; i < grid.length; i++) { html += "<li><a href='#' class='card" + grid[i] + "' id='game1-pairs-card" + i + "'>&nbsp;</li>"; } html += "</ul>"; $("#gamezone").html(html); $("#gamezone ul#game1-pairs li a").click(function () { $(this).css("background-image", "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/" + $(this).attr("class") + ".jpg)"); if (games.game1.firstChosenCard == undefined) { games.game1.firstChosenCard = $(this); } else if (games.game1.secondChosenCard == undefined) { games.game1.secondChosenCard = $(this); if (games.game1.firstChosenCard.attr("class") == games.game1.secondChosenCard.attr("class") && games.game1.firstChosenCard.attr("id") != games.game1.secondChosenCard.attr("id")) { games.game1.firstChosenCard.unbind('click'); games.game1.secondChosenCard.unbind('click'); games.game1.firstChosenCard = undefined; games.game1.secondChosenCard = undefined; games.game1.matches++; if (games.game1.matches == 8) { alert("YAY!!!! you did it! Come back tomorow for another game! Or click the date again at the top to reset"); } } else { setTimeout(function () { var resetBackground = "url(http://12-games-of-christmas.googlecode.com/svn/trunk/assets/back-of-card.png)"; games.game1.firstChosenCard.css("background-image", resetBackground); games.game1.secondChosenCard.css("background-image", resetBackground); games.game1.firstChosenCard = undefined; games.game1.secondChosenCard = undefined; }, 500); } } }); }, randomiseArray: function (myArray) { var i = myArray.length; if (i == 0) return false; while (--i) { var j = Math.floor(Math.random() * (i + 1)); var tempi = myArray[i]; var tempj = myArray[j]; myArray[i] = tempj; myArray[j] = tempi; } } };
JavaScript
var elementState = {"still":1, "walking":2, "jumping":3}; element = function (x, y, size) { this.maxVelocity = 11; this.x = x; this.y = y; this.size = size; this.velocity = 0; this.state = 0; this.isFacingRight = false; this.jumpVelocity = 0; this.state = new Array(); this.frame = 0; this.imagesLoaded = 0; this.l2r = new Array(); for (var i = 0; i < 4; i++) { this.l2r[i] = new Image(); this.l2r[i].src = 'assets/l2r-000{0}.jpg'.replace("{0}", i); ; this.l2r[i].width = 10; this.l2r[i].height = 10; this.l2r[i].onload = function () { gameEngine.player.imagesLoaded++; } } this.r2l = new Array(); for (var i = 0; i < 4; i++) { this.r2l[i] = new Image(); this.r2l[i].src = 'assets/r2l-000{0}.jpg'.replace("{0}", i); ; this.r2l[i].width = 10; this.r2l[i].height = 10; this.r2l[i].onload = function () { gameEngine.player.imagesLoaded++; } } this.adjust = function (context) { // Fg=G(m1*m2)/d^2 var imgdleft = context.getImageData(this.x - 1, this.y + this.size - 1, 1, 1); var pixleft = imgdleft.data; var canMoveLeft = (pixleft[3] == 0); var imgdright = context.getImageData(this.x + this.size + 1, this.y + this.size - 1, 1, 1); var pixright = imgdright.data; var canMoveRight = (pixright[3] == 0); if (this.isFacingRight) { if (canMoveRight) { this.x += this.velocity; } } else { if (canMoveLeft) { this.x -= this.velocity; } } if (this.jumpVelocity > 0) { var jumpinc = (this.jumpVelocity / 3); this.jumpVelocity -= Math.floor(jumpinc); this.y -= jumpinc; if (jumpinc < 2) { this.jumpVelocity = 0; } } } this.accelerate = function (facingRight) { if (facingRight == this.isFacingRight) { this.velocity += 2; } else { this.velocity -= 2; if (this.velocity < 0) { this.velocity = 0; this.isFacingRight = facingRight; } } if (this.velocity > this.maxVelocity) { this.velocity = this.maxVelocity; } } this.decelerate = function () { this.velocity -= 2; if (this.velocity < 0) { this.velocity = 0; return false; } return true; } this.jump = function () { if (!this.state[elementState.jumping]) { this.state[elementState.jumping] = true; this.jumpVelocity = 125 + 5 * this.velocity; this.velocity -= 2; } } this.draw = function (ctx) { this.frame++; this.frame = this.frame > 3 ? 0 : this.frame; var img = undefined; if (this.state[elementState.walking]) { img = this.isFacingRight ? this.l2r[this.frame] : this.r2l[this.frame]; } else if (this.state[elementState.jumping]) { img = this.isFacingRight ? this.l2r[this.frame] : this.r2l[this.frame]; } else { img = this.isFacingRight ? this.l2r[1] : this.r2l[1]; } if (this.imagesLoaded > 15) { ctx.drawImage(img, this.x, this.y, this.size, this.size); } else { ctx.fillStyle = "#ff0000"; ctx.fillRect(this.x, this.y, this.size, this.size); } } } var world = function () { this.maps = ["assets/levelmap1-0.png"]; this.h = 768; this.w = 768; this.gravitate = function (body, context) { var mass1 = Math.PI * Math.pow((50 / 2), 2) / 1.2; var mass2 = Math.PI * Math.pow((body.size / 2), 2) / 1.2; var distance = (this.h / 2) - (body.y + body.size); distance = distance < 0 ? distance * -1 : distance > 25 ? 25 : distance; var pull = ((6.673) * (mass1 * mass2)) / Math.pow(distance, 2); pull = pull > 15 ? 15 : pull; var imgdleft = context.getImageData(body.x, body.y + body.size, 1, 1); var pixleft = imgdleft.data; var imgdright = context.getImageData(body.x + body.size, body.y + body.size, 1, 1); var pixright = imgdright.data; if (pixright[3] == pixleft[3] && pixleft[3] == 0) { body.y += pull; } else { var onGround = false; while (!onGround) { var pxleft = context.getImageData(body.x, body.y + body.size - 1, 1, 1).data; var pxright = context.getImageData(body.x + body.size, body.y + body.size - 1, 1, 1).data; if (pxright[3] == 0 || pxleft[3] == 0) { onGround = true; body.state[elementState.jumping] = false; } else { body.y--; document.title = body.y; } } } } } var gameEngine = new function () { this.player = null; this.canvas = null; this.context = null; this.img = null; this.curX = 0; this.level = 0; this.world = null; this.keysDown = new Array(); this.tick = function () { if (this.curX > this.img.width - this.canvas.width) { //this.level++; //setTimeout("gameEngine.start()", 1000); alert("you finished!!! Well done! Come back tomorow for more."); return; } this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); this.context.drawImage(this.img, this.curX, 0, this.canvas.width, this.img.height, 0, 0, this.canvas.width, this.img.height); this.world.gravitate(this.player, this.context); this.player.adjust(this.context); this.player.decelerate(); this.player.draw(this.context); setTimeout("gameEngine.tick()", 40); } this.handleKeys = function () { if (this.keysDown[38]) { this.player.jump(); } this.player.state[elementState.walking] = false; if (this.keysDown[39]) { this.player.state[elementState.walking] = true; this.player.accelerate(true); if (this.player.x > (this.canvas.width / 100 * 60)) { this.curX += this.player.velocity; this.player.x -= this.player.velocity; } } if (this.keysDown[37]) { this.player.state[elementState.walking] = true; this.player.accelerate(false); if (this.player.x < (this.canvas.width / 100 * 40)) { this.curX -= this.player.velocity; this.player.x += this.player.velocity; } } if (!(this.keysDown[39] & this.keysDown[37])) { } setTimeout("gameEngine.handleKeys()", 1); } this.handleKeyUp = function (keyId) { this.keysDown[keyId] = false; return !(keyId == 38 | keyId == 39 | keyId == 40); } this.handleKeyDown = function (keyId) { this.keysDown[keyId] = true; return !(keyId == 38 | keyId == 39 | keyId == 40); } this.init = function (canvasId) { for (var i = 0; i < 128; i++) { this.keysDown[i] = false; } this.world = new world(); this.player = new element(50, 50, 10); this.player.maxVelocity = 50; this.canvas = document.getElementById(canvasId); this.context = this.canvas.getContext("2d"); this.handleKeys(); } this.start = function () { this.player = new element(50, 50, 50); this.curX = 0; this.img = new Image(); this.img.src = this.world.maps[this.level]; this.img.onload = function () { gameEngine.tick(); } } }
JavaScript
games.game11 = { // mario type game init: function () { $("#gamezone").html('<canvas id="game11-sideways-scroller" width="786" height="786"></canvas>'); gameEngine.init("game11-sideways-scroller"); document.onkeydown = function(e){ var KeyID = (window.event) ? event.keyCode : e.keyCode; return gameEngine.handleKeyDown(KeyID); } document.onkeyup = function(e){ var KeyID = (window.event) ? event.keyCode : e.keyCode; return gameEngine.handleKeyUp(KeyID); } gameEngine.start(); } };
JavaScript
var games = {} || games; games.helper = { getRandomNumber: function (low, high) { return Math.floor(Math.random() * high) + low; } } games.gamezone = { bind:function(){ var lis = $("#windows li"); lis.each(function () { $(this).attr("class", "disabled"); }); for (var i = 0; i <= todaysDate - 13; i++) { var currentLi = lis[i]; currentLi.className = "enabled"; } $('#windows .enabled a').unbind("hover"); $('#windows .enabled a').unbind("click"); $('#windows .enabled a').hover(function () { $(this).stop().animate({ backgroundPosition: "(-20px 94px)" }, { duration: 500 }); }, function () { $(this).stop().animate({ backgroundPosition: "(40px 35px)" }, { duration: 200, complete: function () { $(this).css({ backgroundPosition: "-20px 35px" }) } }); }); $('#windows .enabled a').click(function () { $(this).css({ "background": "blue" }); games.gamezone.loadGame($(this).parent().attr("id")); return false; }); $('#windows .disabled a').hover(function () { $(this).stop().animate({ backgroundPosition: "(0 -250px)" }, { duration: 500 }) }, function () { $(this).stop().animate({ backgroundPosition: "(0 0)" }, { duration: 500 }) }); $('#windows .disabled a').click(function () { alert("This day is currently unavailable. Please come back in " + ($(this).text() - todaysDate) + " days."); return false; }); }, loadGame : function (gameid) { switch (gameid) { case "game1": //done games.game1.init(); break; case "game2": //done games.game2.init(); break; case "game3": //done games.game3.init(); break; case "game4": //done games.game4.init(); break; case "game5": //done games.game5.init(); break; case "game6": //done games.game6.init(); break; case "game7": //done games.game7.init(); break; case "game8": //done games.game8.init(); break; case "game9": //done games.game9.init(); break; case "game10": //done games.game10.init(); break; case "game11": games.game11.init(); break; case "game12": games.game12.init(); break; } } }
JavaScript
games.game3 = { wordsInPlay: 0, words: "paris,newyork,london,frankfurt,harjit,dilshini,may,february,september,germany,paddington,plumstead,ealing,georgia,jackson,starbucks".split(","), wordNumber: 0, timeBetweenWords: 2000, score: 0, stringBuffer: "", init: function () { $("#gamezone").html(""); games.helper.getRandomNumber(0, games.game3.words.length); alert("When your ready, click ok, then type what you see"); $(document).keyup(function (event) { var alphaKey = String.fromCharCode(event.keyCode).toLowerCase(); if ("abcdefghijklmnopqrstuvwxyz".indexOf(alphaKey) > -1) { games.game3.stringBuffer += alphaKey; $(".game3-words").each(function () { var l = games.game3.stringBuffer.length; var l2 = $(this).text().length; if (games.game3.stringBuffer.substring(l - l2, l) == $(this).text()) { games.game3.stringBuffer = ""; $(this).trigger("blow"); games.game3.wordsInPlay--; games.game3.score++; } }); } }); games.game3.addWord(); }, addWord: function () { games.game3.wordsInPlay++; if (games.game3.wordsInPlay < 10) { var word = games.game3.words[games.helper.getRandomNumber(0, games.game3.words.length)]; $("#gamezone").append("<span class='game3-words' id='game3-word" + games.game3.wordNumber + "'>" + word + "</span>"); $("#game3-word" + games.game3.wordNumber).bind("blow", (function () { $(this).remove(); })); $("#game3-word" + games.game3.wordNumber).css("top", "50px").animate({ "top": "500px" }, 4000); games.game3.wordNumber++; setTimeout(function () { games.game3.timeBetweenWords -= 100; if (games.game3.timeBetweenWords < 500) { games.game3.timeBetweenWords = 500 } games.game3.addWord(); }, games.game3.timeBetweenWords); } else { alert("oh dear, you were defeated. You scored " + (games.game3.score)); } } };
JavaScript
/* * 12306 Auto Query => A javascript snippet to help you book tickets online. * 12306 Booking Assistant * Copyright (C) 2011 Hidden * * 12306 Auto Query => A javascript snippet to help you book tickets online. * Copyright (C) 2011 Jingqin Lynn * * 12306 Auto Login => A javascript snippet to help you auto login 12306.com. * Copyright (C) 2011 Kevintop * * Includes jQuery * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ // ==UserScript== // @name 12306 Booking Assistant // @version 1.3.8.2 // @author zzdhidden@gmail.com // @namespace https://github.com/zzdhidden // @description 12306 订票助手之(自动登录,自动查票,自动订单) // @include *://dynamic.12306.cn/otsweb/* // @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js // ==/UserScript== function withjQuery(callback, safe){ if(typeof(jQuery) == "undefined") { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"; if(safe) { var cb = document.createElement("script"); cb.type = "text/javascript"; cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery, window);"; script.addEventListener('load', function() { document.head.appendChild(cb); }); } else { var dollar = undefined; if(typeof($) != "undefined") dollar = $; script.addEventListener('load', function() { jQuery.noConflict(); $ = dollar; callback(jQuery, window); }); } document.head.appendChild(script); } else { setTimeout(function() { //Firefox supports callback(jQuery, typeof unsafeWindow === "undefined" ? window : unsafeWindow); }, 30); } } withjQuery(function($, window){ $(document).click(function() { if( window.webkitNotifications && window.webkitNotifications.checkPermission() != 0 ) { window.webkitNotifications.requestPermission(); } }); function notify(str, timeout, skipAlert) { if( window.webkitNotifications && window.webkitNotifications.checkPermission() == 0 ) { var notification = webkitNotifications.createNotification( "http://www.12306.cn/mormhweb/images/favicon.ico", // icon url - can be relative '订票', // notification title str ); notification.show(); if ( timeout ) { setTimeout(function() { notification.cancel(); }, timeout); } return true; } else { if( !skipAlert ) { alert( str ); } return false; } } function route(match, fn) { if( window.location.href.indexOf(match) != -1 ) { fn(); }; } function query() { //query var isTicketAvailable = false; var firstRemove = false; window.$ && window.$(".obj:first").ajaxComplete(function() { $(this).find("tr").each(function(n, e) { if(checkTickets(e)){ isTicketAvailable = true; highLightRow(e); } }); if(firstRemove) { firstRemove = false; if (isTicketAvailable) { if (isAutoQueryEnabled) document.getElementById("refreshButton").click(); onticketAvailable(); //report } else { //wait for the button to become valid } } }).ajaxError(function() { if(isAutoQueryEnabled) doQuery(); }); //hack into the validQueryButton function to detect query var _delayButton = window.delayButton; window.delayButton = function() { _delayButton(); if(isAutoQueryEnabled) doQuery(); } //Trigger the button var doQuery = function() { displayQueryTimes(queryTimes++); firstRemove = true; document.getElementById(isStudentTicket ? "stu_submitQuery" : "submitQuery").click(); } var $special = $("<input type='text' />") var checkTickets = function(row) { var hasTicket = false; var v1 = $special.val(); if( v1 ) { var v2 = $.trim( $(row).find(".base_txtdiv").text() ); if( v1.indexOf( v2 ) == -1 ) { return false; } } if( $(row).find("td input.yuding_x[type=button]").length ) { return false; } $("td", row).each(function(i, e) { if(ticketType[i-1]) { var info = $.trim($(e).text()); if(info != "--" && info != "无") { hasTicket = true; highLightCell(e); } } }); return hasTicket; } var queryTimes = 0; //counter var isAutoQueryEnabled = false; //enable flag //please DIY: var audio = null; var onticketAvailable = function() { if(window.Audio) { if(!audio) { audio = new Audio("http://www.w3school.com.cn/i/song.ogg"); audio.loop = true; } audio.play(); notify("可以订票了!", null, true); } else { notify("可以订票了!"); } } var highLightRow = function(row) { $(row).css("background-color", "#D1E1F1"); } var highLightCell = function(cell) { $(cell).css("background-color", "#2CC03E"); } var displayQueryTimes = function(n) { document.getElementById("refreshTimes").innerHTML = n; }; var isStudentTicket = false; //Control panel UI var ui = $("<div>请先选择好出发地,目的地,和出发时间。&nbsp;&nbsp;&nbsp;</div>") .append( $("<input id='isStudentTicket' type='checkbox' />").change(function(){ isStudentTicket = this.checked; }) ) .append( $("<label for='isStudentTicket'></label>").html("学生票&nbsp;&nbsp;") ) .append( $("<button style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'/>").attr("id", "refreshButton").html("开始刷票").click(function() { if(!isAutoQueryEnabled) { isTicketAvailable = false; if(audio && !audio.paused) audio.pause(); isAutoQueryEnabled = true; doQuery(); this.innerHTML="停止刷票"; } else { isAutoQueryEnabled = false; this.innerHTML="开始刷票"; } }) ) .append( $("<span>").html("&nbsp;&nbsp;尝试次数:").append( $("<span/>").attr("id", "refreshTimes").text("0") ) ) .append( //Custom ticket type $("<div>如果只需要刷特定的票种,请在余票信息下面勾选。</div>") .append($("<a href='#' style='color: blue;'>只勾选坐票&nbsp;&nbsp;</a>").click(function() { $(".hdr tr:eq(2) td").each(function(i,e) { var val = this.innerHTML.indexOf("座") != -1; var el = $(this).find("input").attr("checked", val); el && el[0] && ( ticketType[el[0].ticketTypeId] = val ); }); return false; })) .append($("<a href='#' style='color: blue;'>只勾选卧铺&nbsp;&nbsp;</a>").click(function() { $(".hdr tr:eq(2) td").each(function(i,e) { var val = this.innerHTML.indexOf("卧") != -1; var el = $(this).find("input").attr("checked", val); el && el[0] && ( ticketType[el[0].ticketTypeId] = val ); }); return false; })) ) .append( $("<div>限定出发车次:</div>") .append( $special ) .append( "不限制不填写,限定多次用逗号分割,例如: G32,G34" ) ); var container = $(".cx_title_w:first"); container.length ? ui.insertBefore(container) : ui.appendTo(document.body); //Ticket type selector & UI var ticketType = new Array(); $(".hdr tr:eq(2) td").each(function(i,e) { ticketType.push(false); if(i<3) return; ticketType[i] = true; var c = $("<input/>").attr("type", "checkBox").attr("checked", true); c[0].ticketTypeId = i; c.change(function() { ticketType[this.ticketTypeId] = this.checked; }).appendTo(e); }); } route("querySingleAction.do", query); route("myOrderAction.do?method=resign", query); route("confirmPassengerResignAction.do?method=cancelOrderToQuery", query); route("loginAction.do?method=init", function() { if( !window.location.href.match( /init$/i ) ) { return; } //login var url = "https://dynamic.12306.cn/otsweb/loginAction.do?method=login"; var queryurl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init"; //Check had login, redirect to query url if( window.parent && window.parent.$ ) { var str = window.parent.$("#username_ a").attr("href"); if( str && str.indexOf("sysuser/user_info") != -1 ){ window.location.href = queryurl; return; } } function submitForm(){ var submitUrl = url; $.ajax({ type: "POST", url: submitUrl, data: { "loginUser.user_name": $("#UserName").val() , "user.password": $("#password").val() , "randCode": $("#randCode").val() }, beforeSend: function( xhr ) { try{ xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }}); xhr.setRequestHeader('Cache-Control', 'max-age=0'); xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); }catch(e){}; }, timeout: 30000, //cache: false, //async: false, success: function(msg){ //密码输入错误 //您的用户已经被锁定 if ( msg.indexOf('请输入正确的验证码') > -1 ) { alert('请输入正确的验证码!'); } else if ( msg.indexOf('当前访问用户过多') > -1 ){ reLogin(); } else if( msg.match(/var\s+isLogin\s*=\s*true/i) ) { notify('登录成功,开始查询车票吧!'); window.location.replace( queryurl ); } else if( msg.indexOf('var message = ""') > -1 ){ reLogin(); } else { msg = msg.match(/var\s+message\s*=\s*"([^"]*)/); alert( msg && msg[1] || "未知错误" ); } }, error: function(msg){ reLogin(); } }); } var count = 1; function reLogin(){ count ++; $('#refreshButton').html("("+count+")次登录中..."); setTimeout(submitForm, 50); } //初始化 $("#subLink").after($("<a href='#' style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'/>").attr("id", "refreshButton").html("自动登录").click(function() { count = 1; $(this).html("(1)次登录中..."); //notify('开始尝试登录,请耐心等待!', 4000); submitForm(); return false; })); alert('如果使用自动登录功能,请输入用户名、密码及验证码后,点击自动登录,系统会尝试登录,直至成功!'); }); route("confirmPassengerAction.do", function() { /** * Auto Submit Order * From: https://gist.github.com/1577671 * Author: kevintop@gmail.com */ //Auto select the first user when not selected if( !$("input._checkbox_class:checked").length ) { try{ //Will failed in IE $("input._checkbox_class:first").click(); }catch(e){}; } //passengerTickets var userInfoUrl = 'https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete&leftmenu=Y'; var count = 1, freq = 1000, doing = false, timer, $msg = $("<div style='padding-left:470px;'></div>"); function submitForm(){ timer = null; //更改提交列车日期参数 //var wantDate = $("#startdatepicker").val(); //$("#start_date").val(wantDate); //$("#_train_date_str").val(wantDate); jQuery.ajax({ url: $("#confirmPassenger").attr('action'), data: $('#confirmPassenger').serialize(), beforeSend: function( xhr ) { try{ xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }}); xhr.setRequestHeader('Cache-Control', 'max-age=0'); xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'); }catch(e){}; }, type: "POST", timeout: 30000, success: function( msg ) { //Refresh token var match = msg && msg.match(/org\.apache\.struts\.taglib\.html\.TOKEN['"]?\s*value=['"]?([^'">]+)/i); var newToken = match && match[1]; if(newToken) { $("input[name='org.apache.struts.taglib.html.TOKEN']").val(newToken); } if( msg.indexOf('payButton') > -1 ) { //Success! var audio; if( window.Audio ) { audio = new Audio("http://www.w3school.com.cn/i/song.ogg"); audio.loop = true; audio.play(); } notify("恭喜,车票预订成!", null, true); setTimeout(function() { if( confirm("车票预订成,去付款?") ){ window.location.replace(userInfoUrl); } else { if(audio && !audio.paused) audio.pause(); } }, 100); return; }else if(msg.indexOf('未处理的订单') > -1){ notify("有未处理的订单!"); window.location.replace(userInfoUrl); return; } var reTryMessage = [ '用户过多' , '确认客票的状态后再尝试后续操作' , '请不要重复提交' , '没有足够的票!' ]; for (var i = reTryMessage.length - 1; i >= 0; i--) { if( msg.indexOf( reTryMessage[i] ) > -1 ) { reSubmitForm( reTryMessage[i] ); return; } }; //Parse error message msg = msg.match(/var\s+message\s*=\s*"([^"]*)/); stop(msg && msg[1] || '出错了。。。。 啥错? 我也不知道。。。。。'); }, error: function(msg){ reSubmitForm("网络错误"); } }); }; function reSubmitForm(msg){ if( !doing )return; count ++; $msg.html("("+count+")次自动提交中... " + (msg || "")); timer = setTimeout( submitForm, freq || 50 ); } function stop ( msg ) { doing = false; $msg.html("("+count+")次 已停止"); $('#refreshButton').html("自动提交订单"); timer && clearTimeout( timer ); msg && alert( msg ); } function reloadSeat(){ $("select[name$='_seat']").html('<option value="M" selected="">一等座</option><option value="O" selected="">二等座</option><option value="1">硬座</option><option value="3">硬卧</option><option value="4">软卧</option>'); } //初始化 if($("#refreshButton").size()<1){ // //重置后加载所有席别 // $("select[name$='_seat']").each(function(){this.blur(function(){ // alert(this.attr("id") + "blur"); // })}); ////初始化所有席别 //$(".qr_box :checkbox[name^='checkbox']").each(function(){$(this).click(reloadSeat)}); //reloadSeat(); //日期可选 //$("td.bluetext:first").html('<input type="text" name="orderRequest.train_date" value="' +$("td.bluetext:first").html()+'" id="startdatepicker" style="width: 150px;" class="input_20txt" onfocus="WdatePicker({firstDayOfWeek:1})" />'); $(".tj_btn").append($("<a style='padding: 5px 10px; background: #2CC03E;border-color: #259A33;border-right-color: #2CC03E;border-bottom-color:#2CC03E;color: white;border-radius: 5px;text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.2);'></a>").attr("id", "refreshButton").html("自动提交订单").click(function() { //alert('开始自动提交订单,请点确定后耐心等待!'); if( this.innerHTML.indexOf("自动提交订单") == -1 ){ //doing stop(); } else { if( window.submit_form_check && !window.submit_form_check("confirmPassenger") ) { return; } count = 0; doing = true; this.innerHTML = "停止自动提交"; reSubmitForm(); } return false; })); $(".tj_btn").append("自动提交频率:") .append($("<select id='freq'><option value='50' >频繁</option><option value='500' selected='' >正常</option><option value='2000' >缓慢</option></select>").change(function() { freq = parseInt( $(this).val() ); })) .append($msg); //alert('如果使用自动提交订单功能,请在确认订单正确无误后,再点击自动提交按钮!'); } }); }, true);
JavaScript
var searchData= [ ['log_5fdebug',['LOG_DEBUG',['../logger_8hpp.html#a6ff63e8955665c4a58b1598f2b07c51a',1,'logger.hpp']]], ['log_5ferror',['LOG_ERROR',['../logger_8hpp.html#aced66975c154ea0e2a8ec3bc818b4e08',1,'logger.hpp']]], ['log_5ffatal',['LOG_FATAL',['../logger_8hpp.html#ac2164369b4d2bf72296f8ba6ea576ecf',1,'logger.hpp']]], ['log_5finfo',['LOG_INFO',['../logger_8hpp.html#aeb4f36db01bd128c7afeac5889dac311',1,'logger.hpp']]], ['log_5fnone',['LOG_NONE',['../logger_8hpp.html#a1632479322efa3952798f98177b54471',1,'logger.hpp']]], ['log_5fwarning',['LOG_WARNING',['../logger_8hpp.html#adf4476a6a4ea6c74231c826e899d7189',1,'logger.hpp']]], ['logger',['logger',['../logger_8hpp.html#ab58cdd006f6b33cbe171ab32effef95b',1,'logger.hpp']]] ];
JavaScript
var searchData= [ ['adjlist_5fcontainer',['adjlist_container',['../classadjlist__container.html',1,'']]], ['als_5ffactor_5fand_5fweight',['als_factor_and_weight',['../structals__factor__and__weight.html',1,'']]], ['als_5fvertex_5fprogram',['als_vertex_program',['../classals__vertex__program.html',1,'']]], ['alsedgefactorsprogram',['ALSEdgeFactorsProgram',['../struct_a_l_s_edge_factors_program.html',1,'']]], ['alsverticesinmemprogram',['ALSVerticesInMemProgram',['../struct_a_l_s_vertices_in_mem_program.html',1,'']]], ['atomic',['atomic',['../classgraphchi_1_1atomic.html',1,'graphchi']]] ];
JavaScript
var searchData= [ ['pagerank_5fkernel',['pagerank_kernel',['../structpagerank__kernel.html',1,'']]], ['pagerankprogram',['PagerankProgram',['../struct_pagerank_program.html',1,'']]], ['paircontainer',['PairContainer',['../structgraphchi_1_1_pair_container.html',1,'graphchi']]], ['paircontainer_3c_20kernel_3a_3aedgedatatype_20_3e',['PairContainer&lt; KERNEL::EdgeDataType &gt;',['../structgraphchi_1_1_pair_container.html',1,'graphchi']]], ['pinned_5ffile',['pinned_file',['../structgraphchi_1_1pinned__file.html',1,'graphchi']]], ['prediction_5fsaver',['prediction_saver',['../structprediction__saver.html',1,'']]], ['program',['Program',['../class_program.html',1,'']]] ];
JavaScript
var searchData= [ ['edge',['edge',['../classgraphchi_1_1graphchi__vertex.html#a79aebd315e4f333e8ba0e756c265883a',1,'graphchi::graphchi_vertex']]], ['edge_5fdata',['edge_data',['../structedge__data.html#a98967d7ad71e7ef996e6b9727e97949c',1,'edge_data']]], ['elapsed_5fseconds',['elapsed_seconds',['../classgraphlab_1_1icontext.html#a863010fd33f3721162d253af3583f8bb',1,'graphlab::icontext']]], ['end_5fpreprocessing',['end_preprocessing',['../classgraphchi_1_1sharder.html#aebb6e75ba00e4f4016b9559e45254142',1,'graphchi::sharder']]], ['execute_5fsharding',['execute_sharding',['../classgraphchi_1_1sharder.html#a8c1af4eca3037578aa7bd5b7cc431c8c',1,'graphchi::sharder']]], ['extend_5fpivotrange',['extend_pivotrange',['../classadjlist__container.html#ac43be3ce9e2e0f19cc1d52e13f766e28',1,'adjlist_container']]], ['extract_5fl2_5ferror',['extract_l2_error',['../als__vertex__program_8hpp.html#afb0b8a4655197699932baa2bac0cc465',1,'als_vertex_program.hpp']]] ];
JavaScript
var searchData= [ ['graphchi',['graphchi',['../namespacegraphchi.html',1,'']]], ['messages',['messages',['../namespacegraphlab_1_1messages.html',1,'graphlab']]] ];
JavaScript
var searchData= [ ['refcountptr',['refcountptr',['../structgraphchi_1_1refcountptr.html',1,'graphchi']]], ['rwlock',['rwlock',['../classgraphchi_1_1rwlock.html',1,'graphchi']]] ];
JavaScript
var searchData= [ ['load',['load',['../classgraphchi_1_1degree__data.html#a845b713beb8419274e2b5312ddd8bc5f',1,'graphchi::degree_data::load()'],['../classgraphchi_1_1vertex__data__store.html#a4885bac577540a6dcf0be31af0c3572c',1,'graphchi::vertex_data_store::load()']]], ['load_5fvertex_5fintervals',['load_vertex_intervals',['../classgraphchi_1_1graphchi__engine.html#a8c4fe7f4bccdbb667e6d4af8d35a07c0',1,'graphchi::graphchi_engine']]], ['local_5fid',['local_id',['../structgraphlab_1_1_graph_lab_vertex_wrapper.html#a751dcd1a2180f251d4ad93175a89602f',1,'graphlab::GraphLabVertexWrapper']]], ['log_5fchange',['log_change',['../structgraphchi_1_1graphchi__context.html#a28176afb423f7351d9ec14569eeb610d',1,'graphchi::graphchi_context']]] ];
JavaScript
var searchData= [ ['outputlevel',['OUTPUTLEVEL',['../logger_8hpp.html#a3d18ed817dcda9f54a4f353ccf9b1b36',1,'logger.hpp']]] ];
JavaScript
var searchData= [ ['grabbed_5fedges',['grabbed_edges',['../trianglecounting_8cpp.html#ade7b20338aaa8b999330cb30c4d079f9',1,'trianglecounting.cpp']]] ];
JavaScript