code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Finnish * language. Translated into Finnish 2010-12-15 by Petteri Salmela, * updated. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['fi'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, ei käytettävissä</span>', confirmCancel : 'Valintoja on muutettu. Suljetaanko ikkuna kuitenkin?', ok : 'OK', cancel : 'Peru', confirmationTitle : 'Varmistus', messageTitle : 'Ilmoitus', inputTitle : 'Kysymys', undo : 'Peru', redo : 'Tee uudelleen', skip : 'Ohita', skipAll : 'Ohita kaikki', makeDecision : 'Mikä toiminto suoritetaan?', rememberDecision: 'Muista valintani' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'fi', LangCode : 'fi', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'yyyy-mm-dd HH:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Kansiot', FolderLoading : 'Lataan...', FolderNew : 'Kirjoita uuden kansion nimi: ', FolderRename : 'Kirjoita uusi nimi kansiolle ', FolderDelete : 'Haluatko varmasti poistaa kansion "%1"?', FolderRenaming : ' (Uudelleennimeää...)', FolderDeleting : ' (Poistaa...)', // Files FileRename : 'Kirjoita uusi tiedostonimi: ', FileRenameExt : 'Haluatko varmasti muuttaa tiedostotarkennetta? Tiedosto voi muuttua käyttökelvottomaksi.', FileRenaming : 'Uudelleennimeää...', FileDelete : 'Haluatko varmasti poistaa tiedoston "%1"?', FilesLoading : 'Lataa...', FilesEmpty : 'Tyhjä kansio.', FilesMoved : 'Tiedosto %1 siirretty nimelle %2:%3.', FilesCopied : 'Tiedosto %1 kopioitu nimelle %2:%3.', // Basket BasketFolder : 'Kori', BasketClear : 'Tyhjennä kori', BasketRemove : 'Poista korista', BasketOpenFolder : 'Avaa ylemmän tason kansio', BasketTruncateConfirm : 'Haluatko todella poistaa kaikki tiedostot korista?', BasketRemoveConfirm : 'Haluatko todella poistaa tiedoston "%1" korista?', BasketEmpty : 'Korissa ei ole tiedostoja. Lisää raahaamalla.', BasketCopyFilesHere : 'Kopioi tiedostot korista.', BasketMoveFilesHere : 'Siirrä tiedostot korista.', BasketPasteErrorOther : 'Tiedoston %s virhe: %e.', BasketPasteMoveSuccess : 'Seuraavat tiedostot siirrettiin: %s', BasketPasteCopySuccess : 'Seuraavat tiedostot kopioitiin: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Lataa palvelimelle', UploadTip : 'Lataa uusi tiedosto palvelimelle', Refresh : 'Päivitä', Settings : 'Asetukset', Help : 'Apua', HelpTip : 'Apua', // Context Menus Select : 'Valitse', SelectThumbnail : 'Valitse esikatselukuva', View : 'Näytä', Download : 'Lataa palvelimelta', NewSubFolder : 'Uusi alikansio', Rename : 'Uudelleennimeä ', Delete : 'Poista', CopyDragDrop : 'Kopioi tiedosto tähän', MoveDragDrop : 'Siirrä tiedosto tähän', // Dialogs RenameDlgTitle : 'Nimeä uudelleen', NewNameDlgTitle : 'Uusi nimi', FileExistsDlgTitle : 'Tiedostonimi on jo olemassa!', SysErrorDlgTitle : 'Järjestelmävirhe', FileOverwrite : 'Ylikirjoita', FileAutorename : 'Nimeä uudelleen automaattisesti', // Generic OkBtn : 'OK', CancelBtn : 'Peru', CloseBtn : 'Sulje', // Upload Panel UploadTitle : 'Lataa uusi tiedosto palvelimelle', UploadSelectLbl : 'Valitse ladattava tiedosto', UploadProgressLbl : '(Lataaminen palvelimelle käynnissä...)', UploadBtn : 'Lataa valittu tiedosto palvelimelle', UploadBtnCancel : 'Peru', UploadNoFileMsg : 'Valitse tiedosto tietokoneeltasi.', UploadNoFolder : 'Valitse kansio ennen palvelimelle lataamista.', UploadNoPerms : 'Tiedoston lataaminen palvelimelle evätty.', UploadUnknError : 'Tiedoston siirrossa tapahtui virhe.', UploadExtIncorrect : 'Tiedostotarkenne ei ole sallittu valitussa kansiossa.', // Flash Uploads UploadLabel : 'Ladattavat tiedostot', UploadTotalFiles : 'Tiedostoja yhteensä:', UploadTotalSize : 'Yhteenlaskettu tiedostokoko:', UploadAddFiles : 'Lisää tiedostoja', UploadClearFiles : 'Poista tiedostot', UploadCancel : 'Peru lataus', UploadRemove : 'Poista', UploadRemoveTip : 'Poista !f', UploadUploaded : 'Ladattu !n%', UploadProcessing : 'Käsittelee...', // Settings Panel SetTitle : 'Asetukset', SetView : 'Näkymä:', SetViewThumb : 'Esikatselukuvat', SetViewList : 'Luettelo', SetDisplay : 'Näytä:', SetDisplayName : 'Tiedostonimi', SetDisplayDate : 'Päivämäärä', SetDisplaySize : 'Tiedostokoko', SetSort : 'Lajittele:', SetSortName : 'aakkosjärjestykseen', SetSortDate : 'päivämäärän mukaan', SetSortSize : 'tiedostokoon mukaan', // Status Bar FilesCountEmpty : '<Tyhjä kansio>', FilesCountOne : '1 tiedosto', FilesCountMany : '%1 tiedostoa', // Size and Speed Kb : '%1 kt', KbPerSecond : '%1 kt/s', // Connector Error Messages. ErrorUnknown : 'Pyyntöä ei voitu suorittaa. (Virhe %1)', Errors : { 10 : 'Virheellinen komento.', 11 : 'Pyynnön resurssityyppi on määrittelemättä.', 12 : 'Pyynnön resurssityyppi on virheellinen.', 102 : 'Virheellinen tiedosto- tai kansionimi.', 103 : 'Oikeutesi eivät riitä pyynnön suorittamiseen.', 104 : 'Tiedosto-oikeudet eivät riitä pyynnön suorittamiseen.', 105 : 'Virheellinen tiedostotarkenne.', 109 : 'Virheellinen pyyntö.', 110 : 'Tuntematon virhe.', 115 : 'Samanniminen tiedosto tai kansio on jo olemassa.', 116 : 'Kansiota ei löydy. Yritä uudelleen kansiopäivityksen jälkeen.', 117 : 'Tiedostoa ei löydy. Yritä uudelleen kansiopäivityksen jälkeen.', 118 : 'Lähde- ja kohdekansio on sama!', 201 : 'Samanniminen tiedosto on jo olemassa. Palvelimelle ladattu tiedosto on nimetty: "%1".', 202 : 'Virheellinen tiedosto.', 203 : 'Virheellinen tiedosto. Tiedostokoko on liian suuri.', 204 : 'Palvelimelle ladattu tiedosto on vioittunut.', 205 : 'Väliaikaishakemistoa ei ole määritetty palvelimelle lataamista varten.', 206 : 'Palvelimelle lataaminen on peruttu turvallisuussyistä. Tiedosto sisältää HTML-tyylistä dataa.', 207 : 'Palvelimelle ladattu tiedosto on nimetty: "%1".', 300 : 'Tiedostosiirto epäonnistui.', 301 : 'Tiedostokopiointi epäonnistui.', 500 : 'Tiedostoselain on kytketty käytöstä turvallisuussyistä. Pyydä pääkäyttäjää tarkastamaan CKFinderin asetustiedosto.', 501 : 'Esikatselukuvien tuki on kytketty toiminnasta.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Tiedosto on nimettävä!', FileExists : 'Tiedosto %s on jo olemassa.', FolderEmpty : 'Kansio on nimettävä!', FileInvChar : 'Tiedostonimi ei voi sisältää seuraavia merkkejä: \n\\ / : * ? " < > |', FolderInvChar : 'Kansionimi ei voi sisältää seuraavia merkkejä: \n\\ / : * ? " < > |', PopupBlockView : 'Tiedostoa ei voitu avata uuteen ikkunaan. Salli selaimesi asetuksissa ponnahdusikkunat tälle sivulle.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Muuta kokoa %s', sizeTooBig : 'Kuvan mittoja ei voi asettaa alkuperäistä suuremmiksi(%size).', resizeSuccess : 'Kuvan koon muuttaminen onnistui.', thumbnailNew : 'Luo uusi esikatselukuva.', thumbnailSmall : 'Pieni (%s)', thumbnailMedium : 'Keskikokoinen (%s)', thumbnailLarge : 'Suuri (%s)', newSize : 'Aseta uusi koko', width : 'Leveys', height : 'Korkeus', invalidHeight : 'Viallinen korkeus.', invalidWidth : 'Viallinen leveys.', invalidName : 'Viallinen tiedostonimi.', newImage : 'Luo uusi kuva', noExtensionChange : 'Tiedostomäärettä ei voi vaihtaa.', imageSmall : 'Lähdekuva on liian pieni.', contextMenuName : 'Muuta kokoa', lockRatio : 'Lukitse suhteet', resetSize : 'Alkuperäinen koko' }, // Fileeditor plugin Fileeditor : { save : 'Tallenna', fileOpenError : 'Tiedostoa ei voi avata.', fileSaveSuccess : 'Tiedoston tallennus onnistui.', contextMenuName : 'Muokkaa', loadingFile : 'Tiedostoa ladataan ...' }, Maximize : { maximize : 'Suurenna', minimize : 'Pienennä' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Norwegian * Nynorsk language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['no'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, utilgjenglig</span>', confirmCancel : 'Noen av valgene har blitt endret. Er du sikker på at du vil lukke dialogen?', ok : 'OK', cancel : 'Avbryt', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Angre', redo : 'Gjør om', skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'no', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy HH:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Mapper', FolderLoading : 'Laster...', FolderNew : 'Skriv inn det nye mappenavnet: ', FolderRename : 'Skriv inn det nye mappenavnet: ', FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?', FolderRenaming : ' (Endrer mappenavn...)', FolderDeleting : ' (Sletter...)', // Files FileRename : 'Skriv inn det nye filnavnet: ', FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig.', FileRenaming : 'Endrer filnavn...', FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?', FilesLoading : 'Laster...', FilesEmpty : 'The folder is empty.', // MISSING FilesMoved : 'File %1 moved to %2:%3.', // MISSING FilesCopied : 'File %1 copied to %2:%3.', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from Basket', // MISSING BasketOpenFolder : 'Open Parent Folder', // MISSING BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING BasketPasteErrorOther : 'File %s error: %e', // MISSING BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Last opp', UploadTip : 'Last opp en ny fil', Refresh : 'Oppdater', Settings : 'Innstillinger', Help : 'Hjelp', HelpTip : 'Hjelp finnes kun på engelsk', // Context Menus Select : 'Velg', SelectThumbnail : 'Velg Miniatyr', View : 'Vis fullversjon', Download : 'Last ned', NewSubFolder : 'Ny Undermappe', Rename : 'Endre navn', Delete : 'Slett', CopyDragDrop : 'Copy File Here', // MISSING MoveDragDrop : 'Move File Here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New Name', // MISSING FileExistsDlgTitle : 'File Already Exists', // MISSING SysErrorDlgTitle : 'System Error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Avbryt', CloseBtn : 'Lukk', // Upload Panel UploadTitle : 'Last opp ny fil', UploadSelectLbl : 'Velg filen du vil laste opp', UploadProgressLbl : '(Laster opp filen, vennligst vent...)', UploadBtn : 'Last opp valgt fil', UploadBtnCancel : 'Avbryt', UploadNoFileMsg : 'Du må velge en fil fra din datamaskin', UploadNoFolder : 'Please select a folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Flash Uploads UploadLabel : 'Files to Upload', // MISSING UploadTotalFiles : 'Total Files:', // MISSING UploadTotalSize : 'Total Size:', // MISSING UploadAddFiles : 'Add Files', // MISSING UploadClearFiles : 'Clear Files', // MISSING UploadCancel : 'Cancel Upload', // MISSING UploadRemove : 'Remove', // MISSING UploadRemoveTip : 'Remove !f', // MISSING UploadUploaded : 'Uploaded !n%', // MISSING UploadProcessing : 'Processing...', // MISSING // Settings Panel SetTitle : 'Innstillinger', SetView : 'Filvisning:', SetViewThumb : 'Miniatyrbilder', SetViewList : 'Liste', SetDisplay : 'Vis:', SetDisplayName : 'Filnavn', SetDisplayDate : 'Dato', SetDisplaySize : 'Filstørrelse', SetSort : 'Sorter etter:', SetSortName : 'Filnavn', SetSortDate : 'Dato', SetSortSize : 'Størrelse', // Status Bar FilesCountEmpty : '<Tom Mappe>', FilesCountOne : '1 fil', FilesCountMany : '%1 filer', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)', Errors : { 10 : 'Ugyldig kommando.', 11 : 'Ressurstypen ble ikke spesifisert i forepørselen.', 12 : 'Ugyldig ressurstype.', 102 : 'Ugyldig fil- eller mappenavn.', 103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.', 104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.', 105 : 'Ugyldig filtype.', 109 : 'Ugyldig forespørsel.', 110 : 'Ukjent feil.', 115 : 'Det finnes allerede en fil eller mappe med dette navnet.', 116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.', 117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1".', 202 : 'Ugyldig fil.', 203 : 'Ugyldig fil. Filen er for stor.', 204 : 'Den opplastede filen er korrupt.', 205 : 'Det finnes ingen midlertidig mappe for filopplastinger.', 206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.', 207 : 'Den opplastede filens navn har blitt endret til "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.', 501 : 'Funksjon for minityrbilder er skrudd av.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Filnavnet kan ikke være tomt.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Mappenavnet kan ikke være tomt.', FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |', FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |', PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create a new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set a new size', // MISSING width : 'Bredde', height : 'Høyde', invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create a new image', // MISSING noExtensionChange : 'File extension cannot be changed.', // MISSING imageSmall : 'Source image is too small.', // MISSING contextMenuName : 'Resize', // MISSING lockRatio : 'Lås forhold', resetSize : 'Tilbakestill størrelse' }, // Fileeditor plugin Fileeditor : { save : 'Lagre', fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING }, Maximize : { maximize : 'Maksimer', minimize : 'Minimer' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Persian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['fa'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, غیر قابل دسترس</span>', confirmCancel : 'برخی از گزینهها تغییر یافتهاند. آیا مطمئن هستید که قصد بستن این پنجره را دارید؟', ok : 'قبول', cancel : 'لغو', confirmationTitle : 'تأییدیه', messageTitle : 'اطلاعات', inputTitle : 'پرسش', undo : 'واچیدن', redo : 'دوباره چیدن', skip : 'عبور', skipAll : 'عبور از همه', makeDecision : 'چه تصمیمی خواهید گرفت؟', rememberDecision: 'یادآوری تصمیم من' }, // Language direction, 'ltr' or 'rtl'. dir : 'rtl', HelpLang : 'en', LangCode : 'fa', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'yyyy/mm/dd h:MM aa', DateAmPm : ['ق.ظ', 'ب.ظ'], // Folders FoldersTitle : 'پوشهها', FolderLoading : 'بارگیری...', FolderNew : 'لطفا نام پوشه جدید را درج کنید: ', FolderRename : 'لطفا نام پوشه جدید را درج کنید: ', FolderDelete : 'آیا اطمینان دارید که قصد حذف کردن پوشه "%1" را دارید؟', FolderRenaming : ' (در حال تغییر نام...)', FolderDeleting : ' (در حال حذف...)', // Files FileRename : 'لطفا نام جدید فایل را درج کنید: ', FileRenameExt : 'آیا اطمینان دارید که قصد تغییر نام پسوند این فایل را دارید؟ ممکن است فایل غیر قابل استفاده شود', FileRenaming : 'در حال تغییر نام...', FileDelete : 'آیا اطمینان دارید که قصد حذف نمودن فایل "%1" را دارید؟', FilesLoading : 'بارگیری...', FilesEmpty : 'این پوشه خالی است', FilesMoved : 'فایل %1 به مسیر %2:%3 منتقل شد.', FilesCopied : 'فایل %1 در مسیر %2:%3 کپی شد.', // Basket BasketFolder : 'سبد', BasketClear : 'پاک کردن سبد', BasketRemove : 'حذف از سبد', BasketOpenFolder : 'باز نمودن پوشه والد', BasketTruncateConfirm : 'آیا واقعا قصد جابجا کردن همه فایلها از سبد را دارید؟', BasketRemoveConfirm : 'آیا واقعا قصد جابجایی فایل "%1" از سبد را دارید؟', BasketEmpty : 'هیچ فایلی در سبد نیست، یکی را بکشید و رها کنید.', BasketCopyFilesHere : 'کپی فایلها از سبد', BasketMoveFilesHere : 'جابجایی فایلها از سبد', BasketPasteErrorOther : 'خطای فایل %s: %e', BasketPasteMoveSuccess : 'فایلهای مقابل جابجا شدند: %s', BasketPasteCopySuccess : 'این فایلها کپی شدند: %s', // Toolbar Buttons (some used elsewhere) Upload : 'آپلود', UploadTip : 'آپلود فایل جدید', Refresh : 'بروزرسانی', Settings : 'تنظیمات', Help : 'راهنما', HelpTip : 'راهنما', // Context Menus Select : 'انتخاب', SelectThumbnail : 'انتخاب انگشتی', View : 'نمایش', Download : 'دانلود', NewSubFolder : 'زیرپوشه جدید', Rename : 'تغییر نام', Delete : 'حذف', CopyDragDrop : 'کپی فایل به اینجا', MoveDragDrop : 'انتقال فایل به اینجا', // Dialogs RenameDlgTitle : 'تغییر نام', NewNameDlgTitle : 'نام جدید', FileExistsDlgTitle : 'فایل از قبل وجود دارد', SysErrorDlgTitle : 'خطای سیستم', FileOverwrite : 'رونویسی', FileAutorename : 'تغییر نام خودکار', // Generic OkBtn : 'قبول', CancelBtn : 'لغو', CloseBtn : 'بستن', // Upload Panel UploadTitle : 'آپلود فایل جدید', UploadSelectLbl : 'انتخاب فابل برای آپلود', UploadProgressLbl : '(آپلود در حال انجام است، لطفا صبر کنید...)', UploadBtn : 'آپلود فایل انتخاب شده', UploadBtnCancel : 'لغو', UploadNoFileMsg : 'لطفا یک فایل از رایانه خود انتخاب کنید', UploadNoFolder : 'لطفا پیش از آپلود کردن یک پوشه انتخاب کنید.', UploadNoPerms : 'آپلود فایل مجاز نیست.', UploadUnknError : 'در حال ارسال خطای فایل.', UploadExtIncorrect : 'پسوند فایل برای این پوشه مجاز نیست.', // Flash Uploads UploadLabel : 'فایل برای آپلود', UploadTotalFiles : 'مجموع فایلها:', UploadTotalSize : 'مجموع حجم:', UploadAddFiles : 'افزودن فایلها', UploadClearFiles : 'پاک کردن فایلها', UploadCancel : 'لغو آپلود', UploadRemove : 'جابجا نمودن', UploadRemoveTip : '!f جابجایی', UploadUploaded : '!n% آپلود شد', UploadProcessing : 'در حال پردازش...', // Settings Panel SetTitle : 'تنظیمات', SetView : 'نمایش:', SetViewThumb : 'انگشتیها', SetViewList : 'فهرست', SetDisplay : 'نمایش:', SetDisplayName : 'نام فایل', SetDisplayDate : 'تاریخ', SetDisplaySize : 'اندازه فایل', SetSort : 'مرتبسازی:', SetSortName : 'با نام فایل', SetSortDate : 'با تاریخ', SetSortSize : 'با اندازه', // Status Bar FilesCountEmpty : '<پوشه خالی>', FilesCountOne : '1 فایل', FilesCountMany : '%1 فایل', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'امکان تکمیل درخواست وجود ندارد. (خطا %1)', Errors : { 10 : 'دستور نامعتبر.', 11 : 'نوع منبع در درخواست تعریف نشده است.', 12 : 'نوع منبع درخواست شده معتبر نیست.', 102 : 'نام فایل یا پوشه نامعتبر است.', 103 : 'امکان اجرای درخواست تا زمانیکه محدودیت مجوز وجود دارد، مقدور نیست.', 104 : 'امکان اجرای درخواست تا زمانیکه محدودیت مجوز سیستمی فایل وجود دارد،\u200bمقدور نیست.', 105 : 'پسوند فایل نامعتبر.', 109 : 'درخواست نامعتبر.', 110 : 'خطای ناشناخته.', 115 : 'یک فایل یا پوشه با همین نام از قبل وجود دارد.', 116 : 'پوشه یافت نشد. لطفا بروزرسانی کرده و مجددا تلاش کنید.', 117 : 'فایل یافت نشد. لطفا فهرست فایلها را بروزرسانی کرده و مجددا تلاش کنید.', 118 : 'منبع و مقصد مسیر یکی است.', 201 : 'یک فایل با همان نام از قبل موجود است. فایل آپلود شده به "%1" تغییر نام یافت.', 202 : 'فایل نامعتبر', 203 : 'فایل نامعتبر. اندازه فایل بیش از حد بزرگ است.', 204 : 'فایل آپلود شده خراب است.', 205 : 'هیچ پوشه موقتی برای آپلود فایل در سرور موجود نیست.', 206 : 'آپلود به دلایل امنیتی متوقف شد. فایل محتوی اطلاعات HTML است.', 207 : 'فایل آپلود شده به "%1" تغییر نام یافت.', 300 : 'جابجایی فایل(ها) ناموفق ماند.', 301 : 'کپی کردن فایل(ها) ناموفق ماند.', 500 : 'مرورگر فایل به دلایل امنیتی غیر فعال است. لطفا با مدیر سامانه تماس بگیرید تا تنظیمات این بخش را بررسی نماید.', 501 : 'پشتیبانی انگشتیها غیر فعال است.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'نام فایل نمیتواند خالی باشد', FileExists : 'فایل %s از قبل وجود دارد', FolderEmpty : 'نام پوشه نمیتواند خالی باشد', FileInvChar : 'نام فایل نمیتواند دارای نویسههای مقابل باشد: \n\\ / : * ? " < > |', FolderInvChar : 'نام پوشه نمیتواند دارای نویسههای مقابل باشد: \n\\ / : * ? " < > |', PopupBlockView : 'امکان بازگشایی فایل در پنجره جدید نیست. لطفا به بخش تنظیمات مرورگر خود مراجعه کنید و امکان بازگشایی پنجرههای بازشور را برای این سایت فعال کنید.', XmlError : 'امکان بارگیری صحیح پاسخ XML از سرور مقدور نیست.', XmlEmpty : 'امکان بارگیری صحیح پاسخ XML از سرور مقدور نیست. سرور پاسخ خالی بر میگرداند.', XmlRawResponse : 'پاسخ اولیه از سرور: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'تغییر اندازه %s', sizeTooBig : 'امکان تغییر مقادیر ابعاد طول و عرض تصویر به مقداری بیش از ابعاد اصلی ممکن نیست (%size).', resizeSuccess : 'تصویر با موفقیت تغییر اندازه یافت.', thumbnailNew : 'ایجاد انگشتی جدید', thumbnailSmall : 'کوچک (%s)', thumbnailMedium : 'متوسط (%s)', thumbnailLarge : 'بزرگ (%s)', newSize : 'تنظیم اندازه جدید', width : 'پهنا', height : 'ارتفاع', invalidHeight : 'ارتفاع نامعتبر.', invalidWidth : 'پهنا نامعتبر.', invalidName : 'نام فایل نامعتبر.', newImage : 'ایجاد تصویر جدید', noExtensionChange : 'نام پسوند فایل نمیتواند تغییر کند.', imageSmall : 'تصویر اصلی خیلی کوچک است', contextMenuName : 'تغییر اندازه', lockRatio : 'قفل کردن تناسب.', resetSize : 'بازنشانی اندازه.' }, // Fileeditor plugin Fileeditor : { save : 'ذخیره', fileOpenError : 'قادر به گشودن فایل نیست.', fileSaveSuccess : 'فایل با موفقیت ذخیره شد.', contextMenuName : 'ویرایش', loadingFile : 'در حال بارگیری فایل، لطفا صبر کنید...' }, Maximize : { maximize : 'حداکثر نمودن', minimize : 'حداقل نمودن' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Estonian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['et'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, pole saadaval</span>', confirmCancel : 'Mõned valikud on muudetud. Kas oled kindel, et tahad dialoogiakna sulgeda?', ok : 'Olgu', cancel : 'Loobu', confirmationTitle : 'Kinnitus', messageTitle : 'Andmed', inputTitle : 'Küsimus', undo : 'Võta tagasi', redo : 'Tee uuesti', skip : 'Jäta vahele', skipAll : 'Jäta kõik vahele', makeDecision : 'Mida tuleks teha?', rememberDecision: 'Jäta valik meelde' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'et', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'yyyy-mm-dd H:MM', DateAmPm : ['EL', 'PL'], // Folders FoldersTitle : 'Kaustad', FolderLoading : 'Laadimine...', FolderNew : 'Palun sisesta uue kataloogi nimi: ', FolderRename : 'Palun sisesta uue kataloogi nimi: ', FolderDelete : 'Kas tahad kindlasti kausta "%1" kustutada?', FolderRenaming : ' (ümbernimetamine...)', FolderDeleting : ' (kustutamine...)', // Files FileRename : 'Palun sisesta faili uus nimi: ', FileRenameExt : 'Kas oled kindel, et tahad faili laiendit muuta? Fail võib muutuda kasutamatuks.', FileRenaming : 'Ümbernimetamine...', FileDelete : 'Kas oled kindel, et tahad kustutada faili "%1"?', FilesLoading : 'Laadimine...', FilesEmpty : 'See kaust on tühi.', FilesMoved : 'Fail %1 liigutati kohta %2:%3.', FilesCopied : 'Fail %1 kopeeriti kohta %2:%3.', // Basket BasketFolder : 'Korv', BasketClear : 'Tühjenda korv', BasketRemove : 'Eemalda korvist', BasketOpenFolder : 'Ava ülemine kaust', BasketTruncateConfirm : 'Kas tahad tõesti eemaldada korvist kõik failid?', BasketRemoveConfirm : 'Kas tahad tõesti eemaldada korvist faili "%1"?', BasketEmpty : 'Korvis ei ole ühtegi faili, lohista mõni siia.', BasketCopyFilesHere : 'Failide kopeerimine korvist', BasketMoveFilesHere : 'Failide liigutamine korvist', BasketPasteErrorOther : 'Faili %s viga: %e', BasketPasteMoveSuccess : 'Järgnevad failid liigutati: %s', BasketPasteCopySuccess : 'Järgnevad failid kopeeriti: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Laadi üles', UploadTip : 'Laadi üles uus fail', Refresh : 'Värskenda', Settings : 'Sätted', Help : 'Abi', HelpTip : 'Abi', // Context Menus Select : 'Vali', SelectThumbnail : 'Vali pisipilt', View : 'Kuva', Download : 'Laadi alla', NewSubFolder : 'Uus alamkaust', Rename : 'Nimeta ümber', Delete : 'Kustuta', CopyDragDrop : 'Kopeeri fail siia', MoveDragDrop : 'Liiguta fail siia', // Dialogs RenameDlgTitle : 'Ümbernimetamine', NewNameDlgTitle : 'Uue nime andmine', FileExistsDlgTitle : 'Fail on juba olemas', SysErrorDlgTitle : 'Süsteemi viga', FileOverwrite : 'Kirjuta üle', FileAutorename : 'Nimeta automaatselt ümber', // Generic OkBtn : 'Olgu', CancelBtn : 'Loobu', CloseBtn : 'Sulge', // Upload Panel UploadTitle : 'Uue faili üleslaadimine', UploadSelectLbl : 'Vali üleslaadimiseks fail', UploadProgressLbl : '(Üleslaadimine, palun oota...)', UploadBtn : 'Laadi valitud fail üles', UploadBtnCancel : 'Loobu', UploadNoFileMsg : 'Palun vali fail oma arvutist.', UploadNoFolder : 'Palun vali enne üleslaadimist kataloog.', UploadNoPerms : 'Failide üleslaadimine pole lubatud.', UploadUnknError : 'Viga faili saatmisel.', UploadExtIncorrect : 'Selline faili laiend pole selles kaustas lubatud.', // Flash Uploads UploadLabel : 'Üleslaaditavad failid', UploadTotalFiles : 'Faile kokku:', UploadTotalSize : 'Kogusuurus:', UploadAddFiles : 'Lisa faile', UploadClearFiles : 'Eemalda failid', UploadCancel : 'Katkesta üleslaadimine', UploadRemove : 'Eemalda', UploadRemoveTip : 'Eemalda !f', UploadUploaded : '!n% üles laaditud', UploadProcessing : 'Töötlemine...', // Settings Panel SetTitle : 'Sätted', SetView : 'Vaade:', SetViewThumb : 'Pisipildid', SetViewList : 'Loend', SetDisplay : 'Kuva:', SetDisplayName : 'Faili nimi', SetDisplayDate : 'Kuupäev', SetDisplaySize : 'Faili suurus', SetSort : 'Sortimine:', SetSortName : 'faili nime järgi', SetSortDate : 'kuupäeva järgi', SetSortSize : 'suuruse järgi', // Status Bar FilesCountEmpty : '<tühi kaust>', FilesCountOne : '1 fail', FilesCountMany : '%1 faili', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Päringu täitmine ei olnud võimalik. (Viga %1)', Errors : { 10 : 'Vigane käsk.', 11 : 'Allika liik ei olnud päringus määratud.', 12 : 'Päritud liik ei ole sobiv.', 102 : 'Sobimatu faili või kausta nimi.', 103 : 'Piiratud õiguste tõttu ei olnud võimalik päringut lõpetada.', 104 : 'Failisüsteemi piiratud õiguste tõttu ei olnud võimalik päringut lõpetada.', 105 : 'Sobimatu faililaiend.', 109 : 'Vigane päring.', 110 : 'Tundmatu viga.', 115 : 'Sellenimeline fail või kaust on juba olemas.', 116 : 'Kausta ei leitud. Palun värskenda lehte ja proovi uuesti.', 117 : 'Faili ei leitud. Palun värskenda lehte ja proovi uuesti.', 118 : 'Lähte- ja sihtasukoht on sama.', 201 : 'Samanimeline fail on juba olemas. Üles laaditud faili nimeks pandi "%1".', 202 : 'Vigane fail.', 203 : 'Vigane fail. Fail on liiga suur.', 204 : 'Üleslaaditud fail on rikutud.', 205 : 'Serverisse üleslaadimiseks pole ühtegi ajutiste failide kataloogi.', 206 : 'Üleslaadimine katkestati turvakaalutlustel. Fail sisaldab HTMLi sarnaseid andmeid.', 207 : 'Üleslaaditud faili nimeks pandi "%1".', 300 : 'Faili(de) liigutamine nurjus.', 301 : 'Faili(de) kopeerimine nurjus.', 500 : 'Failide sirvija on turvakaalutlustel keelatud. Palun võta ühendust oma süsteemi administraatoriga ja kontrolli CKFinderi seadistusfaili.', 501 : 'Pisipiltide tugi on keelatud.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Faili nimi ei tohi olla tühi.', FileExists : 'Fail nimega %s on juba olemas.', FolderEmpty : 'Kausta nimi ei tohi olla tühi.', FileInvChar : 'Faili nimi ei tohi sisaldada ühtegi järgnevatest märkidest: \n\\ / : * ? " < > |', FolderInvChar : 'Faili nimi ei tohi sisaldada ühtegi järgnevatest märkidest: \n\\ / : * ? " < > |', PopupBlockView : 'Faili avamine uues aknas polnud võimalik. Palun seadista oma brauserit ning keela kõik hüpikakende blokeerijad selle saidi jaoks.', XmlError : 'XML vastust veebiserverist polnud võimalik korrektselt laadida.', XmlEmpty : 'XML vastust veebiserverist polnud võimalik korrektselt laadida. Serveri vastus oli tühi.', XmlRawResponse : 'Serveri vastus toorkujul: %s' }, // Imageresize plugin Imageresize : { dialogTitle : '%s suuruse muutmine', sizeTooBig : 'Pildi kõrgust ega laiust ei saa määrata suuremaks pildi esialgsest vastavast mõõtmest (%size).', resizeSuccess : 'Pildi suuruse muutmine õnnestus.', thumbnailNew : 'Tee uus pisipilt', thumbnailSmall : 'Väike (%s)', thumbnailMedium : 'Keskmine (%s)', thumbnailLarge : 'Suur (%s)', newSize : 'Määra uus suurus', width : 'Laius', height : 'Kõrgus', invalidHeight : 'Sobimatu kõrgus.', invalidWidth : 'Sobimatu laius.', invalidName : 'Sobimatu faili nimi.', newImage : 'Loo uus pilt', noExtensionChange : 'Faili laiendit pole võimalik muuta.', imageSmall : 'Lähtepilt on liiga väike.', contextMenuName : 'Muuda suurust', lockRatio : 'Lukusta külgede suhe', resetSize : 'Lähtesta suurus' }, // Fileeditor plugin Fileeditor : { save : 'Salvesta', fileOpenError : 'Faili avamine pole võimalik.', fileSaveSuccess : 'Faili salvestamine õnnestus.', contextMenuName : 'Muuda', loadingFile : 'Faili laadimine, palun oota...' }, Maximize : { maximize : 'Maksimeeri', minimize : 'Minimeeri' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Latvian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['lv'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?', // MISSING ok : 'Darīts!', cancel : 'Atcelt', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Atcelt', redo : 'Atkārtot', skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'lv', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy H:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Mapes', FolderLoading : 'Ielādē...', FolderNew : 'Lūdzu ierakstiet mapes nosaukumu: ', FolderRename : 'Lūdzu ierakstiet jauno mapes nosaukumu: ', FolderDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst mapi "%1"?', FolderRenaming : ' (Pārsauc...)', FolderDeleting : ' (Dzēš...)', // Files FileRename : 'Lūdzu ierakstiet jauno faila nosaukumu: ', FileRenameExt : 'Vai tiešām vēlaties mainīt faila paplašinājumu? Fails var palikt nelietojams.', FileRenaming : 'Pārsauc...', FileDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst failu "%1"?', FilesLoading : 'Ielādē...', FilesEmpty : 'The folder is empty.', // MISSING FilesMoved : 'File %1 moved to %2:%3.', // MISSING FilesCopied : 'File %1 copied to %2:%3.', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from Basket', // MISSING BasketOpenFolder : 'Open Parent Folder', // MISSING BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING BasketPasteErrorOther : 'File %s error: %e', // MISSING BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Augšupielādēt', UploadTip : 'Augšupielādēt jaunu failu', Refresh : 'Pārlādēt', Settings : 'Uzstādījumi', Help : 'Palīdzība', HelpTip : 'Palīdzība', // Context Menus Select : 'Izvēlēties', SelectThumbnail : 'Izvēlēties sīkbildi', View : 'Skatīt', Download : 'Lejupielādēt', NewSubFolder : 'Jauna apakšmape', Rename : 'Pārsaukt', Delete : 'Dzēst', CopyDragDrop : 'Copy File Here', // MISSING MoveDragDrop : 'Move File Here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New Name', // MISSING FileExistsDlgTitle : 'File Already Exists', // MISSING SysErrorDlgTitle : 'System Error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'Labi', CancelBtn : 'Atcelt', CloseBtn : 'Aizvērt', // Upload Panel UploadTitle : 'Jauna faila augšupielādēšana', UploadSelectLbl : 'Izvēlaties failu, ko augšupielādēt', UploadProgressLbl : '(Augšupielādē, lūdzu uzgaidiet...)', UploadBtn : 'Augšupielādēt izvēlēto failu', UploadBtnCancel : 'Atcelt', UploadNoFileMsg : 'Lūdzu izvēlaties failu no sava datora.', UploadNoFolder : 'Please select a folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Flash Uploads UploadLabel : 'Files to Upload', // MISSING UploadTotalFiles : 'Total Files:', // MISSING UploadTotalSize : 'Total Size:', // MISSING UploadAddFiles : 'Add Files', // MISSING UploadClearFiles : 'Clear Files', // MISSING UploadCancel : 'Cancel Upload', // MISSING UploadRemove : 'Remove', // MISSING UploadRemoveTip : 'Remove !f', // MISSING UploadUploaded : 'Uploaded !n%', // MISSING UploadProcessing : 'Processing...', // MISSING // Settings Panel SetTitle : 'Uzstādījumi', SetView : 'Attēlot:', SetViewThumb : 'Sīkbildes', SetViewList : 'Failu Sarakstu', SetDisplay : 'Rādīt:', SetDisplayName : 'Faila Nosaukumu', SetDisplayDate : 'Datumu', SetDisplaySize : 'Faila Izmēru', SetSort : 'Kārtot:', SetSortName : 'pēc Faila Nosaukuma', SetSortDate : 'pēc Datuma', SetSortSize : 'pēc Izmēra', // Status Bar FilesCountEmpty : '<Tukša mape>', FilesCountOne : '1 fails', FilesCountMany : '%1 faili', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Nebija iespējams pabeigt pieprasījumu. (Kļūda %1)', Errors : { 10 : 'Nederīga komanda.', 11 : 'Resursa veids netika norādīts pieprasījumā.', 12 : 'Pieprasītais resursa veids nav derīgs.', 102 : 'Nederīgs faila vai mapes nosaukums.', 103 : 'Nav iespējams pabeigt pieprasījumu, autorizācijas aizliegumu dēļ.', 104 : 'Nav iespējams pabeigt pieprasījumu, failu sistēmas atļauju ierobežojumu dēļ.', 105 : 'Neatļauts faila paplašinājums.', 109 : 'Nederīgs pieprasījums.', 110 : 'Nezināma kļūda.', 115 : 'Fails vai mape ar šādu nosaukumu jau pastāv.', 116 : 'Mape nav atrasta. Lūdzu pārlādējiet šo logu un mēģiniet vēlreiz.', 117 : 'Fails nav atrasts. Lūdzu pārlādējiet failu sarakstu un mēģiniet vēlreiz.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Fails ar šādu nosaukumu jau eksistē. Augšupielādētais fails tika pārsaukts par "%1".', 202 : 'Nederīgs fails.', 203 : 'Nederīgs fails. Faila izmērs pārsniedz pieļaujamo.', 204 : 'Augšupielādētais fails ir bojāts.', 205 : 'Neviena pagaidu mape nav pieejama priekš augšupielādēšanas uz servera.', 206 : 'Augšupielāde atcelta drošības apsvērumu dēļ. Fails satur HTML veida datus.', 207 : 'Augšupielādētais fails tika pārsaukts par "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Failu pārlūks ir atslēgts drošības apsvērumu dēļ. Lūdzu sazinieties ar šīs sistēmas tehnisko administratoru vai pārbaudiet CKFinder konfigurācijas failu.', 501 : 'Sīkbilžu atbalsts ir atslēgts.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Faila nosaukumā nevar būt tukšums.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Mapes nosaukumā nevar būt tukšums.', FileInvChar : 'Faila nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |', FolderInvChar : 'Mapes nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |', PopupBlockView : 'Nav iespējams failu atvērt jaunā logā. Lūdzu veiciet izmaiņas uzstādījumos savai interneta pārlūkprogrammai un izslēdziet visus uznirstošo logu bloķētājus šai adresei.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create a new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set a new size', // MISSING width : 'Platums', height : 'Augstums', invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create a new image', // MISSING noExtensionChange : 'File extension cannot be changed.', // MISSING imageSmall : 'Source image is too small.', // MISSING contextMenuName : 'Resize', // MISSING lockRatio : 'Nemainīga Augstuma/Platuma attiecība', resetSize : 'Atjaunot sākotnējo izmēru' }, // Fileeditor plugin Fileeditor : { save : 'Saglabāt', fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING }, Maximize : { maximize : 'Maximize', // MISSING minimize : 'Minimize' // MISSING } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object, for the English * language. This is the base file for all translations. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['he'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, לא זמין</span>', confirmCancel : 'חלק מהאפשרויות שונו. האם לסגור את החלון?', ok : 'אישור', cancel : 'ביטול', confirmationTitle : 'אישור', messageTitle : 'הודעה', inputTitle : 'שאלה', undo : 'לבטל', redo : 'לעשות שוב', skip : 'דלג', skipAll : 'דלג הכל', makeDecision : 'איזו פעולה לבצע?', rememberDecision: 'זכור החלטתי' }, // Language direction, 'ltr' or 'rtl'. dir : 'rtl', HelpLang : 'en', LangCode : 'he', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'm/d/yyyy h:MM aa', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'תיקיות', FolderLoading : 'טוען...', FolderNew : 'יש להקליד שם חדש לתיקיה: ', FolderRename : 'יש להקליד שם חדש לתיקיה: ', FolderDelete : 'האם למחוק את התיקיה "%1" ?', FolderRenaming : ' (משנה שם...)', FolderDeleting : ' (מוחק...)', // Files FileRename : 'יש להקליד שם חדש לקובץ: ', FileRenameExt : 'האם לשנות את הסיומת של הקובץ?', FileRenaming : 'משנה שם...', FileDelete : 'האם למחוק את הקובץ "%1"?', FilesLoading : 'טוען...', FilesEmpty : 'תיקיה ריקה', FilesMoved : 'קובץ %1 הוזז ל- %2:%3', FilesCopied : 'קובץ %1 הועתק ל- %2:%3', // Basket BasketFolder : 'סל קבצים', BasketClear : 'ניקוי סל הקבצים', BasketRemove : 'מחיקה מסל הקבצים', BasketOpenFolder : 'פתיחת תיקיית אב', BasketTruncateConfirm : 'האם למחוק את כל הקבצים מסל הקבצים?', BasketRemoveConfirm : 'האם למחוק את הקובץ "%1" מסל הקבצים?', BasketEmpty : 'אין קבצים בסל הקבצים, יש לגרור לכאן קובץ.', BasketCopyFilesHere : 'העתקת קבצים מסל הקבצים', BasketMoveFilesHere : 'הזזת קבצים מסל הקבצים', BasketPasteErrorOther : 'שגיאה %e בקובץ %s', BasketPasteMoveSuccess : 'הקבצים הבאים הוזזו: %s', BasketPasteCopySuccess : 'הקבצים הבאים הועתקו: %s', // Toolbar Buttons (some used elsewhere) Upload : 'העלאה', UploadTip : 'העלאת קובץ חדש', Refresh : 'ריענון', Settings : 'הגדרות', Help : 'עזרה', HelpTip : 'עזרה', // Context Menus Select : 'בחירה', SelectThumbnail : 'בחירת תמונה מוקטנת', View : 'צפיה', Download : 'הורדה', NewSubFolder : 'תת-תיקיה חדשה', Rename : 'שינוי שם', Delete : 'מחיקה', CopyDragDrop : 'העתקת קבצים לכאן', MoveDragDrop : 'הזזת קבצים לכאן', // Dialogs RenameDlgTitle : 'שינוי שם', NewNameDlgTitle : 'שם חדש', FileExistsDlgTitle : 'קובץ זה כבר קיים', SysErrorDlgTitle : 'שגיאת מערכת', FileOverwrite : 'החלפה', FileAutorename : 'שינוי שם אוטומטי', // Generic OkBtn : 'אישור', CancelBtn : 'ביטול', CloseBtn : 'סגור', // Upload Panel UploadTitle : 'העלאת קובץ חדש', UploadSelectLbl : 'בחירת קובץ להעלאה', UploadProgressLbl : '(העלאה מתבצעת, נא להמתין...)', UploadBtn : 'העלאת קובץ', UploadBtnCancel : 'ביטול', UploadNoFileMsg : 'יש לבחור קובץ מהמחשב', UploadNoFolder : 'יש לבחור תיקיה לפני ההעלאה.', UploadNoPerms : 'העלאת קובץ אסורה.', UploadUnknError : 'שגיאה בשליחת הקובץ.', UploadExtIncorrect : 'סוג קובץ זה לא מאושר בתיקיה זאת.', // Flash Uploads UploadLabel : 'להעלאה קבצים', UploadTotalFiles : ':קבצים כמות', UploadTotalSize : ':סופי גודל', UploadAddFiles : 'קבצים הוספת', UploadClearFiles : 'קבצים ניקוי', UploadCancel : 'העלאה ביטול', UploadRemove : 'מחיקה', UploadRemoveTip : '!f הקובץ מחיקת', UploadUploaded : 'הועלו !n%', UploadProcessing : 'מעבד...', // Settings Panel SetTitle : 'הגדרות', SetView : 'צפיה:', SetViewThumb : 'תמונות מוקטנות', SetViewList : 'רשימה', SetDisplay : 'תצוגה:', SetDisplayName : 'שם קובץ', SetDisplayDate : 'תאריך', SetDisplaySize : 'גודל קובץ', SetSort : 'מיון:', SetSortName : 'לפי שם', SetSortDate : 'לפי תאריך', SetSortSize : 'לפי גודל', // Status Bar FilesCountEmpty : '<תיקיה ריקה>', FilesCountOne : 'קובץ 1', FilesCountMany : '%1 קבצים', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'לא היה ניתן להשלים את הבקשה. (שגיאה %1)', Errors : { 10 : 'הוראה לא תקינה.', 11 : 'סוג המשאב לא צויין בבקשה.', 12 : 'סוג המשאב המצויין לא תקין.', 102 : 'שם קובץ או תיקיה לא תקין.', 103 : 'לא היה ניתן להשלים את הבקשב בשל הרשאות מוגבלות.', 104 : 'לא היה ניתן להשלים את הבקשב בשל הרשאות מערכת קבצים מוגבלות.', 105 : 'סיומת קובץ לא תקינה.', 109 : 'בקשה לא תקינה.', 110 : 'שגיאה לא ידועה.', 115 : 'קובץ או תיקיה באותו שם כבר קיימ/ת.', 116 : 'התיקיה לא נמצאה. נא לרענן ולנסות שוב.', 117 : 'הקובץ לא נמצא. נא לרענן ולנסות שוב.', 118 : 'כתובות המקור והיעד זהות.', 201 : 'קובץ עם אותו השם כבר קיים. שם הקובץ שהועלה שונה ל "%1"', 202 : 'קובץ לא תקין', 203 : 'קובץ לא תקין. גודל הקובץ גדול מדי.', 204 : 'הקובץ המועלה לא תקין', 205 : 'תיקיה זמנית להעלאה לא קיימת בשרת.', 206 : 'העלאה בוטלה מסיבות אבטחה. הקובץ מכיל תוכן שדומה ל-HTML.', 207 : 'שם הקובץ שהועלה שונה ל "%1"', 300 : 'העברת הקבצים נכשלה.', 301 : 'העתקת הקבצים נכשלה.', 500 : 'דפדפן הקבצים מנוטרל מסיבות אבטחה. יש לפנות למנהל המערכת ולבדוק את קובץ התצורה של CKFinder.', 501 : 'התמיכה בתמונות מוקטנות מבוטלת.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'שם הקובץ לא יכול להיות ריק', FileExists : 'הקובץ %s כבר קיים', FolderEmpty : 'שם התיקיה לא יכול להיות ריק', FileInvChar : 'שם הקובץ לא יכול לכלול תווים הבאים: \n\\ / : * ? " < > |', FolderInvChar : 'שם התיקיה לא יכול לכלול תווים הבאים: \n\\ / : * ? " < > |', PopupBlockView : 'לא היה ניתן לפתוח קובץ בחלון חדש. נא לבדוק את הגדרות הדפדפן ולבטל את חוסמי החלונות הקובצים.', XmlError : 'לא היה ניתן לטעון מהשרת כהלכה את קובץ ה-XML.', XmlEmpty : 'לא היה ניתן לטעון מהשרת את קובץ ה-XML. השרת החזיר תגובה ריקה.', XmlRawResponse : 'תגובה גולמית מהשרת: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'שינוי גודל התמונה %s', sizeTooBig : 'גובה ורוחב התמונה לא יכולים להיות גדולים מהגודל המקורי שלה (%size).', resizeSuccess : 'גודל התמונה שונה שהצלחה.', thumbnailNew : 'יצירת תמונה מוקטנת (Thumbnail)', thumbnailSmall : 'קטנה (%s)', thumbnailMedium : 'בינונית (%s)', thumbnailLarge : 'גדולה (%s)', newSize : 'קביעת גודל חדש', width : 'רוחב', height : 'גובה', invalidHeight : 'גובה לא חוקי.', invalidWidth : 'רוחב לא חוקי.', invalidName : 'שם הקובץ לא חוקי.', newImage : 'יצירת תמונה חדשה', noExtensionChange : 'לא ניתן לשנות את סוג הקובץ.', imageSmall : 'התמונה המקורית קטנה מדי', contextMenuName : 'שינוי גודל', lockRatio : 'נעילת היחס', resetSize : 'איפוס הגודל' }, // Fileeditor plugin Fileeditor : { save : 'שמירה', fileOpenError : 'לא היה ניתן לפתוח את הקובץ.', fileSaveSuccess : 'הקובץ נשמר בהצלחה.', contextMenuName : 'עריכה', loadingFile : 'טוען קובץ, נא להמתין...' }, Maximize : { maximize : 'הגדלה למקסימום', minimize : 'הקטנה למינימום' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Slovenian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['sl'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nedostopen</span>', confirmCancel : 'Nekatere opcije so bile spremenjene. Ali res želite zapreti pogovorno okno?', ok : 'Potrdi', cancel : 'Prekliči', confirmationTitle : 'Potrditev', messageTitle : 'Informacija', inputTitle : 'Vprašanje', undo : 'Razveljavi', redo : 'Obnovi', skip : 'Preskoči', skipAll : 'Preskoči vse', makeDecision : 'Katera aktivnost naj se izvede?', rememberDecision: 'Zapomni si mojo izbiro' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'sl', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'd.m.yyyy H:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Mape', FolderLoading : 'Nalagam...', FolderNew : 'Vnesite ime za novo mapo: ', FolderRename : 'Vnesite ime nove mape: ', FolderDelete : 'Ali ste prepričani, da želite zbrisati mapo "%1"?', FolderRenaming : ' (Preimenujem...)', FolderDeleting : ' (Brišem...)', // Files FileRename : 'Vnesite novo ime datoteke: ', FileRenameExt : 'Ali ste prepričani, da želite spremeniti končnico datoteke? Možno je, da potem datoteka ne bo uporabna.', FileRenaming : 'Preimenujem...', FileDelete : 'Ali ste prepričani, da želite izbrisati datoteko "%1"?', FilesLoading : 'Nalagam...', FilesEmpty : 'Prazna mapa', FilesMoved : 'Datoteka %1 je bila premaknjena v %2:%3.', FilesCopied : 'Datoteka %1 je bila kopirana v %2:%3.', // Basket BasketFolder : 'Koš', BasketClear : 'Izprazni koš', BasketRemove : 'Odstrani iz koša', BasketOpenFolder : 'Odpri izvorno mapo', BasketTruncateConfirm : 'Ali res želite odstraniti vse datoteke iz koša?', BasketRemoveConfirm : 'Ali res želite odstraniti datoteko "%1" iz koša?', BasketEmpty : 'V košu ni datotek. Lahko jih povlečete in spustite.', BasketCopyFilesHere : 'Kopiraj datoteke iz koša', BasketMoveFilesHere : 'Premakni datoteke iz koša', BasketPasteErrorOther : 'Napaka z datoteko %s: %e', BasketPasteMoveSuccess : 'Seznam premaknjenih datotek: %s', BasketPasteCopySuccess : 'Seznam kopiranih datotek: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Naloži na strežnik', UploadTip : 'Naloži novo datoteko na strežnik', Refresh : 'Osveži', Settings : 'Nastavitve', Help : 'Pomoč', HelpTip : 'Pomoč', // Context Menus Select : 'Izberi', SelectThumbnail : 'Izberi malo sličico (predogled)', View : 'Predogled', Download : 'Prenesi na svoj računalnik', NewSubFolder : 'Nova podmapa', Rename : 'Preimenuj', Delete : 'Zbriši', CopyDragDrop : 'Kopiraj datoteko', MoveDragDrop : 'Premakni datoteko', // Dialogs RenameDlgTitle : 'Preimenuj', NewNameDlgTitle : 'Novo ime', FileExistsDlgTitle : 'Datoteka že obstaja', SysErrorDlgTitle : 'Sistemska napaka', FileOverwrite : 'Prepiši', FileAutorename : 'Avtomatsko preimenuj', // Generic OkBtn : 'Potrdi', CancelBtn : 'Prekliči', CloseBtn : 'Zapri', // Upload Panel UploadTitle : 'Naloži novo datoteko na strežnik', UploadSelectLbl : 'Izberi datoteko za prenos na strežnik', UploadProgressLbl : '(Prenos na strežnik poteka, prosimo počakajte...)', UploadBtn : 'Prenesi izbrano datoteko na strežnik', UploadBtnCancel : 'Prekliči', UploadNoFileMsg : 'Prosimo izberite datoteko iz svojega računalnika za prenos na strežnik.', UploadNoFolder : 'Izberite mapo v katero se bo naložilo datoteko!', UploadNoPerms : 'Nalaganje datotek ni dovoljeno.', UploadUnknError : 'Napaka pri pošiljanju datoteke.', UploadExtIncorrect : 'V tej mapi ta vrsta datoteke ni dovoljena.', // Flash Uploads UploadLabel : 'Files to Upload', // MISSING UploadTotalFiles : 'Total Files:', // MISSING UploadTotalSize : 'Total Size:', // MISSING UploadAddFiles : 'Add Files', // MISSING UploadClearFiles : 'Clear Files', // MISSING UploadCancel : 'Cancel Upload', // MISSING UploadRemove : 'Remove', // MISSING UploadRemoveTip : 'Remove !f', // MISSING UploadUploaded : 'Uploaded !n%', // MISSING UploadProcessing : 'Processing...', // MISSING // Settings Panel SetTitle : 'Nastavitve', SetView : 'Pogled:', SetViewThumb : 'majhne sličice', SetViewList : 'seznam', SetDisplay : 'Prikaz:', SetDisplayName : 'ime datoteke', SetDisplayDate : 'datum', SetDisplaySize : 'velikost datoteke', SetSort : 'Razvrščanje:', SetSortName : 'po imenu datoteke', SetSortDate : 'po datumu', SetSortSize : 'po velikosti', // Status Bar FilesCountEmpty : '<Prazna mapa>', FilesCountOne : '1 datoteka', FilesCountMany : '%1 datotek(e)', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/sek', // Connector Error Messages. ErrorUnknown : 'Prišlo je do napake. (Napaka %1)', Errors : { 10 : 'Napačen ukaz.', 11 : 'V poizvedbi ni bil jasen tip (resource type).', 12 : 'Tip datoteke ni primeren.', 102 : 'Napačno ime mape ali datoteke.', 103 : 'Vašega ukaza se ne da izvesti zaradi težav z avtorizacijo.', 104 : 'Vašega ukaza se ne da izvesti zaradi težav z nastavitvami pravic v datotečnem sistemu.', 105 : 'Napačna končnica datoteke.', 109 : 'Napačna zahteva.', 110 : 'Neznana napaka.', 115 : 'Datoteka ali mapa s tem imenom že obstaja.', 116 : 'Mapa ni najdena. Prosimo osvežite okno in poskusite znova.', 117 : 'Datoteka ni najdena. Prosimo osvežite seznam datotek in poskusite znova.', 118 : 'Začetna in končna pot je ista.', 201 : 'Datoteka z istim imenom že obstaja. Naložena datoteka je bila preimenovana v "%1".', 202 : 'Neprimerna datoteka.', 203 : 'Datoteka je prevelika in zasede preveč prostora.', 204 : 'Naložena datoteka je okvarjena.', 205 : 'Na strežniku ni na voljo začasna mapa za prenos datotek.', 206 : 'Nalaganje je bilo prekinjeno zaradi varnostnih razlogov. Datoteka vsebuje podatke, ki spominjajo na HTML kodo.', 207 : 'Naložena datoteka je bila preimenovana v "%1".', 300 : 'Premikanje datotek(e) ni uspelo.', 301 : 'Kopiranje datotek(e) ni uspelo.', 500 : 'Brskalnik je onemogočen zaradi varnostnih razlogov. Prosimo kontaktirajte upravljalca spletnih strani.', 501 : 'Ni podpore za majhne sličice (predogled).' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Ime datoteke ne more biti prazno.', FileExists : 'Datoteka %s že obstaja.', FolderEmpty : 'Mapa ne more biti prazna.', FileInvChar : 'Ime datoteke ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |', FolderInvChar : 'Ime mape ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |', PopupBlockView : 'Datoteke ni možno odpreti v novem oknu. Prosimo nastavite svoj brskalnik tako, da bo dopuščal odpiranje oken (popups) oz. izklopite filtre za blokado odpiranja oken.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Spremeni velikost slike %s', sizeTooBig : 'Širina ali višina slike ne moreta biti večji kot je originalna velikost (%size).', resizeSuccess : 'Velikost slike je bila uspešno spremenjena.', thumbnailNew : 'Kreiraj novo majhno sličico', thumbnailSmall : 'majhna (%s)', thumbnailMedium : 'srednja (%s)', thumbnailLarge : 'velika (%s)', newSize : 'Določite novo velikost', width : 'Širina', height : 'Višina', invalidHeight : 'Nepravilna višina.', invalidWidth : 'Nepravilna širina.', invalidName : 'Nepravilno ime datoteke.', newImage : 'Kreiraj novo sliko', noExtensionChange : 'Končnica datoteke se ne more spremeniti.', imageSmall : 'Izvorna slika je premajhna.', contextMenuName : 'Spremeni velikost', lockRatio : 'Zakleni razmerje', resetSize : 'Ponastavi velikost' }, // Fileeditor plugin Fileeditor : { save : 'Shrani', fileOpenError : 'Datoteke ni mogoče odpreti.', fileSaveSuccess : 'Datoteka je bila shranjena.', contextMenuName : 'Uredi', loadingFile : 'Nalaganje datoteke, prosimo počakajte ...' }, Maximize : { maximize : 'Maksimiraj', minimize : 'Minimiraj' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Czech * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['cs'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nedostupné</span>', confirmCancel : 'Některá z nastavení byla změněna. Skutečně chete zavřít dialogové okno?', ok : 'OK', cancel : 'Zrušit', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Zpět', redo : 'Znovu', skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'cs', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'm/d/yyyy h:MM aa', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Složky', FolderLoading : 'Načítání...', FolderNew : 'Zadejte jméno nové složky: ', FolderRename : 'Zadejte nové jméno složky: ', FolderDelete : 'Opravdu chcete smazat složku "%1"?', FolderRenaming : ' (Přejmenovávám...)', FolderDeleting : ' (Mažu...)', // Files FileRename : 'Zadejte jméno novéhho souboru: ', FileRenameExt : 'Opravdu chcete změnit příponu souboru, může se stát nečitelným.', FileRenaming : 'Přejmenovávám...', FileDelete : 'Opravdu chcete smazat soubor "%1"?', FilesLoading : 'Načítání...', FilesEmpty : 'Prázdná složka.', FilesMoved : 'File %1 moved to %2:%3.', // MISSING FilesCopied : 'File %1 copied to %2:%3.', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from Basket', // MISSING BasketOpenFolder : 'Open Parent Folder', // MISSING BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING BasketPasteErrorOther : 'File %s error: %e', // MISSING BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Nahrát', UploadTip : 'Nahrát nový soubor', Refresh : 'Načíst znova', Settings : 'Nastavení', Help : 'Pomoc', HelpTip : 'Pomoc', // Context Menus Select : 'Vybrat', SelectThumbnail : 'Vybrat náhled', View : 'Zobrazit', Download : 'Uložit jako', NewSubFolder : 'Nová podsložka', Rename : 'Přejmenovat', Delete : 'Smazat', CopyDragDrop : 'Copy File Here', // MISSING MoveDragDrop : 'Move File Here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New Name', // MISSING FileExistsDlgTitle : 'File Already Exists', // MISSING SysErrorDlgTitle : 'System Error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Zrušit', CloseBtn : 'Zavřít', // Upload Panel UploadTitle : 'Nahrát nový soubor', UploadSelectLbl : 'Zvolit soubor k nahrání', UploadProgressLbl : '(Nahrávám, čekejte...)', UploadBtn : 'Nahrát zvolený soubor', UploadBtnCancel : 'Zrušit', UploadNoFileMsg : 'Vyberte prosím soubor.', UploadNoFolder : 'Please select a folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Flash Uploads UploadLabel : 'Files to Upload', // MISSING UploadTotalFiles : 'Total Files:', // MISSING UploadTotalSize : 'Total Size:', // MISSING UploadAddFiles : 'Add Files', // MISSING UploadClearFiles : 'Clear Files', // MISSING UploadCancel : 'Cancel Upload', // MISSING UploadRemove : 'Remove', // MISSING UploadRemoveTip : 'Remove !f', // MISSING UploadUploaded : 'Uploaded !n%', // MISSING UploadProcessing : 'Processing...', // MISSING // Settings Panel SetTitle : 'Nastavení', SetView : 'Zobrazení:', SetViewThumb : 'Náhledy', SetViewList : 'Seznam', SetDisplay : 'Informace:', SetDisplayName : 'Název', SetDisplayDate : 'Datum', SetDisplaySize : 'Velikost', SetSort : 'Seřazení:', SetSortName : 'Podle jména', SetSortDate : 'Podle data', SetSortSize : 'Podle velikosti', // Status Bar FilesCountEmpty : '<Prázdná složka>', FilesCountOne : '1 soubor', FilesCountMany : '%1 soubor', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Nebylo možno dokončit příkaz. (Error %1)', Errors : { 10 : 'Neplatný příkaz.', 11 : 'Požadovaný typ prostředku nebyl specifikován v dotazu.', 12 : 'Požadovaný typ prostředku není validní.', 102 : 'Šatné jméno souboru, nebo složky.', 103 : 'Nebylo možné dokončit příkaz kvůli autorizačním omezením.', 104 : 'Nebylo možné dokončit příkaz kvůli omezeným přístupovým právům k souborům.', 105 : 'Špatná přípona souboru.', 109 : 'Neplatný příkaz.', 110 : 'Neznámá chyba.', 115 : 'Již existuje soubor nebo složka se stejným jménem.', 116 : 'Složka nenalezena, prosím obnovte stránku.', 117 : 'Soubor nenalezen, prosím obnovte stránku.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Již existoval soubor se stejným jménem, nahraný soubor byl přejmenován na "%1".', 202 : 'Špatný soubor.', 203 : 'Špatný soubor. Příliš velký.', 204 : 'Nahraný soubor je poškozen.', 205 : 'Na serveru není dostupná dočasná složka.', 206 : 'Nahrávání zrušeno z bezpečnostních důvodů. Soubor obsahuje data podobná HTML.', 207 : 'Nahraný soubor byl přejmenován na "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Nahrávání zrušeno z bezpečnostních důvodů. Zdělte to prosím administrátorovi a zkontrolujte nastavení CKFinderu.', 501 : 'Podpora náhledů je vypnuta.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Název souboru nemůže být prázdný.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Název složky nemůže být prázdný.', FileInvChar : 'Název souboru nesmí obsahovat následující znaky: \n\\ / : * ? " < > |', FolderInvChar : 'Název složky nesmí obsahovat následující znaky: \n\\ / : * ? " < > |', PopupBlockView : 'Nebylo možné otevřít soubor do nového okna. Prosím nastavte si prohlížeč aby neblokoval vyskakovací okna.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create a new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set a new size', // MISSING width : 'Šířka', height : 'Výška', invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create a new image', // MISSING noExtensionChange : 'File extension cannot be changed.', // MISSING imageSmall : 'Source image is too small.', // MISSING contextMenuName : 'Resize', // MISSING lockRatio : 'Zámek', resetSize : 'Původní velikost' }, // Fileeditor plugin Fileeditor : { save : 'Uložit', fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING }, Maximize : { maximize : 'Maximalizovat', minimize : 'Minimalizovat' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Latin American Spanish * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['es-mx'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, no disponible</span>', confirmCancel : 'Algunas opciones se han cambiado\r\n¿Está seguro de querer cerrar el diálogo?', ok : 'Aceptar', cancel : 'Cancelar', confirmationTitle : 'Confirmación', messageTitle : 'Información', inputTitle : 'Pregunta', undo : 'Deshacer', redo : 'Rehacer', skip : 'Omitir', skipAll : 'Omitir todos', makeDecision : '¿Qué acción debe realizarse?', rememberDecision: 'Recordar mi decisión' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'es-mx', LangCode : 'es-mx', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy H:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Carpetas', FolderLoading : 'Cargando...', FolderNew : 'Por favor, escriba el nombre para la nueva carpeta: ', FolderRename : 'Por favor, escriba el nuevo nombre para la carpeta: ', FolderDelete : '¿Está seguro de que quiere borrar la carpeta "%1"?', FolderRenaming : ' (Renombrando...)', FolderDeleting : ' (Borrando...)', // Files FileRename : 'Por favor, escriba el nuevo nombre del archivo: ', FileRenameExt : '¿Está seguro de querer cambiar la extensión del archivo? El archivo puede dejar de ser usable.', FileRenaming : 'Renombrando...', FileDelete : '¿Está seguro de que quiere borrar el archivo "%1".?', FilesLoading : 'Cargando...', FilesEmpty : 'Carpeta vacía', FilesMoved : 'Archivo %1 movido a %2:%3.', FilesCopied : 'Archivo %1 copiado a %2:%3.', // Basket BasketFolder : 'Cesta', BasketClear : 'Vaciar cesta', BasketRemove : 'Quitar de la cesta', BasketOpenFolder : 'Abrir carpeta padre', BasketTruncateConfirm : '¿Está seguro de querer quitar todos los archivos de la cesta?', BasketRemoveConfirm : '¿Está seguro de querer quitar el archivo "%1" de la cesta?', BasketEmpty : 'No hay archivos en la cesta, arrastra y suelta algunos.', BasketCopyFilesHere : 'Copiar archivos de la cesta', BasketMoveFilesHere : 'Mover archivos de la cesta', BasketPasteErrorOther : 'Fichero %s error: %e.', BasketPasteMoveSuccess : 'Los siguientes ficheros han sido movidos: %s', BasketPasteCopySuccess : 'Los siguientes ficheros han sido copiados: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Añadir', UploadTip : 'Añadir nuevo archivo', Refresh : 'Actualizar', Settings : 'Configuración', Help : 'Ayuda', HelpTip : 'Ayuda', // Context Menus Select : 'Seleccionar', SelectThumbnail : 'Seleccionar el icono', View : 'Ver', Download : 'Descargar', NewSubFolder : 'Nueva Subcarpeta', Rename : 'Renombrar', Delete : 'Borrar', CopyDragDrop : 'Copiar archivo aquí', MoveDragDrop : 'Mover archivo aquí', // Dialogs RenameDlgTitle : 'Renombrar', NewNameDlgTitle : 'Nuevo nombre', FileExistsDlgTitle : 'Archivo existente', SysErrorDlgTitle : 'Error de sistema', FileOverwrite : 'Sobreescribir', FileAutorename : 'Auto-renombrar', // Generic OkBtn : 'Aceptar', CancelBtn : 'Cancelar', CloseBtn : 'Cerrar', // Upload Panel UploadTitle : 'Añadir nuevo archivo', UploadSelectLbl : 'Elija el archivo a subir', UploadProgressLbl : '(Subida en progreso, por favor espere...)', UploadBtn : 'Subir el archivo elegido', UploadBtnCancel : 'Cancelar', UploadNoFileMsg : 'Por favor, elija un archivo de su computadora.', UploadNoFolder : 'Por favor, escoja la carpeta antes de iniciar la subida.', UploadNoPerms : 'No puede subir archivos.', UploadUnknError : 'Error enviando el archivo.', UploadExtIncorrect : 'La extensión del archivo no está permitida en esta carpeta.', // Flash Uploads UploadLabel : 'Archivos a subir', UploadTotalFiles : 'Total de archivos:', UploadTotalSize : 'Tamaño total:', UploadAddFiles : 'Añadir archivos', UploadClearFiles : 'Borrar archivos', UploadCancel : 'Cancelar subida', UploadRemove : 'Quitar', UploadRemoveTip : 'Quitar !f', UploadUploaded : 'Enviado !n%', UploadProcessing : 'Procesando...', // Settings Panel SetTitle : 'Configuración', SetView : 'Vista:', SetViewThumb : 'Iconos', SetViewList : 'Lista', SetDisplay : 'Mostrar:', SetDisplayName : 'Nombre de archivo', SetDisplayDate : 'Fecha', SetDisplaySize : 'Tamaño del archivo', SetSort : 'Ordenar:', SetSortName : 'por Nombre', SetSortDate : 'por Fecha', SetSortSize : 'por Tamaño', // Status Bar FilesCountEmpty : '<Carpeta vacía>', FilesCountOne : '1 archivo', FilesCountMany : '%1 archivos', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'No ha sido posible completar la solicitud. (Error %1)', Errors : { 10 : 'Comando incorrecto.', 11 : 'El tipo de recurso no ha sido especificado en la solicitud.', 12 : 'El tipo de recurso solicitado no es válido.', 102 : 'Nombre de archivo o carpeta no válido.', 103 : 'No se ha podido completar la solicitud debido a las restricciones de autorización.', 104 : 'No ha sido posible completar la solicitud debido a restricciones en el sistema de archivos.', 105 : 'La extensión del archivo no es válida.', 109 : 'Petición inválida.', 110 : 'Error desconocido.', 115 : 'Ya existe un archivo o carpeta con ese nombre.', 116 : 'No se ha encontrado la carpeta. Por favor, actualice y pruebe de nuevo.', 117 : 'No se ha encontrado el archivo. Por favor, actualice la lista de archivos y pruebe de nuevo.', 118 : 'Las rutas origen y destino son iguales.', 201 : 'Ya existía un archivo con ese nombre. El archivo subido ha sido renombrado como "%1".', 202 : 'Archivo inválido.', 203 : 'Archivo inválido. El tamaño es demasiado grande.', 204 : 'El archivo subido está corrupto.', 205 : 'La carpeta temporal no está disponible en el servidor para las subidas.', 206 : 'La subida se ha cancelado por razones de seguridad. El archivo contenía código HTML.', 207 : 'El archivo subido ha sido renombrado como "%1".', 300 : 'Ha fallado el mover el(los) archivo(s).', 301 : 'Ha fallado el copiar el(los) archivo(s).', 500 : 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el archivo de configuración de CKFinder.', 501 : 'El soporte para iconos está deshabilitado.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'El nombre del archivo no puede estar vacío.', FileExists : 'El archivo %s ya existe.', FolderEmpty : 'El nombre de la carpeta no puede estar vacío.', FileInvChar : 'El nombre del archivo no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |', FolderInvChar : 'El nombre de la carpeta no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |', PopupBlockView : 'No ha sido posible abrir el archivo en una nueva ventana. Por favor, configure su navegador y desactive todos los bloqueadores de ventanas para esta página.', XmlError : 'No ha sido posible cargar correctamente la respuesta XML del servidor.', XmlEmpty : 'No ha sido posible cargar correctamente la respuesta XML del servidor. El servidor envió una cadena vacía.', XmlRawResponse : 'Respuesta del servidor: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'Redimensionar %s', sizeTooBig : 'No se puede poner la altura o anchura de la imagen mayor que las dimensiones originales (%size).', resizeSuccess : 'Imagen redimensionada correctamente.', thumbnailNew : 'Crear nueva minuatura', thumbnailSmall : 'Pequeña (%s)', thumbnailMedium : 'Mediana (%s)', thumbnailLarge : 'Grande (%s)', newSize : 'Establecer nuevo tamaño', width : 'Ancho', height : 'Alto', invalidHeight : 'Altura inválida.', invalidWidth : 'Anchura inválida.', invalidName : 'Nombre no válido.', newImage : 'Crear nueva imagen', noExtensionChange : 'La extensión no se puede cambiar.', imageSmall : 'La imagen original es demasiado pequeña.', contextMenuName : 'Redimensionar', lockRatio : 'Proporcional', resetSize : 'Tamaño Original' }, // Fileeditor plugin Fileeditor : { save : 'Guardar', fileOpenError : 'No se puede abrir el archivo.', fileSaveSuccess : 'Archivo guardado correctamente.', contextMenuName : 'Editar', loadingFile : 'Cargando archivo, por favor espere...' }, Maximize : { maximize : 'Maximizar', minimize : 'Minimizar' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Brazilian Portuguese * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['pt-br'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, indisponível</span>', confirmCancel : 'Algumas opções foram modificadas. Deseja fechar a janela realmente?', ok : 'OK', cancel : 'Cancelar', confirmationTitle : 'Confirmação', messageTitle : 'Informação', inputTitle : 'Pergunta', undo : 'Desfazer', redo : 'Refazer', skip : 'Ignorar', skipAll : 'Ignorar todos', makeDecision : 'Que ação deve ser tomada?', rememberDecision: 'Lembra minha decisão' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'pt-br', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy HH:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Pastas', FolderLoading : 'Carregando...', FolderNew : 'Favor informar o nome da nova pasta: ', FolderRename : 'Favor informar o nome da nova pasta: ', FolderDelete : 'Você tem certeza que deseja apagar a pasta "%1"?', FolderRenaming : ' (Renomeando...)', FolderDeleting : ' (Apagando...)', // Files FileRename : 'Favor informar o nome do novo arquivo: ', FileRenameExt : 'Você tem certeza que deseja alterar a extensão do arquivo? O arquivo pode ser danificado.', FileRenaming : 'Renomeando...', FileDelete : 'Você tem certeza que deseja apagar o arquivo "%1"?', FilesLoading : 'Carregando...', FilesEmpty : 'Pasta vazia', FilesMoved : 'Arquivo %1 movido para %2:%3.', FilesCopied : 'Arquivo %1 copiado em %2:%3.', // Basket BasketFolder : 'Cesta', BasketClear : 'Limpa Cesta', BasketRemove : 'Remove da cesta', BasketOpenFolder : 'Abre a pasta original', BasketTruncateConfirm : 'Remover todos os arquivas da cesta?', BasketRemoveConfirm : 'Remover o arquivo "%1" da cesta?', BasketEmpty : 'Nenhum arquivo na cesta, arraste alguns antes.', BasketCopyFilesHere : 'Copia Arquivos da Cesta', BasketMoveFilesHere : 'Move os Arquivos da Cesta', BasketPasteErrorOther : 'Arquivo %s erro: %e', BasketPasteMoveSuccess : 'Os seguintes arquivos foram movidos: %s', BasketPasteCopySuccess : 'Os sequintes arquivos foram copiados: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Enviar arquivo', UploadTip : 'Enviar novo arquivo', Refresh : 'Atualizar', Settings : 'Configurações', Help : 'Ajuda', HelpTip : 'Ajuda', // Context Menus Select : 'Selecionar', SelectThumbnail : 'Selecionar miniatura', View : 'Visualizar', Download : 'Download', NewSubFolder : 'Nova sub-pasta', Rename : 'Renomear', Delete : 'Apagar', CopyDragDrop : 'Copia arquivo aqui', MoveDragDrop : 'Move arquivo aqui', // Dialogs RenameDlgTitle : 'Renomeia', NewNameDlgTitle : 'Novo nome', FileExistsDlgTitle : 'O arquivo já existe', SysErrorDlgTitle : 'Erro de Sistema', FileOverwrite : 'Sobrescrever', FileAutorename : 'Renomeia automaticamente', // Generic OkBtn : 'OK', CancelBtn : 'Cancelar', CloseBtn : 'Fechar', // Upload Panel UploadTitle : 'Enviar novo arquivo', UploadSelectLbl : 'Selecione o arquivo para enviar', UploadProgressLbl : '(Enviado arquivo, favor aguardar...)', UploadBtn : 'Enviar arquivo selecionado', UploadBtnCancel : 'Cancelar', UploadNoFileMsg : 'Favor selecionar o arquivo no seu computador.', UploadNoFolder : 'Favor selecionar a pasta antes the enviar o arquivo.', UploadNoPerms : 'Não é permitido o envio de arquivos.', UploadUnknError : 'Erro no envio do arquivo.', UploadExtIncorrect : 'A extensão deste arquivo não é permitida nesat pasta.', // Flash Uploads UploadLabel : 'Arquivos para Enviar', UploadTotalFiles : 'Arquivos:', UploadTotalSize : 'Tamanho:', UploadAddFiles : 'Adicionar Arquivos', UploadClearFiles : 'Remover Arquivos', UploadCancel : 'Cancelar Envio', UploadRemove : 'Remover', UploadRemoveTip : 'Remover !f', UploadUploaded : '!n% enviado', UploadProcessing : 'Processando...', // Settings Panel SetTitle : 'Configurações', SetView : 'Visualizar:', SetViewThumb : 'Miniaturas', SetViewList : 'Lista', SetDisplay : 'Exibir:', SetDisplayName : 'Arquivo', SetDisplayDate : 'Data', SetDisplaySize : 'Tamanho', SetSort : 'Ordenar:', SetSortName : 'por Nome do arquivo', SetSortDate : 'por Data', SetSortSize : 'por Tamanho', // Status Bar FilesCountEmpty : '<Pasta vazia>', FilesCountOne : '1 arquivo', FilesCountMany : '%1 arquivos', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Não foi possível completer o seu pedido. (Erro %1)', Errors : { 10 : 'Comando inválido.', 11 : 'O tipo de recurso não foi especificado na solicitação.', 12 : 'O recurso solicitado não é válido.', 102 : 'Nome do arquivo ou pasta inválido.', 103 : 'Não foi possível completar a solicitação por restrições de acesso.', 104 : 'Não foi possível completar a solicitação por restrições de acesso do sistema de arquivos.', 105 : 'Extensão de arquivo inválida.', 109 : 'Solicitação inválida.', 110 : 'Erro desconhecido.', 115 : 'Uma arquivo ou pasta já existe com esse nome.', 116 : 'Pasta não encontrada. Atualize e tente novamente.', 117 : 'Arquivo não encontrado. Atualize a lista de arquivos e tente novamente.', 118 : 'Origem e destino são iguais.', 201 : 'Um arquivo com o mesmo nome já está disponível. O arquivo enviado foi renomeado para "%1".', 202 : 'Arquivo inválido.', 203 : 'Arquivo inválido. O tamanho é muito grande.', 204 : 'O arquivo enviado está corrompido.', 205 : 'Nenhuma pasta temporária para envio está disponível no servidor.', 206 : 'Transmissão cancelada por razões de segurança. O arquivo contem dados HTML.', 207 : 'O arquivo enviado foi renomeado para "%1".', 300 : 'Não foi possível mover o(s) arquivo(s).', 301 : 'Não foi possível copiar o(s) arquivos(s).', 500 : 'A navegação de arquivos está desativada por razões de segurança. Contacte o administrador do sistema.', 501 : 'O suporte a miniaturas está desabilitado.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'O nome do arquivo não pode ser vazio.', FileExists : 'O nome %s já é em uso.', FolderEmpty : 'O nome da pasta não pode ser vazio.', FileInvChar : 'O nome do arquivo não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |', FolderInvChar : 'O nome da pasta não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |', PopupBlockView : 'Não foi possível abrir o arquivo em outra janela. Configure seu navegador e desabilite o bloqueio a popups para esse site.', XmlError : 'Não foi possível carregar a resposta XML enviada pelo servidor.', XmlEmpty : 'Não foi possível carregar a resposta XML enviada pelo servidor. Resposta vazia..', XmlRawResponse : 'Resposta original enviada pelo servidor: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'Redimensionar %s', sizeTooBig : 'Não possível usar dimensões maiores do que as originais (%size).', resizeSuccess : 'Imagem redimensionada corretamente.', thumbnailNew : 'Cria nova anteprima', thumbnailSmall : 'Pequeno (%s)', thumbnailMedium : 'Médio (%s)', thumbnailLarge : 'Grande (%s)', newSize : 'Novas dimensões', width : 'Largura', height : 'Altura', invalidHeight : 'Altura incorreta.', invalidWidth : 'Largura incorreta.', invalidName : 'O nome do arquivo não é válido.', newImage : 'Cria nova imagem', noExtensionChange : 'A extensão do arquivo não pode ser modificada.', imageSmall : 'A imagem original é muito pequena.', contextMenuName : 'Redimensionar', lockRatio : 'Travar Proporções', resetSize : 'Redefinir para o Tamanho Original' }, // Fileeditor plugin Fileeditor : { save : 'Salva', fileOpenError : 'Não é possível abrir o arquivo.', fileSaveSuccess : 'Arquivo salvado corretamente.', contextMenuName : 'Modificar', loadingFile : 'Carregando arquivo. Por favor aguarde...' }, Maximize : { maximize : 'Maximizar', minimize : 'Minimizar' } };
JavaScript
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file, and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying, or distributing this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview Defines the {@link CKFinder.lang} object for the Norwegian * Nynorsk language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['no'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, utilgjenglig</span>', confirmCancel : 'Noen av valgene har blitt endret. Er du sikker på at du vil lukke dialogen?', ok : 'OK', cancel : 'Avbryt', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Angre', redo : 'Gjør om', skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'no', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy HH:MM', DateAmPm : ['AM', 'PM'], // Folders FoldersTitle : 'Mapper', FolderLoading : 'Laster...', FolderNew : 'Skriv inn det nye mappenavnet: ', FolderRename : 'Skriv inn det nye mappenavnet: ', FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?', FolderRenaming : ' (Endrer mappenavn...)', FolderDeleting : ' (Sletter...)', // Files FileRename : 'Skriv inn det nye filnavnet: ', FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig.', FileRenaming : 'Endrer filnavn...', FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?', FilesLoading : 'Laster...', FilesEmpty : 'The folder is empty.', // MISSING FilesMoved : 'File %1 moved to %2:%3.', // MISSING FilesCopied : 'File %1 copied to %2:%3.', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from Basket', // MISSING BasketOpenFolder : 'Open Parent Folder', // MISSING BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING BasketPasteErrorOther : 'File %s error: %e', // MISSING BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Last opp', UploadTip : 'Last opp en ny fil', Refresh : 'Oppdater', Settings : 'Innstillinger', Help : 'Hjelp', HelpTip : 'Hjelp finnes kun på engelsk', // Context Menus Select : 'Velg', SelectThumbnail : 'Velg Miniatyr', View : 'Vis fullversjon', Download : 'Last ned', NewSubFolder : 'Ny Undermappe', Rename : 'Endre navn', Delete : 'Slett', CopyDragDrop : 'Copy File Here', // MISSING MoveDragDrop : 'Move File Here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New Name', // MISSING FileExistsDlgTitle : 'File Already Exists', // MISSING SysErrorDlgTitle : 'System Error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Avbryt', CloseBtn : 'Lukk', // Upload Panel UploadTitle : 'Last opp ny fil', UploadSelectLbl : 'Velg filen du vil laste opp', UploadProgressLbl : '(Laster opp filen, vennligst vent...)', UploadBtn : 'Last opp valgt fil', UploadBtnCancel : 'Avbryt', UploadNoFileMsg : 'Du må velge en fil fra din datamaskin', UploadNoFolder : 'Please select a folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Flash Uploads UploadLabel : 'Files to Upload', // MISSING UploadTotalFiles : 'Total Files:', // MISSING UploadTotalSize : 'Total Size:', // MISSING UploadAddFiles : 'Add Files', // MISSING UploadClearFiles : 'Clear Files', // MISSING UploadCancel : 'Cancel Upload', // MISSING UploadRemove : 'Remove', // MISSING UploadRemoveTip : 'Remove !f', // MISSING UploadUploaded : 'Uploaded !n%', // MISSING UploadProcessing : 'Processing...', // MISSING // Settings Panel SetTitle : 'Innstillinger', SetView : 'Filvisning:', SetViewThumb : 'Miniatyrbilder', SetViewList : 'Liste', SetDisplay : 'Vis:', SetDisplayName : 'Filnavn', SetDisplayDate : 'Dato', SetDisplaySize : 'Filstørrelse', SetSort : 'Sorter etter:', SetSortName : 'Filnavn', SetSortDate : 'Dato', SetSortSize : 'Størrelse', // Status Bar FilesCountEmpty : '<Tom Mappe>', FilesCountOne : '1 fil', FilesCountMany : '%1 filer', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)', Errors : { 10 : 'Ugyldig kommando.', 11 : 'Ressurstypen ble ikke spesifisert i forepørselen.', 12 : 'Ugyldig ressurstype.', 102 : 'Ugyldig fil- eller mappenavn.', 103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.', 104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.', 105 : 'Ugyldig filtype.', 109 : 'Ugyldig forespørsel.', 110 : 'Ukjent feil.', 115 : 'Det finnes allerede en fil eller mappe med dette navnet.', 116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.', 117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1".', 202 : 'Ugyldig fil.', 203 : 'Ugyldig fil. Filen er for stor.', 204 : 'Den opplastede filen er korrupt.', 205 : 'Det finnes ingen midlertidig mappe for filopplastinger.', 206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.', 207 : 'Den opplastede filens navn har blitt endret til "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.', 501 : 'Funksjon for minityrbilder er skrudd av.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Filnavnet kan ikke være tomt.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Mappenavnet kan ikke være tomt.', FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |', FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |', PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.', XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING XmlRawResponse : 'Raw response from the server: %s' // MISSING }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create a new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set a new size', // MISSING width : 'Bredde', height : 'Høyde', invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create a new image', // MISSING noExtensionChange : 'File extension cannot be changed.', // MISSING imageSmall : 'Source image is too small.', // MISSING contextMenuName : 'Resize', // MISSING lockRatio : 'Lås forhold', resetSize : 'Tilbakestill størrelse' }, // Fileeditor plugin Fileeditor : { save : 'Lagre', fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING }, Maximize : { maximize : 'Maksimer', minimize : 'Minimer' } };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckfinder.com/license */ CKFinder.customConfig = function( config ) { // Define changes to default configuration here. // For the list of available options, check: // http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.config.html // Sample configuration options: // config.uiColor = '#BDE31E'; // config.language = 'fr'; // config.removePlugins = 'basket'; };
JavaScript
CKFinder.addPlugin( 'imageresize', { connectorInitialized : function( api, xml ) { var node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@smallThumb' ); if ( node ) CKFinder.config.imageresize_thumbSmall = node.value; node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@mediumThumb' ); if ( node ) CKFinder.config.imageresize_thumbMedium = node.value; node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@largeThumb' ); if ( node ) CKFinder.config.imageresize_thumbLarge = node.value; }, uiReady : function( api ) { var regexExt = /^(.*)\.([^\.]+)$/, regexFileName = /^(.*?)(?:_\d+x\d+)?\.([^\.]+)$/, regexGetSize = /^\s*(\d+)(px)?\s*$/i, regexGetSizeOrEmpty = /(^\s*(\d+)(px)?\s*$)|^$/i, imageDimension = { width : 0, height : 0 }, file, doc; var updateFileName = function( dialog ) { var width = dialog.getValueOf( 'tab1', 'width' ) || 0, height = dialog.getValueOf( 'tab1', 'height' ) || 0, e = dialog.getContentElement('tab1', 'createNewBox'); if ( width && height ) { var matches = file.name.match( regexFileName ); dialog.setValueOf( 'tab1', 'fileName', matches[1] + "_" + width + "x" + height + "." + matches[2]); e.getElement().show(); } else e.getElement().hide(); }; var onSizeChange = function() { var value = this.getValue(), // This = input element. dialog = this.getDialog(), maxWidth = api.config.imagesMaxWidth, maxHeight = api.config.imagesMaxHeight, aMatch = value.match( regexGetSize ), width = imageDimension.width, height = imageDimension.height, newHeight, newWidth; if ( aMatch ) value = aMatch[1]; if ( !api.config.imageresize_allowEnlarging ) { if ( width && width < maxWidth ) maxWidth = width; if ( height && height < maxHeight ) maxHeight = height; } if ( maxHeight > 0 && this.id == 'height' && value > maxHeight ) { value = maxHeight; dialog.setValueOf( 'tab1', 'height', value ); } if ( maxWidth > 0 && this.id == 'width' && value > maxWidth ) { value = maxWidth; dialog.setValueOf( 'tab1', 'width', value ); } // Only if ratio is locked if ( dialog.lockRatio && width && height ) { if ( this.id == 'height' ) { if ( value && value != '0' ) value = Math.round( width * ( value / height ) ); if ( !isNaN( value ) ) { // newWidth > maxWidth if ( maxWidth > 0 && value > maxWidth ) { value = maxWidth; newHeight = Math.round( height * ( value / width ) ); dialog.setValueOf( 'tab1', 'height', newHeight ); } dialog.setValueOf( 'tab1', 'width', value ); } } else //this.id = txtWidth. { if ( value && value != '0' ) value = Math.round( height * ( value / width ) ); if ( !isNaN( value ) ) { // newHeight > maxHeight if ( maxHeight > 0 && value > maxHeight ) { value = maxHeight; newWidth = Math.round( width * ( value / height ) ); dialog.setValueOf( 'tab1', 'width', newWidth ); } dialog.setValueOf( 'tab1', 'height', value ); } } } updateFileName( dialog ); }; var resetSize = function( dialog ) { if ( imageDimension.width && imageDimension.height ) { dialog.setValueOf( 'tab1', 'width', imageDimension.width ); dialog.setValueOf( 'tab1', 'height', imageDimension.height ); updateFileName( dialog ); } }; var switchLockRatio = function( dialog, value ) { var doc = dialog.getElement().getDocument(), ratioButton = doc.getById( 'btnLockSizes' ); if ( imageDimension.width && imageDimension.height ) { if ( value == 'check' ) // Check image ratio and original image ratio. { var width = dialog.getValueOf( 'tab1', 'width' ), height = dialog.getValueOf( 'tab1', 'height' ), originalRatio = imageDimension.width * 1000 / imageDimension.height, thisRatio = width * 1000 / height; dialog.lockRatio = false; // Default: unlock ratio if ( !width && !height ) dialog.lockRatio = true; // If someone didn't start typing, lock ratio. else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) ) { if ( Math.round( originalRatio ) == Math.round( thisRatio ) ) dialog.lockRatio = true; } } else if ( value != undefined ) dialog.lockRatio = value; else dialog.lockRatio = !dialog.lockRatio; } else if ( value != 'check' ) // I can't lock ratio if ratio is unknown. dialog.lockRatio = false; if ( dialog.lockRatio ) ratioButton.removeClass( 'ckf_btn_unlocked' ); else ratioButton.addClass( 'ckf_btn_unlocked' ); return dialog.lockRatio; }; CKFinder.dialog.add( 'resizeDialog', function( api ) { return { title : api.lang.Imageresize.dialogTitle.replace( '%s', api.getSelectedFile().name ), // TODO resizable : CKFINDER.DIALOG_RESIZE_BOTH minWidth : 390, minHeight : 230, onShow : function() { var dialog = this, thumbSmall = CKFinder.config.imageresize_thumbSmall, thumbMedium = CKFinder.config.imageresize_thumbMedium, thumbLarge = CKFinder.config.imageresize_thumbLarge; doc = dialog.getElement().getDocument(); file = api.getSelectedFile(); this.setTitle( api.lang.Imageresize.dialogTitle.replace( '%s', file.name ) ); var previewImg = doc.getById('previewImage'); var sizeSpan = doc.getById('imageSize'); previewImg.setAttribute('src', file.getThumbnailUrl( true )); var updateImgDimension = function( width, height ) { if ( !width || !height ) { sizeSpan.setText( '' ); return; } imageDimension.width = width; imageDimension.height = height; sizeSpan.setText( width + " x " + height + " px" ); CKFinder.tools.setTimeout( function(){ switchLockRatio( dialog, 'check' ); }, 0, dialog ); }; api.connector.sendCommand( "ImageResizeInfo", { fileName : file.name }, function( xml ) { if ( xml.checkError() ) return; var width = xml.selectSingleNode( 'Connector/ImageInfo/@width' ), height = xml.selectSingleNode( 'Connector/ImageInfo/@height' ), result; if ( width && height ) { width = parseInt( width.value, 10 ); height = parseInt( height.value, 10 ); updateImgDimension( width, height ); var checkThumbs = function( id, size ) { if ( !size ) return; var reThumb = /^(\d+)x(\d+)$/; result = reThumb.exec( size ); var el = dialog.getContentElement( 'tab1', id ); if ( 0 + result[1] > width && 0 + result[2] > height ) { el.disable(); el.getElement().setAttribute('title', api.lang.Imageresize.imageSmall).addClass('cke_disabled'); } else { el.enable(); el.getElement().setAttribute('title', '').removeClass('cke_disabled'); } }; checkThumbs('smallThumb', thumbSmall ); checkThumbs('mediumThumb', thumbMedium ); checkThumbs('largeThumb', thumbLarge ); } }, file.folder.type, file.folder ); if ( !thumbSmall ) dialog.getContentElement('tab1', 'smallThumb').getElement().hide(); if ( !thumbMedium ) dialog.getContentElement('tab1', 'mediumThumb').getElement().hide(); if ( !thumbLarge ) dialog.getContentElement('tab1', 'largeThumb').getElement().hide(); if ( !thumbSmall && !thumbMedium && !thumbLarge ) dialog.getContentElement('tab1', 'thumbsLabel').getElement().hide(); dialog.setValueOf( 'tab1', 'fileName', file.name ); dialog.getContentElement('tab1', 'width').focus(); dialog.getContentElement('tab1', 'fileName').setValue(''); dialog.getContentElement('tab1', 'createNewBox').getElement().hide(); updateImgDimension( 0,0 ); }, onOk : function() { var dialog = this, width = dialog.getValueOf( 'tab1', 'width' ), height = dialog.getValueOf( 'tab1', 'height' ), small = dialog.getValueOf( 'tab1', 'smallThumb' ), medium = dialog.getValueOf( 'tab1', 'mediumThumb' ), large = dialog.getValueOf( 'tab1', 'largeThumb' ), fileName = dialog.getValueOf( 'tab1', 'fileName' ), createNew = dialog.getValueOf( 'tab1', 'createNew' ); if ( width && !height ) { api.openMsgDialog( '', api.lang.Imageresize.invalidHeight ); return false; } else if ( !width && height ) { api.openMsgDialog( '', api.lang.Imageresize.invalidWidth ); return false; } if ( !api.config.imageresize_allowEnlarging && ( parseInt( width, 10 ) > imageDimension.width || parseInt( height, 10 ) > imageDimension.height ) ) { var str = api.lang.Imageresize.sizeTooBig; api.openMsgDialog( '', str.replace( "%size", imageDimension.width + "x" + imageDimension.height ) ); return false; } if ( ( width && height ) || small || medium || large ) { if ( !createNew ) fileName = file.name; api.connector.sendCommandPost( "ImageResize", null, { width : width, height : height, fileName : file.name, newFileName : fileName, overwrite : createNew ? 0 : 1, small : small ? 1 : 0, medium : medium ? 1 : 0, large : large ? 1 : 0 }, function( xml ) { if ( xml.checkError() ) return; api.openMsgDialog( '', api.lang.Imageresize.resizeSuccess ); api.refreshOpenedFolder(); }, file.folder.type, file.folder ); } return undefined; }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'hbox', widths : [ '180px', '280px' ], children: [ { type : 'vbox', children: [ { type : 'html', html : '' + '<style type="text/css">' + 'a.ckf_btn_reset' + '{' + 'float: right;' + 'background-position: 0 -32px;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' + 'width: 16px;' + 'height: 16px;' + 'background-repeat: no-repeat;' + 'border: 1px none;' + 'font-size: 1px;' + '}' + 'a.ckf_btn_locked,' + 'a.ckf_btn_unlocked' + '{' + 'float: left;' + 'background-position: 0 0;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' + 'width: 16px;' + 'height: 16px;' + 'background-repeat: no-repeat;' + 'border: none 1px;' + 'font-size: 1px;' + '}' + 'a.ckf_btn_unlocked' + '{' + 'background-position: 0 -16px;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + '/images/mini.gif");' + '}' + '.ckf_btn_over' + '{' + 'border: outset 1px;' + 'cursor: pointer;' + 'cursor: hand;' + '}' + '</style>' + '<div style="height:100px;padding:7px">' + '<img id="previewImage" src="" style="margin-bottom:4px;" /><br />' + '<span style="font-size:9px;" id="imageSize"></span>' + '</div>' }, { type : 'html', id : 'thumbsLabel', html : '<strong>' + api.lang.Imageresize.thumbnailNew + '</strong>' }, { type : 'checkbox', id : 'smallThumb', checked : false, label : api.lang.Imageresize.thumbnailSmall.replace( '%s', CKFinder.config.imageresize_thumbSmall ) }, { type : 'checkbox', id : 'mediumThumb', checked : false, label : api.lang.Imageresize.thumbnailMedium.replace( '%s', CKFinder.config.imageresize_thumbMedium ) }, { type : 'checkbox', id : 'largeThumb', checked : false, label : api.lang.Imageresize.thumbnailLarge.replace( '%s', CKFinder.config.imageresize_thumbLarge ) } ] }, { type : 'vbox', children : [ { type : 'html', html : '<strong>' + api.lang.Imageresize.newSize + '</strong>' }, { type : 'hbox', widths : [ '80%', '20%' ], children: [ { type : 'vbox', children: [ { type : 'text', labelLayout : 'horizontal', label : api.lang.Imageresize.width, onKeyUp : onSizeChange, validate: function() { var value = this.getValue(); if ( value ) { var aMatch = value.match( regexGetSize ); if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 ) { api.openMsgDialog( '', api.lang.Imageresize.invalidWidth ); return false; } } return true; }, id : 'width' }, { type : 'text', labelLayout : 'horizontal', label : api.lang.Imageresize.height, onKeyUp : onSizeChange, validate: function() { var value = this.getValue(); if ( value ) { var aMatch = value.match( regexGetSize ); if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 ) { api.openMsgDialog( '', api.lang.Imageresize.invalidHeight ); return false; } } return true; }, id : 'height' } ] }, { type : 'html', onLoad : function() { var doc = this.getElement().getDocument(), dialog = this.getDialog(); // Activate Reset button var resetButton = doc.getById( 'btnResetSize' ), ratioButton = doc.getById( 'btnLockSizes' ); if ( resetButton ) { resetButton.on( 'click', function(evt) { resetSize( this ); evt.data.preventDefault(); }, dialog ); resetButton.on( 'mouseover', function() { this.addClass( 'ckf_btn_over' ); }, resetButton ); resetButton.on( 'mouseout', function() { this.removeClass( 'ckf_btn_over' ); }, resetButton ); } // Activate (Un)LockRatio button if ( ratioButton ) { ratioButton.on( 'click', function(evt) { var locked = switchLockRatio( this ), width = this.getValueOf( 'tab1', 'width' ); if ( imageDimension.width && width ) { var height = imageDimension.height / imageDimension.width * width; if ( !isNaN( height ) ) { this.setValueOf( 'tab1', 'height', Math.round( height ) ); updateFileName( dialog ); } } evt.data.preventDefault(); }, dialog ); ratioButton.on( 'mouseover', function() { this.addClass( 'ckf_btn_over' ); }, ratioButton ); ratioButton.on( 'mouseout', function() { this.removeClass( 'ckf_btn_over' ); }, ratioButton ); } }, html : '<div style="margin-top:4px">'+ '<a href="javascript:void(0)" tabindex="-1" title="' + api.lang.Imageresize.lockRatio + '" class="ckf_btn_locked ckf_btn_unlocked" id="btnLockSizes"></a>' + '<a href="javascript:void(0)" tabindex="-1" title="' + api.lang.Imageresize.resetSize + '" class="ckf_btn_reset" id="btnResetSize"></a>'+ '</div>' } ] }, { type : 'vbox', id : 'createNewBox', hidden : true, children: [ { type : 'checkbox', checked : true, id : 'createNew', label : api.lang.Imageresize.newImage, 'default' : true, onChange : function() { var dialog = this.getDialog(); var filenameInput = dialog.getContentElement('tab1', 'fileName'); if ( filenameInput ) { if (!this.getValue()) filenameInput.getElement().hide(); else filenameInput.getElement().show(); } } }, { type : 'text', label : '', validate : function() { var dialog = this.getDialog(), createNew = dialog.getContentElement('tab1', 'createNew'), value = this.getValue(), matches = value.match( regexExt ); if ( createNew && dialog.getValueOf( 'tab1', 'width' ) && dialog.getValueOf( 'tab1', 'height' ) ) { if ( !value || !matches ) { api.openMsgDialog( '', api.lang.Imageresize.invalidName ); return false; } if ( file.ext != matches[2] ) { api.openMsgDialog( '', api.lang.Imageresize.noExtensionChange ); return false; } } return true; }, id : 'fileName' } ] } ] } ] } ] } ], // TODO http://dev.fckeditor.net/ticket/4750 buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; } ); api.addFileContextMenuOption( { label : api.lang.Imageresize.contextMenuName, command : "resizeImage" } , function( api, file ) { api.openDialog( 'resizeDialog' ); }, function ( file ) { // Disable for files other than images. if ( !file.isImage() || !api.getSelectedFolder().type ) return false; if ( file.folder.acl.fileDelete && file.folder.acl.fileUpload ) return true; else return -1; }); } } );
JavaScript
/* Demonstration of embedding CodeMirror in a bigger application. The * interface defined here is a mess of prompts and confirms, and * should probably not be used in a real project. */ function MirrorFrame(place, options) { this.home = document.createElement("div"); if (place.appendChild) place.appendChild(this.home); else place(this.home); var self = this; function makeButton(name, action) { var button = document.createElement("input"); button.type = "button"; button.value = name; self.home.appendChild(button); button.onclick = function(){self[action].call(self);}; } makeButton("Search", "search"); makeButton("Replace", "replace"); makeButton("Current line", "line"); makeButton("Jump to line", "jump"); makeButton("Insert constructor", "macro"); makeButton("Indent all", "reindent"); this.mirror = new CodeMirror(this.home, options); } MirrorFrame.prototype = { search: function() { var text = prompt("Enter search term:", ""); if (!text) return; var first = true; do { var cursor = this.mirror.getSearchCursor(text, first); first = false; while (cursor.findNext()) { cursor.select(); if (!confirm("Search again?")) return; } } while (confirm("End of document reached. Start over?")); }, replace: function() { // This is a replace-all, but it is possible to implement a // prompting replace. var from = prompt("Enter search string:", ""), to; if (from) to = prompt("What should it be replaced with?", ""); if (to == null) return; var cursor = this.mirror.getSearchCursor(from, false); while (cursor.findNext()) cursor.replace(to); }, jump: function() { var line = prompt("Jump to line:", ""); if (line && !isNaN(Number(line))) this.mirror.jumpToLine(Number(line)); }, line: function() { alert("The cursor is currently at line " + this.mirror.currentLine()); this.mirror.focus(); }, macro: function() { var name = prompt("Name your constructor:", ""); if (name) this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n"); }, reindent: function() { this.mirror.reindent(); } };
JavaScript
var HTMLMixedParser = Editor.Parser = (function() { // tags that trigger seperate parsers var triggers = { "script": "JSParser", "style": "CSSParser" }; function checkDependencies() { var parsers = ['XMLParser']; for (var p in triggers) parsers.push(triggers[p]); for (var i in parsers) { if (!window[parsers[i]]) throw new Error(parsers[i] + " parser must be loaded for HTML mixed mode to work."); } XMLParser.configure({useHTMLKludges: true}); } function parseMixed(stream) { checkDependencies(); var htmlParser = XMLParser.make(stream), localParser = null, inTag = false; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.content == ">") { if (triggers[inTag]) { var parser = window[triggers[inTag]]; iter.next = local(parser, "</" + inTag); } inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { localParser = null; iter.next = top; return top(); } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); }; } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); iter.next = _next; inTag = _inTag; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(obj) { if (obj.triggers) triggers = obj.triggers; } }; })();
JavaScript
/* Simple parser for CSS */ var CSSParser = Editor.Parser = (function() { var tokenizeCSS = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "@") { source.nextWhileMatches(/\w/); return "css-at"; } else if (ch == "/" && source.equals("*")) { setState(inCComment); return null; } else if (ch == "<" && source.equals("!")) { setState(inSGMLComment); return null; } else if (ch == "=") { return "css-compare"; } else if (source.equals("=") && (ch == "~" || ch == "|")) { source.next(); return "css-compare"; } else if (ch == "\"" || ch == "'") { setState(inString(ch)); return null; } else if (ch == "#") { source.nextWhileMatches(/\w/); return "css-hash"; } else if (ch == "!") { source.nextWhileMatches(/[ \t]/); source.nextWhileMatches(/\w/); return "css-important"; } else if (/\d/.test(ch)) { source.nextWhileMatches(/[\w.%]/); return "css-unit"; } else if (/[,.+>*\/]/.test(ch)) { return "css-select-op"; } else if (/[;{}:\[\]]/.test(ch)) { return "css-punctuation"; } else { source.nextWhileMatches(/[\w\\\-_]/); return "css-identifier"; } } function inCComment(source, setState) { var maybeEnd = false; while (!source.endOfLine()) { var ch = source.next(); if (maybeEnd && ch == "/") { setState(normal); break; } maybeEnd = (ch == "*"); } return "css-comment"; } function inSGMLComment(source, setState) { var dashes = 0; while (!source.endOfLine()) { var ch = source.next(); if (dashes >= 2 && ch == ">") { setState(normal); break; } dashes = (ch == "-") ? dashes + 1 : 0; } return "css-comment"; } function inString(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) setState(normal); return "css-string"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentCSS(inBraces, inRule, base) { return function(nextChars) { if (!inBraces || /^\}/.test(nextChars)) return base; else if (inRule) return base + indentUnit * 2; else return base + indentUnit; }; } // This is a very simplistic parser -- since CSS does not really // nest, it works acceptably well, but some nicer colouroing could // be provided with a more complicated parser. function parseCSS(source, basecolumn) { basecolumn = basecolumn || 0; var tokens = tokenizeCSS(source); var inBraces = false, inRule = false, inDecl = false;; var iter = { next: function() { var token = tokens.next(), style = token.style, content = token.content; if (style == "css-hash") style = token.style = inRule ? "css-colorcode" : "css-identifier"; if (style == "css-identifier") { if (inRule) token.style = "css-value"; else if (!inBraces && !inDecl) token.style = "css-selector"; } if (content == "\n") token.indentation = indentCSS(inBraces, inRule, basecolumn); if (content == "{" && inDecl == "@media") inDecl = false; else if (content == "{") inBraces = true; else if (content == "}") inBraces = inRule = inDecl = false; else if (content == ";") inRule = inDecl = false; else if (inBraces && style != "css-comment" && style != "whitespace") inRule = true; else if (!inBraces && style == "css-at") inDecl = content; return token; }, copy: function() { var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state; return function(source) { tokens = tokenizeCSS(source, _tokenState); inBraces = _inBraces; inRule = _inRule; return iter; }; } }; return iter; } return {make: parseCSS, electricChars: "}"}; })();
JavaScript
/* Functionality for finding, storing, and restoring selections * * This does not provide a generic API, just the minimal functionality * required by the CodeMirror system. */ // Namespace object. var select = {}; (function() { select.ie_selection = document.selection && document.selection.createRangeCollection; // Find the 'top-level' (defined as 'a direct child of the node // passed as the top argument') node that the given node is // contained in. Return null if the given node is not inside the top // node. function topLevelNodeAt(node, top) { while (node && node.parentNode != top) node = node.parentNode; return node; } // Find the top-level node that contains the node before this one. function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) node = node.parentNode; return topLevelNodeAt(node.previousSibling, top); } var fourSpaces = "\u00a0\u00a0\u00a0\u00a0"; select.scrollToNode = function(node, cursor) { if (!node) return; var element = node, body = document.body, html = document.documentElement, atEnd = !element.nextSibling || !element.nextSibling.nextSibling || !element.nextSibling.nextSibling.nextSibling; // In Opera (and recent Webkit versions), BR elements *always* // have a offsetTop property of zero. var compensateHack = 0; while (element && !element.offsetTop) { compensateHack++; element = element.previousSibling; } // atEnd is another kludge for these browsers -- if the cursor is // at the end of the document, and the node doesn't have an // offset, just scroll to the end. if (compensateHack == 0) atEnd = false; // WebKit has a bad habit of (sometimes) happily returning bogus // offsets when the document has just been changed. This seems to // always be 5/5, so we don't use those. if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5) return; var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, width = (node ? node.offsetWidth : 0), pos = element; while (pos && pos.offsetParent) { y += pos.offsetTop; // Don't count X offset for <br> nodes if (!isBR(pos)) x += pos.offsetLeft; pos = pos.offsetParent; } var scroll_x = body.scrollLeft || html.scrollLeft || 0, scroll_y = body.scrollTop || html.scrollTop || 0, scroll = false, screen_width = window.innerWidth || html.clientWidth || 0; if (cursor || width < screen_width) { if (cursor) { var off = select.offsetInNode(node), size = nodeText(node).length; if (size) x += width * (off / size); } var screen_x = x - scroll_x; if (screen_x < 0 || screen_x > screen_width) { scroll_x = x; scroll = true; } } var screen_y = y - scroll_y; if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) { scroll_y = atEnd ? 1e6 : y; scroll = true; } if (scroll) window.scrollTo(scroll_x, scroll_y); }; select.scrollToCursor = function(container) { select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true); }; // Used to prevent restoring a selection when we do not need to. var currentSelection = null; select.snapshotChanged = function() { if (currentSelection) currentSelection.changed = true; }; // Find the 'leaf' node (BR or text) after the given one. function baseNodeAfter(node) { var next = node.nextSibling; if (next) { while (next.firstChild) next = next.firstChild; if (next.nodeType == 3 || isBR(next)) return next; else return baseNodeAfter(next); } else { var parent = node.parentNode; while (parent && !parent.nextSibling) parent = parent.parentNode; return parent && baseNodeAfter(parent); } } // This is called by the code in editor.js whenever it is replacing // a text node. The function sees whether the given oldNode is part // of the current selection, and updates this selection if it is. // Because nodes are often only partially replaced, the length of // the part that gets replaced has to be taken into account -- the // selection might stay in the oldNode if the newNode is smaller // than the selection's offset. The offset argument is needed in // case the selection does move to the new object, and the given // length is not the whole length of the new node (part of it might // have been used to replace another node). select.snapshotReplaceNode = function(from, to, length, offset) { if (!currentSelection) return; function replace(point) { if (from == point.node) { currentSelection.changed = true; if (length && point.offset > length) { point.offset -= length; } else { point.node = to; point.offset += (offset || 0); } } else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) { currentSelection.changed = true; } } replace(currentSelection.start); replace(currentSelection.end); }; select.snapshotMove = function(from, to, distance, relative, ifAtStart) { if (!currentSelection) return; function move(point) { if (from == point.node && (!ifAtStart || point.offset == 0)) { currentSelection.changed = true; point.node = to; if (relative) point.offset = Math.max(0, point.offset + distance); else point.offset = distance; } } move(currentSelection.start); move(currentSelection.end); }; // Most functions are defined in two ways, one for the IE selection // model, one for the W3C one. if (select.ie_selection) { function selRange() { var sel = document.selection; return sel && (sel.createRange || sel.createTextRange)(); } function selectionNode(start) { var range = selRange(); range.collapse(start); function nodeAfter(node) { var found = null; while (!found && node) { found = node.nextSibling; node = node.parentNode; } return nodeAtStartOf(found); } function nodeAtStartOf(node) { while (node && node.firstChild) node = node.firstChild; return {node: node, offset: 0}; } var containing = range.parentElement(); if (!isAncestor(document.body, containing)) return null; if (!containing.firstChild) return nodeAtStartOf(containing); var working = range.duplicate(); working.moveToElementText(containing); working.collapse(true); for (var cur = containing.firstChild; cur; cur = cur.nextSibling) { if (cur.nodeType == 3) { var size = cur.nodeValue.length; working.move("character", size); } else { working.moveToElementText(cur); working.collapse(false); } var dir = range.compareEndPoints("StartToStart", working); if (dir == 0) return nodeAfter(cur); if (dir == 1) continue; if (cur.nodeType != 3) return nodeAtStartOf(cur); working.setEndPoint("StartToEnd", range); return {node: cur, offset: size - working.text.length}; } return nodeAfter(containing); } select.markSelection = function() { currentSelection = null; var sel = document.selection; if (!sel) return; var start = selectionNode(true), end = selectionNode(false); if (!start || !end) return; currentSelection = {start: start, end: end, changed: false}; }; select.selectMarked = function() { if (!currentSelection || !currentSelection.changed) return; function makeRange(point) { var range = document.body.createTextRange(), node = point.node; if (!node) { range.moveToElementText(document.body); range.collapse(false); } else if (node.nodeType == 3) { range.moveToElementText(node.parentNode); var offset = point.offset; while (node.previousSibling) { node = node.previousSibling; offset += (node.innerText || "").length; } range.move("character", offset); } else { range.moveToElementText(node); range.collapse(true); } return range; } var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end); start.setEndPoint("StartToEnd", end); start.select(); }; select.offsetInNode = function(node) { var range = selRange(); if (!range) return 0; var range2 = range.duplicate(); try {range2.moveToElementText(node);} catch(e){return 0;} range.setEndPoint("StartToStart", range2); return range.text.length; }; // Get the top-level node that one end of the cursor is inside or // after. Note that this returns false for 'no cursor', and null // for 'start of document'. select.selectionTopNode = function(container, start) { var range = selRange(); if (!range) return false; var range2 = range.duplicate(); range.collapse(start); var around = range.parentElement(); if (around && isAncestor(container, around)) { // Only use this node if the selection is not at its start. range2.moveToElementText(around); if (range.compareEndPoints("StartToStart", range2) == 1) return topLevelNodeAt(around, container); } // Move the start of a range to the start of a node, // compensating for the fact that you can't call // moveToElementText with text nodes. function moveToNodeStart(range, node) { if (node.nodeType == 3) { var count = 0, cur = node.previousSibling; while (cur && cur.nodeType == 3) { count += cur.nodeValue.length; cur = cur.previousSibling; } if (cur) { try{range.moveToElementText(cur);} catch(e){return false;} range.collapse(false); } else range.moveToElementText(node.parentNode); if (count) range.move("character", count); } else { try{range.moveToElementText(node);} catch(e){return false;} } return true; } // Do a binary search through the container object, comparing // the start of each node to the selection var start = 0, end = container.childNodes.length - 1; while (start < end) { var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle]; if (!node) return false; // Don't ask. IE6 manages this sometimes. if (!moveToNodeStart(range2, node)) return false; if (range.compareEndPoints("StartToStart", range2) == 1) start = middle; else end = middle - 1; } if (start == 0) { var test1 = selRange(), test2 = test1.duplicate(); try { test2.moveToElementText(container); } catch(exception) { return null; } if (test1.compareEndPoints("StartToStart", test2) == 0) return null; } return container.childNodes[start] || null; }; // Place the cursor after this.start. This is only useful when // manually moving the cursor instead of restoring it to its old // position. select.focusAfterNode = function(node, container) { var range = document.body.createTextRange(); range.moveToElementText(node || container); range.collapse(!node); range.select(); }; select.somethingSelected = function() { var range = selRange(); return range && (range.text != ""); }; function insertAtCursor(html) { var range = selRange(); if (range) { range.pasteHTML(html); range.collapse(false); range.select(); } } // Used to normalize the effect of the enter key, since browsers // do widely different things when pressing enter in designMode. select.insertNewlineAtCursor = function() { insertAtCursor("<br>"); }; select.insertTabAtCursor = function() { insertAtCursor(fourSpaces); }; // Get the BR node at the start of the line on which the cursor // currently is, and the offset into the line. Returns null as // node if cursor is on first line. select.cursorPos = function(container, start) { var range = selRange(); if (!range) return null; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; var range2 = range.duplicate(); range.collapse(start); if (topNode) { range2.moveToElementText(topNode); range2.collapse(false); } else { // When nothing is selected, we can get all kinds of funky errors here. try { range2.moveToElementText(container); } catch (e) { return null; } range2.collapse(true); } range.setEndPoint("StartToStart", range2); return {node: topNode, offset: range.text.length}; }; select.setCursorPos = function(container, from, to) { function rangeAt(pos) { var range = document.body.createTextRange(); if (!pos.node) { range.moveToElementText(container); range.collapse(true); } else { range.moveToElementText(pos.node); range.collapse(false); } range.move("character", pos.offset); return range; } var range = rangeAt(from); if (to && to != from) range.setEndPoint("EndToEnd", rangeAt(to)); range.select(); } // Some hacks for storing and re-storing the selection when the editor loses and regains focus. select.getBookmark = function (container) { var from = select.cursorPos(container, true), to = select.cursorPos(container, false); if (from && to) return {from: from, to: to}; }; // Restore a stored selection. select.setBookmark = function(container, mark) { if (!mark) return; select.setCursorPos(container, mark.from, mark.to); }; } // W3C model else { // Find the node right at the cursor, not one of its // ancestors with a suitable offset. This goes down the DOM tree // until a 'leaf' is reached (or is it *up* the DOM tree?). function innerNode(node, offset) { while (node.nodeType != 3 && !isBR(node)) { var newNode = node.childNodes[offset] || node.nextSibling; offset = 0; while (!newNode && node.parentNode) { node = node.parentNode; newNode = node.nextSibling; } node = newNode; if (!newNode) break; } return {node: node, offset: offset}; } // Store start and end nodes, and offsets within these, and refer // back to the selection object from those nodes, so that this // object can be updated when the nodes are replaced before the // selection is restored. select.markSelection = function () { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return (currentSelection = null); var range = selection.getRangeAt(0); currentSelection = { start: innerNode(range.startContainer, range.startOffset), end: innerNode(range.endContainer, range.endOffset), changed: false }; }; select.selectMarked = function () { var cs = currentSelection; // on webkit-based browsers, it is apparently possible that the // selection gets reset even when a node that is not one of the // endpoints get messed with. the most common situation where // this occurs is when a selection is deleted or overwitten. we // check for that here. function focusIssue() { if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return true; var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset); return cs.start.node != point.node || cs.start.offset != point.offset; } } if (!cs || !(cs.changed || (webkit && focusIssue()))) return; var range = document.createRange(); function setPoint(point, which) { if (point.node) { // Some magic to generalize the setting of the start and end // of a range. if (point.offset == 0) range["set" + which + "Before"](point.node); else range["set" + which](point.node, point.offset); } else { range.setStartAfter(document.body.lastChild || document.body); } } setPoint(cs.end, "End"); setPoint(cs.start, "Start"); selectRange(range); }; // Helper for selecting a range object. function selectRange(range) { var selection = window.getSelection(); if (!selection) return; selection.removeAllRanges(); selection.addRange(range); } function selectionRange() { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return false; else return selection.getRangeAt(0); } // Finding the top-level node at the cursor in the W3C is, as you // can see, quite an involved process. select.selectionTopNode = function(container, start) { var range = selectionRange(); if (!range) return false; var node = start ? range.startContainer : range.endContainer; var offset = start ? range.startOffset : range.endOffset; // Work around (yet another) bug in Opera's selection model. if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 && container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset])) offset--; // For text nodes, we look at the node itself if the cursor is // inside, or at the node before it if the cursor is at the // start. if (node.nodeType == 3){ if (offset > 0) return topLevelNodeAt(node, container); else return topLevelNodeBefore(node, container); } // Occasionally, browsers will return the HTML node as // selection. If the offset is 0, we take the start of the frame // ('after null'), otherwise, we take the last node. else if (node.nodeName.toUpperCase() == "HTML") { return (offset == 1 ? null : container.lastChild); } // If the given node is our 'container', we just look up the // correct node by using the offset. else if (node == container) { return (offset == 0) ? null : node.childNodes[offset - 1]; } // In any other case, we have a regular node. If the cursor is // at the end of the node, we use the node itself, if it is at // the start, we use the node before it, and in any other // case, we look up the child before the cursor and use that. else { if (offset == node.childNodes.length) return topLevelNodeAt(node, container); else if (offset == 0) return topLevelNodeBefore(node, container); else return topLevelNodeAt(node.childNodes[offset - 1], container); } }; select.focusAfterNode = function(node, container) { var range = document.createRange(); range.setStartBefore(container.firstChild || container); // In Opera, setting the end of a range at the end of a line // (before a BR) will cause the cursor to appear on the next // line, so we set the end inside of the start node when // possible. if (node && !node.firstChild) range.setEndAfter(node); else if (node) range.setEnd(node, node.childNodes.length); else range.setEndBefore(container.firstChild || container); range.collapse(false); selectRange(range); }; select.somethingSelected = function() { var range = selectionRange(); return range && !range.collapsed; }; select.offsetInNode = function(node) { var range = selectionRange(); if (!range) return 0; range = range.cloneRange(); range.setStartBefore(node); return range.toString().length; }; select.insertNodeAtCursor = function(node) { var range = selectionRange(); if (!range) return; range.deleteContents(); range.insertNode(node); webkitLastLineHack(document.body); // work around weirdness where Opera will magically insert a new // BR node when a BR node inside a span is moved around. makes // sure the BR ends up outside of spans. if (window.opera && isBR(node) && isSpan(node.parentNode)) { var next = node.nextSibling, p = node.parentNode, outer = p.parentNode; outer.insertBefore(node, p.nextSibling); var textAfter = ""; for (; next && next.nodeType == 3; next = next.nextSibling) { textAfter += next.nodeValue; removeElement(next); } outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling); } range = document.createRange(); range.selectNode(node); range.collapse(false); selectRange(range); } select.insertNewlineAtCursor = function() { select.insertNodeAtCursor(document.createElement("BR")); }; select.insertTabAtCursor = function() { select.insertNodeAtCursor(document.createTextNode(fourSpaces)); }; select.cursorPos = function(container, start) { var range = selectionRange(); if (!range) return; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; range = range.cloneRange(); range.collapse(start); if (topNode) range.setStartAfter(topNode); else range.setStartBefore(container); var text = range.toString(); return {node: topNode, offset: text.length}; }; select.setCursorPos = function(container, from, to) { var range = document.createRange(); function setPoint(node, offset, side) { if (offset == 0 && node && !node.nextSibling) { range["set" + side + "After"](node); return true; } if (!node) node = container.firstChild; else node = node.nextSibling; if (!node) return; if (offset == 0) { range["set" + side + "Before"](node); return true; } var backlog = [] function decompose(node) { if (node.nodeType == 3) backlog.push(node); else forEach(node.childNodes, decompose); } while (true) { while (node && !backlog.length) { decompose(node); node = node.nextSibling; } var cur = backlog.shift(); if (!cur) return false; var length = cur.nodeValue.length; if (length >= offset) { range["set" + side](cur, offset); return true; } offset -= length; } } to = to || from; if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start")) selectRange(range); }; } })();
JavaScript
/* A few useful utility functions. */ // Capture a method on an object. function method(obj, name) { return function() {obj[name].apply(obj, arguments);}; } // The value used to signal the end of a sequence in iterators. var StopIteration = {toString: function() {return "StopIteration"}}; // Apply a function to each element in a sequence. function forEach(iter, f) { if (iter.next) { try {while (true) f(iter.next());} catch (e) {if (e != StopIteration) throw e;} } else { for (var i = 0; i < iter.length; i++) f(iter[i]); } } // Map a function over a sequence, producing an array of results. function map(iter, f) { var accum = []; forEach(iter, function(val) {accum.push(f(val));}); return accum; } // Create a predicate function that tests a string againsts a given // regular expression. No longer used but might be used by 3rd party // parsers. function matcher(regexp){ return function(value){return regexp.test(value);}; } // Test whether a DOM node has a certain CSS class. function hasClass(element, className) { var classes = element.className; return classes && new RegExp("(^| )" + className + "($| )").test(classes); } function removeClass(element, className) { element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), ""); return element; } // Insert a DOM node after another node. function insertAfter(newNode, oldNode) { var parent = oldNode.parentNode; parent.insertBefore(newNode, oldNode.nextSibling); return newNode; } function removeElement(node) { if (node.parentNode) node.parentNode.removeChild(node); } function clearElement(node) { while (node.firstChild) node.removeChild(node.firstChild); } // Check whether a node is contained in another one. function isAncestor(node, child) { while (child = child.parentNode) { if (node == child) return true; } return false; } // The non-breaking space character. var nbsp = "\u00a0"; var matching = {"{": "}", "[": "]", "(": ")", "}": "{", "]": "[", ")": "("}; // Standardize a few unportable event properties. function normalizeEvent(event) { if (!event.stopPropagation) { event.stopPropagation = function() {this.cancelBubble = true;}; event.preventDefault = function() {this.returnValue = false;}; } if (!event.stop) { event.stop = function() { this.stopPropagation(); this.preventDefault(); }; } if (event.type == "keypress") { event.code = (event.charCode == null) ? event.keyCode : event.charCode; event.character = String.fromCharCode(event.code); } return event; } // Portably register event handlers. function addEventHandler(node, type, handler, removeFunc) { function wrapHandler(event) { handler(normalizeEvent(event || window.event)); } if (typeof node.addEventListener == "function") { node.addEventListener(type, wrapHandler, false); if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);}; } else { node.attachEvent("on" + type, wrapHandler); if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);}; } } function nodeText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } function nodeTop(node) { var top = 0; while (node.offsetParent) { top += node.offsetTop; node = node.offsetParent; } return top; } function isBR(node) { var nn = node.nodeName; return nn == "BR" || nn == "br"; } function isSpan(node) { var nn = node.nodeName; return nn == "SPAN" || nn == "span"; }
JavaScript
var SparqlParser = Editor.Parser = (function() { function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", "isblank", "isliteral", "union", "a"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc"]); var operatorChars = /[*+\-<>=&|]/; var tokenizeSparql = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "$" || ch == "?") { source.nextWhileMatches(/[\w\d]/); return "sp-var"; } else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) { source.nextWhileMatches(/[^\s\u00a0>]/); if (source.equals(">")) source.next(); return "sp-uri"; } else if (ch == "\"" || ch == "'") { setState(inLiteral(ch)); return null; } else if (/[{}\(\),\.;\[\]]/.test(ch)) { return "sp-punc"; } else if (ch == "#") { while (!source.endOfLine()) source.next(); return "sp-comment"; } else if (operatorChars.test(ch)) { source.nextWhileMatches(operatorChars); return "sp-operator"; } else if (ch == ":") { source.nextWhileMatches(/[\w\d\._\-]/); return "sp-prefixed"; } else { source.nextWhileMatches(/[_\w\d]/); if (source.equals(":")) { source.next(); source.nextWhileMatches(/[\w\d_\-]/); return "sp-prefixed"; } var word = source.get(), type; if (ops.test(word)) type = "sp-operator"; else if (keywords.test(word)) type = "sp-keyword"; else type = "sp-word"; return {style: type, content: word}; } } function inLiteral(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) { setState(normal); break; } escaped = !escaped && ch == "\\"; } return "sp-literal"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentSparql(context) { return function(nextChars) { var firstChar = nextChars && nextChars.charAt(0); if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == matching[context.type]; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col - (closing ? context.width : 0); else return context.indent + (closing ? 0 : indentUnit); } } function parseSparql(source) { var tokens = tokenizeSparql(source); var context = null, indent = 0, col = 0; function pushContext(type, width) { context = {prev: context, indent: indent, col: col, type: type, width: width}; } function popContext() { context = context.prev; } var iter = { next: function() { var token = tokens.next(), type = token.style, content = token.content, width = token.value.length; if (content == "\n") { token.indentation = indentSparql(context); indent = col = 0; if (context && context.align == null) context.align = false; } else if (type == "whitespace" && col == 0) { indent = width; } else if (type != "sp-comment" && context && context.align == null) { context.align = true; } if (content != "\n") col += width; if (/[\[\{\(]/.test(content)) { pushContext(content, width); } else if (/[\]\}\)]/.test(content)) { while (context && context.type == "pattern") popContext(); if (context && content == matching[context.type]) popContext(); } else if (content == "." && context && context.type == "pattern") { popContext(); } else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") && context && /[\{\[]/.test(context.type)) { pushContext("pattern", width); } return token; }, copy: function() { var _context = context, _indent = indent, _col = col, _tokenState = tokens.state; return function(source) { tokens = tokenizeSparql(source, _tokenState); context = _context; indent = _indent; col = _col; return iter; }; } }; return iter; } return {make: parseSparql, electricChars: "}]"}; })();
JavaScript
/* This file defines an XML parser, with a few kludges to make it * useable for HTML. autoSelfClosers defines a set of tag names that * are expected to not have a closing tag, and doNotIndent specifies * the tags inside of which no indentation should happen (see Config * object). These can be disabled by passing the editor an object like * {useHTMLKludges: false} as parserConfig option. */ var XMLParser = Editor.Parser = (function() { var Kludges = { autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true, "meta": true, "col": true, "frame": true, "base": true, "area": true}, doNotIndent: {"pre": true, "!cdata": true} }; var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}}; var UseKludges = Kludges; var alignCDATA = false; // Simple stateful tokenizer for XML documents. Returns a // MochiKit-style iterator, with a state property that contains a // function encapsulating the current state. See tokenize.js. var tokenizeXML = (function() { function inText(source, setState) { var ch = source.next(); if (ch == "<") { if (source.equals("!")) { source.next(); if (source.equals("[")) { if (source.lookAhead("[CDATA[", true)) { setState(inBlock("xml-cdata", "]]>")); return null; } else { return "xml-text"; } } else if (source.lookAhead("--", true)) { setState(inBlock("xml-comment", "-->")); return null; } else if (source.lookAhead("DOCTYPE", true)) { source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-doctype", ">")); return "xml-doctype"; } else { return "xml-text"; } } else if (source.equals("?")) { source.next(); source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-processing", "?>")); return "xml-processing"; } else { if (source.equals("/")) source.next(); setState(inTag); return "xml-punctuation"; } } else if (ch == "&") { while (!source.endOfLine()) { if (source.next() == ";") break; } return "xml-entity"; } else { source.nextWhileMatches(/[^&<\n]/); return "xml-text"; } } function inTag(source, setState) { var ch = source.next(); if (ch == ">") { setState(inText); return "xml-punctuation"; } else if (/[?\/]/.test(ch) && source.equals(">")) { source.next(); setState(inText); return "xml-punctuation"; } else if (ch == "=") { return "xml-punctuation"; } else if (/[\'\"]/.test(ch)) { setState(inAttribute(ch)); return null; } else { source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/); return "xml-name"; } } function inAttribute(quote) { return function(source, setState) { while (!source.endOfLine()) { if (source.next() == quote) { setState(inTag); break; } } return "xml-attribute"; }; } function inBlock(style, terminator) { return function(source, setState) { while (!source.endOfLine()) { if (source.lookAhead(terminator, true)) { setState(inText); break; } source.next(); } return style; }; } return function(source, startState) { return tokenizer(source, startState || inText); }; })(); // The parser. The structure of this function largely follows that of // parseJavaScript in parsejavascript.js (there is actually a bit more // shared code than I'd like), but it is quite a bit simpler. function parseXML(source) { var tokens = tokenizeXML(source), token; var cc = [base]; var tokenNr = 0, indented = 0; var currentTag = null, context = null; var consume; function push(fs) { for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } function cont() { push(arguments); consume = true; } function pass() { push(arguments); consume = false; } function markErr() { token.style += " xml-error"; } function expect(text) { return function(style, content) { if (content == text) cont(); else {markErr(); cont(arguments.callee);} }; } function pushContext(tagname, startOfLine) { var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent); context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent}; } function popContext() { context = context.prev; } function computeIndentation(baseContext) { return function(nextChars, current) { var context = baseContext; if (context && context.noIndent) return current; if (alignCDATA && /<!\[CDATA\[/.test(nextChars)) return 0; if (context && /^<\//.test(nextChars)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }; } function base() { return pass(element, base); } var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true, "xml-doctype": true}; function element(style, content) { if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1)); else if (content == "</") cont(closetagname, expect(">")); else if (style == "xml-cdata") { if (!context || context.name != "!cdata") pushContext("!cdata"); if (/\]\]>$/.test(content)) popContext(); cont(); } else if (harmlessTokens.hasOwnProperty(style)) cont(); else {markErr(); cont();} } function tagname(style, content) { if (style == "xml-name") { currentTag = content.toLowerCase(); token.style = "xml-tagname"; cont(); } else { currentTag = null; pass(); } } function closetagname(style, content) { if (style == "xml-name") { token.style = "xml-tagname"; if (context && content.toLowerCase() == context.name) popContext(); else markErr(); } cont(); } function endtag(startOfLine) { return function(style, content) { if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont(); else if (content == ">") {pushContext(currentTag, startOfLine); cont();} else {markErr(); cont(arguments.callee);} }; } function attributes(style) { if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);} else pass(); } function attribute(style, content) { if (content == "=") cont(value); else if (content == ">" || content == "/>") pass(endtag); else pass(); } function value(style) { if (style == "xml-attribute") cont(value); else pass(); } return { indentation: function() {return indented;}, next: function(){ token = tokens.next(); if (token.style == "whitespace" && tokenNr == 0) indented = token.value.length; else tokenNr++; if (token.content == "\n") { indented = tokenNr = 0; token.indentation = computeIndentation(context); } if (token.style == "whitespace" || token.type == "xml-comment") return token; while(true){ consume = false; cc.pop()(token.style, token.content); if (consume) return token; } }, copy: function(){ var _cc = cc.concat([]), _tokenState = tokens.state, _context = context; var parser = this; return function(input){ cc = _cc.concat([]); tokenNr = indented = 0; context = _context; tokens = tokenizeXML(input, _tokenState); return parser; }; } }; } return { make: parseXML, electricChars: "/", configure: function(config) { if (config.useHTMLKludges != null) UseKludges = config.useHTMLKludges ? Kludges : NoKludges; if (config.alignCDATA) alignCDATA = config.alignCDATA; } }; })();
JavaScript
/* Tokenizer for JavaScript code */ var tokenizeJavaScript = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "js-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, intended to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "js-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "js-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "js-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gimy]/); // 'y' is "sticky" option in Mozilla return {type: "regexp", style: "js-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "js-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "js-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "js-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "js-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
JavaScript
// A framework for simple tokenizers. Takes care of newlines and // white-space, and of getting the text from the source stream into // the token object. A state is a function of two arguments -- a // string stream and a setState function. The second can be used to // change the tokenizer's state, and can be ignored for stateless // tokenizers. This function should advance the stream over a token // and return a string or object containing information about the next // token, or null to pass and have the (new) state be called to finish // the token. When a string is given, it is wrapped in a {style, type} // object. In the resulting object, the characters consumed are stored // under the content property. Any whitespace following them is also // automatically consumed, and added to the value property. (Thus, // content is the actual meaningful part of the token, while value // contains all the text it spans.) function tokenizer(source, state) { // Newlines are always a separate token. function isWhiteSpace(ch) { // The messy regexp is because IE's regexp matcher is of the // opinion that non-breaking spaces are no whitespace. return ch != "\n" && /^[\s\u00a0]*$/.test(ch); } var tokenizer = { state: state, take: function(type) { if (typeof(type) == "string") type = {style: type, type: type}; type.content = (type.content || "") + source.get(); if (!/\n$/.test(type.content)) source.nextWhile(isWhiteSpace); type.value = type.content + source.get(); return type; }, next: function () { if (!source.more()) throw StopIteration; var type; if (source.equals("\n")) { source.next(); return this.take("whitespace"); } if (source.applies(isWhiteSpace)) type = "whitespace"; else while (!type) type = this.state(source, function(s) {tokenizer.state = s;}); return this.take(type); } }; return tokenizer; }
JavaScript
/* CodeMirror main module (http://codemirror.net/) * * Implements the CodeMirror constructor and prototype, which take care * of initializing the editor frame, and providing the outside interface. */ // The CodeMirrorConfig object is used to specify a default // configuration. If you specify such an object before loading this // file, the values you put into it will override the defaults given // below. You can also assign to it after loading. var CodeMirrorConfig = window.CodeMirrorConfig || {}; var CodeMirror = (function(){ function setDefaults(object, defaults) { for (var option in defaults) { if (!object.hasOwnProperty(option)) object[option] = defaults[option]; } } function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); } function createHTMLElement(el) { if (document.createElementNS && document.documentElement.namespaceURI !== null) return document.createElementNS("http://www.w3.org/1999/xhtml", el) else return document.createElement(el) } // These default options can be overridden by passing a set of // options to a specific CodeMirror constructor. See manual.html for // their meaning. setDefaults(CodeMirrorConfig, { stylesheet: [], path: "", parserfile: [], basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"], iframeClass: null, passDelay: 200, passTime: 50, lineNumberDelay: 200, lineNumberTime: 50, continuousScanning: false, saveFunction: null, onLoad: null, onChange: null, undoDepth: 50, undoDelay: 800, disableSpellcheck: true, textWrapping: true, readOnly: false, width: "", height: "300px", minHeight: 100, autoMatchParens: false, markParen: null, unmarkParen: null, parserConfig: null, tabMode: "indent", // or "spaces", "default", "shift" enterMode: "indent", // or "keep", "flat" electricChars: true, reindentOnLoad: false, activeTokens: null, onCursorActivity: null, lineNumbers: false, firstLineNumber: 1, onLineNumberClick: null, indentUnit: 2, domain: null, noScriptCaching: false, incrementalLoading: false }); function addLineNumberDiv(container, firstNum) { var nums = createHTMLElement("div"), scroller = createHTMLElement("div"); nums.style.position = "absolute"; nums.style.height = "100%"; if (nums.style.setExpression) { try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");} catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions } nums.style.top = "0px"; nums.style.left = "0px"; nums.style.overflow = "hidden"; container.appendChild(nums); scroller.className = "CodeMirror-line-numbers"; nums.appendChild(scroller); scroller.innerHTML = "<div>" + firstNum + "</div>"; return nums; } function frameHTML(options) { if (typeof options.parserfile == "string") options.parserfile = [options.parserfile]; if (typeof options.basefiles == "string") options.basefiles = [options.basefiles]; if (typeof options.stylesheet == "string") options.stylesheet = [options.stylesheet]; var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"]; // Hack to work around a bunch of IE8-specific problems. html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>"); var queryStr = options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : ""; forEach(options.stylesheet, function(file) { html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + queryStr + "\"/>"); }); forEach(options.basefiles.concat(options.parserfile), function(file) { if (!/^https?:/.test(file)) file = options.path + file; html.push("<script type=\"text/javascript\" src=\"" + file + queryStr + "\"><" + "/script>"); }); html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" + (options.disableSpellcheck ? "false" : "true") + "\"></body></html>"); return html.join(""); } var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); function CodeMirror(place, options) { // Use passed options, if any, to override defaults. this.options = options = options || {}; setDefaults(options, CodeMirrorConfig); // Backward compatibility for deprecated options. if (options.dumbTabs) options.tabMode = "spaces"; else if (options.normalTab) options.tabMode = "default"; if (options.cursorActivity) options.onCursorActivity = options.cursorActivity; var frame = this.frame = createHTMLElement("iframe"); if (options.iframeClass) frame.className = options.iframeClass; frame.frameBorder = 0; frame.style.border = "0"; frame.style.width = '100%'; frame.style.height = '100%'; // display: block occasionally suppresses some Firefox bugs, so we // always add it, redundant as it sounds. frame.style.display = "block"; var div = this.wrapping = createHTMLElement("div"); div.style.position = "relative"; div.className = "CodeMirror-wrapping"; div.style.width = options.width; div.style.height = (options.height == "dynamic") ? options.minHeight + "px" : options.height; // This is used by Editor.reroutePasteEvent var teHack = this.textareaHack = createHTMLElement("textarea"); div.appendChild(teHack); teHack.style.position = "absolute"; teHack.style.left = "-10000px"; teHack.style.width = "10px"; teHack.tabIndex = 100000; // Link back to this object, so that the editor can fetch options // and add a reference to itself. frame.CodeMirror = this; if (options.domain && internetExplorer) { this.html = frameHTML(options); frame.src = "javascript:(function(){document.open();" + (options.domain ? "document.domain=\"" + options.domain + "\";" : "") + "document.write(window.frameElement.CodeMirror.html);document.close();})()"; } else { frame.src = "javascript:;"; } if (place.appendChild) place.appendChild(div); else place(div); div.appendChild(frame); if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div, options.firstLineNumber); this.win = frame.contentWindow; if (!options.domain || !internetExplorer) { this.win.document.open(); this.win.document.write(frameHTML(options)); this.win.document.close(); } } CodeMirror.prototype = { init: function() { // Deprecated, but still supported. if (this.options.initCallback) this.options.initCallback(this); if (this.options.onLoad) this.options.onLoad(this); if (this.options.lineNumbers) this.activateLineNumbers(); if (this.options.reindentOnLoad) this.reindent(); if (this.options.height == "dynamic") this.setDynamicHeight(); }, getCode: function() {return this.editor.getCode();}, setCode: function(code) {this.editor.importCode(code);}, selection: function() {this.focusIfIE(); return this.editor.selectedText();}, reindent: function() {this.editor.reindent();}, reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);}, focusIfIE: function() { // in IE, a lot of selection-related functionality only works when the frame is focused if (this.win.select.ie_selection && document.activeElement != this.frame) this.focus(); }, focus: function() { this.win.focus(); if (this.editor.selectionSnapshot) // IE hack this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot); }, replaceSelection: function(text) { this.focus(); this.editor.replaceSelection(text); return true; }, replaceChars: function(text, start, end) { this.editor.replaceChars(text, start, end); }, getSearchCursor: function(string, fromCursor, caseFold) { return this.editor.getSearchCursor(string, fromCursor, caseFold); }, undo: function() {this.editor.history.undo();}, redo: function() {this.editor.history.redo();}, historySize: function() {return this.editor.history.historySize();}, clearHistory: function() {this.editor.history.clear();}, grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);}, ungrabKeys: function() {this.editor.ungrabKeys();}, setParser: function(name, parserConfig) {this.editor.setParser(name, parserConfig);}, setSpellcheck: function(on) {this.win.document.body.spellcheck = on;}, setStylesheet: function(names) { if (typeof names === "string") names = [names]; var activeStylesheets = {}; var matchedNames = {}; var links = this.win.document.getElementsByTagName("link"); // Create hashes of active stylesheets and matched names. // This is O(n^2) but n is expected to be very small. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { for (var y = 0; y < names.length; y++) { var name = names[y]; if (link.href.substring(link.href.length - name.length) === name) { activeStylesheets[link.href] = true; matchedNames[name] = true; } } } } // Activate the selected stylesheets and disable the rest. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { link.disabled = !(link.href in activeStylesheets); } } // Create any new stylesheets. for (var y = 0; y < names.length; y++) { var name = names[y]; if (!(name in matchedNames)) { var link = this.win.document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = name; this.win.document.getElementsByTagName('head')[0].appendChild(link); } } }, setTextWrapping: function(on) { if (on == this.options.textWrapping) return; this.win.document.body.style.whiteSpace = on ? "" : "nowrap"; this.options.textWrapping = on; if (this.lineNumbers) { this.setLineNumbers(false); this.setLineNumbers(true); } }, setIndentUnit: function(unit) {this.win.indentUnit = unit;}, setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;}, setTabMode: function(mode) {this.options.tabMode = mode;}, setEnterMode: function(mode) {this.options.enterMode = mode;}, setLineNumbers: function(on) { if (on && !this.lineNumbers) { this.lineNumbers = addLineNumberDiv(this.wrapping,this.options.firstLineNumber); this.activateLineNumbers(); } else if (!on && this.lineNumbers) { this.wrapping.removeChild(this.lineNumbers); this.wrapping.style.paddingLeft = ""; this.lineNumbers = null; } }, cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);}, firstLine: function() {return this.editor.firstLine();}, lastLine: function() {return this.editor.lastLine();}, nextLine: function(line) {return this.editor.nextLine(line);}, prevLine: function(line) {return this.editor.prevLine(line);}, lineContent: function(line) {return this.editor.lineContent(line);}, setLineContent: function(line, content) {this.editor.setLineContent(line, content);}, removeLine: function(line){this.editor.removeLine(line);}, insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);}, selectLines: function(startLine, startOffset, endLine, endOffset) { this.win.focus(); this.editor.selectLines(startLine, startOffset, endLine, endOffset); }, nthLine: function(n) { var line = this.firstLine(); for (; n > 1 && line !== false; n--) line = this.nextLine(line); return line; }, lineNumber: function(line) { var num = 0; while (line !== false) { num++; line = this.prevLine(line); } return num; }, jumpToLine: function(line) { if (typeof line == "number") line = this.nthLine(line); this.selectLines(line, 0); this.win.focus(); }, currentLine: function() { // Deprecated, but still there for backward compatibility return this.lineNumber(this.cursorLine()); }, cursorLine: function() { return this.cursorPosition().line; }, cursorCoords: function(start) {return this.editor.cursorCoords(start);}, activateLineNumbers: function() { var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body, nums = this.lineNumbers, scroller = nums.firstChild, self = this; var barWidth = null; nums.onclick = function(e) { var handler = self.options.onLineNumberClick; if (handler) { var div = (e || window.event).target || (e || window.event).srcElement; var num = div == nums ? NaN : Number(div.innerHTML); if (!isNaN(num)) handler(num, div); } }; function sizeBar() { if (frame.offsetWidth == 0) return; for (var root = frame; root.parentNode; root = root.parentNode){} if (!nums.parentNode || root != document || !win.Editor) { // Clear event handlers (their nodes might already be collected, so try/catch) try{clear();}catch(e){} clearInterval(sizeInterval); return; } if (nums.offsetWidth != barWidth) { barWidth = nums.offsetWidth; frame.parentNode.style.paddingLeft = barWidth + "px"; } } function doScroll() { nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0; } // Cleanup function, registered by nonWrapping and wrapping. var clear = function(){}; sizeBar(); var sizeInterval = setInterval(sizeBar, 500); function ensureEnoughLineNumbers(fill) { var lineHeight = scroller.firstChild.offsetHeight; if (lineHeight == 0) return; var targetHeight = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0)), lastNumber = Math.ceil(targetHeight / lineHeight); for (var i = scroller.childNodes.length; i <= lastNumber; i++) { var div = createHTMLElement("div"); div.appendChild(document.createTextNode(fill ? String(i + self.options.firstLineNumber) : "\u00a0")); scroller.appendChild(div); } } function nonWrapping() { function update() { ensureEnoughLineNumbers(true); doScroll(); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ onScroll(); onResize(); if (self.updateNumbers == update) self.updateNumbers = null; }; update(); } function wrapping() { var node, lineNum, next, pos, changes = [], styleNums = self.options.styleNumbers; function setNum(n, node) { // Does not typically happen (but can, if you mess with the // document during the numbering) if (!lineNum) lineNum = scroller.appendChild(createHTMLElement("div")); if (styleNums) styleNums(lineNum, node, n); // Changes are accumulated, so that the document layout // doesn't have to be recomputed during the pass changes.push(lineNum); changes.push(n); pos = lineNum.offsetHeight + lineNum.offsetTop; lineNum = lineNum.nextSibling; } function commitChanges() { for (var i = 0; i < changes.length; i += 2) changes[i].innerHTML = changes[i + 1]; changes = []; } function work() { if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return; var endTime = new Date().getTime() + self.options.lineNumberTime; while (node) { setNum(next++, node.previousSibling); for (; node && !win.isBR(node); node = node.nextSibling) { var bott = node.offsetTop + node.offsetHeight; while (scroller.offsetHeight && bott - 3 > pos) { var oldPos = pos; setNum("&nbsp;"); if (pos <= oldPos) break; } } if (node) node = node.nextSibling; if (new Date().getTime() > endTime) { commitChanges(); pending = setTimeout(work, self.options.lineNumberDelay); return; } } while (lineNum) setNum(next++); commitChanges(); doScroll(); } function start(firstTime) { doScroll(); ensureEnoughLineNumbers(firstTime); node = body.firstChild; lineNum = scroller.firstChild; pos = 0; next = self.options.firstLineNumber; work(); } start(true); var pending = null; function update() { if (pending) clearTimeout(pending); if (self.editor.allClean()) start(); else pending = setTimeout(update, 200); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ if (pending) clearTimeout(pending); if (self.updateNumbers == update) self.updateNumbers = null; onScroll(); onResize(); }; } (this.options.textWrapping || this.options.styleNumbers ? wrapping : nonWrapping)(); }, setDynamicHeight: function() { var self = this, activity = self.options.onCursorActivity, win = self.win, body = win.document.body, lineHeight = null, timeout = null, vmargin = 2 * self.frame.offsetTop; body.style.overflowY = "hidden"; win.document.documentElement.style.overflowY = "hidden"; this.frame.scrolling = "no"; function updateHeight() { var trailingLines = 0, node = body.lastChild, computedHeight; while (node && win.isBR(node)) { if (!node.hackBR) trailingLines++; node = node.previousSibling; } if (node) { lineHeight = node.offsetHeight; computedHeight = node.offsetTop + (1 + trailingLines) * lineHeight; } else if (lineHeight) { computedHeight = trailingLines * lineHeight; } if (computedHeight) self.wrapping.style.height = Math.max(vmargin + computedHeight, self.options.minHeight) + "px"; } setTimeout(updateHeight, 300); self.options.onCursorActivity = function(x) { if (activity) activity(x); clearTimeout(timeout); timeout = setTimeout(updateHeight, 100); }; } }; CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}}; CodeMirror.replace = function(element) { if (typeof element == "string") element = document.getElementById(element); return function(newElement) { element.parentNode.replaceChild(newElement, element); }; }; CodeMirror.fromTextArea = function(area, options) { if (typeof area == "string") area = document.getElementById(area); options = options || {}; if (area.style.width && options.width == null) options.width = area.style.width; if (area.style.height && options.height == null) options.height = area.style.height; if (options.content == null) options.content = area.value; function updateField() { area.value = mirror.getCode(); } if (area.form) { if (typeof area.form.addEventListener == "function") area.form.addEventListener("submit", updateField, false); else area.form.attachEvent("onsubmit", updateField); var realSubmit = area.form.submit; function wrapSubmit() { updateField(); // Can't use realSubmit.apply because IE6 is too stupid area.form.submit = realSubmit; area.form.submit(); area.form.submit = wrapSubmit; } area.form.submit = wrapSubmit; } function insert(frame) { if (area.nextSibling) area.parentNode.insertBefore(frame, area.nextSibling); else area.parentNode.appendChild(frame); } area.style.display = "none"; var mirror = new CodeMirror(insert, options); mirror.save = updateField; mirror.toTextArea = function() { updateField(); area.parentNode.removeChild(mirror.wrapping); area.style.display = ""; if (area.form) { area.form.submit = realSubmit; if (typeof area.form.removeEventListener == "function") area.form.removeEventListener("submit", updateField, false); else area.form.detachEvent("onsubmit", updateField); } }; return mirror; }; CodeMirror.isProbablySupported = function() { // This is rather awful, but can be useful. var match; if (window.opera) return Number(window.opera.version()) >= 9.52; else if (/Apple Computer, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./))) return Number(match[1]) >= 3; else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/))) return Number(match[1]) >= 6; else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i)) return Number(match[1]) >= 20050901; else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/)) return Number(match[1]) >= 525; else return null; }; return CodeMirror; })();
JavaScript
// Minimal framing needed to use CodeMirror-style parsers to highlight // code. Load this along with tokenize.js, stringstream.js, and your // parser. Then call highlightText, passing a string as the first // argument, and as the second argument either a callback function // that will be called with an array of SPAN nodes for every line in // the code, or a DOM node to which to append these spans, and // optionally (not needed if you only loaded one parser) a parser // object. // Stuff from util.js that the parsers are using. var StopIteration = {toString: function() {return "StopIteration"}}; var Editor = {}; var indentUnit = 2; (function(){ function normaliseString(string) { var tab = ""; for (var i = 0; i < indentUnit; i++) tab += " "; string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n"); var pos = 0, parts = [], lines = string.split("\n"); for (var line = 0; line < lines.length; line++) { if (line != 0) parts.push("\n"); parts.push(lines[line]); } return { next: function() { if (pos < parts.length) return parts[pos++]; else throw StopIteration; } }; } window.highlightText = function(string, callback, parser) { parser = (parser || Editor.Parser).make(stringStream(normaliseString(string))); var line = []; if (callback.nodeType == 1) { var node = callback; callback = function(line) { for (var i = 0; i < line.length; i++) node.appendChild(line[i]); node.appendChild(document.createElement("br")); }; } try { while (true) { var token = parser.next(); if (token.value == "\n") { callback(line); line = []; } else { var span = document.createElement("span"); span.className = token.style; span.appendChild(document.createTextNode(token.value)); line.push(span); } } } catch (e) { if (e != StopIteration) throw e; } if (line.length) callback(line); } })();
JavaScript
/* The Editor object manages the content of the editable frame. It * catches events, colours nodes, and indents lines. This file also * holds some functions for transforming arbitrary DOM structures into * plain sequences of <span> and <br> elements */ var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); var webkit = /AppleWebKit/.test(navigator.userAgent); var safari = /Apple Computer, Inc/.test(navigator.vendor); var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i); if (gecko) gecko = Number(gecko[1]); var mac = /Mac/.test(navigator.platform); // TODO this is related to the backspace-at-end-of-line bug. Remove // this if Opera gets their act together, make the version check more // broad if they don't. var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent); // TODO remove this once WebKit 533 becomes less common. var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent); // Make sure a string does not contain two consecutive 'collapseable' // whitespace characters. function makeWhiteSpace(n) { var buffer = [], nb = true; for (; n > 0; n--) { buffer.push((nb || n == 1) ? nbsp : " "); nb ^= true; } return buffer.join(""); } // Create a set of white-space characters that will not be collapsed // by the browser, but will not break text-wrapping either. function fixSpaces(string) { if (string.charAt(0) == " ") string = nbsp + string.slice(1); return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);}) .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);}); } function cleanText(text) { return text.replace(/\u00a0/g, " ").replace(/\u200b/g, ""); } // Create a SPAN node with the expected properties for document part // spans. function makePartSpan(value) { var text = value; if (value.nodeType == 3) text = value.nodeValue; else value = document.createTextNode(text); var span = document.createElement("span"); span.isPart = true; span.appendChild(value); span.currentText = text; return span; } function alwaysZero() {return 0;} // On webkit, when the last BR of the document does not have text // behind it, the cursor can not be put on the line after it. This // makes pressing enter at the end of the document occasionally do // nothing (or at least seem to do nothing). To work around it, this // function makes sure the document ends with a span containing a // zero-width space character. The traverseDOM iterator filters such // character out again, so that the parsers won't see them. This // function is called from a few strategic places to make sure the // zwsp is restored after the highlighting process eats it. var webkitLastLineHack = webkit ? function(container) { var last = container.lastChild; if (!last || !last.hackBR) { var br = document.createElement("br"); br.hackBR = true; container.appendChild(br); } } : function() {}; function asEditorLines(string) { var tab = makeWhiteSpace(indentUnit); return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces); } var Editor = (function(){ // The HTML elements whose content should be suffixed by a newline // when converting them to flat text. var newlineElements = {"P": true, "DIV": true, "LI": true}; // Helper function for traverseDOM. Flattens an arbitrary DOM node // into an array of textnodes and <br> tags. function simplifyDOM(root, atEnd) { var result = []; var leaving = true; function simplifyNode(node, top) { if (node.nodeType == 3) { var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " ")); if (text.length) leaving = false; result.push(node); } else if (isBR(node) && node.childNodes.length == 0) { leaving = true; result.push(node); } else { for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n); if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) { leaving = true; if (!atEnd || !top) result.push(document.createElement("br")); } } } simplifyNode(root, true); return result; } // Creates a MochiKit-style iterator that goes over a series of DOM // nodes. The values it yields are strings, the textual content of // the nodes. It makes sure that all nodes up to and including the // one whose text is being yielded have been 'normalized' to be just // <span> and <br> elements. function traverseDOM(start){ var nodeQueue = []; // Create a function that can be used to insert nodes after the // one given as argument. function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; } var point = null; // This an Opera-specific hack -- always insert an empty span // between two BRs, because Opera's cursor code gets terribly // confused when the cursor is between two BRs. var afterBR = true; // Insert a normalized node at the current point. If it is a text // node, wrap it in a <span>, and give that span a currentText // property -- this is used to cache the nodeValue, because // directly accessing nodeValue is horribly slow on some browsers. // The dirty property is used by the highlighter to determine // which parts of the document have to be re-highlighted. function insertPart(part){ var text = "\n"; if (part.nodeType == 3) { select.snapshotChanged(); part = makePartSpan(part); text = part.currentText; afterBR = false; } else { if (afterBR && window.opera) point(makePartSpan("")); afterBR = true; } part.dirty = true; nodeQueue.push(part); point(part); return text; } // Extract the text and newlines from a DOM node, insert them into // the document, and return the textual content. Used to replace // non-normalized nodes. function writeNode(node, end) { var simplified = simplifyDOM(node, end); for (var i = 0; i < simplified.length; i++) simplified[i] = insertPart(simplified[i]); return simplified.join(""); } // Check whether a node is a normalized <span> element. function partNode(node){ if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { var text = node.firstChild.nodeValue; node.dirty = node.dirty || text != node.currentText; node.currentText = text; return !/[\n\t\r]/.test(node.currentText); } return false; } // Advance to next node, return string for current node. function next() { if (!start) throw StopIteration; var node = start; start = node.nextSibling; if (partNode(node)){ nodeQueue.push(node); afterBR = false; return node.currentText; } else if (isBR(node)) { if (afterBR && window.opera) node.parentNode.insertBefore(makePartSpan(""), node); nodeQueue.push(node); afterBR = true; return "\n"; } else { var end = !node.nextSibling; point = pointAt(node); removeElement(node); return writeNode(node, end); } } // MochiKit iterators are objects with a next function that // returns the next value or throws StopIteration when there are // no more values. return {next: next, nodes: nodeQueue}; } // Determine the text size of a processed node. function nodeSize(node) { return isBR(node) ? 1 : node.currentText.length; } // Search backwards through the top-level nodes until the next BR or // the start of the frame. function startOfLine(node) { while (node && !isBR(node)) node = node.previousSibling; return node; } function endOfLine(node, container) { if (!node) node = container.firstChild; else if (isBR(node)) node = node.nextSibling; while (node && !isBR(node)) node = node.nextSibling; return node; } function time() {return new Date().getTime();} // Client interface for searching the content of the editor. Create // these by calling CodeMirror.getSearchCursor. To use, call // findNext on the resulting object -- this returns a boolean // indicating whether anything was found, and can be called again to // skip to the next find. Use the select and replace methods to // actually do something with the found locations. function SearchCursor(editor, pattern, from, caseFold) { this.editor = editor; this.history = editor.history; this.history.commit(); this.valid = !!pattern; this.atOccurrence = false; if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase(); function getText(node){ var line = cleanText(editor.history.textAfter(node)); return (caseFold ? line.toLowerCase() : line); } var topPos = {node: null, offset: 0}, self = this; if (from && typeof from == "object" && typeof from.character == "number") { editor.checkLine(from.line); var pos = {node: from.line, offset: from.character}; this.pos = {from: pos, to: pos}; } else if (from) { this.pos = {from: select.cursorPos(editor.container, true) || topPos, to: select.cursorPos(editor.container, false) || topPos}; } else { this.pos = {from: topPos, to: topPos}; } if (typeof pattern != "string") { // Regexp match this.matches = function(reverse, node, offset) { if (reverse) { var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0; while (match) { var ind = line.indexOf(match[0]); start += ind; line = line.slice(ind + 1); var newmatch = line.match(pattern); if (newmatch) match = newmatch; else break; } } else { var line = getText(node).slice(offset), match = line.match(pattern), start = match && offset + line.indexOf(match[0]); } if (match) { self.currentMatch = match; return {from: {node: node, offset: start}, to: {node: node, offset: start + match[0].length}}; } }; return; } if (caseFold) pattern = pattern.toLowerCase(); // Create a matcher function based on the kind of string we have. var target = pattern.split("\n"); this.matches = (target.length == 1) ? // For one-line strings, searching can be done simply by calling // indexOf or lastIndexOf on the current line. function(reverse, node, offset) { var line = getText(node), len = pattern.length, match; if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1) : (match = line.indexOf(pattern, offset)) != -1) return {from: {node: node, offset: match}, to: {node: node, offset: match + len}}; } : // Multi-line strings require internal iteration over lines, and // some clunky checks to make sure the first match ends at the // end of the line and the last match starts at the start. function(reverse, node, offset) { var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); if (reverse ? offsetA >= offset || offsetA != match.length : offsetA <= offset || offsetA != line.length - match.length) return; var pos = node; while (true) { if (reverse && !pos) return; pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) ); if (!reverse && !pos) return; line = getText(pos); match = target[reverse ? --idx : ++idx]; if (idx > 0 && idx < target.length - 1) { if (line != match) return; else continue; } var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA}, to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}}; } }; } SearchCursor.prototype = { findNext: function() {return this.find(false);}, findPrevious: function() {return this.find(true);}, find: function(reverse) { if (!this.valid) return false; var self = this, pos = reverse ? this.pos.from : this.pos.to, node = pos.node, offset = pos.offset; // Reset the cursor if the current line is no longer in the DOM tree. if (node && !node.parentNode) { node = null; offset = 0; } function savePosAndFail() { var pos = {node: node, offset: offset}; self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; } while (true) { if (this.pos = this.matches(reverse, node, offset)) { this.atOccurrence = true; return true; } if (reverse) { if (!node) return savePosAndFail(); node = this.history.nodeBefore(node); offset = this.history.textAfter(node).length; } else { var next = this.history.nodeAfter(node); if (!next) { offset = this.history.textAfter(node).length; return savePosAndFail(); } node = next; offset = 0; } } }, select: function() { if (this.atOccurrence) { select.setCursorPos(this.editor.container, this.pos.from, this.pos.to); select.scrollToCursor(this.editor.container); } }, replace: function(string) { if (this.atOccurrence) { var fragments = this.currentMatch; if (fragments) string = string.replace(/\\(\d)/, function(m, i){return fragments[i];}); var end = this.editor.replaceRange(this.pos.from, this.pos.to, string); this.pos.to = end; this.atOccurrence = false; } }, position: function() { if (this.atOccurrence) return {line: this.pos.from.node, character: this.pos.from.offset}; } }; // The Editor object is the main inside-the-iframe interface. function Editor(options) { this.options = options; window.indentUnit = options.indentUnit; var container = this.container = document.body; this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this); var self = this; if (!Editor.Parser) throw "No parser loaded."; if (options.parserConfig && Editor.Parser.configure) Editor.Parser.configure(options.parserConfig); if (!options.readOnly && !internetExplorer) select.setCursorPos(container, {node: null, offset: 0}); this.dirty = []; this.importCode(options.content || ""); this.history.onChange = options.onChange; if (!options.readOnly) { if (options.continuousScanning !== false) { this.scanner = this.documentScanner(options.passTime); this.delayScanning(); } function setEditable() { // Use contentEditable instead of designMode on IE, since designMode frames // can not run any scripts. It would be nice if we could use contentEditable // everywhere, but it is significantly flakier than designMode on every // single non-IE browser. if (document.body.contentEditable != undefined && internetExplorer) document.body.contentEditable = "true"; else document.designMode = "on"; // Work around issue where you have to click on the actual // body of the document to focus it in IE, making focusing // hard when the document is small. if (internetExplorer && options.height != "dynamic") document.body.style.minHeight = ( window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px"; document.documentElement.style.borderWidth = "0"; if (!options.textWrapping) container.style.whiteSpace = "nowrap"; } // If setting the frame editable fails, try again when the user // focus it (happens when the frame is not visible on // initialisation, in Firefox). try { setEditable(); } catch(e) { var focusEvent = addEventHandler(document, "focus", function() { focusEvent(); setEditable(); }, true); } addEventHandler(document, "keydown", method(this, "keyDown")); addEventHandler(document, "keypress", method(this, "keyPress")); addEventHandler(document, "keyup", method(this, "keyUp")); function cursorActivity() {self.cursorActivity(false);} addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity); addEventHandler(document.body, "cut", cursorActivity); // workaround for a gecko bug [?] where going forward and then // back again breaks designmode (no more cursor) if (gecko) addEventHandler(window, "pagehide", function(){self.unloaded = true;}); addEventHandler(document.body, "paste", function(event) { cursorActivity(); var text = null; try { var clipboardData = event.clipboardData || window.clipboardData; if (clipboardData) text = clipboardData.getData('Text'); } catch(e) {} if (text !== null) { event.stop(); self.replaceSelection(text); select.scrollToCursor(self.container); } }); if (this.options.autoMatchParens) addEventHandler(document.body, "click", method(this, "scheduleParenHighlight")); } else if (!options.textWrapping) { container.style.whiteSpace = "nowrap"; } } function isSafeKey(code) { return (code >= 16 && code <= 18) || // shift, control, alt (code >= 33 && code <= 40); // arrows, home, end } Editor.prototype = { // Import a piece of code into the editor. importCode: function(code) { var lines = asEditorLines(code), chunk = 1000; if (!this.options.incrementalLoading || lines.length < chunk) { this.history.push(null, null, lines); this.history.reset(); } else { var cur = 0, self = this; function addChunk() { var chunklines = lines.slice(cur, cur + chunk); chunklines.push(""); self.history.push(self.history.nodeBefore(null), null, chunklines); self.history.reset(); cur += chunk; if (cur < lines.length) parent.setTimeout(addChunk, 1000); } addChunk(); } }, // Extract the code from the editor. getCode: function() { if (!this.container.firstChild) return ""; var accum = []; select.markSelection(); forEach(traverseDOM(this.container.firstChild), method(accum, "push")); select.selectMarked(); // On webkit, don't count last (empty) line if the webkitLastLineHack BR is present if (webkit && this.container.lastChild.hackBR) accum.pop(); webkitLastLineHack(this.container); return cleanText(accum.join("")); }, checkLine: function(node) { if (node === false || !(node == null || node.parentNode == this.container || node.hackBR)) throw parent.CodeMirror.InvalidLineHandle; }, cursorPosition: function(start) { if (start == null) start = true; var pos = select.cursorPos(this.container, start); if (pos) return {line: pos.node, character: pos.offset}; else return {line: null, character: 0}; }, firstLine: function() { return null; }, lastLine: function() { var last = this.container.lastChild; if (last) last = startOfLine(last); if (last && last.hackBR) last = startOfLine(last.previousSibling); return last; }, nextLine: function(line) { this.checkLine(line); var end = endOfLine(line, this.container); if (!end || end.hackBR) return false; else return end; }, prevLine: function(line) { this.checkLine(line); if (line == null) return false; return startOfLine(line.previousSibling); }, visibleLineCount: function() { var line = this.container.firstChild; while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable if (!line) return false; var innerHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight); return Math.floor(innerHeight / line.offsetHeight); }, selectLines: function(startLine, startOffset, endLine, endOffset) { this.checkLine(startLine); var start = {node: startLine, offset: startOffset}, end = null; if (endOffset !== undefined) { this.checkLine(endLine); end = {node: endLine, offset: endOffset}; } select.setCursorPos(this.container, start, end); select.scrollToCursor(this.container); }, lineContent: function(line) { var accum = []; for (line = line ? line.nextSibling : this.container.firstChild; line && !isBR(line); line = line.nextSibling) accum.push(nodeText(line)); return cleanText(accum.join("")); }, setLineContent: function(line, content) { this.history.commit(); this.replaceRange({node: line, offset: 0}, {node: line, offset: this.history.textAfter(line).length}, content); this.addDirtyNode(line); this.scheduleHighlight(); }, removeLine: function(line) { var node = line ? line.nextSibling : this.container.firstChild; while (node) { var next = node.nextSibling; removeElement(node); if (isBR(node)) break; node = next; } this.addDirtyNode(line); this.scheduleHighlight(); }, insertIntoLine: function(line, position, content) { var before = null; if (position == "end") { before = endOfLine(line, this.container); } else { for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) { if (position == 0) { before = cur; break; } var text = nodeText(cur); if (text.length > position) { before = cur.nextSibling; content = text.slice(0, position) + content + text.slice(position); removeElement(cur); break; } position -= text.length; } } var lines = asEditorLines(content); for (var i = 0; i < lines.length; i++) { if (i > 0) this.container.insertBefore(document.createElement("BR"), before); this.container.insertBefore(makePartSpan(lines[i]), before); } this.addDirtyNode(line); this.scheduleHighlight(); }, // Retrieve the selected text. selectedText: function() { var h = this.history; h.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return ""; if (start.node == end.node) return h.textAfter(start.node).slice(start.offset, end.offset); var text = [h.textAfter(start.node).slice(start.offset)]; for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos)) text.push(h.textAfter(pos)); text.push(h.textAfter(end.node).slice(0, end.offset)); return cleanText(text.join("\n")); }, // Replace the selection with another piece of text. replaceSelection: function(text) { this.history.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return; end = this.replaceRange(start, end, text); select.setCursorPos(this.container, end); webkitLastLineHack(this.container); }, cursorCoords: function(start, internal) { var sel = select.cursorPos(this.container, start); if (!sel) return null; var off = sel.offset, node = sel.node, self = this; function measureFromNode(node, xOffset) { var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0), x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset; forEach([node, internal ? null : window.frameElement], function(n) { while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;} }); return {x: x, y: y, yBot: y + node.offsetHeight}; } function withTempNode(text, f) { var node = document.createElement("SPAN"); node.appendChild(document.createTextNode(text)); try {return f(node);} finally {if (node.parentNode) node.parentNode.removeChild(node);} } while (off) { node = node ? node.nextSibling : this.container.firstChild; var txt = nodeText(node); if (off < txt.length) return withTempNode(txt.substr(0, off), function(tmp) { tmp.style.position = "absolute"; tmp.style.visibility = "hidden"; tmp.className = node.className; self.container.appendChild(tmp); return measureFromNode(node, tmp.offsetWidth); }); off -= txt.length; } if (node && isSpan(node)) return measureFromNode(node, node.offsetWidth); else if (node && node.nextSibling && isSpan(node.nextSibling)) return measureFromNode(node.nextSibling, 0); else return withTempNode("\u200b", function(tmp) { if (node) node.parentNode.insertBefore(tmp, node.nextSibling); else self.container.insertBefore(tmp, self.container.firstChild); return measureFromNode(tmp, 0); }); }, reroutePasteEvent: function() { if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return; this.capturingPaste = true; var te = window.frameElement.CodeMirror.textareaHack; var coords = this.cursorCoords(true, true); te.style.top = coords.y + "px"; if (internetExplorer) { var snapshot = select.getBookmark(this.container); if (snapshot) this.selectionSnapshot = snapshot; } parent.focus(); te.value = ""; te.focus(); var self = this; parent.setTimeout(function() { self.capturingPaste = false; window.focus(); if (self.selectionSnapshot) // IE hack window.select.setBookmark(self.container, self.selectionSnapshot); var text = te.value; if (text) { self.replaceSelection(text); select.scrollToCursor(self.container); } }, 10); }, replaceRange: function(from, to, text) { var lines = asEditorLines(text); lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0]; var lastLine = lines[lines.length - 1]; lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset); var end = this.history.nodeAfter(to.node); this.history.push(from.node, end, lines); return {node: this.history.nodeBefore(end), offset: lastLine.length}; }, getSearchCursor: function(string, fromCursor, caseFold) { return new SearchCursor(this, string, fromCursor, caseFold); }, // Re-indent the whole buffer reindent: function() { if (this.container.firstChild) this.indentRegion(null, this.container.lastChild); }, reindentSelection: function(direction) { if (!select.somethingSelected()) { this.indentAtCursor(direction); } else { var start = select.selectionTopNode(this.container, true), end = select.selectionTopNode(this.container, false); if (start === false || end === false) return; this.indentRegion(start, end, direction); } }, grabKeys: function(eventHandler, filter) { this.frozen = eventHandler; this.keyFilter = filter; }, ungrabKeys: function() { this.frozen = "leave"; }, setParser: function(name, parserConfig) { Editor.Parser = window[name]; parserConfig = parserConfig || this.options.parserConfig; if (parserConfig && Editor.Parser.configure) Editor.Parser.configure(parserConfig); if (this.container.firstChild) { forEach(this.container.childNodes, function(n) { if (n.nodeType != 3) n.dirty = true; }); this.addDirtyNode(this.firstChild); this.scheduleHighlight(); } }, // Intercept enter and tab, and assign their new functions. keyDown: function(event) { if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;} if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) { event.stop(); this.frozen(event); return; } var code = event.keyCode; // Don't scan when the user is typing. this.delayScanning(); // Schedule a paren-highlight event, if configured. if (this.options.autoMatchParens) this.scheduleParenHighlight(); // The various checks for !altKey are there because AltGr sets both // ctrlKey and altKey to true, and should not be recognised as // Control. if (code == 13) { // enter if (event.ctrlKey && !event.altKey) { this.reparseBuffer(); } else { select.insertNewlineAtCursor(); var mode = this.options.enterMode; if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined); select.scrollToCursor(this.container); } event.stop(); } else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab this.handleTab(!event.shiftKey); event.stop(); } else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space this.handleTab(true); event.stop(); } else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home if (this.home()) event.stop(); } else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end if (this.end()) event.stop(); } // Only in Firefox is the default behavior for PgUp/PgDn correct. else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp if (this.pageUp()) event.stop(); } else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn if (this.pageDown()) event.stop(); } else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ] this.highlightParens(event.shiftKey, true); event.stop(); } else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right var cursor = select.selectionTopNode(this.container); if (cursor === false || !this.container.firstChild) return; if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container); else { var end = endOfLine(cursor, this.container); select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container); } event.stop(); } else if ((event.ctrlKey || event.metaKey) && !event.altKey) { if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y select.scrollToNode(this.history.redo()); event.stop(); } else if (code == 90 || (safari && code == 8)) { // Z, backspace select.scrollToNode(this.history.undo()); event.stop(); } else if (code == 83 && this.options.saveFunction) { // S this.options.saveFunction(); event.stop(); } else if (code == 86 && !mac) { // V this.reroutePasteEvent(); } } }, // Check for characters that should re-indent the current line, // and prevent Opera from handling enter and tab anyway. keyPress: function(event) { var electric = this.options.electricChars && Editor.Parser.electricChars, self = this; // Hack for Opera, and Firefox on OS X, in which stopping a // keydown event does not prevent the associated keypress event // from happening, so we have to cancel enter and tab again // here. if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) || event.code == 13 || (event.code == 9 && this.options.tabMode != "default") || (event.code == 32 && event.shiftKey && this.options.tabMode == "default")) event.stop(); else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") { this.reroutePasteEvent(); } else if (electric && electric.indexOf(event.character) != -1) parent.setTimeout(function(){self.indentAtCursor(null);}, 0); // Work around a bug where pressing backspace at the end of a // line, or delete at the start, often causes the cursor to jump // to the start of the line in Opera 10.60. else if (brokenOpera) { if (event.code == 8) { // backspace var sel = select.selectionTopNode(this.container), self = this, next = sel ? sel.nextSibling : this.container.firstChild; if (sel !== false && next && isBR(next)) parent.setTimeout(function(){ if (select.selectionTopNode(self.container) == next) select.focusAfterNode(next.previousSibling, self.container); }, 20); } else if (event.code == 46) { // delete var sel = select.selectionTopNode(this.container), self = this; if (sel && isBR(sel)) { parent.setTimeout(function(){ if (select.selectionTopNode(self.container) != sel) select.focusAfterNode(sel, self.container); }, 20); } } } // In 533.* WebKit versions, when the document is big, typing // something at the end of a line causes the browser to do some // kind of stupid heavy operation, creating delays of several // seconds before the typed characters appear. This very crude // hack inserts a temporary zero-width space after the cursor to // make it not be at the end of the line. else if (slowWebkit) { var sel = select.selectionTopNode(this.container), next = sel ? sel.nextSibling : this.container.firstChild; // Doesn't work on empty lines, for some reason those always // trigger the delay. if (sel && next && isBR(next) && !isBR(sel)) { var cheat = document.createTextNode("\u200b"); this.container.insertBefore(cheat, next); parent.setTimeout(function() { if (cheat.nodeValue == "\u200b") removeElement(cheat); else cheat.nodeValue = cheat.nodeValue.replace("\u200b", ""); }, 20); } } // Magic incantation that works abound a webkit bug when you // can't type on a blank line following a line that's wider than // the window. if (webkit && !this.options.textWrapping) setTimeout(function () { var node = select.selectionTopNode(self.container, true); if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling) && node.nextSibling && isBR(node.nextSibling)) node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling); }, 50); }, // Mark the node at the cursor dirty when a non-safe key is // released. keyUp: function(event) { this.cursorActivity(isSafeKey(event.keyCode)); }, // Indent the line following a given <br>, or null for the first // line. If given a <br> element, this must have been highlighted // so that it has an indentation method. Returns the whitespace // element that has been modified or created (if any). indentLineAfter: function(start, direction) { function whiteSpaceAfter(node) { var ws = node ? node.nextSibling : self.container.firstChild; if (!ws || !hasClass(ws, "whitespace")) return null; return ws; } // whiteSpace is the whitespace span at the start of the line, // or null if there is no such node. var self = this, whiteSpace = whiteSpaceAfter(start); var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0; var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild); if (direction == "keep") { if (start) { var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling)) if (prevWS) newIndent = prevWS.currentText.length; } } else { // Sometimes the start of the line can influence the correct // indentation, so we retrieve it. var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : ""; // Ask the lexical context for the correct indentation, and // compute how much this differs from the current indentation. if (direction != null && this.options.tabMode == "shift") newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit) else if (start) newIndent = start.indentation(nextChars, curIndent, direction, firstText); else if (Editor.Parser.firstIndentation) newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText); } var indentDiff = newIndent - curIndent; // If there is too much, this is just a matter of shrinking a span. if (indentDiff < 0) { if (newIndent == 0) { if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0); removeElement(whiteSpace); whiteSpace = null; } else { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; } } // Not enough... else if (indentDiff > 0) { // If there is whitespace, we grow it. if (whiteSpace) { whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); } // Otherwise, we have to add a new whitespace node. else { whiteSpace = makePartSpan(makeWhiteSpace(newIndent)); whiteSpace.className = "whitespace"; if (start) insertAfter(whiteSpace, start); else this.container.insertBefore(whiteSpace, this.container.firstChild); select.snapshotMove(firstText && (firstText.firstChild || firstText), whiteSpace.firstChild, newIndent, false, true); } } // Make sure cursor ends up after the whitespace else if (whiteSpace) { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false); } if (indentDiff != 0) this.addDirtyNode(start); }, // Re-highlight the selected part of the document. highlightAtCursor: function() { var pos = select.selectionTopNode(this.container, true); var to = select.selectionTopNode(this.container, false); if (pos === false || to === false) return false; select.markSelection(); if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false) return false; select.selectMarked(); return true; }, // When tab is pressed with text selected, the whole selection is // re-indented, when nothing is selected, the line with the cursor // is re-indented. handleTab: function(direction) { if (this.options.tabMode == "spaces") select.insertTabAtCursor(); else this.reindentSelection(direction); }, // Custom home behaviour that doesn't land the cursor in front of // leading whitespace unless pressed twice. home: function() { var cur = select.selectionTopNode(this.container, true), start = cur; if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild) return false; while (cur && !isBR(cur)) cur = cur.previousSibling; var next = cur ? cur.nextSibling : this.container.firstChild; if (next && next != start && next.isPart && hasClass(next, "whitespace")) select.focusAfterNode(next, this.container); else select.focusAfterNode(cur, this.container); select.scrollToCursor(this.container); return true; }, // Some browsers (Opera) don't manage to handle the end key // properly in the face of vertical scrolling. end: function() { var cur = select.selectionTopNode(this.container, true); if (cur === false) return false; cur = endOfLine(cur, this.container); if (!cur) return false; select.focusAfterNode(cur.previousSibling, this.container); select.scrollToCursor(this.container); return true; }, pageUp: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to keep one line on the screen. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { line = this.prevLine(line); if (line === false) break; } if (i == 0) return false; // Already at first line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, pageDown: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to move to the last line of the current page. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { var nextLine = this.nextLine(line); if (nextLine === false) break; line = nextLine; } if (i == 0) return false; // Already at last line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, // Delay (or initiate) the next paren highlight event. scheduleParenHighlight: function() { if (this.parenEvent) parent.clearTimeout(this.parenEvent); var self = this; this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300); }, // Take the token before the cursor. If it contains a character in // '()[]{}', search for the matching paren/brace/bracket, and // highlight them in green for a moment, or red if no proper match // was found. highlightParens: function(jump, fromKey) { var self = this, mark = this.options.markParen; if (typeof mark == "string") mark = [mark, mark]; // give the relevant nodes a colour. function highlight(node, ok) { if (!node) return; if (!mark) { node.style.fontWeight = "bold"; node.style.color = ok ? "#8F8" : "#F88"; } else if (mark.call) mark(node, ok); else node.className += " " + mark[ok ? 0 : 1]; } function unhighlight(node) { if (!node) return; if (mark && !mark.call) removeClass(removeClass(node, mark[0]), mark[1]); else if (self.options.unmarkParen) self.options.unmarkParen(node); else { node.style.fontWeight = ""; node.style.color = ""; } } if (!fromKey && self.highlighted) { unhighlight(self.highlighted[0]); unhighlight(self.highlighted[1]); } if (!window || !window.parent || !window.select) return; // Clear the event property. if (this.parenEvent) parent.clearTimeout(this.parenEvent); this.parenEvent = null; // Extract a 'paren' from a piece of text. function paren(node) { if (node.currentText) { var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/); return match && match[1]; } } // Determine the direction a paren is facing. function forward(ch) { return /[\(\[\{]/.test(ch); } var ch, cursor = select.selectionTopNode(this.container, true); if (!cursor || !this.highlightAtCursor()) return; cursor = select.selectionTopNode(this.container, true); if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor))))) return; // We only look for tokens with the same className. var className = cursor.className, dir = forward(ch), match = matching[ch]; // Since parts of the document might not have been properly // highlighted, and it is hard to know in advance which part we // have to scan, we just try, and when we find dirty nodes we // abort, parse them, and re-try. function tryFindMatch() { var stack = [], ch, ok = true; for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) { if (runner.className == className && isSpan(runner) && (ch = paren(runner))) { if (forward(ch) == dir) stack.push(ch); else if (!stack.length) ok = false; else if (stack.pop() != matching[ch]) ok = false; if (!stack.length) break; } else if (runner.dirty || !isSpan(runner) && !isBR(runner)) { return {node: runner, status: "dirty"}; } } return {node: runner, status: runner && ok}; } while (true) { var found = tryFindMatch(); if (found.status == "dirty") { this.highlight(found.node, endOfLine(found.node)); // Needed because in some corner cases a highlight does not // reach a node. found.node.dirty = false; continue; } else { highlight(cursor, found.status); highlight(found.node, found.status); if (fromKey) parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500); else self.highlighted = [cursor, found.node]; if (jump && found.node) select.focusAfterNode(found.node.previousSibling, this.container); break; } } }, // Adjust the amount of whitespace at the start of the line that // the cursor is on so that it is indented properly. indentAtCursor: function(direction) { if (!this.container.firstChild) return; // The line has to have up-to-date lexical information, so we // highlight it first. if (!this.highlightAtCursor()) return; var cursor = select.selectionTopNode(this.container, false); // If we couldn't determine the place of the cursor, // there's nothing to indent. if (cursor === false) return; select.markSelection(); this.indentLineAfter(startOfLine(cursor), direction); select.selectMarked(); }, // Indent all lines whose start falls inside of the current // selection. indentRegion: function(start, end, direction) { var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling); if (!isBR(end)) end = endOfLine(end, this.container); this.addDirtyNode(start); do { var next = endOfLine(current, this.container); if (current) this.highlight(before, next, true); this.indentLineAfter(current, direction); before = current; current = next; } while (current != end); select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0}); }, // Find the node that the cursor is in, mark it as dirty, and make // sure a highlight pass is scheduled. cursorActivity: function(safe) { // pagehide event hack above if (this.unloaded) { window.document.designMode = "off"; window.document.designMode = "on"; this.unloaded = false; } if (internetExplorer) { this.container.createTextRange().execCommand("unlink"); clearTimeout(this.saveSelectionSnapshot); var self = this; this.saveSelectionSnapshot = setTimeout(function() { var snapshot = select.getBookmark(self.container); if (snapshot) self.selectionSnapshot = snapshot; }, 200); } var activity = this.options.onCursorActivity; if (!safe || activity) { var cursor = select.selectionTopNode(this.container, false); if (cursor === false || !this.container.firstChild) return; cursor = cursor || this.container.firstChild; if (activity) activity(cursor); if (!safe) { this.scheduleHighlight(); this.addDirtyNode(cursor); } } }, reparseBuffer: function() { forEach(this.container.childNodes, function(node) {node.dirty = true;}); if (this.container.firstChild) this.addDirtyNode(this.container.firstChild); }, // Add a node to the set of dirty nodes, if it isn't already in // there. addDirtyNode: function(node) { node = node || this.container.firstChild; if (!node) return; for (var i = 0; i < this.dirty.length; i++) if (this.dirty[i] == node) return; if (node.nodeType != 3) node.dirty = true; this.dirty.push(node); }, allClean: function() { return !this.dirty.length; }, // Cause a highlight pass to happen in options.passDelay // milliseconds. Clear the existing timeout, if one exists. This // way, the passes do not happen while the user is typing, and // should as unobtrusive as possible. scheduleHighlight: function() { // Timeouts are routed through the parent window, because on // some browsers designMode windows do not fire timeouts. var self = this; parent.clearTimeout(this.highlightTimeout); this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay); }, // Fetch one dirty node, and remove it from the dirty set. getDirtyNode: function() { while (this.dirty.length > 0) { var found = this.dirty.pop(); // IE8 sometimes throws an unexplainable 'invalid argument' // exception for found.parentNode try { // If the node has been coloured in the meantime, or is no // longer in the document, it should not be returned. while (found && found.parentNode != this.container) found = found.parentNode; if (found && (found.dirty || found.nodeType == 3)) return found; } catch (e) {} } return null; }, // Pick dirty nodes, and highlight them, until options.passTime // milliseconds have gone by. The highlight method will continue // to next lines as long as it finds dirty nodes. It returns // information about the place where it stopped. If there are // dirty nodes left after this function has spent all its lines, // it shedules another highlight to finish the job. highlightDirty: function(force) { // Prevent FF from raising an error when it is firing timeouts // on a page that's no longer loaded. if (!window || !window.parent || !window.select) return false; if (!this.options.readOnly) select.markSelection(); var start, endTime = force ? null : time() + this.options.passTime; while ((time() < endTime || force) && (start = this.getDirtyNode())) { var result = this.highlight(start, endTime); if (result && result.node && result.dirty) this.addDirtyNode(result.node.nextSibling); } if (!this.options.readOnly) select.selectMarked(); if (start) this.scheduleHighlight(); return this.dirty.length == 0; }, // Creates a function that, when called through a timeout, will // continuously re-parse the document. documentScanner: function(passTime) { var self = this, pos = null; return function() { // FF timeout weirdness workaround. if (!window || !window.parent || !window.select) return; // If the current node is no longer in the document... oh // well, we start over. if (pos && pos.parentNode != self.container) pos = null; select.markSelection(); var result = self.highlight(pos, time() + passTime, true); select.selectMarked(); var newPos = result ? (result.node && result.node.nextSibling) : null; pos = (pos == newPos) ? null : newPos; self.delayScanning(); }; }, // Starts the continuous scanning process for this document after // a given interval. delayScanning: function() { if (this.scanner) { parent.clearTimeout(this.documentScan); this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning); } }, // The function that does the actual highlighting/colouring (with // help from the parser and the DOM normalizer). Its interface is // rather overcomplicated, because it is used in different // situations: ensuring that a certain line is highlighted, or // highlighting up to X milliseconds starting from a certain // point. The 'from' argument gives the node at which it should // start. If this is null, it will start at the beginning of the // document. When a timestamp is given with the 'target' argument, // it will stop highlighting at that time. If this argument holds // a DOM node, it will highlight until it reaches that node. If at // any time it comes across two 'clean' lines (no dirty nodes), it // will stop, except when 'cleanLines' is true. maxBacktrack is // the maximum number of lines to backtrack to find an existing // parser instance. This is used to give up in situations where a // highlight would take too long and freeze the browser interface. highlight: function(from, target, cleanLines, maxBacktrack){ var container = this.container, self = this, active = this.options.activeTokens; var endTime = (typeof target == "number" ? target : null); if (!container.firstChild) return false; // Backtrack to the first node before from that has a partial // parse stored. while (from && (!from.parserFromHere || from.dirty)) { if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0) return false; from = from.previousSibling; } // If we are at the end of the document, do nothing. if (from && !from.nextSibling) return false; // Check whether a part (<span> node) and the corresponding token // match. function correctPart(token, part){ return !part.reduced && part.currentText == token.value && part.className == token.style; } // Shorten the text associated with a part by chopping off // characters from the front. Note that only the currentText // property gets changed. For efficiency reasons, we leave the // nodeValue alone -- we set the reduced flag to indicate that // this part must be replaced. function shortenPart(part, minus){ part.currentText = part.currentText.substring(minus); part.reduced = true; } // Create a part corresponding to a given token. function tokenPart(token){ var part = makePartSpan(token.value); part.className = token.style; return part; } function maybeTouch(node) { if (node) { var old = node.oldNextSibling; if (lineDirty || old === undefined || node.nextSibling != old) self.history.touch(node); node.oldNextSibling = node.nextSibling; } else { var old = self.container.oldFirstChild; if (lineDirty || old === undefined || self.container.firstChild != old) self.history.touch(null); self.container.oldFirstChild = self.container.firstChild; } } // Get the token stream. If from is null, we start with a new // parser from the start of the frame, otherwise a partial parse // is resumed. var traversal = traverseDOM(from ? from.nextSibling : container.firstChild), stream = stringStream(traversal), parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream); function surroundedByBRs(node) { return (node.previousSibling == null || isBR(node.previousSibling)) && (node.nextSibling == null || isBR(node.nextSibling)); } // parts is an interface to make it possible to 'delay' fetching // the next DOM node until we are completely done with the one // before it. This is necessary because often the next node is // not yet available when we want to proceed past the current // one. var parts = { current: null, // Fetch current node. get: function(){ if (!this.current) this.current = traversal.nodes.shift(); return this.current; }, // Advance to the next part (do not fetch it yet). next: function(){ this.current = null; }, // Remove the current part from the DOM tree, and move to the // next. remove: function(){ container.removeChild(this.get()); this.current = null; }, // Advance to the next part that is not empty, discarding empty // parts. getNonEmpty: function(){ var part = this.get(); // Allow empty nodes when they are alone on a line, needed // for the FF cursor bug workaround (see select.js, // insertNewlineAtCursor). while (part && isSpan(part) && part.currentText == "") { // Leave empty nodes that are alone on a line alone in // Opera, since that browsers doesn't deal well with // having 2 BRs in a row. if (window.opera && surroundedByBRs(part)) { this.next(); part = this.get(); } else { var old = part; this.remove(); part = this.get(); // Adjust selection information, if any. See select.js for details. select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0); } } return part; } }; var lineDirty = false, prevLineDirty = true, lineNodes = 0; // This forEach loops over the tokens from the parsed stream, and // at the same time uses the parts object to proceed through the // corresponding DOM nodes. forEach(parsed, function(token){ var part = parts.getNonEmpty(); if (token.value == "\n"){ // The idea of the two streams actually staying synchronized // is such a long shot that we explicitly check. if (!isBR(part)) throw "Parser out of sync. Expected BR."; if (part.dirty || !part.indentation) lineDirty = true; maybeTouch(from); from = part; // Every <br> gets a copy of the parser state and a lexical // context assigned to it. The first is used to be able to // later resume parsing from this point, the second is used // for indentation. part.parserFromHere = parsed.copy(); part.indentation = token.indentation || alwaysZero; part.dirty = false; // If the target argument wasn't an integer, go at least // until that node. if (endTime == null && part == target) throw StopIteration; // A clean line with more than one node means we are done. // Throwing a StopIteration is the way to break out of a // MochiKit forEach loop. if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines)) throw StopIteration; prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0; parts.next(); } else { if (!isSpan(part)) throw "Parser out of sync. Expected SPAN."; if (part.dirty) lineDirty = true; lineNodes++; // If the part matches the token, we can leave it alone. if (correctPart(token, part)){ if (active && part.dirty) active(part, token, self); part.dirty = false; parts.next(); } // Otherwise, we have to fix it. else { lineDirty = true; // Insert the correct part. var newPart = tokenPart(token); container.insertBefore(newPart, part); if (active) active(newPart, token, self); var tokensize = token.value.length; var offset = 0; // Eat up parts until the text for this token has been // removed, adjusting the stored selection info (see // select.js) in the process. while (tokensize > 0) { part = parts.get(); var partsize = part.currentText.length; select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset); if (partsize > tokensize){ shortenPart(part, tokensize); tokensize = 0; } else { tokensize -= partsize; offset += partsize; parts.remove(); } } } } }); maybeTouch(from); webkitLastLineHack(this.container); // The function returns some status information that is used by // hightlightDirty to determine whether and where it has to // continue. return {node: parts.getNonEmpty(), dirty: lineDirty}; } }; return Editor; })(); addEventHandler(window, "load", function() { var CodeMirror = window.frameElement.CodeMirror; var e = CodeMirror.editor = new Editor(CodeMirror.options); parent.setTimeout(method(CodeMirror, "init"), 0); });
JavaScript
/* String streams are the things fed to parsers (which can feed them * to a tokenizer if they want). They provide peek and next methods * for looking at the current character (next 'consumes' this * character, peek does not), and a get method for retrieving all the * text that was consumed since the last time get was called. * * An easy mistake to make is to let a StopIteration exception finish * the token stream while there are still characters pending in the * string stream (hitting the end of the buffer while parsing a * token). To make it easier to detect such errors, the stringstreams * throw an exception when this happens. */ // Make a stringstream stream out of an iterator that returns strings. // This is applied to the result of traverseDOM (see codemirror.js), // and the resulting stream is fed to the parser. var stringStream = function(source){ // String that's currently being iterated over. var current = ""; // Position in that string. var pos = 0; // Accumulator for strings that have been iterated over but not // get()-ed yet. var accum = ""; // Make sure there are more characters ready, or throw // StopIteration. function ensureChars() { while (pos == current.length) { accum += current; current = ""; // In case source.next() throws pos = 0; try {current = source.next();} catch (e) { if (e != StopIteration) throw e; else return false; } } return true; } return { // peek: -> character // Return the next character in the stream. peek: function() { if (!ensureChars()) return null; return current.charAt(pos); }, // next: -> character // Get the next character, throw StopIteration if at end, check // for unused content. next: function() { if (!ensureChars()) { if (accum.length > 0) throw "End of stringstream reached without emptying buffer ('" + accum + "')."; else throw StopIteration; } return current.charAt(pos++); }, // get(): -> string // Return the characters iterated over since the last call to // .get(). get: function() { var temp = accum; accum = ""; if (pos > 0){ temp += current.slice(0, pos); current = current.slice(pos); pos = 0; } return temp; }, // Push a string back into the stream. push: function(str) { current = current.slice(0, pos) + str + current.slice(pos); }, lookAhead: function(str, consume, skipSpaces, caseInsensitive) { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} str = cased(str); var found = false; var _accum = accum, _pos = pos; if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/); while (true) { var end = pos + str.length, left = current.length - pos; if (end <= current.length) { found = str == cased(current.slice(pos, end)); pos = end; break; } else if (str.slice(0, left) == cased(current.slice(pos))) { accum += current; current = ""; try {current = source.next();} catch (e) {if (e != StopIteration) throw e; break;} pos = 0; str = str.slice(left); } else { break; } } if (!(found && consume)) { current = accum.slice(_accum.length) + current; pos = _pos; accum = _accum; } return found; }, // Wont't match past end of line. lookAheadRegex: function(regex, consume) { if (regex.source.charAt(0) != "^") throw new Error("Regexps passed to lookAheadRegex must start with ^"); // Fetch the rest of the line while (current.indexOf("\n", pos) == -1) { try {current += source.next();} catch (e) {if (e != StopIteration) throw e; break;} } var matched = current.slice(pos).match(regex); if (matched && consume) pos += matched[0].length; return matched; }, // Utils built on top of the above // more: -> boolean // Produce true if the stream isn't empty. more: function() { return this.peek() !== null; }, applies: function(test) { var next = this.peek(); return (next !== null && test(next)); }, nextWhile: function(test) { var next; while ((next = this.peek()) !== null && test(next)) this.next(); }, matches: function(re) { var next = this.peek(); return (next !== null && re.test(next)); }, nextWhileMatches: function(re) { var next; while ((next = this.peek()) !== null && re.test(next)) this.next(); }, equals: function(ch) { return ch === this.peek(); }, endOfLine: function() { var next = this.peek(); return next == null || next == "\n"; } }; };
JavaScript
/** * Storage and control for undo information within a CodeMirror * editor. 'Why on earth is such a complicated mess required for * that?', I hear you ask. The goal, in implementing this, was to make * the complexity of storing and reverting undo information depend * only on the size of the edited or restored content, not on the size * of the whole document. This makes it necessary to use a kind of * 'diff' system, which, when applied to a DOM tree, causes some * complexity and hackery. * * In short, the editor 'touches' BR elements as it parses them, and * the UndoHistory stores these. When nothing is touched in commitDelay * milliseconds, the changes are committed: It goes over all touched * nodes, throws out the ones that did not change since last commit or * are no longer in the document, and assembles the rest into zero or * more 'chains' -- arrays of adjacent lines. Links back to these * chains are added to the BR nodes, while the chain that previously * spanned these nodes is added to the undo history. Undoing a change * means taking such a chain off the undo history, restoring its * content (text is saved per line) and linking it back into the * document. */ // A history object needs to know about the DOM container holding the // document, the maximum amount of undo levels it should store, the // delay (of no input) after which it commits a set of changes, and, // unfortunately, the 'parent' window -- a window that is not in // designMode, and on which setTimeout works in every browser. function UndoHistory(container, maxDepth, commitDelay, editor) { this.container = container; this.maxDepth = maxDepth; this.commitDelay = commitDelay; this.editor = editor; // This line object represents the initial, empty editor. var initial = {text: "", from: null, to: null}; // As the borders between lines are represented by BR elements, the // start of the first line and the end of the last one are // represented by null. Since you can not store any properties // (links to line objects) in null, these properties are used in // those cases. this.first = initial; this.last = initial; // Similarly, a 'historyTouched' property is added to the BR in // front of lines that have already been touched, and 'firstTouched' // is used for the first line. this.firstTouched = false; // History is the set of committed changes, touched is the set of // nodes touched since the last commit. this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0; } UndoHistory.prototype = { // Schedule a commit (if no other touches come in for commitDelay // milliseconds). scheduleCommit: function() { var self = this; parent.clearTimeout(this.commitTimeout); this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay); }, // Mark a node as touched. Null is a valid argument. touch: function(node) { this.setTouched(node); this.scheduleCommit(); }, // Undo the last change. undo: function() { // Make sure pending changes have been committed. this.commit(); if (this.history.length) { // Take the top diff from the history, apply it, and store its // shadow in the redo history. var item = this.history.pop(); this.redoHistory.push(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, // Redo the last undone change. redo: function() { this.commit(); if (this.redoHistory.length) { // The inverse of undo, basically. var item = this.redoHistory.pop(); this.addUndoLevel(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, clear: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, // Ask for the size of the un/redo histories. historySize: function() { return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo}; }, // Push a changeset into the document. push: function(from, to, lines) { var chain = []; for (var i = 0; i < lines.length; i++) { var end = (i == lines.length - 1) ? to : document.createElement("br"); chain.push({from: from, to: end, text: cleanText(lines[i])}); from = end; } this.pushChains([chain], from == null && to == null); this.notifyEnvironment(); }, pushChains: function(chains, doNotHighlight) { this.commit(doNotHighlight); this.addUndoLevel(this.updateTo(chains, "applyChain")); this.redoHistory = []; }, // Retrieve a DOM node from a chain (for scrolling to it after undo/redo). chainNode: function(chains) { for (var i = 0; i < chains.length; i++) { var start = chains[i][0], node = start && (start.from || start.to); if (node) return node; } }, // Clear the undo history, make the current document the start // position. reset: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, textAfter: function(br) { return this.after(br).text; }, nodeAfter: function(br) { return this.after(br).to; }, nodeBefore: function(br) { return this.before(br).from; }, // Commit unless there are pending dirty nodes. tryCommit: function() { if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded if (this.editor.highlightDirty()) this.commit(true); else this.scheduleCommit(); }, // Check whether the touched nodes hold any changes, if so, commit // them. commit: function(doNotHighlight) { parent.clearTimeout(this.commitTimeout); // Make sure there are no pending dirty nodes. if (!doNotHighlight) this.editor.highlightDirty(true); // Build set of chains. var chains = this.touchedChains(), self = this; if (chains.length) { this.addUndoLevel(this.updateTo(chains, "linkChain")); this.redoHistory = []; this.notifyEnvironment(); } }, // [ end of public interface ] // Update the document with a given set of chains, return its // shadow. updateFunc should be "applyChain" or "linkChain". In the // second case, the chains are taken to correspond the the current // document, and only the state of the line data is updated. In the // first case, the content of the chains is also pushed iinto the // document. updateTo: function(chains, updateFunc) { var shadows = [], dirty = []; for (var i = 0; i < chains.length; i++) { shadows.push(this.shadowChain(chains[i])); dirty.push(this[updateFunc](chains[i])); } if (updateFunc == "applyChain") this.notifyDirty(dirty); return shadows; }, // Notify the editor that some nodes have changed. notifyDirty: function(nodes) { forEach(nodes, method(this.editor, "addDirtyNode")) this.editor.scheduleHighlight(); }, notifyEnvironment: function() { if (this.onChange) this.onChange(this.editor); // Used by the line-wrapping line-numbering code. if (window.frameElement && window.frameElement.CodeMirror.updateNumbers) window.frameElement.CodeMirror.updateNumbers(); }, // Link a chain into the DOM nodes (or the first/last links for null // nodes). linkChain: function(chain) { for (var i = 0; i < chain.length; i++) { var line = chain[i]; if (line.from) line.from.historyAfter = line; else this.first = line; if (line.to) line.to.historyBefore = line; else this.last = line; } }, // Get the line object after/before a given node. after: function(node) { return node ? node.historyAfter : this.first; }, before: function(node) { return node ? node.historyBefore : this.last; }, // Mark a node as touched if it has not already been marked. setTouched: function(node) { if (node) { if (!node.historyTouched) { this.touched.push(node); node.historyTouched = true; } } else { this.firstTouched = true; } }, // Store a new set of undo info, throw away info if there is more of // it than allowed. addUndoLevel: function(diffs) { this.history.push(diffs); if (this.history.length > this.maxDepth) { this.history.shift(); lostundo += 1; } }, // Build chains from a set of touched nodes. touchedChains: function() { var self = this; // The temp system is a crummy hack to speed up determining // whether a (currently touched) node has a line object associated // with it. nullTemp is used to store the object for the first // line, other nodes get it stored in their historyTemp property. var nullTemp = null; function temp(node) {return node ? node.historyTemp : nullTemp;} function setTemp(node, line) { if (node) node.historyTemp = line; else nullTemp = line; } function buildLine(node) { var text = []; for (var cur = node ? node.nextSibling : self.container.firstChild; cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling) if (!cur.hackBR && cur.currentText) text.push(cur.currentText); return {from: node, to: cur, text: cleanText(text.join(""))}; } // Filter out unchanged lines and nodes that are no longer in the // document. Build up line objects for remaining nodes. var lines = []; if (self.firstTouched) self.touched.push(null); forEach(self.touched, function(node) { if (node && (node.parentNode != self.container || node.hackBR)) return; if (node) node.historyTouched = false; else self.firstTouched = false; var line = buildLine(node), shadow = self.after(node); if (!shadow || shadow.text != line.text || shadow.to != line.to) { lines.push(line); setTemp(node, line); } }); // Get the BR element after/before the given node. function nextBR(node, dir) { var link = dir + "Sibling", search = node[link]; while (search && !isBR(search)) search = search[link]; return search; } // Assemble line objects into chains by scanning the DOM tree // around them. var chains = []; self.touched = []; forEach(lines, function(line) { // Note that this makes the loop skip line objects that have // been pulled into chains by lines before them. if (!temp(line.from)) return; var chain = [], curNode = line.from, safe = true; // Put any line objects (referred to by temp info) before this // one on the front of the array. while (true) { var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.unshift(curLine); setTemp(curNode, null); if (!curNode) break; safe = self.after(curNode); curNode = nextBR(curNode, "previous"); } curNode = line.to; safe = self.before(line.from); // Add lines after this one at end of array. while (true) { if (!curNode) break; var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.push(curLine); setTemp(curNode, null); safe = self.before(curNode); curNode = nextBR(curNode, "next"); } chains.push(chain); }); return chains; }, // Find the 'shadow' of a given chain by following the links in the // DOM nodes at its start and end. shadowChain: function(chain) { var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to; while (true) { shadows.push(next); var nextNode = next.to; if (!nextNode || nextNode == end) break; else next = nextNode.historyAfter || this.before(end); // (The this.before(end) is a hack -- FF sometimes removes // properties from BR nodes, in which case the best we can hope // for is to not break.) } return shadows; }, // Update the DOM tree to contain the lines specified in a given // chain, link this chain into the DOM nodes. applyChain: function(chain) { // Some attempt is made to prevent the cursor from jumping // randomly when an undo or redo happens. It still behaves a bit // strange sometimes. var cursor = select.cursorPos(this.container, false), self = this; // Remove all nodes in the DOM tree between from and to (null for // start/end of container). function removeRange(from, to) { var pos = from ? from.nextSibling : self.container.firstChild; while (pos != to) { var temp = pos.nextSibling; removeElement(pos); pos = temp; } } var start = chain[0].from, end = chain[chain.length - 1].to; // Clear the space where this change has to be made. removeRange(start, end); // Insert the content specified by the chain into the DOM tree. for (var i = 0; i < chain.length; i++) { var line = chain[i]; // The start and end of the space are already correct, but BR // tags inside it have to be put back. if (i > 0) self.container.insertBefore(line.from, end); // Add the text. var node = makePartSpan(fixSpaces(line.text)); self.container.insertBefore(node, end); // See if the cursor was on this line. Put it back, adjusting // for changed line length, if it was. if (cursor && cursor.node == line.from) { var cursordiff = 0; var prev = this.after(line.from); if (prev && i == chain.length - 1) { // Only adjust if the cursor is after the unchanged part of // the line. for (var match = 0; match < cursor.offset && line.text.charAt(match) == prev.text.charAt(match); match++){} if (cursor.offset > match) cursordiff = line.text.length - prev.text.length; } select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)}); } // Cursor was in removed line, this is last new line. else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) { select.setCursorPos(this.container, {node: line.from, offset: line.text.length}); } } // Anchor the chain in the DOM tree. this.linkChain(chain); return start; } };
JavaScript
/* Parse function for JavaScript. Makes use of the tokenizer from * tokenizejavascript.js. Note that your parsers do not have to be * this complicated -- if you don't want to recognize local variables, * in many languages it is enough to just look for braces, semicolons, * parentheses, etc, and know when you are inside a string or comment. * * See manual.html for more info about the parser interface. */ var JSParser = Editor.Parser = (function() { // Token types that can be considered to be atoms. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; // Setting that can be used to have JSON data indent properly. var json = false; // Constructor for the lexical context objects. function JSLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // My favourite JavaScript indentation rules. function indentJS(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parseJS(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizeJavaScript(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [json ? expressions : statements]; // Context contains information about the current local scope, the // variables defined in that, and the scopes above it. var context = null; // The lexical scope, used mostly for indentation. var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' // function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch a token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentJS(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment") return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. while(true) { consume = marked = false; // Take and execute the topmost action. cc.pop()(token.type, token.content); if (consume){ // Marked is used to change the style of the current token. if (marked) token.style = marked; // Here we differentiate between local and global variables. else if (token.type == "variable" && inScope(token.content)) token.style = "js-localvariable"; return token; } } } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, and context // objects are not mutated in a harmful way, so they can be shared // between runs of the parser. function copy(){ var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ context = _context; lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizeJavaScript(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Push a new scope. Will automatically link the current scope. function pushcontext(){ context = {prev: context, vars: {"this": true, "arguments": true}}; } // Pop off the current scope. function popcontext(){ context = context.prev; } // Register a variable in the current scope. function register(varname){ if (context){ mark("js-variabledef"); context.vars[varname] = true; } } // Check whether a variable is defined in the current scope. function inScope(varname){ var cursor = context; while (cursor) { if (cursor.vars[varname]) return true; cursor = cursor.prev; } return false; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function(){ lexical = new JSLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.type == ")") indented = lexical.indented; lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. function expect(wanted){ return function expecting(type){ if (type == wanted) cont(); else if (wanted == ";") pass(); else cont(arguments.callee); }; } // Looks for a statement, and then calls itself. function statements(type){ return pass(statement, statements); } function expressions(type){ return pass(expression, expressions); } // Dispatches various types of statements based on the type of the // current token. function statement(type){ if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex); else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == ";") cont(); else if (type == "function") cont(functiondef); else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); else if (type == "variable") cont(pushlex("stat"), maybelabel); else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); else if (type == "case") cont(expression, expect(":")); else if (type == "default") cont(expect(":")); else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); else pass(pushlex("stat"), expression, expect(";"), poplex); } // Dispatch expression types. function expression(type){ if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "function") cont(functiondef); else if (type == "keyword c") cont(expression); else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); else if (type == "operator") cont(expression); else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); else cont(); } // Called for places where operators, function calls, or // subscripts are valid. Will skip on to the next action if none // is found. function maybeoperator(type, value){ if (type == "operator" && /\+\+|--/.test(value)) cont(maybeoperator); else if (type == "operator") cont(expression); else if (type == ";") pass(); else if (type == "(") cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); else if (type == ".") cont(property, maybeoperator); else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } // When a statement starts with a variable name, it might be a // label. If no colon follows, it's a regular statement. function maybelabel(type){ if (type == ":") cont(poplex, statement); else pass(maybeoperator, expect(";"), poplex); } // Property names need to have their style adjusted -- the // tokenizer thinks they are variables. function property(type){ if (type == "variable") {mark("js-property"); cont();} } // This parses a property and its value in an object literal. function objprop(type){ if (type == "variable") mark("js-property"); if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what, end){ function proceed(type) { if (type == ",") cont(what, proceed); else if (type == end) cont(); else cont(expect(end)); } return function commaSeparated(type) { if (type == end) cont(); else pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(type){ if (type == "}") cont(); else pass(statement, block); } // Variable definitions are split into two actions -- 1 looks for // a name or the end of the definition, 2 looks for an '=' sign or // a comma. function vardef1(type, value){ if (type == "variable"){register(value); cont(vardef2);} else cont(); } function vardef2(type, value){ if (value == "=") cont(expression, vardef2); else if (type == ",") cont(vardef1); } // For loops. function forspec1(type){ if (type == "var") cont(vardef1, forspec2); else if (type == ";") pass(forspec2); else if (type == "variable") cont(formaybein); else pass(forspec2); } function formaybein(type, value){ if (value == "in") cont(expression); else cont(maybeoperator, forspec2); } function forspec2(type, value){ if (type == ";") cont(forspec3); else if (value == "in") cont(expression); else cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type == ")") pass(); else cont(expression); } // A function definition creates a new context, and the variables // in its argument list have to be added to this context. function functiondef(type, value){ if (type == "variable"){register(value); cont(functiondef);} else if (type == "(") cont(pushcontext, commasep(funarg, ")"), statement, popcontext); } function funarg(type, value){ if (type == "variable"){register(value); cont();} } return parser; } return { make: parseJS, electricChars: "{}:", configure: function(obj) { if (obj.json != null) json = obj.json; } }; })();
JavaScript
var DummyParser = Editor.Parser = (function() { function tokenizeDummy(source) { while (!source.endOfLine()) source.next(); return "text"; } function parseDummy(source) { function indentTo(n) {return function() {return n;}} source = tokenizer(source, tokenizeDummy); var space = 0; var iter = { next: function() { var tok = source.next(); if (tok.type == "whitespace") { if (tok.value == "\n") tok.indentation = indentTo(space); else space = tok.value.length; } return tok; }, copy: function() { var _space = space; return function(_source) { space = _space; source = tokenizer(_source, tokenizeDummy); return iter; }; } }; return iter; } return {make: parseDummy}; })();
JavaScript
/* Tokenizer for CSharp code */ var tokenizeCSharp = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; var next; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "csharp-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); // just a keyword with no indentation implications var keywordD = result("keyword d", "keyword"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "class": result("class", "keyword"), "namespace": result("class", "keyword"), "public": keywordD, "private": keywordD, "protected": keywordD, "internal": keywordD, "extern": keywordD, "override": keywordD, "virtual": keywordD, "abstract": keywordD, "static": keywordD, "out": keywordD, "ref": keywordD, "const": keywordD, "foreach": result("for", "keyword"), "using": keywordC, "int": keywordD, "double": keywordD, "long": keywordD, "bool": keywordD, "char": keywordD, "void": keywordD, "string": keywordD, "byte": keywordD, "sbyte": keywordD, "decimal": keywordD, "float": keywordD, "uint": keywordD, "ulong": keywordD, "object": keywordD, "short": keywordD, "ushort": keywordD, "get": keywordD, "set": keywordD, "value": keywordD }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "csharp-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "csharp-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "csharp-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gi]/); return {type: "regexp", style: "csharp-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "csharp-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "csharp-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "csharp-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "csharp-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "csharp-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (ch == "#") { // treat c# regions like comments nextUntilUnescaped(source, null); return {type: "comment", style: "csharp-comment"}; } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
JavaScript
/* Parse function for JavaScript. Makes use of the tokenizer from * tokenizecsharp.js. Note that your parsers do not have to be * this complicated -- if you don't want to recognize local variables, * in many languages it is enough to just look for braces, semicolons, * parentheses, etc, and know when you are inside a string or comment. * * See manual.html for more info about the parser interface. */ var JSParser = Editor.Parser = (function() { // Token types that can be considered to be atoms. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; // Setting that can be used to have JSON data indent properly. var json = false; // Constructor for the lexical context objects. function CSharpLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // CSharp indentation rules. function indentCSharp(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parseCSharp(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizeCSharp(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [statements]; // The lexical scope, used mostly for indentation. var lexical = new CSharpLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' // function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch a token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentCSharp(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment") return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. while(true) { consume = marked = false; // Take and execute the topmost action. cc.pop()(token.type, token.content); if (consume){ // Marked is used to change the style of the current token. if (marked) token.style = marked; return token; } } } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, and context // objects are not mutated in a harmful way, so they can be shared // between runs of the parser. function copy(){ var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizeCSharp(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function(){ lexical = new CSharpLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. function expect(wanted){ return function expecting(type){ if (type == wanted) cont(); else cont(arguments.callee); }; } // Looks for a statement, and then calls itself. function statements(type){ return pass(statement, statements); } // Dispatches various types of statements based on the type of the // current token. function statement(type){ if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex); else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), statement, poplex); else if (type == "{" && json) cont(pushlex("}"), commasep(objprop, "}"), poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == "function") cont(functiondef); else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); else if (type == "variable") cont(pushlex("stat"), maybelabel); else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); else if (type == "case") cont(expression, expect(":")); else if (type == "default") cont(expect(":")); else if (type == "catch") cont(pushlex("form"), expect("("), funarg, expect(")"), statement, poplex); else if (type == "class") cont(classdef); else if (type == "keyword d") cont(statement); else pass(pushlex("stat"), expression, expect(";"), poplex); } // Dispatch expression types. function expression(type){ if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "function") cont(functiondef); else if (type == "keyword c") cont(expression); else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); else if (type == "operator") cont(expression); else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); } // Called for places where operators, function calls, or // subscripts are valid. Will skip on to the next action if none // is found. function maybeoperator(type){ if (type == "operator") cont(expression); else if (type == "(") cont(pushlex(")"), expression, commasep(expression, ")"), poplex, maybeoperator); else if (type == ".") cont(property, maybeoperator); else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } // When a statement starts with a variable name, it might be a // label. If no colon follows, it's a regular statement. function maybelabel(type){ if (type == ":") cont(poplex, statement); else if (type == "(") cont(commasep(funarg, ")"), poplex, statement); // method definition else if (type == "{") cont(poplex, pushlex("}"), block, poplex); // property definition else pass(maybeoperator, expect(";"), poplex); } // Property names need to have their style adjusted -- the // tokenizer thinks they are variables. function property(type){ if (type == "variable") {mark("csharp-property"); cont();} } // This parses a property and its value in an object literal. function objprop(type){ if (type == "variable") mark("csharp-property"); if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what, end){ function proceed(type) { if (type == ",") cont(what, proceed); else if (type == end) cont(); else cont(expect(end)); }; return function commaSeparated(type) { if (type == end) cont(); else pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(type){ if (type == "}") cont(); else pass(statement, block); } // Variable definitions are split into two actions -- 1 looks for // a name or the end of the definition, 2 looks for an '=' sign or // a comma. function vardef1(type, value){ if (type == "variable"){cont(vardef2);} else cont(); } function vardef2(type, value){ if (value == "=") cont(expression, vardef2); else if (type == ",") cont(vardef1); } // For loops. function forspec1(type){ if (type == "var") cont(vardef1, forspec2); else if (type == "keyword d") cont(vardef1, forspec2); else if (type == ";") pass(forspec2); else if (type == "variable") cont(formaybein); else pass(forspec2); } function formaybein(type, value){ if (value == "in") cont(expression); else cont(maybeoperator, forspec2); } function forspec2(type, value){ if (type == ";") cont(forspec3); else if (value == "in") cont(expression); else cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type == ")") pass(); else cont(expression); } // A function definition creates a new context, and the variables // in its argument list have to be added to this context. function functiondef(type, value){ if (type == "variable") cont(functiondef); else if (type == "(") cont(commasep(funarg, ")"), statement); } function funarg(type, value){ if (type == "variable"){cont();} } function classdef(type) { if (type == "variable") cont(classdef, statement); else if (type == ":") cont(classdef, statement); } return parser; } return { make: parseCSharp, electricChars: "{}:", configure: function(obj) { if (obj.json != null) json = obj.json; } }; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Parse function for PHP. Makes use of the tokenizer from tokenizephp.js. Based on parsejavascript.js by Marijn Haverbeke. Features: + special "deprecated" style for PHP4 keywords like 'var' + support for PHP 5.3 keywords: 'namespace', 'use' + 911 predefined constants, 1301 predefined functions, 105 predeclared classes from a typical PHP installation in a LAMP environment + new feature: syntax error flagging, thus enabling strict parsing of: + function definitions with explicitly or implicitly typed arguments and default values + modifiers (public, static etc.) applied to method and member definitions + foreach(array_expression as $key [=> $value]) loops + differentiation between single-quoted strings and double-quoted interpolating strings */ // add the Array.indexOf method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/IndexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var PHPParser = Editor.Parser = (function() { // Token types that can be considered to be atoms, part of operator expressions var atomicTypes = { "atom": true, "number": true, "variable": true, "string": true }; // Constructor for the lexical context objects. function PHPLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // PHP indentation rules function indentPHP(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parsePHP(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizePHP(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [statements]; // The lexical scope, used mostly for indentation. var lexical = new PHPLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; // parsing is accomplished by calling next() repeatedly function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch the next token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentPHP(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment" || token.type == "string_not_terminated" ) return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. 'marked' is used to change the style of the current token. while(true) { consume = marked = false; // Take and execute the topmost action. var action = cc.pop(); action(token); if (consume){ if (marked) token.style = marked; // Here we differentiate between local and global variables. return token; } } return 1; // Firebug workaround for http://code.google.com/p/fbug/issues/detail?id=1239#c1 } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, so they can // be shared between runs of the parser. function copy(){ var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizePHP(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Add a lyer of style to the current token, for example syntax-error function mark_add(style){ marked = marked + ' ' + style; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function pushlexing() { lexical = new PHPLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.prev) lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. This will ignore (and recover from) syntax errors. function expect(wanted){ return function expecting(token){ if (token.type == wanted) cont(); // consume the token else { cont(arguments.callee); // continue expecting() - call itself } }; } // Require a specific token type, or one of the tokens passed in the 'wanted' array // Used to detect blatant syntax errors. 'execute' is used to pass extra code // to be executed if the token is matched. For example, a '(' match could // 'execute' a cont( compasep(funcarg), require(")") ) function require(wanted, execute){ return function requiring(token){ var ok; var type = token.type; if (typeof(wanted) == "string") ok = (type == wanted) -1; else ok = wanted.indexOf(type); if (ok >= 0) { if (execute && typeof(execute[ok]) == "function") pass(execute[ok]); else cont(); } else { if (!marked) mark(token.style); mark_add("syntax-error"); cont(arguments.callee); } }; } // Looks for a statement, and then calls itself. function statements(token){ return pass(statement, statements); } // Dispatches various types of statements based on the type of the current token. function statement(token){ var type = token.type; if (type == "keyword a") cont(pushlex("form"), expression, altsyntax, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), altsyntax, statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == "function") funcdef(); // technically, "class implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "class") classdef(); else if (type == "foreach") cont(pushlex("form"), require("("), pushlex(")"), expression, require("as"), require("variable"), /* => $value */ expect(")"), altsyntax, poplex, statement, poplex); else if (type == "for") cont(pushlex("form"), require("("), pushlex(")"), expression, require(";"), expression, require(";"), expression, require(")"), altsyntax, poplex, statement, poplex); // public final function foo(), protected static $bar; else if (type == "modifier") cont(require(["modifier", "variable", "function", "abstract"], [null, commasep(require("variable")), funcdef, absfun])); else if (type == "abstract") abs(); else if (type == "switch") cont(pushlex("form"), require("("), expression, require(")"), pushlex("}", "switch"), require([":", "{"]), block, poplex, poplex); else if (type == "case") cont(expression, require(":")); else if (type == "default") cont(require(":")); else if (type == "catch") cont(pushlex("form"), require("("), require("t_string"), require("variable"), require(")"), statement, poplex); else if (type == "const") cont(require("t_string")); // 'const static x=5' is a syntax error // technically, "namespace implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "namespace") cont(namespacedef, require(";")); // $variables may be followed by operators, () for variable function calls, or [] subscripts else pass(pushlex("stat"), expression, require(";"), poplex); } // Dispatch expression types. function expression(token){ var type = token.type; if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "<<<") cont(require("string"), maybeoperator); // heredoc/nowdoc else if (type == "t_string") cont(maybe_double_colon, maybeoperator); else if (type == "keyword c" || type == "operator") cont(expression); // lambda else if (type == "function") lambdadef(); // function call or parenthesized expression: $a = ($b + 1) * 2; else if (type == "(") cont(pushlex(")"), commasep(expression), require(")"), poplex, maybeoperator); } // Called for places where operators, function calls, or subscripts are // valid. Will skip on to the next action if none is found. function maybeoperator(token){ var type = token.type; if (type == "operator") { if (token.content == "?") cont(expression, require(":"), expression); // ternary operator else cont(expression); } else if (type == "(") cont(pushlex(")"), expression, commasep(expression), require(")"), poplex, maybeoperator /* $varfunc() + 3 */); else if (type == "[") cont(pushlex("]"), expression, require("]"), maybeoperator /* for multidimensional arrays, or $func[$i]() */, poplex); } // A regular use of the double colon to specify a class, as in self::func() or myclass::$var; // Differs from `namespace` or `use` in that only one class can be the parent; chains (A::B::$var) are a syntax error. function maybe_double_colon(token) { if (token.type == "t_double_colon") // A::$var, A::func(), A::const cont(require(["t_string", "variable"]), maybeoperator); else { // a t_string wasn't followed by ::, such as in a function call: foo() pass(expression) } } // the declaration or definition of a function function funcdef() { cont(require("t_string"), require("("), pushlex(")"), commasep(funcarg), require(")"), poplex, block); } // the declaration or definition of a lambda function lambdadef() { cont(require("("), pushlex(")"), commasep(funcarg), require(")"), maybe_lambda_use, poplex, require("{"), pushlex("}"), block, poplex); } // optional lambda 'use' statement function maybe_lambda_use(token) { if(token.type == "namespace") { cont(require('('), commasep(funcarg), require(')')); } else { pass(expression); } } // the definition of a class function classdef() { cont(require("t_string"), expect("{"), pushlex("}"), block, poplex); } // either funcdef if the current token is "function", or the keyword "function" + funcdef function absfun(token) { if(token.type == "function") funcdef(); else cont(require(["function"], [funcdef])); } // the abstract class or function (with optional modifier) function abs(token) { cont(require(["modifier", "function", "class"], [absfun, funcdef, classdef])); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what){ function proceed(token) { if (token.type == ",") cont(what, proceed); } return function commaSeparated() { pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(token) { if (token.type == "}") cont(); else pass(statement, block); } function empty_parens_if_array(token) { if(token.content == "array") cont(require("("), require(")")); } function maybedefaultparameter(token){ if (token.content == "=") cont(require(["t_string", "string", "number", "atom"], [empty_parens_if_array, null, null])); } function var_or_reference(token) { if(token.type == "variable") cont(maybedefaultparameter); else if(token.content == "&") cont(require("variable"), maybedefaultparameter); } // support for default arguments: http://us.php.net/manual/en/functions.arguments.php#functions.arguments.default function funcarg(token){ // function foo(myclass $obj) {...} or function foo(myclass &objref) {...} if (token.type == "t_string") cont(var_or_reference); // function foo($var) {...} or function foo(&$ref) {...} else var_or_reference(token); } // A namespace definition or use function maybe_double_colon_def(token) { if (token.type == "t_double_colon") cont(namespacedef); } function namespacedef(token) { pass(require("t_string"), maybe_double_colon_def); } function altsyntax(token){ if(token.content==':') cont(altsyntaxBlock,poplex); } function altsyntaxBlock(token){ if (token.type == "altsyntaxend") cont(require(';')); else pass(statement, altsyntaxBlock); } return parser; } return {make: parsePHP, electricChars: "{}:"}; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Based on parsehtmlmixed.js by Marijn Haverbeke. */ var PHPHTMLMixedParser = Editor.Parser = (function() { var processingInstructions = ["<?php"]; if (!(PHPParser && CSSParser && JSParser && XMLParser)) throw new Error("PHP, CSS, JS, and XML parsers must be loaded for PHP+HTML mixed mode to work."); XMLParser.configure({useHTMLKludges: true}); function parseMixed(stream) { var htmlParser = XMLParser.make(stream), localParser = null, inTag = false, lastAtt = null, phpParserState = null; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.style == "xml-attname") lastAtt = token.content; else if (token.type == "xml-processing") { // see if this opens a PHP block for (var i = 0; i < processingInstructions.length; i++) if (processingInstructions[i] == token.content) { iter.next = local(PHPParser, "?>"); break; } } else if (token.style == "xml-attribute" && token.content == "\"php\"" && inTag == "script" && lastAtt == "language") inTag = "script/php"; // "xml-processing" tokens are ignored, because they should be handled by a specific local parser else if (token.content == ">") { if (inTag == "script/php") iter.next = local(PHPParser, "</script>"); else if (inTag == "script") iter.next = local(JSParser, "</script"); else if (inTag == "style") iter.next = local(CSSParser, "</style"); lastAtt = null; inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); if (parser == PHPParser && phpParserState) localParser = phpParserState(stream); else localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { if (parser == PHPParser) phpParserState = localParser.copy(); localParser = null; iter.next = top; return top(); // pass the ending tag to the enclosing parser } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); } } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag, _lastAtt = lastAtt, _php = phpParserState; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); phpParserState = _php; iter.next = _next; inTag = _inTag; lastAtt = _lastAtt; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(conf) { if (conf.opening != null) processingInstructions = conf.opening; } }; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Vlad Dan Dascalescu <dandv@yahoo-inc.com> Tokenizer for PHP code References: + http://php.net/manual/en/reserved.php + http://php.net/tokens + get_defined_constants(), get_defined_functions(), get_declared_classes() executed on a realistic (not vanilla) PHP installation with typical LAMP modules. Specifically, the PHP bundled with the Uniform Web Server (www.uniformserver.com). */ // add the forEach method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this); } }; } var tokenizePHP = (function() { /* A map of PHP's reserved words (keywords, predefined classes, functions and constants. Each token has a type ('keyword', 'operator' etc.) and a style. The style corresponds to the CSS span class in phpcolors.css. Keywords can be of three types: a - takes an expression and forms a statement - e.g. if b - takes just a statement - e.g. else c - takes an optinoal expression, but no statement - e.g. return This distinction gives the parser enough information to parse correct code correctly (we don't care that much how we parse incorrect code). Reference: http://us.php.net/manual/en/reserved.php */ var keywords = function(){ function token(type, style){ return {type: type, style: style}; } var result = {}; // for each(var element in ["...", "..."]) can pick up elements added to // Array.prototype, so we'll use the loop structure below. See also // http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in // keywords that take an expression and form a statement ["if", "elseif", "while", "declare"].forEach(function(element, index, array) { result[element] = token("keyword a", "php-keyword"); }); // keywords that take just a statement ["do", "else", "try" ].forEach(function(element, index, array) { result[element] = token("keyword b", "php-keyword"); }); // keywords that take an optional expression, but no statement ["return", "break", "continue", // the expression is optional "new", "clone", "throw" // the expression is mandatory ].forEach(function(element, index, array) { result[element] = token("keyword c", "php-keyword"); }); ["__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__"].forEach(function(element, index, array) { result[element] = token("atom", "php-compile-time-constant"); }); ["true", "false", "null"].forEach(function(element, index, array) { result[element] = token("atom", "php-atom"); }); ["and", "or", "xor", "instanceof"].forEach(function(element, index, array) { result[element] = token("operator", "php-keyword php-operator"); }); ["class", "interface"].forEach(function(element, index, array) { result[element] = token("class", "php-keyword"); }); ["namespace", "use", "extends", "implements"].forEach(function(element, index, array) { result[element] = token("namespace", "php-keyword"); }); // reserved "language constructs"... http://php.net/manual/en/reserved.php [ "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset", "list", "require", "require_once", "return", "print", "unset", "array" // a keyword rather, but mandates a parenthesized parameter list ].forEach(function(element, index, array) { result[element] = token("t_string", "php-reserved-language-construct"); }); result["switch"] = token("switch", "php-keyword"); result["case"] = token("case", "php-keyword"); result["default"] = token("default", "php-keyword"); result["catch"] = token("catch", "php-keyword"); result["function"] = token("function", "php-keyword"); // http://php.net/manual/en/control-structures.alternative-syntax.php must be followed by a ':' ["endif", "endwhile", "endfor", "endforeach", "endswitch", "enddeclare"].forEach(function(element, index, array) { result[element] = token("altsyntaxend", "php-keyword"); }); result["const"] = token("const", "php-keyword"); ["final", "private", "protected", "public", "global", "static"].forEach(function(element, index, array) { result[element] = token("modifier", "php-keyword"); }); result["var"] = token("modifier", "php-keyword deprecated"); result["abstract"] = token("abstract", "php-keyword"); result["foreach"] = token("foreach", "php-keyword"); result["as"] = token("as", "php-keyword"); result["for"] = token("for", "php-keyword"); // PHP built-in functions - output of get_defined_functions()["internal"] [ "zend_version", "func_num_args", "func_get_arg", "func_get_args", "strlen", "strcmp", "strncmp", "strcasecmp", "strncasecmp", "each", "error_reporting", "define", "defined", "get_class", "get_parent_class", "method_exists", "property_exists", "class_exists", "interface_exists", "function_exists", "get_included_files", "get_required_files", "is_subclass_of", "is_a", "get_class_vars", "get_object_vars", "get_class_methods", "trigger_error", "user_error", "set_error_handler", "restore_error_handler", "set_exception_handler", "restore_exception_handler", "get_declared_classes", "get_declared_interfaces", "get_defined_functions", "get_defined_vars", "create_function", "get_resource_type", "get_loaded_extensions", "extension_loaded", "get_extension_funcs", "get_defined_constants", "debug_backtrace", "debug_print_backtrace", "bcadd", "bcsub", "bcmul", "bcdiv", "bcmod", "bcpow", "bcsqrt", "bcscale", "bccomp", "bcpowmod", "jdtogregorian", "gregoriantojd", "jdtojulian", "juliantojd", "jdtojewish", "jewishtojd", "jdtofrench", "frenchtojd", "jddayofweek", "jdmonthname", "easter_date", "easter_days", "unixtojd", "jdtounix", "cal_to_jd", "cal_from_jd", "cal_days_in_month", "cal_info", "variant_set", "variant_add", "variant_cat", "variant_sub", "variant_mul", "variant_and", "variant_div", "variant_eqv", "variant_idiv", "variant_imp", "variant_mod", "variant_or", "variant_pow", "variant_xor", "variant_abs", "variant_fix", "variant_int", "variant_neg", "variant_not", "variant_round", "variant_cmp", "variant_date_to_timestamp", "variant_date_from_timestamp", "variant_get_type", "variant_set_type", "variant_cast", "com_create_guid", "com_event_sink", "com_print_typeinfo", "com_message_pump", "com_load_typelib", "com_get_active_object", "ctype_alnum", "ctype_alpha", "ctype_cntrl", "ctype_digit", "ctype_lower", "ctype_graph", "ctype_print", "ctype_punct", "ctype_space", "ctype_upper", "ctype_xdigit", "strtotime", "date", "idate", "gmdate", "mktime", "gmmktime", "checkdate", "strftime", "gmstrftime", "time", "localtime", "getdate", "date_create", "date_parse", "date_format", "date_modify", "date_timezone_get", "date_timezone_set", "date_offset_get", "date_time_set", "date_date_set", "date_isodate_set", "timezone_open", "timezone_name_get", "timezone_name_from_abbr", "timezone_offset_get", "timezone_transitions_get", "timezone_identifiers_list", "timezone_abbreviations_list", "date_default_timezone_set", "date_default_timezone_get", "date_sunrise", "date_sunset", "date_sun_info", "filter_input", "filter_var", "filter_input_array", "filter_var_array", "filter_list", "filter_has_var", "filter_id", "ftp_connect", "ftp_login", "ftp_pwd", "ftp_cdup", "ftp_chdir", "ftp_exec", "ftp_raw", "ftp_mkdir", "ftp_rmdir", "ftp_chmod", "ftp_alloc", "ftp_nlist", "ftp_rawlist", "ftp_systype", "ftp_pasv", "ftp_get", "ftp_fget", "ftp_put", "ftp_fput", "ftp_size", "ftp_mdtm", "ftp_rename", "ftp_delete", "ftp_site", "ftp_close", "ftp_set_option", "ftp_get_option", "ftp_nb_fget", "ftp_nb_get", "ftp_nb_continue", "ftp_nb_put", "ftp_nb_fput", "ftp_quit", "hash", "hash_file", "hash_hmac", "hash_hmac_file", "hash_init", "hash_update", "hash_update_stream", "hash_update_file", "hash_final", "hash_algos", "iconv", "ob_iconv_handler", "iconv_get_encoding", "iconv_set_encoding", "iconv_strlen", "iconv_substr", "iconv_strpos", "iconv_strrpos", "iconv_mime_encode", "iconv_mime_decode", "iconv_mime_decode_headers", "json_encode", "json_decode", "odbc_autocommit", "odbc_binmode", "odbc_close", "odbc_close_all", "odbc_columns", "odbc_commit", "odbc_connect", "odbc_cursor", "odbc_data_source", "odbc_execute", "odbc_error", "odbc_errormsg", "odbc_exec", "odbc_fetch_array", "odbc_fetch_object", "odbc_fetch_row", "odbc_fetch_into", "odbc_field_len", "odbc_field_scale", "odbc_field_name", "odbc_field_type", "odbc_field_num", "odbc_free_result", "odbc_gettypeinfo", "odbc_longreadlen", "odbc_next_result", "odbc_num_fields", "odbc_num_rows", "odbc_pconnect", "odbc_prepare", "odbc_result", "odbc_result_all", "odbc_rollback", "odbc_setoption", "odbc_specialcolumns", "odbc_statistics", "odbc_tables", "odbc_primarykeys", "odbc_columnprivileges", "odbc_tableprivileges", "odbc_foreignkeys", "odbc_procedures", "odbc_procedurecolumns", "odbc_do", "odbc_field_precision", "preg_match", "preg_match_all", "preg_replace", "preg_replace_callback", "preg_split", "preg_quote", "preg_grep", "preg_last_error", "session_name", "session_module_name", "session_save_path", "session_id", "session_regenerate_id", "session_decode", "session_register", "session_unregister", "session_is_registered", "session_encode", "session_start", "session_destroy", "session_unset", "session_set_save_handler", "session_cache_limiter", "session_cache_expire", "session_set_cookie_params", "session_get_cookie_params", "session_write_close", "session_commit", "spl_classes", "spl_autoload", "spl_autoload_extensions", "spl_autoload_register", "spl_autoload_unregister", "spl_autoload_functions", "spl_autoload_call", "class_parents", "class_implements", "spl_object_hash", "iterator_to_array", "iterator_count", "iterator_apply", "constant", "bin2hex", "sleep", "usleep", "flush", "wordwrap", "htmlspecialchars", "htmlentities", "html_entity_decode", "htmlspecialchars_decode", "get_html_translation_table", "sha1", "sha1_file", "md5", "md5_file", "crc32", "iptcparse", "iptcembed", "getimagesize", "image_type_to_mime_type", "image_type_to_extension", "phpinfo", "phpversion", "phpcredits", "php_logo_guid", "php_real_logo_guid", "php_egg_logo_guid", "zend_logo_guid", "php_sapi_name", "php_uname", "php_ini_scanned_files", "strnatcmp", "strnatcasecmp", "substr_count", "strspn", "strcspn", "strtok", "strtoupper", "strtolower", "strpos", "stripos", "strrpos", "strripos", "strrev", "hebrev", "hebrevc", "nl2br", "basename", "dirname", "pathinfo", "stripslashes", "stripcslashes", "strstr", "stristr", "strrchr", "str_shuffle", "str_word_count", "str_split", "strpbrk", "substr_compare", "strcoll", "substr", "substr_replace", "quotemeta", "ucfirst", "ucwords", "strtr", "addslashes", "addcslashes", "rtrim", "str_replace", "str_ireplace", "str_repeat", "count_chars", "chunk_split", "trim", "ltrim", "strip_tags", "similar_text", "explode", "implode", "setlocale", "localeconv", "soundex", "levenshtein", "chr", "ord", "parse_str", "str_pad", "chop", "strchr", "sprintf", "printf", "vprintf", "vsprintf", "fprintf", "vfprintf", "sscanf", "fscanf", "parse_url", "urlencode", "urldecode", "rawurlencode", "rawurldecode", "http_build_query", "unlink", "exec", "system", "escapeshellcmd", "escapeshellarg", "passthru", "shell_exec", "proc_open", "proc_close", "proc_terminate", "proc_get_status", "rand", "srand", "getrandmax", "mt_rand", "mt_srand", "mt_getrandmax", "getservbyname", "getservbyport", "getprotobyname", "getprotobynumber", "getmyuid", "getmygid", "getmypid", "getmyinode", "getlastmod", "base64_decode", "base64_encode", "convert_uuencode", "convert_uudecode", "abs", "ceil", "floor", "round", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "pi", "is_finite", "is_nan", "is_infinite", "pow", "exp", "log", "log10", "sqrt", "hypot", "deg2rad", "rad2deg", "bindec", "hexdec", "octdec", "decbin", "decoct", "dechex", "base_convert", "number_format", "fmod", "ip2long", "long2ip", "getenv", "putenv", "microtime", "gettimeofday", "uniqid", "quoted_printable_decode", "convert_cyr_string", "get_current_user", "set_time_limit", "get_cfg_var", "magic_quotes_runtime", "set_magic_quotes_runtime", "get_magic_quotes_gpc", "get_magic_quotes_runtime", "import_request_variables", "error_log", "error_get_last", "call_user_func", "call_user_func_array", "call_user_method", "call_user_method_array", "serialize", "unserialize", "var_dump", "var_export", "debug_zval_dump", "print_r", "memory_get_usage", "memory_get_peak_usage", "register_shutdown_function", "register_tick_function", "unregister_tick_function", "highlight_file", "show_source", "highlight_string", "php_strip_whitespace", "ini_get", "ini_get_all", "ini_set", "ini_alter", "ini_restore", "get_include_path", "set_include_path", "restore_include_path", "setcookie", "setrawcookie", "header", "headers_sent", "headers_list", "connection_aborted", "connection_status", "ignore_user_abort", "parse_ini_file", "is_uploaded_file", "move_uploaded_file", "gethostbyaddr", "gethostbyname", "gethostbynamel", "intval", "floatval", "doubleval", "strval", "gettype", "settype", "is_null", "is_resource", "is_bool", "is_long", "is_float", "is_int", "is_integer", "is_double", "is_real", "is_numeric", "is_string", "is_array", "is_object", "is_scalar", "is_callable", "ereg", "ereg_replace", "eregi", "eregi_replace", "split", "spliti", "join", "sql_regcase", "dl", "pclose", "popen", "readfile", "rewind", "rmdir", "umask", "fclose", "feof", "fgetc", "fgets", "fgetss", "fread", "fopen", "fpassthru", "ftruncate", "fstat", "fseek", "ftell", "fflush", "fwrite", "fputs", "mkdir", "rename", "copy", "tempnam", "tmpfile", "file", "file_get_contents", "file_put_contents", "stream_select", "stream_context_create", "stream_context_set_params", "stream_context_set_option", "stream_context_get_options", "stream_context_get_default", "stream_filter_prepend", "stream_filter_append", "stream_filter_remove", "stream_socket_client", "stream_socket_server", "stream_socket_accept", "stream_socket_get_name", "stream_socket_recvfrom", "stream_socket_sendto", "stream_socket_enable_crypto", "stream_socket_shutdown", "stream_copy_to_stream", "stream_get_contents", "fgetcsv", "fputcsv", "flock", "get_meta_tags", "stream_set_write_buffer", "set_file_buffer", "set_socket_blocking", "stream_set_blocking", "socket_set_blocking", "stream_get_meta_data", "stream_get_line", "stream_wrapper_register", "stream_register_wrapper", "stream_wrapper_unregister", "stream_wrapper_restore", "stream_get_wrappers", "stream_get_transports", "get_headers", "stream_set_timeout", "socket_set_timeout", "socket_get_status", "realpath", "fsockopen", "pfsockopen", "pack", "unpack", "get_browser", "crypt", "opendir", "closedir", "chdir", "getcwd", "rewinddir", "readdir", "dir", "scandir", "glob", "fileatime", "filectime", "filegroup", "fileinode", "filemtime", "fileowner", "fileperms", "filesize", "filetype", "file_exists", "is_writable", "is_writeable", "is_readable", "is_executable", "is_file", "is_dir", "is_link", "stat", "lstat", "chown", "chgrp", "chmod", "touch", "clearstatcache", "disk_total_space", "disk_free_space", "diskfreespace", "mail", "ezmlm_hash", "openlog", "syslog", "closelog", "define_syslog_variables", "lcg_value", "metaphone", "ob_start", "ob_flush", "ob_clean", "ob_end_flush", "ob_end_clean", "ob_get_flush", "ob_get_clean", "ob_get_length", "ob_get_level", "ob_get_status", "ob_get_contents", "ob_implicit_flush", "ob_list_handlers", "ksort", "krsort", "natsort", "natcasesort", "asort", "arsort", "sort", "rsort", "usort", "uasort", "uksort", "shuffle", "array_walk", "array_walk_recursive", "count", "end", "prev", "next", "reset", "current", "key", "min", "max", "in_array", "array_search", "extract", "compact", "array_fill", "array_fill_keys", "range", "array_multisort", "array_push", "array_pop", "array_shift", "array_unshift", "array_splice", "array_slice", "array_merge", "array_merge_recursive", "array_keys", "array_values", "array_count_values", "array_reverse", "array_reduce", "array_pad", "array_flip", "array_change_key_case", "array_rand", "array_unique", "array_intersect", "array_intersect_key", "array_intersect_ukey", "array_uintersect", "array_intersect_assoc", "array_uintersect_assoc", "array_intersect_uassoc", "array_uintersect_uassoc", "array_diff", "array_diff_key", "array_diff_ukey", "array_udiff", "array_diff_assoc", "array_udiff_assoc", "array_diff_uassoc", "array_udiff_uassoc", "array_sum", "array_product", "array_filter", "array_map", "array_chunk", "array_combine", "array_key_exists", "pos", "sizeof", "key_exists", "assert", "assert_options", "version_compare", "str_rot13", "stream_get_filters", "stream_filter_register", "stream_bucket_make_writeable", "stream_bucket_prepend", "stream_bucket_append", "stream_bucket_new", "output_add_rewrite_var", "output_reset_rewrite_vars", "sys_get_temp_dir", "token_get_all", "token_name", "readgzfile", "gzrewind", "gzclose", "gzeof", "gzgetc", "gzgets", "gzgetss", "gzread", "gzopen", "gzpassthru", "gzseek", "gztell", "gzwrite", "gzputs", "gzfile", "gzcompress", "gzuncompress", "gzdeflate", "gzinflate", "gzencode", "ob_gzhandler", "zlib_get_coding_type", "libxml_set_streams_context", "libxml_use_internal_errors", "libxml_get_last_error", "libxml_clear_errors", "libxml_get_errors", "dom_import_simplexml", "simplexml_load_file", "simplexml_load_string", "simplexml_import_dom", "wddx_serialize_value", "wddx_serialize_vars", "wddx_packet_start", "wddx_packet_end", "wddx_add_vars", "wddx_deserialize", "xml_parser_create", "xml_parser_create_ns", "xml_set_object", "xml_set_element_handler", "xml_set_character_data_handler", "xml_set_processing_instruction_handler", "xml_set_default_handler", "xml_set_unparsed_entity_decl_handler", "xml_set_notation_decl_handler", "xml_set_external_entity_ref_handler", "xml_set_start_namespace_decl_handler", "xml_set_end_namespace_decl_handler", "xml_parse", "xml_parse_into_struct", "xml_get_error_code", "xml_error_string", "xml_get_current_line_number", "xml_get_current_column_number", "xml_get_current_byte_index", "xml_parser_free", "xml_parser_set_option", "xml_parser_get_option", "utf8_encode", "utf8_decode", "xmlwriter_open_uri", "xmlwriter_open_memory", "xmlwriter_set_indent", "xmlwriter_set_indent_string", "xmlwriter_start_comment", "xmlwriter_end_comment", "xmlwriter_start_attribute", "xmlwriter_end_attribute", "xmlwriter_write_attribute", "xmlwriter_start_attribute_ns", "xmlwriter_write_attribute_ns", "xmlwriter_start_element", "xmlwriter_end_element", "xmlwriter_full_end_element", "xmlwriter_start_element_ns", "xmlwriter_write_element", "xmlwriter_write_element_ns", "xmlwriter_start_pi", "xmlwriter_end_pi", "xmlwriter_write_pi", "xmlwriter_start_cdata", "xmlwriter_end_cdata", "xmlwriter_write_cdata", "xmlwriter_text", "xmlwriter_write_raw", "xmlwriter_start_document", "xmlwriter_end_document", "xmlwriter_write_comment", "xmlwriter_start_dtd", "xmlwriter_end_dtd", "xmlwriter_write_dtd", "xmlwriter_start_dtd_element", "xmlwriter_end_dtd_element", "xmlwriter_write_dtd_element", "xmlwriter_start_dtd_attlist", "xmlwriter_end_dtd_attlist", "xmlwriter_write_dtd_attlist", "xmlwriter_start_dtd_entity", "xmlwriter_end_dtd_entity", "xmlwriter_write_dtd_entity", "xmlwriter_output_memory", "xmlwriter_flush", "gd_info", "imagearc", "imageellipse", "imagechar", "imagecharup", "imagecolorat", "imagecolorallocate", "imagepalettecopy", "imagecreatefromstring", "imagecolorclosest", "imagecolordeallocate", "imagecolorresolve", "imagecolorexact", "imagecolorset", "imagecolortransparent", "imagecolorstotal", "imagecolorsforindex", "imagecopy", "imagecopymerge", "imagecopymergegray", "imagecopyresized", "imagecreate", "imagecreatetruecolor", "imageistruecolor", "imagetruecolortopalette", "imagesetthickness", "imagefilledarc", "imagefilledellipse", "imagealphablending", "imagesavealpha", "imagecolorallocatealpha", "imagecolorresolvealpha", "imagecolorclosestalpha", "imagecolorexactalpha", "imagecopyresampled", "imagegrabwindow", "imagegrabscreen", "imagerotate", "imageantialias", "imagesettile", "imagesetbrush", "imagesetstyle", "imagecreatefrompng", "imagecreatefromgif", "imagecreatefromjpeg", "imagecreatefromwbmp", "imagecreatefromxbm", "imagecreatefromgd", "imagecreatefromgd2", "imagecreatefromgd2part", "imagepng", "imagegif", "imagejpeg", "imagewbmp", "imagegd", "imagegd2", "imagedestroy", "imagegammacorrect", "imagefill", "imagefilledpolygon", "imagefilledrectangle", "imagefilltoborder", "imagefontwidth", "imagefontheight", "imageinterlace", "imageline", "imageloadfont", "imagepolygon", "imagerectangle", "imagesetpixel", "imagestring", "imagestringup", "imagesx", "imagesy", "imagedashedline", "imagettfbbox", "imagettftext", "imageftbbox", "imagefttext", "imagepsloadfont", "imagepsfreefont", "imagepsencodefont", "imagepsextendfont", "imagepsslantfont", "imagepstext", "imagepsbbox", "imagetypes", "jpeg2wbmp", "png2wbmp", "image2wbmp", "imagelayereffect", "imagecolormatch", "imagexbm", "imagefilter", "imageconvolution", "mb_convert_case", "mb_strtoupper", "mb_strtolower", "mb_language", "mb_internal_encoding", "mb_http_input", "mb_http_output", "mb_detect_order", "mb_substitute_character", "mb_parse_str", "mb_output_handler", "mb_preferred_mime_name", "mb_strlen", "mb_strpos", "mb_strrpos", "mb_stripos", "mb_strripos", "mb_strstr", "mb_strrchr", "mb_stristr", "mb_strrichr", "mb_substr_count", "mb_substr", "mb_strcut", "mb_strwidth", "mb_strimwidth", "mb_convert_encoding", "mb_detect_encoding", "mb_list_encodings", "mb_convert_kana", "mb_encode_mimeheader", "mb_decode_mimeheader", "mb_convert_variables", "mb_encode_numericentity", "mb_decode_numericentity", "mb_send_mail", "mb_get_info", "mb_check_encoding", "mb_regex_encoding", "mb_regex_set_options", "mb_ereg", "mb_eregi", "mb_ereg_replace", "mb_eregi_replace", "mb_split", "mb_ereg_match", "mb_ereg_search", "mb_ereg_search_pos", "mb_ereg_search_regs", "mb_ereg_search_init", "mb_ereg_search_getregs", "mb_ereg_search_getpos", "mb_ereg_search_setpos", "mbregex_encoding", "mbereg", "mberegi", "mbereg_replace", "mberegi_replace", "mbsplit", "mbereg_match", "mbereg_search", "mbereg_search_pos", "mbereg_search_regs", "mbereg_search_init", "mbereg_search_getregs", "mbereg_search_getpos", "mbereg_search_setpos", "mysql_connect", "mysql_pconnect", "mysql_close", "mysql_select_db", "mysql_query", "mysql_unbuffered_query", "mysql_db_query", "mysql_list_dbs", "mysql_list_tables", "mysql_list_fields", "mysql_list_processes", "mysql_error", "mysql_errno", "mysql_affected_rows", "mysql_insert_id", "mysql_result", "mysql_num_rows", "mysql_num_fields", "mysql_fetch_row", "mysql_fetch_array", "mysql_fetch_assoc", "mysql_fetch_object", "mysql_data_seek", "mysql_fetch_lengths", "mysql_fetch_field", "mysql_field_seek", "mysql_free_result", "mysql_field_name", "mysql_field_table", "mysql_field_len", "mysql_field_type", "mysql_field_flags", "mysql_escape_string", "mysql_real_escape_string", "mysql_stat", "mysql_thread_id", "mysql_client_encoding", "mysql_ping", "mysql_get_client_info", "mysql_get_host_info", "mysql_get_proto_info", "mysql_get_server_info", "mysql_info", "mysql_set_charset", "mysql", "mysql_fieldname", "mysql_fieldtable", "mysql_fieldlen", "mysql_fieldtype", "mysql_fieldflags", "mysql_selectdb", "mysql_freeresult", "mysql_numfields", "mysql_numrows", "mysql_listdbs", "mysql_listtables", "mysql_listfields", "mysql_db_name", "mysql_dbname", "mysql_tablename", "mysql_table_name", "mysqli_affected_rows", "mysqli_autocommit", "mysqli_change_user", "mysqli_character_set_name", "mysqli_close", "mysqli_commit", "mysqli_connect", "mysqli_connect_errno", "mysqli_connect_error", "mysqli_data_seek", "mysqli_debug", "mysqli_disable_reads_from_master", "mysqli_disable_rpl_parse", "mysqli_dump_debug_info", "mysqli_enable_reads_from_master", "mysqli_enable_rpl_parse", "mysqli_embedded_server_end", "mysqli_embedded_server_start", "mysqli_errno", "mysqli_error", "mysqli_stmt_execute", "mysqli_execute", "mysqli_fetch_field", "mysqli_fetch_fields", "mysqli_fetch_field_direct", "mysqli_fetch_lengths", "mysqli_fetch_array", "mysqli_fetch_assoc", "mysqli_fetch_object", "mysqli_fetch_row", "mysqli_field_count", "mysqli_field_seek", "mysqli_field_tell", "mysqli_free_result", "mysqli_get_charset", "mysqli_get_client_info", "mysqli_get_client_version", "mysqli_get_host_info", "mysqli_get_proto_info", "mysqli_get_server_info", "mysqli_get_server_version", "mysqli_get_warnings", "mysqli_init", "mysqli_info", "mysqli_insert_id", "mysqli_kill", "mysqli_set_local_infile_default", "mysqli_set_local_infile_handler", "mysqli_master_query", "mysqli_more_results", "mysqli_multi_query", "mysqli_next_result", "mysqli_num_fields", "mysqli_num_rows", "mysqli_options", "mysqli_ping", "mysqli_prepare", "mysqli_report", "mysqli_query", "mysqli_real_connect", "mysqli_real_escape_string", "mysqli_real_query", "mysqli_rollback", "mysqli_rpl_parse_enabled", "mysqli_rpl_probe", "mysqli_rpl_query_type", "mysqli_select_db", "mysqli_set_charset", "mysqli_stmt_attr_get", "mysqli_stmt_attr_set", "mysqli_stmt_field_count", "mysqli_stmt_init", "mysqli_stmt_prepare", "mysqli_stmt_result_metadata", "mysqli_stmt_send_long_data", "mysqli_stmt_bind_param", "mysqli_stmt_bind_result", "mysqli_stmt_fetch", "mysqli_stmt_free_result", "mysqli_stmt_get_warnings", "mysqli_stmt_insert_id", "mysqli_stmt_reset", "mysqli_stmt_param_count", "mysqli_send_query", "mysqli_slave_query", "mysqli_sqlstate", "mysqli_ssl_set", "mysqli_stat", "mysqli_stmt_affected_rows", "mysqli_stmt_close", "mysqli_stmt_data_seek", "mysqli_stmt_errno", "mysqli_stmt_error", "mysqli_stmt_num_rows", "mysqli_stmt_sqlstate", "mysqli_store_result", "mysqli_stmt_store_result", "mysqli_thread_id", "mysqli_thread_safe", "mysqli_use_result", "mysqli_warning_count", "mysqli_bind_param", "mysqli_bind_result", "mysqli_client_encoding", "mysqli_escape_string", "mysqli_fetch", "mysqli_param_count", "mysqli_get_metadata", "mysqli_send_long_data", "mysqli_set_opt", "pdo_drivers", "socket_select", "socket_create", "socket_create_listen", "socket_accept", "socket_set_nonblock", "socket_set_block", "socket_listen", "socket_close", "socket_write", "socket_read", "socket_getsockname", "socket_getpeername", "socket_connect", "socket_strerror", "socket_bind", "socket_recv", "socket_send", "socket_recvfrom", "socket_sendto", "socket_get_option", "socket_set_option", "socket_shutdown", "socket_last_error", "socket_clear_error", "socket_getopt", "socket_setopt", "eaccelerator_put", "eaccelerator_get", "eaccelerator_rm", "eaccelerator_gc", "eaccelerator_lock", "eaccelerator_unlock", "eaccelerator_caching", "eaccelerator_optimizer", "eaccelerator_clear", "eaccelerator_clean", "eaccelerator_info", "eaccelerator_purge", "eaccelerator_cached_scripts", "eaccelerator_removed_scripts", "eaccelerator_list_keys", "eaccelerator_encode", "eaccelerator_load", "_eaccelerator_loader_file", "_eaccelerator_loader_line", "eaccelerator_set_session_handlers", "_eaccelerator_output_handler", "eaccelerator_cache_page", "eaccelerator_rm_page", "eaccelerator_cache_output", "eaccelerator_cache_result", "xdebug_get_stack_depth", "xdebug_get_function_stack", "xdebug_print_function_stack", "xdebug_get_declared_vars", "xdebug_call_class", "xdebug_call_function", "xdebug_call_file", "xdebug_call_line", "xdebug_var_dump", "xdebug_debug_zval", "xdebug_debug_zval_stdout", "xdebug_enable", "xdebug_disable", "xdebug_is_enabled", "xdebug_break", "xdebug_start_trace", "xdebug_stop_trace", "xdebug_get_tracefile_name", "xdebug_get_profiler_filename", "xdebug_dump_aggr_profiling_data", "xdebug_clear_aggr_profiling_data", "xdebug_memory_usage", "xdebug_peak_memory_usage", "xdebug_time_index", "xdebug_start_error_collection", "xdebug_stop_error_collection", "xdebug_get_collected_errors", "xdebug_start_code_coverage", "xdebug_stop_code_coverage", "xdebug_get_code_coverage", "xdebug_get_function_count", "xdebug_dump_superglobals", "_", /* alias for gettext()*/ "get_called_class","class_alias","gc_collect_cycles","gc_enabled","gc_enable", "gc_disable","date_create_from_format","date_parse_from_format", "date_get_last_errors","date_add","date_sub","date_diff","date_timestamp_set", "date_timestamp_get","timezone_location_get","timezone_version_get", "date_interval_create_from_date_string","date_interval_format", "libxml_disable_entity_loader","openssl_pkey_free","openssl_pkey_new", "openssl_pkey_export","openssl_pkey_export_to_file","openssl_pkey_get_private", "openssl_pkey_get_public","openssl_pkey_get_details","openssl_free_key", "openssl_get_privatekey","openssl_get_publickey","openssl_x509_read", "openssl_x509_free","openssl_x509_parse","openssl_x509_checkpurpose", "openssl_x509_check_private_key","openssl_x509_export","openssl_x509_export_to_file", "openssl_pkcs12_export","openssl_pkcs12_export_to_file","openssl_pkcs12_read", "openssl_csr_new","openssl_csr_export","openssl_csr_export_to_file", "openssl_csr_sign","openssl_csr_get_subject","openssl_csr_get_public_key", "openssl_digest","openssl_encrypt","openssl_decrypt","openssl_cipher_iv_length", "openssl_sign","openssl_verify","openssl_seal","openssl_open","openssl_pkcs7_verify", "openssl_pkcs7_decrypt","openssl_pkcs7_sign","openssl_pkcs7_encrypt", "openssl_private_encrypt","openssl_private_decrypt","openssl_public_encrypt", "openssl_public_decrypt","openssl_get_md_methods","openssl_get_cipher_methods", "openssl_dh_compute_key","openssl_random_pseudo_bytes","openssl_error_string", "preg_filter","bzopen","bzread","bzwrite","bzflush","bzclose","bzerrno", "bzerrstr","bzerror","bzcompress","bzdecompress","curl_init","curl_copy_handle", "curl_version","curl_setopt","curl_setopt_array","curl_exec","curl_getinfo", "curl_error","curl_errno","curl_close","curl_multi_init","curl_multi_add_handle", "curl_multi_remove_handle","curl_multi_select","curl_multi_exec","curl_multi_getcontent", "curl_multi_info_read","curl_multi_close","exif_read_data","read_exif_data", "exif_tagname","exif_thumbnail","exif_imagetype","ftp_ssl_connect", "imagecolorclosesthwb","imagecreatefromxpm","textdomain","gettext","dgettext", "dcgettext","bindtextdomain","ngettext","dngettext","dcngettext", "bind_textdomain_codeset","hash_copy","imap_open","imap_reopen","imap_close", "imap_num_msg","imap_num_recent","imap_headers","imap_headerinfo", "imap_rfc822_parse_headers","imap_rfc822_write_address","imap_rfc822_parse_adrlist", "imap_body","imap_bodystruct","imap_fetchbody","imap_savebody","imap_fetchheader", "imap_fetchstructure","imap_gc","imap_expunge","imap_delete","imap_undelete", "imap_check","imap_listscan","imap_mail_copy","imap_mail_move","imap_mail_compose", "imap_createmailbox","imap_renamemailbox","imap_deletemailbox","imap_subscribe", "imap_unsubscribe","imap_append","imap_ping","imap_base64","imap_qprint","imap_8bit", "imap_binary","imap_utf8","imap_status","imap_mailboxmsginfo","imap_setflag_full", "imap_clearflag_full","imap_sort","imap_uid","imap_msgno","imap_list","imap_lsub", "imap_fetch_overview","imap_alerts","imap_errors","imap_last_error","imap_search", "imap_utf7_decode","imap_utf7_encode","imap_mime_header_decode","imap_thread", "imap_timeout","imap_get_quota","imap_get_quotaroot","imap_set_quota","imap_setacl", "imap_getacl","imap_mail","imap_header","imap_listmailbox","imap_getmailboxes", "imap_scanmailbox","imap_listsubscribed","imap_getsubscribed","imap_fetchtext", "imap_scan","imap_create","imap_rename","json_last_error","mb_encoding_aliases", "mcrypt_ecb","mcrypt_cbc","mcrypt_cfb","mcrypt_ofb","mcrypt_get_key_size", "mcrypt_get_block_size","mcrypt_get_cipher_name","mcrypt_create_iv","mcrypt_list_algorithms", "mcrypt_list_modes","mcrypt_get_iv_size","mcrypt_encrypt","mcrypt_decrypt", "mcrypt_module_open","mcrypt_generic_init","mcrypt_generic","mdecrypt_generic", "mcrypt_generic_end","mcrypt_generic_deinit","mcrypt_enc_self_test", "mcrypt_enc_is_block_algorithm_mode","mcrypt_enc_is_block_algorithm", "mcrypt_enc_is_block_mode","mcrypt_enc_get_block_size","mcrypt_enc_get_key_size", "mcrypt_enc_get_supported_key_sizes","mcrypt_enc_get_iv_size", "mcrypt_enc_get_algorithms_name","mcrypt_enc_get_modes_name","mcrypt_module_self_test", "mcrypt_module_is_block_algorithm_mode","mcrypt_module_is_block_algorithm", "mcrypt_module_is_block_mode","mcrypt_module_get_algo_block_size", "mcrypt_module_get_algo_key_size","mcrypt_module_get_supported_key_sizes", "mcrypt_module_close","mysqli_refresh","posix_kill","posix_getpid","posix_getppid", "posix_getuid","posix_setuid","posix_geteuid","posix_seteuid","posix_getgid", "posix_setgid","posix_getegid","posix_setegid","posix_getgroups","posix_getlogin", "posix_getpgrp","posix_setsid","posix_setpgid","posix_getpgid","posix_getsid", "posix_uname","posix_times","posix_ctermid","posix_ttyname","posix_isatty", "posix_getcwd","posix_mkfifo","posix_mknod","posix_access","posix_getgrnam", "posix_getgrgid","posix_getpwnam","posix_getpwuid","posix_getrlimit", "posix_get_last_error","posix_errno","posix_strerror","posix_initgroups", "pspell_new","pspell_new_personal","pspell_new_config","pspell_check", "pspell_suggest","pspell_store_replacement","pspell_add_to_personal", "pspell_add_to_session","pspell_clear_session","pspell_save_wordlist", "pspell_config_create","pspell_config_runtogether","pspell_config_mode", "pspell_config_ignore","pspell_config_personal","pspell_config_dict_dir", "pspell_config_data_dir","pspell_config_repl","pspell_config_save_repl", "snmpget","snmpgetnext","snmpwalk","snmprealwalk","snmpwalkoid", "snmp_get_quick_print","snmp_set_quick_print","snmp_set_enum_print", "snmp_set_oid_output_format","snmp_set_oid_numeric_print","snmpset", "snmp2_get","snmp2_getnext","snmp2_walk","snmp2_real_walk","snmp2_set", "snmp3_get","snmp3_getnext","snmp3_walk","snmp3_real_walk","snmp3_set", "snmp_set_valueretrieval","snmp_get_valueretrieval","snmp_read_mib", "use_soap_error_handler","is_soap_fault","socket_create_pair","time_nanosleep", "time_sleep_until","strptime","php_ini_loaded_file","money_format","lcfirst", "nl_langinfo","str_getcsv","readlink","linkinfo","symlink","link","proc_nice", "atanh","asinh","acosh","expm1","log1p","inet_ntop","inet_pton","getopt", "sys_getloadavg","getrusage","quoted_printable_encode","forward_static_call", "forward_static_call_array","header_remove","parse_ini_string","gethostname", "dns_check_record","checkdnsrr","dns_get_mx","getmxrr","dns_get_record", "stream_context_get_params","stream_context_set_default","stream_socket_pair", "stream_supports_lock","stream_set_read_buffer","stream_resolve_include_path", "stream_is_local","fnmatch","chroot","lchown","lchgrp","realpath_cache_size", "realpath_cache_get","array_replace","array_replace_recursive","ftok","xmlrpc_encode", "xmlrpc_decode","xmlrpc_decode_request","xmlrpc_encode_request","xmlrpc_get_type", "xmlrpc_set_type","xmlrpc_is_fault","xmlrpc_server_create","xmlrpc_server_destroy", "xmlrpc_server_register_method","xmlrpc_server_call_method", "xmlrpc_parse_method_descriptions","xmlrpc_server_add_introspection_data", "xmlrpc_server_register_introspection_callback","zip_open","zip_close", "zip_read","zip_entry_open","zip_entry_close","zip_entry_read","zip_entry_filesize", "zip_entry_name","zip_entry_compressedsize","zip_entry_compressionmethod", "svn_checkout","svn_cat","svn_ls","svn_log","svn_auth_set_parameter", "svn_auth_get_parameter","svn_client_version","svn_config_ensure","svn_diff", "svn_cleanup","svn_revert","svn_resolved","svn_commit","svn_lock","svn_unlock", "svn_add","svn_status","svn_update","svn_import","svn_info","svn_export", "svn_copy","svn_switch","svn_blame","svn_delete","svn_mkdir","svn_move", "svn_proplist","svn_propget","svn_repos_create","svn_repos_recover", "svn_repos_hotcopy","svn_repos_open","svn_repos_fs", "svn_repos_fs_begin_txn_for_commit","svn_repos_fs_commit_txn", "svn_fs_revision_root","svn_fs_check_path","svn_fs_revision_prop", "svn_fs_dir_entries","svn_fs_node_created_rev","svn_fs_youngest_rev", "svn_fs_file_contents","svn_fs_file_length","svn_fs_txn_root","svn_fs_make_file", "svn_fs_make_dir","svn_fs_apply_text","svn_fs_copy","svn_fs_delete", "svn_fs_begin_txn2","svn_fs_is_dir","svn_fs_is_file","svn_fs_node_prop", "svn_fs_change_node_prop","svn_fs_contents_changed","svn_fs_props_changed", "svn_fs_abort_txn","sqlite_open","sqlite_popen","sqlite_close","sqlite_query", "sqlite_exec","sqlite_array_query","sqlite_single_query","sqlite_fetch_array", "sqlite_fetch_object","sqlite_fetch_single","sqlite_fetch_string", "sqlite_fetch_all","sqlite_current","sqlite_column","sqlite_libversion", "sqlite_libencoding","sqlite_changes","sqlite_last_insert_rowid", "sqlite_num_rows","sqlite_num_fields","sqlite_field_name","sqlite_seek", "sqlite_rewind","sqlite_next","sqlite_prev","sqlite_valid","sqlite_has_more", "sqlite_has_prev","sqlite_escape_string","sqlite_busy_timeout","sqlite_last_error", "sqlite_error_string","sqlite_unbuffered_query","sqlite_create_aggregate", "sqlite_create_function","sqlite_factory","sqlite_udf_encode_binary", "sqlite_udf_decode_binary","sqlite_fetch_column_types" ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-function"); }); // output of get_defined_constants(). Differs significantly from http://php.net/manual/en/reserved.constants.php [ "E_ERROR", "E_RECOVERABLE_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE", "E_STRICT", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR", "E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE", "E_ALL", "TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE", "PHP_VERSION", "PHP_OS", "PHP_SAPI", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR", "PHP_EXTENSION_DIR", "PHP_PREFIX", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR", "PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR", "PHP_CONFIG_FILE_PATH", "PHP_CONFIG_FILE_SCAN_DIR", "PHP_SHLIB_SUFFIX", "PHP_EOL", "PHP_EOL", "PHP_INT_MAX", "PHP_INT_SIZE", "PHP_OUTPUT_HANDLER_START", "PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END", "UPLOAD_ERR_OK", "UPLOAD_ERR_INI_SIZE", "UPLOAD_ERR_FORM_SIZE", "UPLOAD_ERR_PARTIAL", "UPLOAD_ERR_NO_FILE", "UPLOAD_ERR_NO_TMP_DIR", "UPLOAD_ERR_CANT_WRITE", "UPLOAD_ERR_EXTENSION", "CAL_GREGORIAN", "CAL_JULIAN", "CAL_JEWISH", "CAL_FRENCH", "CAL_NUM_CALS", "CAL_DOW_DAYNO", "CAL_DOW_SHORT", "CAL_DOW_LONG", "CAL_MONTH_GREGORIAN_SHORT", "CAL_MONTH_GREGORIAN_LONG", "CAL_MONTH_JULIAN_SHORT", "CAL_MONTH_JULIAN_LONG", "CAL_MONTH_JEWISH", "CAL_MONTH_FRENCH", "CAL_EASTER_DEFAULT", "CAL_EASTER_ROMAN", "CAL_EASTER_ALWAYS_GREGORIAN", "CAL_EASTER_ALWAYS_JULIAN", "CAL_JEWISH_ADD_ALAFIM_GERESH", "CAL_JEWISH_ADD_ALAFIM", "CAL_JEWISH_ADD_GERESHAYIM", "CLSCTX_INPROC_SERVER", "CLSCTX_INPROC_HANDLER", "CLSCTX_LOCAL_SERVER", "CLSCTX_REMOTE_SERVER", "CLSCTX_SERVER", "CLSCTX_ALL", "VT_NULL", "VT_EMPTY", "VT_UI1", "VT_I1", "VT_UI2", "VT_I2", "VT_UI4", "VT_I4", "VT_R4", "VT_R8", "VT_BOOL", "VT_ERROR", "VT_CY", "VT_DATE", "VT_BSTR", "VT_DECIMAL", "VT_UNKNOWN", "VT_DISPATCH", "VT_VARIANT", "VT_INT", "VT_UINT", "VT_ARRAY", "VT_BYREF", "CP_ACP", "CP_MACCP", "CP_OEMCP", "CP_UTF7", "CP_UTF8", "CP_SYMBOL", "CP_THREAD_ACP", "VARCMP_LT", "VARCMP_EQ", "VARCMP_GT", "VARCMP_NULL", "NORM_IGNORECASE", "NORM_IGNORENONSPACE", "NORM_IGNORESYMBOLS", "NORM_IGNOREWIDTH", "NORM_IGNOREKANATYPE", "DISP_E_DIVBYZERO", "DISP_E_OVERFLOW", "DISP_E_BADINDEX", "MK_E_UNAVAILABLE", "INPUT_POST", "INPUT_GET", "INPUT_COOKIE", "INPUT_ENV", "INPUT_SERVER", "INPUT_SESSION", "INPUT_REQUEST", "FILTER_FLAG_NONE", "FILTER_REQUIRE_SCALAR", "FILTER_REQUIRE_ARRAY", "FILTER_FORCE_ARRAY", "FILTER_NULL_ON_FAILURE", "FILTER_VALIDATE_INT", "FILTER_VALIDATE_BOOLEAN", "FILTER_VALIDATE_FLOAT", "FILTER_VALIDATE_REGEXP", "FILTER_VALIDATE_URL", "FILTER_VALIDATE_EMAIL", "FILTER_VALIDATE_IP", "FILTER_DEFAULT", "FILTER_UNSAFE_RAW", "FILTER_SANITIZE_STRING", "FILTER_SANITIZE_STRIPPED", "FILTER_SANITIZE_ENCODED", "FILTER_SANITIZE_SPECIAL_CHARS", "FILTER_SANITIZE_EMAIL", "FILTER_SANITIZE_URL", "FILTER_SANITIZE_NUMBER_INT", "FILTER_SANITIZE_NUMBER_FLOAT", "FILTER_SANITIZE_MAGIC_QUOTES", "FILTER_CALLBACK", "FILTER_FLAG_ALLOW_OCTAL", "FILTER_FLAG_ALLOW_HEX", "FILTER_FLAG_STRIP_LOW", "FILTER_FLAG_STRIP_HIGH", "FILTER_FLAG_ENCODE_LOW", "FILTER_FLAG_ENCODE_HIGH", "FILTER_FLAG_ENCODE_AMP", "FILTER_FLAG_NO_ENCODE_QUOTES", "FILTER_FLAG_EMPTY_STRING_NULL", "FILTER_FLAG_ALLOW_FRACTION", "FILTER_FLAG_ALLOW_THOUSAND", "FILTER_FLAG_ALLOW_SCIENTIFIC", "FILTER_FLAG_SCHEME_REQUIRED", "FILTER_FLAG_HOST_REQUIRED", "FILTER_FLAG_PATH_REQUIRED", "FILTER_FLAG_QUERY_REQUIRED", "FILTER_FLAG_IPV4", "FILTER_FLAG_IPV6", "FILTER_FLAG_NO_RES_RANGE", "FILTER_FLAG_NO_PRIV_RANGE", "FTP_ASCII", "FTP_TEXT", "FTP_BINARY", "FTP_IMAGE", "FTP_AUTORESUME", "FTP_TIMEOUT_SEC", "FTP_AUTOSEEK", "FTP_FAILED", "FTP_FINISHED", "FTP_MOREDATA", "HASH_HMAC", "ICONV_IMPL", "ICONV_VERSION", "ICONV_MIME_DECODE_STRICT", "ICONV_MIME_DECODE_CONTINUE_ON_ERROR", "ODBC_TYPE", "ODBC_BINMODE_PASSTHRU", "ODBC_BINMODE_RETURN", "ODBC_BINMODE_CONVERT", "SQL_ODBC_CURSORS", "SQL_CUR_USE_DRIVER", "SQL_CUR_USE_IF_NEEDED", "SQL_CUR_USE_ODBC", "SQL_CONCURRENCY", "SQL_CONCUR_READ_ONLY", "SQL_CONCUR_LOCK", "SQL_CONCUR_ROWVER", "SQL_CONCUR_VALUES", "SQL_CURSOR_TYPE", "SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC", "SQL_CURSOR_STATIC", "SQL_KEYSET_SIZE", "SQL_FETCH_FIRST", "SQL_FETCH_NEXT", "SQL_CHAR", "SQL_VARCHAR", "SQL_LONGVARCHAR", "SQL_DECIMAL", "SQL_NUMERIC", "SQL_BIT", "SQL_TINYINT", "SQL_SMALLINT", "SQL_INTEGER", "SQL_BIGINT", "SQL_REAL", "SQL_FLOAT", "SQL_DOUBLE", "SQL_BINARY", "SQL_VARBINARY", "SQL_LONGVARBINARY", "SQL_DATE", "SQL_TIME", "SQL_TIMESTAMP", "PREG_PATTERN_ORDER", "PREG_SET_ORDER", "PREG_OFFSET_CAPTURE", "PREG_SPLIT_NO_EMPTY", "PREG_SPLIT_DELIM_CAPTURE", "PREG_SPLIT_OFFSET_CAPTURE", "PREG_GREP_INVERT", "PREG_NO_ERROR", "PREG_INTERNAL_ERROR", "PREG_BACKTRACK_LIMIT_ERROR", "PREG_RECURSION_LIMIT_ERROR", "PREG_BAD_UTF8_ERROR", "DATE_ATOM", "DATE_COOKIE", "DATE_ISO8601", "DATE_RFC822", "DATE_RFC850", "DATE_RFC1036", "DATE_RFC1123", "DATE_RFC2822", "DATE_RFC3339", "DATE_RSS", "DATE_W3C", "SUNFUNCS_RET_TIMESTAMP", "SUNFUNCS_RET_STRING", "SUNFUNCS_RET_DOUBLE", "LIBXML_VERSION", "LIBXML_DOTTED_VERSION", "LIBXML_NOENT", "LIBXML_DTDLOAD", "LIBXML_DTDATTR", "LIBXML_DTDVALID", "LIBXML_NOERROR", "LIBXML_NOWARNING", "LIBXML_NOBLANKS", "LIBXML_XINCLUDE", "LIBXML_NSCLEAN", "LIBXML_NOCDATA", "LIBXML_NONET", "LIBXML_COMPACT", "LIBXML_NOXMLDECL", "LIBXML_NOEMPTYTAG", "LIBXML_ERR_NONE", "LIBXML_ERR_WARNING", "LIBXML_ERR_ERROR", "LIBXML_ERR_FATAL", "CONNECTION_ABORTED", "CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER", "INI_PERDIR", "INI_SYSTEM", "INI_ALL", "PHP_URL_SCHEME", "PHP_URL_HOST", "PHP_URL_PORT", "PHP_URL_USER", "PHP_URL_PASS", "PHP_URL_PATH", "PHP_URL_QUERY", "PHP_URL_FRAGMENT", "M_E", "M_LOG2E", "M_LOG10E", "M_LN2", "M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI", "M_SQRTPI", "M_2_SQRTPI", "M_LNPI", "M_EULER", "M_SQRT2", "M_SQRT1_2", "M_SQRT3", "INF", "NAN", "INFO_GENERAL", "INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES", "INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE", "INFO_ALL", "CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES", "CREDITS_DOCS", "CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL", "HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES", "ENT_NOQUOTES", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH", "PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION", "PATHINFO_FILENAME", "CHAR_MAX", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_ALL", "SEEK_SET", "SEEK_CUR", "SEEK_END", "LOCK_SH", "LOCK_EX", "LOCK_UN", "LOCK_NB", "STREAM_NOTIFY_CONNECT", "STREAM_NOTIFY_AUTH_REQUIRED", "STREAM_NOTIFY_AUTH_RESULT", "STREAM_NOTIFY_MIME_TYPE_IS", "STREAM_NOTIFY_FILE_SIZE_IS", "STREAM_NOTIFY_REDIRECTED", "STREAM_NOTIFY_PROGRESS", "STREAM_NOTIFY_FAILURE", "STREAM_NOTIFY_COMPLETED", "STREAM_NOTIFY_RESOLVE", "STREAM_NOTIFY_SEVERITY_INFO", "STREAM_NOTIFY_SEVERITY_WARN", "STREAM_NOTIFY_SEVERITY_ERR", "STREAM_FILTER_READ", "STREAM_FILTER_WRITE", "STREAM_FILTER_ALL", "STREAM_CLIENT_PERSISTENT", "STREAM_CLIENT_ASYNC_CONNECT", "STREAM_CLIENT_CONNECT", "STREAM_CRYPTO_METHOD_SSLv2_CLIENT", "STREAM_CRYPTO_METHOD_SSLv3_CLIENT", "STREAM_CRYPTO_METHOD_SSLv23_CLIENT", "STREAM_CRYPTO_METHOD_TLS_CLIENT", "STREAM_CRYPTO_METHOD_SSLv2_SERVER", "STREAM_CRYPTO_METHOD_SSLv3_SERVER", "STREAM_CRYPTO_METHOD_SSLv23_SERVER", "STREAM_CRYPTO_METHOD_TLS_SERVER", "STREAM_SHUT_RD", "STREAM_SHUT_WR", "STREAM_SHUT_RDWR", "STREAM_PF_INET", "STREAM_PF_INET6", "STREAM_PF_UNIX", "STREAM_IPPROTO_IP", "STREAM_IPPROTO_TCP", "STREAM_IPPROTO_UDP", "STREAM_IPPROTO_ICMP", "STREAM_IPPROTO_RAW", "STREAM_SOCK_STREAM", "STREAM_SOCK_DGRAM", "STREAM_SOCK_RAW", "STREAM_SOCK_SEQPACKET", "STREAM_SOCK_RDM", "STREAM_PEEK", "STREAM_OOB", "STREAM_SERVER_BIND", "STREAM_SERVER_LISTEN", "FILE_USE_INCLUDE_PATH", "FILE_IGNORE_NEW_LINES", "FILE_SKIP_EMPTY_LINES", "FILE_APPEND", "FILE_NO_DEFAULT_CONTEXT", "PSFS_PASS_ON", "PSFS_FEED_ME", "PSFS_ERR_FATAL", "PSFS_FLAG_NORMAL", "PSFS_FLAG_FLUSH_INC", "PSFS_FLAG_FLUSH_CLOSE", "CRYPT_SALT_LENGTH", "CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5", "CRYPT_BLOWFISH", "DIRECTORY_SEPARATOR", "PATH_SEPARATOR", "GLOB_BRACE", "GLOB_MARK", "GLOB_NOSORT", "GLOB_NOCHECK", "GLOB_NOESCAPE", "GLOB_ERR", "GLOB_ONLYDIR", "LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR", "LOG_WARNING", "LOG_NOTICE", "LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON", "LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON", "LOG_AUTHPRIV", "LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY", "LOG_NOWAIT", "LOG_PERROR", "EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME", "EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID", "EXTR_PREFIX_IF_EXISTS", "EXTR_IF_EXISTS", "EXTR_REFS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR", "SORT_NUMERIC", "SORT_STRING", "SORT_LOCALE_STRING", "CASE_LOWER", "CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE", "ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL", "STREAM_USE_PATH", "STREAM_IGNORE_URL", "STREAM_ENFORCE_SAFE_MODE", "STREAM_REPORT_ERRORS", "STREAM_MUST_SEEK", "STREAM_URL_STAT_LINK", "STREAM_URL_STAT_QUIET", "STREAM_MKDIR_RECURSIVE", "IMAGETYPE_GIF", "IMAGETYPE_JPEG", "IMAGETYPE_PNG", "IMAGETYPE_SWF", "IMAGETYPE_PSD", "IMAGETYPE_BMP", "IMAGETYPE_TIFF_II", "IMAGETYPE_TIFF_MM", "IMAGETYPE_JPC", "IMAGETYPE_JP2", "IMAGETYPE_JPX", "IMAGETYPE_JB2", "IMAGETYPE_SWC", "IMAGETYPE_IFF", "IMAGETYPE_WBMP", "IMAGETYPE_JPEG2000", "IMAGETYPE_XBM", "T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE", "T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "T_PLUS_EQUAL", "T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL", "T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL", "T_BOOLEAN_OR", "T_BOOLEAN_AND", "T_IS_EQUAL", "T_IS_NOT_EQUAL", "T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "T_IS_SMALLER_OR_EQUAL", "T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "T_INC", "T_DEC", "T_INT_CAST", "T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST", "T_BOOL_CAST", "T_UNSET_CAST", "T_NEW", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE", "T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME", "T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_CHARACTER", "T_BAD_CHARACTER", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING", "T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH", "T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH", "T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_FUNCTION", "T_CONST", "T_RETURN", "T_USE", "T_GLOBAL", "T_STATIC", "T_VAR", "T_UNSET", "T_ISSET", "T_EMPTY", "T_CLASS", "T_EXTENDS", "T_INTERFACE", "T_IMPLEMENTS", "T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CLASS_C", "T_FUNC_C", "T_METHOD_C", "T_LINE", "T_FILE", "T_COMMENT", "T_DOC_COMMENT", "T_OPEN_TAG", "T_OPEN_TAG_WITH_ECHO", "T_CLOSE_TAG", "T_WHITESPACE", "T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES", "T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_DOUBLE_COLON", "T_ABSTRACT", "T_CATCH", "T_FINAL", "T_INSTANCEOF", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC", "T_THROW", "T_TRY", "T_CLONE", "T_HALT_COMPILER", "FORCE_GZIP", "FORCE_DEFLATE", "XML_ELEMENT_NODE", "XML_ATTRIBUTE_NODE", "XML_TEXT_NODE", "XML_CDATA_SECTION_NODE", "XML_ENTITY_REF_NODE", "XML_ENTITY_NODE", "XML_PI_NODE", "XML_COMMENT_NODE", "XML_DOCUMENT_NODE", "XML_DOCUMENT_TYPE_NODE", "XML_DOCUMENT_FRAG_NODE", "XML_NOTATION_NODE", "XML_HTML_DOCUMENT_NODE", "XML_DTD_NODE", "XML_ELEMENT_DECL_NODE", "XML_ATTRIBUTE_DECL_NODE", "XML_ENTITY_DECL_NODE", "XML_NAMESPACE_DECL_NODE", "XML_LOCAL_NAMESPACE", "XML_ATTRIBUTE_CDATA", "XML_ATTRIBUTE_ID", "XML_ATTRIBUTE_IDREF", "XML_ATTRIBUTE_IDREFS", "XML_ATTRIBUTE_ENTITY", "XML_ATTRIBUTE_NMTOKEN", "XML_ATTRIBUTE_NMTOKENS", "XML_ATTRIBUTE_ENUMERATION", "XML_ATTRIBUTE_NOTATION", "DOM_PHP_ERR", "DOM_INDEX_SIZE_ERR", "DOMSTRING_SIZE_ERR", "DOM_HIERARCHY_REQUEST_ERR", "DOM_WRONG_DOCUMENT_ERR", "DOM_INVALID_CHARACTER_ERR", "DOM_NO_DATA_ALLOWED_ERR", "DOM_NO_MODIFICATION_ALLOWED_ERR", "DOM_NOT_FOUND_ERR", "DOM_NOT_SUPPORTED_ERR", "DOM_INUSE_ATTRIBUTE_ERR", "DOM_INVALID_STATE_ERR", "DOM_SYNTAX_ERR", "DOM_INVALID_MODIFICATION_ERR", "DOM_NAMESPACE_ERR", "DOM_INVALID_ACCESS_ERR", "DOM_VALIDATION_ERR", "XML_ERROR_NONE", "XML_ERROR_NO_MEMORY", "XML_ERROR_SYNTAX", "XML_ERROR_NO_ELEMENTS", "XML_ERROR_INVALID_TOKEN", "XML_ERROR_UNCLOSED_TOKEN", "XML_ERROR_PARTIAL_CHAR", "XML_ERROR_TAG_MISMATCH", "XML_ERROR_DUPLICATE_ATTRIBUTE", "XML_ERROR_JUNK_AFTER_DOC_ELEMENT", "XML_ERROR_PARAM_ENTITY_REF", "XML_ERROR_UNDEFINED_ENTITY", "XML_ERROR_RECURSIVE_ENTITY_REF", "XML_ERROR_ASYNC_ENTITY", "XML_ERROR_BAD_CHAR_REF", "XML_ERROR_BINARY_ENTITY_REF", "XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "XML_ERROR_MISPLACED_XML_PI", "XML_ERROR_UNKNOWN_ENCODING", "XML_ERROR_INCORRECT_ENCODING", "XML_ERROR_UNCLOSED_CDATA_SECTION", "XML_ERROR_EXTERNAL_ENTITY_HANDLING", "XML_OPTION_CASE_FOLDING", "XML_OPTION_TARGET_ENCODING", "XML_OPTION_SKIP_TAGSTART", "XML_OPTION_SKIP_WHITE", "XML_SAX_IMPL", "IMG_GIF", "IMG_JPG", "IMG_JPEG", "IMG_PNG", "IMG_WBMP", "IMG_XPM", "IMG_COLOR_TILED", "IMG_COLOR_STYLED", "IMG_COLOR_BRUSHED", "IMG_COLOR_STYLEDBRUSHED", "IMG_COLOR_TRANSPARENT", "IMG_ARC_ROUNDED", "IMG_ARC_PIE", "IMG_ARC_CHORD", "IMG_ARC_NOFILL", "IMG_ARC_EDGED", "IMG_GD2_RAW", "IMG_GD2_COMPRESSED", "IMG_EFFECT_REPLACE", "IMG_EFFECT_ALPHABLEND", "IMG_EFFECT_NORMAL", "IMG_EFFECT_OVERLAY", "GD_BUNDLED", "IMG_FILTER_NEGATE", "IMG_FILTER_GRAYSCALE", "IMG_FILTER_BRIGHTNESS", "IMG_FILTER_CONTRAST", "IMG_FILTER_COLORIZE", "IMG_FILTER_EDGEDETECT", "IMG_FILTER_GAUSSIAN_BLUR", "IMG_FILTER_SELECTIVE_BLUR", "IMG_FILTER_EMBOSS", "IMG_FILTER_MEAN_REMOVAL", "IMG_FILTER_SMOOTH", "PNG_NO_FILTER", "PNG_FILTER_NONE", "PNG_FILTER_SUB", "PNG_FILTER_UP", "PNG_FILTER_AVG", "PNG_FILTER_PAETH", "PNG_ALL_FILTERS", "MB_OVERLOAD_MAIL", "MB_OVERLOAD_STRING", "MB_OVERLOAD_REGEX", "MB_CASE_UPPER", "MB_CASE_LOWER", "MB_CASE_TITLE", "MYSQL_ASSOC", "MYSQL_NUM", "MYSQL_BOTH", "MYSQL_CLIENT_COMPRESS", "MYSQL_CLIENT_SSL", "MYSQL_CLIENT_INTERACTIVE", "MYSQL_CLIENT_IGNORE_SPACE", "MYSQLI_READ_DEFAULT_GROUP", "MYSQLI_READ_DEFAULT_FILE", "MYSQLI_OPT_CONNECT_TIMEOUT", "MYSQLI_OPT_LOCAL_INFILE", "MYSQLI_INIT_COMMAND", "MYSQLI_CLIENT_SSL", "MYSQLI_CLIENT_COMPRESS", "MYSQLI_CLIENT_INTERACTIVE", "MYSQLI_CLIENT_IGNORE_SPACE", "MYSQLI_CLIENT_NO_SCHEMA", "MYSQLI_CLIENT_FOUND_ROWS", "MYSQLI_STORE_RESULT", "MYSQLI_USE_RESULT", "MYSQLI_ASSOC", "MYSQLI_NUM", "MYSQLI_BOTH", "MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH", "MYSQLI_STMT_ATTR_CURSOR_TYPE", "MYSQLI_CURSOR_TYPE_NO_CURSOR", "MYSQLI_CURSOR_TYPE_READ_ONLY", "MYSQLI_CURSOR_TYPE_FOR_UPDATE", "MYSQLI_CURSOR_TYPE_SCROLLABLE", "MYSQLI_STMT_ATTR_PREFETCH_ROWS", "MYSQLI_NOT_NULL_FLAG", "MYSQLI_PRI_KEY_FLAG", "MYSQLI_UNIQUE_KEY_FLAG", "MYSQLI_MULTIPLE_KEY_FLAG", "MYSQLI_BLOB_FLAG", "MYSQLI_UNSIGNED_FLAG", "MYSQLI_ZEROFILL_FLAG", "MYSQLI_AUTO_INCREMENT_FLAG", "MYSQLI_TIMESTAMP_FLAG", "MYSQLI_SET_FLAG", "MYSQLI_NUM_FLAG", "MYSQLI_PART_KEY_FLAG", "MYSQLI_GROUP_FLAG", "MYSQLI_TYPE_DECIMAL", "MYSQLI_TYPE_TINY", "MYSQLI_TYPE_SHORT", "MYSQLI_TYPE_LONG", "MYSQLI_TYPE_FLOAT", "MYSQLI_TYPE_DOUBLE", "MYSQLI_TYPE_NULL", "MYSQLI_TYPE_TIMESTAMP", "MYSQLI_TYPE_LONGLONG", "MYSQLI_TYPE_INT24", "MYSQLI_TYPE_DATE", "MYSQLI_TYPE_TIME", "MYSQLI_TYPE_DATETIME", "MYSQLI_TYPE_YEAR", "MYSQLI_TYPE_NEWDATE", "MYSQLI_TYPE_ENUM", "MYSQLI_TYPE_SET", "MYSQLI_TYPE_TINY_BLOB", "MYSQLI_TYPE_MEDIUM_BLOB", "MYSQLI_TYPE_LONG_BLOB", "MYSQLI_TYPE_BLOB", "MYSQLI_TYPE_VAR_STRING", "MYSQLI_TYPE_STRING", "MYSQLI_TYPE_CHAR", "MYSQLI_TYPE_INTERVAL", "MYSQLI_TYPE_GEOMETRY", "MYSQLI_TYPE_NEWDECIMAL", "MYSQLI_TYPE_BIT", "MYSQLI_RPL_MASTER", "MYSQLI_RPL_SLAVE", "MYSQLI_RPL_ADMIN", "MYSQLI_NO_DATA", "MYSQLI_DATA_TRUNCATED", "MYSQLI_REPORT_INDEX", "MYSQLI_REPORT_ERROR", "MYSQLI_REPORT_STRICT", "MYSQLI_REPORT_ALL", "MYSQLI_REPORT_OFF", "AF_UNIX", "AF_INET", "AF_INET6", "SOCK_STREAM", "SOCK_DGRAM", "SOCK_RAW", "SOCK_SEQPACKET", "SOCK_RDM", "MSG_OOB", "MSG_WAITALL", "MSG_PEEK", "MSG_DONTROUTE", "SO_DEBUG", "SO_REUSEADDR", "SO_KEEPALIVE", "SO_DONTROUTE", "SO_LINGER", "SO_BROADCAST", "SO_OOBINLINE", "SO_SNDBUF", "SO_RCVBUF", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO", "SO_TYPE", "SO_ERROR", "SOL_SOCKET", "SOMAXCONN", "PHP_NORMAL_READ", "PHP_BINARY_READ", "SOCKET_EINTR", "SOCKET_EBADF", "SOCKET_EACCES", "SOCKET_EFAULT", "SOCKET_EINVAL", "SOCKET_EMFILE", "SOCKET_EWOULDBLOCK", "SOCKET_EINPROGRESS", "SOCKET_EALREADY", "SOCKET_ENOTSOCK", "SOCKET_EDESTADDRREQ", "SOCKET_EMSGSIZE", "SOCKET_EPROTOTYPE", "SOCKET_ENOPROTOOPT", "SOCKET_EPROTONOSUPPORT", "SOCKET_ESOCKTNOSUPPORT", "SOCKET_EOPNOTSUPP", "SOCKET_EPFNOSUPPORT", "SOCKET_EAFNOSUPPORT", "SOCKET_EADDRINUSE", "SOCKET_EADDRNOTAVAIL", "SOCKET_ENETDOWN", "SOCKET_ENETUNREACH", "SOCKET_ENETRESET", "SOCKET_ECONNABORTED", "SOCKET_ECONNRESET", "SOCKET_ENOBUFS", "SOCKET_EISCONN", "SOCKET_ENOTCONN", "SOCKET_ESHUTDOWN", "SOCKET_ETOOMANYREFS", "SOCKET_ETIMEDOUT", "SOCKET_ECONNREFUSED", "SOCKET_ELOOP", "SOCKET_ENAMETOOLONG", "SOCKET_EHOSTDOWN", "SOCKET_EHOSTUNREACH", "SOCKET_ENOTEMPTY", "SOCKET_EPROCLIM", "SOCKET_EUSERS", "SOCKET_EDQUOT", "SOCKET_ESTALE", "SOCKET_EREMOTE", "SOCKET_EDISCON", "SOCKET_SYSNOTREADY", "SOCKET_VERNOTSUPPORTED", "SOCKET_NOTINITIALISED", "SOCKET_HOST_NOT_FOUND", "SOCKET_TRY_AGAIN", "SOCKET_NO_RECOVERY", "SOCKET_NO_DATA", "SOCKET_NO_ADDRESS", "SOL_TCP", "SOL_UDP", "EACCELERATOR_VERSION", "EACCELERATOR_SHM_AND_DISK", "EACCELERATOR_SHM", "EACCELERATOR_SHM_ONLY", "EACCELERATOR_DISK_ONLY", "EACCELERATOR_NONE", "XDEBUG_TRACE_APPEND", "XDEBUG_TRACE_COMPUTERIZED", "XDEBUG_TRACE_HTML", "XDEBUG_CC_UNUSED", "XDEBUG_CC_DEAD_CODE", "STDIN", "STDOUT", "STDERR", "DNS_HINFO", "DNS_PTR", "SQLITE_EMPTY", "SVN_SHOW_UPDATES", "SVN_NO_IGNORE", "MSG_EOF", "DNS_MX", "GD_EXTRA_VERSION", "PHP_VERSION_ID", "SQLITE_OK", "LIBXML_LOADED_VERSION", "RADIXCHAR", "OPENSSL_VERSION_TEXT", "OPENSSL_VERSION_NUMBER", "PCRE_VERSION", "CURLOPT_FILE", "CURLOPT_INFILE", "CURLOPT_URL", "CURLOPT_PROXY", "CURLE_FUNCTION_NOT_FOUND", "SOCKET_ENOMSG", "CURLOPT_HTTPHEADER", "SOCKET_EIDRM", "CURLOPT_PROGRESSFUNCTION", "SOCKET_ECHRNG", "SOCKET_EL2NSYNC", "SOCKET_EL3HLT", "SOCKET_EL3RST", "SOCKET_ELNRNG", "SOCKET_ENOCSI", "SOCKET_EL2HLT", "SOCKET_EBADE", "SOCKET_EXFULL", "CURLOPT_USERPWD", "CURLOPT_PROXYUSERPWD", "CURLOPT_RANGE", "CURLOPT_TIMEOUT_MS", "CURLOPT_POSTFIELDS", "CURLOPT_REFERER", "CURLOPT_USERAGENT", "CURLOPT_FTPPORT", "SOCKET_ERESTART", "SQLITE_CONSTRAINT", "SQLITE_MISMATCH", "SQLITE_MISUSE", "CURLOPT_COOKIE", "CURLE_SSL_CERTPROBLEM", "CURLOPT_SSLCERT", "CURLOPT_KEYPASSWD", "CURLOPT_WRITEHEADER", "CURLOPT_SSL_VERIFYHOST", "CURLOPT_COOKIEFILE", "CURLE_HTTP_RANGE_ERROR", "CURLE_HTTP_POST_ERROR", "CURLOPT_CUSTOMREQUEST", "CURLOPT_STDERR", "SOCKET_EBADR", "CURLOPT_RETURNTRANSFER", "CURLOPT_QUOTE", "CURLOPT_POSTQUOTE", "CURLOPT_INTERFACE", "CURLOPT_KRB4LEVEL", "SOCKET_ENODATA", "SOCKET_ESRMNT", "CURLOPT_WRITEFUNCTION", "CURLOPT_READFUNCTION", "CURLOPT_HEADERFUNCTION", "SOCKET_EADV", "SOCKET_EPROTO", "SOCKET_EMULTIHOP", "SOCKET_EBADMSG", "CURLOPT_FORBID_REUSE", "CURLOPT_RANDOM_FILE", "CURLOPT_EGDSOCKET", "SOCKET_EREMCHG", "CURLOPT_CONNECTTIMEOUT_MS", "CURLOPT_CAINFO", "CURLOPT_CAPATH", "CURLOPT_COOKIEJAR", "CURLOPT_SSL_CIPHER_LIST", "CURLOPT_BINARYTRANSFER", "SQLITE_DONE", "CURLOPT_HTTP_VERSION", "CURLOPT_SSLKEY", "CURLOPT_SSLKEYTYPE", "CURLOPT_SSLENGINE", "CURLOPT_SSLCERTTYPE", "CURLE_OUT_OF_MEMORY", "CURLOPT_ENCODING", "CURLE_SSL_CIPHER", "SOCKET_EREMOTEIO", "CURLOPT_HTTP200ALIASES", "CURLAUTH_ANY", "CURLAUTH_ANYSAFE", "CURLOPT_PRIVATE", "CURLINFO_EFFECTIVE_URL", "CURLINFO_HTTP_CODE", "CURLINFO_HEADER_SIZE", "CURLINFO_REQUEST_SIZE", "CURLINFO_TOTAL_TIME", "CURLINFO_NAMELOOKUP_TIME", "CURLINFO_CONNECT_TIME", "CURLINFO_PRETRANSFER_TIME", "CURLINFO_SIZE_UPLOAD", "CURLINFO_SIZE_DOWNLOAD", "CURLINFO_SPEED_DOWNLOAD", "CURLINFO_SPEED_UPLOAD", "CURLINFO_FILETIME", "CURLINFO_SSL_VERIFYRESULT", "CURLINFO_CONTENT_LENGTH_DOWNLOAD", "CURLINFO_CONTENT_LENGTH_UPLOAD", "CURLINFO_STARTTRANSFER_TIME", "CURLINFO_CONTENT_TYPE", "CURLINFO_REDIRECT_TIME", "CURLINFO_REDIRECT_COUNT", "CURLINFO_PRIVATE", "CURLINFO_CERTINFO", "SQLITE_PROTOCOL", "SQLITE_SCHEMA", "SQLITE_TOOBIG", "SQLITE_NOLFS", "SQLITE_AUTH", "SQLITE_FORMAT", "SOCKET_ENOTTY", "SQLITE_NOTADB", "SOCKET_ENOSPC", "SOCKET_ESPIPE", "SOCKET_EROFS", "SOCKET_EMLINK", "GD_RELEASE_VERSION", "SOCKET_ENOLCK", "SOCKET_ENOSYS", "SOCKET_EUNATCH", "SOCKET_ENOANO", "SOCKET_EBADRQC", "SOCKET_EBADSLT", "SOCKET_ENOSTR", "SOCKET_ETIME", "SOCKET_ENOSR", "SVN_REVISION_HEAD", "XSD_ENTITY", "XSD_NOTATION", "CURLOPT_CERTINFO", "CURLOPT_POSTREDIR", "CURLOPT_SSH_AUTH_TYPES", "CURLOPT_SSH_PUBLIC_KEYFILE", "CURLOPT_SSH_PRIVATE_KEYFILE", "CURLOPT_SSH_HOST_PUBLIC_KEY_MD5", "CURLE_SSH", "CURLOPT_REDIR_PROTOCOLS", "CURLOPT_PROTOCOLS", "XSD_NONNEGATIVEINTEGER", "XSD_BYTE","DNS_SRV","DNS_A6", "DNS_NAPTR", "DNS_AAAA", "FILTER_SANITIZE_FULL_SPECIAL_CHARS", "ABDAY_1", "SVN_REVISION_UNSPECIFIED", "SVN_REVISION_BASE", "SVN_REVISION_COMMITTED", "SVN_REVISION_PREV", "GD_VERSION", "MCRYPT_TRIPLEDES", "MCRYPT_ARCFOUR_IV", "MCRYPT_ARCFOUR", "MCRYPT_BLOWFISH", "MCRYPT_BLOWFISH_COMPAT", "MCRYPT_CAST_128", "MCRYPT_CAST_256", "MCRYPT_ENIGNA", "MCRYPT_DES", "MCRYPT_GOST", "MCRYPT_LOKI97", "MCRYPT_PANAMA", "MCRYPT_RC2", "MCRYPT_RIJNDAEL_128", "MCRYPT_RIJNDAEL_192", "MCRYPT_RIJNDAEL_256", "MCRYPT_SAFER64", "MCRYPT_SAFER128","MCRYPT_SAFERPLUS", "MCRYPT_SERPENT", "MCRYPT_THREEWAY", "MCRYPT_TWOFISH", "MCRYPT_WAKE", "MCRYPT_XTEA", "MCRYPT_IDEA", "MCRYPT_MARS", "MCRYPT_RC6", "MCRYPT_SKIPJACK", "MCRYPT_MODE_CBC", "MCRYPT_MODE_CFB", "MCRYPT_MODE_ECB", "MCRYPT_MODE_NOFB", "MCRYPT_MODE_OFB", "MCRYPT_MODE_STREAM", "CL_EXPUNGE", "SQLITE_ROW", "POSIX_S_IFBLK", "POSIX_S_IFSOCK", "XSD_IDREF", "ABDAY_2", "ABDAY_3", "ABDAY_4", "ABDAY_5", "ABDAY_6", "ABDAY_7", "DAY_1", "DAY_2", "DAY_3", "DAY_4", "DAY_5", "DAY_6", "DAY_7", "ABMON_1", "ABMON_2", "ABMON_3", "ABMON_4", "ABMON_5", "ABMON_6", "ABMON_7","ABMON_8", "ABMON_9", "ABMON_10", "ABMON_11", "ABMON_12", "MON_1", "MON_2", "MON_3", "MON_4", "MON_5", "MON_6", "MON_7", "MON_8", "MON_9", "MON_10", "MON_11", "MON_12", "AM_STR", "PM_STR", "D_T_FMT", "D_FMT", "T_FMT", "T_FMT_AMPM", "ERA", "ERA_D_T_FMT", "ERA_D_FMT", "ERA_T_FMT", "ALT_DIGITS", "CRNCYSTR", "THOUSEP", "YESEXPR", "NOEXPR", "SOCKET_ENOMEDIUM", "GLOB_AVAILABLE_FLAGS", "XSD_SHORT", "XSD_NMTOKENS", "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7", "DNS_ANY", "DNS_ALL", "SOCKET_ENOLINK", "SOCKET_ECOMM", "SOAP_FUNCTIONS_ALL", "UNKNOWN_TYPE", "XSD_BASE64BINARY", "XSD_ANYURI", "XSD_QNAME", "SOCKET_EISNAM", "SOCKET_EMEDIUMTYPE", "XSD_NCNAME", "XSD_ID", "XSD_ENTITIES", "XSD_INTEGER", "XSD_NONPOSITIVEINTEGER", "XSD_NEGATIVEINTEGER", "XSD_LONG", "XSD_INT", "XSD_UNSIGNEDLONG", "XSD_UNSIGNEDINT", "XSD_UNSIGNEDSHORT", "XSD_UNSIGNEDBYTE", "XSD_POSITIVEINTEGER", "XSD_ANYTYPE", "XSD_ANYXML", "APACHE_MAP", "XSD_1999_TIMEINSTANT", "XSD_NAMESPACE", "XSD_1999_NAMESPACE", "SOCKET_ENOTUNIQ", "SOCKET_EBADFD", "SOCKET_ESTRPIPE", "T_GOTO", "T_NAMESPACE", "T_NS_C", "T_DIR", "T_NS_SEPARATOR", "LIBXSLT_VERSION","LIBEXSLT_DOTTED_VERSION", "LIBEXSLT_VERSION", "SVN_AUTH_PARAM_DEFAULT_USERNAME", "SVN_AUTH_PARAM_DEFAULT_PASSWORD", "SVN_AUTH_PARAM_NON_INTERACTIVE", "SVN_AUTH_PARAM_DONT_STORE_PASSWORDS", "SVN_AUTH_PARAM_NO_AUTH_CACHE", "SVN_AUTH_PARAM_SSL_SERVER_FAILURES", "SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO", "SVN_AUTH_PARAM_CONFIG", "SVN_AUTH_PARAM_SERVER_GROUP", "SVN_AUTH_PARAM_CONFIG_DIR", "PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS", "SVN_FS_CONFIG_FS_TYPE", "SVN_FS_TYPE_BDB", "SVN_FS_TYPE_FSFS", "SVN_PROP_REVISION_DATE", "SVN_PROP_REVISION_ORIG_DATE", "SVN_PROP_REVISION_AUTHOR", "SVN_PROP_REVISION_LOG" ].forEach(function(element, index, array) { result[element] = token("atom", "php-predefined-constant"); }); // PHP declared classes - output of get_declared_classes(). Differs from http://php.net/manual/en/reserved.classes.php [ "stdClass", "Exception", "ErrorException", "COMPersistHelper", "com_exception", "com_safearray_proxy", "variant", "com", "dotnet", "ReflectionException", "Reflection", "ReflectionFunctionAbstract", "ReflectionFunction", "ReflectionParameter", "ReflectionMethod", "ReflectionClass", "ReflectionObject", "ReflectionProperty", "ReflectionExtension", "DateTime", "DateTimeZone", "LibXMLError", "__PHP_Incomplete_Class", "php_user_filter", "Directory", "SimpleXMLElement", "DOMException", "DOMStringList", "DOMNameList", "DOMImplementationList", "DOMImplementationSource", "DOMImplementation", "DOMNode", "DOMNameSpaceNode", "DOMDocumentFragment", "DOMDocument", "DOMNodeList", "DOMNamedNodeMap", "DOMCharacterData", "DOMAttr", "DOMElement", "DOMText", "DOMComment", "DOMTypeinfo", "DOMUserDataHandler", "DOMDomError", "DOMErrorHandler", "DOMLocator", "DOMConfiguration", "DOMCdataSection", "DOMDocumentType", "DOMNotation", "DOMEntity", "DOMEntityReference", "DOMProcessingInstruction", "DOMStringExtend", "DOMXPath", "RecursiveIteratorIterator", "IteratorIterator", "FilterIterator", "RecursiveFilterIterator", "ParentIterator", "LimitIterator", "CachingIterator", "RecursiveCachingIterator", "NoRewindIterator", "AppendIterator", "InfiniteIterator", "RegexIterator", "RecursiveRegexIterator", "EmptyIterator", "ArrayObject", "ArrayIterator", "RecursiveArrayIterator", "SplFileInfo", "DirectoryIterator", "RecursiveDirectoryIterator", "SplFileObject", "SplTempFileObject", "SimpleXMLIterator", "LogicException", "BadFunctionCallException", "BadMethodCallException", "DomainException", "InvalidArgumentException", "LengthException", "OutOfRangeException", "RuntimeException", "OutOfBoundsException", "OverflowException", "RangeException", "UnderflowException", "UnexpectedValueException", "SplObjectStorage", "XMLReader", "XMLWriter", "mysqli_sql_exception", "mysqli_driver", "mysqli", "mysqli_warning", "mysqli_result", "mysqli_stmt", "PDOException", "PDO", "PDOStatement", "PDORow","Closure", "DateInterval", "DatePeriod", "FilesystemIterator", "GlobIterator", "MultipleIterator", "RecursiveTreeIterator", "SoapClient", "SoapFault", "SoapHeader", "SoapParam", "SoapServer", "SoapVar", "SplDoublyLinkedList", "SplFixedArray", "SplHeap", "SplMaxHeap", "SplMinHeap", "SplPriorityQueue", "SplQueue", "SplStack", "SQLite3", "SQLite3Result", "SQLite3Stmt", "SQLiteDatabase", "SQLiteException", "SQLiteResult", "SQLiteUnbuffered", "Svn", "SvnNode", "SvnWc", "SvnWcSchedule", "XSLTProcessor", "ZipArchive", ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-class"); }); return result; }(); // Helper regexps var isOperatorChar = /[+*&%\/=<>!?.|^@-]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_\\]/; // Wrapper around phpToken that helps maintain parser state (whether // we are inside of a multi-line comment) function phpTokenState(inside) { return function(source, setState) { var newInside = inside; var type = phpToken(inside, source, function(c) {newInside = c;}); if (newInside != inside) setState(phpTokenState(newInside)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through phpTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function phpToken(inside, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "php-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "php-atom"}; } // Read a word and look it up in the keywords array. If found, it's a // keyword of that type; otherwise it's a PHP T_STRING. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; // since we called get(), tokenize::take won't get() anything. Thus, we must set token.content return known ? {type: known.type, style: known.style, content: word} : {type: "t_string", style: "php-t_string", content: word}; } function readVariable() { source.nextWhileMatches(isWordChar); var word = source.get(); // in PHP, '$this' is a reserved word, but 'this' isn't. You can have function this() {...} if (word == "$this") return {type: "variable", style: "php-keyword", content: word}; else return {type: "variable", style: "php-variable", content: word}; } // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while(!source.endOfLine()){ var next = source.next(); if (next == end && !escaped) return false; escaped = next == "\\" && !escaped; } return escaped; } function readSingleLineComment() { // read until the end of the line or until ?>, which terminates single-line comments // `<?php echo 1; // comment ?> foo` will display "1 foo" while(!source.lookAhead("?>") && !source.endOfLine()) source.next(); return {type: "comment", style: "php-comment"}; } /* For multi-line comments, we want to return a comment token for every line of the comment, but we also want to return the newlines in them as regular newline tokens. We therefore need to save a state variable ("inside") to indicate whether we are inside a multi-line comment. */ function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "php-comment"}; } // similar to readMultilineComment and nextUntilUnescaped // unlike comments, strings are not stopped by ?> function readMultilineString(start){ var newInside = start; var escaped = false; while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == start && !escaped){ newInside = null; // we're outside of the string now break; } escaped = (next == "\\" && !escaped); } setInside(newInside); return { type: newInside == null? "string" : "string_not_terminated", style: (start == "'"? "php-string-single-quoted" : "php-string-double-quoted") }; } // http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc // See also 'nowdoc' on the page. Heredocs are not interrupted by the '?>' token. function readHeredoc(identifier){ var token = {}; if (identifier == "<<<") { // on our first invocation after reading the <<<, we must determine the closing identifier if (source.equals("'")) { // nowdoc source.nextWhileMatches(isWordChar); identifier = "'" + source.get() + "'"; source.next(); // consume the closing "'" } else if (source.matches(/[A-Za-z_]/)) { // heredoc source.nextWhileMatches(isWordChar); identifier = source.get(); } else { // syntax error setInside(null); return { type: "error", style: "syntax-error" }; } setInside(identifier); token.type = "string_not_terminated"; token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; token.content = identifier; } else { token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; // consume a line of heredoc and check if it equals the closing identifier plus an optional semicolon if (source.lookAhead(identifier, true) && (source.lookAhead(";\n") || source.endOfLine())) { // the closing identifier can only appear at the beginning of the line // note that even whitespace after the ";" is forbidden by the PHP heredoc syntax token.type = "string"; token.content = source.get(); // don't get the ";" if there is one setInside(null); } else { token.type = "string_not_terminated"; source.nextWhileMatches(/[^\n]/); token.content = source.get(); } } return token; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "php-operator"}; } function readStringSingleQuoted() { var endBackSlash = nextUntilUnescaped(source, "'", false); setInside(endBackSlash ? "'" : null); return {type: "string", style: "php-string-single-quoted"}; } function readStringDoubleQuoted() { var endBackSlash = nextUntilUnescaped(source, "\"", false); setInside(endBackSlash ? "\"": null); return {type: "string", style: "php-string-double-quoted"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. switch (inside) { case null: case false: break; case "'": case "\"": return readMultilineString(inside); case "/*": return readMultilineComment(source.next()); default: return readHeredoc(inside); } var ch = source.next(); if (ch == "'" || ch == "\"") return readMultilineString(ch); else if (ch == "#") return readSingleLineComment(); else if (ch == "$") return readVariable(); else if (ch == ":" && source.equals(":")) { source.next(); // the T_DOUBLE_COLON can only follow a T_STRING (class name) return {type: "t_double_colon", style: "php-operator"}; } // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;:]/.test(ch)) { return {type: ch, style: "php-punctuation"}; } else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/") { if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) return readSingleLineComment(); else return readOperator(); } else if (ch == "<") { if (source.lookAhead("<<", true)) { setInside("<<<"); return {type: "<<<", style: "php-punctuation"}; } else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || phpTokenState(false, true)); }; })();
JavaScript
function waitForStyles() { for (var i = 0; i < document.styleSheets.length; i++) if (/googleapis/.test(document.styleSheets[i].href)) return document.body.className += " droid"; setTimeout(waitForStyles, 100); } setTimeout(function() { if (/AppleWebKit/.test(navigator.userAgent) && /iP[oa]d|iPhone/.test(navigator.userAgent)) return; var link = document.createElement("LINK"); link.type = "text/css"; link.rel = "stylesheet"; link.href = "http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"; document.documentElement.getElementsByTagName("HEAD")[0].appendChild(link); waitForStyles(); }, 20);
JavaScript
CKFinder.addPlugin( 'fileeditor', function( api ) { var regexExt = /^(.*)\.([^\.]+)$/, regexTextExt = /^(txt|css|html|htm|js|asp|cfm|cfc|ascx|php|inc|xml|xslt|xsl)$/i, regexCodeMirrorExt = /^(css|html|htm|js|xml|xsl|php)$/i, codemirror, file, fileLoaded = false, doc; var codemirrorPath = CKFinder.getPluginPath('fileeditor') + 'codemirror/'; var codeMirrorParsers = { css : 'parsecss.js', js : [ 'tokenizejavascript.js', 'parsejavascript.js' ], xml : 'parsexml.js', php : ['parsexml.js', 'parsecss.js', 'tokenizejavascript.js', 'parsejavascript.js', '../contrib/php/js/tokenizephp.js', '../contrib/php/js/parsephp.js', '../contrib/php/js/parsephphtmlmixed.js'] }; var codeMirrorCss = { css : codemirrorPath + 'css/csscolors.css', js : codemirrorPath + 'css/jscolors.css', xml : codemirrorPath + 'css/xmlcolors.css', php : [ codemirrorPath + 'css/xmlcolors.css', codemirrorPath + 'css/jscolors.css', codemirrorPath + 'css/csscolors.css', codemirrorPath + 'contrib/php/css/phpcolors.css' ] }; codeMirrorCss.xsl = codeMirrorCss.xml; codeMirrorCss.htm = codeMirrorCss.xml; codeMirrorCss.html = codeMirrorCss.xml; codeMirrorParsers.xsl = codeMirrorParsers.xml; codeMirrorParsers.htm = codeMirrorParsers.xml; codeMirrorParsers.html = codeMirrorParsers.xml; var isTextFile = function( file ) { return regexTextExt.test( file.ext ); }; CKFinder.dialog.add( 'fileEditor', function( api ) { var height, width; var saveButton = (function() { return { id : 'save', label : api.lang.Fileeditor.save, type : 'button', onClick : function ( evt ) { if ( !fileLoaded ) return true; var dialog = evt.data.dialog; var content = codemirror ? codemirror.getCode() : doc.getById( 'fileContent' ).getValue(); api.connector.sendCommandPost( "SaveFile", null, { content : content, fileName : file.name }, function( xml ) { if ( xml.checkError() ) return false; api.openMsgDialog( '', api.lang.Fileeditor.fileSaveSuccess ); dialog.hide(); return undefined; }, file.folder.type, file.folder ); return false; } }; })(); if ( api.inPopup ) { width = api.document.documentElement.offsetWidth; height = api.document.documentElement.offsetHeight; } else { var parentWindow = ( api.document.parentWindow || api.document.defaultView ).parent; width = parentWindow.innerWidth ? parentWindow.innerWidth : parentWindow.document.documentElement.clientWidth; height = parentWindow.innerHeight ? parentWindow.innerHeight : parentWindow.document.documentElement.clientHeight; } return { title : api.getSelectedFile().name, minWidth : parseInt( width, 10 ) * 0.6, minHeight : parseInt( height, 10 ) * 0.7, onHide : function() { if ( fileLoaded ) { var fileContent = doc.getById( 'fileContent' ); if ( fileContent ) fileContent.remove(); } }, onShow : function() { var dialog = this; var cssWidth = parseInt( width, 10 ) * 0.6 - 10; var cssHeight = parseInt( height, 10 ) * 0.7 - 20; doc = dialog.getElement().getDocument(); var win = doc.getWindow(); doc.getById( 'fileArea' ).setHtml( '<div class="ckfinder_loader_32" style="margin: 100px auto 0 auto;text-align:center;"><p style="height:' + cssHeight + 'px;width:' + cssWidth + 'px;">' + api.lang.Fileeditor.loadingFile + '</p></div>' ); file = api.getSelectedFile(); var enableCodeMirror = regexCodeMirrorExt.test( file.ext ); this.setTitle( file.name ); if ( enableCodeMirror && win.$.CodeMirror === undefined ) { var head= doc.$.getElementsByTagName( 'head' )[0]; var script= doc.$.createElement( 'script' ); script.type= 'text/javascript'; script.src = CKFinder.getPluginPath( 'fileeditor' ) + 'codemirror/js/codemirror.js'; head.appendChild( script ); } // If CKFinder is runninng under a different domain than baseUrl, then the following call will fail: // CKFinder.ajax.load( file.getUrl() + '?t=' + (new Date().getTime()), function( data )... var url = api.connector.composeUrl( 'DownloadFile', { FileName : file.name, format : 'text', t : new Date().getTime() }, file.folder.type, file.folder ); CKFinder.ajax.load( url, function( data ) { if ( data === null || ( file.size > 0 && data === '' ) ) { api.openMsgDialog( '', api.lang.Fileeditor.fileOpenError ); dialog.hide(); return; } else fileLoaded = true; var fileArea = doc.getById( 'fileArea' ); fileArea.setStyle('height', '100%'); fileArea.setHtml( '<textarea id="fileContent" style="height:' + cssHeight + 'px; width:' + cssWidth + 'px"></textarea>' ); doc.getById( 'fileContent' ).setText( data ); codemirror = null; if ( enableCodeMirror && win.$.CodeMirror !== undefined ) { codemirror = win.$.CodeMirror.fromTextArea( doc.getById( 'fileContent').$, { height : cssHeight + 'px', parserfile : codeMirrorParsers[ file.ext.toLowerCase() ], stylesheet : codeMirrorCss[ file.ext.toLowerCase() ], path : codemirrorPath + "js/" } ); // TODO get rid of ugly buttons and provide something better var undoB = doc.createElement( "button", { attributes: { "label" : api.lang.common.undo } } ); undoB.on( 'click', function() { codemirror.undo(); }); undoB.setHtml( api.lang.common.undo ); undoB.appendTo( doc.getById( 'fileArea' ) ); var redoB = doc.createElement( 'button', { attributes: { "label" : api.lang.common.redo } } ); redoB.on('click', function() { codemirror.redo(); }); redoB.setHtml( api.lang.common.redo ); redoB.appendTo( doc.getById( 'fileArea' ) ); } }); }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'html', id : 'htmlLoader', html : '' + '<style type="text/css">' + '.CodeMirror-wrapping {background:white;}' + '</style>' + '<div id="fileArea"></div>' } ] } ], // TODO http://dev.fckeditor.net/ticket/4750 buttons : [ saveButton, CKFinder.dialog.cancelButton ] }; } ); api.addFileContextMenuOption( { label : api.lang.Fileeditor.contextMenuName, command : "fileEditor" } , function( api, file ) { api.openDialog( 'fileEditor' ); }, function ( file ) { var maxSize = 1024; if ( typeof (CKFinder.config.fileeditorMaxSize) != 'undefined' ) maxSize = CKFinder.config.fileeditorMaxSize; // Disable for images, binary files, large files etc. if ( isTextFile( file ) && file.size <= maxSize ) { if ( file.folder.acl.fileDelete ) return true; else return -1; } return false; }); } );
JavaScript
/** * Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license * * CKFinder 2.x - sample "dummy" plugin. * * To enable it, add the following line to config.js: * config.extraPlugins = 'dummy'; */ /** * See http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.html#.addPlugin */ CKFinder.addPlugin( 'dummy', { lang : [ 'en', 'pl' ], appReady : function( api ) { CKFinder.dialog.add( 'dummydialog', function( api ) { // CKFinder.dialog.definition var dialogDefinition = { title : api.lang.dummy.title, minWidth : 390, minHeight : 230, onOk : function() { // "this" is now a CKFinder.dialog object. var value = this.getValueOf( 'tab1', 'textareaId' ); if ( !value ) { api.openMsgDialog( '', api.lang.dummy.typeText ); return false; } else { alert( "You have entered: " + value ); return true; } }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'html', html : '<h3>' + api.lang.dummy.typeText + '</h3>' }, { type : 'textarea', id : 'textareaId', rows : 10, cols : 40 } ] } ], buttons : [ CKFinder.dialog.cancelButton, CKFinder.dialog.okButton ] }; return dialogDefinition; } ); api.addFileContextMenuOption( { label : api.lang.dummy.menuItem, command : "dummycommand" } , function( api, file ) { api.openDialog('dummydialog'); }); } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKFinder.setPluginLang( 'dummy', 'pl', { dummy : { title : 'Testowe okienko', menuItem : 'Otwórz okienko dummy', typeText : 'Podaj jakiś tekst.' } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKFinder.setPluginLang( 'dummy', 'en', { dummy : { title : 'Dummy dialog', menuItem : 'Open dummy dialog', typeText : 'Please type some text.' } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { window.CKFinder = function(a, b, c, d) { var e = this; e.BasePath = a || CKFinder.DEFAULT_BASEPATH; e.Width = b || '100%'; e.Height = c || 400; e.SelectFunction = d || null; e.SelectFunctionData = null; e.SelectThumbnailFunction = d || null; e.SelectThumbnailFunctionData = null; e.DisableThumbnailSelection = false; e.ClassName = 'CKFinderFrame'; e.StartupPath = null; e.StartupFolderExpanded = false; e.RememberLastFolder = true; e.ResourceType = null; e.Id = null; e.Skin = null; e.ConnectorLanguage = 'php'; }; CKFinder.DEFAULT_BASEPATH = '/ckfinder/'; CKFinder.prototype = { Create : function() { document.write(this.CreateHtml()); }, CreateHtml : function() { var c = this; var a = c.ClassName; if (a && a.length > 0) a = ' class="' + a + '"'; var b = c.Id; if (b && b.length > 0) b = ' id="' + b + '"'; return '<iframe src="' + c._BuildUrl() + '" width="' + c.Width + '" ' + 'height="' + c.Height + '"' + a + b + ' frameborder="0" scrolling="no"></iframe>'; }, Popup : function(a, b) { a = a || '80%'; b = b || '70%'; if (typeof a == 'string' && a.length > 1 && a.substr(a.length - 1, 1) == '%') a = parseInt(window.screen.width * parseInt(a, 10) / 100, 10); if (typeof b == 'string' && b.length > 1 && b.substr(b.length - 1, 1) == '%') b = parseInt(window.screen.height * parseInt(b, 10) / 100, 10); if (a < 200) a = 200; if (b < 200) b = 200; var c = parseInt((window.screen.height - b) / 2, 10), d = parseInt( (window.screen.width - a) / 2, 10), e = 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width=' + a + ',height=' + b + ',top=' + c + ',left=' + d, f = window .open('', 'CKFinderPopup', e, true); if (!f) return false; var g = this._BuildUrl().replace(/&amp;/g, '&'); try { f.moveTo(d, c); f.resizeTo(a, b); f.focus(); f.location.href = g; } catch (h) { f = window.open(g, 'CKFinderPopup', e, true); } return true; }, _BuildUrl : function(a) { var d = this; a = a || d.BasePath; var b = ''; if (!a || a.length === 0) a = CKFinder.DEFAULT_BASEPATH; if (a.substr(a.length - 1, 1) != '/') a += '/'; a += 'ckfinder.html'; var c; if (d.SelectFunction) { c = d.SelectFunction; if (typeof c == 'function') c = c.toString().match(/function ([^(]+)/)[1]; b += '?action=js&amp;func=' + c; } if (d.Skin) { b += b ? '&amp;' : '?'; b += 'skin=' + encodeURIComponent(d.Skin); } if (d.SelectFunctionData) { b += b ? '&amp;' : '?'; b += 'data=' + encodeURIComponent(d.SelectFunctionData); } if (d.ResourceType) { b += b ? '&amp;' : '?'; b += 'type=' + encodeURIComponent(d.ResourceType); } if (d.DisableThumbnailSelection) { b += b ? '&amp;' : '?'; b += 'dts=1'; } else if (d.SelectThumbnailFunction || d.SelectFunction) { c = d.SelectThumbnailFunction || d.SelectFunction; if (typeof c == 'function') c = c.toString().match(/function ([^(]+)/)[1]; b += b ? '&amp;' : '?'; b += 'thumbFunc=' + c; if (d.SelectThumbnailFunctionData) b += '&amp;tdata=' + encodeURIComponent(d.SelectThumbnailFunctionData); else if (!d.SelectThumbnailFunction && d.SelectFunctionData) b += '&amp;tdata=' + encodeURIComponent(d.SelectFunctionData); } if (d.StartupPath) { b += b ? '&amp;' : '?'; b += 'start=' + encodeURIComponent(d.StartupPath + (d.StartupFolderExpanded ? ':1' : ':0')); } if (!d.RememberLastFolder) { b += b ? '&amp;' : '?'; b += 'rlf=0'; } if (d.Id) { b += b ? '&amp;' : '?'; b += 'id=' + encodeURIComponent(d.Id); } return a + b; } }; CKFinder.Create = function(a, b, c, d) { var e; if (a !== null && typeof a == 'object') { e = new CKFinder(); for ( var f in a) e[f] = a[f]; } else e = new CKFinder(a, b, c, d); e.Create(); }; CKFinder.Popup = function(a, b, c, d) { var e; if (a !== null && typeof a == 'object') { e = new CKFinder(); for ( var f in a) e[f] = a[f]; } else e = new CKFinder(a, b, c, d); e.Popup(b, c); }; CKFinder.SetupFCKeditor = function(a, b, c, d) { var e; if (b !== null && typeof b == 'object') { e = new CKFinder(); for ( var f in b) { e[f] = b[f]; if (f == 'Width') { var g = e[f] || 800; if (typeof g == 'string' && g.length > 1 && g.substr(g.length - 1, 1) == '%') g = parseInt(window.screen.width * parseInt(g, 10) / 100, 10); a.Config.LinkBrowserWindowWidth = g; a.Config.ImageBrowserWindowWidth = g; a.Config.FlashBrowserWindowWidth = g; } else if (f == 'Height') { var h = e[f] || 600; if (typeof h == 'string' && h.length > 1 && h.substr(h.length - 1, 1) == '%') h = parseInt(window.screen.height * parseInt(h, 10) / 100, 10); a.Config.LinkBrowserWindowHeight = h; a.Config.ImageBrowserWindowHeight = h; a.Config.FlashBrowserWindowHeight = h; } } } else e = new CKFinder(b); var i = e.BasePath; if (i.substr(0, 1) != '/' && i.indexOf('://') == -1) i = document.location.pathname.substring(0, document.location.pathname.lastIndexOf('/') + 1) + i; i = e._BuildUrl(i); var j = i.indexOf('?') !== -1 ? '&amp;' : '?'; a.Config.LinkBrowserURL = i; a.Config.ImageBrowserURL = i + j + 'type=' + (c || 'Images'); a.Config.FlashBrowserURL = i + j + 'type=' + (d || 'Flash'); var k = i.substring(0, 1 + i.lastIndexOf('/')); a.Config.LinkUploadURL = k + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=Files'; a.Config.ImageUploadURL = k + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (c || 'Images'); a.Config.FlashUploadURL = k + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (d || 'Flash'); }; CKFinder.SetupCKEditor = function(a, b, c, d) { if (a === null) { for ( var e in CKEDITOR.instances) CKFinder.SetupCKEditor(CKEDITOR.instances[e], b, c, d); CKEDITOR.on('instanceCreated', function(m) { CKFinder.SetupCKEditor(m.editor, b, c, d); }); return; } var f; if (b !== null && typeof b == 'object') { f = new CKFinder(); for ( var g in b) { f[g] = b[g]; if (g == 'Width') { var h = f[g] || 800; if (typeof h == 'string' && h.length > 1 && h.substr(h.length - 1, 1) == '%') h = parseInt(window.screen.width * parseInt(h, 10) / 100, 10); a.config.filebrowserWindowWidth = h; } else if (g == 'Height') { var i = f[g] || 600; if (typeof i == 'string' && i.length > 1 && i.substr(i.length - 1, 1) == '%') i = parseInt(window.screen.height * parseInt(i, 10) / 100, 10); a.config.filebrowserWindowHeight = h; } } } else f = new CKFinder(b); var j = f.BasePath; if (j.substr(0, 1) != '/' && j.indexOf('://') == -1) j = document.location.pathname.substring(0, document.location.pathname.lastIndexOf('/') + 1) + j; j = f._BuildUrl(j); var k = j.indexOf('?') !== -1 ? '&amp;' : '?'; a.config.filebrowserBrowseUrl = j; a.config.filebrowserImageBrowseUrl = j + k + 'type=' + (c || 'Images'); a.config.filebrowserFlashBrowseUrl = j + k + 'type=' + (d || 'Flash'); var l = j.substring(0, 1 + j.lastIndexOf('/')); a.config.filebrowserUploadUrl = l + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=Files'; a.config.filebrowserImageUploadUrl = l + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (c || 'Images'); a.config.filebrowserFlashUploadUrl = l + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (d || 'Flash'); }; })();
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var a = (function() { var f = { jY : 'B8MI1HT', _ : {}, status : 'unloaded', basePath : (function() { var i = window.CKFINDER_BASEPATH || ''; if (!i) { var j = document.getElementsByTagName('script'); for ( var k = 0; k < j.length; k++) { var l = j[k].src .match(/(^|.*[\\\/])CKFINDER(?:_basic)?(?:_v2)?(?:_source)?.js(?:\?.*)?$/i); if (l) { i = l[1]; break; } } } if (i.indexOf('://') == -1) if (i.indexOf('/') === 0) i = location.href.match(/^.*?:\/\/[^\/]*/)[0] + i; else i = location.href.match(/^[^\?]*\/(?:)/)[0] + i; return i; })(), getUrl : function(i) { if (i.indexOf('://') == -1 && i.indexOf('/') !== 0) i = this.basePath + i; if (this.jY && i.charAt(i.length - 1) != '/') i += (i.indexOf('?') >= 0 ? '&' : '?') + 't=' + this.jY; return i; } }, g = window.CKFINDER_GETURL; if (g) { var h = f.getUrl; f.getUrl = function(i) { return g.call(f, i) || h.call(f, i); }; } return f; })(); function b(f) { return a.instances[f]; } ; var c = { callback : 1, selectThumbnailActionFunction : 1, selectActionFunction : 1 }; a.jd = function() { var h = this; var f = {}; for ( var g in h) { if (!h.hasOwnProperty(g)) continue; if (typeof h[g] == 'function' && !c[g]) continue; f[g] = h[g]; } if (h.callback) f.callback = h.callback; return f; }; a.lj = function(f) { var i = this; f = f || i.basePath; var g = ''; if (!f || f.length === 0) f = CKFinder.DEFAULT_basePath; if (f.substr(f.length - 1, 1) != '/') f += '/'; f += 'ckfinder.html'; var h; if (i.hh) { h = i.hh; if (typeof h == 'function') h = h.toString().match(/function ([^(]+)/)[1]; g += '?action=js&amp;func=' + h; } if (i.jx) { g += g ? '&amp;' : '?'; g += 'data=' + encodeURIComponent(i.jx); } if (i.disableThumbnailSelection) { g += g ? '&amp;' : '?'; g += 'dts=1'; } else if (i.lH || i.hh) { h = i.lH || i.hh; if (typeof h == 'function') h = h.toString().match(/function ([^(]+)/)[1]; g += g ? '&amp;' : '?'; g += 'thumbFunc=' + h; if (i.nm) g += '&amp;tdata=' + encodeURIComponent(i.nm); else if (!i.lH && i.jx) g += '&amp;tdata=' + encodeURIComponent(i.jx); } if (i.startupPath) { g += g ? '&amp;' : '?'; g += 'start=' + encodeURIComponent(i.startupPath + (i.startupFolderExpanded ? ':1' : ':0')); } if (!i.rememberLastFolder) { g += g ? '&amp;' : '?'; g += 'rlf=0'; } if (i.id) { g += g ? '&amp;' : '?'; g += 'id=' + encodeURIComponent(i.id); } if (i.skin) { g += g ? '&amp;' : '?'; g += 'skin=' + encodeURIComponent(i.skin); } return f + g; }; function d(f) { var i = this; i.id = f.name; var g = f.element.getDocument().getWindow().$, h = a.oC.getWindow().$; i.inPopup = !!(g && g.opener); i.inIframe = !i.inPopup && g != h.top && g.frameElement.nodeName.toLowerCase() == 'iframe'; i.inFrame = !i.inPopup && g != h.top && g.frameElement.nodeName.toLowerCase() == 'frame'; i.inUrlPopup = !!(i.inPopup && h.opener); } ; function e(f, g, h) { g.on('appReady', function(i) { i.removeListener(); f.document = g.document.$; f.folders = g.folders; f.files = g.aG['filesview.filesview'][0].data().files; f.basketFiles = g.basketFiles; f.resourceTypes = g.resourceTypes; f.connector = g.connector; f.lang = g.lang; f.langCode = g.langCode; f.config = g.config; g.aG['foldertree.foldertree'][0].on('afterAddFolder', function(j) { j.removeListener(); if (h) h(f); }, f); }, f, null, 999); } ; d.prototype = { _ : {}, addFileContextMenuOption : function(f, g, h) { var i = b(this.id), j = 'FileContextMenu_' + f.command; i.bD(j, { exec : function(m) { var n = m.aG['filesview.filesview'][0].tools.dH(); g(m.cg, n); } }); f.command = j; if (!f.group) f.group = 'file1'; i.gp(j, f); var k = i.aG['filesview.filesview']; for ( var l = 0; l < k.length; l++) k[l].on('beforeContextMenu', function o(m) { if (h) { var n = h(this.tools.dH()); if (n) m.data.bj[j] = n == -1 ? a.aY : a.aS; } else m.data.bj[j] = a.aS; }); }, disableFileContextMenuOption : function(f, g) { var h = b(this.id), i = g ? 'FileContextMenu_' + f : f, j = h.aG['filesview.filesview'], k = []; for ( var l = 0; l < j.length; l++) { var m = k.push(function o(n) { delete n.data.bj[i]; }); j[l].on('beforeContextMenu', k[m - 1]); } return function() { for ( var n = 0; n < k.length; n++) h.aG['foldertree.foldertree'][n].removeListener( 'beforeContextMenu', k[n]); }; }, addFolderContextMenuOption : function(f, g, h) { var i = b(this.id), j = 'FolderContextMenu_' + f.command; i.bD(j, { exec : function(m) { g(m.cg, m.aV); } }); f.command = j; if (!f.group) f.group = 'folder1'; i.gp(j, f); var k = i.aG['foldertree.foldertree']; for ( var l = 0; l < k.length; l++) k[l].on('beforeContextMenu', function o(m) { if (h) { var n = h(this.app.aV); if (n) m.data.bj[j] = n == -1 ? a.aY : a.aS; } else m.data.bj[j] = a.aS; }); }, disableFolderContextMenuOption : function(f, g) { var h = b(this.id), i = g ? 'FolderContextMenu_' + f : f, j = h.aG['foldertree.foldertree'], k = []; for ( var l = 0; l < j.length; l++) { var m = k.push(function o(n) { delete n.data.bj[i]; }); j[l].on('beforeContextMenu', k[m - 1]); } return function() { for ( var n = 0; n < k.length; n++) h.aG['foldertree.foldertree'][n].removeListener( 'beforeContextMenu', k[n]); }; }, getSelectedFile : function() { return b(this.id).aG['filesview.filesview'][0].tools.dH(); }, getSelectedFolder : function() { return b(this.id).aV; }, setUiColor : function(f) { return b(this.id).setUiColor(f); }, openDialog : function(f, g) { var j = this; var h = new a.dom.document(window.document).eD(), i = b(j.id).document .getWindow(); if (j.inFrame || j.inPopup || j.inIframe) a.document = b(j.id).document; return b(j.id).openDialog(f, g, h); }, openMsgDialog : function(f, g) { b(this.id).msgDialog(f, g); }, openConfirmDialog : function(f, g, h) { b(this.id).fe(f, g, h); }, openInputDialog : function(f, g, h, i) { b(this.id).hs(f, g, h, i); }, addTool : function(f) { return b(this.id).plugins.tools.addTool(f); }, addToolPanel : function(f) { return b(this.id).plugins.tools.addToolPanel(f); }, removeTool : function(f) { b(this.id).plugins.tools.removeTool(f); }, showTool : function(f) { b(this.id).plugins.tools.showTool(f); }, hideTool : function(f) { b(this.id).plugins.tools.hideTool(f); }, getResourceType : function(f) { return b(this.id).getResourceType(f); }, log : function(f) { a.log.apply(a.log, arguments); }, getLog : function() { return a.mZ(); }, emptyBasket : function() { b(this.id).execCommand('TruncateBasket'); }, replaceUploadForm : function(f, g, h) { var i = b(this.id); i.aG['formpanel.formpanel'][0].on('beforeUploadFileForm', function( j) { if (j.data.step != 2) return; j.cancel(true); var k = this.data(), l = j.data.folder; try { if (k.dc == 'upload') this.oW('requestUnloadForm', function() { this.app.cS('upload').bR(a.aS); }); else { if (this.data().dc) this.oW('requestUnloadForm'); if (!h) this.eh.removeClass('show_border'); this.oW('requestLoadForm', { html : f, command : 'upload' }); g && g(); } } catch (m) { this.oW('failedUploadFileForm', j.data); this.oW('afterUploadFileForm', j.data); throw a.ba(m); } }); return { hide : function() { i.oW('requestUnloadForm', function() { i.cS('upload').bR(a.aS); }); } }; }, resizeFormPanel : function(f) { var g = b(this.id); if (typeof f == 'undefined') { g.document.getById('panel_view').setStyle('height', ''); g.document.getById('panel_widget').setStyle('height', ''); } else { var h = Math.min(f, Math.max(90, g.document .getById('main_container').$.offsetHeight - 300)); g.document.getById('panel_view').setStyle('height', h + 'px'); g.document.getById('panel_widget').setStyle('height', h - 3 + 'px'); } g.layout.ea(true); }, refreshOpenedFolder : function() { var f = b(this.id), g = f.aG['filesview.filesview'][0].tools .currentFolder(); f.oW('requestSelectFolder', { folder : g }); }, selectFile : function(f) { var g = b(this.id); g.oW('requestSelectFile', { file : f, scrollTo : 1 }); }, closePopup : function() { if (!this.inPopup) return; b(this.id).element.getDocument().getWindow().$.close(); }, openFolder : function(f, g) { var h = b(this.id); g = g.replace(/\/$/, ''); f = f.toLowerCase(); for ( var i = 0; i < h.folders.length; i++) { var j = h.folders[i]; if (j.getPath().replace(/\/$/, '') == g && f == j.type.toLowerCase()) { h.oW('requestSelectFolder', { folder : j }); h.oW('requestShowFolderFiles', { folder : j }); return; } } }, setUiColor : function(f) { b(this.id).setUiColor(f); }, execCommand : function(f) { b(this.id).execCommand(f); } }; (function() { window.CKFinder = function(f, g) { if (f) for ( var h in f) { if (!f.hasOwnProperty(h)) continue; if (typeof f[h] == 'function' && h != 'callback') continue; this[h] = f[h]; } this.callback = g; }; CKFinder.prototype = { create : function(f) { var g = 'ckf' + Math.random().toString().substr(2, 4); document.write('<span id="' + g + '"></span>'); f = a.tools.extend(a.jd.call(this), f, true); var h = a.replace(g, f, CKFinder); this.api = h.cg; return h.cg; }, appendTo : function(f, g) { g = a.tools.extend(a.jd.call(this), g, true); var h = a.appendTo(f, g, CKFinder); this.api = h.cg; return h.cg; }, replace : function(f, g) { g = a.tools.extend(a.jd.call(this), g, true); var h = a.replace(f, g, CKFinder); this.api = h.cg; return h.cg; }, popup : function(f, g) { var o = this; f = f || '80%'; g = g || '70%'; if (typeof f == 'string' && f.length > 1 && f.substr(f.length - 1, 1) == '%') f = parseInt(window.screen.width * parseInt(f, 10) / 100, 10); if (typeof g == 'string' && g.length > 1 && g.substr(g.length - 1, 1) == '%') g = parseInt(window.screen.height * parseInt(g, 10) / 100, 10); if (f < 200) f = 200; if (g < 200) g = 200; var h = parseInt((window.screen.height - g) / 2, 10), i = parseInt( (window.screen.width - f) / 2, 10), j = 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width=' + f + ',height=' + g + ',top=' + h + ',left=' + i, k = a.env.webkit ? 'about:blank' : '', l = window.open(k, 'CKFinderpopup', j, true); if (!l) return false; o.width = o.height = '100%'; var m = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>CKFinder 2</title><style type="text/css">body, html, iframe, #ckfinder { margin: 0; padding: 0; border: 0; width: 100%; height: 100%; overflow: hidden; }</style></head><body></body></html>', n = new a.dom.document( l.document); n.$.open(); if (a.env.isCustomDomain()) n.$.domain = window.document.domain; n.$.write(m); n.$.close(); try { l.moveTo(i, h); l.resizeTo(f, g); l.focus(); return o.appendTo(n.bH()); } catch (p) { return o.appendTo(n.bH()); } return false; } }; CKFinder._ = {}; CKFinder.lang = {}; CKFinder.version = '2.1'; CKFinder.revision = '1937'; CKFinder.addPlugin = function(f, g, h) { var i = { bM : h || [] }; if (typeof g == 'function') g = { appReady : g }; for ( var j in g) { if (!g.hasOwnProperty(j)) continue; if (j != 'connectorInitialized' && j != 'uiReady') i[j] = g[j]; } i.bz = function(k) { if (g.connectorInitialized) k.on('connectorInitialized', function(l) { var m = g.connectorInitialized; if (m) m.call(m, k.cg, l.data.xml); }, null, null, 1000); if (g.uiReady) k.on('uiReady', function() { var l = g.uiReady; l.call(l, k.cg); }, null, null, 1000); if (g.appReady) k.on('appReady', function() { var l = g.appReady; l.call(l, k.cg); }, null, null, 1000); }; a.plugins.add(f, i); }; CKFinder.getPluginPath = function(f) { return a.plugins.getPath(f); }; CKFinder.addExternalPlugin = function(f, g, h) { a.plugins.tR(f, g, h); }; CKFinder.setPluginLang = function(f, g, h) { a.plugins.rX(f, g, h); }; CKFinder.dialog = { add : function(f, g) { if (typeof g == 'function') g = a.tools.override(g, function(h) { return function(i) { return h(i.cg); }; }); a.dialog.add(f, g); } }; CKFinder.tools = {}; CKFinder.env = {}; CKFinder.dom = {}; CKFinder.create = function(f, g, h, i, j) { var k; if (f !== null && typeof f === 'object') { k = new CKFinder(); for ( var l in f) k[l] = f[l]; } else { k = new CKFinder(); k.basePath = f; if (g) k.width = g; if (h) k.height = g; if (i) k.selectActionFunction = i; if (j) k.callback = j; } return k.create(); }; CKFinder.popup = function(f, g, h, i, j) { var k; if (f !== null && typeof f === 'object') { k = new CKFinder(); for ( var l in f) k[l] = f[l]; } else { k = new CKFinder(); k.basePath = f; if (i) k.selectActionFunction = i; if (j) k.callback = j; } return k.popup(g, h); }; CKFinder.setupFCKeditor = function(f, g, h, i) { var j; if (g !== null && typeof g === 'object') { j = new CKFinder(); for ( var k in g) { j[k] = g[k]; if (k == 'width') { var l = j[k] || 800; if (typeof l == 'string' && l.length > 1 && l.substr(l.length - 1, 1) == '%') l = parseInt(window.screen.width * parseInt(l, 10) / 100, 10); f.Config.LinkBrowserWindowWidth = l; f.Config.ImageBrowserWindowWidth = l; f.Config.FlashBrowserWindowWidth = l; } else if (k == 'height') { var m = j[k] || 600; if (typeof m == 'string' && m.length > 1 && m.substr(m.length - 1, 1) == '%') m = parseInt(window.screen.height * parseInt(m, 10) / 100, 10); f.Config.LinkBrowserWindowHeight = m; f.Config.ImageBrowserWindowHeight = m; f.Config.FlashBrowserWindowHeight = m; } } } else { j = new CKFinder(); j.basePath = g; } var n = j.basePath; if (n.substr(0, 1) != '/' && n.indexOf('://') == -1) n = document.location.pathname.substring(0, document.location.pathname.lastIndexOf('/') + 1) + n; n = a.lj.call(j, n); var o = n.indexOf('?') !== -1 ? '&amp;' : '?'; f.Config.LinkBrowserURL = n; f.Config.ImageBrowserURL = n + o + 'type=' + (h || 'Images'); f.Config.FlashBrowserURL = n + o + 'type=' + (i || 'Flash'); var p = n.substring(0, 1 + n.lastIndexOf('/')); f.Config.LinkUploadURL = p + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=Files'; f.Config.ImageUploadURL = p + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (h || 'Images'); f.Config.FlashUploadURL = p + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (i || 'Flash'); }; CKFinder.setupCKEditor = function(f, g, h, i) { if (f === null) { for ( var j in CKEDITOR.instances) CKFinder.setupCKEditor(CKEDITOR.instances[j], g, h, i); CKEDITOR.on('instanceCreated', function(r) { CKFinder.setupCKEditor(r.editor, g, h, i); }); return; } var k; if (g !== null && typeof g === 'object') { k = new CKFinder(); for ( var l in g) { k[l] = g[l]; if (l == 'width') { var m = k[l] || 800; if (typeof m == 'string' && m.length > 1 && m.substr(m.length - 1, 1) == '%') m = parseInt(window.screen.width * parseInt(m, 10) / 100, 10); f.config.filebrowserWindowWidth = m; } else if (l == 'height') { var n = k[l] || 600; if (typeof n == 'string' && n.length > 1 && n.substr(n.length - 1, 1) == '%') n = parseInt(window.screen.height * parseInt(n, 10) / 100, 10); f.config.filebrowserWindowHeight = m; } } } else { k = new CKFinder(); k.basePath = g; } var o = k.basePath; if (o.substr(0, 1) != '/' && o.indexOf('://') == -1) o = document.location.pathname.substring(0, document.location.pathname.lastIndexOf('/') + 1) + o; o = a.lj.call(k, o); var p = o.indexOf('?') !== -1 ? '&amp;' : '?'; f.config.filebrowserBrowseUrl = o; f.config.filebrowserImageBrowseUrl = o + p + 'type=' + (h || 'Images'); f.config.filebrowserFlashBrowseUrl = o + p + 'type=' + (i || 'Flash'); var q = o.substring(0, 1 + o.lastIndexOf('/')); f.config.filebrowserUploadUrl = q + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=Files'; f.config.filebrowserImageUploadUrl = q + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (h || 'Images'); f.config.filebrowserFlashUploadUrl = q + 'core/connector/' + CKFinder.config.connectorLanguage + '/connector.' + CKFinder.config.connectorLanguage + '?command=QuickUpload&type=' + (i || 'Flash'); }; })(); if (!a.event) { a.event = function() { }; a.event.du = function(f, g) { var h = a.event.prototype; for ( var i in h) { if (f[i] == undefined) f[i] = h[i]; } }; a.event.prototype = (function() { var f = function(h) { var i = h.kk && h.kk() || h._ || (h._ = {}); return i.cC || (i.cC = {}); }, g = function(h) { this.name = h; this.dF = []; }; g.prototype = { mi : function(h) { for ( var i = 0, j = this.dF; i < j.length; i++) { if (j[i].gg == h) return i; } return -1; } }; return { on : function(h, i, j, k, l) { var m = f(this), n = m[h] || (m[h] = new g(h)); if (n.mi(i) < 0) { var o = n.dF; if (!j) j = this; if (isNaN(l)) l = 10; var p = this, q = function(s, t, u, v) { var w = { name : h, jN : this, application : s, data : t, jO : k, stop : u, cancel : v, removeListener : function() { p.removeListener(h, i); } }; i.call(j, w); return w.data; }; q.gg = i; q.nT = l; for ( var r = o.length - 1; r >= 0; r--) { if (o[r].nT <= l) { o.splice(r + 1, 0, q); return; } } o.unshift(q); } }, oW : (function() { var h = false, i = function() { h = true; }, j = false, k = function(l) { j = l ? 2 : true; }; return function w(l, m, n, o) { if (typeof m == 'function') { o = m; m = null; } else if (typeof n == 'function') { o = n; n = null; } if (l != 'mousemove') a.log('[EVENT] ' + l, m, o); var p = f(this)[l], q = h, r = j; h = j = false; if (p) { var s = p.dF; if (s.length) { s = s.slice(0); for ( var t = 0; t < s.length; t++) { var u = s[t].call(this, n, m, i, k); if (typeof u != 'undefined') m = u; if (h || j && j != 2) break; } } } var v = j || (typeof m == 'undefined' ? false : !m || typeof m.result == 'undefined' ? m : m.result); if (typeof o === 'function' && j != 2) v = o.call(this, j, m) || v; h = q; j = r; return v; }; })(), cr : function(h, i, j) { var k = this.oW(h, i, j); delete f(this)[h]; return k; }, removeListener : function(h, i) { var j = f(this)[h]; if (j) { var k = j.mi(i); if (k >= 0) j.dF.splice(k, 1); } }, mF : function() { var h = f(this); for ( var i = 0; i < h.length; i++) h[i].dF = []; }, rC : function(h) { var i = f(this)[h]; return i && i.dF.length > 0; } }; })(); } if (!a.application) { a.kZ = 0; a.fc = 1; a.qE = 2; a.application = function(f, g, h, i) { var j = this; j._ = { kw : f, element : g }; j.ff = h || a.kZ; a.event.call(j); j.iI(i); }; a.application.replace = function(f, g, h) { var i = f; if (typeof i != 'object') { i = document.getElementById(f); if (!i) { var j = 0, k = document.getElementsByName(f); while ((i = k[j++]) && i.tagName.toLowerCase() != 'textarea') { } } if (!i) throw '[CKFINDER.application.replace] The element with id or name "' + f + '" was not found.'; } return new a.application(g, i, a.fc, h); }; a.application.appendTo = function(f, g, h) { if (typeof f != 'object') { f = document.getElementById(f); if (!f) throw '[CKFINDER.application.appendTo] The element with id "' + f + '" was not found.'; } return new a.application(g, f, a.qE, h); }; a.application.prototype = { iI : function() { var f = a.application.eb || (a.application.eb = []); f.push(this); }, oW : function(f, g, h) { return a.event.prototype.oW.call(this, f, g, this, h); }, cr : function(f, g, h) { return a.event.prototype.cr.call(this, f, g, this, h); } }; a.event.du(a.application.prototype, true); } if (!a.env) { a.env = (function() { var f = navigator.userAgent.toLowerCase(), g = window.opera, h = { ie : /* @cc_on!@ */false, opera : !!g && g.version, webkit : f.indexOf(' applewebkit/') > -1, air : f.indexOf(' adobeair/') > -1, mac : f.indexOf('macintosh') > -1, quirks : document.compatMode == 'BackCompat', isCustomDomain : function() { return this.ie && document.domain != window.location.hostname; } }; h.gecko = navigator.product == 'Gecko' && !h.webkit && !h.opera; var i = 0; if (h.ie) { i = parseFloat(f.match(/msie (\d+)/)[1]); h.ie8 = !!document.documentMode; h.ie8Compat = document.documentMode == 8; h.ie7Compat = i == 7 && !document.documentMode || document.documentMode == 7; h.ie6Compat = i < 7 || h.quirks; } if (h.gecko) { var j = f.match(/rv:([\d\.]+)/); if (j) { j = j[1].split('.'); i = j[0] * 10000 + (j[1] || 0) * 100 + +(j[2] || 0); } h.isMobile = f.indexOf('fennec') > -1; } if (h.opera) { i = parseFloat(g.version()); h.isMobile = f.indexOf('opera mobi') > -1; } if (h.air) i = parseFloat(f.match(/ adobeair\/(\d+)/)[1]); if (h.webkit) { i = parseFloat(f.match(/ applewebkit\/(\d+)/)[1]); h.isMobile = f.indexOf('mobile') > -1; } h.version = i; h.isCompatible = h.ie && i >= 6 || h.gecko && i >= 10801 || h.opera && i >= 9.5 || h.air && i >= 1 || h.webkit && i >= 522 || false; h.cssClass = 'browser_' + (h.ie ? 'ie' : h.gecko ? 'gecko' : h.opera ? 'opera' : h.air ? 'air' : h.webkit ? 'webkit' : 'unknown'); if (h.quirks) h.cssClass += ' browser_quirks'; if (h.ie) { h.cssClass += ' browser_ie' + (h.version < 7 ? '6' : h.version >= 8 ? '8' : '7'); if (h.quirks) h.cssClass += ' browser_iequirks'; } if (h.gecko && i < 10900) h.cssClass += ' browser_gecko18'; return h; })(); CKFinder.env = a.env; } var f = a.env; var g = f.ie; if (a.status == 'unloaded') (function() { a.event.du(a); a.dO = function() { if (a.status != 'basic_ready') { a.dO.qr = true; return; } delete a.dO; var i = document.createElement('script'); i.type = 'text/javascript'; i.src = a.basePath + 'ckfinder.js'; document.getElementsByTagName('head')[0].appendChild(i); }; a.mS = 0; a.uQ = 'ckfinder'; a.uM = true; var h = function(i, j, k, l) { if (f.isCompatible) { if (a.dO) a.dO(); var m = k(i, j, l); a.add(m); return m; } return null; }; a.replace = function(i, j, k) { return h(i, j, a.application.replace, k); }; a.appendTo = function(i, j, k) { return h(i, j, a.application.appendTo, k); }; a.add = function(i) { var j = this._.io || (this._.io = []); j.push(i); }; a.uL = function() { var i = document.getElementsByTagName('textarea'); for ( var j = 0; j < i.length; j++) { var k = null, l = i[j], m = l.name; if (!l.name && !l.id) continue; if (typeof arguments[0] == 'string') { var n = new RegExp('(?:^| )' + arguments[0] + '(?:$| )'); if (!n.test(l.className)) continue; } else if (typeof arguments[0] == 'function') { k = {}; if (arguments[0](l, k) === false) continue; } this.replace(l, k); } }; (function() { var i = function() { var j = a.dO, k = a.mS; a.status = 'basic_ready'; if (j && j.qr) j(); else if (k) setTimeout(function() { if (a.dO) a.dO(); }, k * 1000); }; if (window.addEventListener) window.addEventListener('load', i, false); else if (window.attachEvent) window.attachEvent('onload', i); })(); a.status = 'basic_loaded'; })(); a.dom = {}; CKFinder.dom = a.dom; var h = a.dom; a.ajax = (function() { var i = function() { if (!g || location.protocol != 'file:') try { return new XMLHttpRequest(); } catch (n) { } try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (o) { } try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (p) { } return null; }, j = function(n) { return n.readyState == 4 && (n.status >= 200 && n.status < 300 || n.status == 304 || n.status === 0 || n.status == 1223); }, k = function(n) { if (j(n)) return n.responseText; return null; }, l = function(n) { if (j(n)) { var o = n.responseXML, p = new a.xml(o && o.firstChild && o.documentElement && o.documentElement.nodeName != 'parsererror' ? o : n.responseText.replace(/^[^<]+/, '').replace( /[^>]+$/, '')); if (p && p.mq && p.mq.documentElement && p.mq.documentElement.nodeName != 'parsererror' && p.mq.documentElement.nodeName != 'html' && p.mq.documentElement.nodeName != 'br') return p; } var q = a.eq || a.jt, r = n.responseText, s = q.lang.ErrorMsg[!r ? 'XmlEmpty' : 'XmlError'] + '<br>'; if (p && p.mq) if (p.mq.parseError && p.mq.parseError.reason) s += p.mq.parseError.reason; else if (p.mq.documentElement && p.mq.documentElement.nodeName == 'parsererror') s += p.mq.documentElement.textContent; if (!r) q.msgDialog(q.lang.SysErrorDlgTitle, s); else { if (/text\/plain/.test(n.getResponseHeader('Content-Type')) || /<Connector\s*/.test(r)) { r = a.tools.htmlEncode(r); r = r.replace(/\n/g, '<br>'); r = '<div style="width:600px; overflow:scroll"><font>' + r + '</font></div>'; } q.msgDialog(q.lang.SysErrorDlgTitle, s + '<br>' + q.lang.ErrorMsg.XmlRawResponse.replace('%s', '<br><br>' + r)); } return {}; }, m = function(n, o, p, q) { var r = !!o; a.log('[AJAX] POST ' + n); var s = i(); if (!s) return null; if (!q) s.open('GET', n, r); else s.open('POST', n, r); if (r) s.onreadystatechange = function() { if (s.readyState == 4) { o(p(s)); s = null; } }; if (q) { s.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); s.send(q); } else s.send(null); return r ? '' : p(s); }; return { load : function(n, o, p) { return m(n, o, k, p); }, loadXml : function(n, o, p) { return m(n, o, l, p); } }; })(); CKFinder.ajax = a.ajax; (function() { var i = []; a.tools = { arrayCompare : function(j, k) { if (!j && !k) return true; if (!j || !k || j.length != k.length) return false; for ( var l = 0; l < j.length; l++) { if (j[l] != k[l]) return false; } return true; }, clone : function(j) { var k; if (j && j instanceof Array) { k = []; for ( var l = 0; l < j.length; l++) k[l] = this.clone(j[l]); return k; } if (j === null || typeof j != 'object' || j instanceof String || j instanceof Number || j instanceof Boolean || j instanceof Date) return j; k = new j.constructor(); for ( var m in j) { var n = j[m]; k[m] = this.clone(n); } return k; }, capitalize : function(j) { return j.charAt(0).toUpperCase() + j.substring(1).toLowerCase(); }, extend : function(j) { var k = arguments.length, l, m; if (typeof (l = arguments[k - 1]) == 'boolean') k--; else if (typeof (l = arguments[k - 2]) == 'boolean') { m = arguments[k - 1]; k -= 2; } for ( var n = 1; n < k; n++) { var o = arguments[n]; for ( var p in o) { if (l === true || j[p] == undefined) if (!m || p in m) j[p] = o[p]; } } return j; }, prototypedCopy : function(j) { var k = function() { }; k.prototype = j; return new k(); }, isArray : function(j) { return !!j && j instanceof Array; }, cssStyleToDomStyle : (function() { var j = document.createElement('div').style, k = typeof j.cssFloat != 'undefined' ? 'cssFloat' : typeof j.styleFloat != 'undefined' ? 'styleFloat' : 'float'; return function(l) { if (l == 'float') return k; else return l.replace(/-./g, function(m) { return m.substr(1).toUpperCase(); }); }; })(), htmlEncode : function(j) { var k = function(o) { var p = new h.element('span'); p.setText(o); return p.getHtml(); }, l = k('\n').toLowerCase() == '<br>' ? function(o) { return k(o).replace(/<br>/gi, '\n'); } : k, m = k('>') == '>' ? function(o) { return l(o).replace(/>/g, '&gt;'); } : l, n = k(' ') == '&nbsp; ' ? function(o) { return m(o).replace(/&nbsp;/g, ' '); } : m; this.htmlEncode = n; return this.htmlEncode(j); }, getNextNumber : (function() { var j = 0; return function() { return ++j; }; })(), override : function(j, k) { return k(j); }, setTimeout : function(j, k, l, m, n) { if (!n) n = window; if (!l) l = n; return n.setTimeout(function() { if (m) j.apply(l, [].concat(m)); else j.apply(l); }, k || 0); }, trim : (function() { var j = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g; return function(k) { return k ? k.replace(j, '') : null; }; })(), ltrim : (function() { var j = /^[ \t\n\r]+/g; return function(k) { return k ? k.replace(j, '') : null; }; })(), rtrim : (function() { var j = /[ \t\n\r]+$/g; return function(k) { return k ? k.replace(j, '') : null; }; })(), indexOf : Array.prototype.indexOf ? function(j, k) { return j.indexOf(k); } : function(j, k) { for ( var l = 0, m = j.length; l < m; l++) { if (j[l] === k) return l; } return -1; }, bind : function(j, k) { return function() { return j.apply(k, arguments); }; }, createClass : function(j) { var k = j.$, l = j.base, m = j.vd || j._, n = j.ej, o = j.statics; if (m) { var p = k; k = function() { var t = this; var q = t._ || (t._ = {}); for ( var r in m) { var s = m[r]; q[r] = typeof s == 'function' ? a.tools.bind(s, t) : s; } p.apply(t, arguments); }; } if (l) { k.prototype = this.prototypedCopy(l.prototype); k.prototype['constructor'] = k; k.prototype.base = function() { this.base = l.prototype.base; l.apply(this, arguments); this.base = arguments.callee; }; } if (n) this.extend(k.prototype, n, true); if (o) this.extend(k, o, true); return k; }, addFunction : function(j, k) { return i.push(function() { j.apply(k || this, arguments); }) - 1; }, removeFunction : function(j) { i[j] = null; }, callFunction : function(j) { var k = i[j]; return k .apply(window, Array.prototype.slice.call(arguments, 1)); }, cssLength : (function() { var j = /^\d+(?:\.\d+)?$/; return function(k) { return k + (j.test(k) ? 'px' : ''); }; })(), repeat : function(j, k) { return new Array(k + 1).join(j); }, deepCopy : function(j) { var k = {}; if (typeof j == 'object') { if (typeof j.length != 'undefined') k = []; for ( var l in j) { if (j[l] === null) k[l] = j[l]; else if (typeof j[l] == 'object') k[l] = a.tools.deepCopy(j[l]); else if (typeof j[l] == 'string') k[l] = j[l]; else if (typeof j[l] == 'number') k[l] = j[l]; else if (typeof j[l] == 'boolean') j[l] === true ? k[l] = true : k[l] = false; } } return k; }, getUrlParam : function(j, k) { var l = new RegExp('(?:[?&]|&amp;)' + j + '=([^&]+)', 'i'), m = (k || window).location.search .match(l); return m && m.length > 1 ? m[1] : null; }, htmlEncode : function(j) { if (!j) return ''; j = typeof j != 'string' ? j.toString() : j; j = j.replace(/&/g, '&amp;'); j = j.replace(/</g, '&lt;'); j = j.replace(/>/g, '&gt;'); return j; }, setCookie : function(j, k, l) { document.cookie = j + '=' + k + (!l ? '; expires=Thu, 6 Oct 2016 01:00:00 UTC; path=/' : ''); }, getCookie : function(j) { var k = document.cookie.match(new RegExp( '(^|\\s|;)' + j + '=([^;]*)')); return k && k.length > 0 ? k[2] : ''; }, mH : function(j) { if (g) { j.$.onfocusin = function() { j.addClass('focus_inside'); }; j.$.onfocusout = function() { j.removeClass('focus_inside'); }; } else { j.$.addEventListener('focus', function() { j.addClass('focus_inside'); }, true); j.$.addEventListener('blur', function() { j.removeClass('focus_inside'); }, true); } } }; CKFinder._.callFunction = a.tools.callFunction; CKFinder.tools = a.tools; })(); var i = a.tools; h.event = function(j) { this.$ = j; }; h.event.prototype = { oV : function() { return this.$.keyCode || this.$.which; }, db : function() { var k = this; var j = k.oV(); if (k.$.ctrlKey || k.$.metaKey) j += a.bP; if (k.$.shiftKey) j += a.dy; if (k.$.altKey) j += a.eJ; return j; }, preventDefault : function(j) { var k = this.$; if (k.preventDefault) k.preventDefault(); else k.returnValue = false; if (j) this.stopPropagation(); }, stopPropagation : function() { var j = this.$; if (j.stopPropagation) j.stopPropagation(); else j.cancelBubble = true; }, bK : function() { var j = this.$.target || this.$.srcElement; return j ? new h.bi(j) : null; } }; a.bP = 1000; a.dy = 2000; a.eJ = 4000; h.dE = function(j) { if (j) this.$ = j; }; h.dE.prototype = (function() { var j = function(k, l) { return function(m) { if (typeof a != 'undefined') k.oW(l, new h.event(m)); }; }; return { kk : function() { var k; if (!(k = this.dw('_'))) this.fL('_', k = {}); return k; }, on : function(k) { var n = this; var l = n.dw('_cke_nativeListeners'); if (!l) { l = {}; n.fL('_cke_nativeListeners', l); } if (!l[k]) { var m = l[k] = j(n, k); if (n.$.addEventListener && !g) n.$.addEventListener(k, m, !!a.event.jP); else if (n.$.attachEvent) n.$.attachEvent('on' + k, m); } return a.event.prototype.on.apply(n, arguments); }, removeListener : function(k) { var n = this; a.event.prototype.removeListener.apply(n, arguments); if (!n.rC(k)) { var l = n.dw('_cke_nativeListeners'), m = l && l[k]; if (m) { if (n.$.removeEventListener) n.$.removeEventListener(k, m, false); else if (n.$.detachEvent) n.$.detachEvent('on' + k, m); delete l[k]; } } } }; })(); (function(j) { var k = {}; j.equals = function(l) { return l && l.$ === this.$; }; j.fL = function(l, m) { var n = this.iY(), o = k[n] || (k[n] = {}); o[l] = m; return this; }; j.dw = function(l) { var m = this.$.dj, n = m && k[m]; return n && n[l]; }; j.jF = function(l) { var m = this.$.dj, n = m && k[m], o = n && n[l]; if (typeof o != 'undefined') delete n[l]; return o || null; }; j.iY = function() { return this.$.dj || (this.$.dj = i.getNextNumber()); }; a.event.du(j); })(h.dE.prototype); h.window = function(j) { h.dE.call(this, j); }; h.window.prototype = new h.dE(); i.extend(h.window.prototype, { focus : function() { if (f.webkit && this.$.parent) this.$.parent.focus(); this.$.focus(); }, eR : function() { var j = this.$.document, k = j.compatMode == 'CSS1Compat'; return { width : (k ? j.documentElement.clientWidth : j.body.clientWidth) || 0, height : (k ? j.documentElement.clientHeight : j.body.clientHeight) || 0 }; }, hV : function() { var j = this.$; if ('pageXOffset' in j) return { x : j.pageXOffset || 0, y : j.pageYOffset || 0 }; else { var k = j.document; return { x : k.documentElement.scrollLeft || k.body.scrollLeft || 0, y : k.documentElement.scrollTop || k.body.scrollTop || 0 }; } } }); h.document = function(j) { h.dE.call(this, j); }; var j = h.document; j.prototype = new h.dE(); i.extend(j.prototype, { pb : function(k) { if (this.$.createStyleSheet) this.$.createStyleSheet(k); else { var l = new h.element('link'); l.setAttributes( { rel : 'stylesheet', type : 'text/css', href : k }); this.eD().append(l); } }, createElement : function(k, l) { var m = new h.element(k, this); if (l) { if (l.attributes) m.setAttributes(l.attributes); if (l.gS) m.setStyles(l.gS); } return m; }, jT : function(k) { return new h.text(k, this); }, focus : function() { this.getWindow().focus(); }, getById : function(k) { var l = this.$.getElementById(k); return l ? new h.element(l) : null; }, vu : function(k, l) { var m = this.$.documentElement; for ( var n = 0; m && n < k.length; n++) { var o = k[n]; if (!l) { m = m.childNodes[o]; continue; } var p = -1; for ( var q = 0; q < m.childNodes.length; q++) { var r = m.childNodes[q]; if (l === true && r.nodeType == 3 && r.previousSibling && r.previousSibling.nodeType == 3) continue; p++; if (p == o) { m = r; break; } } } return m ? new h.bi(m) : null; }, eG : function(k, l) { if (!g && l) k = l + ':' + k; return new h.iT(this.$.getElementsByTagName(k)); }, eD : function() { var k = this.$.getElementsByTagName('head')[0]; k = new h.element(k); return (this.eD = function() { return k; })(); }, bH : function() { var k = new h.element(this.$.body); return (this.bH = function() { return k; })(); }, gT : function() { var k = new h.element(this.$.documentElement); return (this.gT = function() { return k; })(); }, getWindow : function() { var k = new h.window(this.$.parentWindow || this.$.defaultView); return (this.getWindow = function() { return k; })(); } }); h.bi = function(k) { if (k) { switch (k.nodeType) { case a.cv: return new h.element(k); case a.fl: return new h.text(k); } h.dE.call(this, k); } return this; }; h.bi.prototype = new h.dE(); a.cv = 1; a.fl = 3; a.va = 8; a.om = 11; a.oh = 0; a.op = 1; a.gW = 2; a.gX = 4; a.mo = 8; a.lF = 16; i .extend( h.bi.prototype, { appendTo : function(k, l) { k.append(this, l); return k; }, clone : function(k, l) { var m = this.$.cloneNode(k); if (!l) { var n = function(o) { if (o.nodeType != a.cv) return; o.removeAttribute('id', false); o.removeAttribute('dj', false); var p = o.childNodes; for ( var q = 0; q < p.length; q++) n(p[q]); }; n(m); } return new h.bi(m); }, gE : function() { return !!this.$.previousSibling; }, ge : function() { return !!this.$.nextSibling; }, kB : function(k) { k.$.parentNode .insertBefore(this.$, k.$.nextSibling); return k; }, insertBefore : function(k) { k.$.parentNode.insertBefore(this.$, k.$); return k; }, vP : function(k) { this.$.parentNode.insertBefore(k.$, this.$); return k; }, lU : function(k) { var l = [], m = this.getDocument().$.documentElement, n = this.$; while (n && n != m) { var o = n.parentNode, p = -1; for ( var q = 0; q < o.childNodes.length; q++) { var r = o.childNodes[q]; if (k && r.nodeType == 3 && r.previousSibling && r.previousSibling.nodeType == 3) continue; p++; if (r == n) break; } l.unshift(p); n = n.parentNode; } return l; }, getDocument : function() { var k = new j(this.$.ownerDocument || this.$.parentNode.ownerDocument); return (this.getDocument = function() { return k; })(); }, vA : function() { var k = this.$, l = k.parentNode && k.parentNode.firstChild, m = -1; while (l) { m++; if (l == k) return m; l = l.nextSibling; } return -1; }, hL : function(k, l, m) { if (m && !m.call) { var n = m; m = function(q) { return !q.equals(n); }; } var o = !k && this.getFirst && this.getFirst(), p; if (!o) { if (this.type == a.cv && m && m(this, true) === false) return null; o = this.dG(); } while (!o && (p = (p || this).getParent())) { if (m && m(p, true) === false) return null; o = p.dG(); } if (!o) return null; if (m && m(o) === false) return null; if (l && l != o.type) return o.hL(false, l, m); return o; }, hZ : function(k, l, m) { if (m && !m.call) { var n = m; m = function(q) { return !q.equals(n); }; } var o = !k && this.dB && this.dB(), p; if (!o) { if (this.type == a.cv && m && m(this, true) === false) return null; o = this.cf(); } while (!o && (p = (p || this).getParent())) { if (m && m(p, true) === false) return null; o = p.cf(); } if (!o) return null; if (m && m(o) === false) return null; if (l && o.type != l) return o.hZ(false, l, m); return o; }, cf : function(k) { var l = this.$, m; do { l = l.previousSibling; m = l && new h.bi(l); } while (m && k && !k(m)); return m; }, vs : function() { return this.cf(function(k) { return k.$.nodeType == 1; }); }, dG : function(k) { var l = this.$, m; do { l = l.nextSibling; m = l && new h.bi(l); } while (m && k && !k(m)); return m; }, vk : function() { return this.dG(function(k) { return k.$.nodeType == 1; }); }, getParent : function() { var k = this.$.parentNode; return k && k.nodeType == 1 ? new h.bi(k) : null; }, vn : function(k) { var l = this, m = []; do m[k ? 'push' : 'unshift'](l); while (l = l.getParent()); return m; }, vv : function(k) { var m = this; if (k.equals(m)) return m; if (k.contains && k.contains(m)) return k; var l = m.contains ? m : m.getParent(); do { if (l.contains(k)) return l; } while (l = l.getParent()); return null; }, gz : function(k) { var l = this.$, m = k.$; if (l.compareDocumentPosition) return l.compareDocumentPosition(m); if (l == m) return a.oh; if (this.type == a.cv && k.type == a.cv) { if (l.contains) { if (l.contains(m)) return a.lF + a.gX; if (m.contains(l)) return a.mo + a.gW; } if ('sourceIndex' in l) return l.sourceIndex < 0 || m.sourceIndex < 0 ? a.op : l.sourceIndex < m.sourceIndex ? a.gX : a.gW; } var n = this.lU(), o = k.lU(), p = Math.min( n.length, o.length); for ( var q = 0; q <= p - 1; q++) { if (n[q] != o[q]) { if (q < p) return n[q] < o[q] ? a.gX : a.gW; break; } } return n.length < o.length ? a.lF + a.gX : a.mo + a.gW; }, vw : function(k, l) { var m = this.$; if (!l) m = m.parentNode; while (m) { if (m.nodeName && m.nodeName.toLowerCase() == k) return new h.bi(m); m = m.parentNode; } return null; }, vX : function(k, l) { var m = this.$; if (!l) m = m.parentNode; while (m) { if (m.nodeName && m.nodeName.toLowerCase() == k) return true; m = m.parentNode; } return false; }, move : function(k, l) { k.append(this.remove(), l); }, remove : function(k) { var l = this.$, m = l.parentNode; if (m) { if (k) for ( var n; n = l.firstChild;) m.insertBefore(l.removeChild(n), l); m.removeChild(l); } return this; }, replace : function(k) { this.insertBefore(k); k.remove(); }, trim : function() { this.ltrim(); this.rtrim(); }, ltrim : function() { var n = this; var k; while (n.getFirst && (k = n.getFirst())) { if (k.type == a.fl) { var l = i.ltrim(k.getText()), m = k.hJ(); if (!l) { k.remove(); continue; } else if (l.length < m) { k.split(m - l.length); n.$.removeChild(n.$.firstChild); } } break; } }, rtrim : function() { var n = this; var k; while (n.dB && (k = n.dB())) { if (k.type == a.fl) { var l = i.rtrim(k.getText()), m = k.hJ(); if (!l) { k.remove(); continue; } else if (l.length < m) { k.split(l.length); n.$.lastChild.parentNode .removeChild(n.$.lastChild); } } break; } if (!g && !f.opera) { k = n.$.lastChild; if (k && k.type == 1 && k.nodeName.toLowerCase() == 'br') k.parentNode.removeChild(k); } } }); h.iT = function(k) { this.$ = k; }; h.iT.prototype = { count : function() { return this.$.length; }, getItem : function(k) { var l = this.$[k]; return l ? new h.bi(l) : null; } }; h.element = function(k, l) { if (typeof k == 'string') k = (l ? l.$ : document).createElement(k); h.dE.call(this, k); }; var k = h.element; k.eB = function(l) { return l && (l.$ ? l : new k(l)); }; k.prototype = new h.bi(); k.kE = function(l, m) { var n = new k('div', m); n.setHtml(l); return n.getFirst().remove(); }; k.rS = function(l, m, n, o) { var p = m.dw('list_marker_id') || m.fL('list_marker_id', i.getNextNumber()).dw( 'list_marker_id'), q = m.dw('list_marker_names') || m.fL('list_marker_names', {}).dw('list_marker_names'); l[p] = m; q[n] = 1; return m.fL(n, o); }; k.sM = function(l) { for ( var m in l) k.qZ(l, l[m], true); }; k.qZ = function(l, m, n) { var o = m.dw('list_marker_names'), p = m.dw('list_marker_id'); for ( var q in o) m.jF(q); m.jF('list_marker_names'); if (n) { m.jF('list_marker_id'); delete l[p]; } }; i .extend( k.prototype, { type : a.cv, addClass : function(l) { var m = this.$.className; if (m) { var n = new RegExp( '(?:^|\\s)' + l + '(?:\\s|$)', ''); if (!n.test(m)) m += ' ' + l; } this.$.className = m || l; }, removeClass : function(l) { var m = this.getAttribute('class'); if (m) { var n = new RegExp( '(?:^|\\s+)' + l + '(?=\\s|$)', 'i'); if (n.test(m)) { m = m.replace(n, '').replace(/^\s+/, ''); if (m) this.setAttribute('class', m); else this.removeAttribute('class'); } } }, hasClass : function(l) { var m = new RegExp('(?:^|\\s+)' + l + '(?=\\s|$)', ''); return m.test(this.getAttribute('class')); }, append : function(l, m) { var n = this; if (typeof l == 'string') l = n.getDocument().createElement(l); if (m) n.$.insertBefore(l.$, n.$.firstChild); else n.$.appendChild(l.$); a.log('[DOM] DOM flush into ' + n.getName()); return l; }, appendHtml : function(l) { var n = this; if (!n.$.childNodes.length) n.setHtml(l); else { var m = new k('div', n.getDocument()); m.setHtml(l); m.jg(n); } }, appendText : function(l) { if (this.$.text != undefined) this.$.text += l; else this.append(new h.text(l)); }, pd : function() { var m = this; var l = m.dB(); while (l && l.type == a.fl && !i.rtrim(l.getText())) l = l.cf(); if (!l || !l.is || !l.is('br')) m.append(f.opera ? m.getDocument().jT('') : m .getDocument().createElement('br')); }, tV : function(l) { var o = this; var m = new h.mk(o.getDocument()); m.setStartAfter(o); m.setEndAfter(l); var n = m.extractContents(); m.insertNode(o.remove()); n.kA(o); }, contains : g || f.webkit ? function(l) { var m = this.$; return l.type != a.cv ? m.contains(l.getParent().$) : m != l.$ && m.contains(l.$); } : function(l) { return !!(this.$ .compareDocumentPosition(l.$) & 16); }, focus : function() { try { this.$.focus(); } catch (l) { } }, getHtml : function() { return this.$.innerHTML; }, vi : function() { var m = this; if (m.$.outerHTML) return m.$.outerHTML.replace(/<\?[^>]*>/, ''); var l = m.$.ownerDocument.createElement('div'); l.appendChild(m.$.cloneNode(true)); return l.innerHTML; }, setHtml : function(l) { a.log('[DOM] DOM flush into ' + this.getName()); return this.$.innerHTML = l; }, setText : function(l) { k.prototype.setText = this.$.innerText != undefined ? function( m) { a.log('[DOM] Text flush'); return this.$.innerText = m; } : function(m) { a.log('[DOM] Text flush'); return this.$.textContent = m; }; return this.setText(l); }, getAttribute : (function() { var l = function(m) { return this.$.getAttribute(m, 2); }; if (g && (f.ie7Compat || f.ie6Compat)) return function(m) { var o = this; switch (m) { case 'class': m = 'className'; break; case 'tabindex': var n = l.call(o, m); if (n !== 0 && o.$.tabIndex === 0) n = null; return n; break; case 'checked': return o.$.checked; break; case 'style': return o.$.style.cssText; } return l.call(o, m); }; else return l; })(), getChildren : function() { return new h.iT(this.$.childNodes); }, getComputedStyle : g ? function(l) { return this.$.currentStyle[i.cssStyleToDomStyle(l)]; } : function(l) { return this.getWindow().$.getComputedStyle( this.$, '').getPropertyValue(l); }, pf : function() { var l = a.ga[this.getName()]; this.pf = function() { return l; }; return l; }, eG : j.prototype.eG, vp : g ? function() { var l = this.$.tabIndex; if (l === 0 && !a.ga.ug[this.getName()] && parseInt(this.getAttribute('tabindex'), 10) !== 0) l = -1; return l; } : f.webkit ? function() { var l = this.$.tabIndex; if (l == undefined) { l = parseInt(this .getAttribute('tabindex'), 10); if (isNaN(l)) l = -1; } return l; } : function() { return this.$.tabIndex; }, getText : function() { return this.$.textContent || this.$.innerText || ''; }, getWindow : function() { return this.getDocument().getWindow(); }, dS : function() { return this.$.id || null; }, data : function(l, m) { l = 'data-' + l; if (m === undefined) return this.getAttribute(l); else if (m === false) this.removeAttribute(l); else this.setAttribute(l, m); return null; }, vm : function() { return this.$.name || null; }, getName : function() { var l = this.$.nodeName.toLowerCase(); if (g) { var m = this.$.scopeName; if (m != 'HTML') l = m.toLowerCase() + ':' + l; } return (this.getName = function() { return l; })(); }, getValue : function() { return this.$.value; }, getFirst : function() { var l = this.$.firstChild; return l ? new h.bi(l) : null; }, dB : function(l) { var m = this.$.lastChild, n = m && new h.bi(m); if (n && l && !l(n)) n = n.cf(l); return n; }, rd : function(l) { return this.$.style[i.cssStyleToDomStyle(l)]; }, is : function() { var l = this.getName(); for ( var m = 0; m < arguments.length; m++) { if (arguments[m] == l) return true; } return false; }, vL : function() { var l = this.getName(), m = !a.ga.uj[l] && (a.ga[l] || a.ga.span); return m && m['#']; }, isIdentical : function(l) { if (this.getName() != l.getName()) return false; var m = this.$.attributes, n = l.$.attributes, o = m.length, p = n.length; if (!g && o != p) return false; for ( var q = 0; q < o; q++) { var r = m[q]; if ((!g || r.specified && r.nodeName != 'dj') && r.nodeValue != l .getAttribute(r.nodeName)) return false; } if (g) for (q = 0; q < p; q++) { r = n[q]; if ((!g || r.specified && r.nodeName != 'dj') && r.nodeValue != m .getAttribute(r.nodeName)) return false; } return true; }, isVisible : function() { return this.$.offsetWidth && this.$.style.visibility != 'hidden'; }, hasAttributes : g && (f.ie7Compat || f.ie6Compat) ? function() { var l = this.$.attributes; for ( var m = 0; m < l.length; m++) { var n = l[m]; switch (n.nodeName) { case 'class': if (this.getAttribute('class')) return true; case 'dj': continue; default: if (n.specified) return true; } } return false; } : function() { var l = this.$.attributes; return l.length > 1 || l.length == 1 && l[0].nodeName != 'dj'; }, hasAttribute : function(l) { var m = this.$.attributes.getNamedItem(l); return !!(m && m.specified); }, hide : function() { this.setStyle('display', 'none'); }, jg : function(l, m) { var n = this.$; l = l.$; if (n == l) return; var o; if (m) while (o = n.lastChild) l.insertBefore(n.removeChild(o), l.firstChild); else while (o = n.firstChild) l.appendChild(n.removeChild(o)); }, show : function() { this.setStyles( { display : '', visibility : '' }); }, setAttribute : (function() { var l = function(m, n) { this.$.setAttribute(m, n); return this; }; if (g && (f.ie7Compat || f.ie6Compat)) return function(m, n) { var o = this; if (m == 'class') o.$.className = n; else if (m == 'style') o.$.style.cssText = n; else if (m == 'tabindex') o.$.tabIndex = n; else if (m == 'checked') o.$.checked = n; else l.apply(o, arguments); return o; }; else return l; })(), setAttributes : function(l) { for ( var m in l) this.setAttribute(m, l[m]); return this; }, setValue : function(l) { this.$.value = l; return this; }, removeAttribute : (function() { var l = function(m) { this.$.removeAttribute(m); }; if (g && (f.ie7Compat || f.ie6Compat)) return function(m) { if (m == 'class') m = 'className'; else if (m == 'tabindex') m = 'tabIndex'; l.call(this, m); }; else return l; })(), uW : function(l) { for ( var m = 0; m < l.length; m++) this.removeAttribute(l[m]); }, removeStyle : function(l) { var m = this; if (m.$.style.removeAttribute) m.$.style.removeAttribute(i .cssStyleToDomStyle(l)); else m.setStyle(l, ''); if (!m.$.style.cssText) m.removeAttribute('style'); }, setStyle : function(l, m) { this.$.style[i.cssStyleToDomStyle(l)] = m; return this; }, setStyles : function(l) { for ( var m in l) this.setStyle(m, l[m]); return this; }, setOpacity : function(l) { if (g) { l = Math.round(l * 100); this .setStyle( 'filter', l >= 100 ? '' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + l + ')'); } else this.setStyle('opacity', l); }, unselectable : f.gecko ? function() { this.$.style.MozUserSelect = 'none'; } : f.webkit ? function() { this.$.style.uE = 'none'; } : function() { if (g || f.opera) { var l = this.$, m, n = 0; l.unselectable = 'on'; while (m = l.all[n++]) switch (m.tagName.toLowerCase()) { case 'iframe': case 'textarea': case 'input': case 'select': break; default: m.unselectable = 'on'; } } }, vr : function() { var l = this; while (l.getName() != 'html') { if (l.getComputedStyle('position') != 'static') return l; l = l.getParent(); } return null; }, ir : function(l) { var G = this; var m = 0, n = 0, o = G.getDocument().bH(), p = G .getDocument().$.compatMode == 'BackCompat', q = G .getDocument(); if (document.documentElement.getBoundingClientRect) { var r = G.$.getBoundingClientRect(), s = q.$, t = s.documentElement, u = t.clientTop || o.$.clientTop || 0, v = t.clientLeft || o.$.clientLeft || 0, w = true; if (g) { var x = q.gT().contains(G), y = q.bH() .contains(G); w = p && y || !p && x; } if (w) { m = r.left + (!p && t.scrollLeft || o.$.scrollLeft); m -= v; n = r.top + (!p && t.scrollTop || o.$.scrollTop); n -= u; } } else { var z = G, A = null, B; while (z && !(z.getName() == 'body' || z .getName() == 'html')) { m += z.$.offsetLeft - z.$.scrollLeft; n += z.$.offsetTop - z.$.scrollTop; if (!z.equals(G)) { m += z.$.clientLeft || 0; n += z.$.clientTop || 0; } var C = A; while (C && !C.equals(z)) { m -= C.$.scrollLeft; n -= C.$.scrollTop; C = C.getParent(); } A = z; z = (B = z.$.offsetParent) ? new k(B) : null; } } if (l) { var D = G.getWindow(), E = l.getWindow(); if (!D.equals(E) && D.$.frameElement) { var F = new k(D.$.frameElement).ir(l); m += F.x; n += F.y; } } if (!document.documentElement.getBoundingClientRect) if (f.gecko && !p) { m += G.$.clientLeft ? 1 : 0; n += G.$.clientTop ? 1 : 0; } return { x : m, y : n }; }, scrollIntoView : function(l) { var r = this; var m = r.getWindow(), n = m.eR().height, o = n * -1; if (l) o += n; else { o += r.$.offsetHeight || 0; o += parseInt(r .getComputedStyle('marginBottom') || 0, 10) || 0; } var p = r.ir(); o += p.y; o = o < 0 ? 0 : o; var q = m.hV().y; if (o > q || o < q - n) m.$.scrollTo(0, o); }, bR : function(l) { var m = this; switch (l) { case a.eV: m.addClass('cke_on'); m.removeClass('cke_off'); m.removeClass('cke_disabled'); break; case a.aY: m.addClass('cke_disabled'); m.removeClass('cke_off'); m.removeClass('cke_on'); break; default: m.addClass('cke_off'); m.removeClass('cke_on'); m.removeClass('cke_disabled'); break; } }, getFrameDocument : function() { var l = this.$; try { l.contentWindow.document; } catch (m) { l.src = l.src; if (g && f.version < 7) window .showModalDialog('javascript:document.write("<script>window.setTimeout(function(){window.close();},50);</script>")'); } return l && new j(l.contentWindow.document); }, qw : function(l, m) { var s = this; var n = s.$.attributes; m = m || {}; for ( var o = 0; o < n.length; o++) { var p = n[o]; if (p.specified || g && p.nodeValue && p.nodeName.toLowerCase() == 'value') { var q = p.nodeName; if (q in m) continue; var r = s.getAttribute(q); if (r === null) r = p.nodeValue; l.setAttribute(q, r); } } if (s.$.style.cssText !== '') l.$.style.cssText = s.$.style.cssText; }, renameNode : function(l) { var o = this; if (o.getName() == l) return; var m = o.getDocument(), n = new k(l, m); o.qw(n); o.jg(n); o.$.parentNode.replaceChild(n.$, o.$); n.$.dj = o.$.dj; o.$ = n.$; }, getChild : function(l) { var m = this.$; if (!l.slice) m = m.childNodes[l]; else while (l.length > 0 && m) m = m.childNodes[l.shift()]; return m ? new h.bi(m) : null; }, iu : function() { return this.$.childNodes.length; }, hX : function() { this.on('contextmenu', function(l) { if (!l.data.bK().hasClass( 'cke_enable_context_menu')) l.data.preventDefault(); }); }, 'toString' : function() { return this.getName() + '#' + this.dS() + '.' + this.getAttribute('class'); } }); (function() { var l = { width : [ 'border-left-width', 'border-right-width', 'padding-left', 'padding-right' ], height : [ 'border-top-width', 'border-bottom-width', 'padding-top', 'padding-bottom' ] }; function m(n) { var o = 0; for ( var p = 0, q = l[n].length; p < q; p++) o += parseInt(this.getComputedStyle(l[n][p]) || 0, 10) || 0; return o; } ; k.prototype.setSize = function(n, o, p) { if (typeof o == 'number') { if (p && !(g && f.quirks)) o -= m.call(this, n); this.setStyle(n, o + 'px'); } }; k.prototype.hR = function(n, o) { var p = Math.max(this.$['offset' + i.capitalize(n)], this.$['client' + i.capitalize(n)]) || 0; if (o) p -= m.call(this, n); return p; }; })(); a.command = function(l, m) { this.pW = []; this.exec = function(n) { if (this.bu == a.aY) return false; if (m.oD) l.focus(); return m.exec.call(this, l, n) !== false; }; i.extend(this, m, { iH : { qt : 1 }, oD : true, bu : a.aS }); a.event.call(this); }; a.command.prototype = { enable : function() { var l = this; if (l.bu == a.aY) l.bR(!l.vf || typeof l.lJ == 'undefined' ? a.aS : l.lJ); }, disable : function() { this.bR(a.aY); }, bR : function(l) { var m = this; if (m.bu == l) return false; m.lJ = m.bu; m.bu = l; m.oW('bu'); return true; }, rJ : function() { var l = this; if (l.bu == a.aS) l.bR(a.eV); else if (l.bu == a.eV) l.bR(a.aS); } }; a.event.du(a.command.prototype, true); a.config = { customConfig : a.getUrl('config.js'), connectorLanguage : 'php', language : '', defaultLanguage : 'en', defaultViewType : 'thumbnails', defaultSortBy : 'filename', defaultDisplayFilename : true, defaultDisplayDate : true, defaultDisplayFilesize : true, pO : '', height : 400, plugins : 'foldertree,folder,filebrowser,container,connector,resource,toolbar,formpanel,filesview,status,contextmenu,uploadform,keystrokes,dragdrop,basket,dialog,tools,resize,help,flashupload,mobile', extraPlugins : '', fileIcons : 'ai|avi|bmp|cs|dll|doc|docx|exe|fla|gif|jpg|js|mdb|mp3|ogg|pdf|ppt|pptx|rdp|swf|swt|txt|vsd|xls|xlsx|xml|zip', removePlugins : '', tabIndex : 0, thumbnailDelay : 50, theme : 'default', skin : 'kama', width : '100%', baseFloatZIndex : 10000, directDownload : false, log : false, logStackTrace : false, rememberLastFolder : true, id : null, startupPath : '', startupFolderExpanded : true, selectActionFunction : null, selectActionData : null, selectThumbnailActionFunction : null, selectThumbnailActionData : null, disableThumbnailSelection : false, thumbsUrl : null, thumbsDirectAccess : false, imagesMaxWidth : 0, imagesMaxHeight : 0, selectActionType : 'js', resourceType : null, disableHelpButton : false, connectorPath : '', uiColor : null, showContextMenuArrow : false, useNativeIcons : false }; CKFinder.config = a.config; var l = a.config; a.dU = function(m, n) { this.rG = m; this.message = n; }; a.fs = function(m) { if (m.fs) return m.fs; this.hasFocus = false; this._ = { application : m }; return this; }; a.fs.prototype = { focus : function() { var n = this; if (n._.fW) clearTimeout(n._.fW); if (!n.hasFocus) { if (a.eq) a.eq.fs.ly(); var m = n._.application; m.container.getFirst().addClass('cke_focus'); n.hasFocus = true; m.oW('focus'); } }, blur : function() { var m = this; if (m._.fW) clearTimeout(m._.fW); m._.fW = setTimeout(function() { delete m._.fW; m.ly(); }, 100); }, ly : function() { if (this.hasFocus) { var m = this._.application; m.container.getFirst().removeClass('cke_focus'); this.hasFocus = false; m.oW('blur'); } } }; (function() { var m = {}; a.lang = { ko : { cs : 1, da : 1, de : 1, el : 1, en : 1, es : 1, 'es-mx' : 1, et : 1, fa : 1, fi : 1, fr : 1, he : 1, hu : 1, it : 1, ja : 1, lv : 1, lt : 1, nb : 1, nl : 1, no : 1, nn : 1, pl : 1, 'pt-br' : 1, ru : 1, sk : 1, sl : 1, sv : 1, tr : 1, 'zh-cn' : 1, 'zh-tw' : 1 }, load : function(n, o, p) { if (!n || !a.lang.ko[n]) n = this.jV(o, n); if (!this[n]) a.ec.load(a.getUrl('lang/' + n + '.js'), function() { p(n, CKFinder.lang[n]); }, this); else p(n, this[n]); }, jV : function(n, o) { var p = this.ko; o = o || navigator.userLanguage || navigator.language; var q = o.toLowerCase().match(/([a-z]+)(?:-([a-z]+))?/), r = q[1], s = q[2]; if (p[r + '-' + s]) r = r + '-' + s; else if (!p[r]) r = null; a.lang.jV = r ? function() { return r; } : function(t) { return t; }; return r || n; } }; })(); (function() { a.log = function() { if (!l.log && !window.CKFINDER_LOG) return; var m = ''; for ( var n = 0; n < arguments.length; n++) { var o = arguments[n]; if (!o) continue; if (m) m += '; '; switch (typeof o) { case 'function': var p = /function (\w+?)\(/.exec(o.toString()); p = p ? p[1] : 'anonymous func'; m += p; break; default: m += o ? o.toString() : ''; } } a._.log.push(m); if (typeof window.console == 'object') if (!console.log.apply) console.log(m); else console.log.apply(console, arguments); }; a.ba = function(m) { if (l.logStackTrace) a.log('[EXCEPTION] ' + m.toString()); return m; }; a.mZ = function(m) { var n = ''; for ( var o = 0; o < a._.log.length; o++) n += o + 1 + '. ' + a._.log[o] + '\n'; return n; }; a._.log = []; })(); a.ec = (function() { var m = {}, n = {}; return { load : function(o, p, q, r, s) { var t = typeof o == 'string'; if (t) o = [ o ]; if (!q) q = a; var u = o.length, v = [], w = [], x = function(C) { if (p) if (t) p.call(q, C); else p.call(q, v, w); }; if (u === 0) { x(true); return; } var y = function(C, D) { (D ? v : w).push(C); if (--u <= 0) x(D); }, z = function(C, D) { m[C] = 1; var E = n[C]; delete n[C]; for ( var F = 0; F < E.length; F++) E[F](C, D); }, A = function(C) { if (r !== true && m[C]) { y(C, true); return; } var D = n[C] || (n[C] = []); D.push(y); if (D.length > 1) return; var E = new k('script'); E.setAttributes( { type : 'text/javascript', src : C }); if (p) if (g) E.$.onreadystatechange = function() { if (E.$.readyState == 'loaded' || E.$.readyState == 'complete') { E.$.onreadystatechange = null; a.log('[LOADED] ' + C); z(C, true); } }; else { E.$.onload = function() { setTimeout(function() { a.log('[LOADED] ' + C); z(C, true); }, 0); }; E.$.onerror = function() { z(C, false); }; } E.appendTo(s ? s : a.document.eD()); }; for ( var B = 0; B < u; B++) A(o[B]); }, uq : function(o) { var p = new k('script'); p.setAttribute('type', 'text/javascript'); p.appendText(o); p.appendTo(a.document.eD()); } }; })(); a.fQ = function(m, n) { var o = this; o.basePath = m; o.fileName = n; o.bX = {}; o.loaded = {}; o.jn = {}; o._ = { rZ : {} }; }; a.fQ.prototype = { add : function(m, n) { if (this.bX[m]) throw '[CKFINDER.fQ.add] The resource name "' + m + '" is already bX.'; this.bX[m] = n || {}; }, eB : function(m) { return this.bX[m] || null; }, getPath : function(m) { var n = this.jn[m]; return a.getUrl(n && n.dir || this.basePath + m + '/'); }, pi : function(m) { var n = this.jn[m]; return a.getUrl(this.getPath(m) + (n && n.file || this.fileName + '.js')); }, tR : function(m, n, o) { m = m.split(','); for ( var p = 0; p < m.length; p++) { var q = m[p]; this.jn[q] = { dir : n, file : o }; } }, load : function(m, n, o) { if (!i.isArray(m)) m = m ? [ m ] : []; var p = this.loaded, q = this.bX, r = [], s = {}, t = {}; for ( var u = 0; u < m.length; u++) { var v = m[u]; if (!v) continue; if (!p[v] && !q[v]) { var w = this.pi(v); r.push(w); if (!(w in s)) s[w] = []; s[w].push(v); } else t[v] = this.eB(v); } a.ec.load(r, function(x, y) { if (y.length) throw '[CKFINDER.fQ.load] Resource name "' + s[y[0]].join(',') + '" was not found at "' + y[0] + '".'; for ( var z = 0; z < x.length; z++) { var A = s[x[z]]; for ( var B = 0; B < A.length; B++) { var C = A[B]; t[C] = this.eB(C); p[C] = 1; } } n.call(o, t); }, this); } }; a.plugins = new a.fQ('plugins/', 'plugin'); var m = a.plugins; m.load = i.override(m.load, function(n) { return function(o, p, q) { var r = {}, s = function(t) { n.call(this, t, function(u) { i.extend(r, u); var v = []; for ( var w in u) { var x = u[w], y = x && x.bM; if (y) for ( var z = 0; z < y.length; z++) { if (!r[y[z]]) v.push(y[z]); } } if (v.length) s.call(this, v); else { for (w in r) { x = r[w]; if (x.onLoad && !x.onLoad.qK) { x.onLoad(); x.onLoad.qK = 1; } } if (p) p.call(q || window, r); } }, this); }; s.call(this, o); }; }); m.rX = function(n, o, p) { var q = this.eB(n); q.lang[o] = p; }; (function() { var n = {}, o = function(p, q) { var r = function() { n[p] = 1; q(); }, s = new k('img'); s.on('load', r); s.on('error', r); s.setAttribute('src', p); }; a.rw = { load : function(p, q) { var r = p.length, s = function() { if (--r === 0) q(); }; for ( var t = 0; t < p.length; t++) { var u = p[t]; if (n[u]) s(); else o(u, s); } } }; })(); a.skins = (function() { var n = {}, o = {}, p = {}, q = function(r, s, t, u) { var v = n[s]; if (!r.skin) { r.skin = v; if (v.bz) v.bz(r); } var w = function(E) { for ( var F = 0; F < E.length; F++) E[F] = a.getUrl(p[s] + E[F]); }; if (!o[s]) { var x = v.ls; if (x && x.length > 0) { w(x); a.rw.load(x, function() { o[s] = 1; q(r, s, t, u); }); return; } o[s] = 1; } t = v[t]; var y = 0; if (t) { if (!t.iB) t.iB = []; else if (t.iB[r.name]) y = 1; } else y = 1; if (y) u && u(); else { if (t.eb === undefined) t.eb = []; if (t.eb[r.name] === undefined) t.eb[r.name] = []; var z = t.eb[r.name]; z.push(u); if (z.length > 1) return; var A = !t.css || !t.css.length, B = !t.js || !t.js.length, C = function() { if (A && B) { t.iB[r.name] = 1; for ( var E = 0; E < z.length; E++) { if (z[E]) z[E](); } } }; if (!A) { if (!t.rr) { w(t.css); t.rr = 1; } if (t.qx) for ( var D = 0; D < t.css.length; D++) a.oC.pb(t.css[D]); else r .on( 'themeSpace', function(E) { if (E.data.space == 'head') for ( var F = 0; F < t.css.length; F++) E.data.html += "<link rel='stylesheet' href='" + t.css[F] + "'>\n"; E.removeListener(); }); A = 1; } if (!B) { w(t.js); r.ec.load(t.js, function() { B = 1; C(); }); } C(); } }; return { add : function(r, s) { n[r] = s; s.fh = p[r] || (p[r] = a.getUrl('skins/' + r + '/')); }, loaded : n, load : function(r, s, t) { var u = r.gd, v = r.fh; if (n[u]) { q(r, u, s, t); var w = n[u]; } else { p[u] = v; a.ec.load(v + 'skin.js', function() { q(r, u, s, t); }); } } }; })(); a.gc = new a.fQ('gc/', 'theme'); a.bY = function(n) { if (n.bY) return n.bY; this._ = { jZ : {}, items : {}, application : n }; return this; }; var n = a.bY; n.prototype = { add : function(o, p, q) { this._.items[o] = { type : p, command : q.command || null, mp : Array.prototype.slice.call(arguments, 2) }; }, create : function(o) { var t = this; var p = t._.items[o], q = p && t._.jZ[p.type], r = p && p.command && t._.application.cS(p.command), s = q && q.create.apply(t, p.mp); if (r) r.pW.push(s); return s; }, kd : function(o, p) { this._.jZ[o] = p; } }; (function() { var o = 0, p = function() { var y = 'ckfinder' + ++o; return a.instances && a.instances[y] ? p() : y; }, q = {}, r = function(y) { var z = y.config.customConfig; if (!z) return false; var A = q[z] || (q[z] = {}); if (A.gg) { A.gg.call(y, y.config); if (y.config.customConfig == z || !r(y)) y.cr('customConfigLoaded'); } else a.ec.load(z, function() { if (CKFinder.customConfig) A.gg = CKFinder.customConfig; else A.gg = function() { }; r(y); }); return true; }, s = function(y, z) { y.on('customConfigLoaded', function() { if (z) { if (z.on) for ( var A in z.on) y.on(A, z.on[A]); i.extend(y.config, z, true); delete y.config.on; } t(y); }); if (z && z.customConfig != undefined) y.config.customConfig = z.customConfig; if (!r(y)) y.cr('customConfigLoaded'); }, t = function(y) { var z = y.config.skin.split(','), A = z[0], B = a.getUrl(z[1] || 'skins/' + A + '/'); y.gd = A; y.fh = B; y.iy = 'cke_skin_' + A + ' skin_' + A; y.qn = y.ox(); y.on('uiReady', function() { y.document.getWindow().on( 'lW', function() { i.setCookie('CKFinder_UTime', Math.round(new Date() .getTime() / 1000), true); i.setCookie('CKFinder_UId', encodeURIComponent(y.id ? y.id : location.href), true); }); }); y.cr('configLoaded'); u(y); }, u = function(y) { a.lang .load( y.config.language, y.config.defaultLanguage, function(z, A) { y.langCode = z; y.lang = i.prototypedCopy(A); y.lB = (function() { var B = "['" + y.lang.DateAmPm.join("','") + "']", C = y.lang.DateTime .replace( /dd|mm|yyyy|hh|HH|MM|aa|d|m|yy|h|H|M|a/g, function(D) { var E; switch (D) { case 'd': E = "day.replace(/^0/,'')"; break; case 'dd': E = 'day'; break; case 'm': E = "month.replace(/^0/,'')"; break; case 'mm': E = 'month'; break; case 'yy': E = 'year.substr(2)'; break; case 'yyyy': E = 'year'; break; case 'H': E = "hour.replace(/^0/,'')"; break; case 'HH': E = 'hour'; break; case 'h': E = "( hour < 12 ? hour : ( ( hour - 12 ) + 100 ).toString().substr( 1 ) ).replace(/^0/,'')"; break; case 'hh': E = '( hour < 12 ? hour : ( ( hour - 12 ) + 100 ).toString().substr( 1 ) )'; break; case 'M': E = "minute.replace(/^0/,'')"; break; case 'MM': E = 'minute'; break; case 'a': E = B + '[ hour < 12 ? 0 : 1 ].charAt(0)'; break; case 'aa': E = B + '[ hour < 12 ? 0 : 1 ]'; break; default: E = "'" + D + "'"; } return "'," + E + ",'"; }); C = "'" + C + "'"; C = C.replace(/('',)|,''$/g, ''); return new Function('day', 'month', 'year', 'hour', 'minute', 'return [' + C + "].join('');"); })(); if (f.gecko && f.version < 10900 && y.lang.dir == 'rtl') y.lang.dir = 'ltr'; v(y); }); }, v = function(y) { var z = y.config, A = z.plugins, B = z.extraPlugins, C = z.removePlugins; if (B) { var D = new RegExp( '(?:^|,)(?:' + B.replace(/\s*,\s*/g, '|') + ')(?=,|$)', 'g'); A = A.replace(D, ''); A += ',' + B; } if (C) { D = new RegExp( '(?:^|,)(?:' + C.replace(/\s*,\s*/g, '|') + ')(?=,|$)', 'g'); A = A.replace(D, ''); } m.load(A.split(','), function(E) { var F = [], G = [], H = []; y.plugins = E; for ( var I in E) { var J = E[I], K = J.lang, L = m.getPath(I), M = null; E[I].name = I; J.pathName = L; if (K) { M = i.indexOf(K, y.langCode) >= 0 ? y.langCode : K[0]; if (!J.lang[M]) H.push(a.getUrl(L + 'lang/' + M + '.js')); else { i.extend(y.lang, J.lang[M]); M = null; } } G.push(M); F.push(J); } a.ec.load(H, function() { var N = [ 'eK', 'bz', 'gr' ]; for ( var O = 0; O < N.length; O++) for ( var P = 0; P < F.length; P++) { var Q = F[P]; if (O === 0 && G[P] && Q.lang) i.extend(y.lang, Q.lang[G[P]]); if (Q[N[O]]) { a.log('[PLUGIN] ' + Q.name + '.' + N[O]); Q[N[O]](y); } } y.oW('pluginsLoaded'); w(y); }); }); }, w = function(y) { a.skins.load(y, 'application', function() { a.skins.load(y, 'host', function() { x(y); }); }); }, x = function(y) { var z = y.config.theme; a.gc.load(z, function() { var A = y.theme = a.gc.eB(z); A.pathName = a.gc.getPath(z); y.oW('themeAvailable'); }); }; a.application.prototype.iI = function(y) { var z = k.eB(this._.element), A = this._.kw; delete this._.element; delete this._.kw; this._.ky = {}; this._.gS = []; z.getDocument().getWindow().$.CKFinder = y; this.element = z; this.document = null; this.rQ = {}; this.name = p(); if (this.name in a.instances) throw '[CKFINDER.application] The instance "' + this.name + '" already exists.'; this.config = i.prototypedCopy(l); this.bY = new n(this); this.fs = new a.fs(this); this.aL = {}; this.aG = {}; this.on('uiReady', function(B) { this.document.getWindow().on('lW', this.fH, this); }, this); this.cg = new d(this); this .on( 'configLoaded', function(B) { e(this.cg, this, this.config.callback); this.id = this.config.id; if (this.cg.inPopup) { var C = this, D = [ a.oC ]; if (C.cg.inUrlPopup) D .push(new j( a.oC.getWindow().$.opener.document)); for ( var E = 0; E < D.length; E++) D[E].bH().$.onbeforeunload = D[E] .getWindow().$.onunload = D[E] .getWindow().$.onbeforeunload = function() { C.element.getDocument().getWindow().$ .close(); }; } }, this); s(this, A); a.oW('instanceCreated', null, this); }; })(); i.extend(a.application.prototype, { bD : function(o, p) { return this._.ky[o] = new a.command(this, p); }, fH : function(o) { var p = this; if (!o) p.hS(); p.theme.fH(p); p.oW('fH'); a.remove(p); }, execCommand : function(o, p) { a.log('[COMMAND] ' + o); var q = this.cS(o), r = { name : o, rm : p, command : q }; if (q && q.bu != a.aY) if (this.oW('beforeCommandExec', r) !== true) { r.returnValue = q.exec(r.rm); if (!q.async && this.oW('afterCommandExec', r) !== true) return r.returnValue; } return false; }, cS : function(o) { return this._.ky[o]; }, ox : function() { var o = Math.round(new Date().getTime() / 1000), p = i .getCookie('CKFinder_UTime'), q = decodeURIComponent(i .getCookie('CKFinder_UId')); if (q && p && q == (this.id ? this.id : location.href) && Math.abs(o - p) < 5) return 1; return 0; }, bs : '' }); (function() { var o = ''; for ( var p = 49; p < 58; p++) o += String.fromCharCode(p); for (p = 65; p < 91; p++) { if (p == 73 || p == 79) continue; o += String.fromCharCode(p); } a.bs = o; a.nd = "\x6c\x6f"; a.jG = "\x68\157"; a.hf = new window["\x52\x65\147\105\x78\160"]( "\136\x77\x77\167\134\056"); a.hg = new window["\122\x65\x67\x45\x78\x70"]("\x3a\x5c\144\053\044"); a.lS = function(q) { return q.toLowerCase().replace(a.hf, '').replace(a.hg, ''); }; })(); a.on('loaded', function() { var o = a.application.eb; if (o) { delete a.application.eb; for ( var p = 0; p < o.length; p++) o[p].iI(); } }); delete a.dO; a.instances = {}; a.document = new j(document); a.oC = a.document.getWindow().$ != a.document.getWindow().$.top ? new j( a.document.getWindow().$.top.document) : a.document; a.add = function(o) { a.instances[o.name] = o; a.jt = o; o.on('focus', function() { if (a.eq != o) { a.eq = o; a.oW('eq'); } }); o.on('blur', function() { if (a.eq == o) { a.eq = null; a.oW('eq'); } }); }; a.remove = function(o) { delete a.instances[o.name]; }; a.aL = {}; a.eV = 1; a.aS = 2; a.aY = 0; a.bF = ''; (function() { function o(r, s) { return r + '.' + (s.name || s || r); } ; a.aG = { bX : {}, hi : function(r, s, t) { var u = o(r, s); if (this.bX[u] !== undefined) throw '[CKFINDER] Widget ' + u + ' already bX!'; a.log('[WIDGET] bX ' + u); this.bX[u] = new q(u, t); return this.bX[u]; }, bz : function(r, s, t, u, v) { var w = o(s, t), x = this.bX[w], y = i.deepCopy(x.hF), z = function( C, D, E) { this.app = C; this.eh = D instanceof k ? D : new k(D); this.hF = y ? i.extend(y, E) : E || {}; this._ = {}; var F = function(I) { this.ib = I; }; F.prototype = this.tools; this.tools = new F(this); var G = x.dT; if (G.length) for ( var H = 0; H < G.length; H++) G[H].call(this, C, this); }; z.prototype = x; var A = new z(r, u, v); for ( var B in A.fw) A.gA(B); if (!r.aG[w]) r.aG[w] = []; r.aG[w].push(A); a.log('[WIDGET] instanced ' + w); return A; } }; var p = { click : 1, mouseover : 1, mouseout : 1, focus : 1, blur : 1, submit : 1, dblclick : 1, mousedown : 1, mouseup : 1, mousemove : 1, keypress : 1, keydown : 1, keyup : 1, load : 1, lW : 1, abort : 1, error : 1, resize : 1, scroll : 1, select : 1, change : 1, reset : 1 }, q = function(r, s) { var t = this; t.id = r; t.fw = {}; t.hF = s || {}; t.dT = []; t.tools = new t.tools(t); }; q.prototype = { gA : function(r) { var w = this; a.log('[WIDGET] Enabling behavior ' + r); var s = w.fw[r]; if (!s) return; var t = w; for ( var u = 0; u < s.cC.length; u++) { var v = s.cC[u]; if (p[v]) w.eh.on(v, s.fO, t); else { w.on(v, s.fO, t); w.app.on(v, s.fO, t); } } }, ke : function(r) { a.log('[WIDGET] Disabling behavior ' + r); var s = this.fw[r]; if (!s) return; for ( var t = 0; t < s.cC.length; t++) { var u = s.cC[t]; if (p[u]) this.eh.removeListener(u, s.fO); else this.removeListener(u, s.fO); } }, bh : function(r, s, t) { if (!i.isArray(s)) s = [ s ]; this.fw[r] = { cC : s, fO : t }; if (this.eh) this.gA(r); }, removeBehavior : function(r) { delete this.fw[r]; }, ur : function() { return this.fw; }, bn : function() { return this.eh; }, oE : function() { return this.hF; }, data : function() { return this.hF; }, tools : function() { } }; q.prototype.tools.prototype = { kg : function(r) { if (r.target == this.ib.eh) return 1; } }; a.event.du(q.prototype); })(); a.xml = function(o) { var p = null; if (typeof o == 'object') p = o; else { var q = (o || '').replace(/&nbsp;/g, '\xa0'); if (window.DOMParser) p = new DOMParser().parseFromString(q, 'text/xml'); else if (window.ActiveXObject) { try { p = new ActiveXObject('MSXML2.DOMDocument'); } catch (r) { try { p = new ActiveXObject('Microsoft.XmlDom'); } catch (r) { } } if (p) { p.async = false; p.resolveExternals = false; p.validateOnParse = false; p.loadXML(q); } } } this.mq = p; }; a.xml.prototype = { selectSingleNode : function(o, p) { var q = this.mq; if (p || (p = q)) if (g || p.selectSingleNode) return p.selectSingleNode(o); else if (q.evaluate) { var r = q.evaluate(o, p, null, 9, null); return r && r.singleNodeValue || null; } else if (p.querySelectorAll) { var s = this.selectNodes(o, p); if (s.length == 1) return s[0].getAttributeNode(o.match(/\/@(.*$)/)[1]); } else alert('XPath is not supported in your browser'); return null; }, selectNodes : function(o, p) { var q = this.mq, r = []; if (p || (p = q)) if (g || p.selectNodes) return p.selectNodes(o); else if (q.evaluate) { var s = q.evaluate(o, p, null, 5, null); if (s) { var t; while (t = s.iterateNext()) r.push(t); } } else if (p.querySelectorAll) { var u = o.replace(/\/@(.*$)/, '[$1]').replace(/\//gi, '>'); return p.querySelectorAll(u); } else alert('XPath is not supported in your browser'); return r; }, vB : function(o, p) { var q = this.selectSingleNode(o, p), r = []; if (q) { q = q.firstChild; while (q) { if (q.xml) r.push(q.xml); else if (window.XMLSerializer) r.push(new XMLSerializer().serializeToString(q)); q = q.nextSibling; } } return r.length ? r.join('') : null; } }; (function() { var o = { address : 1, tY : 1, dl : 1, h1 : 1, h2 : 1, h3 : 1, h4 : 1, h5 : 1, h6 : 1, p : 1, pre : 1, li : 1, dt : 1, de : 1 }, p = { body : 1, div : 1, table : 1, tbody : 1, tr : 1, td : 1, th : 1, caption : 1, form : 1 }, q = function(r) { var s = r.getChildren(); for ( var t = 0, u = s.count(); t < u; t++) { var v = s.getItem(t); if (v.type == a.cv && a.ga.um[v.getName()]) return true; } return false; }; h.qS = function(r) { var x = this; var s = null, t = null, u = [], v = r; while (v) { if (v.type == a.cv) { if (!x.qH) x.qH = v; var w = v.getName(); if (g && v.$.scopeName != 'HTML') w = v.$.scopeName.toLowerCase() + ':' + w; if (!t) { if (!s && o[w]) s = v; if (p[w]) if (!s && w == 'div' && !q(v)) s = v; else t = v; } u.push(v); if (w == 'body') break; } v = v.getParent(); } x.block = s; x.tX = t; x.elements = u; }; })(); h.qS.prototype = { sJ : function(o) { var p = this.elements, q = o && o.elements; if (!q || p.length != q.length) return false; for ( var r = 0; r < p.length; r++) { if (!p[r].equals(q[r])) return false; } return true; } }; h.text = function(o, p) { if (typeof o == 'string') o = (p ? p.$ : document).createTextNode(o); this.$ = o; }; h.text.prototype = new h.bi(); i.extend(h.text.prototype, { type : a.fl, hJ : function() { return this.$.nodeValue.length; }, getText : function() { return this.$.nodeValue; }, split : function(o) { var t = this; if (g && o == t.hJ()) { var p = t.getDocument().jT(''); p.kB(t); return p; } var q = t.getDocument(), r = new h.text(t.$.splitText(o), q); if (f.ie8) { var s = new h.text('', q); s.kB(r); s.remove(); } return r; }, substring : function(o, p) { if (typeof p != 'number') return this.$.nodeValue.substr(o); else return this.$.nodeValue.substring(o, p); } }); h.pa = function(o) { o = o || a.document; this.$ = o.$.createDocumentFragment(); }; i.extend(h.pa.prototype, k.prototype, { type : a.om, kA : function(o) { o = o.$; o.parentNode.insertBefore(this.$, o.nextSibling); } }, true, { append : 1, pd : 1, getFirst : 1, dB : 1, appendTo : 1, jg : 1, insertBefore : 1, kA : 1, replace : 1, trim : 1, type : 1, ltrim : 1, rtrim : 1, getDocument : 1, iu : 1, getChild : 1, getChildren : 1 }); (function() { function o(s, t) { if (this._.end) return null; var u, v = this.mk, w, x = this.vR, y = this.type, z = s ? 'getPreviousSourceNode' : 'getNextSourceNode'; if (!this._.start) { this._.start = 1; v.trim(); if (v.collapsed) { this.end(); return null; } } if (!s && !this._.kp) { var A = v.endContainer, B = A.getChild(v.endOffset); this._.kp = function(F, G) { return (!G || !A.equals(F)) && (!B || !F.equals(B)) && (F.type != a.cv || F.getName() != 'body'); }; } if (s && !this._.ka) { var C = v.startContainer, D = v.startOffset > 0 && C.getChild(v.startOffset - 1); this._.ka = function(F, G) { return (!G || !C.equals(F)) && (!D || !F.equals(D)) && (F.type != a.cv || F.getName() != 'body'); }; } var E = s ? this._.ka : this._.kp; if (x) w = function(F, G) { if (E(F, G) === false) return false; return x(F); }; else w = E; if (this.current) u = this.current[z](false, y, w); else if (s) { u = v.endContainer; if (v.endOffset > 0) { u = u.getChild(v.endOffset - 1); if (w(u) === false) u = null; } else u = w(u) === false ? null : u.hZ(true, y, w); } else { u = v.startContainer; u = u.getChild(v.startOffset); if (u) { if (w(u) === false) u = null; } else u = w(v.startContainer) === false ? null : v.startContainer .hL(true, y, w); } while (u && !this._.end) { this.current = u; if (!this.lf || this.lf(u) !== false) { if (!t) return u; } else if (t && this.lf) return false; u = u[z](false, y, w); } this.end(); return this.current = null; } ; function p(s) { var t, u = null; while (t = o.call(this, s)) u = t; return u; } ; h.gm = i.createClass( { $ : function(s) { this.mk = s; this._ = {}; }, ej : { end : function() { this._.end = 1; }, next : function() { return o.call(this); }, previous : function() { return o.call(this, true); }, sC : function() { return o.call(this, false, true) !== false; }, sD : function() { return o.call(this, true, true) !== false; }, uF : function() { return p.call(this); }, uB : function() { return p.call(this, true); }, reset : function() { delete this.current; this._ = {}; } } }); var q = { block : 1, 'list-item' : 1, table : 1, 'table-row-group' : 1, 'table-header-group' : 1, 'table-footer-group' : 1, 'table-row' : 1, 'table-column-group' : 1, 'table-column' : 1, 'table-cell' : 1, 'table-caption' : 1 }, r = { hr : 1 }; k.prototype.qy = function(s) { var t = i.extend( {}, r, s || {}); return q[this.getComputedStyle('display')] || t[this.getName()]; }; h.gm.pQ = function(s) { return function(t, u) { return !(t.type == a.cv && t.qy(s)); }; }; h.gm.us = function() { return this.pQ( { br : 1 }); }; h.gm.tU = function(s) { }, h.gm.tW = function(s, t) { function u(v) { return v && v.getName && v.getName() == 'span' && v.hasAttribute('_fck_bookmark'); } ; return function(v) { var w, x; w = v && !v.getName && (x = v.getParent()) && u(x); w = s ? w : w || u(v); return t ^ w; }; }; h.gm.sf = function(s) { return function(t) { var u = t && t.type == a.fl && !i.trim(t.getText()); return s ^ u; }; }; })(); (function() { if (f.webkit) { f.hc = false; return; } var o = g && f.version < 7, p = g && f.version == 7, q = o ? a.basePath + 'images/spacer.gif' : p ? 'about:blank' : 'data:image/png;base64,', r = k .kE( '<div style="width:0px;height:0px;position:absolute;left:-10000px;background-image:url(' + q + ')"></div>', a.document); r.appendTo(a.document.eD()); try { f.hc = r.getComputedStyle('background-image') == 'none'; } catch (s) { f.hc = false; } if (f.hc) f.cssClass += ' cke_hc'; r.remove(); })(); m.load(l.pO.split(','), function() { a.status = 'loaded'; a.oW('loaded'); var o = a._.io; if (o) { delete a._.io; for ( var p = 0; p < o.length; p++) a.add(o[p]); } }); if (g) try { document.execCommand('BackgroundImageCache', false, true); } catch (o) { } CKFinder.lang.en = { appTitle : 'CKFinder', common : { unavailable : '%1<span class="cke_accessibility">, unavailable</span>', confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?', ok : 'OK', cancel : 'Cancel', confirmationTitle : 'Confirmation', messageTitle : 'Information', inputTitle : 'Question', undo : 'Undo', redo : 'Redo', skip : 'Skip', skipAll : 'Skip all', makeDecision : 'What action should be taken?', rememberDecision : 'Remember my decision' }, dir : 'ltr', HelpLang : 'en', LangCode : 'en', DateTime : 'm/d/yyyy h:MM aa', DateAmPm : [ 'AM', 'PM' ], FoldersTitle : 'Folders', FolderLoading : 'Loading...', FolderNew : 'Please type the new folder name: ', FolderRename : 'Please type the new folder name: ', FolderDelete : 'Are you sure you want to delete the "%1" folder?', FolderRenaming : ' (Renaming...)', FolderDeleting : ' (Deleting...)', FileRename : 'Please type the new file name: ', FileRenameExt : 'Are you sure you want to change the file extension? The file may become unusable.', FileRenaming : 'Renaming...', FileDelete : 'Are you sure you want to delete the file "%1"?', FilesLoading : 'Loading...', FilesEmpty : 'The folder is empty.', FilesMoved : 'File %1 moved to %2:%3.', FilesCopied : 'File %1 copied to %2:%3.', BasketFolder : 'Basket', BasketClear : 'Clear Basket', BasketRemove : 'Remove from Basket', BasketOpenFolder : 'Open Parent Folder', BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', BasketEmpty : 'No files in the basket, drag and drop some.', BasketCopyFilesHere : 'Copy Files from Basket', BasketMoveFilesHere : 'Move Files from Basket', BasketPasteErrorOther : 'File %s error: %e', BasketPasteMoveSuccess : 'The following files were moved: %s', BasketPasteCopySuccess : 'The following files were copied: %s', Upload : 'Upload', UploadTip : 'Upload New File', Refresh : 'Refresh', Settings : 'Settings', Help : 'Help', HelpTip : 'Help', Select : 'Select', SelectThumbnail : 'Select Thumbnail', View : 'View', Download : 'Download', NewSubFolder : 'New Subfolder', Rename : 'Rename', Delete : 'Delete', CopyDragDrop : 'Copy File Here', MoveDragDrop : 'Move File Here', RenameDlgTitle : 'Rename', NewNameDlgTitle : 'New Name', FileExistsDlgTitle : 'File Already Exists', SysErrorDlgTitle : 'System Error', FileOverwrite : 'Overwrite', FileAutorename : 'Auto-rename', OkBtn : 'OK', CancelBtn : 'Cancel', CloseBtn : 'Close', UploadTitle : 'Upload New File', UploadSelectLbl : 'Select a file to upload', UploadProgressLbl : '(Upload in progress, please wait...)', UploadBtn : 'Upload Selected File', UploadBtnCancel : 'Cancel', UploadNoFileMsg : 'Please select a file from your computer.', UploadNoFolder : 'Please select a folder before uploading.', UploadNoPerms : 'File upload not allowed.', UploadUnknError : 'Error sending the file.', UploadExtIncorrect : 'File extension not allowed in this folder.', UploadLabel : 'Files to Upload', UploadTotalFiles : 'Total Files:', UploadTotalSize : 'Total Size:', UploadAddFiles : 'Add Files', UploadClearFiles : 'Clear Files', UploadCancel : 'Cancel Upload', UploadRemove : 'Remove', UploadRemoveTip : 'Remove !f', UploadUploaded : 'Uploaded !n%', UploadProcessing : 'Processing...', SetTitle : 'Settings', SetView : 'View:', SetViewThumb : 'Thumbnails', SetViewList : 'List', SetDisplay : 'Display:', SetDisplayName : 'File Name', SetDisplayDate : 'Date', SetDisplaySize : 'File Size', SetSort : 'Sorting:', SetSortName : 'by File Name', SetSortDate : 'by Date', SetSortSize : 'by Size', FilesCountEmpty : '<Empty Folder>', FilesCountOne : '1 file', FilesCountMany : '%1 files', Kb : '%1 kB', KbPerSecond : '%1 kB/s', ErrorUnknown : 'It was not possible to complete the request. (Error %1)', Errors : { 10 : 'Invalid command.', 11 : 'The resource type was not specified in the request.', 12 : 'The requested resource type is not valid.', 102 : 'Invalid file or folder name.', 103 : 'It was not possible to complete the request due to authorization restrictions.', 104 : 'It was not possible to complete the request due to file system permission restrictions.', 105 : 'Invalid file extension.', 109 : 'Invalid request.', 110 : 'Unknown error.', 115 : 'A file or folder with the same name already exists.', 116 : 'Folder not found. Please refresh and try again.', 117 : 'File not found. Please refresh the files list and try again.', 118 : 'Source and target paths are equal.', 201 : 'A file with the same name is already available. The uploaded file was renamed to "%1".', 202 : 'Invalid file.', 203 : 'Invalid file. The file size is too big.', 204 : 'The uploaded file is corrupt.', 205 : 'No temporary folder is available for upload in the server.', 206 : 'Upload cancelled due to security reasons. The file contains HTML-like data.', 207 : 'The uploaded file was renamed to "%1".', 300 : 'Moving file(s) failed.', 301 : 'Copying file(s) failed.', 500 : 'The file browser is disabled for security reasons. Please contact your system administrator and check the CKFinder configuration file.', 501 : 'The thumbnails support is disabled.' }, ErrorMsg : { pg : 'The file name cannot be empty.', FileExists : 'File %s already exists.', FolderEmpty : 'The folder name cannot be empty.', oP : 'The file name cannot contain any of the following characters: \n\\ / : * ? " < > |', FolderInvChar : 'The folder name cannot contain any of the following characters: \n\\ / : * ? " < > |', oo : 'It was not possible to open the file in a new window. Please configure your browser and disable all popup blockers for this site.', XmlError : 'It was not possible to properly load the XML response from the web server.', XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', XmlRawResponse : 'Raw response from the server: %s' }, Imageresize : { dialogTitle : 'Resize %s', sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', resizeSuccess : 'Image resized successfully.', thumbnailNew : 'Create a new thumbnail', thumbnailSmall : 'Small (%s)', thumbnailMedium : 'Medium (%s)', thumbnailLarge : 'Large (%s)', newSize : 'Set a new size', width : 'Width', height : 'Height', invalidHeight : 'Invalid height.', invalidWidth : 'Invalid width.', invalidName : 'Invalid file name.', newImage : 'Create a new image', noExtensionChange : 'File extension cannot be changed.', imageSmall : 'Source image is too small.', contextMenuName : 'Resize', lockRatio : 'Lock ratio', resetSize : 'Reset size' }, Fileeditor : { save : 'Save', fileOpenError : 'Unable to open file.', fileSaveSuccess : 'File saved successfully.', contextMenuName : 'Edit', loadingFile : 'Loading file, please wait...' }, Maximize : { maximize : 'Maximize', minimize : 'Minimize' } }; (function() { var p = 1, q = 2, r = 4, s = 8, t = 16, u = 32, v = 64, w = 128; a.aL.Acl = function(x) { var y = this; if (!x) x = 0; y.folderView = (x & p) == p; y.folderCreate = (x & q) == q; y.folderRename = (x & r) == r; y.folderDelete = (x & s) == s; y.fileView = (x & t) == t; y.fileUpload = (x & u) == u; y.fileRename = (x & v) == v; y.fileDelete = (x & w) == w; }; m.add('acl'); })(); (function() { m .add( 'connector', { bM : [], bz : function(q) { q .on( 'appReady', function() { q.connector = new a.aL.Connector( q); var r = q.config.resourceType, s = r ? { type : r } : null; q.connector .sendCommand( 'Init', s, function(t) { var u; if (t .checkError()) return; var v = "\103\157\156\156\x65\x63\164\x6f\x72\x2f\x43\157\156\x6e\145\143\x74\x6f\x72\111\156\x66\x6f\057"; a.ed = t .selectSingleNode(v + "\x40\163").value; a.bF = t .selectSingleNode(v + "\100\143").value + '----'; q.config.thumbsEnabled = t .selectSingleNode(v + "\100\x74\x68\x75\155\142\163\x45\156\x61\142\154\x65\144").value == 'true'; q.config.thumbsDirectAccess = false; if (q.config.thumbsEnabled) { u = t .selectSingleNode(v + "\x40\164\150\x75\x6d\142\163\x55\x72\154"); if (u) q.config.thumbsUrl = u.value; u = t .selectSingleNode(v + "\x40\x74\150\x75\155\142\x73\x44\151\162\x65\x63\164\x41\x63\143\x65\x73\x73"); if (u) q.config.thumbsDirectAccess = u.value == 'true'; } q.config.imagesMaxWidth = parseInt( t .selectSingleNode(v + "\x40\x69\155\147\x57\151\x64\164\x68").value, 10); q.config.imagesMaxHeight = parseInt( t .selectSingleNode(v + "\100\151\x6d\x67\110\145\x69\x67\x68\x74").value, 10); u = t .selectSingleNode(v + "\100\165\x70\154\x6f\141\144\x4d\141\x78\x53\x69\172\145"); q.config.uploadMaxSize = u ? parseInt( u.value, 10) : 0; u = t .selectSingleNode(v + "\x40\x75\x70\x6c\157\141\144\x43\150\145\143\x6b\111\x6d\141\147\145\x73"); q.config.uploadCheckImages = u ? u.value == 'true' : false; var w = t .selectSingleNode(v + "\100\x70\154\165\x67\x69\156\163"), x = w && w.value; if (x && x.length) m .load( x .split(','), function( y) { var z = [], A = [], B = []; for ( var C in y) { var D = y[C], E = D.lang, F = m .getPath(C), G = null; if (!q.plugins[C]) q.plugins[C] = y[C]; else continue; y[C].name = C; D.pathName = F; if (E) { G = i .indexOf( E, q.langCode) >= 0 ? q.langCode : E[0]; if (!D.lang[G]) B .push(a .getUrl(F + 'lang/' + G + '.js')); else { i .extend( q.lang, D.lang[G]); G = null; } } A .push(G); z .push(D); } a.ec .load( B, function() { var H = [ 'eK', 'bz', 'gr' ]; for ( var I = 0; I < H.length; I++) for ( var J = 0; J < z.length; J++) { var K = z[J]; if (I === 0 && A[J] && K.lang) i .extend( q.lang, K.lang[A[J]]); if (K[H[I]]) { a .log('[PLUGIN] ' + K.name + '.' + H[I]); K[H[I]] (q); } } q .cr('uiReady'); q .cr('appReady'); q .oW( 'pluginsLoaded', { step : 2, jN : q.connector }); q .cr( 'connectorInitialized', { xml : t }); }); }); else { q .oW( 'pluginsLoaded', { step : 2, jN : q.connector }); q .cr( 'connectorInitialized', { xml : t }); } }); }); } }); a.aL.Connector = function(q) { this.app = q; var r = q.config.connectorLanguage || 'php'; if (q.config.connectorPath) this.oN = q.config.connectorPath; else this.oN = a.basePath + 'core/connector/' + r + '/connector.' + r; }; a.aL.Connector.prototype = { ERROR_NONE : 0, ERROR_CUSTOMERROR : 1, ERROR_INVALIDCOMMAND : 10, ERROR_TYPENOTSPECIFIED : 11, ERROR_INVALIDTYPE : 12, ERROR_INVALIDNAME : 102, ERROR_UNAUTHORIZED : 103, ERROR_ACCESSDENIED : 104, ERROR_INVALIDEXTENSION : 105, ERROR_INVALIDREQUEST : 109, ERROR_UNKNOWN : 110, ERROR_ALREADYEXIST : 115, ERROR_FOLDERNOTFOUND : 116, ERROR_FILENOTFOUND : 117, ERROR_SOURCE_AND_TARGET_PATH_EQUAL : 118, ERROR_UPLOADEDFILERENAMED : 201, ERROR_UPLOADEDINVALID : 202, ERROR_UPLOADEDTOOBIG : 203, ERROR_UPLOADEDCORRUPT : 204, ERROR_UPLOADEDNOTMPDIR : 205, ERROR_UPLOADEDWRONGHTMLFILE : 206, ERROR_UPLOADEDINVALIDNAMERENAMED : 207, ERROR_MOVE_FAILED : 300, ERROR_COPY_FAILED : 301, ERROR_CONNECTORDISABLED : 500, ERROR_THUMBNAILSDISABLED : 501, currentFolderUrl : function() { if (this.app.aV) return this.app.aV.getUrl(); }, currentType : function() { if (this.app.aV) return this.app.aV.type; }, currentTypeHash : function() { if (this.app.aV) return a.getResourceType(this.app.aV.type).hash; }, currentResourceType : function() { return a.getResourceType(this.currentType()); }, sendCommand : function(q, r, s, t, u) { var v = this.composeUrl(q, r, t, u), w = this; if (s) return a.ajax.loadXml(v, function(x) { x.hy = w.app; s(i.extend(x, p)); }); else return a.ajax.loadXml(v); }, sendCommandPost : function(q, r, s, t, u, v) { var w = this.composeUrl(q, r, u, v), x = this; if (!s) s = {}; s.CKFinderCommand = true; if (t) return a.ajax.loadXml(w, function(y) { y.hy = x.app; t(i.extend(y, p)); }, this.composeUrlParams(s)); else return a.ajax.loadXml(w, null, this.composeUrlParams(s)); }, composeUrl : function(q, r, s, t) { var w = this; var u = w.oN + '?command=' + encodeURIComponent(q); if (q != 'Init') { var v = ''; if (!t) t = w.app.aV; if (s) v = w.app.getResourceType(s).hash; else v = w.app.getResourceType(t.type).hash; u += '&type=' + encodeURIComponent(s || w.app.aV.type) + '&currentFolder=' + encodeURIComponent(t.getPath() || '') + '&langCode=' + w.app.langCode + '&hash=' + v; } if (r) u += '&' + w.composeUrlParams(r); if (w.app.id) u += '&id=' + encodeURIComponent(w.app.id); return u; }, composeUrlParams : function(q) { if (!q) return ''; var r = ''; for ( var s in q) { if (r.length) r += '&'; r += encodeURIComponent(s) + '=' + encodeURIComponent(q[s]); } return r; } }; var p = { checkError : function() { var w = this; var q = w.getErrorNumber(), r = w.hy.connector; if (q == r.ERROR_NONE) return false; if (q === -1) return true; var s = w.getErrorMessage(); a.log('[ERROR] ' + q); var t; if (q == r.ERROR_CUSTOMERROR) t = s; else { t = w.hy.lang.Errors[q]; if (t) for ( var u = 0; u <= arguments.length; u++) { var v = u === 0 ? s : arguments[u - 1]; t = t.replace(/%(\d+)/, v); } else t = w.hy.lang.ErrorUnknown.replace(/%1/, q); } w.hy.msgDialog('', t); return q != r.ERROR_UPLOADEDFILERENAMED; }, getErrorNumber : function() { var q = this.selectSingleNode && this.selectSingleNode('Connector/Error/@number'); if (!q) return -1; return parseInt(q.value, 10); }, getErrorMessage : function() { var q = this.selectSingleNode && this.selectSingleNode('Connector/Error/@text'); if (!q) return ''; return q.value; } }; })(); m .add( 'resource', { bM : [ 'connector' ], bz : function(p) { p.resourceTypes = []; p .on( 'connectorInitialized', function(q) { var r = q.data.xml .selectNodes('Connector/ResourceTypes/ResourceType'); for ( var s = 0; s < r.length; s++) { var t = r[s].attributes; p.resourceTypes .push(new a.aL.ResourceType( p, { name : t .getNamedItem('name').value, url : t .getNamedItem('url').value, hasChildren : t .getNamedItem('hasChildren').value, allowedExtensions : t .getNamedItem('allowedExtensions').value, deniedExtensions : t .getNamedItem('deniedExtensions').value, acl : t .getNamedItem('acl').value, hash : t .getNamedItem('hash').value, maxSize : t .getNamedItem('maxSize').value })); } p.cr('resourcesReceived', { hK : p.resourceTypes }); }); p.getResourceType = function(q) { for ( var r = 0; r < this.resourceTypes.length; r++) { var s = this.resourceTypes[r]; if (s.name == q) return s; } return null; }; } }); (function() { a.aL.ResourceType = function(q, r) { var s = this; s.app = q; s.name = r.name; s.url = r.url; s.hasChildren = r.hasChildren === 'true'; s.defaultView = 'Thumbnails'; s.allowedExtensions = r.allowedExtensions; s.deniedExtensions = r.deniedExtensions; s.oT = p(r.allowedExtensions); s.ms = p(r.deniedExtensions); s.nS = r.acl; s.hash = r.hash; s.maxSize = r.maxSize; }; a.aL.ResourceType.prototype = { isExtensionAllowed : function(q) { var r = this; q = q.toLowerCase(); return (r.deniedExtensions.length === 0 || !r.ms[q]) && (r.allowedExtensions.length === 0 || !!r.oT[q]); }, allowedExtensions : function() { return this.allowedExtensions; }, getRootFolder : function() { for ( var q = 0; q < this.app.folders.length; q++) { var r = this.app.folders[q]; if (r.isRoot && r.type == this.name) return r; } return undefined; } }; function p(q) { var r = {}; if (q.length > 0) { var s = q.toLowerCase().split(','); for ( var t = 0; t < s.length; t++) r[s[t]] = true; } return r; } ; })(); (function() { var p = { iz : /[\\\/:\*\?"<>\|]/ }; m .add( 'folder', { bM : [ 'resource', 'connector', 'acl' ], bz : function(s) { s.folders = []; s.aV = null; s .on( 'resourcesReceived', function y(t) { var u = [], v = t.data.hK; for ( var w = 0; w < v.length; w++) { var x = v[w]; u.push(new a.aL.Folder( s, x.name, x.name, x.hasChildren, x.nS)); u[u.length - 1].isRoot = true; } s .oW( 'requestAddFolder', { folders : u }, function G() { var z = s.config.startupPath || '', A = 0, B = '', C = ''; if (s.config.rememberLastFolder) { var D = s.id ? 'CKFinder_Path_' + s.id : 'CKFinder_Path'; B = decodeURIComponent(i .getCookie(D)) || ''; } if (z && !s.qn) { C = z; A = 1; } else if (B) C = B; else if (z) C = z; else if (s.resourceTypes.length) C = s.resourceTypes[0].name + '/'; if (C) { a .log('[FOLDER] Opening startup path: ' + C); var E = C .split(':'); if (!s .getResourceType(E[0]) || E.length < 2) E = [ s.resourceTypes[0].name, '/' ]; var F = s.aG['foldertree.foldertree'][0]; F.tools .jL( E[0], E[1], function J( H) { if (!H) return; a .log( '[FOLDER] Opening startup folder: ', H); var I = E[2] == '1' || E[2] === undefined; if (I && s.config.startupFolderExpanded === false) I = 0; F .oW( 'requestSelectFolder', { folder : H, expand : I }); }); } }); }); s .bD( 'RemoveFolder', { exec : function(t) { var u = t.aV; if (u) { if (u.isRoot || !u.acl.folderDelete) return; t .fe( '', t.lang.FolderDelete .replace( '%1', u.name), function() { t .oW( 'requestProcessingFolder', { folder : u }); u .remove(); }); } } }); s .bD( 'CreateSubFolder', { exec : function(t) { var u = t.aV; if (u) t .hs( t.lang.NewNameDlgTitle, t.lang.FolderRename, '', function( v) { v = i .trim(v); if (v) try { t .oW( 'requestProcessingFolder', { folder : u }); u .createNewFolder(v); } catch (w) { if (w instanceof a.dU) { t .oW( 'requestRepaintFolder', { folder : u }); t .msgDialog( '', w.message); } else throw w; } }); } }); s .bD( 'RenameFolder', { exec : function(t) { var u = t.aV; if (u) { if (u.isRoot || !u.acl.folderRename) return; t .hs( t.lang.RenameDlgTitle, t.lang.FolderRename, t.aV.name, function( v) { v = i .trim(v); if (v) try { u .rename(v); } catch (w) { if (w instanceof a.dU) { t .oW( 'requestRepaintFolder', { folder : u }); t .msgDialog( '', w.message); } else throw w; } }); } } }); if (s.eU) { s.dZ('folder0', 99); s.dZ('folder1', 100); s.dZ('folder2', 101); s.dZ('folder3', 102); s.eU( { kl : { label : s.lang.NewSubFolder, command : 'CreateSubFolder', group : 'folder1' }, lI : { label : s.lang.Rename, command : 'RenameFolder', group : 'folder1' }, removeFolder : { label : s.lang.Delete, command : 'RemoveFolder', group : 'folder2' } }); } } }); a.aL.Folder = function(s, t, u, v, w) { var x = this; x.app = s; x.type = t || ''; x.name = u || ''; x.hasChildren = v == undefined || v === null ? true : !!v; x.isRoot = false; x.isOpened = false; x.parent = null; x.isDirty = false; x.acl = new a.aL.Acl(w); x.index = s.folders.push(x) - 1; x.childFolders = null; }; function q(s, t, u, v, w) { if (s.childFolders === null) s.childFolders = []; var x = new a.aL.Folder(s.app, t, u, v, w); x.parent = s; x.nh = s.isRoot ? 0 : s.nh + 1; s.childFolders.push(x); return x; } ; a.aL.Folder.prototype = { getPath : function() { var s = this, t = s.isRoot ? '/' : s.name; while (s.parent) { s = s.parent; t = s.isRoot ? '/' + t : s.name + '/' + t; } return s != this ? t + '/' : t; }, getUrl : function() { var s = this, t = ''; while (s) { t = s.isRoot ? this.app.getResourceType(s.type).url + t : encodeURIComponent(s.name) + '/' + t; s = s.parent; } return t; }, getUploadUrl : function() { return this.app.connector.composeUrl('FileUpload', {}, this.type, this); }, getResourceType : function() { return this.app.getResourceType(this.type); }, updateReference : function() { var t = this; if (t.app.folders[t.index] == t) return t; for ( var s = 0; s < t.parent.childFolders.length; s++) { if (t.parent.childFolders[s].name == t.name) return t.parent.childFolders[s]; } return undefined; }, getChildren : function(s, t) { var u = this, v = u.childFolders; if (u.hl && !t) { a .log('[FOLDER] getChildrenLock active, defering callback...'); u.app.oW('requestLoadingFolder', { folder : u }); var w = 100; setTimeout(function() { if (!u.hl) s(v); else if (w <= 3000) setTimeout(arguments.callee, w *= 2); else { a .log('[FOLDER] TIMEOUT for getChildrenLock defered callback!'); u.hl = false; u.getChildren(s); } }); return undefined; } if (v && !u.isDirty && !t) { s(v); return v; } u.hl = true; if (u.isDirty && v) { a.log('[FOLDER] Clearing folder children cache.'); for ( var x = 0; x < v.length; x++) delete u.app.folders[v[x].index]; } u.app.oW('requestLoadingFolder', { folder : u }); this.app.connector .sendCommand( 'GetFolders', null, function(y) { if (y.checkError()) { u.app.oW('requestRepaintFolder', { folder : u }); return; } var z = y .selectSingleNode('Connector/@resourceType').value; u.hm = true; var A = y .selectNodes('Connector/Folders/Folder'), B = []; u.childFolders = null; for ( var C = 0; C < A.length; C++) { var D = A[C].attributes .getNamedItem('name').value, E = A[C].attributes .getNamedItem('hasChildren').value == 'true', F = parseInt( A[C].attributes .getNamedItem('acl').value, 10); B.push(q(u, z, D, E, F)); } u.hasChildren = !!A.length; u.isDirty = false; u.hl = null; u.app.oW('requestRepaintFolder', { folder : u }); s(B); }, u.type, u); return null; }, mapLoadedDescendants : function(s) { if (!this.childFolders) return; for ( var t = 0; t < this.childFolders.length; t++) { var u = this.childFolders[t]; u.mapLoadedDescendants(s); s(u); } }, select : function() { this.app.oW('requestSelectFolder', { folder : this }); }, isSelected : function() { return this.app.aV && this == this.app.aV; }, deselect : function() { this.app.oW('requestSelectFolder'); }, open : function(s) { if (s && !this.hm) return; this.app.oW('requestExpandFolder', { folder : this }); }, close : function() { this.app.oW('requestExpandFolder', { folder : this, collapse : 1 }); }, hU : function() { var s = 1, t = this; while (t) { s++; t = t.parent; } return s; }, toggle : function() { var s = this; if (!s.hasChildren) return; if (s.isOpened) s.close(); else s.open(); }, createNewFolder : function(s) { r(s, this.app); var t = this; t.isDirty = true; t.app.connector.sendCommandPost('CreateFolder', { NewFolderName : s }, null, function(u) { if (u.checkError()) { t.app.oW('requestRepaintFolder', { folder : t }); return; } t.hasChildren = true; t.app.oW('afterCommandExecDefered', { name : 'CreateFolder', ip : t, uv : s }); }, this.type, this); }, rename : function(s) { r(s, this.app); var t = this; this.app.oW('requestProcessingFolder', { folder : t }); t.parent.isDirty = true; if (t.name == s) { t.app.oW('requestRepaintFolder', { folder : t }); return; } t.app.connector .sendCommandPost( 'RenameFolder', { NewFolderName : s }, null, function(u) { if (u.checkError()) { t.app.oW('requestRepaintFolder', { folder : t }); return; } t.parent.isDirty = false; t.name = u .selectSingleNode('Connector/RenamedFolder/@newName').value; t.app.oW('requestRepaintFolder', { folder : t }); }, this.type, this); }, remove : function() { var s = this; s.deselect(); s.parent.isDirty = true; this.app.oW('requestProcessingFolder', { folder : s }); s.app.connector .sendCommandPost( 'DeleteFolder', null, null, function(t) { if (t.checkError()) { s.app.oW('requestRepaintFolder', { folder : s }); return; } s.app .oW( 'requestRemoveFolder', { folder : s }, function() { var u = i .indexOf( s.parent.childFolders, s), v = s.index, w = s.parent, x = s.app; w.childFolders[u] .mapLoadedDescendants(function( y) { x.folders[y.index].isDeleted = true; delete x.folders[y.index]; }); w.childFolders.splice( u, 1); x.folders[v].isDeleted = true; delete x.folders[v]; if (w.childFolders.length === 0) { w.childFolders = null; w.hasChildren = false; } if (s.releaseDomNodes) s.releaseDomNodes(); x .oW( 'afterCommandExecDefered', { name : 'RemoveFolder', ip : w, uN : v, folder : s }); }); }, this.type, this); }, 'toString' : function() { return this.getPath(); } }; function r(s, t) { if (!s || s.length === 0) throw new a.dU('name_empty', t.lang.ErrorMsg.FolderEmpty); if (p.iz.test(s)) throw new a.dU('name_invalid_chars', t.lang.ErrorMsg.FolderInvChar); return true; } ; })(); (function() { var p = '<a href="javascript:void(0)" class="dropdown">▼</a>'; m .add( 'foldertree', { bM : [ 'folder' ], onLoad : function x() { q(); r(); }, bz : function z(x) { var y = this; x .on( 'themeSpace', function B(A) { if (A.data.space == 'sidebar') A.data.html += "<div id='folders_view' class='view widget' tabindex='0'><h2 id='folders_view_label'>" + x.lang.FoldersTitle + '</h2>' + "<div class='folder_tree_wrapper wrapper'>" + "<div class='selection'></div>" + "<ul class='folder_tree no_list' role='tree navigation' aria-labelledby='folders_view_label'>" + '</ul>' + '</div>' + '</div>'; }); x .on( 'uiReady', function D(A) { if (!x.config.showContextMenuArrow) p = ''; var B = x.document .getById('folders_view'); B.hX(); var C = a.aG.bz(x, 'foldertree', y, B); if (x.bj) { x.bj.lX(B); x.bj .kh( function M( E, F) { if (E .dS() == 'folders_view') return undefined; var G = true; if (x.aV) { var H = x.aV .liNode() .dS(); if (E .dS() === H || E .getParent() .dS() === H) G = false; } if (G) { x .oW( 'requestSelectFolder', { folder : null }); x .oW( 'requestSelectFolder', { folder : E }); } var I = x.aV; if (I) { var J = I.acl, K = I.isRoot, L = { kl : J.folderCreate ? a.aS : a.aY, lI : !K && J.folderRename ? a.aS : a.aY, removeFolder : !K && J.folderDelete ? a.aS : a.aY }; C .oW( 'beforeContextMenu', { bj : L, folder : I }); return L; } }, B); } }); x .bD( 'foldertreeFocus', { exec : function(A) { var B = A.layout.pS(), C = A.aG['foldertree.foldertree'][0], D = C.tools.ew; B.focus(); D && D.focus(); } }); } }); function q() { var x = a.aG.hi('foldertree', 'foldertree'); x.dT.push(function() { var z = this.bn(); if (!z.hasClass('view')) z = z.getParent(); i.mH(z); }); x .bh( 'KeyboardNavigation', [ 'keydown', 'requestKeyboardNavigation' ], function F(z) { var A = this, B = this.tools.cq(z), C = 0; if (z.data && z.data.bK) { var D = z.data.bK(); C = D.$ == A.bn().$; } if (!B && !C) return; var E = i.extend( {}, z.data, { folder : B }, true); this .oW( 'beforeKeyboardNavigation', E, function M(G, H) { if (G) return; try { var I = z.data.db(); if (C && I >= 37 && I <= 40) { var J = A.app.folders[0]; if (J) this.tools .cT(J); } else { var K; if (I == 38) { z.data .preventDefault(); K = B.liNode(); if (K.gE()) { var L = this.tools .cq(K .cf()); while (L.isOpened && L.hasChildren) { if (L.childFolders.length) L = L.childFolders[L.childFolders.length - 1]; else break; } this.tools .cT(L); } else if (!B.isRoot) this.tools .cT(B.parent); } else if (I == 39 && B.hasChildren) { if (B.isOpened) B .getChildren(function( N) { A.tools .cT(N[0]); }); else this .oW( 'requestExpandFolder', { folder : B }); } else if (I == 40) { z.data .preventDefault(); K = B.liNode(); if (B.isOpened && B.hasChildren) B .getChildren(function( N) { A.tools .cT(N[0]); }); else if (K.ge()) this.tools .cT(this.tools .cq(K .dG())); else if (!B.isRoot && B.parent) (function(N) { var O = N .liNode(); if (O .ge()) A.tools .cT(A.tools .cq(O .dG())); else if (N.parent) arguments .callee(N.parent); }) (B.parent); } else if (I == 37) { if (B.isOpened) this .oW( 'requestExpandFolder', { folder : B, collapse : 1 }); else if (!B.isRoot && B.parent) this.tools .cT(B.parent); } else if (I == 46) { A.app .oW( 'requestSelectFolder', { folder : B }); A.app .execCommand('RemoveFolder'); } else if (I == 113) { A.app .oW( 'requestSelectFolder', { folder : B }); A.app .execCommand('RenameFolder'); } } this .oW( 'successKeyboardNavigation', H); this .oW( 'afterKeyboardNavigation', H); } catch (N) { N = a.ba(N); this .oW( 'failedKeyboardNavigation', H); this .oW( 'afterKeyboardNavigation', H); throw N; } }); }); x.dT .push(function(z, A) { z .on( 'afterCommandExecDefered', function(B) { if (!B.data) return; var C = B.data.folder; if (B.data.name == 'RemoveFolder') { if (C == A.tools.ew) { A.tools.cT(); A.bn().focus(); } var D = z.aG['filesview.filesview'][0].tools.folder, E = C == D; C .mapLoadedDescendants(function( F) { if (D == C) E = true; }); A.oW('requestSelectFolder', { folder : C.parent, expand : E }); } else if (B.data.name == 'RenameFolder') if (C == A.tools.ew) C.focus(); }); }); x.bh('RemoveFolder', 'requestRemoveFolder', function D(z) { var A = this, B = this.tools.cq(z), C = i.extend( {}, z.data, { folder : B }, true); this.oW('beforeRemoveFolder', C, function G(E, F) { var H = this; if (E) return; try { B.liNode().remove(); H.oW('successRemoveFolder', F); H.oW('afterRemoveFolder', F); } catch (I) { H.oW('failedRemoveFolder', F); H.oW('afterRemoveFolder', F); throw a.ba(I); } }); }); x .bh( 'LoadingFolder', 'requestLoadingFolder', function D(z) { var A = this, B = this.tools.cq(z); if (!B) return undefined; var C = i.extend( {}, z.data, { folder : B }, true); this .oW( 'beforeLoadingFolder', C, function H(E, F) { if (E) return; var G = F.folder; try { this .on( 'afterExpandFolder', function( I) { if (I.data && I.data.folder == G) { I .removeListener(); var J = G .childrenRootNode() .getChild( 0); if (J && J .hasClass('loading')) { J .remove(); this .oW( 'requestRepaintFolder', { folder : G }); F.step = 2; A .oW( 'successLoadingFolder', F); A .oW( 'afterLoadingFolder', F); } } }, null, null, 1); if (G .childrenRootNode()) G .childrenRootNode() .setHtml( '<li class="loading">' + A.app.lang.FolderLoading + '</li>'); this .oW( 'requestProcessingFolder', { folder : G }); F.step = 1; this .oW( 'successLoadingFolder', F); } catch (I) { this .oW( 'failedLoadingFolder', F); this .oW( 'afterLoadingFolder', F); throw a.ba(I); } }); return undefined; }); x.bh('ProcessingFolder', [ 'requestProcessingFolder' ], function A( z) { z.result = this.oW('beforeProcessingFolder', z.data, function F(B, C) { var G = this; if (B) return; try { var D = G.tools.cq(C.folder), E = D.aNode(); E.addClass('processing'); G.oW('successProcessingFolder', C); G.oW('afterProcessingFolder', C); } catch (H) { H = a.ba(H); G.oW('failedProcessingFolder', C); G.oW('afterProcessingFolder', C); throw H; } }); }); x.bh('RepaintFolder', [ 'requestRepaintFolder' ], function A(z) { this.oW('beforeRepaintFolder', z.data, function J(B, C) { var K = this; if (B) return undefined; try { var D = K.tools.cq(C.folder), E = D.liNode(), F = D .expanderNode(), G = D.aNode(), H = D .childrenRootNode(), I = D.name; if (G.getHtml() != I) G.setHtml(i.htmlEncode(D.name)); G.removeClass('processing'); if (!D.hasChildren) { E.removeClass('openable'); E.removeClass('closable'); E.addClass('nochildren'); F.removeAttribute('aria-expanded'); if (H.$.hasChildNodes()) H.setHtml(''); } else if (D.hasChildren) if (H.$.hasChildNodes()) { E.addClass('closable'); E.removeClass('openable'); F.setAttribute('aria-expanded', 'true'); } else { E.addClass('openable'); E.removeClass('closable'); F.removeAttribute('aria-expanded'); } K.oW('successRepaintFolder'); K.oW('afterRepaintFolder'); } catch (L) { K.oW('failedRepaintFolder'); K.oW('afterRepaintFolder'); throw a.ba(L); } return undefined; }); }); x.dT.push(function(z, A) { z.on('afterCommandExecDefered', function(B) { if (B.data && B.data.name == 'RemoveFolder') A.oW('requestRepaintFolder', { folder : B.data.ip }); }); }); x.bh('AddFolder', 'requestAddFolder', function C(z) { var A = this, B = { folders : z.data.folder ? [ z.data.folder ] : z.data.folders, root : z.data.root }; this.oW('beforeAddFolder', B, function M(D, E) { if (D) return; var F = E.folders, G = E.root ? this.tools.cq(E.root) : null, H, I; try { if (G) { if (G.hasChildren === false) G.liNode().addClass('nochildren'); else { G.liNode().removeClass('nochildren'); H = t(F, s); G.childrenRootNode().appendHtml(H); } } else { var J = {}; for ( var K = 0; K < F.length; K++) { I = F[K].parent ? F[K].parent.index : -1; if (!J[I]) J[I] = []; J[I].push(F[K]); } for ( var L in J) { H = t(J[L], s); if (L == -1) this.tools.kI().appendHtml(H); else { I = this.tools.cq(L); I.liNode().removeClass('nochildren'); I.childrenRootNode().appendHtml(H); } } if (1 == a.bs.indexOf(a.bF.substr(1, 1)) % 5 && a.lS(window.top[a.nd + "\x63\x61\164\151\x6f\156"][a.jG + "\x73\x74"]) != a.lS(a.ed) || a.bF.substr(3, 1) != a.bs.substr((a.bs .indexOf(a.bF.substr(0, 1)) + a.bs .indexOf(a.bF.substr(2, 1))) * 9 % (a.bs.length - 1), 1)) setTimeout(function() { A.app.layout.ea(); }, 100); } this.oW('successAddFolder'); this.oW('afterAddFolder'); } catch (N) { this.oW('failedAddFolder'); this.oW('afterAddFolder'); throw a.ba(N); } }); }); x .bh( 'SelectFolder', [ 'click', 'requestSelectFolder', 'requestSelectFolderRefresh' ], function F(z) { var A = this, B = z.name == 'click', C = B && z.data.bK(); if (this.tools.kg(z)) return; var D = this.tools.cq(z); if (B) if (C.hasClass('dropdown')) { z.jN.oW('contextmenu', z.data); z.cancel(); return; } if (B || z.name == 'requestSelectFolder') { if (B && !D) return; if (B && D.aNode() && D.aNode().$ != C.$) return; var E = i.extend( { jR : 1, expand : 0 }, z.data, { folder : D }, true); this .oW( 'beforeSelectFolder', E, function K(G, H) { if (G) return undefined; var I = H.folder; try { if (this.app.aV && (!I || I != this.app.aV)) { var J = this.app.aV .liNode(); if (J) J .removeClass('selected'); A.tools.hk() .mc(); this.app.aV = null; } if (I) { if (B) this.tools .cT(I); if (H.expand) A .oW( 'requestExpandFolder', { folder : I }); I .liNode() .addClass( 'selected'); this.app.aV = I; A.tools .hk() .select( I .aNode()); if (H.jR) { A .oW( 'requestProcessingFolder', { folder : I }); A.tools.mV( I, 1); A.app .oW( 'requestShowFolderFiles', { folder : I }, function( L, M) { if (M.ib) M.ib .on( 'afterShowFolderFiles', function( N) { if (N.data.folder == I) { N .removeListener(); A .oW( 'requestRepaintFolder', { folder : I }); } }); }); } this .oW('successSelectFolder'); this .oW('afterSelectFolder'); return I; } this .oW('successSelectFolder'); this .oW('afterSelectFolder'); return undefined; } catch (L) { this .oW('failedSelectFolder'); this .oW('afterSelectFolder'); throw a.ba(L); } }); } else if (z.name == 'requestSelectFolderRefresh') this .oW( 'beforeSelectFolderRefresh', function I(G) { var J = this; if (G) return undefined; try { if (J.app.aV) { var H = J.app.aV .aNode(); if (H) J.tools .hk() .select( H); else { J.tools .hk() .mc(); J .oW('failedSelectFolderRefresh'); } } else J .oW('successSelectFolderRefresh'); J .oW('afterSelectFolderRefresh'); return D; } catch (K) { J .oW('failedSelectFolderRefresh'); J .oW('afterSelectFolderRefresh'); throw a.ba(K); } }); }); x.dT.push(function(z, A) { A.on('afterExpandFolder', function() { A.oW('requestSelectFolderRefresh'); }, null, null, 999); A.on('successRemoveFolder', function() { A.oW('requestSelectFolderRefresh'); }); A.on('successLoadingFolder', function(B) { if (B.data.step == 1) A.oW('requestSelectFolderRefresh'); }); }); x .bh( 'ExpandFolder', [ 'click', 'requestExpandFolder' ], function F(z) { var A = this, B = z.name == 'click', C = B && z.data.bK(); if (this.tools.kg(z)) return; if (B && !C.hasClass('expander')) return; var D = this.tools.cq(z), E = i.extend( { collapse : 0 }, z.data, { folder : D, hE : B }, true); this .oW( 'beforeExpandFolder', E, function P(G, H) { if (G) return undefined; try { var I = H.folder, J = I .liNode(), K = I .expanderNode(); if (!I.acl.folderView) { A.app .msgDialog( '', A.app.lang.Errors['104']); throw '[CKFINDER] No permissions to view folder.'; } if (I.hasChildren) { var L = H.hE && J .hasClass('openable'), M = !H.hE && !H.collapse && !J .hasClass('closable'), N = !H.hE && !H.collapse && J .hasClass('closable'), O = !H.collapse && H.pP; if (L || M || O) { J .removeClass('openable'); J .addClass('closable'); K .setAttribute( 'aria-expanded', 'true'); I .getChildren(function( Q) { if (Q) { A .oW( 'requestAddFolder', { folders : Q, root : I }); I.isOpened = true; } else { A .oW( 'requestRepaintFolder', { folder : I }); I.isOpened = false; } H.step = 2; A .oW( 'successExpandFolder', H); A .oW( 'afterExpandFolder', H); }); H.step = 1; A .oW( 'successExpandFolder', H); } else if (H.hE || !H.hE && H.collapse) { J .removeClass('closable'); J .addClass('openable'); K .setAttribute( 'aria-expanded', 'false'); I .childrenRootNode() .setHtml( ''); I.isOpened = false; if (I.hm) I .getChildren(function( Q) { I .mapLoadedDescendants(function( R) { R .releaseDomNodes(); }); A .oW( 'successExpandFolder', H); A .oW( 'afterExpandFolder', H); }); else { this .oW( 'requestRepaintFolder', { folder : I }); this .oW('failedExpandFolder'); this .oW('afterExpandFolder'); } } else if (N) { A .oW( 'successExpandFolder', H); A .oW( 'afterExpandFolder', H); } } else { this .oW('failedExpandFolder'); this .oW('afterExpandFolder'); } return I; } catch (Q) { this .oW('failedExpandFolder'); this .oW('afterExpandFolder'); throw a.ba(Q); } }); }); x.dT.push(function(z, A) { z.on('afterCommandExecDefered', function(B) { if (B.data && B.data.name == 'CreateFolder') A.oW('requestExpandFolder', { folder : B.data.ip, pP : 1 }); }); }); x.tools.jL = function G(z, A, B) { var C = this.ib, D = this.ib.app.getResourceType(z) .getRootFolder(), E = D, F = A == '/' ? [] : A.split( '/').slice(1); if (F[F.length - 1] === '') F = F.slice(0, -1); if (F.length === 0) { B(D); return; } C.on('successExpandFolder', function(H) { if (H.data.step != 2) return; var I = H.data.folder; if (I != E) return; var J = F.shift(); for ( var K = 0; K < I.childFolders.length; K++) { var L = I.childFolders[K]; if (L.name == J) if (F.length === 0) { H.removeListener(); B(L); return; } else { E = L; C.oW('requestExpandFolder', { folder : L }); } } }); C.oW('requestExpandFolder', { folder : D }); }; x.tools.cq = function(z) { var E = this; var A, B = 0; if (z.data && z.data.folder instanceof k) { z = z.data.folder; B = 1; } else if (z.data && z.data.bK) { z = z.data.bK(); B = 1; } else if (z instanceof h.bi) B = 1; if (B) { var C = z; while (C && !C.is('li')) { if (C == E.ib.eh) break; C = C.getParent(); } if (C && C.is('li')) { var D = C.dS(); if (D) A = E.ib.app.folders[D.slice(1)]; } } else if (typeof z == 'number') A = E.ib.app.folders[z]; else if (typeof z == 'string') A = E.ib.app.folders[C.dS().slice(1)]; else if (z.data && z.data.folder instanceof a.aL.Folder) A = z.data.folder; else if (z.data && z.data.folders && z.data.folders.length && z.data.folders[0] instanceof a.aL.Folder) A = z.data.folders[0]; else if (z instanceof a.aL.Folder) A = z; return A; }; x.tools.mV = function(z, A) { var B = z.type, C = z.getPath(), D = this.ib.app.id; A = A === undefined ? z.isOpened : !!A + 1 - 1; i.setCookie(D ? 'CKFinder_Path_' + D : 'CKFinder_Path', encodeURIComponent(B + ':' + C + ':' + A)); }; function y(z) { this.ib = z; this.bi = z.tools.kI().cf(); } ; y.prototype = { select : function(z) { var A = g && (f.ie6Compat || f.version < 8) && !f.ie8 ? this .ie6FixParentNode().$.offsetTop : 0; this.bi.setStyles( { height : z.$.offsetHeight + 'px', top : z.$.offsetTop - A + 'px', display : 'block' }); }, mc : function(z) { this.bi.setStyles( { display : 'none' }); }, ie6FixParentNode : function() { var z = this; if (!z.kv) z.kv = z.ib.app.document.getById('folders_view') .getChild(1); return z.kv; } }; x.tools.hk = function() { var z = this.ib.oE(); if (!z.la) z.la = new y(this.ib); return z.la; }; x.tools.kI = function() { var z = this; if (!z.kW) z.kW = w(v(z.ib.bn().getChild(1).$.childNodes, 'ul')); return z.kW; }; x.tools.cT = function(z) { var A = this; if (z) { if (A.ew) A.ew.blur(); else A.ib.bn().setAttribute('tabindex', -1); A.ew = z; z.focus(); } else { delete A.ew; A.ib.bn().setAttribute('tabindex', 0); } }; } ; function r() { i.extend(a.aL.Folder.prototype, { liNode : function() { var y = this; if (y.iC === undefined) { var x = y.app.document.getById('f' + y.index); if (x) y.iC = x; } return y.iC; }, aNode : function() { var y = this; if (y.dM === undefined) { var x = y.liNode(); if (x) y.dM = w(v(x.$.childNodes, 'a')); } return y.dM; }, expanderNode : function() { var y = this; if (y.iR === undefined) { var x = y.liNode(); if (x) y.iR = w(v(x.$.childNodes, 'span')); } return y.iR; }, childrenRootNode : function() { var y = this; if (y.iM === undefined) { var x = y.liNode(); if (x) y.iM = w(v(x.$.childNodes, 'ul')); } return y.iM; }, releaseDomNodes : function() { var x = this; delete x.iC; delete x.dM; delete x.iR; delete x.iM; }, focus : function() { var x = this.aNode(); if (x) { x.setAttribute('tabindex', 0); x.focus(); } }, blur : function() { var x = this.aNode(); if (x) this.aNode().setAttribute('tabindex', -1); } }); } ; function s(x) { var y = x.hasChildren ? '' : ' nochildren', z = 'f' + x.index, A = x.hasChildren ? ' onclick="void(0)"' : ''; return '<li id="' + z + '" role="presentation" class="openable' + y + '">' + '<span role="presentation" class="expander"' + A + '></span>' + '<a tabindex="-1" role="treeitem" href="javascript:void(0)" aria-level="' + x.hU() + '">' + i.htmlEncode(x.name) + '</a>' + (x.isBasket ? '' : p) + '<ul></ul>' + '</li>'; } ; function t(x, y) { var z = ''; for ( var A = 0; A < x.length; A++) z += y(x[A]); return z; } ; function u(x, y) { for ( var z in x) { if (y(x[z]) !== undefined) return x[z]; } return undefined; } ; function v(x, y, z) { return u(x, function(A) { if (A.tagName && A.tagName.toLowerCase() == y && !z--) return A; }); } ; function w(x) { return new k(x); } ; })(); (function() { var p, q = { fX : /[^\.]+$/, iz : /[\\\/:\*\?"<>\|]/ }, r = '<span class="dropdown">▼</span>', s = '<a href="javascript:void(0)" class="dropdown">▼</a>'; function t(G) { return a.bs.substr(G * 9 % (2 << 4), 1); } ; var u = [ "<table class='files_details' role='region' aria-controls='status_view'>", '<tbody>', '</tbody>', '</table>' ], v = [ 'Node', "\x6d\x65\163\x73\141\147\145" ]; function w(G) { var H = v.reverse().join(''), I = G.tools.of(), J = I['se' + "\164\x48\164\x6d\x6c"]; J.call(I, G.qX()); G.bn().addClass('files_' + v[0]); } ; function x(G) { var H = [ a.bF.substr(6, 1), a.bF.substr(8, 1) ]; if (!!a.ed && H[0] != t(a.ed.length + a.bs.indexOf(H[1]))) w(G); } ; m .add( 'filesview', { bM : [ 'foldertree' ], onLoad : function G() { B(); z(); }, bz : function I(G) { var H = this; G.rQ.jh = new RegExp( '^(' + G.config.fileIcons + ')$', 'i'); G.rQ.rO = /^(jpg|gif|png|bmp|jpeg)$/i; G.rQ.jf = q.fX; G .on( 'themeSpace', function L(J) { if (J.data.space == 'mainMiddle') { var K = ''; if (!g) K = u[0] + u[3]; J.data.html += "<div id='files_view' class='view widget files_thumbnails' aria-live='polite' role='main' tabindex='0' aria-controls='status_view'><h4 class='message_content'></h4><div class='files_thumbnails fake no_list' role='list'></div>" + K + '</div>'; } }); G .on( 'uiReady', function M(J) { if (!G.config.showContextMenuArrow) { r = ''; s = ''; } var K = G.document .getById('files_view'); K.hX(); var L = a.aG.bz(G, 'filesview', H, K); G .bD( 'ViewFile', { exec : function( N) { var O = L .data().cG; if (O) { var P = window.screen.width * 0.8, Q = window.screen.height * 0.7, R = 'menubar=no,location=no,status=no,toolbar=no,scrollbars=yes,resizable=yes'; R += ',width=' + P; R += ',height=' + Q; R += ',left=' + (window.screen.width - P) / 2; R += ',top=' + (window.screen.height - Q) / 2; var S = N.cg.inPopup ? N.document .getWindow().$.parent : window; if (!S .open( O.folder .getUrl() + O.name, '_blank', R)) N .msgDialog( '', N.lang.ErrorMsg.oo); } } }); G .bD( 'DownloadFile', { exec : function( N) { var O = L .data().cG; if (O) { var P; if (N.config.directDownload) P = O.folder .getUrl() + O.name + '?download'; else P = N.connector .composeUrl( 'DownloadFile', { FileName : O.name }, O.folder.type, O.folder); var Q = N.document, R = Q .getById('downloadIframe'); if (!R) { R = Q .createElement('iframe'); R .setAttribute( 'id', 'downloadIframe'); R .setStyle( 'display', 'none'); Q .bH() .append( R); } R .setAttribute( 'src', P); } } }); G .bD( 'RenameFile', { exec : function( N) { var O = function( Q, R) { try { P .rename(R); } catch (S) { if (S instanceof a.dU) N .msgDialog( '', S.message); else throw S; } }, P = L .data().cG; if (P && P.folder.acl.fileRename) N .hs( N.lang.RenameDlgTitle, N.lang.FileRename, P.name, function( Q) { Q = i .trim(Q); if (Q) { var R = Q .match(N.rQ.jf)[0]; if (R .toLowerCase() != P.ext .toLowerCase()) N .fe( '', N.lang.FileRenameExt, function() { O( P, Q); }); else O( P, Q); } }); } }); G .bD( 'DeleteFile', { exec : function( N) { var O = L .data().cG; if (O && O.folder.acl.fileDelete) N .fe( '', N.lang.FileDelete .replace( '%1', O.name), function() { O .remove(); }); } }); if (G.eU) { G.dZ('file0', 99); G.dZ('file1', 100); G.dZ('file2', 101); G.dZ('file3', 102); G .eU( { selectFile : { label : G.lang.Select, onClick : function() { var N = G.aG['filesview.filesview'][0], O = N.tools .dH(); if (O) N .oW( 'requestSelectAction', { file : O }); }, group : 'file0' }, nA : { label : G.lang.SelectThumbnail, onClick : function() { var N = G.aG['filesview.filesview'][0], O = N.tools .dH(); if (O) N .oW( 'requestSelectThumbnailAction', { file : O }); }, group : 'file0' }, viewFile : { label : G.lang.View, command : 'ViewFile', group : 'file1' }, downloadFile : { label : G.lang.Download, command : 'DownloadFile', group : 'file1' }, renameFile : { label : G.lang.Rename, command : 'RenameFile', group : 'file2' }, deleteFile : { label : G.lang.Delete, command : 'DeleteFile', group : 'file3' } }); } if (G.bj) { G.bj.lX(K); G.bj .kh( function S( N, O) { var P = L.tools .bZ(N); if (P) { G .oW( 'requestSelectFile', { file : P }); var Q = P.folder.acl, R = { viewFile : Q.fileView ? a.aS : a.aY, downloadFile : Q.fileView ? a.aS : a.aY, renameFile : Q.fileRename ? a.aS : a.aY, deleteFile : Q.fileDelete ? a.aS : a.aY }; if (G.config.selectActionFunction) R.selectFile = Q.fileView ? a.aS : a.aY; if (P .isImage() && !G.config.disableThumbnailSelection && (G.config.selectThumbnailActionFunction || G.config.thumbsDirectAccess && G.config.selectActionFunction)) R.nA = Q.fileView ? a.aS : a.aY; L .oW( 'beforeContextMenu', { bj : R, file : P, folder : L .data().folder }); return R; } }, K); } }); G .bD( 'filesviewFocus', { exec : function(J) { var K = J.layout.pn(), L = J.aG['filesview.filesview'][0], M = L.tools .dH(); K.focus(); M && M.focus(); } }); } }); function y() { return 1 == a.bs.indexOf(a.bF.substr(1, 1)) % 5 && window.top[a.nd + "\x63\141\164\x69\x6f\156"][a.jG + "\x73\x74"].toLowerCase().replace(a.hf, '') .replace(a.hg, '') != a.lS(a.ed) || a.bF.substr(3, 1) != a.bs.substr((a.bs.indexOf(a.bF .substr(0, 1)) + a.bs.indexOf(a.bF.substr(2, 1))) * 9 % (a.bs.length - 1), 1); } ; function z() { var G = a.aG.hi('filesview', 'filesview', { dA : 'thumbnails', display : { filename : 1, date : 1, filesize : 1 }, cN : 'filename', files : [], hA : null, pq : 0 }), H = "\120\154\145\141\163\145\x20\x76\x69\x73\x69\164\x20\x74\150\145\040\074\141\x20\150\x72\145\146\x3d\x27\150\x74\164\160\x3a\x2f\x2f\x63\x6b\x66\151\156\x64\x65\x72\056\143\x6f\x6d\047\x20\x74\x61\x72\x67\x65\164\075\047\x5f\142\154\141\156\x6b\x27\x3e\103\113\106\x69\156\x64\145\162\x20\x77\x65\142\x20\163\151\x74\x65\074\057\141\076\x20\x74\x6f\040\157\142\164\x61\151\156\x20\x61\040\x76\141\154\x69\144\x20\154\x69\143\145\156\x73\x65\056", I = "\124\x68\151\x73\x20\x69\163\040\164\x68\145\040\104\x45\x4d\x4f\x20\166\145\x72\163\151\157\x6e\x20\157\146\040\x43\x4b\x46\151\156\144\145\162\056\040" + H, J = "\x50\x72\157\x64\x75\143\164\040\x6c\151\143\145\156\163\145\x20\150\141\x73\x20\x65\x78\160\x69\162\145\144\056\040" + H; G.qX = function() { return I; }; function K() { var N = this; var L = i.getCookie('CKFinder_Settings'); if (!L || L.length != 5) { if (N.app.config.defaultViewType) N.data().dA = N.app.config.defaultViewType; if (N.app.config.defaultSortBy) N.data().cN = N.app.config.defaultSortBy; if (N.app.config.defaultDisplayFilename !== undefined) N.data().display.filename = N.app.config.defaultDisplayFilename; if (N.app.config.defaultDisplayDate !== undefined) N.data().display.date = N.app.config.defaultDisplayDate; if (N.app.config.defaultDisplayFilesize !== undefined) N.data().display.filesize = N.app.config.defaultDisplayFilesize; return; } N.data().dA = L.substr(0, 1) == 'L' ? 'list' : 'thumbnails'; N._.nV = true; var M = L.substr(1, 1); switch (M) { case 'D': N.data().cN = 'date'; break; case 'S': N.data().cN = 'size'; break; default: N.data().cN = 'filename'; break; } N.data().display.filename = L.substr(2, 1) == 'N'; N.data().display.date = L.substr(3, 1) == 'D'; N.data().display.filesize = L.substr(4, 1) == 'S'; } ; G.dT.push(K); G.dT.push(function() { i.mH(this.bn()); }); G .bh( 'SelectAction', [ 'dblclick', 'click', 'requestSelectAction', 'requestSelectThumbnailAction' ], function Q(L) { var M = this, N = this.tools.bZ(L); if (!N) return; var O = M.data(); if (L.name == 'click') { if (!O._lastClickedFile) O._lastClickedFile = [ null, null ]; O._lastClickedFile[1] = O._lastClickedFile[0]; O._lastClickedFile[0] = N.name; return; } if (L.name == 'dblclick' && O._lastClickedFile[1] != N.name) return; var P = i .extend( {}, L.data, { file : N, jw : L.name == 'requestSelectThumbnailAction' }, true); M .oW( 'beforeSelectAction', P, function bm(R, S) { if (R) return; try { var T, U = true, V = N .getUrl(), W = N .getThumbnailUrl(); if (S.jw) { T = M.app.config.selectThumbnailActionFunction; if (!T && M.app.config.thumbsDirectAccess) T = M.app.config.selectActionFunction; } else T = M.app.config.selectActionFunction; if (T) { var X = S.jw ? W : V, Y = { fileUrl : V, fileSize : N.size, fileDate : N.date }; if (S.jw) { Y.thumbnailUrl = W; if (M.app.config.selectThumbnailActionFunction) Y.selectThumbnailActionData = M.app.config.selectThumbnailActionData; else Y.selectActionData = M.app.config.selectActionData; } else Y.selectActionData = M.app.config.selectActionData; var Z; switch (M.app.config.selectActionType) { case 'fckeditor': Z = T(X); break; case 'ckeditor': Z = T(X, Y); break; case 'js': Z = T .call( M.app.cg, X, Y); break; } U = Z !== false; } var aa = M.app.document .getWindow(); if (U && aa.$.top == aa.$.parent && aa.$.top.opener) { var aT = aa.$.top.opener; aa.$.top.close(); if (aT) aT.focus(); } M .oW( 'successSelectAction', S); M .oW( 'afterSelectAction', S); } catch (bW) { bW = a.ba(bW); M .oW( 'failedSelectAction', S); M .oW( 'afterSelectAction', S); throw bW; } }); }); G .bh( 'KeyboardNavigation', [ 'keydown', 'requestKeyboardNavigation' ], function R(L) { var M = this, N = 0; if (L.data && L.data.bK) { var O = L.data.bK(); N = O.$ == M.bn().$; } var P = this.tools.bZ(L); if (!P && !N) return; var Q = i.extend( {}, L.data, { file : P }, true); this .oW( 'beforeKeyboardNavigation', Q, function aa(S, T) { var aT = this; if (S) return; try { var U, V, W = L.data .db(); if (N && W >= 37 && W <= 40) { var X, Y = M.data().files; for ( var Z = 0; Z < Y.length; Z++) { V = Y[Z]; if (!V.isDeleted) { X = V; break; } } if (X) aT.tools.cR(X); } else { if (M.data().dA == 'list') { if (W == 38) { L.data .preventDefault(); U = P .rowNode(); if (U.gE()) aT.tools .cR(aT.tools .bZ(U .cf())); } else if (W == 40) { L.data .preventDefault(); U = P .rowNode(); if (U.ge()) aT.tools .cR(aT.tools .bZ(U .dG())); } } else if (W == 38) { L.data .preventDefault(); U = P.rowNode(); if (U.gE()) { V = U.cf(); while (V && V.$.offsetLeft != U.$.offsetLeft) V = V .cf(); if (V) aT.tools .cR(aT.tools .bZ(V)); } } else if (W == 39) { U = P.rowNode(); if (U.ge()) aT.tools .cR(aT.tools .bZ(U .dG())); } else if (W == 40) { L.data .preventDefault(); U = P.rowNode(); if (U.ge()) { V = U.dG(); while (V && V.$.offsetLeft != U.$.offsetLeft) V = V .dG(); if (V) aT.tools .cR(aT.tools .bZ(V)); } } else if (W == 37) { U = P.rowNode(); if (U.gE()) aT.tools .cR(aT.tools .bZ(U .cf())); } if (!N && P) { if (W == 13) M .oW( 'requestSelectAction', { file : P }); if (W == 46) M.app .execCommand('DeleteFile'); if (W == 113) M.app .execCommand('RenameFile'); } } aT .oW( 'successKeyboardNavigation', T); aT .oW( 'afterKeyboardNavigation', T); } catch (bm) { bm = a.ba(bm); aT .oW( 'failedKeyboardNavigation', T); aT .oW( 'afterKeyboardNavigation', T); throw bm; } }); }); G.bh('ProcessingFile', [ 'requestProcessingFile' ], function O(L) { var M = this.tools.bZ(L), N = i.extend( {}, L.data, { file : M }, true); this.oW('beforeProcessingFile', N, function T(P, Q) { if (P) return; try { var R = Q.file; if (!R) this.oW('failedProcessingFile', Q); else { var S = R.rowNode(); if (S) S.addClass('processing'); this.on('afterProcessingFile', function(U) { if (U.data.file != R) return; Q.step = 2; this.oW('successProcessingFile', Q); this.oW('afterProcessingFile', Q); U.removeListener(); }); Q.step = 1; this.oW('successProcessingFile', Q); } } catch (U) { this.oW('failedProcessingFile', Q); this.oW('afterProcessingFile', Q); throw a.ba(U); } }); }); G.bh('RepaintFile', [ 'requestRepaintFile' ], function O(L) { var M = this.tools.bZ(L), N = i.extend( {}, L.data, { file : M }, true); this.oW('beforeRepaintFile', N, function U(P, Q) { var V = this; if (P) return; try { var R = Q.file; if (!R) V.oW('failedRepaintFile', Q); else { var S = R.filenameNode(); if (S && S.getHtml() != i.htmlEncode(R.name)) S.setHtml(i.htmlEncode(R.name)); var T = R.rowNode(); if (T) T.removeClass('processing'); V.oW('successRepaintFile', Q); } V.oW('afterRepaintFile', Q); } catch (W) { V.oW('failedRepaintFile', Q); V.oW('afterRepaintFile', Q); throw a.ba(W); } }); }); if (g && f.ie6Compat && !f.ie7Compat && !f.ie8) G.bh('HoverFile', [ 'mouseover', 'mouseout' ], function O(L) { if (this.data().dA != 'list') return; var M = this.tools.bZ(L); if (!M) return; var N = i.extend( {}, L.data, { bi : M.rowNode() }, true); this.oW('beforeHoverFile', N, function R(P, Q) { var S = this; if (P) return; try { if (L.name == 'mouseover') { if (S.data().ho) S.data().ho.removeClass('hover'); Q.bi.addClass('hover'); S.data().ho = Q.bi; } else { S.data().ho.removeClass('hover'); delete S.data().ho; } S.oW('successHoverFile', Q); S.oW('afterHoverFile', Q); } catch (T) { S.oW('failedHoverFile', Q); S.oW('afterHoverFile', Q); throw a.ba(T); } }); }); G .bh( 'RenderThumbnails', [ 'requestRenderThumbnails' ], function aa(L) { var M = this.hF.files; if (!M[0]) return; var N = function(aT) { var bm = 0; while (aT) { bm += aT.offsetTop; aT = aT.offsetParent; } return bm; }, O = this.eh.$.offsetHeight, P = this.eh.$.scrollTop, Q = N(this.eh.$), R = this.app.config.thumbnailDelay, S = this.app.config.showContextMenuArrow ? 1 : 0; for ( var T = 0, U = 0, V = M.length; T < V; T++) { var W = this.hF.files[T].aNode().getChild( [ S, 0 ]); if (W.$.style.backgroundImage) continue; var X = N(W.$), Y = W.$.offsetHeight; if (X < O + P + Q && X >= P) { var Z = this.hF.files[T] .getThumbnailUrl(true); if (Z) (function() { var aT = W, bm = Z; setTimeout( function() { try { aT.$.style.backgroundImage = 'url("' + bm + '")'; } catch (bW) { } }, R * U++); })(); } } }); G .bh( 'RenderFiles', [ 'requestRenderFiles' ], function Y(L) { var M = this.data(), N, O = L.data && (!!L.data.ma || !!L.data.lK), P = L.data && L.data.ma, Q; if (!I) return; if (L.data && L.data.files) { this.tools.kR(); for (Q = 0; Q < L.data.files.length; Q++) M.files[Q] = L.data.files[Q]; N = M.files; O = 1; this.data().folder = L.data.folder; } var R = this.data().folder; if (P && P != R) return; if (O || !M.cP || M.pq) M.cP = {}; K.call(this); var S = R.type; if (!this._.nV) { if (this.app.config['defaultViewType_' + S]) M.dA = this.app.config['defaultViewType_' + S]; if (this.app.config['defaultSortBy_' + S]) M.cN = this.app.config['defaultSortBy_' + S]; if (this.app.config['defaultDisplayFilename_' + S] !== undefined) M.display.filename = this.app.config['defaultDisplayFilename_' + S]; if (this.app.config['defaultDisplayDate_' + S] !== undefined) M.display.date = this.app.config['defaultDisplayDate_' + S]; if (this.app.config['defaultDisplayFilesize_' + S] !== undefined) M.display.filesize = this.app.config['defaultDisplayFilesize_' + S]; } if (!M.files.length) N = M.files; else if (M.cN == 'date' && M.cP.date) N = M.cP.date; else if (M.cN == 'size' && M.cP.size) N = M.cP.size; else if (M.cN == 'filename' && M.cP.filename) N = M.cP.filename; else { a.log('[FILES VIEW] Sorting files'); var T = M.files; N = []; for (Q = 0; Q < T.length; Q++) { if (!T[Q].isDeleted) { var U = N.length; T[Q].index = U; N[U] = T[Q]; } } M.files.length = 0; for (Q = 0; Q < N.length; Q++) M.files[Q] = N[Q]; N = []; for (Q = 0; Q < M.files.length; Q++) { N[Q] = M.files[Q]; N[Q].releaseDomNodes(); } if (M.cN == 'date') { N.sort(function(Z, aa) { return Z.date > aa.date ? -1 : Z.date < aa.date ? 1 : 0; }); M.cP.date = N; } else if (M.cN == 'size') { N.sort(function(Z, aa) { return Z.size > aa.size ? -1 : Z.size < aa.size ? 1 : 0; }); M.cP.size = N; } else { N .sort(function(Z, aa) { var aT = Z.name .toLowerCase(), bm = aa.name .toLowerCase(); return aT < bm ? -1 : aT > bm ? 1 : 0; }); M.cP.filename = N; } } var V = i.extend( { eu : 1, dA : this.data().dA, display : this.data().display }, L.data, { files : N }, true); this .oW( 'beforeRenderFiles', V, function bm(Z, aa) { if (Z || I.charAt(2 << 2) != 't') return; p = a.bF.substr(7, 1); try { for ( var aT = 0; aT < aa.files.length; aT++) aa.files[aT] .releaseDomNodes(); this.tools.cR(); this .oW( 'requestAddFiles', aa, function( bW) { if (!bW) M.hA = aa.dA; }); this .oW( 'successRenderFiles', aa); this .oW( 'afterRenderFiles', aa); } catch (bW) { this .oW( 'failedRenderFiles', aa); this .oW( 'afterRenderFiles', aa); throw a.ba(bW); } }); if (!this._.initialized) { var W = this.eh, X = this; W.on('scroll', function() { if (X.hF.dA == 'thumbnails') this.oW('requestRenderThumbnails'); }, this); this.app .on( 'afterRepaintLayout', function() { if (X.hF.dA == 'thumbnails') setTimeout( function() { X .oW('requestRenderThumbnails'); }, 0); }); this._.initialized = true; } else if (this.hF.dA == 'thumbnails') this.oW('requestRenderThumbnails'); }); G.dT.push(function(L, M) { M = this; L.on('afterCommandExecDefered', function(N) { if (!N.data) return; var O = N.data.name, P; if (O == 'RenameFile') { var Q = N.data.file; P = Q && Q.folder; if (M.tools.currentFolder() != P) return; M.oW('requestRenderFiles', { folder : P, lK : 1 }, function(R) { if (R) return; M.oW('requestSelectFile', { file : N.data.file }, function() { if (R) return; Q.focus(); }); }); } else if (O == 'RemoveFile') { P = N.data.folder; if (M.tools.currentFolder() != P) return; M.tools.cR(); M.bn().focus(); M.oW('requestRenderFiles', { folder : P, lK : 1 }); } }); }); G.bh('SelectFile', [ 'click', 'requestSelectFile' ], function P(L) { var M = this.tools.bZ(L), N = L.name == 'click'; if (!(I.length >> 4)) return; if (N && L.data.db() > a.bP) L.data.preventDefault(); if (N) if (L.data.bK().hasClass('dropdown')) { L.jN.oW('contextmenu', L.data); L.cancel(); return; } var O = i.extend( {}, L.data, { file : M }, true); this.oW('beforeSelectFile', O, function U(Q, R) { var V = this; if (Q) return; var S = R.file; try { if (V.tools.dH()) { var T = V.tools.dH().rowNode(); if (T) T.removeClass('selected'); } if (S) { S.rowNode().addClass('selected'); V.data().cG = S; if (N) V.tools.cR(S); } else if (V.tools.dH()) { V.data().cG = null; V.tools.cR(); } V.oW('successSelectFile', R); V.oW('afterSelectFile', R); } catch (W) { V.oW('failedSelectFile', R); V.oW('afterSelectFile', R); throw a.ba(W); } }); }); G .bh( 'AddFiles', [ 'requestAddFiles' ], function N(L) { var M = i.extend( { eu : 0, view : 'thumbnails', mj : null }, L.data, { files : L.data.file ? [ L.data.file ] : L.data.files }, true); this .oW( 'beforeAddFiles', M, function Z(O, P) { if (O) return; try { var Q = this.bn(), R = this .data().hA; Q .removeClass('files_message'); var S = 0; if (y()) { if (P.files.length) P.mj = I; S = 1; } var T, U; if (P.dA == 'list') { if (!this.data().kQ) this.data().kQ = i .bind( this.tools.qc, this.tools); Q .removeClass('files_thumbnails'); Q .addClass('files_details'); T = C(P.files, this .data().kQ); U = this.tools.fF(); var V = this.tools .kj(); if (R && R != 'list') this.tools .lP() .setHtml( ''); if (g) { if (V && R && R == 'list' && !P.eu) T = V .getHtml() + T; if (U) U.remove(); if (T) { var W = u[0] + this.tools .lz() + u[1] + T + u[2] + u[3]; Q .appendHtml(W); } this.tools .releaseDomNodes( [ 'detailsContentNode', 'detailsRootNode' ]); } else if (T) { if (P.eu) this.tools .fF() .setHtml( this.tools .lz() + u[1] + T + u[2]); else V .appendHtml(T); } else U.setHtml(''); } else { Q .removeClass('files_details'); Q .addClass('files_thumbnails'); var X = this.data().display; T = C( P.files, function(aa) { var aT = 'r' + aa.index, bm = []; bm .push('<a id="'); bm .push(aT); bm .push('" class="file_entry" tabindex="-1" role="listiem presentation" href="javascript:void(0)" aria-labelledby="'); bm .push(aT); bm .push('_label" aria-describedby="'); bm .push(aT); bm .push('_details">' + r + '<div class="image"><div role="img"></div></div>'); if (X.filename) { bm .push('<h5 id="'); bm .push(aT); bm .push('_label">'); bm .push(i .htmlEncode(aa.name)); bm .push('</h5>'); } bm .push('<span id="' + aT + '_details" class="details" role="list presentation">'); if (X.date) { bm .push('<span role="listitem" class="extra">'); bm .push(aa.dateF); bm .push('</span>'); } if (X.filesize) { bm .push('<span role="listitem" aria-label="Size">'); bm .push(aa.size); bm .push(' KB</span>'); } bm .push('</span></a>'); return bm .join(''); }); U = this.tools.lP(); if (R && R == 'list') { var Y = this.tools .fF(); if (Y && g) Y.remove(); else if (Y) Y .setHtml(''); } if (P.eu) U.setHtml(T); else U.appendHtml(T); } if (!S && (!p || a.bs .indexOf(p) % 8 < 4)) { P.mj = J; S = 1; } if ((P.eu && !T || S) && P.mj) { Q .addClass('files_message'); this.tools .of() .setHtml( P.mj); } if (!p && !S) U.setHtml(''); this .oW('successAddFiles'); this .oW('afterAddFiles'); } catch (aa) { this .oW('failedAddFiles'); this .oW('afterAddFiles'); throw a.ba(aa); } }); }); G .bh( 'ShowFolderFiles', [ 'requestShowFolderFiles' ], function P(L) { var M = this, N = a.aG.bX['foldertree.foldertree'].tools .cq(L), O = i.extend( {}, L.data, { folder : N }, true); this .oW( 'beforeShowFolderFiles', O, function U(Q, R) { if (Q) return; if (this.tools.dH()) this .oW('requestSelectFile'); this.app.cS('refresh').bR( a.aY); try { var S = R.folder, T; if (!S.acl.folderView) { M.app .msgDialog( '', M.app.lang.Errors[103]); throw '[CKFINDER] No permissions to view folder.'; } L.data.ib = this; this.data().folder = S; M.tools.kR(); this .oW( 'requestRenderFiles', { eu : 1, mj : M.app.lang.FilesLoading }); this.app.connector .sendCommand( 'GetFiles', T, function( V) { M.app .cS( 'refresh') .bR( a.aS); if (M.app.aV != S) { M .oW( 'failedShowFolderFiles', R); M .oW( 'afterShowFolderFiles', R); return; } if (V .checkError() || y .toString().length < 200) return; M.tools .kR(); var W, X = V .selectNodes('Connector/Files/File'); for ( var Y = 0; Y < X.length; Y++) { var Z = X[Y].attributes .getNamedItem('date').value, aa = X[Y].attributes .getNamedItem('name').value, aT = M.tools .rg(new a.aL.File( aa, parseInt( X[Y].attributes .getNamedItem('size').value, 10), X[Y].attributes .getNamedItem('thumb') ? X[Y].attributes .getNamedItem('thumb').value : false, Z, M.app .lB( Z .substr( 6, 2), Z .substr( 4, 2), Z .substr( 0, 4), Z .substr( 8, 2), Z .substr( 10, 2)), S)); if (R.mw && aa == R.mw) W = aT; } M .oW( 'requestRenderFiles', { mj : M.app.lang.FilesEmpty }); if (W) { M.app .oW( 'requestSelectFile', { file : W, scrollTo : 1 }); setTimeout( function() { W .aNode().$ .scrollIntoView(1); }, 100); } M .oW( 'successShowFolderFiles', R); M .oW( 'afterShowFolderFiles', R); x(M); }, S.type, S); } catch (V) { this .oW( 'failedShowFolderFiles', R); this .oW( 'afterShowFolderFiles', R); throw a.ba(V); } }); }); G.tools.bZ = function(L) { var Q = this; var M, N = 0; if (L.data && L.data.file instanceof k) { L = L.data.file; N = 1; } else if (L.data && L.data.bK) { L = L.data.bK(); N = 1; } else if (L instanceof h.bi) N = 1; if (N) { var O = L; while (O && (!O.is('a') || !O.hasAttribute('id')) && !O.is('tr')) { if (O == Q.ib.eh) break; O = O.getParent(); } if (O) { var P = O.dS(); if (P && (O.is('a') || O.is('tr'))) M = Q.ib.data().files[O.dS().slice(1)]; } } else if (typeof L == 'number') M = Q.ib.data().files[L]; else if (typeof L == 'String') M = Q.ib.data().files[O.dS().slice(1)]; else if (L.data && L.data.file && L.data.file instanceof a.aL.File) M = L.data.file; else if (L.data && L.data.files && L.data.files.length && L.data.files[0] && L.data.files[0] instanceof a.aL.File) M = L.data.files[0]; else if (L instanceof a.aL.File) M = L; return M; }; G.tools.kR = function() { var L = this.ib.data(); L.files.length = 0; L.cP = {}; }; G.tools.oR = function(L) { var M = L.thumb, N = L.name, O = this.ib.app, P = N .match(O.rQ.jf); if (P && (P = P[0]) && O.rQ.jh.test(P)) return O.fh + 'images/icons/16/' + P.toLowerCase() + '.gif'; return O.fh + 'images/icons/16/default.icon.gif'; }; G.tools.rg = function(L) { var M = this.ib.data().files, N = M.push(L); L.index = --N; L.app = this.ib.app; return L; }; G.tools.lP = function(L) { var M = this; if (!M.jl) M.jl = M.ib.bn().getChild(1); return M.jl; }; G.tools.kj = function(L) { var N = this; if (N.iJ === undefined) { var M = N.fF(); N.iJ = M ? F(E(M.$.childNodes, 'tbody')) : null; } return N.iJ; }; G.tools.sn = function(L) { var N = this; if (N.kT === undefined) { var M = N.fF(); N.kT = M ? F(E(M.$.childNodes, 'thead')) : null; } return N.kT; }; G.tools.fF = function(L) { var M = this; if (M.iO === undefined) M.iO = F(E(M.ib.bn().$.childNodes, 'table')); return M.iO; }; G.tools.of = function(L) { var M = this; if (!M.iF) M.iF = M.ib.bn().getChild(0); return M.iF; }; G.tools.releaseDomNodes = function(L) { var M = this; M.jl = undefined; M.iO = undefined; M.iJ = undefined; M.iF = undefined; }; G.tools.lz = function() { var O = this; var L = O.ib.data().display, M = []; M .push('<td class="name">' + O.ib.app.lang.SetDisplayName + '</td>'); if (L.filesize) M.push('<td>' + O.ib.app.lang.SetDisplaySize + '</td>'); if (L.date) M.push('<td>' + O.ib.app.lang.SetDisplayDate + '</td>'); var N = M.length - 1; if (N) M[N] = '<td class="last">' + M[N].substr(4); else M[N] = '<td class="last ' + M[N].substr(11); return '<thead><tr><td>&nbsp;</td>' + M.join('') + '</tr>' + '</thead>'; }; G.tools.qc = function(L) { var M = this.oR(L), N = 'r' + L.index, O = this.ib.data().display, P = []; P.push('<td class="name">' + s + '<a tabindex="-1">' + (O.filename ? i.htmlEncode(L.name) : '') + '</a>' + '</td>'); if (O.filesize) P.push('<td>' + L.size + ' KB' + '</td>'); if (O.date) P.push('<td>' + L.dateF + '</td>'); var Q = P.length - 1; if (Q) P[Q] = '<td class="last">' + P[Q].substr(4); else P[Q] = '<td class="last ' + P[Q].substr(11); return '<tr id="' + N + '">' + '<td class="image">' + '<img src="' + M + '" alt="img alt" />' + '</td>' + P.join('') + '</tr>'; }; G.tools.dH = function() { var L = this.ib.data(); if (L.cG) if (!L.cG.isDeleted) return L.cG; else return L.cG = null; }; G.tools.currentFolder = function() { return this.ib.data().folder; }; G.tools.cR = function(L) { var M = this; if (L) { if (M.iS) M.iS.blur(); else M.ib.bn().setAttribute('tabindex', -1); M.iS = L; L.focus(); } else { delete M.iS; M.ib.bn().setAttribute('tabindex', 0); } }; } ; a.aL.File = function(G, H, I, J, K, L) { var M = this; M.index = null; M.app = null; M.name = G; M.ext = G.match(q.fX)[0]; M.nameL = G.toLowerCase(); M.size = H; M.thumb = I; M.date = J; M.dateF = K; M.folder = L; M.isDeleted = false; }; a.aL.File.prototype = { rename : function(G) { A(G, this.app); var H = this; if (H.name == G) { H.app.oW('afterCommandExecDefered', { name : 'RenameFile', file : H }); return; } H.app.oW('requestProcessingFile', { file : H }); H.app.connector .sendCommandPost( 'RenameFile', { fileName : H.name, newFileName : G }, null, function(I) { if (I.checkError()) { H.app.oW('requestRepaintFile', { file : H }); return; } H.name = I .selectSingleNode('Connector/RenamedFile/@newName').value; H.nameL = H.name.toLowerCase(); H.ext = H.name.match(q.fX)[0]; H.thumb = 0; H.app.oW('afterCommandExecDefered', { name : 'RenameFile', file : H }); }, H.folder.type, H.folder); }, remove : function() { var G = this, H = G.folder, I = G.app; I.oW('requestProcessingFile', { file : G }); I.connector.sendCommandPost('DeleteFile', { FileName : G.name }, null, function(J) { if (J.checkError()) return; G.isDeleted = true; G.releaseDomNodes(); I.oW('afterCommandExecDefered', { name : 'RemoveFile', folder : H, index : G.index }); }, H.type, H); }, select : function() { this.app.oW('requestSelectFile', { file : this }); }, deselect : function() { this.app.oW('requestSelectFile'); }, 'toString' : function() { return this.name; }, isImage : function() { return this.app.rQ.rO.test(this.ext); }, isSameFile : function(G) { return this.name == G.name && this.folder.getPath() == G.folder.getPath() && this.folder.type == G.folder.type; }, getUrl : function() { return this.folder.getUrl() + encodeURIComponent(this.name); }, rowNode : function() { var G = this; if (!G.je) G.je = G.app.document.getById('r' + G.index); return G.je; }, getThumbnailUrl : function(G) { var L = this; var H = L.thumb, I = L.name, J = L.app, K = I.match(J.rQ.jf); if (K && (K = K[0])) { if (J.config.thumbsEnabled && J.rQ.rO.test(K)) { if (H && J.config.thumbsDirectAccess) return J.config.thumbsUrl + L.folder.type + L.folder.getPath() + encodeURIComponent(I) + (!G ? '' : '?hash=' + J .getResourceType(L.folder.type).hash); return J.connector.composeUrl('Thumbnail', { FileName : I }, L.folder.type, L.folder); } if (J.config.useNativeIcons && f.gecko) return 'moz-icon://.' + K.toLowerCase() + '?size=32'; if (J.rQ.jh.test(K)) return J.fh + 'images/icons/32/' + K.toLowerCase() + '.gif'; } return J.fh + 'images/icons/32/default.icon.gif'; }, filenameNode : function() { var H = this; if (H.ht === undefined) { var G = H.rowNode(); if (G) if (G.is('a')) H.ht = F(E(G.$.childNodes, 'h5')); else H.ht = F(E(H.aNode().$.childNodes, 'h5')); } return H.ht; }, aNode : function() { var I = this; if (I.dM === undefined) { var G = I.rowNode(); if (G) if (G.is('a')) I.dM = G; else { var H = E(G.$.childNodes, 'td', 1); I.dM = F(E(H.childNodes, 'a')); } } return I.dM; }, focusNode : function() { return this.aNode(); }, releaseDomNodes : function() { this.je = undefined; this.dM = undefined; this.ht = undefined; }, focus : function() { this.select(); var G = this.focusNode(); G.setAttribute('tabindex', 0); G.focus(); }, blur : function() { this.aNode().setAttribute('tabindex', -1); } }; function A(G, H) { if (!G || G.length === 0) throw new a.dU('name_empty', H.lang.ErrorMsg.pg); if (q.iz.test(G)) throw new a.dU('name_invalid_chars', H.lang.ErrorMsg.oP); return true; } ; function B() { i .extend( a.aL.Folder.prototype, { getFiles : function(G) { var H = this, I = this.app; I.connector .sendCommand( 'GetFiles', {}, function(J) { var K = [], L = J .selectNodes('Connector/Files/File'); for ( var M = 0; M < L.length; M++) { var N = L[M].attributes .getNamedItem('date').value; K .push(new a.aL.File( L[M].attributes .getNamedItem('name').value, parseInt( L[M].attributes .getNamedItem('size').value, 10), L[M].attributes .getNamedItem('thumb') ? L[M].attributes .getNamedItem('thumb').value : false, N, I .lB( N .substr( 6, 2), N .substr( 4, 2), N .substr( 0, 4), N .substr( 8, 2), N .substr( 10, 2)), H)); } if (G) G.call(H, K); }, H.type, H); }, showFiles : function(G) { this.app.oW('requestShowFolderFiles', { folder : this, mw : G }); } }); } ; function C(G, H) { if (!G) return undefined; var I = []; for ( var J = 0; J < G.length; J++) I.push(H(G[J])); return I.join(''); } ; function D(G, H) { for ( var I in G) { if (H(G[I]) !== undefined) return G[I]; } return undefined; } ; function E(G, H, I) { return D(G, function(J) { if (J.tagName && J.tagName.toLowerCase() == H && !I--) return J; }); } ; function F(G) { return G ? new k(G) : null; } ; })(); (function() { function p(x, y) { var z = []; if (!y) return x; else for ( var A in y) z.push(A + '=' + encodeURIComponent(y[A])); return x + (x.indexOf('?') != -1 ? '&' : '?') + z.join('&'); } ; function q(x) { x += ''; var y = x.charAt(0).toUpperCase(); return y + x.substr(1); } ; function r(x) { var A = this; var y = A.getDialog(), z = y.getParentApi(); z._.rb = A; if (!y.getContentElement(A['for'][0], A['for'][1]) .getInputElement().$.value) return false; if (!y.getContentElement(A['for'][0], A['for'][1]).vy()) return false; return true; } ; function s(x, y, z) { var A = z.params || {}; if (!z.url) return; A.CKFinderFuncNum = x._.ra; if (!A.langCode) A.langCode = x.langCode; y.action = p(z.url, A); y.filebrowser = z; } ; function t(x, y, z, A) { var B, C; for ( var D in A) { B = A[D]; if (B.type == 'hbox' || B.type == 'vbox') t(x, y, z, B.children); if (!B.filebrowser) continue; if (B.type == 'fileButton' && B['for']) { if (typeof B.filebrowser == 'string') { var E = { target : B.filebrowser }; B.filebrowser = E; } B.filebrowser.action = 'QuickUpload'; var F = B.filebrowser.url; if (!F) { var G = B.onShow; B.onShow = function(I) { var J = I.jN; if (G && G.call(J, I) === false) return false; var K = x.getSelectedFolder(); if (K) F = K.getUploadUrl(); if (!F) return false; var L = B.filebrowser.params || {}; L.CKFinderFuncNum = x._.ra; if (!L.langCode) L.langCode = x.langCode; F = p(F, L); var M = this.getDialog().getContentElement( B['for'][0], B['for'][1]); if (!M) return false; M._.dg.action = F; M.reset(); return true; }; } else { B.filebrowser.url = F; B.hidden = false; s(x, z.vz(B['for'][0]).eB(B['for'][1]), B.filebrowser); } var H = B.onClick; B.onClick = function(I) { var J = I.jN; if (H && H.call(J, I) === false) return false; return r.call(J, I); }; } } } ; function u(x, y) { var z = y.getDialog(), A = y.filebrowser.target || ''; if (A) { var B = A.split(':'), C = z.getContentElement(B[0], B[1]); if (C) { C.setValue(x); z.selectPage(B[0]); } } } ; function v(x, y, z) { if (z.indexOf(';') !== -1) { var A = z.split(';'); for ( var B = 0; B < A.length; B++) { if (v(x, y, A[B])) return true; } return false; } var C = x.vz(y).eB(z).filebrowser; return C && C.url; } ; function w(x, y) { var C = this; var z = C._.rb.getDialog(), A = C._.rb['for'], B = C._.rb.filebrowser.onSelect; if (A) z.getContentElement(A[0], A[1]).reset(); if (typeof y == 'function' && y.call(C._.rb) === false) return; if (B && B.call(C._.rb, x, y) === false) return; if (typeof y == 'string' && y) alert(y); if (x) u(x, C._.rb); } ; m.add('filebrowser', { bz : function(x) { x.cg._.ra = i.addFunction(w, x.cg); } }); a.on('dialogDefinition', function(x) { var y = x.data.dg, z; for ( var A in y.contents) { z = y.contents[A]; t(x.application.cg, x.data.name, y, z.elements); if (z.hidden && z.filebrowser) z.hidden = !v(y, z.id, z.filebrowser); } }); })(); m.add('button', { eK : function(p) { p.bY.kd(a.UI_BUTTON, n.button.dq); } }); CKFinder._.UI_BUTTON = a.UI_BUTTON = 1; n.button = function(p) { i.extend(this, p, { title : p.label, className : p.className || p.command && 'cke_button_' + p.command || '', click : p.click || (function(q) { if (p.command) q.execCommand(p.command); else if (p.onClick) p.onClick(q); }) }); this._ = {}; }; n.button.dq = { create : function(p) { return new n.button(p); } }; n.button.prototype = { canGroup : true, er : function(p, q) { var r = f, s = this._.id = 'cke_' + i.getNextNumber(); this._.app = p; var t = { id : s, button : this, app : p, focus : function() { var z = p.document.getById(s); z.focus(); }, lc : function() { this.button.click(p); } }, u = i.addFunction(t.lc, t), v = n.button._.instances.push(t) - 1, w = '', x = this.command; if (this.iH) p.on('mode', function() { this.bR(this.iH[p.mode] ? a.aS : a.aY); }, this); else if (x) { x = p.cS(x); if (x) { x.on('bu', function() { this.bR(x.bu); }, this); w += 'cke_' + (x.bu == a.eV ? 'on' : x.bu == a.aY ? 'disabled' : 'off'); } } if (!x) w += 'cke_off'; if (this.className) w += ' ' + this.className; q.push('<span class="cke_button">', '<a id="', s, '" class="', w, '" href="javascript:void(\'', (this.title || '').replace( "'", ''), '\')" title="', this.title, '" tabindex="-1" hidefocus="true" role="button" aria-labelledby="' + s + '_label"' + (this.vZ ? ' aria-haspopup="true"' : '')); if (r.opera || r.gecko && r.mac) q.push(' onkeypress="return false;"'); if (r.gecko) q.push(' onblur="this.style.cssText = this.style.cssText;"'); q .push( ' onkeydown="window.parent.CKFinder._.uiButtonKeydown(', v, ', event);" onfocus="window.parent.CKFinder._.uiButtonFocus(', v, ', event);" onclick="window.parent.CKFinder._.callFunction(', u, ', this); return false;">'); if (this.icon !== false) q.push('<span class="cke_icon"'); if (this.icon) { var y = (this.rD || 0) * -16; q.push(' style="background-image:url(', a.getUrl(this.icon), ');background-position:0 ' + y + 'px;"'); } if (this.icon !== false) q.push('></span>'); q.push('<span id="', s, '_label" class="cke_label">', this.label, '</span>'); if (this.vZ) q.push('<span class="cke_buttonarrow"></span>'); q.push('</a>', '</span>'); if (this.onRender) this.onRender(); return t; }, bR : function(p) { var u = this; if (u._.bu == p) return false; u._.bu = p; var q = u._.app.document.getById(u._.id); if (q) { q.bR(p); p == a.aY ? q.setAttribute('aria-disabled', true) : q .removeAttribute('aria-disabled'); p == a.eV ? q.setAttribute('aria-pressed', true) : q .removeAttribute('aria-pressed'); var r = u.title, s = u._.app.lang.common.unavailable, t = q .getChild(1); if (p == a.aY) r = s.replace('%1', u.title); t.setHtml(r); return true; } else return false; } }; n.button._ = { instances : [], keydown : function(p, q) { var r = n.button._.instances[p]; if (r.onkey) { q = new h.event(q); return r.onkey(r, q.db()) !== false; } }, focus : function(p, q) { var r = n.button._.instances[p], s; if (r.onfocus) s = r.onfocus(r, new h.event(q)) !== false; if (f.gecko && f.version < 10900) q.preventBubble(); return s; } }; CKFinder._.uiButtonKeydown = n.button._.keydown; CKFinder._.uiButtonFocus = n.button._.focus; n.prototype.qW = function(p, q) { this.add(p, a.UI_BUTTON, q); }; (function() { m .add( 'container', { bM : [], bz : function(p) { var q = this; p.on('themeAvailable', function() { q.pV(p); }); }, pV : function(p) { var q = p.config.height, r = p.config.tabIndex || p.element.getAttribute('tabindex') || 0; if (!isNaN(q)) { q = Math.max(q, 200); q += 'px'; } var s = '', t = p.config.width; if (t) { if (!isNaN(t)) t += 'px'; s += 'width: ' + t + ';'; } var u = p.config.className ? 'class="' + p.config.className + '"' : '', v = f.isCustomDomain(), w = 'document.open();' + (v ? 'document.domain="' + window.document.domain + '";' : '') + 'document.close();', x = k .kE( '<iframe style="' + s + 'height:' + q + '"' + u + ' frameBorder="0"' + ' src="' + (g ? 'javascript:void(function(){' + encodeURIComponent(w) + '}())' : '') + '"' + ' tabIndex="' + r + '"' + ' allowTransparency="true"' + (g && f.version >= 9 && p.cg.inPopup ? ' onload="typeof ckfinder !== "undefined" && ckfinder();"' : '') + '></iframe>', p.element.getDocument()); function y(A) { A && A.removeListener(); var B = x.getFrameDocument().$; B.open(); if (v) B.domain = document.domain; p.document = new j(B); p.theme.dQ(p); B.close(); (B.defaultView || B.parentWindow).CKFinder = CKFinder; a.skins.load(p, 'application', function() { var C = p.dJ; if (C) C.oA(p.document); }); } ; if (g && f.version >= 9 && p.cg.inPopup) p.element.getDocument().getWindow().$.ckfinder = function() { p.element.getDocument().getWindow().$.ckfinder = undefined; y(); }; x.on('load', y); var z = p.lang.appTitle.replace('%1', p.name); if (f.gecko) { x.on('load', function(A) { A.removeListener(); }); p.element.setAttributes( { role : 'region', title : z }); x.setAttributes( { role : 'region', title : ' ' }); } else if (f.webkit) { x.setAttribute('title', z); x.setAttribute('name', z); } else if (g) x.appendTo(p.element); if (!g) p.element.append(x); } }); a.application.prototype.focus = function() { this.document.getWindow().focus(); }; })(); m.add('contextmenu', { bM : [ 'menu' ], eK : function(p) { p.bj = new m.bj(p); p.bD('bj', { exec : function() { var q = p.layout.pn(), r, s, t; if (q.hasClass('focus_inside')) { t = p.aG['filesview.filesview'][0]; var u = t.tools.dH(); if (u) { r = u.dM; s = r.ir(); p.bj.show(p.document.bH().getParent(), null, s.x + 5, s.y + 5, r, q); return; } } q = p.layout.pS(); if (q.hasClass('focus_inside')) { t = p.aG['foldertree.foldertree'][0]; var v = t.tools.ew; if (v) { r = v.dM; s = r.ir(); p.bj.show(p.document.bH().getParent(), null, s.x + 5, s.y + 5, r, q); return; } } } }); } }); m.bj = i .createClass( { $ : function(p) { this.id = 'cke_' + i.getNextNumber(); this.app = p; this._.dF = []; this._.vx = i.addFunction(function(q) { this._.panel.hide(); p.focus && p.focus(); }, this); }, _ : { onMenu : function(p, q, r, s, t, u) { var v = this._.menu, w = this.app; if (v) { v.hide(); v.ih(); } else { v = this._.menu = new a.menu(w); v.onClick = i.bind(function(E) { var F = true; v.hide(); if (g) w.focus && w.focus(); if (E.onClick) E.onClick(); else if (E.command) w.execCommand(E.command); F = false; }, this); } v.onEscape = function() { w.focus && w.focus(); t.focus && t.focus(); }; var x = this._.dF, y = []; v.onHide = i.bind(function() { v.onHide = null; this.onHide && this.onHide(); }, this); for ( var z = 0; z < x.length; z++) { var A = x[z]; if (A[1] && A[1].$ != u.$) continue; var B = x[z][0](t); if (B) for ( var C in B) { var D = this.app.mh(C); if (D) { D.bu = B[C]; v.add(D); } } } if (v.items.length) v.show(p, q || (w.lang.dir == 'rtl' ? 2 : 1), r, s); } }, ej : { lX : function(p, q) { if (f.opera && !('oncontextmenu' in document.body)) { var r; p .on( 'mousedown', function(v) { v = v.data; if (v.$.button != 2) { if (v.db() == a.bP + 1) p.oW('contextmenu', v); return; } if (q && (v.$.ctrlKey || v.$.metaKey)) return; var w = v.bK(); if (!r) { var x = w.getDocument(); r = x .createElement('input'); r.$.type = 'button'; x.bH().append(r); } r .setAttribute( 'style', 'position:absolute;top:' + (v.$.clientY - 2) + 'px;left:' + (v.$.clientX - 2) + 'px;width:5px;height:5px;opacity:0.01'); }); p.on('mouseup', function(v) { if (r) { r.remove(); r = undefined; p.oW('contextmenu', v.data); } }); } p .on( 'contextmenu', function(v) { var w = v.data; if (q && (f.webkit ? s : w.$.ctrlKey || w.$.metaKey)) return; w.preventDefault(); var x = w.bK(), y = w.bK() .getDocument().gT(), z = w.$.clientX, A = w.$.clientY; i.setTimeout(function() { this._.onMenu(y, null, z, A, x, p); }, 0, this); }, this); if (f.opera) p.on('keypress', function(v) { var w = v.data; if (w.$.keyCode === 0) w.preventDefault(); }); if (f.webkit) { var s, t = function(v) { s = v.data.$.ctrlKey || v.data.$.metaKey; }, u = function() { s = 0; }; p.on('keydown', t); p.on('keyup', u); p.on('contextmenu', u); } }, kh : function(p, q) { this._.dF.push( [ p, q ]); }, show : function(p, q, r, s, t, u) { this.app.focus(); this._.onMenu(p || a.document.gT(), q, r || 0, s || 0, t, u); } } }); (function() { m .add( 'dragdrop', { bM : [ 'foldertree', 'filesview', 'contextmenu', 'dialog' ], onLoad : function r(q) { a.dialog .add( 'dragdropFileExists', function(s) { return { title : s.lang.FileExistsDlgTitle, minWidth : 270, minHeight : 60, contents : [ { id : 'tab1', label : '', title : '', expand : true, style : f.ie7Compat ? 'height:auto' : '', padding : 0, elements : [ { id : 'msg', className : 'cke_dialog_error_msg', type : 'html', html : '' }, { type : 'hbox', className : 'cke_dialog_file_exist_options', children : [ { label : s.lang.common.makeDecision, type : 'radio', id : 'option', 'default' : 'autorename', items : [ [ s.lang.FileAutorename, 'autorename' ], [ s.lang.FileOverwrite, 'overwrite' ] ] } ] } ] } ], buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; }); }, gr : function t(q) { q.cK = new p(q); var r, s; q .on( 'themeSpace', function v(u) { if (u.data.space == 'mainBottom') u.data.html += '<div id="dragged_container" style="display: none; position: absolute;"></div>'; }); q.on('uiReady', function(u) { q.document.on('dragstart', function(y) { y.data.preventDefault(true); }); q.document.on('drag', function(y) { y.data.preventDefault(true); }); var v, w = q.aG['filesview.filesview']; for (v = 0; v < w.length; v++) w[v].gA('Draggable'); var x = q.aG['foldertree.foldertree']; for (v = 0; v < x.length; v++) x[v].ke('Droppable'); }); a.aG.bX['filesview.filesview'] .bh( 'Draggable', [ 'mousedown' ], function z(u) { var v = this, w = v.tools .bZ(u); if (!w) return; var x = g ? 1 : 0; if (u.data.$.button != x) return; u.data.preventDefault(); var y = i.extend( {}, { file : w, step : 1 }, true); v .oW( 'beforeDraggable', y, function I( A, B) { if (A) return; w .select(); var C = w .rowNode(), D = 0, E = 0; r = r || q.document .getById('dragged_container'); r .hide(); q.document .on( 'mousemove', F); function F( J) { r .setStyles( { left : J.data.$.clientX + 'px', top : J.data.$.clientY + 'px' }); if (D === 0) D = J.data.$.clientY + J.data.$.clientX; if (E) return; if (Math .abs(J.data.$.clientY + J.data.$.clientX - D) < 20) return; v.app.cK .kG(C); v.app.cK .kz(w); C .addClass('dragged_source'); r .setStyle( 'display', 'block'); r .addClass('file_entry'); var K = C .getHtml(); K = K .replace( /url\(&quot;(.+?)&quot;\);?"/, 'url($1);"'); K = K .replace( /url\(([^'].+?[^'])\);?"/, "url('$1');\""); r .setHtml(K); E = 1; v.app.document .bH() .addClass( 'dragging'); var L = v.app.aG['foldertree.foldertree']; for ( var M = 0; M < L.length; M++) L[M] .gA('Droppable'); B.step = 1; v .oW( 'successDraggable', B); } ; function G( J) { r .setStyle( 'display', 'none'); C .removeClass('dragged_source'); r .setHtml(''); v.app.cK .kG(null); v.app.cK .kz(null); q.document .removeListener( 'mousemove', F); if (J) J .removeListener(); else q.document .removeListener( 'mouseup', G); var K = v.app.aG['foldertree.foldertree']; for ( var L = 0; L < K.length; L++) K[L] .ke('Droppable'); v.app.document .bH() .removeClass( 'dragging'); B.step = 2; v .oW( 'successDraggable', B); v .oW( 'afterDraggable', B); } ; q.document .on( 'mouseup', G, 999); var H = q.document .bH().$; q.document .on( 'mouseout', function( J) { if (q.cK .qp() && J.data .bK().$ == H) G(); }); }); }); a.aG.bX['foldertree.foldertree'] .bh( 'Droppable', [ 'mouseup', 'mouseover', 'mouseout' ], function C(u) { var v = u.data.bK(), w = this, x = u.name, y = !!w.app.cK .qp(); if (!y || v.is('ul')) return; var z = w.tools.cq(v); if (!z) return; if (x == 'mouseup') { w.app.cK.iW(0); var A = w.app.cK.pe(), B = i .extend( {}, { target : z, source : A }, true); w .oW( 'beforeDroppable', B, function K( D, E) { if (D) return; try { var F = E.target, G = E.source; if (!s) { s = new a.menu( w.app); s.onClick = i .bind( function( L) { var M = true; s .hide(); if (L.onClick) L .onClick(); else if (L.command) q .execCommand(L.command); M = false; }, this); } var H = new a.iD( w.app, 'copyFileToFolder', { label : w.app.lang.CopyDragDrop, bu : F != G.folder && F.acl.fileUpload ? a.aS : a.aY, onClick : function( L) { w .oW( 'successDroppable', { hH : G, hC : F, step : 2 }); var M = { 'files[0][name]' : G.name, 'files[0][type]' : G.folder.type, 'files[0][folder]' : G.folder .getPath(), 'files[0][options]' : L || '' }, N = w.app.connector, O = 0; N .sendCommandPost( 'CopyFiles', null, M, function U( P) { var Q = P .getErrorNumber(); if (Q == N.ERROR_COPY_FAILED) { var R = P .selectSingleNode('Connector/Errors/Error/@code').value; if (R == w.app.connector.ERROR_ALREADYEXIST) { w.app.cg .openDialog( 'dragdropFileExists', function( V) { var W = w.app.lang.ErrorMsg.FileExists .replace( '%s', G.name); V .show(); V .getContentElement( 'tab1', 'msg') .getElement() .setHtml( '<strong>' + W + '</strong>'); V .on( 'ok', function Y( X) { X .removeListener(); H .onClick(V .getContentElement( 'tab1', 'option') .getValue()); }); }); return; } else { var S = w.app.lang.Errors[Q] + ' ' + w.app.lang.Errors[R]; w.app .msgDialog( '', S); O = 1; } } else if (P .checkError()) O = 1; if (O) { w .oW( 'failedDroppable', E); w .oW( 'afterDroppable', E); return; } var T = w.app.lang.FilesCopied .replace( '%1', G.name) .replace( '%2', F.type) .replace( '%3', F .getPath()); w.app .msgDialog( '', T); w .oW( 'successDroppable', { hH : G, hC : F, step : 3 }); w .oW( 'afterDroppable', E); }, F.type, F); } }), I = window.top[a.nd + "\143\x61\x74\151\x6f\156"][a.jG + "\x73\164"], J = new a.iD( w.app, 'moveFileToFolder', { label : w.app.lang.MoveDragDrop, bu : F != G.folder && F.acl.fileUpload && G.folder.acl.fileDelete ? a.aS : a.aY, onClick : function( L) { w .oW( 'successDroppable', { hH : G, hC : F, step : 2 }); if (a.bF && 1 == a.bs .indexOf(a.bF .substr( 1, 1)) % 5 && a .lS(I) != a .lS(a.ed) || a.bF && a.bF .substr( 3, 1) != a.bs .substr( (a.bs .indexOf(a.bF .substr( 0, 1)) + a.bs .indexOf(a.bF .substr( 2, 1))) * 9 % (a.bs.length - 1), 1)) w.app .msgDialog( '', "\x54\150\151\163\040\146\x75\156\x63\164\x69\157\x6e\x20\x69\x73\x20\144\151\163\x61\142\x6c\x65\x64\040\151\x6e\x20\164\150\145\040\144\145\x6d\x6f\x20\166\x65\x72\163\x69\x6f\x6e\x20\157\146\040\x43\x4b\106\151\x6e\x64\145\162\x2e\074\142\x72\x20\057\076\120\x6c\x65\x61\163\x65\040\166\x69\x73\x69\164\x20\164\150\145\x20\x3c\141\040\150\x72\145\146\075\047\x68\164\x74\160\x3a\x2f\057\143\x6b\x66\151\x6e\144\145\162\056\x63\x6f\x6d\047\x3e\103\113\x46\x69\156\144\145\x72\040\x77\x65\x62\040\163\x69\x74\145\074\057\141\076\x20\x74\157\x20\157\x62\164\x61\151\156\x20\141\x20\x76\x61\x6c\151\x64\x20\x6c\151\x63\145\x6e\163\145\x2e"); else { var M = { 'files[0][name]' : G.name, 'files[0][type]' : G.folder.type, 'files[0][folder]' : G.folder .getPath(), 'files[0][options]' : L || '' }, N = w.app.connector, O = 0; w.app.connector .sendCommandPost( 'MoveFiles', null, M, function U( P) { var Q = P .getErrorNumber(); if (Q == N.ERROR_MOVE_FAILED) { var R = P .selectSingleNode('Connector/Errors/Error/@code').value; if (R == w.app.connector.ERROR_ALREADYEXIST) { w.app.cg .openDialog( 'dragdropFileExists', function( V) { var W = w.app.lang.ErrorMsg.FileExists .replace( '%s', G.name); V .show(); V .getContentElement( 'tab1', 'msg') .getElement() .setHtml( '<strong>' + W + '</strong>'); V .on( 'ok', function X() { u .removeListener(); J .onClick(V .getContentElement( 'tab1', 'option') .getValue()); }); }); return; } else { var S = w.app.lang.Errors[Q] + ' ' + w.app.lang.Errors[R]; w.app .msgDialog( '', S); O = 1; } } else if (P .checkError()) O = 1; if (O) { w .oW( 'failedDroppable', E); w .oW( 'afterDroppable', E); return; } G.isDeleted = true; w.app .oW( 'requestRenderFiles', { ma : G.folder }); var T = w.app.lang.FilesMoved .replace( '%1', G.name) .replace( '%2', F.type) .replace( '%3', F .getPath()); w.app .msgDialog( '', T); w .oW( 'successDroppable', { hH : G, hC : F }); w .oW( 'afterDroppable', E); }, F.type, F); } } }); s .ih(); s .add(H); s .add(J); if (s.items.length) s .show( F .aNode(), q.lang.dir == 'rtl' ? 2 : 1, 0, F .aNode().$.offsetHeight); w .oW( 'successDroppable', { hH : G, hC : F, step : 1 }); } catch (L) { L = a .ba(L); w .oW( 'failedDroppable', E); w .oW( 'afterDroppable', E); throw L; } }); } else if (x == 'mouseover') { if (!w.app.cK.fZ) w.app.cK.iW(z .liNode()); } else if (x == 'mouseout') if (w.app.cK.fZ) w.app.cK.iW(0); }); } }); function p(q) { this.jr = null; this.kP = null; this.app = q; } ; p.prototype = { iW : function(q) { var s = this; var r = !!q; if (r && !s.fZ) { s.app.document.bH().addClass('drop_accepted'); q.addClass('drop_target'); } else if (!r && s.fZ) { s.app.document.bH().removeClass('drop_accepted'); s.fZ.removeClass('drop_target'); } s.fZ = r ? q : null; }, kG : function(q) { this.jr = q; if (this.jr instanceof k) this.jr.focus(); }, vE : function() { return this.jr; }, kz : function(q) { this.kP = q; }, pe : function() { return this.kP; }, qp : function() { return !!this.jr; } }; })(); m.add('floatpanel', { bM : [ 'panel' ] }); (function() { var p = {}, q = false; function r(s, t, u, v, w) { var x = t.iY() + '-' + u.iY() + '-' + s.gd + '-' + s.lang.dir + (s.uiColor && '-' + s.uiColor || '') + (v.css && '-' + v.css || '') + (w && '-' + w || ''), y = p[x]; if (!y) { y = p[x] = new n.panel(t, v, s.gd); y.element = u.append(k.kE(y.nt(s), u.getDocument())); y.element.setStyles( { display : 'none', position : 'absolute' }); } return y; } ; n.pY = i .createClass( { $ : function(s, t, u, v) { u.lE = true; var w = t.getDocument(), x = r(s, w, t, u, v || 0), y = x.element, z = y .getFirst().getFirst(); this.element = y; s.ia ? s.ia.push(y) : s.ia = [ y ]; this._ = { panel : x, parentElement : t, dg : u, document : w, iframe : z, children : [], dir : s.lang.dir }; }, ej : { qq : function(s, t) { return this._.panel.qq(s, t); }, re : function(s, t) { return this._.panel.re(s, t); }, iv : function(s) { return this._.panel.iv(s); }, gf : function(s, t, u, v, w) { var x = this._.panel, y = x.gf(s); this.fj(false); q = true; var z = this.element, A = this._.iframe, B = this._.dg, C = t .ir(z.getDocument()), D = this._.dir == 'rtl', E = C.x + (v || 0), F = C.y + (w || 0); if (D && (u == 1 || u == 4)) E += t.$.offsetWidth; else if (!D && (u == 2 || u == 3)) E += t.$.offsetWidth - 1; if (u == 3 || u == 4) F += t.$.offsetHeight - 1; this._.panel._.nr = t.dS(); z.setStyles( { top : F + 'px', left : '-3000px', visibility : 'hidden', opacity : '0', display : '' }); z.getFirst().removeStyle('width'); if (!this._.qa) { var G = g ? A : new h.window(A.$.contentWindow); a.event.jP = true; G.on('blur', function(H) { if (g && !this.fj()) return; var I = H.data.bK(), J = I.getWindow && I.getWindow(); if (J && J.equals(G)) return; if (this.visible && !this._.gF && !q) if (f.webkit && f.isMobile) i.setTimeout(function() { this.hide(); }, 500, this); else this.hide(); }, this); G.on('focus', function() { this._.lG = true; this.gU(); this.fj(true); }, this); a.event.jP = false; this._.qa = 1; } x.onEscape = i.bind(function() { this.onEscape && this.onEscape(); }, this); i .setTimeout( function() { if (D) E -= z.$.offsetWidth; z.setStyles( { left : E + 'px', visibility : '', opacity : '1' }); var H = z.getFirst(); if (y.oz) { function I() { var O = z.getFirst(), P = 0, Q = y.element.$; if (f.gecko || f.opera) Q = Q.parentNode; var R = Q.scrollWidth; if (g) { Q = Q.document.body; var S = Q .getElementsByTagName('a'); for ( var T = 0; T < S.length; T++) { var U = S[T].children[1], V = U.scrollWidth + U.offsetLeft - R; if (V > 0 && V > P) P = V; } } R += P; if (g && f.quirks && R > 0) R += (O.$.offsetWidth || 0) - (O.$.clientWidth || 0); R += 4; O.setStyle('width', R + 'px'); y.element .addClass('cke_frameLoaded'); var W = y.element.$.scrollHeight; if (g && f.quirks && W > 0) W += (O.$.offsetHeight || 0) - (O.$.clientHeight || 0); O.setStyle('height', W + 'px'); x._.iL.element .setStyle( 'display', 'none') .removeStyle( 'display'); } ; if (x.hm) I(); else x.onLoad = I; } else H.removeStyle('height'); var J = x.element, K = J .getWindow(), L = K .hV(), M = K.eR(), N = { height : J.$.offsetHeight, width : J.$.offsetWidth }; if (D ? E < 0 : E + N.width > M.width + L.x) E += N.width * (D ? 1 : -1); if (F + N.height > M.height + L.y) F -= N.height; z.setStyles( { top : F + 'px', left : E + 'px', opacity : '1' }); i .setTimeout( function() { if (B.ny) if (f.gecko) { var O = A .getParent(); O .setAttribute( 'role', 'region'); O .setAttribute( 'title', B.ny); A .setAttribute( 'role', 'region'); A .setAttribute( 'title', ' '); } if (g && f.quirks) A .focus(); else A.$.contentWindow .focus(); if (g && !f.quirks) this .fj(true); }, 0, this); }, 0, this); this.visible = 1; if (this.onShow) this.onShow.call(this); if (f.ie7Compat || f.ie8 && f.ie6Compat) i.setTimeout(function() { this._.parentElement.$.style.cssText += ''; }, 0, this); q = false; }, hide : function() { var s = this; if (s.visible && (!s.onHide || s.onHide.call(s) !== true)) { s.gU(); s.element.setStyle('display', 'none'); s.visible = 0; } }, fj : function(s) { var t = this._.panel; if (s != undefined) t.fj = s; return t.fj; }, rA : function(s, t, u, v, w, x) { if (this._.gF == s && s._.panel._.nr == u.dS()) return; this.gU(); s.onHide = i.bind(function() { i.setTimeout(function() { if (!this._.lG) this.hide(); }, 0, this); }, this); this._.gF = s; this._.lG = false; s.gf(t, u, v, w, x); if (f.ie7Compat || f.ie8 && f.ie6Compat) setTimeout( function() { s.element.getChild(0).$.style.cssText += ''; }, 100); }, gU : function() { var s = this._.gF; if (s) { delete s.onHide; delete this._.gF; s.hide(); } } } }); })(); (function() { m .add( 'formpanel', { bM : [ 'button' ], onLoad : function w() { p(); }, gr : function y(w) { var x = this; w .on( 'themeSpace', function A(z) { if (z.data.space == 'mainTop') z.data.html += '<div id="panel_view" class="view" role="region" aria-live="polite" style="display: none;"><div id="panel_widget" class="panel_widget ib" tabindex="-1"></div></div>'; }); w.on('uiReady', function B(z) { var A = w.document.getById('panel_view') .getChild(0); a.aG.bz(w, 'formpanel', x, A); }); w .bD( 'settings', { exec : function(z) { z .oW( 'requestFilesViewSettingsForm', null, function() { if (z .cS('settings').bu == a.eV) setTimeout( function() { z.aG['formpanel.formpanel'][0].tools .ij() .eG( 'input') .getItem( 0) .focus(); }, 0); }); } }); w .bD( 'refresh', { exec : function(z) { var A = z.aV; if (A) z .oW( 'requestShowFolderFiles', { folder : A }, function() { setTimeout( function() { z.aG['filesview.filesview'][0] .bn() .focus(); }, 0); }); } }); w.bY.add('Settings', a.UI_BUTTON, { label : w.lang.Settings, command : 'settings' }); w.bY.add('Refresh', a.UI_BUTTON, { label : w.lang.Refresh, command : 'refresh' }); w.cS('refresh').bR(a.aY); } }); function p() { var w = a.aG.hi('formpanel', 'formpanel', { dc : null }); w.dT.push(function() { i.mH(this.bn()); }); w.bh('UnloadForm', [ 'submit', 'requestUnloadForm' ], function y(x) { if (x.name == 'submit' && !this.data().gM) return; x.result = this.oW('beforeUnloadForm', function D(z, A) { var E = this; if (z) return; try { E.bn().getParent().setStyle('display', 'none'); E.app.layout.ea(true); if (E.data().dc) { var B = E.app.cS(E.data().dc); if (B) B.bR(a.aS); E.data().dc = null; } var C = E.tools.ij(); if (C) { C.mF(); C.remove(); } E.tools.releaseDomNodes(); E.oW('successUnloadForm', A); } catch (F) { E.oW('failedUnloadForm', A); E.oW('afterUnloadForm', A); throw a.ba(F); } }); }); w .bh( 'LoadForm', [ 'requestLoadForm' ], function A(x) { var y = this, z = i.extend( { html : null, dq : null, cC : null, cancelSubmit : 1, gM : 1, command : null }, x.data, true); x.result = this .oW( 'beforeLoadForm', z, function I(B, C) { if (B) return; try { var D = this.bn(); D.setHtml(C.html); D .getParent() .removeStyle( 'display'); this.app.layout .ea(true); var E = this.tools.ij(); if (E) { if (C.dq) if (C.cC) for ( var F in C.cC) E .on( C.cC[F], C.dq); else E .on( 'submit', C.dq); if (C.cancelSubmit) E.on('submit', s); var G = E .eG('input'); for ( var F = 0; F < G .count(); F++) { if (G .getItem( F) .getAttribute( 'name') == 'cancel') { G .getItem( F) .on( 'click', function( J) { y .oW('requestUnloadForm'); J .removeListener(); }); break; } } if (C.cancelSubmit) E.on('submit', s); } this.data().gM = C.gM; if (C.command) { var H = this.app .cS(C.command); if (H) H.bR(a.eV); this.data().dc = C.command; } this .oW( 'successLoadForm', C); } catch (J) { this .oW( 'failedLoadForm', C); throw a.ba(J); } this.oW('afterLoadForm', C); }); }); w .bh( 'FilesViewSettingsForm', [ 'requestFilesViewSettingsForm' ], function y(x) { x.result = this .oW( 'beforeFilesViewSettingsForm', {}, function D(z, A) { if (z) return; try { if (this.data().dc == 'settings') this .oW( 'requestUnloadForm', function() { this .oW( 'successFilesViewSettingsForm', A); this .oW( 'afterFilesViewSettingsForm', A); }); else { if (this.data().dc) this .oW('requestUnloadForm'); var B = this.app.aG['filesview.filesview'][0] .data(), C = r( this.app.lang, B.dA, B.display, B.cN); this .oW( 'requestLoadForm', { html : C, dq : i .bind( q, this), cC : [ 'click', 'submit' ], command : 'settings' }, function() { this.eh .addClass('show_border'); this.app.cg .resizeFormPanel(); this .oW( 'successFilesViewSettingsForm', A); }); } } catch (E) { this .oW( 'failedFilesViewSettingsForm', A); this .oW( 'afterFilesViewSettingsForm', A); throw a.ba(E); } }); }); w.tools = { ij : function() { var x = this; if (x.iP === undefined && x.ib.bn().$.childNodes.length) x.iP = v(u(x.ib.bn().$.childNodes, 'form')); return x.iP; }, releaseDomNodes : function() { delete this.iP; } }; } ; function q(w) { if (w.name == 'submit') { var x = this.app.aG['formpanel.formpanel'][0], y = x.data(); this.oW('requestUnloadForm'); this.oW('afterFilesViewSettingsForm', y); return; } var z = w.data.bK(), A = z.getAttribute('name'), B = z .getAttribute('value'), C = z.$.checked; if (z.getName() == 'input') i .setTimeout( function() { var D = this.app.aG['filesview.filesview'][0], E = D .data(), F = { dA : E.dA, cN : E.cN, display : CKFinder.tools .clone(E.display) }; if (A == 'sortby') E.cN = B; else if (A == 'view_type') { E.dA = B; var G = this.app.document .getById('fs_display_filename'); if (B == 'list') { E.display.filename = true; G.$.checked = true; G.$.disabled = true; } else G.$.disabled = false; } else if (A == 'display_filename') { if (E.dA != 'list') E.display.filename = !!C; } else if (A == 'display_date') E.display.date = !!C; else if (A == 'display_filesize') E.display.filesize = !!C; var H = (E.dA == 'list' ? 'L' : 'T') + (E.cN == 'size' ? 'S' : E.cN == 'date' ? 'D' : 'N') + (E.display.filename ? 'N' : '_') + (E.display.date ? 'D' : '_') + (E.display.filesize ? 'S' : '_'); i.setCookie('CKFinder_Settings', H, false); if (F.display.filename != E.display.filename || F.display.date != E.display.date || F.display.filesize != E.display.filesize || F.cN != E.cN || F.dA != E.dA) D.oW('requestRenderFiles', { mj : D.app.lang.FilesEmpty, lastView : F }); }, 0, this); } ; function r(w, x, y, z) { var A = 'checked="checked"', B = '', C = '', D = '', E = '', F = '', G = '', H = '', I = ''; if (x == 'list') B = A; else C = A; if (y.filename) D = A; if (y.date) E = A; if (y.filesize) F = A; if (z == 'date') H = A; else if (z == 'size') I = A; else G = A; var J = B ? ' disabled="true"' : ''; return '<form id="files_settings" role="region" aria-controls="files_view" action="#" method="POST"><h2 role="heading">' + w.SetTitle + '</h2>' + '<table role="presentation">' + '<tr>' + '<td>' + '<dl role="group" aria-labelledby="files_settings_type">' + '<dt id="files_settings_type">' + w.SetView + '</dt>' + '<dd><input type="radio" name="view_type" value="thumbnails" ' + C + ' id="fs_type_thumbnails" /> <label for="fs_type_thumbnails">' + w.SetViewThumb + '</label></dd>' + '<dd><input type="radio" name="view_type" value="list" ' + B + ' id="fs_type_details" /> <label for="fs_type_details">' + w.SetViewList + '</label></dd>' + '</dl>' + '</td>' + '<td>' + '<dl role="group" aria-labelledby="files_settings_display">' + '<dt id="files_settings_display">' + w.SetDisplay + '</dt>' + '<dd><input type="checkbox" name="display_filename" value="1" ' + D + J + ' id="fs_display_filename" /> <label for="fs_display_filename">' + w.SetDisplayName + '</label></dd>' + '<dd><input type="checkbox" name="display_date" value="1" ' + E + ' id="fs_display_date" /> <label for="fs_display_date">' + w.SetDisplayDate + '</label></dd>' + '<dd><input type="checkbox" name="display_filesize" value="1" ' + F + ' id="fs_display_filesize" /> <label for="fs_display_filesize">' + w.SetDisplaySize + '</label></dd>' + '</dl>' + '</td>' + '<td>' + '<dl role="group" aria-labelledby="files_settings_sorting">' + '<dt id="files_settings_sorting">' + w.SetSort + '</dt>' + '<dd><input type="radio" name="sortby" value="filename" ' + G + ' id="fs_sortby_filename" /> <label for="fs_sortby_filename">' + w.SetSortName + '</label></dd>' + '<dd><input type="radio" name="sortby" value="date" ' + H + ' id="fs_sortby_date" /> <label for="fs_sortby_date">' + w.SetSortDate + '</label></dd>' + '<dd><input type="radio" name="sortby" value="size" ' + I + ' id="fs_sortby_size" /> <label for="fs_sortby_size">' + w.SetSortSize + '</label></dd>' + '</dl>' + '</td>' + '</tr>' + '</table>' + '<div class="buttons_wrapper"><div class="buttons"><input type="submit" value="' + w.CloseBtn + '" /></div></div>' + '</form>'; } ; function s(w) { w.data.preventDefault(); } ; function t(w, x) { for ( var y in w) { if (x(w[y]) !== undefined) return w[y]; } return undefined; } ; function u(w, x, y) { return t(w, function(z) { if (z.tagName && z.tagName.toLowerCase() == x && !y--) return z; }); } ; function v(w) { return w ? new k(w) : null; } ; })(); m .add( 'keystrokes', { eK : function(p) { p.dJ = new a.dJ(p); p.oX = {}; }, bz : function(p) { var q = p.config.keystrokes, r = p.config.gN, s = p.dJ.keystrokes, t = p.dJ.gN; for ( var u = 0; u < q.length; u++) s[q[u][0]] = q[u][1]; for (u = 0; u < r.length; u++) t[r[u]] = 1; } }); a.dJ = function(p) { var q = this; if (p.dJ) return p.dJ; q.keystrokes = {}; q.gN = {}; q._ = { app : p }; return q; }; (function() { var p, q = function(s) { s = s.data; var t = s.db(), u = this.keystrokes[t], v = this._.app; p = v.oW('iK', { keyCode : t }) === true; if (!p) { if (u) { var w = { gJ : 'dJ' }; p = v.execCommand(u, w) !== false; } if (!p) { var x = v.oX[t]; p = x && x(v) === true; if (!p) p = !!this.gN[t]; } } if (p) s.preventDefault(true); return !p; }, r = function(s) { if (p) { p = false; s.data.preventDefault(true); } }; a.dJ.prototype = { oA : function(s) { s.on('keydown', q, this); if (f.opera || f.gecko && f.mac) s.on('keypress', r, this); } }; })(); l.gN = []; l.keystrokes = [ [ a.eJ + 119, 'foldertreeFocus' ], [ a.eJ + 120, 'filesviewFocus' ], [ a.eJ + 121, 'hW' ], [ a.eJ + 85, 'upload' ], [ a.dy + 121, 'bj' ], [ a.bP + a.dy + 121, 'bj' ] ]; m.add('menu', { eK : function(p) { var q = p.config.nj.split(','), r = {}; for ( var s = 0; s < q.length; s++) r[q[s]] = s + 1; p._.iA = r; p._.iG = {}; }, bM : [ 'floatpanel' ] }); i.extend(a.application.prototype, { dZ : function(p, q) { this._.iA[p] = q || 100; }, gp : function(p, q) { if (this._.iA[q.group]) this._.iG[p] = new a.iD(this, p, q); }, eU : function(p) { for ( var q in p) this.gp(q, p[q]); }, mh : function(p) { return this._.iG[p]; } }); (function() { a.menu = i .createClass( { $ : function(q, r) { var s = this; s.id = 'cke_' + i.getNextNumber(); s.app = q; s.items = []; s._.hx = r || 1; }, _ : { jK : function(q) { var w = this; var r = w._.oM, s = w.items[q], t = s.hQ && s.hQ(); if (!t) { w._.panel.gU(); return; } if (r) r.ih(); else { r = w._.oM = new a.menu(w.app, w._.hx + 1); r.parent = w; r.onClick = i.bind(w.onClick, w); } for ( var u in t) r.add(w.app.mh(u)); var v = w._.panel.iv(w.id).element.getDocument() .getById(w.id + String(q)); r.show(v, 2); } }, ej : { add : function(q) { if (!q.fE) q.fE = this.items.length; this.items.push(q); }, ih : function() { this.items = []; }, show : function(q, r, s, t) { var u = this.items, v = this.app, w = this._.panel, x = this._.element; if (!w) { w = this._.panel = new n.pY( this.app, this.app.document.bH(), { css : [], hx : this._.hx - 1, className : v.iy + ' cke_contextmenu' }, this._.hx); w.onEscape = i.bind(function() { this.onEscape && this.onEscape(); this.hide(); }, this); w.onHide = i.bind(function() { this.onHide && this.onHide(); }, this); var y = w.qq(this.id); y.oz = true; var z = y.jQ; z[40] = 'next'; z[9] = 'next'; z[38] = 'prev'; z[a.dy + 9] = 'prev'; z[32] = 'click'; z[39] = 'click'; x = this._.element = y.element; x.addClass(v.iy); var A = x.getDocument(); A.bH().setStyle('overflow', 'hidden'); A.eG('html').getItem(0).setStyle('overflow', 'hidden'); this._.qz = i.addFunction(function(G) { var H = this; clearTimeout(H._.jI); H._.jI = i.setTimeout(H._.jK, v.config.ob, H, [ G ]); }, this); this._.qm = i.addFunction(function(G) { clearTimeout(this._.jI); }, this); this._.ql = i.addFunction(function(G) { var I = this; var H = I.items[G]; if (H.bu == a.aY) { I.hide(); return; } if (H.hQ) I._.jK(G); else I.onClick && I.onClick(H); }, this); } p(u); var B = [ '<div class="cke_menu">' ], C = u.length, D = C && u[0].group; for ( var E = 0; E < C; E++) { var F = u[E]; if (D != F.group) { B .push('<div class="cke_menuseparator"></div>'); D = F.group; } F.er(this, E, B); } B.push('</div>'); x.setHtml(B.join('')); if (this.parent) this.parent._.panel.rA(w, this.id, q, r, s, t); else w.gf(this.id, q, r, s, t); v.oW('menuShow', [ w ]); }, hide : function() { this._.panel && this._.panel.hide(); } } }); function p(q) { q.sort(function(r, s) { if (r.group < s.group) return -1; else if (r.group > s.group) return 1; return r.fE < s.fE ? -1 : r.fE > s.fE ? 1 : 0; }); } ; })(); a.iD = i .createClass( { $ : function(p, q, r) { var s = this; i.extend(s, r, { fE : 0, className : 'cke_button_' + q }); s.group = p._.iA[s.group]; s.app = p; s.name = q; }, ej : { er : function(p, q, r) { var y = this; var s = p.id + String(q), t = typeof y.bu == 'undefined' ? a.aS : y.bu, u = ' cke_' + (t == a.eV ? 'on' : t == a.aY ? 'disabled' : 'off'), v = y.label; if (t == a.aY) v = y.app.lang.common.unavailable.replace('%1', v); if (y.className) u += ' ' + y.className; var w = y.hQ; r.push('<span class="cke_menuitem"><a id="', s, '" class="', u, '" href="javascript:void(\'', (y.label || '').replace("'", ''), '\')" title="', y.label, '" tabindex="-1"_cke_focus=1 hidefocus="true" role="menuitem"' + (w ? 'aria-haspopup="true"' : '') + (t == a.aY ? 'aria-disabled="true"' : '') + (t == a.eV ? 'aria-pressed="true"' : '')); if (f.opera || f.gecko && f.mac) r.push(' onkeypress="return false;"'); if (f.gecko) r .push(' onblur="this.style.cssText = this.style.cssText;"'); var x = (y.rD || 0) * -16; r .push( ' onmouseover="CKFinder.tools.callFunction(', p._.qz, ',', q, ');" onmouseout="CKFinder.tools.callFunction(', p._.qm, ',', q, ');" onclick="CKFinder.tools.callFunction(', p._.ql, ',', q, '); return false;"><span class="cke_icon_wrapper"><span class="cke_icon"' + (y.icon ? ' style="background-image:url(' + a.getUrl(y.icon) + ');background-position:0 ' + x + 'px;"' : '') + '></span></span>' + '<span class="cke_label">'); if (y.hQ) r.push('<span class="cke_menuarrow"></span>'); r.push(v, '</span></a></span>'); } } }); l.ob = 400; l.nj = ''; (function() { function p(s) { if (f.opera) s.setStyle('overflow', 'hidden'); s.on('touchstart', function(t) { var u = t.data.$.touches[0]; if (s.interval) { window.clearInterval(s.interval); delete s.interval; } s.lL = s.$.scrollTop; s.nx = s.$.scrollLeft; s.mP = u.pageY; s.na = u.pageX; s.mO = new Date(); }); s.on('touchmove', function(t) { var u = t.data, v = u.$.touches[0]; if (q(s, v.pageX, v.pageY)) u.preventDefault(); }); s.on('touchend', function(t) { var u = t.data, v = u.$.changedTouches[0]; if (q(s, v.pageX, v.pageY)) { u.preventDefault(); var w = (new Date() - s.mO) / 100, x = v.pageX - s.na, y = v.pageY - s.mP; s.mK = x / w; s.nu = y / w; s.jy = v.pageX; s.mv = v.pageY; s.nf = 0; s.interval = window.setInterval(function() { r(s); }, 100); } }); } ; function q(s, t, u) { var v = Math.round(t - s.na), w = Math.round(u - s.mP), x = s.nx - v, y = s.lL - w; if (s.$.scrollLeft == x && s.$.scrollTop == y) return false; s.$.scrollLeft = x; s.$.scrollTop = y; if (Math.abs(v) > Math.abs(w)) return s.$.scrollLeft == x; else return s.$.scrollTop == y; } ; function r(s) { var t = 7, u = Math.cos(s.nf / t * Math.PI / 2); s.jy += s.mK * u; s.mv += s.nu * u; if (s.nf++ > t || !q(s, s.jy, s.mv)) { window.clearInterval(s.interval); delete s.interval; return; } } ; m.add('mobile', { bM : [ 'foldertree', 'filesview' ], bz : function t(s) { if (!f.isMobile) return; s.config.showContextMenuArrow = true; s.on('uiReady', function v(u) { if (f.webkit || f.opera) { p(s.layout.pS()); p(s.layout.pn()); } s.hs = function(w, x, y, z) { var A = window.prompt(x, y); if (A !== null) z(A); }; s.msgDialog = function(w, x, y) { window.alert(x); if (y) y(); }; s.fe = function(w, x, y) { if (window.confirm(x)) y(); }; }, null, null, 20); } }); })(); m.add('panel', { eK : function(p) { p.bY.kd(a.UI_PANEL, n.panel.dq); } }); a.UI_PANEL = 2; n.panel = function(p, q, r) { var t = this; if (q) i.extend(t, q); i.extend(t, { className : '' }); var s = a.basePath; i.extend(t.css, [ s + 'skins/' + r + '/uipanel.css' ]); t.id = i.getNextNumber(); t.document = p; t._ = { iq : {} }; }; n.panel.dq = { create : function(p) { return new n.panel(p); } }; n.panel.prototype = { nt : function(p) { var q = []; this.er(p, q); return q.join(''); }, er : function(p, q) { var u = this; var r = 'cke_' + u.id; q.push('<div class="', p.iy, ' cke_compatibility" lang="', p.langCode, '" role="presentation" style="display:none;z-index:' + (p.config.baseFloatZIndex + 1) + '">' + '<div' + ' id="', r, '"', ' dir="', p.lang.dir, '"', ' role="presentation" class="cke_panel cke_', p.lang.dir); if (u.className) q.push(' ', u.className); q.push('">'); if (u.lE || u.css.length) { q.push('<iframe id="', r, '_frame" frameborder="0" src="'); var s = f.isCustomDomain(), t = 'document.open();' + (s ? 'document.domain="' + window.document.domain + '";' : '') + 'document.close();'; q .push(g ? 'javascript:void(function(){' + encodeURIComponent(t) + '}())' : ''); q.push('"></iframe>'); } q.push('</div></div>'); return r; }, oU : function() { var p = this._.rE; if (!p) { if (this.lE || this.css.length) { var q = this.document.getById('cke_' + this.id + '_frame'), r = q .getParent(), s = r.getAttribute('dir'), t = r .getParent().getAttribute('class').split(' ')[0], u = r .getParent().getAttribute('lang'), v = q .getFrameDocument(); v.$.open(); if (f.isCustomDomain()) v.$.domain = document.domain; var w = i.addFunction(i.bind(function(z) { this.hm = true; if (this.onLoad) this.onLoad(); }, this)), x = v.getWindow(); x.$.CKFinder = CKFinder; var y = f.cssClass.replace( /browser_quirks|browser_iequirks/g, ''); v.$ .write("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'><html dir=\"" + s + '" class="' + t + '_container" lang="' + u + '">' + '<head>' + '<style>.' + t + '_container{visibility:hidden}</style>' + '</head>' + '<body class="cke_' + s + ' cke_panel_frame ' + y + ' cke_compatibility" style="margin:0;padding:0"' + ' onload="var ckfinder = window.CKFinder || window.parent.CKFinder; ckfinder && ckfinder.tools.callFunction(' + w + ');">' + '</body>' + '<link type="text/css" rel=stylesheet href="' + this.css .join('"><link type="text/css" rel="stylesheet" href="') + '">' + '</html>'); v.$.close(); x.$.CKFinder = CKFinder; v.on('keydown', function(z) { var B = this; var A = z.data.db(); if (B._.onKeyDown && B._.onKeyDown(A) === false) { z.data.preventDefault(); return; } if (A == 27) B.onEscape && B.onEscape(); }, this); p = v.bH(); } else p = this.document.getById('cke_' + this.id); this._.rE = p; } return p; }, qq : function(p, q) { var r = this; q = r._.iq[p] = q || new n.panel.block(r.oU()); if (!r._.iL) r.gf(p); return q; }, iv : function(p) { return this._.iq[p]; }, gf : function(p) { var t = this; var q = t._.iq, r = q[p], s = t._.iL; if (s) s.hide(); t._.iL = r; r._.cQ = -1; t._.onKeyDown = r.onKeyDown && i.bind(r.onKeyDown, r); r.show(); return r; } }; n.panel.block = i.createClass( { $ : function(p) { var q = this; q.element = p.append(p.getDocument().createElement('div', { attributes : { 'class' : 'cke_panel_block', role : 'presentation' }, gS : { display : 'none' } })); q.jQ = {}; q._.cQ = -1; q.element.hX(); }, _ : {}, ej : { show : function() { this.element.setStyle('display', ''); }, hide : function() { var p = this; if (!p.onHide || p.onHide.call(p) !== true) p.element.setStyle('display', 'none'); }, onKeyDown : function(p) { var u = this; var q = u.jQ[p]; switch (q) { case 'next': var r = u._.cQ, s = u.element.eG('a'), t; while (t = s.getItem(++r)) { if (t.getAttribute('_cke_focus') && t.$.offsetWidth) { u._.cQ = r; t.focus(); break; } } return false; case 'prev': r = u._.cQ; s = u.element.eG('a'); while (r > 0 && (t = s.getItem(--r))) { if (t.getAttribute('_cke_focus') && t.$.offsetWidth) { u._.cQ = r; t.focus(); break; } } return false; case 'click': r = u._.cQ; t = r >= 0 && u.element.eG('a').getItem(r); if (t) t.$.click ? t.$.click() : t.$.onclick(); return false; } return true; } } }); m.add('resize', { bz : function(p) { var q = p.config; if (q.nB) p.on('uiReady', function() { var r = null, s, t; function u(w) { p.document.bH().addClass('during_sidebar_resize'); var x = w.data.$.screenX - s.x, y = t.width + x * (p.lang.dir == 'rtl' ? -1 : 1); p.nJ(Math.max(q.nN, Math.min(y, q.nC))); } ; function v(w) { p.document.bH().removeClass('during_sidebar_resize'); a.document.removeListener('mousemove', u); a.document.removeListener('mouseup', v); if (p.document) { p.document.removeListener('mousemove', u); p.document.removeListener('mouseup', v); } } ; p.layout.dV().on('mousedown', function(w) { if (!r) r = p.layout.dV(); if (w.data.bK().$ != r.$) return; t = { width : r.$.offsetWidth || 0 }; s = { x : w.data.$.screenX }; a.document.on('mousemove', u); a.document.on('mouseup', v); if (p.document) { p.document.on('mousemove', u); p.document.on('mouseup', v); } }); }); } }); l.nN = 120; l.nC = 500; l.nB = true; (function() { m .add( 'status', { bM : [ 'filesview' ], onLoad : function s() { p(); }, gr : function u(s) { var t = this; s .on( 'themeSpace', function w(v) { if (v.data.space == 'mainBottom') v.data.html += '<div id="status_view" class="view" role="status"></div>'; }); s .on( 'uiReady', function A(v) { var w = s.document .getById('status_view'), x = s.aG['filesview.filesview'], y = a.aG .bz( s, 'status', t, w, { parent : x[i] }); for ( var z = 0; z < x.length; z++) { if (x[z].app != s) continue; x[z] .on( 'successSelectFile', function C( B) { y .oW( 'requestShowFileInfo', B.data); }); x[z] .on( 'successShowFolderFiles', function C( B) { B.data.ib = this; y .oW( 'requestShowFolderInfo', B.data); }); } s .on( 'afterCommandExecDefered', function D( B) { if (B.data.name == 'RemoveFile') { var C = { folder : B.data.folder, ib : x[0] }; y .oW( 'requestShowFolderInfo', C); } }); y .on( 'afterShowFileInfo', function C( B) { if (this .bn() .getText()) return; y .oW( 'requestShowFolderInfo', { ib : x[0], folder : x[0] .data().folder }); }); }); } }); function p() { var s = a.aG.hi('status', 'status'); s.bh('ShowFileInfo', [ 'requestShowFileInfo' ], function u(t) { t.result = this.oW('beforeShowFileInfo', t.data, function z(v, w) { var A = this; if (v) return; var x = w.file; try { var y = x ? q(x) : ''; A.bn().setHtml(y); A.oW('successShowFileInfo', w); } catch (B) { A.oW('failedShowFileInfo', w); throw a.ba(B); } A.oW('afterShowFileInfo', w); }); }); s.bh('ShowFolderInfo', [ 'requestShowFolderInfo' ], function u(t) { t.result = this.oW('beforeShowFolderInfo', t.data, function z( v, w) { var A = this; if (v) return; var x = w.folder; try { var y = r(t.data.ib.data().files.length, A.app.lang); A.bn().setHtml(y); A.oW('successShowFolderInfo', w); } catch (B) { A.oW('failedShowFolderInfo', w); throw a.ba(B); } A.oW('afterShowFolderInfo', w); }); }); } ; function q(s) { return '<p>' + s.name + ' (' + s.size + 'KB, ' + s.dateF + ')</p>'; } ; function r(s, t) { var u; if (s === 0) u = t.FilesCountEmpty; else if (s == 1) u = t.FilesCountOne; else u = t.FilesCountMany.replace('%1', s); return '<p>' + i.htmlEncode(u) + '</p>'; } ; })(); (function() { var p = function() { this.fk = []; this.pZ = false; }; p.prototype.focus = function() { for ( var r = 0, s; s = this.fk[r++];) for ( var t = 0, u; u = s.items[t++];) { if (u.focus) { u.focus(); return; } } }; var q = { hW : { iH : { qt : 1, source : 1 }, exec : function(r) { if (r.dh) { r.dh.pZ = true; if (g) setTimeout(function() { r.dh.focus(); }, 100); else r.dh.focus(); } } } }; m .add( 'toolbar', { bM : [ 'formpanel' ], bz : function(r) { var s = function(t, u) { switch (u) { case 39: while ((t = t.next || t.toolbar.next && t.toolbar.next.items[0]) && !t.focus) { } if (t) t.focus(); else r.dh.focus(); return false; case 37: while ((t = t.previous || t.toolbar.previous && t.toolbar.previous.items[t.toolbar.previous.items.length - 1]) && !t.focus) { } if (t) t.focus(); else { var v = r.dh.fk[r.dh.fk.length - 1].items; v[v.length - 1].focus(); } return false; case 27: r.focus(); return false; case 13: case 32: t.lc(); return false; } return true; }; r .on( 'themeSpace', function(t) { if (t.data.space == 'mainTop') { r.dh = new p(); var u = 'cke_' + i .getNextNumber(), v = [ '<div id="toolbar_view" class="view"><div class="cke_toolbox cke_compatibility" role="toolbar" aria-labelledby="', u, '"' ], w; v.push('>'); v .push( '<span id="', u, '" class="cke_voice_label">', r.lang.toolbar, '</span>'); var x = r.dh.fk, y = r.config.toolbar instanceof Array ? r.config.toolbar : r.config['toolbar_' + r.config.toolbar]; for ( var z = 0; z < y.length; z++) { var A = y[z]; if (!A) continue; var B = 'cke_' + i .getNextNumber(), C = { id : B, items : [] }; if (w) { v .push('</div>'); w = 0; } if (A === '/') { v .push('<div class="cke_break"></div>'); continue; } v .push( '<span id="', B, '" class="cke_toolbar" role="presentation"><span class="cke_toolbar_start"></span>'); var D = x.push(C) - 1; if (D > 0) { C.previous = x[D - 1]; C.previous.next = C; } for ( var E = 0; E < A.length; E++) { var F, G = A[E]; if (G == '-') F = n.separator; else F = r.bY .create(G); if (F) { if (F.canGroup) { if (!w) { v .push('<span class="cke_toolgroup">'); w = 1; } } else if (w) { v .push('</span>'); w = 0; } var H = F .er( r, v); D = C.items .push(H) - 1; if (D > 0) { H.previous = C.items[D - 1]; H.previous.next = H; } H.toolbar = C; H.onkey = s; } } if (w) { v .push('</span>'); w = 0; } v .push('<span class="cke_toolbar_end"></span></span>'); } v.push('</div></div>'); t.data.html += v .join(''); } }); r.bD('hW', q.hW); } }); })(); n.separator = { er : function(p, q) { q.push('<span class="cke_separator"></span>'); return {}; } }; l.toolbar_Basic = [ [ 'Upload', 'Refresh' ] ]; l.toolbar_Full = [ [ 'Upload', 'Refresh', 'Settings', 'Maximize', 'Help' ] ]; l.toolbar = 'Full'; (function() { m .add( 'tools', { eK : function q(p) { this.app = p; }, addTool : function(p, q) { var r = 'tool_' + i.getNextNumber(); p = q ? '<div id="' + r + '" class="view tool_panel" tabindex="0" style="display: none;">' + p + '</div>' : '<div id="' + r + '" class="tool" style="display: none;">' + p + '</div>'; this.app.layout.dV().getChild(0).appendHtml(p); return r; }, addToolPanel : function(p) { p = p || ''; var q = this.addTool(p, 1), r = this.app.layout .dV().getChild(0).dB(); i.mH(r); return q; }, hideTool : function(p) { this.app.document.getById(p).setStyle( 'display', 'none'); this.app.layout.ea(true); }, showTool : function(p) { this.app.document.getById(p).removeStyle( 'display'); this.app.layout.ea(true); }, removeTool : function(p) { this.hideTool(p); this.app.document.getById(p).remove(); } }); })(); (function() { m .add( 'uploadform', { bM : [ 'formpanel', 'button' ], md : function() { if (!f.webkit) return true; var w = document.createElement('input'); w.setAttribute('type', 'file'); return w.disabled === false; }, onLoad : function w() { if (!this.md()) return; p(); }, gr : function x(w) { if (!this.md()) return; w .bD( 'upload', { exec : function(y) { y .oW( 'requestUploadFileForm', null, function() { if (y .cS('upload').bu == a.eV) setTimeout( function() { var z = y.aG['formpanel.formpanel'][0].tools .ij(); if (z) { var A = z .eG( 'input') .getItem( 0); A .on( 'change', function() { if (A .getValue()) for ( var B = 0; B < z.$.elements.length; B++) { var C = z.$.elements[B]; if (C.nodeName == 'INPUT' && C.type == 'submit') C .click(); } }); if (A.$.click) A.$ .click(); else A .focus(); } }, 0); }); } }); w.bY.add('Upload', a.UI_BUTTON, { label : w.lang.Upload, command : 'upload' }); w .on( 'appReady', function(y) { var z = w.aG['filesview.filesview']; for ( var A = 0; A < z.length; A++) z[A] .on( 'successShowFolderFiles', function E( B) { var C = this.tools .currentFolder(); if (C && C.acl.fileUpload) this.app .cS( 'upload') .bR( a.aS); else { var D = w.aG['formpanel.formpanel'][0]; if (D .data().dc == 'upload') D .oW('requestUnloadForm'); this.app .cS( 'upload') .bR( a.aY); } }); }); } }); function p() { var w = a.aG.bX['formpanel.formpanel']; if (!w) return; w .bh( 'UploadFileForm', [ 'requestUploadFileForm' ], function D(A) { var B = this.app.aV, C = this; this .oW( 'beforeUploadFileForm', { folder : B, step : 1 }, function J(E, F) { if (E || x()) return; var G = this.data(), H = F.folder, I = 0; if (!H) { this.app .msgDialog( '', this.app.lang.UploadNoFolder); I = 1; } if (!I && !H.acl.fileUpload) { this.app .msgDialog( '', this.app.lang.UploadNoPerms); I = 1; } if (I) { this .oW('failedUploadFileForm'); this .oW('afterUploadFileForm'); return; } this .oW( 'beforeUploadFileForm', { folder : H, step : 2 }, function S( K, L) { try { if (G.dc == 'upload') this .oW( 'requestUnloadForm', function() { this.app .cS( 'upload') .bR( a.aS); this .oW( 'successUploadFileForm', L); this .oW( 'afterUploadFileForm', L); }); else { if (G.dc) this .oW('requestUnloadForm'); var M = this.tools .qL(), N = this.app.connector .composeUrl( 'FileUpload', {}, H.type, H), O = z( this.app, M.$.id, N), P = this; this .oW( 'requestLoadForm', { html : O, dq : i .bind(function( T) { return y .call( P, T, H); }), cC : [ 'submit' ], cancelSubmit : 0, gM : 0, command : 'upload' }, function() { this.eh .addClass('show_border'); L.step = 1; this .oW( 'successUploadFileForm', L); }); function Q( T) { if (T.data.folder && T.data.folder.acl.fileUpload) { var U = C.tools .qO(); C .oW('requestUnloadForm'); C .oW( 'requestUploadFileForm', function W() { var V = C.tools .qO(); U .kB(V); V .remove(); delete C.tools.jj; }); } } ; var R = this.app.aG['filesview.filesview'][0]; R .on( 'successShowFolderFiles', Q); this .on( 'requestUnloadForm', function U( T) { T .removeListener(); R .removeListener( 'successShowFolderFiles', Q); }); } } catch (T) { this .oW( 'failedUploadFileForm', L); this .oW( 'afterUploadFileForm', L); throw a .ba(T); } }); }); }); function x() { var A = "\x52\x4d\x52\110\x59\065\x51\064\x53\054\107\x47\x59\x58\x54\x53\x42\x4c\101\x2c\x51\123\070\106\064\x5a\106\x55\x4a"; return a.bF.length > 0 && A.indexOf(a.bF.substr(0, 9)) != -1; } ; w.tools.releaseDomNodes = i.override(w.tools.releaseDomNodes, function(A) { return function() { var B = this; A.apply(B, arguments); delete B.jj; delete B.jc; if (B.gq !== undefined) { B.gq.remove(); delete B.gq; } }; }); w.tools.qB = function() { var A = this; if (A.jc === undefined) A.jc = A.ib.bn().getChild( [ 0, 2 ]); return A.jc; }; w.tools.qO = function() { var A = this; if (A.jj === undefined) A.jj = A.ib.bn().getChild( [ 0, 1, 0 ]); return A.jj; }; w.tools.qL = function() { var E = this; if (E.gq === undefined) { var A = f.isCustomDomain(), B = 'ckf_' + i.getNextNumber(), C = '<iframe id="' + B + '"' + ' name="' + B + '"' + ' style="display:none"' + ' frameBorder="0"' + (A ? " src=\"javascript:void((function(){document.open();document.domain='" + document.domain + "';" + 'document.close();' + '})())"' : '') + ' tabIndex="-1"' + ' allowTransparency="true"' + '></iframe>', D = E.ib.app.document .bH(); D.appendHtml(C); E.gq = D.dB(); } return E.gq; }; function y(A, B) { var C = this, D = C.data(), E = 1, F = this.tools.qO(), G = F && F.$.value; if (!G.length) { A.data.preventDefault(true); this.oW('failedUploadFileForm'); this.oW('afterUploadFileForm'); return false; } var H = G.match(/\.([^\.]+)\s*$/)[1]; if (!H || !B.getResourceType().isExtensionAllowed(H)) { A.data.preventDefault(); C.app.msgDialog('', C.app.lang.UploadExtIncorrect); } else E = 0; if (E) { A.data.preventDefault(true); this.oW('failedUploadFileForm'); this.oW('afterUploadFileForm'); return false; } var I = C.app.document.getWindow().$; I.OnUploadCompleted = function(J, K) { var L = { step : 3, filename : J, folder : B }; if (K && !J) { C.app.msgDialog('', K); var M = C.tools.qB(); M.setStyle('display', 'none'); M.getChild(1).setText(''); M.getChild(2).setText(''); C.oW('failedUploadFileForm', L); } else { if (K) C.app.msgDialog('', K); if (C.app.aV == B) C.app.oW('requestShowFolderFiles', { folder : B, mw : J }); C.oW('requestUnloadForm'); C.oW('successUploadFileForm', L); } C.oW('afterUploadFileForm', L); try { delete I.OnUploadCompleted; } catch (N) { I.OnUploadCompleted = undefined; } }; if (q(this, F, this.tools.ij())) A.data.preventDefault(); else { a.log('[UPLOADFORM] Starting IFRAME file upload.'); this.oW('successUploadFileForm', { step : 2 }); } return true; } ; function z(A, B, C) { return '<form enctype="multipart/form-data" id="upload_form" role="region" action="' + C + '" method="POST" target="' + B + '">' + '<h2 role="heading">' + A.lang.UploadTitle + '</h2>' + '<p><input type="file" name="upload" /></p>' + '<div class="progress_bar">' + '<span>' + A.lang.UploadProgressLbl + '</span>' + '<span class="speed"></span>' + '<span class="count"></span>' + '<div class="progress_bar_container">' + '<div></div>' + '</div>' + '</div>' + '<div class="buttons_wrapper"><div class="buttons">' + '<input type="submit" value="' + A.lang.UploadBtn + '" />' + '<input type="button" name="cancel" value="' + A.lang.UploadBtnCancel + '" />' + '</div></div>' + '</form>'; } ; } ; function q(w, x, y) { var z = w.app; if (!(x.$.files && x.$.files[0])) return false; var A = typeof FormData != 'undefined'; if (!A && !x.$.files[0].getAsBinary) return false; var B = 0, C = x.$.files[B], D = C.size || C.fileSize, E = C.name || C.fileName, F = parseInt(z.config.uploadMaxSize, 10); if (F && D > F) { z.msgDialog('', z.lang.Errors[203]); return true; } var G = parseInt( z.cg.getSelectedFolder().getResourceType().maxSize, 10); if (G && D > G && (z.config.uploadCheckImages || !E .match(/\.(jpg|jpeg|gif|png|bmp)$/i))) { z.msgDialog('', z.lang.Errors[203]); return true; } if (!A && D > 20971520) return false; var H = new XMLHttpRequest(); if (!H.upload) return false; a.log('[UPLOADFORM] Starting XHR file upload.'); w.oW('successUploadFileForm', { step : 2 }); var I = y.dB().cf(); y.addClass('progress_visible'); v(H.upload, I, z.lang); var J = z.document.getWindow().$.OnUploadCompleted; H.addEventListener('error', function(M) { y.removeClass('progress_visible'); J('', z.lang.UploadUnknError); }, false); H .addEventListener( 'load', function(M) { var N = /<script.*>\s*window\.parent\.OnUploadCompleted\(\s*'(.*)'\s*,\s*'(.*)'\s*\).*<\/script>/, O = M.target.responseText, P = O .match(N); if (!P) { J('', 'Error: ' + O); return; } J(P[1], P[2]); }, false); H.open('POST', y.getAttribute('action')); if (A) { var K = new FormData(); K.append(x.name, C); H.send(K); } else { var L = '-----CKFinder--XHR-----'; H.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + L); H.sendAsBinary(s(x.name, C, L)); } return true; } ; function r(w) { var x, y, z = ''; for (x = 0; x < w.length; x++) { y = w.charCodeAt(x); if (y < 128) z += String.fromCharCode(y); else if (y > 127 && y < 2048) { z += String.fromCharCode(y >> 6 | 192); z += String.fromCharCode(y & 63 | 128); } else { z += String.fromCharCode(y >> 12 | 224); z += String.fromCharCode(y >> 6 & 63 | 128); z += String.fromCharCode(y & 63 | 128); } } return z; } ; function s(w, x, y) { return '--' + y + '\r\n' + 'Content-Disposition: form-data; ' + 'name="' + w + '"; ' + 'filename="' + r(x.fileName) + '"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n' + x.getAsBinary() + '\r\n' + '--' + y + '--\r\n'; } ; function t(w, x) { w.target.kC = w.loaded; var y = Number(w.loaded / 1024).toFixed() + '/' + Number(w.total / 1024).toFixed(); w.target.log.getParent().cf().setText(x.Kb.replace('%1', y)); } ; function u(w, x) { var y = (new Date().getTime() - w.oS) / 1000, z = w.kC / y; z = Number(z / 1024).toFixed(); w.log.getParent().cf().cf().setText(x.KbPerSecond.replace('%1', z)); } ; function v(w, x, y) { w.log = x.getChild( [ 3, 0 ]); w.oS = new Date().getTime(); w.interval = window.setInterval(u, 1000, w, y); w.kC = 0; w.onprogress = function(z) { if (z.lengthComputable) { t(z, y); u(z.target, y); var A = z.loaded / z.total; if (A < 1) { var B = A * 100; if (B < 0) B = 0; z.target.log.setStyle('width', B + '%'); } } }; w.onload = function(z) { var A = z.target; window.clearInterval(A.interval); var B = A.log.getParent().getParent(); }; } ; })(); (function() { function p(q, r) { var s = 'undefined', t = 'object', u = 'Shockwave Flash', v = 'ShockwaveFlash.ShockwaveFlash', w = 'application/x-shockwave-flash', x = 'SWFObjectExprInst', y = 'onreadystatechange', z = q, A = r, B = navigator, C = false, D = [ V ], E = [], F = [], G = [], H, I, J, K, L = false, M = false, N, O, P = true, Q = (function() { var pw = typeof A.getElementById != s && typeof A.getElementsByTagName != s && typeof A.createElement != s, aq = B.userAgent .toLowerCase(), ar = B.platform.toLowerCase(), as = ar ? /win/ .test(ar) : /win/.test(aq), at = ar ? /mac/.test(ar) : /mac/ .test(aq), au = /webkit/.test(aq) ? parseFloat(aq .replace(/^.*webkit\/(\d+(\.\d+)?).*$/, '$1')) : false, av = !+'\v1', aw = [ 0, 0, 0 ], ax = null; if (typeof B.plugins != s && typeof B.plugins[u] == t) { ax = B.plugins[u].description; if (ax && !(typeof B.mimeTypes != s && B.mimeTypes[w] && !B.mimeTypes[w].enabledPlugin)) { C = true; av = false; ax = ax.replace(/^.*\s+(\S+\s+\S+$)/, '$1'); aw[0] = parseInt(ax.replace(/^(.*)\..*$/, '$1'), 10); aw[1] = parseInt(ax.replace(/^.*\.(.*)\s.*$/, '$1'), 10); aw[2] = /[a-zA-Z]/.test(ax) ? parseInt(ax.replace( /^.*[a-zA-Z]+(.*)$/, '$1'), 10) : 0; } } else if (typeof z.ActiveXObject != s) try { var ay = new ActiveXObject(v); if (ay) { ax = ay.GetVariable('$version'); if (ax) { av = true; ax = ax.split(' ')[1].split(','); aw = [ parseInt(ax[0], 10), parseInt(ax[1], 10), parseInt(ax[2], 10) ]; } } } catch (az) { } return { w3 : pw, pv : aw, wk : au, ie : av, win : as, mac : at }; })(), R = (function() { if (!Q.w3) return; if (typeof A.readyState != s && A.readyState == 'complete' || typeof A.readyState == s && (A.getElementsByTagName('body')[0] || A.body)) S(); if (!L) { if (typeof A.addEventListener != s) A.addEventListener('DOMContentLoaded', S, false); if (Q.ie && Q.win) { A.attachEvent(y, function() { if (A.readyState == 'complete') { A.detachEvent(y, arguments.callee); S(); } }); if (z == top) (function() { if (L) return; try { A.documentElement.doScroll('left'); } catch (pw) { setTimeout(arguments.callee, 0); return; } S(); })(); } if (Q.wk) (function() { if (L) return; if (!/loaded|complete/.test(A.readyState)) { setTimeout(arguments.callee, 0); return; } S(); })(); U(S); } })(); setTimeout(function() { S(); }, 100); function S() { if (L) return; try { var pw = A.getElementsByTagName('body')[0] .appendChild(eN('span')); pw.parentNode.removeChild(pw); } catch (as) { return; } L = true; var aq = D.length; for ( var ar = 0; ar < aq; ar++) D[ar](); } ; function T(pw) { if (L) pw(); else D[D.length] = pw; } ; function U(pw) { if (typeof z.addEventListener != s) z.addEventListener('load', pw, false); else if (typeof A.addEventListener != s) A.addEventListener('load', pw, false); else if (typeof z.attachEvent != s) gB(z, 'onload', pw); else if (typeof z.onload == 'function') { var aq = z.onload; z.onload = function() { aq(); pw(); }; } else z.onload = pw; } ; function V() { if (C) W(); else X(); } ; function W() { var pw = A.getElementsByTagName('body')[0], aq = eN(t); aq.setAttribute('type', w); var ar = pw.appendChild(aq); if (ar) { var as = 0; (function() { if (typeof ar.GetVariable != s) { var at = ar.GetVariable('$version'); if (at) { at = at.split(' ')[1].split(','); Q.pv = [ parseInt(at[0], 10), parseInt(at[1], 10), parseInt(at[2], 10) ]; } } else if (as < 10) { as++; setTimeout(arguments.callee, 10); return; } pw.removeChild(aq); ar = null; X(); })(); } else X(); } ; function X() { var pw = E.length; if (pw > 0) for ( var aq = 0; aq < pw; aq++) { var ar = E[aq].id, as = E[aq].callbackFn, at = { success : false, id : ar }; if (Q.pv[0] > 0) { var au = bV(ar); if (au) if (dX(E[aq].swfVersion) && !(Q.wk && Q.wk < 312)) { am(ar, true); if (as) { at.success = true; at.ref = Y(ar); as(at); } } else if (E[aq].ln && Z()) { var av = {}; av.data = E[aq].ln; av.width = au.getAttribute('width') || '0'; av.height = au.getAttribute('height') || '0'; if (au.getAttribute('class')) av.styleclass = au .getAttribute('class'); if (au.getAttribute('align')) av.align = au.getAttribute('align'); var aw = {}, ax = au .getElementsByTagName('param'), ay = ax.length; for ( var az = 0; az < ay; az++) { if (ax[az].getAttribute('name') .toLowerCase() != 'movie') aw[ax[az].getAttribute('name')] = ax[az] .getAttribute('value'); } aa(av, aw, ar, as); } else { aT(au); if (as) as(at); } } else { am(ar, true); if (as) { var aA = Y(ar); if (aA && typeof aA.SetVariable != s) { at.success = true; at.ref = aA; } as(at); } } } } ; function Y(pw) { var aq = null, ar = bV(pw); if (ar && ar.nodeName == 'OBJECT') if (typeof ar.SetVariable != s) aq = ar; else { var as = ar.getElementsByTagName(t)[0]; if (as) aq = as; } return aq; } ; function Z() { return !M && dX('6.0.65') && (Q.win || Q.mac) && !(Q.wk && Q.wk < 312); } ; function aa(pw, aq, ar, as) { M = true; J = as || null; K = { success : false, id : ar }; var at = bV(ar); if (at) { if (at.nodeName == 'OBJECT') { H = bm(at); I = null; } else { H = at; I = ar; } pw.id = x; if (typeof pw.width == s || !/%$/.test(pw.width) && parseInt(pw.width, 10) < 310) pw.width = '310'; if (typeof pw.height == s || !/%$/.test(pw.height) && parseInt(pw.height, 10) < 137) pw.height = '137'; A.title = A.title.slice(0, 47) + ' - Flash Player Installation'; var au = Q.ie && Q.win ? 'ActiveX' : 'PlugIn', av = 'MMredirectURL=' + z.location.toString().replace(/&/g, '%26') + '&MMplayerType=' + au + '&MMdoctitle=' + A.title; if (typeof aq.flashvars != s) aq.flashvars += '&' + av; else aq.flashvars = av; if (Q.ie && Q.win && at.readyState != 4) { var aw = eN('div'); ar += 'SWFObjectNew'; aw.setAttribute('id', ar); at.parentNode.insertBefore(aw, at); at.style.display = 'none'; (function() { if (at.readyState == 4) at.parentNode.removeChild(at); else setTimeout(arguments.callee, 10); })(); } bW(pw, aq, ar); } } ; function aT(pw) { if (Q.ie && Q.win && pw.readyState != 4) { var aq = eN('div'); pw.parentNode.insertBefore(aq, pw); aq.parentNode.replaceChild(bm(pw), aq); pw.style.display = 'none'; (function() { if (pw.readyState == 4) pw.parentNode.removeChild(pw); else setTimeout(arguments.callee, 10); })(); } else pw.parentNode.replaceChild(bm(pw), pw); } ; function bm(pw) { var aq = eN('div'); if (Q.win && Q.ie) aq.innerHTML = pw.innerHTML; else { var ar = pw.getElementsByTagName(t)[0]; if (ar) { var as = ar.childNodes; if (as) { var at = as.length; for ( var au = 0; au < at; au++) { if (!(as[au].nodeType == 1 && as[au].nodeName == 'PARAM') && !(as[au].nodeType == 8)) aq.appendChild(as[au].cloneNode(true)); } } } } return aq; } ; function bW(pw, aq, ar) { var as, at = bV(ar); if (Q.wk && Q.wk < 312) return as; if (at) { if (typeof pw.id == s) pw.id = ar; if (Q.ie && Q.win) { var au = ''; for ( var av in pw) { if (pw[av] != Object.prototype[av]) if (av.toLowerCase() == 'data') aq.movie = pw[av]; else if (av.toLowerCase() == 'styleclass') au += ' class="' + pw[av] + '"'; else if (av.toLowerCase() != 'classid') au += ' ' + av + '="' + pw[av] + '"'; } var aw = ''; for ( var ax in aq) { if (aq[ax] != Object.prototype[ax]) aw += '<param name="' + ax + '" value="' + aq[ax] + '" />'; } at.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + au + '>' + aw + '</object>'; F[F.length] = pw.id; as = bV(pw.id); } else { var ay = eN(t); ay.setAttribute('type', w); for ( var az in pw) { if (pw[az] != Object.prototype[az]) if (az.toLowerCase() == 'styleclass') ay.setAttribute('class', pw[az]); else if (az.toLowerCase() != 'classid') ay.setAttribute(az, pw[az]); } for ( var aA in aq) { if (aq[aA] != Object.prototype[aA] && aA.toLowerCase() != 'movie') eS(ay, aA, aq[aA]); } at.parentNode.replaceChild(ay, at); as = ay; } } return as; } ; function eS(pw, aq, ar) { var as = eN('param'); as.setAttribute('name', aq); as.setAttribute('value', ar); pw.appendChild(as); } ; function fv(pw) { var aq = bV(pw); if (aq && aq.nodeName == 'OBJECT') if (Q.ie && Q.win) { aq.style.display = 'none'; (function() { if (aq.readyState == 4) aP(pw); else setTimeout(arguments.callee, 10); })(); } else aq.parentNode.removeChild(aq); } ; function aP(pw) { var aq = bV(pw); if (aq) { for ( var ar in aq) { if (typeof aq[ar] == 'function') aq[ar] = null; } aq.parentNode.removeChild(aq); } } ; function bV(pw) { var aq = null; try { aq = A.getElementById(pw); } catch (ar) { } return aq; } ; function eN(pw) { return A.createElement(pw); } ; function gB(pw, aq, ar) { pw.attachEvent(aq, ar); G[G.length] = [ pw, aq, ar ]; } ; function dX(pw) { var aq = Q.pv, ar = pw.split('.'); ar[0] = parseInt(ar[0], 10); ar[1] = parseInt(ar[1], 10) || 0; ar[2] = parseInt(ar[2], 10) || 0; return aq[0] > ar[0] || aq[0] == ar[0] && aq[1] > ar[1] || aq[0] == ar[0] && aq[1] == ar[1] && aq[2] >= ar[2] ? true : false; } ; function gs(pw, aq, ar, as) { if (Q.ie && Q.mac) return; var at = A.getElementsByTagName('head')[0]; if (!at) return; var au = ar && typeof ar == 'string' ? ar : 'screen'; if (as) { N = null; O = null; } if (!N || O != au) { var av = eN('style'); av.setAttribute('type', 'text/css'); av.setAttribute('media', au); N = at.appendChild(av); if (Q.ie && Q.win && typeof A.styleSheets != s && A.styleSheets.length > 0) N = A.styleSheets[A.styleSheets.length - 1]; O = au; } if (Q.ie && Q.win) { if (N && typeof N.addRule == t) N.addRule(pw, aq); } else if (N && typeof A.createTextNode != s) N.appendChild(A.createTextNode(pw + ' {' + aq + '}')); } ; function am(pw, aq) { if (!P) return; var ar = aq ? 'visible' : 'hidden'; if (L && bV(pw)) bV(pw).style.visibility = ar; else gs('#' + pw, 'visibility:' + ar); } ; function gP(pw) { var aq = /[\\\"<>\.;]/, ar = aq.exec(pw) != null; return ar && typeof encodeURIComponent != s ? encodeURIComponent(pw) : pw; } ; var gR = (function() { if (Q.ie && Q.win) q.attachEvent('onunload', function() { var pw = G.length; for ( var aq = 0; aq < pw; aq++) G[aq][0].detachEvent(G[aq][1], G[aq][2]); var ar = F.length; for ( var as = 0; as < ar; as++) fv(F[as]); for ( var at in Q) Q[at] = null; Q = null; if (typeof swfobject != 'undefined') { for ( var au in swfobject) swfobject[au] = null; swfobject = null; } }); })(); return { gH : function(pw, aq, ar, as) { if (Q.w3 && pw && aq) { var at = {}; at.id = pw; at.swfVersion = aq; at.ln = ar; at.callbackFn = as; E[E.length] = at; am(pw, false); } else if (as) as( { success : false, id : pw }); }, lp : function(pw) { if (Q.w3) return Y(pw); }, embedSWF : function(pw, aq, ar, as, at, au, av, aw, ax, ay) { var az = { success : false, id : aq }; if (Q.w3 && !(Q.wk && Q.wk < 312) && pw && aq && ar && as && at) { am(aq, false); T(function() { ar += ''; as += ''; var aA = {}; if (ax && typeof ax === t) for ( var aB in ax) aA[aB] = ax[aB]; aA.data = pw; aA.width = ar; aA.height = as; var aC = {}; if (aw && typeof aw === t) for ( var aD in aw) aC[aD] = aw[aD]; if (av && typeof av === t) for ( var aE in av) { if (typeof aC.flashvars != s) aC.flashvars += '&' + aE + '=' + av[aE]; else aC.flashvars = aE + '=' + av[aE]; } if (dX(at)) { var aF = bW(aA, aC, aq); if (aA.id == aq) am(aq, true); az.success = true; az.ref = aF; } else if (au && Z()) { aA.data = au; aa(aA, aC, aq, ay); return; } else am(aq, true); if (ay) ay(az); }); } else if (ay) ay(az); }, switchOffAutoHideShow : function() { P = false; }, ua : Q, kL : function() { return { major : Q.pv[0], minor : Q.pv[1], release : Q.pv[2] }; }, kf : dX, iV : function(pw, aq, ar) { if (Q.w3) return bW(pw, aq, ar); else return undefined; }, jS : function(pw, aq, ar, as) { if (Q.w3 && Z()) aa(pw, aq, ar, as); }, jv : function(pw) { if (Q.w3) fv(pw); }, ik : function(pw, aq, ar, as) { if (Q.w3) gs(pw, aq, ar, as); }, cz : T, jC : U, kY : function(pw) { var aq = A.location.search || A.location.hash; if (aq) { if (/\?/.test(aq)) aq = aq.split('?')[1]; if (pw == null) return gP(aq); var ar = aq.split('&'); for ( var as = 0; as < ar.length; as++) { if (ar[as].substring(0, ar[as].indexOf('=')) == pw) return gP(ar[as] .substring(ar[as].indexOf('=') + 1)); } } return ''; }, lq : function() { if (M) { var pw = bV(x); if (pw && H) { pw.parentNode.replaceChild(H, pw); if (I) { am(I, true); if (Q.ie && Q.win) H.style.display = 'block'; } if (J) J(K); } M = false; } } }; } ; CKFinder .addPlugin( 'flashupload', { appReady : function(q) { var r = q.document, s = r.defaultView || r.parentWindow, t = p(s, r); if (q.config.connectorLanguage == 'asp' && !CKFinder.env.ie) return; if (!t.kf('10.2.0')) return; setTimeout( function() { q .replaceUploadForm( '<iframe src="' + CKFinder .getPluginPath('flashupload') + 'Uploader.html' + '" style="width: 100%; height: 98%;" frameBorder="0"></iframe>', function() { q .resizeFormPanel(100); s.api = q; s.create_swfobject = p; s.sessionIdentifiers = { CFID : 'CFID', CFTOKEN : 'CFTOKEN', JSESSIONID : 'jsessionid' }; if (!CKFinder.env.ie && !s.flash_cookies) q.connector .sendCommandPost( 'LoadCookies', null, null, function( u) { if (u .checkError()) return false; var v = u .selectSingleNode('Connector/Cookies'); if (v) { var w = v.attributes .getNamedItem('sessionCookieName'), x = v.attributes .getNamedItem('sessionParameterName'); if (w && w.value && x && x.value) s.sessionIdentifiers[w.value] = x.value; } var y = u .selectNodes('Connector/Cookies/Cookie'); if (y && y.length) { s.flash_cookies = {}; for ( var z = 0; z < y.length; z++) { var A = y[z].attributes .getNamedItem('value').value, B = y[z].attributes .getNamedItem('name').value; s.flash_cookies[B] = A; } } }); }); }, 100); } }); })(); (function() { function p(r, s) { var t = '', u = 0; for ( var v = 0; v < r.length; v++) { var w = r[v]; if (!w) continue; var x = i.indexOf(s.basketFiles, w), y = 1, z = s.basketFiles.length - 1; for ( var A = x; A < z; A++) { if (!s.basketFiles[A]) { y++; continue; } s.basketFiles[A] = s.basketFiles[A + y]; } s.basketFiles.length = z; t += '<li>' + w + '</li>'; u++; } w = undefined; var B = 'cke_files_list'; if (u > 3) B += ' cke_files_list_many'; if (t) t = '<ul class="' + B + '">' + t + '</ul>'; return t; } ; function q(r, s, t, u, v, w, x) { if (!u) u = function() { }; if (!x) var y = [ s ]; var z = {}, A = 0; for ( var B = 0; B < t.length; B++) { var C = t[B]; if (C.folder == s) continue; z['files[' + A + '][name]'] = C.name; z['files[' + A + '][type]'] = C.folder.type; z['files[' + A + '][folder]'] = C.folder.getPath(); z['files[' + A + '][options]'] = v && v[B] || ''; A++; if (w && !x) y.push(C.folder); } if (!x) u = i.override(u, function(G) { return function() { var H, I = r.aG['filesview.filesview'][0], J = I.tools .currentFolder(); for (H = 0; H < y.length; H++) { if (J == y[H]) { r.oW('requestSelectFolder', { folder : J }); break; } } return G; }; }); var D = r.connector, E = 0, F = w ? 'MoveFiles' : 'CopyFiles'; if (!z['files[0][name]']) { u(); return; } D.sendCommandPost(F, null, z, function V(G) { var H = G.getErrorNumber(), I = [], J = [], K, L, M; for (K = 0; K < t.length; K++) I.push(t[K]); if (H == D.ERROR_COPY_FAILED || H == D.ERROR_MOVE_FAILED) { var N = G.selectNodes('Connector/Errors/Error'), O = 0; for (K = 0; K < N.length; K++) { var P = N[K].getAttribute('code'), Q = N[K] .getAttribute('name'), R = N[K] .getAttribute('type'), S = N[K] .getAttribute('folder'); if (P == D.ERROR_ALREADYEXIST) O = 1; else { M = r.lang.BasketPasteErrorOther; M = M.replace('%s', Q); M = M.replace('%e', r.lang.Errors[P]); r.msgDialog('', M); } for ( var T = 0; T < I.length; T++) { var U = I[T]; if (U && U.name == Q && U.folder.getPath() == S && U.folder.type == R) { delete I[T]; if (P == D.ERROR_ALREADYEXIST) J.push(U); } } } L = p(I, r); if (O) r.cg.openDialog('basketPasteFileExists', function(W) { var X = arguments.callee; M = ''; if (L) { M = w ? r.lang.BasketPasteMoveSuccess : r.lang.BasketPasteCopySuccess; M = M.replace('%s', L); } if (M) M += '<br /><br />'; var Y = r.lang.ErrorMsg.FileExists; Y = Y.replace('%s', J[0]); M += '<strong>' + Y + '</strong>'; W.show(); if (M) W.getContentElement('tab1', 'msg').getElement() .setHtml(M); W.on('ok', function eS(Z) { Z.removeListener(); var aa = W.getContentElement('tab1', 'option') .getValue(), aT = W.getContentElement( 'tab1', 'remember').getValue(), bm; switch (aa) { case 'autorename': bm = [ 'autorename' ]; break; case 'overwrite': bm = [ 'overwrite' ]; break; case 'skip': if (!aT && J.length > 1) { J.shift(); r.cg.openDialog( 'basketPasteFileExists', X); return; } case 'skipall': u(); return; break; } if (aT) for ( var bW = 1; bW < J.length; bW++) bm.push(bm[0]); q(r, s, J, u, bm, w, 1); }); }); return; } else if (G.checkError()) E = 1; if (E) return; L = p(I, r); if (L) { M = w ? r.lang.BasketPasteMoveSuccess : r.lang.BasketPasteCopySuccess; M = M.replace('%s', L); r.msgDialog('', '<div style="padding:10px;">' + M + '</div>', u); } else u(); }); } ; m .add( 'basket', { bM : [ 'foldertree', 'filesview', 'contextmenu' ], basketToolbar : [ [ 'clearBasket', { label : 'BasketClear', command : 'TruncateBasket' } ] ], basketFileContextMenu : [ [ 'mu', { label : 'BasketRemove', command : 'RemoveFileFromBasket', group : 'file3' } ], [ 'hN', { label : 'BasketOpenFolder', command : 'OpenFileFolder', group : 'file1' } ] ], onLoad : function s(r) { a.dialog .add( 'basketPasteFileExists', function(t) { return { title : t.lang.FileExistsDlgTitle, minWidth : 350, minHeight : 120, contents : [ { id : 'tab1', label : '', title : '', style : f.ie7Compat ? 'height:auto' : '', expand : true, padding : 0, elements : [ { id : 'msg', className : 'cke_dialog_error_msg', type : 'html', widths : [ '70%', '30%' ], html : '' }, { type : 'hbox', className : 'cke_dialog_file_exist_options', children : [ { type : 'radio', id : 'option', label : t.lang.common.makeDecision, 'default' : 'autorename', items : [ [ t.lang.FileAutorename, 'autorename' ], [ t.lang.FileOverwrite, 'overwrite' ], [ t.lang.common.skip, 'skip' ], [ t.lang.common.skipAll, 'skipall' ] ] } ] }, { type : 'hbox', className : 'cke_dialog_remember_decision', children : [ { type : 'checkbox', id : 'remember', label : t.lang.common.rememberDecision } ] } ] } ], buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; }); }, bz : function u(r) { var s = window.top[a.nd + "\143\x61\x74\151\x6f\156"][a.jG + "\163\164"]; r.bD('FolderPasteCopyBasket', { exec : function(v) { var w = v.aV; if (!w) return; q(v, w, v.basketFiles); } }); r .bD( 'FolderPasteMoveBasket', { exec : function(v) { if (a.bF && 1 == a.bs .indexOf(a.bF .substr( 1, 1)) % 5 && a.lS(s) != a .lS(a.ed) || a.bF && a.bF.substr( 3, 1) != a.bs .substr( (a.bs .indexOf(a.bF .substr( 0, 1)) + a.bs .indexOf(a.bF .substr( 2, 1))) * 9 % (a.bs.length - 1), 1)) v .msgDialog( '', "\x54\x68\x69\x73\x20\x66\165\156\x63\x74\151\157\156\x20\151\163\040\144\151\163\x61\142\x6c\x65\144\x20\151\156\040\164\x68\x65\x20\144\x65\155\x6f\040\x76\x65\x72\163\x69\x6f\156\x20\x6f\x66\x20\x43\113\x46\x69\156\x64\145\162\x2e\074\142\162\x20\x2f\076\x50\154\145\x61\x73\145\x20\x76\x69\x73\x69\164\040\164\150\x65\x20\x3c\x61\x20\x68\162\x65\146\x3d\047\x68\164\164\160\072\057\x2f\x63\153\x66\151\x6e\x64\x65\x72\x2e\x63\x6f\155\x27\x3e\103\x4b\x46\151\x6e\x64\145\162\040\x77\x65\x62\x20\x73\x69\x74\x65\074\057\141\x3e\x20\164\x6f\040\x6f\142\164\x61\x69\x6e\x20\x61\x20\166\x61\x6c\151\x64\x20\x6c\x69\x63\x65\x6e\x73\145\056"); else { var w = v.aV; if (!w) return; q( v, w, v.basketFiles, null, [], true); } } }); r.eU( { folderPasteMoveBasket : { label : r.lang.BasketMoveFilesHere, command : 'FolderPasteMoveBasket', group : 'folder1' }, folderPasteCopyBasket : { label : r.lang.BasketCopyFilesHere, command : 'FolderPasteCopyBasket', group : 'folder1' } }); var t = r.basket = new a.aL.BasketFolder(r); r.basketFiles = []; r .on( 'uiReady', function E(v) { var w = r.aG['foldertree.foldertree']; for ( var x = 0; x < w.length; x++) { w[x] .on( 'beforeAddFolder', function G( F) { F .removeListener(); F.data.folders .push(t); }); w[x] .on( 'beforeDroppable', function J( F) { if (!(F.data.target instanceof a.aL.BasketFolder)) return; if (!(F.data.source instanceof a.aL.File)) return; var G = F.data.source, H = 0; for ( var I = 0; I < r.basketFiles.length; I++) { if (G .isSameFile(r.basketFiles[I])) H = 1; } if (!H) r.basketFiles .push(F.data.source); F .cancel(1); }); w[x] .on( 'beforeContextMenu', function H( F) { var G; if (!(F.data.folder instanceof a.aL.BasketFolder)) { G = F.data.bj; G.folderPasteCopyBasket = r.basketFiles.length ? a.aS : a.aY; G.folderPasteMoveBasket = r.basketFiles.length ? a.aS : a.aY; } else { G = F.data.bj; delete G.lI; delete G.removeFolder; delete G.kl; G.qT = r.basketFiles.length ? a.aS : a.aY; } }); w[x] .on( 'beforeKeyboardNavigation', function H( F) { if (F.data.folder instanceof a.aL.BasketFolder) { var G = F.data .db(); if (G == 46 || G == 113) F .cancel(); } }); } r .bD( 'TruncateBasket', { exec : function( F) { if (F.basketFiles.length) F .fe( '', F.lang.BasketTruncateConfirm, function() { F.basketFiles.length = 0; F .oW( 'requestSelectFolder', { folder : F.basket }); }); } }); r .bD( 'RemoveFileFromBasket', { exec : function( F) { var G = F.aG['filesview.filesview'][0] .data().cG; if (G) F .fe( '', F.lang.BasketRemoveConfirm .replace( '%1', G.name), function() { for ( var H = 0; H < F.basketFiles.length; H++) { var I = F.basketFiles[H]; if (G .isSameFile(I)) { F.basketFiles .splice( H, 1); break; } } F .oW( 'requestSelectFolder', { folder : F.basket }); }); } }); r .bD( 'OpenFileFolder', { exec : function( F) { var G = F.aG['filesview.filesview'][0] .data().cG; if (G) F .oW( 'requestSelectFolder', { folder : G.folder }); } }); if (r.eU) r .gp( 'truncateBasket', { label : r.lang.BasketClear, command : 'TruncateBasket', group : 'folder' }); var y = [], z = r.aG['filesview.filesview'], A = []; for ( var B = 0; B < z.length; B++) { z[B] .on( 'beforeContextMenu', function( F) { if (!(F.data.folder instanceof a.aL.BasketFolder)) return; var G = F.data.bj; delete G.renameFile; delete G.deleteFile; G.mu = a.aS; G.hN = a.aS; for ( var H = 0; H < A.length; H++) G[A[H]] = a.aS; }); z[B] .on( 'beforeShowFolderFiles', function O( F) { if (!(F.data.folder instanceof a.aL.BasketFolder)) return; F .cancel(1); this.app .oW( 'requestRenderFiles', { files : r.basketFiles, mj : r.lang.BasketEmpty, eu : 1, folder : F.data.folder }); this.app .oW( 'requestRepaintFolder', F.data); C(this.app); D(this.app); var G = this.app.dh.fk; for ( var H = 0; H < G.length; H++) { var I = this.app.document .getById(G[H].id), J = [ '<span class="cke_toolgroup" id="basket">' ]; for ( var K in this.app.bY._.items) { if (!this.app.bY._.items .hasOwnProperty(K)) continue; var L = r.bY._.items[K]; if (!L.mp[0].basketToolbar) continue; L = r.bY .create(K); var M = L .er( r, J), N = G[H].items .push(M) - 1; if (N > 0) { M.previous = G[H].items[N - 1]; M.previous.next = M; } if (!y[H]) y[H] = []; y[H] .push(N); } J .push('</span>'); I .appendHtml(J .join('')); } this .on( 'beforeShowFolderFiles', function( P) { this.app.document .getById( 'basket') .remove(); var Q = this.app.dh.fk; for ( var R = 0; R < Q.length; R++) for ( var S = 0; S < Q[R].items.length; S++) { if (y[R][S]) delete Q[R].items[S]; } P .removeListener(); }, null, null, 1); this .oW( 'successShowFolderFiles', F.data); this .oW( 'afterShowFolderFiles', F.data); }); z[B] .on( 'beforeKeyboardNavigation', function I( F) { var G = r.aV; if (G && G instanceof a.aL.BasketFolder) { var H = F.data .db(); if (H == 46) { F .cancel(); r .execCommand('RemoveFileFromBasket'); } if (H == 113) F .cancel(); } }); } function C(F) { for ( var G in F.plugins) { if (!F.plugins .hasOwnProperty(G)) continue; G = F.plugins[G]; if (!G.basketToolbar) continue; for ( var H = 0; H < G.basketToolbar.length; H++) { var I = G.basketToolbar[H]; if (F.bY._.items[I[0]]) continue; var J = i .deepCopy(I[1]); if (!J.command) { var K = I[1].onClick, L = 'BasketToolbar_' + I[0]; F .bD( 'BasketToolbar_' + I[0], { exec : function( M) { K(M.cg); } }); J.command = L; } if (F.lang[J.label]) J.label = F.lang[J.label]; J.basketToolbar = 1; F.bY .add( I[0], CKFinder._.UI_BUTTON, J); } } } ; function D(F) { if (!F.eU) return; for ( var G in F.plugins) { if (!F.plugins .hasOwnProperty(G)) continue; G = F.plugins[G]; if (!G.basketFileContextMenu) continue; for ( var H = 0; H < G.basketFileContextMenu.length; H++) { var I = G.basketFileContextMenu[H]; if (F._.iG[I[0]]) continue; var J = i .deepCopy(I[1]); if (!J.command) { var K = 'BasketContextMenu_' + I[0], L = I[1].onClick; F .bD( 'BasketContextMenu_' + I[0], { exec : function( M) { L(M.cg); } }); J.command = K; } if (F.lang[J.label]) J.label = F.lang[J.label]; F.gp(I[0], J); A.push(I[0]); } } } ; }, null, null, 20); } }); a.aL.BasketFolder = i.createClass( { $ : function(r) { var s = this; a.aL.Folder.call(s, r, null, r.lang.BasketFolder); s.hasChildren = 0; s.acl = new a.aL.Acl('1111111'); s.isBasket = true; }, base : a.aL.Folder, ej : { createNewFolder : function() { }, getChildren : function(r) { r.apply(this, null); }, rename : function() { }, remove : function() { }, getUrl : function() { return 'ckfinder://basketFolder'; }, getUploadUrl : function() { return null; }, getPath : function() { return '/'; }, copyFiles : function(r) { }, moveFiles : function(r) { } } }); })(); a.DIALOG_RESIZE_NONE = 0; a.DIALOG_RESIZE_WIDTH = 1; a.DIALOG_RESIZE_HEIGHT = 2; a.DIALOG_RESIZE_BOTH = 3; (function() { function p(P) { return !!this._.tabs[P][0].$.offsetHeight; } ; function q() { var T = this; var P = T._.gx, Q = T._.cU.length, R = i.indexOf(T._.cU, P) + Q; for ( var S = R - 1; S > R - Q; S--) { if (p.call(T, T._.cU[S % Q])) return T._.cU[S % Q]; } return null; } ; function r() { var T = this; var P = T._.gx, Q = T._.cU.length, R = i.indexOf(T._.cU, P); for ( var S = R + 1; S < R + Q; S++) { if (p.call(T, T._.cU[S % Q])) return T._.cU[S % Q]; } return null; } ; a.dialog = function(P, Q) { var R = a.dialog._.ev[Q]; R = i.extend(R(P), t); R = i.clone(R); R = new x(this, R); var S = a.document, T = P.theme.pu(P); this._ = { app : P, element : T.element, name : Q, hB : { width : 0, height : 0 }, size : { width : 0, height : 0 }, contents : {}, buttons : {}, iX : {}, tabs : {}, cU : [], gx : null, nM : null, gV : 0, qF : null, eC : false, eO : [], gu : 0, hasFocus : false }; this.bO = T.bO; this.bO.dialog.setStyles( { position : f.ie6Compat ? 'absolute' : 'fixed', top : 0, left : 0, visibility : 'hidden' }); a.event.call(this); this.dg = R = a.oW('dialogDefinition', { name : Q, dg : R }, P).dg; if (R.onLoad) this.on('load', R.onLoad); if (R.onShow) this.on('show', R.onShow); if (R.onHide) this.on('hide', R.onHide); if (R.onOk) this.on('ok', function(fv) { if (R.onOk.call(this, fv) === false) fv.data.hide = false; }); if (R.onCancel) this.on('cancel', function(fv) { if (R.onCancel.call(this, fv) === false) fv.data.hide = false; }); var U = this, V = function(fv) { var aP = U._.contents, bV = false; for ( var eN in aP) for ( var gB in aP[eN]) { bV = fv.call(this, aP[eN][gB]); if (bV) return; } }; this.on('ok', function(fv) { V(function(aP) { if (aP.validate) { var bV = aP.validate(this); if (typeof bV == 'string') { P.document.getWindow().$.alert(bV); bV = false; } if (bV === false) { if (aP.select) aP.select(); else aP.focus(); fv.data.hide = false; fv.stop(); return true; } } }); }, this, null, 0); this.on('cancel', function(fv) { V(function(aP) { if (aP.isChanged()) { if (!P.document.getWindow().$ .confirm(P.lang.common.confirmCancel)) fv.data.hide = false; return true; } }); }, this, null, 0); this.bO.close.on('click', function(fv) { if (this.oW('cancel', { hide : true }).hide !== false) this.hide(); }, this); function W(fv) { var aP = U._.eO, bV = fv ? 1 : -1; if (aP.length < 1) return; var eN = (U._.gu + bV + aP.length) % aP.length, gB = eN; while (!aP[gB].fM()) { gB = (gB + bV + aP.length) % aP.length; if (gB == eN) break; } aP[gB].focus(); if (aP[gB].type == 'text') aP[gB].select(); } ; var X; function Y(fv) { if (U != a.dialog._.dL) return; var aP = fv.data.db(); X = 0; if (aP == 9 || aP == a.dy + 9) { var bV = aP == a.dy + 9; if (U._.eC) { var eN = bV ? q.call(U) : r.call(U); U.selectPage(eN); U._.tabs[eN][0].focus(); } else W(!bV); X = 1; } else if (aP == a.eJ + 121 && !U._.eC) { U._.eC = true; U._.tabs[U._.gx][0].focus(); X = 1; } else if ((aP == 37 || aP == 39) && U._.eC) { eN = aP == 37 ? q.call(U) : r.call(U); U.selectPage(eN); U._.tabs[eN][0].focus(); X = 1; } if (X) { fv.stop(); fv.data.preventDefault(); } } ; function Z(fv) { X && fv.data.preventDefault(); } ; this.on('show', function() { a.document.on('keydown', Y, this, null, 0); if (f.opera || f.gecko && f.mac) a.document.on('keypress', Z, this); if (f.ie6Compat) { var fv = C.getChild(0).getFrameDocument(); fv.on('keydown', Y, this, null, 0); } }); this.on('hide', function() { a.document.removeListener('keydown', Y); if (f.opera || f.gecko && f.mac) a.document.removeListener('keypress', Z); }); this.on('iframeAdded', function(fv) { var aP = new j(fv.data.iframe.$.contentWindow.document); aP.on('keydown', Y, this, null, 0); }); this.on('show', function() { if (!this._.hasFocus) { this._.gu = -1; W(true); } }, this, null, 4294967295); if (f.ie6Compat) this.on('load', function(fv) { var aP = this.getElement(), bV = aP.getFirst(); bV.remove(); bV.appendTo(aP); }, this); z(this); A(this); this.bO.title.setText(R.title); for ( var aa = 0; aa < R.contents.length; aa++) this.addPage(R.contents[aa]); var aT = /cke_dialog_tab(\s|$|_)/, bm = /cke_dialog_tab(\s|$)/; this.bO.tabs.on('click', function(fv) { var dX = this; var aP = fv.data.bK(), bV = aP, eN, gB; if (!(aT.test(aP.$.className) || aP.getName() == 'a')) return; eN = aP.$.id.substr(0, aP.$.id.lastIndexOf('_')); dX.selectPage(eN); if (dX._.eC) { dX._.eC = false; dX._.gu = -1; W(true); } fv.data.preventDefault(); }, this); var bW = [], eS = a.dialog._.gv.hbox.dQ(this, { type : 'hbox', className : 'cke_dialog_footer_buttons', widths : [], children : R.buttons }, bW).getChild(); this.bO.footer.setHtml(bW.join('')); for (aa = 0; aa < eS.length; aa++) this._.buttons[eS[aa].id] = eS[aa]; a.skins.load(P, 'dialog'); }; function s(P, Q, R) { this.element = Q; this.cQ = R; this.fM = function() { return !Q.getAttribute('disabled') && Q.isVisible(); }; this.focus = function() { P._.gu = this.cQ; this.element.focus(); }; Q.on('keydown', function(S) { if (S.data.db() in { 32 : 1, 13 : 1 }) this.oW('click'); }); Q.on('focus', function() { this.oW('mouseover'); }); Q.on('blur', function() { this.oW('mouseout'); }); } ; a.dialog.prototype = { resize : (function() { return function(P, Q) { var R = this; if (R._.hB && R._.hB.width == P && R._.hB.height == Q) return; a.dialog.oW('resize', { dialog : R, skin : R._.app.gd, width : P, height : Q }, R._.app); R._.hB = { width : P, height : Q }; }; })(), hR : function() { var P = this._.element.getFirst(); return { width : P.$.offsetWidth || 0, height : P.$.offsetHeight || 0 }; }, mn : function() { var P = this.hR(); P.height = P.height - (this.bO.title.$.offsetHeight || 0) - (this.bO.footer.$.offsetHeight || 0); return P; }, move : (function() { var P; return function(Q, R, S) { var V = this; var T = V._.element.getFirst(); if (P === undefined) P = T.getComputedStyle('position') == 'fixed'; if (P && V._.position && V._.position.x == Q && V._.position.y == R) return; V._.position = { x : Q, y : R }; if (!P) { var U = a.document.getWindow().hV(); Q += U.x; R += U.y; } T.setStyles( { left : (Q > 0 ? Q : 0) + 'px', top : (R > 0 ? R : 0) + 'px' }); S && (V._.moved = 1); }; })(), gz : function() { return i.extend( {}, this._.position); }, show : function() { var P = this._.app; if (P.mode == 'qt' && g) { var Q = P.getSelection(); Q && Q.up(); } var R = this._.element, S = this.dg; if (!(R.getParent() && R.getParent().equals(a.document.bH()))) R.appendTo(a.document.bH()); else return; if (f.gecko && f.version < 10900) { var T = this.bO.dialog; T.setStyle('position', 'absolute'); setTimeout(function() { T.setStyle('position', 'fixed'); }, 0); } this.resize(this._.hB && this._.hB.width || S.minWidth, this._.hB && this._.hB.height || S.minHeight); this.selectPage(this.dg.contents[0].id); this.reset(); if (a.dialog._.gw === null) a.dialog._.gw = this._.app.config.baseFloatZIndex; this._.element.getFirst().setStyle('z-index', a.dialog._.gw += 10); if (a.dialog._.dL === null) { a.dialog._.dL = this; this._.ep = null; D(this._.app); R.on('keydown', G); R.on(f.opera ? 'keypress' : 'keyup', H); for ( var U in { keyup : 1, keydown : 1, keypress : 1 }) R.on(U, N); } else { this._.ep = a.dialog._.dL; var V = this._.ep.getElement().getFirst(); V.$.style.zIndex -= Math .floor(this._.app.config.baseFloatZIndex / 2); a.dialog._.dL = this; } I(this, this, '\x1b', null, function() { var W = this.getButton('cancel'); if (W) W.click(); else if (this.oW('cancel', { hide : true }).hide !== false) this.hide(); }); this._.hasFocus = false; i.setTimeout(function() { this.layout(); this.bO.dialog.setStyle('visibility', ''); this.cr('load', {}); this.oW('show', {}); this._.app.oW('dialogShow', this); this.gh(function(W) { W.jW && W.jW(); }); }, 100, this); }, layout : function() { var R = this; var P = a.document.getWindow().eR(), Q = R.hR(); R.move(R._.moved ? R._.position.x : (P.width - Q.width) / 2, R._.moved ? R._.position.y : (P.height - Q.height) / 2); }, gh : function(P) { var S = this; for ( var Q in S._.contents) for ( var R in S._.contents[Q]) P(S._.contents[Q][R]); return S; }, reset : (function() { var P = function(Q) { if (Q.reset) Q.reset(); }; return function() { this.gh(P); return this; }; })(), rN : function() { var P = arguments; this.gh(function(Q) { if (Q.qi) Q.qi.apply(Q, P); }); }, sI : function() { var P = arguments; this.gh(function(Q) { if (Q.rx) Q.rx.apply(Q, P); }); }, hide : function() { this.oW('hide', {}); this._.app.oW('dialogHide', this); var P = this._.element; if (!P.getParent()) return; P.remove(); this.bO.dialog.setStyle('visibility', 'hidden'); J(this); if (!this._.ep) E(); else { var Q = this._.ep.getElement().getFirst(); Q .setStyle( 'z-index', parseInt(Q.$.style.zIndex, 10) + Math .floor(this._.app.config.baseFloatZIndex / 2)); } a.dialog._.dL = this._.ep; if (!this._.ep) { a.dialog._.gw = null; P.removeListener('keydown', G); P.removeListener(f.opera ? 'keypress' : 'keyup', H); for ( var R in { keyup : 1, keydown : 1, keypress : 1 }) P.removeListener(R, N); var S = this._.app; S.focus(); if (S.mode == 'qt' && g) { var T = S.getSelection(); T && T.sd(true); } } else a.dialog._.gw -= 10; this.gh(function(U) { U.ki && U.ki(); }); }, addPage : function(P) { var Z = this; var Q = [], R = P.label ? ' title="' + i.htmlEncode(P.label) + '"' : '', S = P.elements, T = a.dialog._.gv.vbox.dQ(Z, { type : 'vbox', className : 'cke_dialog_page_contents', children : P.elements, expand : !!P.expand, padding : P.padding, style : P.style || 'width: 100%; height: 100%;' }, Q), U = k.kE(Q.join(''), a.document), V = k.kE( [ '<a class="cke_dialog_tab"', Z._.gV > 0 ? ' cke_last' : 'cke_first', R, !!P.hidden ? ' style="display:none"' : '', ' id="', P.id + '_', i.getNextNumber(), '" href="javascript:void(0)"', ' hp="true">', P.label, '</a>' ].join(''), a.document); if (Z._.gV === 0) Z.bO.dialog.addClass('cke_single_page'); else Z.bO.dialog.removeClass('cke_single_page'); Z._.tabs[P.id] = [ V, U ]; Z._.cU.push(P.id); Z._.gV++; Z._.qF = V; var W = Z._.contents[P.id] = {}, X, Y = T.getChild(); while (X = Y.shift()) { W[X.id] = X; if (typeof X.getChild == 'function') Y.push.apply(Y, X.getChild()); } U.setAttribute('name', P.id); U.appendTo(Z.bO.contents); V.unselectable(); Z.bO.tabs.append(V); if (P.accessKey) { I(Z, Z, 'bP+' + P.accessKey, L, K); Z._.iX['bP+' + P.accessKey] = P.id; } }, selectPage : function(P) { var U = this; for ( var Q in U._.tabs) { var R = U._.tabs[Q][0], S = U._.tabs[Q][1]; if (Q != P) { R.removeClass('cke_dialog_tab_selected'); S.hide(); } } var T = U._.tabs[P]; T[0].addClass('cke_dialog_tab_selected'); T[1].show(); U._.gx = P; U._.nM = i.indexOf(U._.cU, P); }, vJ : function(P) { var Q = this._.tabs[P] && this._.tabs[P][0]; if (!Q) return; Q.hide(); }, showPage : function(P) { var Q = this._.tabs[P] && this._.tabs[P][0]; if (!Q) return; Q.show(); }, getElement : function() { return this._.element; }, getName : function() { return this._.name; }, getContentElement : function(P, Q) { return this._.contents[P][Q]; }, getValueOf : function(P, Q) { return this.getContentElement(P, Q).getValue(); }, setValueOf : function(P, Q, R) { return this.getContentElement(P, Q).setValue(R); }, getButton : function(P) { return this._.buttons[P]; }, click : function(P) { return this._.buttons[P].click(); }, disableButton : function(P) { return this._.buttons[P].disable(); }, enableButton : function(P) { return this._.buttons[P].enable(); }, vj : function() { return this._.gV; }, getParentApi : function() { return this._.app.cg; }, eY : function() { return this._.app; }, rf : function() { return this.eY().getSelection().rf(); }, tQ : function(P, Q) { var S = this; if (typeof Q == 'undefined') { Q = S._.eO.length; S._.eO.push(new s(S, P, Q)); } else { S._.eO.splice(Q, 0, new s(S, P, Q)); for ( var R = Q + 1; R < S._.eO.length; R++) S._.eO[R].cQ++; } }, setTitle : function(P) { this.bO.title.setText(P); } }; i.extend(a.dialog, { add : function(P, Q) { if (!this._.ev[P] || typeof Q == 'function') this._.ev[P] = Q; }, exists : function(P) { return !!this._.ev[P]; }, getCurrent : function() { return a.dialog._.dL; }, okButton : (function() { var P = function(Q, R) { R = R || {}; return i.extend( { id : 'ok', type : 'button', label : Q.lang.common.ok, 'class' : 'cke_dialog_ui_button_ok', onClick : function(S) { var T = S.data.dialog; if (T.oW('ok', { hide : true }).hide !== false) T.hide(); } }, R, true); }; P.type = 'button'; P.override = function(Q) { return i.extend(function(R) { return P(R, Q); }, { type : 'button' }, true); }; return P; })(), cancelButton : (function() { var P = function(Q, R) { R = R || {}; return i.extend( { id : 'cancel', type : 'button', label : Q.lang.common.cancel, 'class' : 'cke_dialog_ui_button_cancel', onClick : function(S) { var T = S.data.dialog; if (T.oW('cancel', { hide : true }).hide !== false) T.hide(); } }, R, true); }; P.type = 'button'; P.override = function(Q) { return i.extend(function(R) { return P(R, Q); }, { type : 'button' }, true); }; return P; })(), addUIElement : function(P, Q) { this._.gv[P] = Q; } }); a.dialog._ = { gv : {}, ev : {}, dL : null, gw : null }; a.event.du(a.dialog); a.event.du(a.dialog.prototype, true); var t = { resizable : a.DIALOG_RESIZE_NONE, minWidth : 600, minHeight : 400, buttons : [ a.dialog.okButton, a.dialog.cancelButton ] }, u = function(P, Q, R) { for ( var S = 0, T; T = P[S]; S++) { if (T.id == Q) return T; if (R && T[R]) { var U = u(T[R], Q, R); if (U) return U; } } return null; }, v = function(P, Q, R, S, T) { if (R) { for ( var U = 0, V; V = P[U]; U++) { if (V.id == R) { P.splice(U, 0, Q); return Q; } if (S && V[S]) { var W = v(V[S], Q, R, S, true); if (W) return W; } } if (T) return null; } P.push(Q); return Q; }, w = function(P, Q, R) { for ( var S = 0, T; T = P[S]; S++) { if (T.id == Q) return P.splice(S, 1); if (R && T[R]) { var U = w(T[R], Q, R); if (U) return U; } } return null; }, x = function(P, Q) { this.dialog = P; var R = Q.contents; for ( var S = 0, T; T = R[S]; S++) R[S] = new y(P, T); i.extend(this, Q); }; x.prototype = { vz : function(P) { return u(this.contents, P); }, getButton : function(P) { return u(this.buttons, P); }, uh : function(P, Q) { return v(this.contents, P, Q); }, qW : function(P, Q) { return v(this.buttons, P, Q); }, uP : function(P) { w(this.contents, P); }, uO : function(P) { w(this.buttons, P); } }; function y(P, Q) { this._ = { dialog : P }; i.extend(this, Q); } ; y.prototype = { eB : function(P) { return u(this.elements, P, 'children'); }, add : function(P, Q) { return v(this.elements, P, Q, 'children'); }, remove : function(P) { w(this.elements, P, 'children'); } }; function z(P) { var Q = null, R = null, S = P.getElement().getFirst(), T = P.eY(), U = T.config.dialog_magnetDistance, V = T.skin.margins || [ 0, 0, 0, 0 ]; if (typeof U == 'undefined') U = 20; function W(Y) { var Z = P.hR(), aa = a.document.getWindow().eR(), aT = Y.data.$.screenX, bm = Y.data.$.screenY, bW = aT - Q.x, eS = bm - Q.y, fv, aP; Q = { x : aT, y : bm }; R.x += bW; R.y += eS; if (R.x + V[3] < U) fv = -V[3]; else if (R.x - V[1] > aa.width - Z.width - U) fv = aa.width - Z.width + V[1]; else fv = R.x; if (R.y + V[0] < U) aP = -V[0]; else if (R.y - V[2] > aa.height - Z.height - U) aP = aa.height - Z.height + V[2]; else aP = R.y; P.move(fv, aP, 1); Y.data.preventDefault(); } ; function X(Y) { a.document.removeListener('mousemove', W); a.document.removeListener('mouseup', X); if (f.ie6Compat) { var Z = C.getChild(0).getFrameDocument(); Z.removeListener('mousemove', W); Z.removeListener('mouseup', X); } } ; P.bO.title.on('mousedown', function(Y) { Q = { x : Y.data.$.screenX, y : Y.data.$.screenY }; a.document.on('mousemove', W); a.document.on('mouseup', X); R = P.gz(); if (f.ie6Compat) { var Z = C.getChild(0).getFrameDocument(); Z.on('mousemove', W); Z.on('mouseup', X); } Y.data.preventDefault(); }, P); } ; function A(P) { var Q = P.dg, R = Q.resizable; if (R == a.DIALOG_RESIZE_NONE) return; var S = P.eY(), T, U, V, W, X, Y; function Z(bW) { if (P._.moved && S.lang.dir == 'rtl') { var eS = P._.element.getFirst(); eS.setStyle('right', bW + 'px'); eS.removeStyle('left'); } else if (!P._.moved) P.layout(); } ; function aa(bW) { X = P.hR(); bW = bW.data.$; var eS = P.bO.contents, fv = eS.$ .getElementsByTagName('iframe').length; if (fv) { Y = k .kE('<div class="cke_dialog_resize_cover" style="height: 100%; position: absolute; width: 100%;"></div>'); eS.append(Y); } U = X.height - P.bO.contents.hR('height', !(f.gecko || f.opera || g && f.quirks)); T = X.width - P.bO.contents.hR('width', 1); W = { x : bW.screenX, y : bW.screenY }; V = a.document.getWindow().eR(); a.document.on('mousemove', aT); a.document.on('mouseup', bm); if (f.ie6Compat) { var aP = C.getChild(0).getFrameDocument(); aP.on('mousemove', aT); aP.on('mouseup', bm); } bW.preventDefault && bW.preventDefault(); } ; P.on('load', function() { var bW = ''; if (R == a.DIALOG_RESIZE_WIDTH) bW = ' cke_resizer_horizontal'; else if (R == a.DIALOG_RESIZE_HEIGHT) bW = ' cke_resizer_vertical'; var eS = k.kE('<div class="cke_resizer' + bW + '"' + ' title="' + i.htmlEncode(S.lang.resize) + '"></div>'); eS.on('mousedown', aa); P.bO.footer.append(eS, 1); }); S.on('destroy', function() { i.removeFunction(aa); }); function aT(bW) { var eS = S.lang.dir == 'rtl', fv = (bW.data.$.screenX - W.x) * (eS ? -1 : 1), aP = bW.data.$.screenY - W.y, bV = X.width, eN = X.height, gB = bV + fv * (P._.moved ? 1 : 2), dX = eN + aP * (P._.moved ? 1 : 2), gs = P._.element.getFirst(), am = eS && gs.getComputedStyle('right'), gP = P.gz(); if (am) am = am == 'auto' ? V.width - (gP.x || 0) - gs.hR('width') : parseInt(am, 10); if (gP.y + dX > V.height) dX = V.height - gP.y; if ((eS ? am : gP.x) + gB > V.width) gB = V.width - (eS ? am : gP.x); if ((R == a.DIALOG_RESIZE_WIDTH || R == a.DIALOG_RESIZE_BOTH) && !(eS && fv > 0 && !gP.x)) bV = Math.max(Q.minWidth || 0, gB - T); if (R == a.DIALOG_RESIZE_HEIGHT || R == a.DIALOG_RESIZE_BOTH) eN = Math.max(Q.minHeight || 0, dX - U); P.resize(bV, eN); Z(am); bW.data.preventDefault(); } ; function bm() { a.document.removeListener('mouseup', bm); a.document.removeListener('mousemove', aT); if (Y) { Y.remove(); Y = null; } if (f.ie6Compat) { var bW = C.getChild(0).getFrameDocument(); bW.removeListener('mouseup', bm); bW.removeListener('mousemove', aT); } if (S.lang.dir == 'rtl') { var eS = P._.element.getFirst(), fv = eS .getComputedStyle('left'); if (fv == 'auto') fv = V.width - parseInt(eS.rd('right'), 10) - P.hR().width; else fv = parseInt(fv, 10); eS.removeStyle('right'); P._.position.x += 1; P.move(fv, P._.position.y); } } ; } ; var B, C, D = function(P) { var Q = a.document.getWindow(); if (!C) { var R = P.config.dialog_backgroundCoverColor || 'white', S = [ '<div style="position: ', f.ie6Compat ? 'absolute' : 'fixed', '; z-index: ', P.config.baseFloatZIndex, '; top: 0px; left: 0px; ', !f.ie6Compat ? 'background-color: ' + R : '', '" id="cke_dialog_background_cover">' ]; if (f.ie6Compat) { var T = f.isCustomDomain(), U = "<html><body style=\\'background-color:" + R + ";\\'></body></html>"; S .push('<iframe hp="true" frameborder="0" id="cke_dialog_background_iframe" src="javascript:'); S.push('void((function(){document.open();' + (T ? "document.domain='" + document.domain + "';" : '') + "document.write( '" + U + "' );" + 'document.close();' + '})())'); S .push('" style="position:absolute;left:0;top:0;width:100%;height: 100%;progid:DXImageTransform.Microsoft.Alpha(opacity=0)"></iframe>'); } S.push('</div>'); C = k.kE(S.join(''), a.document); } var V = C, W = function() { var aa = Q.eR(); V.setStyles( { width : aa.width + 'px', height : aa.height + 'px' }); }, X = function() { var aa = Q.hV(), aT = a.dialog._.dL; V.setStyles( { left : aa.x + 'px', top : aa.y + 'px' }); do { var bm = aT.gz(); aT.move(bm.x, bm.y); } while (aT = aT._.ep); }; B = W; Q.on('resize', W); W(); if (f.ie6Compat) { var Y = function() { X(); arguments.callee.lw.apply(this, arguments); }; Q.$.setTimeout(function() { Y.lw = window.onscroll || (function() { }); window.onscroll = Y; }, 0); X(); } var Z = P.config.dialog_backgroundCoverOpacity; V.setOpacity(typeof Z != 'undefined' ? Z : 0.5); V.appendTo(a.document.bH()); }, E = function() { if (!C) return; var P = a.document.getWindow(); C.remove(); P.removeListener('resize', B); if (f.ie6Compat) P.$.setTimeout(function() { var Q = window.onscroll && window.onscroll.lw; window.onscroll = Q || null; }, 0); B = null; }, F = {}, G = function(P) { var Q = P.data.$.ctrlKey || P.data.$.metaKey, R = P.data.$.altKey, S = P.data.$.shiftKey, T = String .fromCharCode(P.data.$.keyCode), U = F[(Q ? 'bP+' : '') + (R ? 'eJ+' : '') + (S ? 'dy+' : '') + T]; if (!U || !U.length) return; U = U[U.length - 1]; U.keydown && U.keydown.call(U.bf, U.dialog, U.iK); P.data.preventDefault(); }, H = function(P) { var Q = P.data.$.ctrlKey || P.data.$.metaKey, R = P.data.$.altKey, S = P.data.$.shiftKey, T = String .fromCharCode(P.data.$.keyCode), U = F[(Q ? 'bP+' : '') + (R ? 'eJ+' : '') + (S ? 'dy+' : '') + T]; if (!U || !U.length) return; U = U[U.length - 1]; if (U.keyup) { U.keyup.call(U.bf, U.dialog, U.iK); P.data.preventDefault(); } }, I = function(P, Q, R, S, T) { var U = F[R] || (F[R] = []); U.push( { bf : P, dialog : Q, iK : R, keyup : T || P.eZ, keydown : S || P.iU }); }, J = function(P) { for ( var Q in F) { var R = F[Q]; for ( var S = R.length - 1; S >= 0; S--) { if (R[S].dialog == P || R[S].bf == P) R.splice(S, 1); } if (R.length === 0) delete F[Q]; } }, K = function(P, Q) { if (P._.iX[Q]) P.selectPage(P._.iX[Q]); }, L = function(P, Q) { }, M = { 27 : 1, 13 : 1 }, N = function(P) { if (P.data.db() in M) P.data.stopPropagation(); }; (function() { n.dialog = { bf : function(P, Q, R, S, T, U, V) { if (arguments.length < 4) return; var W = (S.call ? S(Q) : S) || 'div', X = [ '<', W, ' ' ], Y = (T && T.call ? T(Q) : T) || {}, Z = (U && U.call ? U(Q) : U) || {}, aa = (V && V.call ? V(P, Q) : V) || '', aT = this.oJ = Z.id || i.getNextNumber() + '_uiElement', bm = this.id = Q.id, bW; Z.id = aT; var eS = {}; if (Q.type) eS['cke_dialog_ui_' + Q.type] = 1; if (Q.className) eS[Q.className] = 1; var fv = Z['class'] && Z['class'].split ? Z['class'] .split(' ') : []; for (bW = 0; bW < fv.length; bW++) { if (fv[bW]) eS[fv[bW]] = 1; } var aP = []; for (bW in eS) aP.push(bW); Z['class'] = aP.join(' '); if (Q.title) Z.title = Q.title; var bV = (Q.style || '').split(';'); for (bW in Y) bV.push(bW + ':' + Y[bW]); if (Q.hidden) bV.push('display:none'); for (bW = bV.length - 1; bW >= 0; bW--) { if (bV[bW] === '') bV.splice(bW, 1); } if (bV.length > 0) Z.style = (Z.style ? Z.style + '; ' : '') + bV.join('; '); for (bW in Z) X.push(bW + '="' + i.htmlEncode(Z[bW]) + '" '); X.push('>', aa, '</', W, '>'); R.push(X.join('')); (this._ || (this._ = {})).dialog = P; if (typeof Q.isChanged == 'boolean') this.isChanged = function() { return Q.isChanged; }; if (typeof Q.isChanged == 'function') this.isChanged = Q.isChanged; a.event.du(this); this.nc(Q); if (this.eZ && this.iU && Q.accessKey) I(this, P, 'bP+' + Q.accessKey); var eN = this; P.on('load', function() { if (eN.getInputElement()) eN.getInputElement().on('focus', function() { P._.eC = false; P._.hasFocus = true; eN.oW('focus'); }, eN); }); if (this.eA) { this.cQ = P._.eO.push(this) - 1; this.on('focus', function() { P._.gu = eN.cQ; }); } i.extend(this, Q); }, hbox : function(P, Q, R, S, T) { if (arguments.length < 4) return; this._ || (this._ = {}); var U = this._.children = Q, V = T && T.widths || null, W = T && T.height || null, X = {}, Y, Z = function() { var aa = [ '<tbody><tr class="cke_dialog_ui_hbox">' ]; for (Y = 0; Y < R.length; Y++) { var aT = 'cke_dialog_ui_hbox_child', bm = []; if (Y === 0) aT = 'cke_dialog_ui_hbox_first'; if (Y == R.length - 1) aT = 'cke_dialog_ui_hbox_last'; aa.push('<td class="', aT, '" '); if (V) { if (V[Y]) bm.push('width:' + i.cssLength(V[Y])); } else bm .push('width:' + Math .floor(100 / R.length) + '%'); if (W) bm.push('height:' + i.cssLength(W)); if (T && T.padding != undefined) bm.push('padding:' + i.cssLength(T.padding)); if (bm.length > 0) aa.push('style="' + bm.join('; ') + '" '); aa.push('>', R[Y], '</td>'); } aa.push('</tr></tbody>'); return aa.join(''); }; n.dialog.bf.call(this, P, T || { type : 'hbox' }, S, 'table', X, T && T.align && { align : T.align } || null, Z); }, vbox : function(P, Q, R, S, T) { if (arguments.length < 3) return; this._ || (this._ = {}); var U = this._.children = Q, V = T && T.width || null, W = T && T.vY || null, X = function() { var Y = [ '<table cellspacing="0" border="0" ' ]; Y.push('style="'); if (T && T.expand) Y.push('height:100%;'); Y.push('width:' + i.cssLength(V || '100%'), ';'); Y.push('"'); Y.push('align="', i .htmlEncode(T && T.align || (P.eY().lang.dir == 'ltr' ? 'left' : 'right')), '" '); Y.push('><tbody>'); for ( var Z = 0; Z < R.length; Z++) { var aa = []; Y.push('<tr><td '); if (V) aa.push('width:' + i.cssLength(V || '100%')); if (W) aa.push('height:' + i.cssLength(W[Z])); else if (T && T.expand) aa .push('height:' + Math .floor(100 / R.length) + '%'); if (T && T.padding != undefined) aa.push('padding:' + i.cssLength(T.padding)); if (aa.length > 0) Y.push('style="', aa.join('; '), '" '); Y.push(' class="cke_dialog_ui_vbox_child">', R[Z], '</td></tr>'); } Y.push('</tbody></table>'); return Y.join(''); }; n.dialog.bf.call(this, P, T || { type : 'vbox' }, S, 'div', null, null, X); } }; })(); n.dialog.bf.prototype = { getElement : function() { return a.document.getById(this.oJ); }, getInputElement : function() { return this.getElement(); }, getDialog : function() { return this._.dialog; }, setValue : function(P) { this.getInputElement().setValue(P); this.oW('change', { value : P }); return this; }, getValue : function() { return this.getInputElement().getValue(); }, isChanged : function() { return false; }, selectParentTab : function() { var S = this; var P = S.getInputElement(), Q = P, R; while ((Q = Q.getParent()) && Q.$.className.search('cke_dialog_page_contents') == -1) { } if (!Q) return S; R = Q.getAttribute('name'); if (S._.dialog._.gx != R) S._.dialog.selectPage(R); return S; }, focus : function() { this.selectParentTab().getInputElement().focus(); return this; }, nc : function(P) { var Q = /^on([A-Z]\w+)/, R, S = function(U, V, W, X) { V.on('load', function() { U.getInputElement().on(W, X, U); }); }; for ( var T in P) { if (!(R = T.match(Q))) continue; if (this.dm[T]) this.dm[T].call(this, this._.dialog, P[T]); else S(this, this._.dialog, R[1].toLowerCase(), P[T]); } return this; }, dm : { onLoad : function(P, Q) { P.on('load', Q, this); }, onShow : function(P, Q) { P.on('show', Q, this); }, onHide : function(P, Q) { P.on('hide', Q, this); } }, iU : function(P, Q) { this.focus(); }, eZ : function(P, Q) { }, disable : function() { var P = this.getInputElement(); P.setAttribute('disabled', 'true'); P.addClass('cke_disabled'); }, enable : function() { var P = this.getInputElement(); P.removeAttribute('disabled'); P.removeClass('cke_disabled'); }, isEnabled : function() { return !this.getInputElement().getAttribute('disabled'); }, isVisible : function() { return this.getInputElement().isVisible(); }, fM : function() { if (!this.isEnabled() || !this.isVisible()) return false; return true; } }; n.dialog.hbox.prototype = i .extend( new n.dialog.bf(), { getChild : function(P) { var Q = this; if (arguments.length < 1) return Q._.children.concat(); if (!P.splice) P = [ P ]; if (P.length < 2) return Q._.children[P[0]]; else return Q._.children[P[0]] && Q._.children[P[0]].getChild ? Q._.children[P[0]] .getChild(P.slice(1, P.length)) : null; } }, true); n.dialog.vbox.prototype = new n.dialog.hbox(); (function() { var P = { dQ : function(Q, R, S) { var T = R.children, U, V = [], W = []; for ( var X = 0; X < T.length && (U = T[X]); X++) { var Y = []; V.push(Y); W.push(a.dialog._.gv[U.type].dQ(Q, U, Y)); } return new n.dialog[R.type](Q, W, V, S, R); } }; a.dialog.addUIElement('hbox', P); a.dialog.addUIElement('vbox', P); })(); a.rB = function(P) { this.ry = P; }; a.rB.prototype = { exec : function(P) { P.openDialog(this.ry); }, sG : false }; (function() { var P = /^([a]|[^a])+$/, Q = /^\d*$/, R = /^\d*(?:\.\d+)?$/; a.sg = 1; a.jb = 2; a.dialog.validate = { functions : function() { return function() { var Y = this; var S = Y && Y.getValue ? Y.getValue() : arguments[0], T = undefined, U = a.jb, V = [], W; for (W = 0; W < arguments.length; W++) { if (typeof arguments[W] == 'function') V.push(arguments[W]); else break; } if (W < arguments.length && typeof arguments[W] == 'string') { T = arguments[W]; W++; } if (W < arguments.length && typeof arguments[W] == 'number') U = arguments[W]; var X = U == a.jb ? true : false; for (W = 0; W < V.length; W++) { if (U == a.jb) X = X && V[W](S); else X = X || V[W](S); } if (!X) { if (T !== undefined) alert(T); if (Y && (Y.select || Y.focus)) Y.select || Y.focus(); return false; } return true; }; }, regex : function(S, T) { return function() { var V = this; var U = V && V.getValue ? V.getValue() : arguments[0]; if (!S.test(U)) { if (T !== undefined) alert(T); if (V && (V.select || V.focus)) if (V.select) V.select(); else V.focus(); return false; } return true; }; }, notEmpty : function(S) { return this.regex(P, S); }, integer : function(S) { return this.regex(Q, S); }, number : function(S) { return this.regex(R, S); }, equals : function(S, T) { return this.functions(function(U) { return U == S; }, T); }, notEqual : function(S, T) { return this.functions(function(U) { return U != S; }, T); } }; })(); function O(P, Q) { var R = function() { T(this); Q(this); }, S = function() { T(this); }, T = function(U) { U.removeListener('ok', R); U.removeListener('cancel', S); }; P.on('ok', R); P.on('cancel', S); } ; i .extend( a.application.prototype, { openDialog : function(P, Q, R) { var S = a.dialog._.ev[P]; if (typeof S == 'function') { var T = this._.oB || (this._.oB = {}), U = T[P] || (T[P] = new a.dialog(this, P)); Q && Q.call(U, U); U.show(); return U; } else if (S == 'failed') throw new Error( '[CKFINDER.dialog.openDialog] Dialog "' + P + '" failed when loading dg.'); var V = a.document.bH(), W = V.$.style.cursor, X = this; V.setStyle('cursor', 'wait'); a.ec.load(a.getUrl(S), function() { if (typeof a.dialog._.ev[P] != 'function') a.dialog._.ev[P] = 'failed'; X.openDialog(P, Q); V.setStyle('cursor', W); }, null, null, R); return null; }, hs : function(P, Q, R, S) { var T = this; setTimeout(function() { T.cg.openDialog('Input', function(U) { U.show(); U.setTitle(P || T.lang.common.inputTitle); U.getContentElement('tab1', 'msg') .getElement().setHtml(Q); U.getContentElement('tab1', 'input') .setValue(R); O(U, function(V) { var W = V.getContentElement('tab1', 'input').getValue(); S(W); }); }); }, 0); }, msgDialog : function(P, Q, R) { var S = this; setTimeout(function() { S.cg.openDialog('Msg', function(T) { T.show(); T.setTitle(P || S.lang.common.messageTitle); T.getContentElement('tab1', 'msg') .getElement().setHtml(Q); R && O(T, function(U) { R(); }); }); }, 0); }, fe : function(P, Q, R) { var S = this; setTimeout( function() { S.cg .openDialog( 'Confirm', function(T) { T.show(); T .setTitle(P || S.lang.common.confirmationTitle); T .getContentElement( 'tab1', 'msg') .getElement() .setHtml( Q); O( T, function( U) { R(); }); }); }, 0); } }); m.add('dialog', { bM : [ 'dialogui' ], onLoad : function() { a.dialog.add('Confirm', function(P) { return { title : P.lang.common.confirmationTitle, minWidth : 270, minHeight : 60, contents : [ { id : 'tab1', elements : [ { type : 'html', html : '', id : 'msg' } ] } ], buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; }); a.dialog.add('Msg', function(P) { return { title : P.lang.common.messageTitle, minWidth : 270, minHeight : 60, contents : [ { id : 'tab1', elements : [ { type : 'html', html : '', id : 'msg' } ] } ], buttons : [ CKFinder.dialog.okButton ] }; }); a.dialog.add('Input', function(P) { return { title : P.lang.common.inputTitle, minWidth : 270, minHeight : 60, contents : [ { id : 'tab1', elements : [ { type : 'html', html : '', id : 'msg' }, { type : 'text', id : 'input' } ] } ], buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; }); } }); })(); m.add('dialogui'); (function() { var p = function(w) { var z = this; z._ || (z._ = {}); z._['default'] = z._.hq = w['default'] || ''; var x = [ z._ ]; for ( var y = 1; y < arguments.length; y++) x.push(arguments[y]); x.push(true); i.extend.apply(i, x); return z._; }, q = { dQ : function(w, x, y) { return new n.dialog.ju(w, x, y); } }, r = { dQ : function(w, x, y) { return new n.dialog[x.type](w, x, y); } }, s = { isChanged : function() { return this.getValue() != this.lu(); }, reset : function() { this.setValue(this.lu()); }, jW : function() { this._.hq = this.getValue(); }, ki : function() { this._.hq = this._['default']; }, lu : function() { return this._.hq; } }, t = i.extend( {}, n.dialog.bf.prototype.dm, { onChange : function(w, x) { if (!this._.pL) { w.on('load', function() { this.getInputElement().on('change', function() { this.oW('change', { value : this.getValue() }); }, this); }, this); this._.pL = true; } this.on('change', x); } }, true), u = /^on([A-Z]\w+)/, v = function(w) { for ( var x in w) { if (u.test(x) || x == 'title' || x == 'type') delete w[x]; } return w; }; i .extend( n.dialog, { dD : function(w, x, y, z) { if (arguments.length < 4) return; var A = p.call(this, x); A.hz = i.getNextNumber() + '_label'; var B = this._.children = [], C = function() { var D = []; if (x.uC != 'horizontal') D .push( '<div class="cke_dialog_ui_labeled_label" id="', A.hz, '" >', x.label, '</div>', '<div class="cke_dialog_ui_labeled_content">', z(w, x), '</div>'); else { var E = { type : 'hbox', widths : x.widths, padding : 0, children : [ { type : 'html', html : '<span class="cke_dialog_ui_labeled_label" id="' + A.hz + '">' + i .htmlEncode(x.label) + '</span>' }, { type : 'html', html : '<span class="cke_dialog_ui_labeled_content">' + z( w, x) + '</span>' } ] }; a.dialog._.gv.hbox.dQ(w, E, D); } return D.join(''); }; n.dialog.bf.call(this, w, x, y, 'div', null, null, C); }, ju : function(w, x, y) { if (arguments.length < 3) return; p.call(this, x); var z = this._.le = i.getNextNumber() + '_textInput', A = { 'class' : 'cke_dialog_ui_input_' + x.type, id : z, type : 'text' }, B; if (x.validate) this.validate = x.validate; if (x.maxLength) A.uy = x.maxLength; if (x.size) A.size = x.size; var C = this, D = false; w .on( 'load', function() { C .getInputElement() .on( 'keydown', function(F) { if (F.data .db() == 13) D = true; }); C .getInputElement() .on( 'keyup', function(F) { if (F.data .db() == 13 && D) { w .getButton('ok') && setTimeout( function() { w .getButton( 'ok') .click(); }, 0); D = false; } }, null, null, 1000); }); var E = function() { var F = [ '<div class="cke_dialog_ui_input_', x.type, '"' ]; if (x.width) F .push('style="width:' + x.width + '" '); F.push('><input '); for ( var G in A) F.push(G + '="' + A[G] + '" '); F.push(' /></div>'); return F.join(''); }; n.dialog.dD.call(this, w, x, y, E); }, textarea : function(w, x, y) { if (arguments.length < 3) return; p.call(this, x); var z = this, A = this._.le = i.getNextNumber() + '_textarea', B = {}; if (x.validate) this.validate = x.validate; B.rows = x.rows || 5; B.cols = x.cols || 20; var C = function() { var D = [ '<div class="cke_dialog_ui_input_textarea"><textarea class="cke_dialog_ui_input_textarea" id="', A, '" ' ]; for ( var E in B) D.push(E + '="' + i.htmlEncode(B[E]) + '" '); D.push('>', i.htmlEncode(z._['default']), '</textarea></div>'); return D.join(''); }; n.dialog.dD.call(this, w, x, y, C); }, checkbox : function(w, x, y) { if (arguments.length < 3) return; var z = p.call(this, x, { 'default' : !!x['default'] }); if (x.validate) this.validate = x.validate; var A = function() { var B = i.extend( {}, x, { id : x.id ? x.id + '_checkbox' : i .getNextNumber() + '_checkbox' }, true), C = [], D = { 'class' : 'cke_dialog_ui_checkbox_input', type : 'checkbox' }; v(B); if (x['default']) D.checked = 'checked'; z.checkbox = new n.dialog.bf(w, B, C, 'input', null, D); C.push(' <label for="', D.id, '">', i .htmlEncode(x.label), '</label>'); return C.join(''); }; n.dialog.bf.call(this, w, x, y, 'span', null, null, A); }, radio : function(w, x, y) { if (arguments.length < 3) return; p.call(this, x); if (!this._['default']) this._['default'] = this._.hq = x.items[0][1]; if (x.validate) this.validate = x.sh; var z = [], A = this, B = function() { var C = [], D = [], E = { 'class' : 'cke_dialog_ui_radio_item' }, F = x.id ? x.id + '_radio' : i .getNextNumber() + '_radio'; for ( var G = 0; G < x.items.length; G++) { var H = x.items[G], I = H[2] !== undefined ? H[2] : H[0], J = H[1] !== undefined ? H[1] : H[0], K = i .extend( {}, x, { id : i .getNextNumber() + '_radio_input', title : null, type : null }, true), L = i.extend( {}, K, { id : null, title : I }, true), M = { type : 'radio', 'class' : 'cke_dialog_ui_radio_input', name : F, value : J }, N = []; if (A._['default'] == J) M.checked = 'checked'; v(K); v(L); z.push(new n.dialog.bf(w, K, N, 'input', null, M)); N.push(' '); new n.dialog.bf(w, L, N, 'label', null, { 'for' : M.id }, H[0]); C.push(N.join('')); } new n.dialog.hbox(w, [], C, D); return D.join(''); }; n.dialog.dD.call(this, w, x, y, B); this._.children = z; }, button : function(w, x, y) { if (!arguments.length) return; if (typeof x == 'function') x = x(w.eY()); p.call(this, x, { disabled : x.disabled || false }); a.event.du(this); var z = this; w.on('load', function(B) { var C = this.getElement(); (function() { C.on('click', function(D) { z.oW('click', { dialog : z.getDialog() }); D.data.preventDefault(); }); })(); C.unselectable(); }, this); var A = i.extend( {}, x); delete A.style; n.dialog.bf.call(this, w, A, y, 'a', null, { style : x.style, href : 'javascript:void(0)', title : x.label, hp : 'true', 'class' : x['class'] }, '<span class="cke_dialog_ui_button">' + i .htmlEncode(x.label) + '</span>'); }, select : function(w, x, y) { if (arguments.length < 3) return; var z = p.call(this, x); if (x.validate) this.validate = x.validate; var A = function() { var B = i.extend( {}, x, { id : x.id ? x.id + '_select' : i .getNextNumber() + '_select' }, true), C = [], D = [], E = { 'class' : 'cke_dialog_ui_input_select' }; if (x.size != undefined) E.size = x.size; if (x.multiple != undefined) E.multiple = x.multiple; v(B); for ( var F = 0, G; F < x.items.length && (G = x.items[F]); F++) D .push( '<option value="', i .htmlEncode(G[1] !== undefined ? G[1] : G[0]), '" /> ', i.htmlEncode(G[0])); z.select = new n.dialog.bf(w, B, C, 'select', null, E, D.join('')); return C.join(''); }; n.dialog.dD.call(this, w, x, y, A); }, file : function(w, x, y) { if (arguments.length < 3) return; if (x['default'] === undefined) x['default'] = ''; var z = i.extend(p.call(this, x), { dg : x, buttons : [] }); if (x.validate) this.validate = x.validate; var A = function() { z.gL = i.getNextNumber() + '_fileInput'; var B = f.isCustomDomain(), C = [ '<iframe frameborder="0" allowtransparency="0" class="cke_dialog_ui_input_file" id="', z.gL, '" title="', x.label, '" src="javascript:void(' ]; C .push(B ? "(function(){document.open();document.domain='" + document.domain + "';" + 'document.close();' + '})()' : '0'); C.push(')"></iframe>'); return C.join(''); }; w.on('load', function() { var B = a.document.getById(z.gL), C = B .getParent(); C.addClass('cke_dialog_ui_input_file'); }); n.dialog.dD.call(this, w, x, y, A); }, fileButton : function(w, x, y) { if (arguments.length < 3) return; var z = p.call(this, x), A = this; if (x.validate) this.validate = x.validate; var B = i.extend( {}, x), C = B.onClick; B.className = (B.className ? B.className + ' ' : '') + 'cke_dialog_ui_button'; B.onClick = function(D) { var E = x['for']; if (!C || C.call(this, D) !== false) { w.getContentElement(E[0], E[1]) .submit(); this.disable(); } }; w.on('load', function() { w.getContentElement(x['for'][0], x['for'][1])._.buttons.push(A); }); n.dialog.button.call(this, w, B, y); }, html : (function() { var w = /^\s*<[\w:]+\s+([^>]*)?>/, x = /^(\s*<[\w:]+(?:\s+[^>]*)?)((?:.|\r|\n)+)$/, y = /\/$/; return function(z, A, B) { if (arguments.length < 3) return; var C = [], D, E = A.html, F, G; if (E.charAt(0) != '<') E = '<span>' + E + '</span>'; if (A.focus) { var H = this.focus; this.focus = function() { H.call(this); A.focus.call(this); this.oW('focus'); }; if (A.fM) { var I = this.fM; this.fM = I; } this.eA = true; } n.dialog.bf.call(this, z, A, C, 'span', null, null, ''); D = C.join(''); F = D.match(w); G = E.match(x) || [ '', '', '' ]; if (y.test(G[1])) { G[1] = G[1].slice(0, -1); G[2] = '/' + G[2]; } B.push( [ G[1], ' ', F[1] || '', G[2] ] .join('')); }; })() }, true); n.dialog.html.prototype = new n.dialog.bf(); n.dialog.dD.prototype = i.extend(new n.dialog.bf(), { rW : function(w) { var x = a.document.getById(this._.hz); if (x.iu() < 1) new h.text(w, a.document).appendTo(x); else x.getChild(0).$.nodeValue = w; return this; }, vt : function() { var w = a.document.getById(this._.hz); if (!w || w.iu() < 1) return ''; else return w.getChild(0).getText(); }, dm : t }, true); n.dialog.button.prototype = i.extend(new n.dialog.bf(), { click : function() { var w = this; if (!w._.disabled) return w.oW('click', { dialog : w._.dialog }); w.getElement().$.blur(); return false; }, enable : function() { this._.disabled = false; var w = this.getElement(); w && w.removeClass('disabled'); }, disable : function() { this._.disabled = true; this.getElement().addClass('disabled'); }, isVisible : function() { return this.getElement().getFirst().isVisible(); }, isEnabled : function() { return !this._.disabled; }, dm : i.extend( {}, n.dialog.bf.prototype.dm, { onClick : function(w, x) { this.on('click', x); } }, true), eZ : function() { this.click(); }, iU : function() { this.focus(); }, eA : true }, true); n.dialog.ju.prototype = i.extend(new n.dialog.dD(), { getInputElement : function() { return a.document.getById(this._.le); }, focus : function() { var w = this.selectParentTab(); setTimeout(function() { var x = w.getInputElement(); x && x.$.focus(); }, 0); }, select : function() { var w = this.selectParentTab(); setTimeout(function() { var x = w.getInputElement(); if (x) { x.$.focus(); x.$.select(); } }, 0); }, eZ : function() { this.select(); }, setValue : function(w) { w = w !== null ? w : ''; return n.dialog.bf.prototype.setValue.call(this, w); }, eA : true }, s, true); n.dialog.textarea.prototype = new n.dialog.ju(); n.dialog.select.prototype = i .extend( new n.dialog.dD(), { getInputElement : function() { return this._.select.getElement(); }, add : function(w, x, y) { var z = new k('option', this.getDialog().eY().document), A = this .getInputElement().$; z.$.text = w; z.$.value = x === undefined || x === null ? w : x; if (y === undefined || y === null) { if (g) A.add(z.$); else A.add(z.$, null); } else A.add(z.$, y); return this; }, remove : function(w) { var x = this.getInputElement().$; x.remove(w); return this; }, clear : function() { var w = this.getInputElement().$; while (w.length > 0) w.remove(0); return this; }, eA : true }, s, true); n.dialog.checkbox.prototype = i.extend(new n.dialog.bf(), { getInputElement : function() { return this._.checkbox.getElement(); }, setValue : function(w) { this.getInputElement().$.checked = w; this.oW('change', { value : w }); }, getValue : function() { return this.getInputElement().$.checked; }, eZ : function() { this.setValue(!this.getValue()); }, dm : { onChange : function(w, x) { if (!g) return t.onChange.apply(this, arguments); else { w.on('load', function() { var y = this._.checkbox.getElement(); y.on('propertychange', function(z) { z = z.data.$; if (z.propertyName == 'checked') this.oW('change', { value : y.$.checked }); }, this); }, this); this.on('change', x); } return null; } }, eA : true }, s, true); n.dialog.radio.prototype = i.extend(new n.dialog.bf(), { setValue : function(w) { var x = this._.children, y; for ( var z = 0; z < x.length && (y = x[z]); z++) y.getElement().$.checked = y.getValue() == w; this.oW('change', { value : w }); }, getValue : function() { var w = this._.children; for ( var x = 0; x < w.length; x++) { if (w[x].getElement().$.checked) return w[x].getValue(); } return null; }, eZ : function() { var w = this._.children, x; for (x = 0; x < w.length; x++) { if (w[x].getElement().$.checked) { w[x].getElement().focus(); return; } } w[0].getElement().focus(); }, dm : { onChange : function(w, x) { if (!g) return t.onChange.apply(this, arguments); else { w.on('load', function() { var y = this._.children, z = this; for ( var A = 0; A < y.length; A++) { var B = y[A].getElement(); B.on('propertychange', function(C) { C = C.data.$; if (C.propertyName == 'checked' && this.$.checked) z.oW('change', { value : this.getAttribute('value') }); }); } }, this); this.on('change', x); } return null; } }, eA : true }, s, true); n.dialog.file.prototype = i .extend( new n.dialog.dD(), s, { getInputElement : function() { var w = a.document.getById(this._.gL) .getFrameDocument(); return w.$.forms.length > 0 ? new k( w.$.forms[0].elements[0]) : this .getElement(); }, submit : function() { this.getInputElement().getParent().$.submit(); return this; }, vy : function(w) { return this.getInputElement().getParent().$.action; }, reset : function() { var w = a.document.getById(this._.gL), x = w .getFrameDocument(), y = this._.dg, z = this._.buttons; function A() { x.$.open(); if (f.isCustomDomain()) x.$.domain = document.domain; var B = ''; if (y.size) B = y.size - (g ? 7 : 0); x.$ .write( [ '<html><head><title></title></head><body style="margin: 0; overflow: hidden; background: transparent;">', '<form enctype="multipart/form-data" method="POST" action="', i.htmlEncode(y.action), '">', '<input type="file" name="', i .htmlEncode(y.id || 'cke_upload'), '" size="', i .htmlEncode(B > 0 ? B : ''), '" />', '</form>', '</body></html>' ].join('')); x.$.close(); for ( var C = 0; C < z.length; C++) z[C].enable(); } ; if (f.gecko) setTimeout(A, 500); else A(); }, getValue : function() { return ''; }, dm : t, eA : true }, true); n.dialog.fileButton.prototype = new n.dialog.button(); a.dialog.addUIElement('text', q); a.dialog.addUIElement('password', q); a.dialog.addUIElement('textarea', r); a.dialog.addUIElement('checkbox', r); a.dialog.addUIElement('radio', r); a.dialog.addUIElement('button', r); a.dialog.addUIElement('select', r); a.dialog.addUIElement('file', r); a.dialog.addUIElement('fileButton', r); a.dialog.addUIElement('html', r); i.extend(CKFinder.dialog, a.dialog); })(); (function() { m.add('help', { bM : [ 'toolbar', 'button' ], bz : function q(p) { if (!p.config.disableHelpButton) { p.bD('help', { exec : function(r) { r.aG['filesview.filesview'][0].bn().focus(); window .open(a.basePath + 'help/' + (r.lang.HelpLang || 'en') + '/index.html'); } }); p.bY.add('Help', a.UI_BUTTON, { label : p.lang.Help, command : 'help' }); } } }); })(); a.skins .add( 'kama', (function() { var p = [ 'images/loaders/16x16.gif', 'images/loaders/32x32.gif', 'images/ckffolder.gif', 'images/ckffolderopened.gif' ]; if (g && f.version < 7) p.push('images/sprites_ie6.png'); return { ls : p, application : { css : [ 'app.css' ] }, host : { qx : 1, css : [ 'host.css' ] }, mA : 7, kN : 7, ps : 1, bz : function(q) { if (q.config.width && !isNaN(q.config.width)) q.config.width -= 12; var r = [], s = '/* UI Color Support */.cke_skin_kama .cke_menuitem .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a:focus .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a:active .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover .cke_label,.cke_skin_kama .cke_menuitem a:focus .cke_label,.cke_skin_kama .cke_menuitem a:active .cke_label{\tbackground-color: $color !important;}.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_label,.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_label,.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_label{\tbackground-color: transparent !important;}.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a.cke_disabled .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuseparator{\tbackground-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover,.cke_skin_kama .cke_menuitem a:focus,.cke_skin_kama .cke_menuitem a:active{\tbackground-color: $color !important;}'; if (f.webkit) { s = s.split('}').slice(0, -1); for ( var t = 0; t < s.length; t++) s[t] = s[t].split('{'); } function u(x) { var y = x.eD().append('style'); y.setAttribute('id', 'cke_ui_color'); y.setAttribute('type', 'text/css'); return y; } ; function v(x, y, z) { var A, B, C; for ( var D = 0; D < x.length; D++) { if (f.webkit) { for (B = 0; B < x[D].$.sheet.rules.length; B++) x[D].$.sheet.removeRule(B); for (B = 0; B < y.length; B++) { C = y[B][1]; for (A = 0; A < z.length; A++) C = C.replace(z[A][0], z[A][1]); x[D].$.sheet .addRule(y[B][0], C); } } else { C = y; for (A = 0; A < z.length; A++) C = C.replace(z[A][0], z[A][1]); if (g) x[D].$.styleSheet.cssText = C; else x[D].setHtml(C); } } } ; var w = /\$color/g; i .extend( q, { uiColor : null, rk : function() { return this.uiColor; }, setUiColor : function(x) { var y, z, A = u(a.oC), B = u(this.document), C = '.cke_' + q.name .replace('.', '\\.'), D = [ C + ' .cke_wrapper', C + '_dialog .cke_dialog_contents', C + '_dialog a.cke_dialog_tab', C + '_dialog .cke_dialog_footer' ] .join(','), E = 'background-color: $color !important;'; if (f.webkit) { y = [ [ D, E ] ]; z = [ [ 'body,' + D, E ] ]; } else { y = D + '{' + E + '}'; z = 'body,' + D + '{' + E + '}'; } return (this.setUiColor = function( F) { var G = [ [ w, F ] ]; q.uiColor = F; v( [ A ], y, G); v( [ B ], z, G); v(r, s, G); })(x); } }); q.on('menuShow', function(x) { var y = x.data[0], z = y.element.eG( 'iframe').getItem(0) .getFrameDocument(); if (!z.getById('cke_ui_color')) { var A = u(z); r.push(A); var B = q.rk(); if (B) v( [ A ], s, [ [ w, B ] ]); } }); if (q.config.uiColor) q.on('uiReady', function() { q.setUiColor(q.config.uiColor); }); } }; })()); (function() { a.dialog ? p() : a.on('dialogPluginReady', p); function p() { a.dialog .on( 'resize', function(q) { var r = q.data, s = r.width, t = r.height, u = r.dialog, v = u.bO.contents; if (r.skin != 'kama') return; v.setStyles( { width : s + 'px', height : t + 'px' }); setTimeout( function() { var w = u.bO.dialog.getChild( [ 0, 0, 0 ]), x = w.getChild(0), y = w .getChild(2); y.setStyle('width', x.$.offsetWidth + 'px'); y = w.getChild(7); y .setStyle( 'width', x.$.offsetWidth - 28 + 'px'); y = w.getChild(4); y .setStyle( 'height', x.$.offsetHeight - 31 - 14 + 'px'); y = w.getChild(5); y .setStyle( 'height', x.$.offsetHeight - 31 - 14 + 'px'); }, 100); }); } ; })(); a.skins.add('v1', (function() { var p = [ 'images/loaders/16x16.gif', 'images/loaders/32x32.gif', 'images/ckffolder.gif', 'images/ckffolderopened.gif' ]; if (g && f.version < 7) p.push('images/sprites_ie6.png'); return { ls : p, application : { css : [ 'app.css' ] }, ps : 1, rv : -8, kN : 0, host : { qx : 1, css : [ 'host.css' ] } }; })()); (function() { a.dialog ? p() : a.on('dialogPluginReady', p); function p() { a.dialog .on( 'resize', function(q) { var r = q.data, s = r.width, t = r.height, u = r.dialog, v = u.bO.contents; if (r.skin != 'v1') return; v.setStyles( { width : s + 'px', height : t + 'px' }); setTimeout( function() { var w = u.bO.dialog.getChild( [ 0, 0, 0 ]), x = w.getChild(0), y = w .getChild(2); y.setStyle('width', x.$.offsetWidth + 'px'); y = w.getChild(7); y .setStyle( 'width', x.$.offsetWidth - 28 + 'px'); y = w.getChild(4); y .setStyle( 'height', x.$.offsetHeight - 31 - 14 + 'px'); y = w.getChild(5); y .setStyle( 'height', x.$.offsetHeight - 31 - 14 + 'px'); }, 100); }); } ; })(); a.gc .add( 'default', (function() { return { dQ : function(p) { var q = p.name, r = p.element, s = p.ff; if (!r || s == a.kZ) return; p.layout = new a.application.layout(p); var t = p.oW('themeSpace', { space : 'head', html : '' }), u = p.oW('themeSpace', { space : 'sidebar', html : '' }), v = p.oW('themeSpace', { space : 'mainTop', html : '' }), w = p.oW('themeSpace', { space : 'mainMiddle', html : '' }), x = p.oW('themeSpace', { space : 'mainBottom', html : '' }), y = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="' + p.lang.LangCode + '" dir="' + p.lang.dir + '">' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' + t.html + '</head>' + '<body>' + (f.ie6Compat ? '<div id="ckfinder" role="application">' : '<div id="ckfinder" role="application" style="visibility: hidden">') + '<!-- 1. CKE Skin class. -->' + '<div class="fake_wrapper cke_skin_' + (p.config.skin || 'kama') + '">' + '<!-- 2. High contrast class. -->' + '<div class="fake_wrapper"><!-- Applicable: hc cke_hc -->' + '<!-- 3. Browser class. -->' + '<div class="fake_wrapper ' + f.cssClass + '">' + '<!-- 4. RTL class. -->' + '<div class="fake_wrapper"><!-- Applicable: rtl cke_rtl -->' + '<!-- 5. Layout class. -->' + '<div class="fake_wrapper">' + '<div id="ckfinder_view" class="columns_2"><!-- Applicable: columns_1 columns_2 -->' + '<div id="sidebar_container" class="container" role="region">' + '<div id="sidebar_wrapper" class="wrapper">' + u.html + '</div>' + '</div>' + '<div id="main_container" class="container" role="region">' + v.html + w.html + x.html + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</body>' + '</html>'; a.log('[THEME] DOM flush using document.write'); p.document.$.write(y); function z() { if (f.ie6Compat) p.layout.oG = p.document.getWindow() .eR(); } ; p.cr('themeLoaded'); p .cr( 'uiReady', function() { z(); p .cr( 'appReady', function() { z(); if (f.ie8) { var A = p.document.$, B; if (A.documentMode) B = A.documentMode; else { B = 5; if (A.compatMode) if (A.compatMode == 'CSS1Compat') B = 7; } if (B < 8) { var C = '<strong style="color: red;">Forced IE compatibility mode! CKFinder may not look as intended.</strong>', D = p.plugins.tools; D .showTool(D .addTool(C)); } } if (f.ie6Compat) p.document .getWindow() .on( 'resize', z); p.document .getWindow() .on( 'resize', function() { p.layout.ea .call(p.layout); }); var E; function F() { E = E || p.document .eD() .eG( 'link') .getItem( 0); var G = 0; if (E) try { if (E.$.sheet && E.$.sheet.cssRules.length > 0) G = 1; else if (E.$.styleSheet && E.$.styleSheet.cssText.length > 0) G = 1; else if (E.$.innerHTML && E.$.innerHTML.length > 0) G = 1; } catch (H) { } if (!G) { window .setTimeout( F, 250); return; } if (f.ie6Compat) { z(); p.layout .ea(); setTimeout( function() { p.layout .ea(); }, 500); } else { p.layout .ea(true); setTimeout(function() { p.document .getById( 'ckfinder') .removeStyle( 'visibility'); }); } return undefined; } ; F(); }); }); }, pu : function(p) { var q = i.getNextNumber(), r = k .kE( [ '<div class="cke_compatibility cke_' + p.name .replace('.', '\\.') + '_dialog cke_skin_', p.gd, '" dir="', p.lang.dir, '" lang="', p.langCode, '"><table class="cke_dialog', ' ' + f.cssClass .replace( /browser/g, 'cke_browser'), ' cke_', p.lang.dir, '" style="position:absolute"><tr><td><div class="%body"><div id="%title#" class="%title"></div><div id="%close_button#" class="%close_button"><span>X</span></div><div id="%tabs#" class="%tabs"></div><table class="%contents"><tr><td id="%contents#" class="%contents"></td></tr></table><div id="%footer#" class="%footer"></div></div><div id="%tl#" class="%tl"></div><div id="%tc#" class="%tc"></div><div id="%tr#" class="%tr"></div><div id="%ml#" class="%ml"></div><div id="%mr#" class="%mr"></div><div id="%bl#" class="%bl"></div><div id="%bc#" class="%bc"></div><div id="%br#" class="%br"></div></td></tr></table>', g ? '' : '<style>.cke_dialog{visibility:hidden;}</style>', '</div>' ].join('') .replace(/#/g, '_' + q) .replace(/%/g, 'cke_dialog_'), a.document), s = r.getChild( [ 0, 0, 0, 0, 0 ]), t = s.getChild(0), u = s .getChild(1); t.unselectable(); u.unselectable(); return { element : r, bO : { dialog : r.getChild(0), title : t, close : u, tabs : s.getChild(2), contents : s.getChild( [ 3, 0, 0, 0 ]), footer : s.getChild(4) } }; }, fH : function(p) { var q = p.container, r = p.ia; if (q) q.remove(); for ( var s = 0; r && s < r.length; s++) r[s].remove(); if (p.ff == a.fc) { p.element.show(); delete p.element; } } }; })()); a.application.prototype.vU = function(p) { var q = '' + p, r = this._[q] || (this._[q] = a.document.getById(q + '_' + this.name)); return r; }; a.application.prototype.nJ = function(p) { var q = /^\d+$/; if (q.test(p)) p += 'px'; var r = this.layout.dV(); r.setStyle('width', p); this.oW('resize'); this.layout.ea(); }; a.application.prototype.resize = function(p, q) { this.element.getChild(0).setStyle('height', q + 'px'); this.element.getChild(0).setStyle('width', p + 'px'); }; (function() { var p = "\074\144\151\166\040\143\154\x61\x73\163\x3d\047\166\151\x65\167\040\x74\157\157\154\137\x70\x61\x6e\x65\x6c\x27\x20\163\164\x79\154\x65\075\047\160\x61\144\144\151\156\x67\072\x32\160\170\073\x64\x69\163\x70\x6c\141\171\x3a\x62\154\157\143\x6b\x20\x21\x69\x6d\x70\x6f\x72\164\141\x6e\164\073\160\157\x73\x69\x74\151\x6f\x6e\x3a\163\164\x61\164\x69\143\040\x21\151\155\160\157\x72\164\141\x6e\164\073\x63\157\x6c\157\162\072\142\x6c\x61\143\x6b\x20\041\x69\x6d\x70\x6f\x72\164\141\x6e\x74\073\142\141\x63\x6b\147\162\x6f\x75\x6e\144\x2d\143\x6f\154\157\162\072\x77\x68\151\164\145\x20\x21\151\155\160\x6f\162\x74\x61\156\x74\x3b\x27\076", q = "\074\057\144\151\x76\x3e", r = p + "\124\x68\x69\x73\040\x69\x73\040\164\x68\145\040\x44\x45\115\x4f\x20\166\145\162\163\151\x6f\156\x20\x6f\146\x20\x43\x4b\106\x69\156\144\145\x72\056\040\x50\154\x65\x61\x73\145\x20\166\151\x73\x69\164\040\164\x68\x65\040\x3c\141\x20\x68\x72\145\146\x3d\x27\x68\164\x74\160\072\x2f\x2f\143\153\146\151\156\144\145\x72\056\143\157\155\047\x20\164\141\x72\x67\145\x74\075\047\137\x62\154\141\156\153\047\076\x43\113\106\151\156\x64\145\x72\x20\x77\x65\142\040\163\x69\x74\x65\x3c\057\x61\076\040\x74\x6f\x20\x6f\x62\164\141\x69\x6e\040\x61\x20\x76\141\x6c\151\x64\x20\x6c\x69\143\x65\x6e\163\x65\056" + q, s = p + "\x43\x4b\x46\x69\x6e\x64\145\162\x20\104\x65\x76\x65\154\x6f\160\x65\162\040\x4c\x69\x63\145\156\x73\145\x3c\142\162\x2f\x3e\x4c\x69\143\x65\x6e\x73\145\x64\x20\164\157\x3a\x20"; function t(v, w) { var x = 0, y = 0; for ( var z = 0; z < v.$.parentNode.childNodes.length; z++) { var A = v.$.parentNode.childNodes[z]; if (A.nodeType == 1) { var B = A == v.$; if (!A.offsetHeight && !B) continue; y++; if (!B) x += A.offsetHeight; } } var C = v.$.offsetHeight - v.$.clientHeight, D = (y - 1) * w; if (f.ie6Compat && !f.ie8 && !f.ie7Compat) D += w * 2; var E = g ? v.$.parentNode.parentNode.parentNode.offsetHeight : v.$.parentNode.offsetHeight, F = E - C - x - (D || 0); try { v.setStyle('height', F + 'px'); } catch (G) { } } ; function u(v) { return a.bs.substr(v * 9 % (2 << 4), 1); } ; a.application.layout = function(v) { this.app = r.length ? v : null; this.jB = null; }; a.application.layout.prototype = { ea : function(v) { if (this.jB) return; this.jB = i .setTimeout( function() { a.log('[THEME] Repainting layout'); var w = a.bs.indexOf(a.bF.substr(1, 1)) % 5, x = [ a.bF.substr(8, 1), a.bF.substr(6, 1) ], y = a.bF && a.bF.substr(3, 1) != a.bs .substr( (a.bs.indexOf(a.bF .substr(0, 1)) + a.bs .indexOf(a.bF .substr( 2, 1))) * 9 % (a.bs.length - 1), 1), z = !!a.ed && x[1] != u(a.ed.length + a.bs.indexOf(x[0])); if (a.bF && 1 == w && a .lS(window.top[a.nd + "\x63\x61\164\151\157\156"][a.jG + "\x73\x74"]) != a .lS(a.ed) || w == 4 || y) { var A = this.dV().getChild(0) .getChildren(), B = 0; for ( var C = 0; C < A.count(); C++) { if (A .getItem(C) .rd( "\160\157\163\151\164\151\157\x6e") == "\x73\164\141\164\151\143") B = 1; } if (!B) this .dV() .getChild(0) .appendHtml( y || z || w != 4 ? r : s + "\x3c\x62\076" + i .htmlEncode(a.ed) + "\x3c\057\x62\076\074\057\144\151\x76\076"); } var D = this.pn(), E = this.pS(), F = a.skins.loaded[this.app.gd]; if (F.ps && g && f.ie6Compat && !f.ie8) { var G = this.mB(), H = this.dV(), I = 3 * F.kN, J = F.rv ? F.rv : 0, K = this.oG.width - H.$.offsetWidth - I + J; G.setStyle('width', K + 'px'); } if (D) t(D, F.mA); if (E) t(E, F.kN); this.jB = null; v = false; this.app.oW('afterRepaintLayout'); if (f.ie6Compat) i .setTimeout( function() { this.app.element.$.style.cssText += ''; }, 0, this); }, v === true ? 0 : 500, this); }, dV : function() { var v = this; if (!v.kS) v.kS = v.app.document.getById('sidebar_container'); return v.kS; }, mB : function() { var v = this; if (!v.lb) v.lb = v.app.document.getById('main_container'); return v.lb; }, pS : function() { var v = this; if (typeof v.kK === 'undefined') v.kK = v.app.document.getById('folders_view'); return v.kK; }, pn : function() { var v = this; if (typeof v.kD === 'undefined') v.kD = v.app.document.getById('files_view'); return v.kD; } }; })(); })();
JavaScript
/*! * MediaElementPlayer * http://mediaelementjs.com/ * * Creates a controller bar for HTML5 <video> add <audio> tags * using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper) * * Copyright 2010-2012, John Dyer (http://j.hn/) * Dual licensed under the MIT or GPL Version 2 licenses. * */ if (typeof jQuery != 'undefined') { mejs.$ = jQuery; } else if (typeof ender != 'undefined') { mejs.$ = ender; } (function ($) { // default player values mejs.MepDefaults = { // url to poster (to fix iOS 3.x) poster: '', // default if the <video width> is not specified defaultVideoWidth: 480, // default if the <video height> is not specified defaultVideoHeight: 270, // if set, overrides <video width> videoWidth: -1, // if set, overrides <video height> videoHeight: -1, // default if the user doesn't specify defaultAudioWidth: 400, // default if the user doesn't specify defaultAudioHeight: 30, // default amount to move back when back key is pressed defaultSeekBackwardInterval: function(media) { return (media.duration * 0.05); }, // default amount to move forward when forward key is pressed defaultSeekForwardInterval: function(media) { return (media.duration * 0.05); }, // width of audio player audioWidth: -1, // height of audio player audioHeight: -1, // initial volume when the player starts (overrided by user cookie) startVolume: 0.8, // useful for <audio> player loops loop: false, // resize to media dimensions enableAutosize: true, // forces the hour marker (##:00:00) alwaysShowHours: false, // show framecount in timecode (##:00:00:00) showTimecodeFrameCount: false, // used when showTimecodeFrameCount is set to true framesPerSecond: 25, // automatically calculate the width of the progress bar based on the sizes of other elements autosizeProgress : true, // Hide controls when playing and mouse is not over the video alwaysShowControls: false, // force iPad's native controls iPadUseNativeControls: false, // force iPhone's native controls iPhoneUseNativeControls: false, // force Android's native controls AndroidUseNativeControls: false, // features to show features: ['playpause','current','progress','duration','tracks','volume','fullscreen'], // only for dynamic isVideo: true, // turns keyboard support on and off for this instance enableKeyboard: true, // whenthis player starts, it will pause other players pauseOtherPlayers: true, // array of keyboard actions such as play pause keyActions: [ { keys: [ 32, // SPACE 179 // GOOGLE play/pause button ], action: function(player, media) { if (media.paused || media.ended) { media.play(); } else { media.pause(); } } }, { keys: [38], // UP action: function(player, media) { var newVolume = Math.min(media.volume + 0.1, 1); media.setVolume(newVolume); } }, { keys: [40], // DOWN action: function(player, media) { var newVolume = Math.max(media.volume - 0.1, 0); media.setVolume(newVolume); } }, { keys: [ 37, // LEFT 227 // Google TV rewind ], action: function(player, media) { if (!isNaN(media.duration) && media.duration > 0) { if (player.isVideo) { player.showControls(); player.startControlsTimer(); } // 5% var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0); media.setCurrentTime(newTime); } } }, { keys: [ 39, // RIGHT 228 // Google TV forward ], action: function(player, media) { if (!isNaN(media.duration) && media.duration > 0) { if (player.isVideo) { player.showControls(); player.startControlsTimer(); } // 5% var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration); media.setCurrentTime(newTime); } } }, { keys: [70], // f action: function(player, media) { if (typeof player.enterFullScreen != 'undefined') { if (player.isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } } } } ] }; mejs.mepIndex = 0; mejs.players = []; // wraps a MediaElement object in player controls mejs.MediaElementPlayer = function(node, o) { // enforce object, even without "new" (via John Resig) if ( !(this instanceof mejs.MediaElementPlayer) ) { return new mejs.MediaElementPlayer(node, o); } var t = this; // these will be reset after the MediaElement.success fires t.$media = t.$node = $(node); t.node = t.media = t.$media[0]; // check for existing player if (typeof t.node.player != 'undefined') { return t.node.player; } else { // attach player to DOM node for reference t.node.player = t; } // try to get options from data-mejsoptions if (typeof o == 'undefined') { o = t.$node.data('mejsoptions'); } // extend default options t.options = $.extend({},mejs.MepDefaults,o); // add to player array (for focus events) mejs.players.push(t); // start up t.init(); return t; }; // actual player mejs.MediaElementPlayer.prototype = { hasFocus: false, controlsAreVisible: true, init: function() { var t = this, mf = mejs.MediaFeatures, // options for MediaElement (shim) meOptions = $.extend(true, {}, t.options, { success: function(media, domNode) { t.meReady(media, domNode); }, error: function(e) { t.handleError(e);} }), tagName = t.media.tagName.toLowerCase(); t.isDynamic = (tagName !== 'audio' && tagName !== 'video'); if (t.isDynamic) { // get video from src or href? t.isVideo = t.options.isVideo; } else { t.isVideo = (tagName !== 'audio' && t.options.isVideo); } // use native controls in iPad, iPhone, and Android if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) { // add controls and stop t.$media.attr('controls', 'controls'); // attempt to fix iOS 3 bug //t.$media.removeAttr('poster'); // no Issue found on iOS3 -ttroxell // override Apple's autoplay override for iPads if (mf.isiPad && t.media.getAttribute('autoplay') !== null) { t.media.load(); t.media.play(); } } else if (mf.isAndroid && t.AndroidUseNativeControls) { // leave default player } else { // DESKTOP: use MediaElementPlayer controls // remove native controls t.$media.removeAttr('controls'); // unique ID t.id = 'mep_' + mejs.mepIndex++; // build container t.container = $('<div id="' + t.id + '" class="mejs-container">'+ '<div class="mejs-inner">'+ '<div class="mejs-mediaelement"></div>'+ '<div class="mejs-layers"></div>'+ '<div class="mejs-controls"></div>'+ '<div class="mejs-clear"></div>'+ '</div>' + '</div>') .addClass(t.$media[0].className) .insertBefore(t.$media); // add classes for user and content t.container.addClass( (mf.isAndroid ? 'mejs-android ' : '') + (mf.isiOS ? 'mejs-ios ' : '') + (mf.isiPad ? 'mejs-ipad ' : '') + (mf.isiPhone ? 'mejs-iphone ' : '') + (t.isVideo ? 'mejs-video ' : 'mejs-audio ') ); // move the <video/video> tag into the right spot if (mf.isiOS) { // sadly, you can't move nodes in iOS, so we have to destroy and recreate it! var $newMedia = t.$media.clone(); t.container.find('.mejs-mediaelement').append($newMedia); t.$media.remove(); t.$node = t.$media = $newMedia; t.node = t.media = $newMedia[0] } else { // normal way of moving it into place (doesn't work on iOS) t.container.find('.mejs-mediaelement').append(t.$media); } // find parts t.controls = t.container.find('.mejs-controls'); t.layers = t.container.find('.mejs-layers'); // determine the size /* size priority: (1) videoWidth (forced), (2) style="width;height;" (3) width attribute, (4) defaultVideoWidth (for unspecified cases) */ var tagType = (t.isVideo ? 'video' : 'audio'), capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1); if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) { t.width = t.options[tagType + 'Width']; } else if (t.media.style.width !== '' && t.media.style.width !== null) { t.width = t.media.style.width; } else if (t.media.getAttribute('width') !== null) { t.width = t.$media.attr('width'); } else { t.width = t.options['default' + capsTagName + 'Width']; } if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) { t.height = t.options[tagType + 'Height']; } else if (t.media.style.height !== '' && t.media.style.height !== null) { t.height = t.media.style.height; } else if (t.$media[0].getAttribute('height') !== null) { t.height = t.$media.attr('height'); } else { t.height = t.options['default' + capsTagName + 'Height']; } // set the size, while we wait for the plugins to load below t.setPlayerSize(t.width, t.height); // create MediaElementShim meOptions.pluginWidth = t.height; meOptions.pluginHeight = t.width; } // create MediaElement shim mejs.MediaElement(t.$media[0], meOptions); }, showControls: function(doAnimation) { var t = this; doAnimation = typeof doAnimation == 'undefined' || doAnimation; if (t.controlsAreVisible) return; if (doAnimation) { t.controls .css('visibility','visible') .stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;}); // any additional controls people might add and want to hide t.container.find('.mejs-control') .css('visibility','visible') .stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;}); } else { t.controls .css('visibility','visible') .css('display','block'); // any additional controls people might add and want to hide t.container.find('.mejs-control') .css('visibility','visible') .css('display','block'); t.controlsAreVisible = true; } t.setControlsSize(); }, hideControls: function(doAnimation) { var t = this; doAnimation = typeof doAnimation == 'undefined' || doAnimation; if (!t.controlsAreVisible) return; if (doAnimation) { // fade out main controls t.controls.stop(true, true).fadeOut(200, function() { $(this) .css('visibility','hidden') .css('display','block'); t.controlsAreVisible = false; }); // any additional controls people might add and want to hide t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() { $(this) .css('visibility','hidden') .css('display','block'); }); } else { // hide main controls t.controls .css('visibility','hidden') .css('display','block'); // hide others t.container.find('.mejs-control') .css('visibility','hidden') .css('display','block'); t.controlsAreVisible = false; } }, controlsTimer: null, startControlsTimer: function(timeout) { var t = this; timeout = typeof timeout != 'undefined' ? timeout : 1500; t.killControlsTimer('start'); t.controlsTimer = setTimeout(function() { //console.log('timer fired'); t.hideControls(); t.killControlsTimer('hide'); }, timeout); }, killControlsTimer: function(src) { var t = this; if (t.controlsTimer !== null) { clearTimeout(t.controlsTimer); delete t.controlsTimer; t.controlsTimer = null; } }, controlsEnabled: true, disableControls: function() { var t= this; t.killControlsTimer(); t.hideControls(false); this.controlsEnabled = false; }, enableControls: function() { var t= this; t.showControls(false); t.controlsEnabled = true; }, // Sets up all controls and events meReady: function(media, domNode) { var t = this, mf = mejs.MediaFeatures, autoplayAttr = domNode.getAttribute('autoplay'), autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'), featureIndex, feature; // make sure it can't create itself again if a plugin reloads if (t.created) return; else t.created = true; t.media = media; t.domNode = domNode; if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) { // two built in features t.buildposter(t, t.controls, t.layers, t.media); t.buildkeyboard(t, t.controls, t.layers, t.media); t.buildoverlays(t, t.controls, t.layers, t.media); // grab for use by features t.findTracks(); // add user-defined features/controls for (featureIndex in t.options.features) { feature = t.options.features[featureIndex]; if (t['build' + feature]) { try { t['build' + feature](t, t.controls, t.layers, t.media); } catch (e) { // TODO: report control error //throw e; //console.log('error building ' + feature); //console.log(e); } } } t.container.trigger('controlsready'); // reset all layers and controls t.setPlayerSize(t.width, t.height); t.setControlsSize(); // controls fade if (t.isVideo) { if (mejs.MediaFeatures.hasTouch) { // for touch devices (iOS, Android) // show/hide without animation on touch t.$media.bind('touchstart', function() { // toggle controls if (t.controlsAreVisible) { t.hideControls(false); } else { if (t.controlsEnabled) { t.showControls(false); } } }); } else { // click controls var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement); // click to play/pause clickElement.click(function() { if (media.paused) { media.play(); } else { media.pause(); } }); // show/hide controls t.container .bind('mouseenter mouseover', function () { if (t.controlsEnabled) { if (!t.options.alwaysShowControls) { t.killControlsTimer('enter'); t.showControls(); t.startControlsTimer(2500); } } }) .bind('mousemove', function() { if (t.controlsEnabled) { if (!t.controlsAreVisible) { t.showControls(); } //t.killControlsTimer('move'); if (!t.options.alwaysShowControls) { t.startControlsTimer(2500); } } }) .bind('mouseleave', function () { if (t.controlsEnabled) { if (!t.media.paused && !t.options.alwaysShowControls) { t.startControlsTimer(1000); } } }); } // check for autoplay if (autoplay && !t.options.alwaysShowControls) { t.hideControls(); } // resizer if (t.options.enableAutosize) { t.media.addEventListener('loadedmetadata', function(e) { // if the <video height> was not set and the options.videoHeight was not set // then resize to the real dimensions if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) { t.setPlayerSize(e.target.videoWidth, e.target.videoHeight); t.setControlsSize(); t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight); } }, false); } } // EVENTS // FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them) media.addEventListener('play', function() { // go through all other players for (var i=0, il=mejs.players.length; i<il; i++) { var p = mejs.players[i]; if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) { p.pause(); } p.hasFocus = false; } t.hasFocus = true; },false); // ended for all t.media.addEventListener('ended', function (e) { try{ t.media.setCurrentTime(0); } catch (exp) { } t.media.pause(); if (t.setProgressRail) t.setProgressRail(); if (t.setCurrentRail) t.setCurrentRail(); if (t.options.loop) { t.media.play(); } else if (!t.options.alwaysShowControls && t.controlsEnabled) { t.showControls(); } }, false); // resize on the first play t.media.addEventListener('loadedmetadata', function(e) { if (t.updateDuration) { t.updateDuration(); } if (t.updateCurrent) { t.updateCurrent(); } if (!t.isFullScreen) { t.setPlayerSize(t.width, t.height); t.setControlsSize(); } }, false); // webkit has trouble doing this without a delay setTimeout(function () { t.setPlayerSize(t.width, t.height); t.setControlsSize(); }, 50); // adjust controls whenever window sizes (used to be in fullscreen only) $(window).resize(function() { // don't resize for fullscreen mode if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) { t.setPlayerSize(t.width, t.height); } // always adjust controls t.setControlsSize(); }); // TEMP: needs to be moved somewhere else if (t.media.pluginType == 'youtube') { t.container.find('.mejs-overlay-play').hide(); } } // force autoplay for HTML5 if (autoplay && media.pluginType == 'native') { media.load(); media.play(); } if (t.options.success) { if (typeof t.options.success == 'string') { window[t.options.success](t.media, t.domNode, t); } else { t.options.success(t.media, t.domNode, t); } } }, handleError: function(e) { var t = this; t.controls.hide(); // Tell user that the file cannot be played if (t.options.error) { t.options.error(e); } }, setPlayerSize: function(width,height) { var t = this; if (typeof width != 'undefined') t.width = width; if (typeof height != 'undefined') t.height = height; // detect 100% mode if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') { // do we have the native dimensions yet? var nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth, nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight, parentWidth = t.container.parent().width(), newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10); if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) { parentWidth = $(window).width(); newHeight = $(window).height(); } if ( newHeight != 0 ) { // set outer container size t.container .width(parentWidth) .height(newHeight); // set native <video> t.$media .width('100%') .height('100%'); // set shims t.container.find('object, embed, iframe') .width('100%') .height('100%'); // if shim is ready, send the size to the embeded plugin if (t.isVideo) { if (t.media.setVideoSize) { t.media.setVideoSize(parentWidth, newHeight); } } // set the layers t.layers.children('.mejs-layer') .width('100%') .height('100%'); } } else { t.container .width(t.width) .height(t.height); t.layers.children('.mejs-layer') .width(t.width) .height(t.height); } }, setControlsSize: function() { var t = this, usedWidth = 0, railWidth = 0, rail = t.controls.find('.mejs-time-rail'), total = t.controls.find('.mejs-time-total'), current = t.controls.find('.mejs-time-current'), loaded = t.controls.find('.mejs-time-loaded'), others = rail.siblings(); // allow the size to come from custom CSS if (t.options && !t.options.autosizeProgress) { // Also, frontends devs can be more flexible // due the opportunity of absolute positioning. railWidth = parseInt(rail.css('width')); } // attempt to autosize if (railWidth === 0 || !railWidth) { // find the size of all the other controls besides the rail others.each(function() { if ($(this).css('position') != 'absolute') { usedWidth += $(this).outerWidth(true); } }); // fit the rail into the remaining space railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width()); } // outer area rail.width(railWidth); // dark space total.width(railWidth - (total.outerWidth(true) - total.width())); if (t.setProgressRail) t.setProgressRail(); if (t.setCurrentRail) t.setCurrentRail(); }, buildposter: function(player, controls, layers, media) { var t = this, poster = $('<div class="mejs-poster mejs-layer">' + '</div>') .appendTo(layers), posterUrl = player.$media.attr('poster'); // prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster) if (player.options.poster !== '') { posterUrl = player.options.poster; } // second, try the real poster if (posterUrl !== '' && posterUrl != null) { t.setPoster(posterUrl); } else { poster.hide(); } media.addEventListener('play',function() { poster.hide(); }, false); }, setPoster: function(url) { var t = this, posterDiv = t.container.find('.mejs-poster'), posterImg = posterDiv.find('img'); if (posterImg.length == 0) { posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv); } posterImg.attr('src', url); }, buildoverlays: function(player, controls, layers, media) { if (!player.isVideo) return; var loading = $('<div class="mejs-overlay mejs-layer">'+ '<div class="mejs-overlay-loading"><span></span></div>'+ '</div>') .hide() // start out hidden .appendTo(layers), error = $('<div class="mejs-overlay mejs-layer">'+ '<div class="mejs-overlay-error"></div>'+ '</div>') .hide() // start out hidden .appendTo(layers), // this needs to come last so it's on top bigPlay = $('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+ '<div class="mejs-overlay-button"></div>'+ '</div>') .appendTo(layers) .click(function() { if (media.paused) { media.play(); } else { media.pause(); } }); /* if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) { bigPlay.remove(); loading.remove(); } */ // show/hide big play button media.addEventListener('play',function() { bigPlay.hide(); loading.hide(); controls.find('.mejs-time-buffering').hide(); error.hide(); }, false); media.addEventListener('playing', function() { bigPlay.hide(); loading.hide(); controls.find('.mejs-time-buffering').hide(); error.hide(); }, false); media.addEventListener('seeking', function() { loading.show(); controls.find('.mejs-time-buffering').show(); }, false); media.addEventListener('seeked', function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); }, false); media.addEventListener('pause',function() { if (!mejs.MediaFeatures.isiPhone) { bigPlay.show(); } }, false); media.addEventListener('waiting', function() { loading.show(); controls.find('.mejs-time-buffering').show(); }, false); // show/hide loading media.addEventListener('loadeddata',function() { // for some reason Chrome is firing this event //if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none') // return; loading.show(); controls.find('.mejs-time-buffering').show(); }, false); media.addEventListener('canplay',function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); }, false); // error handling media.addEventListener('error',function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); error.show(); error.find('mejs-overlay-error').html("Error loading this resource"); }, false); }, buildkeyboard: function(player, controls, layers, media) { var t = this; // listen for key presses $(document).keydown(function(e) { if (player.hasFocus && player.options.enableKeyboard) { // find a matching key for (var i=0, il=player.options.keyActions.length; i<il; i++) { var keyAction = player.options.keyActions[i]; for (var j=0, jl=keyAction.keys.length; j<jl; j++) { if (e.keyCode == keyAction.keys[j]) { e.preventDefault(); keyAction.action(player, media, e.keyCode); return false; } } } } return true; }); // check if someone clicked outside a player region, then kill its focus $(document).click(function(event) { if ($(event.target).closest('.mejs-container').length == 0) { player.hasFocus = false; } }); }, findTracks: function() { var t = this, tracktags = t.$media.find('track'); // store for use by plugins t.tracks = []; tracktags.each(function(index, track) { track = $(track); t.tracks.push({ srclang: track.attr('srclang').toLowerCase(), src: track.attr('src'), kind: track.attr('kind'), label: track.attr('label') || '', entries: [], isLoaded: false }); }); }, changeSkin: function(className) { this.container[0].className = 'mejs-container ' + className; this.setPlayerSize(this.width, this.height); this.setControlsSize(); }, play: function() { this.media.play(); }, pause: function() { this.media.pause(); }, load: function() { this.media.load(); }, setMuted: function(muted) { this.media.setMuted(muted); }, setCurrentTime: function(time) { this.media.setCurrentTime(time); }, getCurrentTime: function() { return this.media.currentTime; }, setVolume: function(volume) { this.media.setVolume(volume); }, getVolume: function() { return this.media.volume; }, setSrc: function(src) { this.media.setSrc(src); }, remove: function() { var t = this; if (t.media.pluginType === 'flash') { t.media.remove(); } else if (t.media.pluginType === 'native') { t.$media.prop('controls', true); } // grab video and put it back in place if (!t.isDynamic) { t.$node.insertBefore(t.container) } t.container.remove(); } }; // turn into jQuery plugin if (typeof jQuery != 'undefined') { jQuery.fn.mediaelementplayer = function (options) { return this.each(function () { new mejs.MediaElementPlayer(this, options); }); }; } $(document).ready(function() { // auto enable using JSON attribute $('.mejs-player').mediaelementplayer(); }); // push out to window window.MediaElementPlayer = mejs.MediaElementPlayer; })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { playpauseText: 'Play/Pause' }); // PLAY/pause BUTTON $.extend(MediaElementPlayer.prototype, { buildplaypause: function(player, controls, layers, media) { var t = this, play = $('<div class="mejs-button mejs-playpause-button mejs-play" >' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' + '</div>') .appendTo(controls) .click(function(e) { e.preventDefault(); if (media.paused) { media.play(); } else { media.pause(); } return false; }); media.addEventListener('play',function() { play.removeClass('mejs-play').addClass('mejs-pause'); }, false); media.addEventListener('playing',function() { play.removeClass('mejs-play').addClass('mejs-pause'); }, false); media.addEventListener('pause',function() { play.removeClass('mejs-pause').addClass('mejs-play'); }, false); media.addEventListener('paused',function() { play.removeClass('mejs-pause').addClass('mejs-play'); }, false); } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { stopText: 'Stop' }); // STOP BUTTON $.extend(MediaElementPlayer.prototype, { buildstop: function(player, controls, layers, media) { var t = this, stop = $('<div class="mejs-button mejs-stop-button mejs-stop">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' + '</div>') .appendTo(controls) .click(function() { if (!media.paused) { media.pause(); } if (media.currentTime > 0) { media.setCurrentTime(0); controls.find('.mejs-time-current').width('0px'); controls.find('.mejs-time-handle').css('left', '0px'); controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) ); controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) ); layers.find('.mejs-poster').show(); } }); } }); })(mejs.$); (function($) { // progress/loaded bar $.extend(MediaElementPlayer.prototype, { buildprogress: function(player, controls, layers, media) { $('<div class="mejs-time-rail">'+ '<span class="mejs-time-total">'+ '<span class="mejs-time-buffering"></span>'+ '<span class="mejs-time-loaded"></span>'+ '<span class="mejs-time-current"></span>'+ '<span class="mejs-time-handle"></span>'+ '<span class="mejs-time-float">' + '<span class="mejs-time-float-current">00:00</span>' + '<span class="mejs-time-float-corner"></span>' + '</span>'+ '</span>'+ '</div>') .appendTo(controls); controls.find('.mejs-time-buffering').hide(); var t = this, total = controls.find('.mejs-time-total'), loaded = controls.find('.mejs-time-loaded'), current = controls.find('.mejs-time-current'), handle = controls.find('.mejs-time-handle'), timefloat = controls.find('.mejs-time-float'), timefloatcurrent = controls.find('.mejs-time-float-current'), handleMouseMove = function (e) { // mouse position relative to the object var x = e.pageX, offset = total.offset(), width = total.outerWidth(), percentage = 0, newTime = 0, pos = x - offset.left; if (x > offset.left && x <= width + offset.left && media.duration) { percentage = ((x - offset.left) / width); newTime = (percentage <= 0.02) ? 0 : percentage * media.duration; // seek to where the mouse is if (mouseIsDown) { media.setCurrentTime(newTime); } // position floating time box if (!mejs.MediaFeatures.hasTouch) { timefloat.css('left', pos); timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) ); timefloat.show(); } } }, mouseIsDown = false, mouseIsOver = false; // handle clicks //controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove); total .bind('mousedown', function (e) { // only handle left clicks if (e.which === 1) { mouseIsDown = true; handleMouseMove(e); $(document) .bind('mousemove.dur', function(e) { handleMouseMove(e); }) .bind('mouseup.dur', function (e) { mouseIsDown = false; timefloat.hide(); $(document).unbind('.dur'); }); return false; } }) .bind('mouseenter', function(e) { mouseIsOver = true; $(document).bind('mousemove.dur', function(e) { handleMouseMove(e); }); if (!mejs.MediaFeatures.hasTouch) { timefloat.show(); } }) .bind('mouseleave',function(e) { mouseIsOver = false; if (!mouseIsDown) { $(document).unbind('.dur'); timefloat.hide(); } }); // loading media.addEventListener('progress', function (e) { player.setProgressRail(e); player.setCurrentRail(e); }, false); // current time media.addEventListener('timeupdate', function(e) { player.setProgressRail(e); player.setCurrentRail(e); }, false); // store for later use t.loaded = loaded; t.total = total; t.current = current; t.handle = handle; }, setProgressRail: function(e) { var t = this, target = (e != undefined) ? e.target : t.media, percent = null; // newest HTML5 spec has buffered array (FF4, Webkit) if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) { // TODO: account for a real array with multiple values (only Firefox 4 has this so far) percent = target.buffered.end(0) / target.duration; } // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end() // to be anything other than 0. If the byte count is available we use this instead. // Browsers that support the else if do not seem to have the bufferedBytes value and // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8. else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) { percent = target.bufferedBytes / target.bytesTotal; } // Firefox 3 with an Ogg file seems to go this way else if (e && e.lengthComputable && e.total != 0) { percent = e.loaded/e.total; } // finally update the progress bar if (percent !== null) { percent = Math.min(1, Math.max(0, percent)); // update loaded bar if (t.loaded && t.total) { t.loaded.width(t.total.width() * percent); } } }, setCurrentRail: function() { var t = this; if (t.media.currentTime != undefined && t.media.duration) { // update bar and handle if (t.total && t.handle) { var newWidth = t.total.width() * t.media.currentTime / t.media.duration, handlePos = newWidth - (t.handle.outerWidth(true) / 2); t.current.width(newWidth); t.handle.css('left', handlePos); } } } }); })(mejs.$); (function($) { // options $.extend(mejs.MepDefaults, { duration: -1, timeAndDurationSeparator: ' <span> | </span> ' }); // current and duration 00:00 / 00:00 $.extend(MediaElementPlayer.prototype, { buildcurrent: function(player, controls, layers, media) { var t = this; $('<div class="mejs-time">'+ '<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+ '</div>') .appendTo(controls); t.currenttime = t.controls.find('.mejs-currenttime'); media.addEventListener('timeupdate',function() { player.updateCurrent(); }, false); }, buildduration: function(player, controls, layers, media) { var t = this; if (controls.children().last().find('.mejs-currenttime').length > 0) { $(t.options.timeAndDurationSeparator + '<span class="mejs-duration">' + (t.options.duration > 0 ? mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) : ((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')) ) + '</span>') .appendTo(controls.find('.mejs-time')); } else { // add class to current time controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container'); $('<div class="mejs-time mejs-duration-container">'+ '<span class="mejs-duration">' + (t.options.duration > 0 ? mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) : ((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')) ) + '</span>' + '</div>') .appendTo(controls); } t.durationD = t.controls.find('.mejs-duration'); media.addEventListener('timeupdate',function() { player.updateDuration(); }, false); }, updateCurrent: function() { var t = this; if (t.currenttime) { t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25)); } }, updateDuration: function() { var t = this; if (t.media.duration && t.durationD) { t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25)); } } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { muteText: 'Mute Toggle', hideVolumeOnTouchDevices: true, audioVolume: 'horizontal', videoVolume: 'vertical' }); $.extend(MediaElementPlayer.prototype, { buildvolume: function(player, controls, layers, media) { // Android and iOS don't support volume controls if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices) return; var t = this, mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume, mute = (mode == 'horizontal') ? // horizontal version $('<div class="mejs-button mejs-volume-button mejs-mute">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+ '</div>' + '<div class="mejs-horizontal-volume-slider">'+ // outer background '<div class="mejs-horizontal-volume-total"></div>'+ // line background '<div class="mejs-horizontal-volume-current"></div>'+ // current volume '<div class="mejs-horizontal-volume-handle"></div>'+ // handle '</div>' ) .appendTo(controls) : // vertical version $('<div class="mejs-button mejs-volume-button mejs-mute">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+ '<div class="mejs-volume-slider">'+ // outer background '<div class="mejs-volume-total"></div>'+ // line background '<div class="mejs-volume-current"></div>'+ // current volume '<div class="mejs-volume-handle"></div>'+ // handle '</div>'+ '</div>') .appendTo(controls), volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'), volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'), volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'), volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'), positionVolumeHandle = function(volume, secondTry) { if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') { volumeSlider.show(); positionVolumeHandle(volume, true); volumeSlider.hide() return; } // correct to 0-1 volume = Math.max(0,volume); volume = Math.min(volume,1); // ajust mute button style if (volume == 0) { mute.removeClass('mejs-mute').addClass('mejs-unmute'); } else { mute.removeClass('mejs-unmute').addClass('mejs-mute'); } // position slider if (mode == 'vertical') { var // height of the full size volume slider background totalHeight = volumeTotal.height(), // top/left of full size volume slider background totalPosition = volumeTotal.position(), // the new top position based on the current volume // 70% volume on 100px height == top:30px newTop = totalHeight - (totalHeight * volume); // handle volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2)); // show the current visibility volumeCurrent.height(totalHeight - newTop ); volumeCurrent.css('top', totalPosition.top + newTop); } else { var // height of the full size volume slider background totalWidth = volumeTotal.width(), // top/left of full size volume slider background totalPosition = volumeTotal.position(), // the new left position based on the current volume newLeft = totalWidth * volume; // handle volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2)); // rezize the current part of the volume bar volumeCurrent.width( newLeft ); } }, handleVolumeMove = function(e) { var volume = null, totalOffset = volumeTotal.offset(); // calculate the new volume based on the moust position if (mode == 'vertical') { var railHeight = volumeTotal.height(), totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10), newY = e.pageY - totalOffset.top; volume = (railHeight - newY) / railHeight; // the controls just hide themselves (usually when mouse moves too far up) if (totalOffset.top == 0 || totalOffset.left == 0) return; } else { var railWidth = volumeTotal.width(), newX = e.pageX - totalOffset.left; volume = newX / railWidth; } // ensure the volume isn't outside 0-1 volume = Math.max(0,volume); volume = Math.min(volume,1); // position the slider and handle positionVolumeHandle(volume); // set the media object (this will trigger the volumechanged event) if (volume == 0) { media.setMuted(true); } else { media.setMuted(false); } media.setVolume(volume); }, mouseIsDown = false, mouseIsOver = false; // SLIDER mute .hover(function() { volumeSlider.show(); mouseIsOver = true; }, function() { mouseIsOver = false; if (!mouseIsDown && mode == 'vertical') { volumeSlider.hide(); } }); volumeSlider .bind('mouseover', function() { mouseIsOver = true; }) .bind('mousedown', function (e) { handleVolumeMove(e); $(document) .bind('mousemove.vol', function(e) { handleVolumeMove(e); }) .bind('mouseup.vol', function () { mouseIsDown = false; $(document).unbind('.vol'); if (!mouseIsOver && mode == 'vertical') { volumeSlider.hide(); } }); mouseIsDown = true; return false; }); // MUTE button mute.find('button').click(function() { media.setMuted( !media.muted ); }); // listen for volume change events from other sources media.addEventListener('volumechange', function(e) { if (!mouseIsDown) { if (media.muted) { positionVolumeHandle(0); mute.removeClass('mejs-mute').addClass('mejs-unmute'); } else { positionVolumeHandle(media.volume); mute.removeClass('mejs-unmute').addClass('mejs-mute'); } } }, false); if (t.container.is(':visible')) { // set initial volume positionVolumeHandle(player.options.startVolume); // shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements if (media.pluginType === 'native') { media.setVolume(player.options.startVolume); } } } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { usePluginFullScreen: true, newWindowCallback: function() { return '';}, fullscreenText: 'Fullscreen' }); $.extend(MediaElementPlayer.prototype, { isFullScreen: false, isNativeFullScreen: false, docStyleOverflow: null, isInIframe: false, buildfullscreen: function(player, controls, layers, media) { if (!player.isVideo) return; player.isInIframe = (window.location != window.parent.location); // native events if (mejs.MediaFeatures.hasTrueNativeFullScreen) { // chrome doesn't alays fire this in an iframe var target = null; if (mejs.MediaFeatures.hasMozNativeFullScreen) { target = $(document); } else { target = player.container; } target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) { if (mejs.MediaFeatures.isFullScreen()) { player.isNativeFullScreen = true; // reset the controls once we are fully in full screen player.setControlsSize(); } else { player.isNativeFullScreen = false; // when a user presses ESC // make sure to put the player back into place player.exitFullScreen(); } }); } var t = this, normalHeight = 0, normalWidth = 0, container = player.container, fullscreenBtn = $('<div class="mejs-button mejs-fullscreen-button">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' + '</div>') .appendTo(controls); if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) { fullscreenBtn.click(function() { var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen; if (isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } }); } else { var hideTimeout = null, supportsPointerEvents = (function() { // TAKEN FROM MODERNIZR var element = document.createElement('x'), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if(!('pointerEvents' in element.style)){ return false; } element.style.pointerEvents = 'auto'; element.style.pointerEvents = 'x'; documentElement.appendChild(element); supports = getComputedStyle && getComputedStyle(element, '').pointerEvents === 'auto'; documentElement.removeChild(element); return !!supports; })(); //console.log('supportsPointerEvents', supportsPointerEvents); if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :( // allows clicking through the fullscreen button and controls down directly to Flash /* When a user puts his mouse over the fullscreen button, the controls are disabled So we put a div over the video and another one on iether side of the fullscreen button that caputre mouse movement and restore the controls once the mouse moves outside of the fullscreen button */ var fullscreenIsDisabled = false, restoreControls = function() { if (fullscreenIsDisabled) { // hide the hovers videoHoverDiv.hide(); controlsLeftHoverDiv.hide(); controlsRightHoverDiv.hide(); // restore the control bar fullscreenBtn.css('pointer-events', ''); t.controls.css('pointer-events', ''); // store for later fullscreenIsDisabled = false; } }, videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), positionHoverDivs = function() { var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'}; videoHoverDiv.css(style); controlsLeftHoverDiv.css(style); controlsRightHoverDiv.css(style); // over video, but not controls videoHoverDiv .width( t.container.width() ) .height( t.container.height() - t.controls.height() ); // over controls, but not the fullscreen button var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left; fullScreenBtnWidth = fullscreenBtn.outerWidth(true); controlsLeftHoverDiv .width( fullScreenBtnOffset ) .height( t.controls.height() ) .css({top: t.container.height() - t.controls.height()}); // after the fullscreen button controlsRightHoverDiv .width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth ) .height( t.controls.height() ) .css({top: t.container.height() - t.controls.height(), left: fullScreenBtnOffset + fullScreenBtnWidth}); }; $(document).resize(function() { positionHoverDivs(); }); // on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash fullscreenBtn .mouseover(function() { if (!t.isFullScreen) { var buttonPos = fullscreenBtn.offset(), containerPos = player.container.offset(); // move the button in Flash into place media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false); // allows click through fullscreenBtn.css('pointer-events', 'none'); t.controls.css('pointer-events', 'none'); // show the divs that will restore things videoHoverDiv.show(); controlsRightHoverDiv.show(); controlsLeftHoverDiv.show(); positionHoverDivs(); fullscreenIsDisabled = true; } }); // restore controls anytime the user enters or leaves fullscreen media.addEventListener('fullscreenchange', function(e) { restoreControls(); }); // the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events // so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button /* $(document).mousemove(function(e) { // if the mouse is anywhere but the fullsceen button, then restore it all if (fullscreenIsDisabled) { var fullscreenBtnPos = fullscreenBtn.offset(); if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) || e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true) ) { fullscreenBtn.css('pointer-events', ''); t.controls.css('pointer-events', ''); fullscreenIsDisabled = false; } } }); */ } else { // the hover state will show the fullscreen button in Flash to hover up and click fullscreenBtn .mouseover(function() { if (hideTimeout !== null) { clearTimeout(hideTimeout); delete hideTimeout; } var buttonPos = fullscreenBtn.offset(), containerPos = player.container.offset(); media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true); }) .mouseout(function() { if (hideTimeout !== null) { clearTimeout(hideTimeout); delete hideTimeout; } hideTimeout = setTimeout(function() { media.hideFullscreenButton(); }, 1500); }); } } player.fullscreenBtn = fullscreenBtn; $(document).bind('keydown',function (e) { if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) { player.exitFullScreen(); } }); }, enterFullScreen: function() { var t = this; // firefox+flash can't adjust plugin sizes without resetting :( if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) { //t.media.setFullscreen(true); //player.isFullScreen = true; return; } // store overflow docStyleOverflow = document.documentElement.style.overflow; // set it to not show scroll bars so 100% will work document.documentElement.style.overflow = 'hidden'; // store sizing normalHeight = t.container.height(); normalWidth = t.container.width(); // attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now) if (t.media.pluginType === 'native') { if (mejs.MediaFeatures.hasTrueNativeFullScreen) { mejs.MediaFeatures.requestFullScreen(t.container[0]); //return; if (t.isInIframe) { // sometimes exiting from fullscreen doesn't work // notably in Chrome <iframe>. Fixed in version 17 setTimeout(function checkFullscreen() { if (t.isNativeFullScreen) { // check if the video is suddenly not really fullscreen if ($(window).width() !== screen.width) { // manually exit t.exitFullScreen(); } else { // test again setTimeout(checkFullscreen, 500); } } }, 500); } } else if (mejs.MediaFeatures.hasSemiNativeFullScreen) { t.media.webkitEnterFullscreen(); return; } } // check for iframe launch if (t.isInIframe) { var url = t.options.newWindowCallback(this); if (url !== '') { // launch immediately if (!mejs.MediaFeatures.hasTrueNativeFullScreen) { t.pause(); window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no'); return; } else { setTimeout(function() { if (!t.isNativeFullScreen) { t.pause(); window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no'); } }, 250); } } } // full window code // make full size t.container .addClass('mejs-container-fullscreen') .width('100%') .height('100%'); //.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000}); // Only needed for safari 5.1 native full screen, can cause display issues elsewhere // Actually, it seems to be needed for IE8, too //if (mejs.MediaFeatures.hasTrueNativeFullScreen) { setTimeout(function() { t.container.css({width: '100%', height: '100%'}); t.setControlsSize(); }, 500); //} if (t.pluginType === 'native') { t.$media .width('100%') .height('100%'); } else { t.container.find('object, embed, iframe') .width('100%') .height('100%'); //if (!mejs.MediaFeatures.hasTrueNativeFullScreen) { t.media.setVideoSize($(window).width(),$(window).height()); //} } t.layers.children('div') .width('100%') .height('100%'); if (t.fullscreenBtn) { t.fullscreenBtn .removeClass('mejs-fullscreen') .addClass('mejs-unfullscreen'); } t.setControlsSize(); t.isFullScreen = true; }, exitFullScreen: function() { var t = this; // firefox can't adjust plugins if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) { t.media.setFullscreen(false); //player.isFullScreen = false; return; } // come outo of native fullscreen if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) { mejs.MediaFeatures.cancelFullScreen(); } // restore scroll bars to document document.documentElement.style.overflow = docStyleOverflow; t.container .removeClass('mejs-container-fullscreen') .width(normalWidth) .height(normalHeight); //.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1}); if (t.pluginType === 'native') { t.$media .width(normalWidth) .height(normalHeight); } else { t.container.find('object embed') .width(normalWidth) .height(normalHeight); t.media.setVideoSize(normalWidth, normalHeight); } t.layers.children('div') .width(normalWidth) .height(normalHeight); t.fullscreenBtn .removeClass('mejs-unfullscreen') .addClass('mejs-fullscreen'); t.setControlsSize(); t.isFullScreen = false; } }); })(mejs.$); (function($) { // add extra default options $.extend(mejs.MepDefaults, { // this will automatically turn on a <track> startLanguage: '', tracksText: 'Captions/Subtitles' }); $.extend(MediaElementPlayer.prototype, { hasChapters: false, buildtracks: function(player, controls, layers, media) { if (!player.isVideo) return; if (player.tracks.length == 0) return; var t= this, i, options = ''; player.chapters = $('<div class="mejs-chapters mejs-layer"></div>') .prependTo(layers).hide(); player.captions = $('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>') .prependTo(layers).hide(); player.captionsText = player.captions.find('.mejs-captions-text'); player.captionsButton = $('<div class="mejs-button mejs-captions-button">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+ '<div class="mejs-captions-selector">'+ '<ul>'+ '<li>'+ '<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' + '<label for="' + player.id + '_captions_none">None</label>'+ '</li>' + '</ul>'+ '</div>'+ '</div>') .appendTo(controls) // hover .hover(function() { $(this).find('.mejs-captions-selector').css('visibility','visible'); }, function() { $(this).find('.mejs-captions-selector').css('visibility','hidden'); }) // handle clicks to the language radio buttons .delegate('input[type=radio]','click',function() { lang = this.value; if (lang == 'none') { player.selectedTrack = null; } else { for (i=0; i<player.tracks.length; i++) { if (player.tracks[i].srclang == lang) { player.selectedTrack = player.tracks[i]; player.captions.attr('lang', player.selectedTrack.srclang); player.displayCaptions(); break; } } } }); //.bind('mouseenter', function() { // player.captionsButton.find('.mejs-captions-selector').css('visibility','visible') //}); if (!player.options.alwaysShowControls) { // move with controls player.container .bind('mouseenter', function () { // push captions above controls player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover'); }) .bind('mouseleave', function () { if (!media.paused) { // move back to normal place player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover'); } }); } else { player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover'); } player.trackToLoad = -1; player.selectedTrack = null; player.isLoadingTrack = false; // add to list for (i=0; i<player.tracks.length; i++) { if (player.tracks[i].kind == 'subtitles') { player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label); } } player.loadNextTrack(); media.addEventListener('timeupdate',function(e) { player.displayCaptions(); }, false); media.addEventListener('loadedmetadata', function(e) { player.displayChapters(); }, false); player.container.hover( function () { // chapters if (player.hasChapters) { player.chapters.css('visibility','visible'); player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight()); } }, function () { if (player.hasChapters && !media.paused) { player.chapters.fadeOut(200, function() { $(this).css('visibility','hidden'); $(this).css('display','block'); }); } }); // check for autoplay if (player.node.getAttribute('autoplay') !== null) { player.chapters.css('visibility','hidden'); } }, loadNextTrack: function() { var t = this; t.trackToLoad++; if (t.trackToLoad < t.tracks.length) { t.isLoadingTrack = true; t.loadTrack(t.trackToLoad); } else { // add done? t.isLoadingTrack = false; } }, loadTrack: function(index){ var t = this, track = t.tracks[index], after = function() { track.isLoaded = true; // create button //t.addTrackButton(track.srclang); t.enableTrackButton(track.srclang, track.label); t.loadNextTrack(); }; $.ajax({ url: track.src, dataType: "text", success: function(d) { // parse the loaded file if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) { track.entries = mejs.TrackFormatParser.dfxp.parse(d); } else { track.entries = mejs.TrackFormatParser.webvvt.parse(d); } after(); if (track.kind == 'chapters' && t.media.duration > 0) { t.drawChapters(track); } }, error: function() { t.loadNextTrack(); } }); }, enableTrackButton: function(lang, label) { var t = this; if (label === '') { label = mejs.language.codes[lang] || lang; } t.captionsButton .find('input[value=' + lang + ']') .prop('disabled',false) .siblings('label') .html( label ); // auto select if (t.options.startLanguage == lang) { $('#' + t.id + '_captions_' + lang).click(); } t.adjustLanguageBox(); }, addTrackButton: function(lang, label) { var t = this; if (label === '') { label = mejs.language.codes[lang] || lang; } t.captionsButton.find('ul').append( $('<li>'+ '<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' + '<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+ '</li>') ); t.adjustLanguageBox(); // remove this from the dropdownlist (if it exists) t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove(); }, adjustLanguageBox:function() { var t = this; // adjust the size of the outer box t.captionsButton.find('.mejs-captions-selector').height( t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) + t.captionsButton.find('.mejs-captions-translations').outerHeight(true) ); }, displayCaptions: function() { if (typeof this.tracks == 'undefined') return; var t = this, i, track = t.selectedTrack; if (track != null && track.isLoaded) { for (i=0; i<track.entries.times.length; i++) { if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){ t.captionsText.html(track.entries.text[i]); t.captions.show().height(0); return; // exit out if one is visible; } } t.captions.hide(); } else { t.captions.hide(); } }, displayChapters: function() { var t = this, i; for (i=0; i<t.tracks.length; i++) { if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) { t.drawChapters(t.tracks[i]); t.hasChapters = true; break; } } }, drawChapters: function(chapters) { var t = this, i, dur, //width, //left, percent = 0, usedPercent = 0; t.chapters.empty(); for (i=0; i<chapters.entries.times.length; i++) { dur = chapters.entries.times[i].stop - chapters.entries.times[i].start; percent = Math.floor(dur / t.media.duration * 100); if (percent + usedPercent > 100 || // too large i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in { percent = 100 - usedPercent; } //width = Math.floor(t.width * dur / t.media.duration); //left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration); //if (left + width > t.width) { // width = t.width - left; //} t.chapters.append( $( '<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' + '<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' + '<span class="ch-title">' + chapters.entries.text[i] + '</span>' + '<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '&ndash;' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' + '</div>' + '</div>')); usedPercent += percent; } t.chapters.find('div.mejs-chapter').click(function() { t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) ); if (t.media.paused) { t.media.play(); } }); t.chapters.show(); } }); mejs.language = { codes: { af:'Afrikaans', sq:'Albanian', ar:'Arabic', be:'Belarusian', bg:'Bulgarian', ca:'Catalan', zh:'Chinese', 'zh-cn':'Chinese Simplified', 'zh-tw':'Chinese Traditional', hr:'Croatian', cs:'Czech', da:'Danish', nl:'Dutch', en:'English', et:'Estonian', tl:'Filipino', fi:'Finnish', fr:'French', gl:'Galician', de:'German', el:'Greek', ht:'Haitian Creole', iw:'Hebrew', hi:'Hindi', hu:'Hungarian', is:'Icelandic', id:'Indonesian', ga:'Irish', it:'Italian', ja:'Japanese', ko:'Korean', lv:'Latvian', lt:'Lithuanian', mk:'Macedonian', ms:'Malay', mt:'Maltese', no:'Norwegian', fa:'Persian', pl:'Polish', pt:'Portuguese', //'pt-pt':'Portuguese (Portugal)', ro:'Romanian', ru:'Russian', sr:'Serbian', sk:'Slovak', sl:'Slovenian', es:'Spanish', sw:'Swahili', sv:'Swedish', tl:'Tagalog', th:'Thai', tr:'Turkish', uk:'Ukrainian', vi:'Vietnamese', cy:'Welsh', yi:'Yiddish' } }; /* Parses WebVVT format which should be formatted as ================================ WEBVTT 1 00:00:01,1 --> 00:00:05,000 A line of text 2 00:01:15,1 --> 00:02:05,000 A second line of text =============================== Adapted from: http://www.delphiki.com/html5/playr */ mejs.TrackFormatParser = { webvvt: { // match start "chapter-" (or anythingelse) pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/, pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/, parse: function(trackText) { var i = 0, lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/), entries = {text:[], times:[]}, timecode, text; for(; i<lines.length; i++) { // check for the line number if (this.pattern_identifier.exec(lines[i])){ // skip to the next line where the start --> end time code should be i++; timecode = this.pattern_timecode.exec(lines[i]); if (timecode && i<lines.length){ i++; // grab all the (possibly multi-line) text that follows text = lines[i]; i++; while(lines[i] !== '' && i<lines.length){ text = text + '\n' + lines[i]; i++; } text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>"); // Text is in a different array so I can use .join entries.text.push(text); entries.times.push( { start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]), stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]), settings: timecode[5] }); } } } return entries; } }, // Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420 dfxp: { parse: function(trackText) { trackText = $(trackText).filter("tt"); var i = 0, container = trackText.children("div").eq(0), lines = container.find("p"), styleNode = trackText.find("#" + container.attr("style")), styles, begin, end, text, entries = {text:[], times:[]}; if (styleNode.length) { var attributes = styleNode.removeAttr("id").get(0).attributes; if (attributes.length) { styles = {}; for (i = 0; i < attributes.length; i++) { styles[attributes[i].name.split(":")[1]] = attributes[i].value; } } } for(i = 0; i<lines.length; i++) { var style; var _temp_times = { start: null, stop: null, style: null }; if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin")); if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end")); if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end")); if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin")); if (styles) { style = ""; for (var _style in styles) { style += _style + ":" + styles[_style] + ";"; } } if (style) _temp_times.style = style; if (_temp_times.start == 0) _temp_times.start = 0.200; entries.times.push(_temp_times); text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>"); entries.text.push(text); if (entries.times.start == 0) entries.times.start = 2; } return entries; } }, split2: function (text, regex) { // normal version for compliant browsers // see below for IE fix return text.split(regex); } }; // test for browsers with bad String.split method. if ('x\n\ny'.split(/\n/gi).length != 3) { // add super slow IE8 and below version mejs.TrackFormatParser.split2 = function(text, regex) { var parts = [], chunk = '', i; for (i=0; i<text.length; i++) { chunk += text.substring(i,i+1); if (regex.test(chunk)) { parts.push(chunk.replace(regex, '')); chunk = ''; } } parts.push(chunk); return parts; } } })(mejs.$); /* * ContextMenu Plugin * * */ (function($) { $.extend(mejs.MepDefaults, { 'contextMenuItems': [ // demo of a fullscreen option { render: function(player) { // check for fullscreen plugin if (typeof player.enterFullScreen == 'undefined') return null; if (player.isFullScreen) { return "Turn off Fullscreen"; } else { return "Go Fullscreen"; } }, click: function(player) { if (player.isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } } } , // demo of a mute/unmute button { render: function(player) { if (player.media.muted) { return "Unmute"; } else { return "Mute"; } }, click: function(player) { if (player.media.muted) { player.setMuted(false); } else { player.setMuted(true); } } }, // separator { isSeparator: true } , // demo of simple download video { render: function(player) { return "Download Video"; }, click: function(player) { window.location.href = player.media.currentSrc; } } ]} ); $.extend(MediaElementPlayer.prototype, { buildcontextmenu: function(player, controls, layers, media) { // create context menu player.contextMenu = $('<div class="mejs-contextmenu"></div>') .appendTo($('body')) .hide(); // create events for showing context menu player.container.bind('contextmenu', function(e) { if (player.isContextMenuEnabled) { e.preventDefault(); player.renderContextMenu(e.clientX-1, e.clientY-1); return false; } }); player.container.bind('click', function() { player.contextMenu.hide(); }); player.contextMenu.bind('mouseleave', function() { //console.log('context hover out'); player.startContextMenuTimer(); }); }, isContextMenuEnabled: true, enableContextMenu: function() { this.isContextMenuEnabled = true; }, disableContextMenu: function() { this.isContextMenuEnabled = false; }, contextMenuTimeout: null, startContextMenuTimer: function() { //console.log('startContextMenuTimer'); var t = this; t.killContextMenuTimer(); t.contextMenuTimer = setTimeout(function() { t.hideContextMenu(); t.killContextMenuTimer(); }, 750); }, killContextMenuTimer: function() { var timer = this.contextMenuTimer; //console.log('killContextMenuTimer', timer); if (timer != null) { clearTimeout(timer); delete timer; timer = null; } }, hideContextMenu: function() { this.contextMenu.hide(); }, renderContextMenu: function(x,y) { // alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly var t = this, html = '', items = t.options.contextMenuItems; for (var i=0, il=items.length; i<il; i++) { if (items[i].isSeparator) { html += '<div class="mejs-contextmenu-separator"></div>'; } else { var rendered = items[i].render(t); // render can return null if the item doesn't need to be used at the moment if (rendered != null) { html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>'; } } } // position and show the context menu t.contextMenu .empty() .append($(html)) .css({top:y, left:x}) .show(); // bind events t.contextMenu.find('.mejs-contextmenu-item').each(function() { // which one is this? var $dom = $(this), itemIndex = parseInt( $dom.data('itemindex'), 10 ), item = t.options.contextMenuItems[itemIndex]; // bind extra functionality? if (typeof item.show != 'undefined') item.show( $dom , t); // bind click action $dom.click(function() { // perform click action if (typeof item.click != 'undefined') item.click(t); // close t.contextMenu.hide(); }); }); // stop the controls from hiding setTimeout(function() { t.killControlsTimer('rev3'); }, 100); } }); })(mejs.$);
JavaScript
/*! * MediaElement.js * HTML5 <video> and <audio> shim and player * http://mediaelementjs.com/ * * Creates a JavaScript object that mimics HTML5 MediaElement API * for browsers that don't understand HTML5 or can't play the provided codec * Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3 * * Copyright 2010-2012, John Dyer (http://j.hn) * Dual licensed under the MIT or GPL Version 2 licenses. * */ // Namespace var mejs = mejs || {}; // version number mejs.version = '2.9.5'; // player number (for missing, same id attr) mejs.meIndex = 0; // media types accepted by plugins mejs.plugins = { silverlight: [ {version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']} ], flash: [ {version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']} //,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!) ], youtube: [ {version: null, types: ['video/youtube', 'video/x-youtube']} ], vimeo: [ {version: null, types: ['video/vimeo']} ] }; /* Utility methods */ mejs.Utility = { encodeUrl: function(url) { return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26'); }, escapeHTML: function(s) { return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, absolutizeUrl: function(url) { var el = document.createElement('div'); el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>'; return el.firstChild.href; }, getScriptPath: function(scriptNames) { var i = 0, j, path = '', name = '', script, scripts = document.getElementsByTagName('script'), il = scripts.length, jl = scriptNames.length; for (; i < il; i++) { script = scripts[i].src; for (j = 0; j < jl; j++) { name = scriptNames[j]; if (script.indexOf(name) > -1) { path = script.substring(0, script.indexOf(name)); break; } } if (path !== '') { break; } } return path; }, secondsToTimeCode: function(time, forceHours, showFrameCount, fps) { //add framecount if (typeof showFrameCount == 'undefined') { showFrameCount=false; } else if(typeof fps == 'undefined') { fps = 25; } var hours = Math.floor(time / 3600) % 24, minutes = Math.floor(time / 60) % 60, seconds = Math.floor(time % 60), frames = Math.floor(((time % 1)*fps).toFixed(3)), result = ( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '') + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds) + ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : ''); return result; }, timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){ if (typeof showFrameCount == 'undefined') { showFrameCount=false; } else if(typeof fps == 'undefined') { fps = 25; } var tc_array = hh_mm_ss_ff.split(":"), tc_hh = parseInt(tc_array[0], 10), tc_mm = parseInt(tc_array[1], 10), tc_ss = parseInt(tc_array[2], 10), tc_ff = 0, tc_in_seconds = 0; if (showFrameCount) { tc_ff = parseInt(tc_array[3])/fps; } tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff; return tc_in_seconds; }, convertSMPTEtoSeconds: function (SMPTE) { if (typeof SMPTE != 'string') return false; SMPTE = SMPTE.replace(',', '.'); var secs = 0, decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0, multiplier = 1; SMPTE = SMPTE.split(':').reverse(); for (var i = 0; i < SMPTE.length; i++) { multiplier = 1; if (i > 0) { multiplier = Math.pow(60, i); } secs += Number(SMPTE[i]) * multiplier; } return Number(secs.toFixed(decimalLen)); }, /* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */ removeSwf: function(id) { var obj = document.getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (mejs.MediaFeatures.isIE) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { mejs.Utility.removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } }, removeObjectInIE: function(id) { var obj = document.getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } }; // Core detector, plugins are added below mejs.PluginDetector = { // main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]); hasPluginVersion: function(plugin, v) { var pv = this.plugins[plugin]; v[1] = v[1] || 0; v[2] = v[2] || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; }, // cached values nav: window.navigator, ua: window.navigator.userAgent.toLowerCase(), // stored version numbers plugins: [], // runs detectPlugin() and stores the version number addPlugin: function(p, pluginName, mimeType, activeX, axDetect) { this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect); }, // get the version number from the mimetype (all but IE) or ActiveX (IE) detectPlugin: function(pluginName, mimeType, activeX, axDetect) { var version = [0,0,0], description, i, ax; // Firefox, Webkit, Opera if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') { description = this.nav.plugins[pluginName].description; if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) { version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.'); for (i=0; i<version.length; i++) { version[i] = parseInt(version[i].match(/\d+/), 10); } } // Internet Explorer / ActiveX } else if (typeof(window.ActiveXObject) != 'undefined') { try { ax = new ActiveXObject(activeX); if (ax) { version = axDetect(ax); } } catch (e) { } } return version; } }; // Add Flash detection mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) { // adapted from SWFObject var version = [], d = ax.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } return version; }); // Add Silverlight detection mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) { // Silverlight cannot report its version number to IE // but it does have a isVersionSupported function, so we have to loop through it to get a version number. // adapted from http://www.silverlightversion.com/ var v = [0,0,0,0], loopMatch = function(ax, v, i, n) { while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){ v[i]+=n; } v[i] -= n; }; loopMatch(ax, v, 0, 1); loopMatch(ax, v, 1, 1); loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx) loopMatch(ax, v, 2, 1000); loopMatch(ax, v, 2, 100); loopMatch(ax, v, 2, 10); loopMatch(ax, v, 2, 1); loopMatch(ax, v, 3, 1); return v; }); // add adobe acrobat /* PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) { var version = [], d = ax.GetVersions().split(',')[0].split('=')[1].split('.'); if (d) { version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } return version; }); */ // necessary detection (fixes for <IE9) mejs.MediaFeatures = { init: function() { var t = this, d = document, nav = mejs.PluginDetector.nav, ua = mejs.PluginDetector.ua.toLowerCase(), i, v, html5Elements = ['source','track','audio','video']; // detect browsers (only the ones that have some kind of quirk we need to work around) t.isiPad = (ua.match(/ipad/i) !== null); t.isiPhone = (ua.match(/iphone/i) !== null); t.isiOS = t.isiPhone || t.isiPad; t.isAndroid = (ua.match(/android/i) !== null); t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null); t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1); t.isChrome = (ua.match(/chrome/gi) !== null); t.isFirefox = (ua.match(/firefox/gi) !== null); t.isWebkit = (ua.match(/webkit/gi) !== null); t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit; t.isOpera = (ua.match(/opera/gi) !== null); t.hasTouch = ('ontouchstart' in window); // create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection for (i=0; i<html5Elements.length; i++) { v = document.createElement(html5Elements[i]); } t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid); // detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails) // iOS t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined'); // Webkit/firefox t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined'); t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined'); t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen); t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen; if (t.hasMozNativeFullScreen) { t.nativeFullScreenEnabled = v.mozFullScreenEnabled; } if (this.isChrome) { t.hasSemiNativeFullScreen = false; } if (t.hasTrueNativeFullScreen) { t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange'; t.isFullScreen = function() { if (v.mozRequestFullScreen) { return d.mozFullScreen; } else if (v.webkitRequestFullScreen) { return d.webkitIsFullScreen; } } t.requestFullScreen = function(el) { if (t.hasWebkitNativeFullScreen) { el.webkitRequestFullScreen(); } else if (t.hasMozNativeFullScreen) { el.mozRequestFullScreen(); } } t.cancelFullScreen = function() { if (t.hasWebkitNativeFullScreen) { document.webkitCancelFullScreen(); } else if (t.hasMozNativeFullScreen) { document.mozCancelFullScreen(); } } } // OS X 10.5 can't do this even if it says it can :( if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) { t.hasNativeFullScreen = false; t.hasSemiNativeFullScreen = false; } } }; mejs.MediaFeatures.init(); /* extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below) */ mejs.HtmlMediaElement = { pluginType: 'native', isFullScreen: false, setCurrentTime: function (time) { this.currentTime = time; }, setMuted: function (muted) { this.muted = muted; }, setVolume: function (volume) { this.volume = volume; }, // for parity with the plugin versions stop: function () { this.pause(); }, // This can be a url string // or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}] setSrc: function (url) { // Fix for IE9 which can't set .src when there are <source> elements. Awesome, right? var existingSources = this.getElementsByTagName('source'); while (existingSources.length > 0){ this.removeChild(existingSources[0]); } if (typeof url == 'string') { this.src = url; } else { var i, media; for (i=0; i<url.length; i++) { media = url[i]; if (this.canPlayType(media.type)) { this.src = media.src; } } } }, setVideoSize: function (width, height) { this.width = width; this.height = height; } }; /* Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember] */ mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) { this.id = pluginid; this.pluginType = pluginType; this.src = mediaUrl; this.events = {}; }; // JavaScript values and ExternalInterface methods that match HTML5 video properties methods // http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html mejs.PluginMediaElement.prototype = { // special pluginElement: null, pluginType: '', isFullScreen: false, // not implemented :( playbackRate: -1, defaultPlaybackRate: -1, seekable: [], played: [], // HTML5 read-only properties paused: true, ended: false, seeking: false, duration: 0, error: null, tagName: '', // HTML5 get/set properties, but only set (updated by event handlers) muted: false, volume: 1, currentTime: 0, // HTML5 methods play: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.playVideo(); } else { this.pluginApi.playMedia(); } this.paused = false; } }, load: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { } else { this.pluginApi.loadMedia(); } this.paused = false; } }, pause: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.pauseVideo(); } else { this.pluginApi.pauseMedia(); } this.paused = true; } }, stop: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.stopVideo(); } else { this.pluginApi.stopMedia(); } this.paused = true; } }, canPlayType: function(type) { var i, j, pluginInfo, pluginVersions = mejs.plugins[this.pluginType]; for (i=0; i<pluginVersions.length; i++) { pluginInfo = pluginVersions[i]; // test if user has the correct plugin version if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) { // test for plugin playback types for (j=0; j<pluginInfo.types.length; j++) { // find plugin that can play the type if (type == pluginInfo.types[j]) { return true; } } } } return false; }, positionFullscreenButton: function(x,y,visibleAndAbove) { if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) { this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove); } }, hideFullscreenButton: function() { if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) { this.pluginApi.hideFullscreenButton(); } }, // custom methods since not all JavaScript implementations support get/set // This can be a url string // or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}] setSrc: function (url) { if (typeof url == 'string') { this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url)); this.src = mejs.Utility.absolutizeUrl(url); } else { var i, media; for (i=0; i<url.length; i++) { media = url[i]; if (this.canPlayType(media.type)) { this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src)); this.src = mejs.Utility.absolutizeUrl(url); } } } }, setCurrentTime: function (time) { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.seekTo(time); } else { this.pluginApi.setCurrentTime(time); } this.currentTime = time; } }, setVolume: function (volume) { if (this.pluginApi != null) { // same on YouTube and MEjs if (this.pluginType == 'youtube') { this.pluginApi.setVolume(volume * 100); } else { this.pluginApi.setVolume(volume); } this.volume = volume; } }, setMuted: function (muted) { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { if (muted) { this.pluginApi.mute(); } else { this.pluginApi.unMute(); } this.muted = muted; this.dispatchEvent('volumechange'); } else { this.pluginApi.setMuted(muted); } this.muted = muted; } }, // additional non-HTML5 methods setVideoSize: function (width, height) { //if (this.pluginType == 'flash' || this.pluginType == 'silverlight') { if ( this.pluginElement.style) { this.pluginElement.style.width = width + 'px'; this.pluginElement.style.height = height + 'px'; } if (this.pluginApi != null && this.pluginApi.setVideoSize) { this.pluginApi.setVideoSize(width, height); } //} }, setFullscreen: function (fullscreen) { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.pluginApi.setFullscreen(fullscreen); } }, enterFullScreen: function() { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.setFullscreen(true); } }, exitFullScreen: function() { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.setFullscreen(false); } }, // start: fake events addEventListener: function (eventName, callback, bubble) { this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(callback); }, removeEventListener: function (eventName, callback) { if (!eventName) { this.events = {}; return true; } var callbacks = this.events[eventName]; if (!callbacks) return true; if (!callback) { this.events[eventName] = []; return true; } for (i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { this.events[eventName].splice(i, 1); return true; } } return false; }, dispatchEvent: function (eventName) { var i, args, callbacks = this.events[eventName]; if (callbacks) { args = Array.prototype.slice.call(arguments, 1); for (i = 0; i < callbacks.length; i++) { callbacks[i].apply(null, args); } } }, // end: fake events // fake DOM attribute methods attributes: {}, hasAttribute: function(name){ return (name in this.attributes); }, removeAttribute: function(name){ delete this.attributes[name]; }, getAttribute: function(name){ if (this.hasAttribute(name)) { return this.attributes[name]; } return ''; }, setAttribute: function(name, value){ this.attributes[name] = value; }, remove: function() { mejs.Utility.removeSwf(this.pluginElement.id); } }; // Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties mejs.MediaPluginBridge = { pluginMediaElements:{}, htmlMediaElements:{}, registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) { this.pluginMediaElements[id] = pluginMediaElement; this.htmlMediaElements[id] = htmlMediaElement; }, // when Flash/Silverlight is ready, it calls out to this method initPlugin: function (id) { var pluginMediaElement = this.pluginMediaElements[id], htmlMediaElement = this.htmlMediaElements[id]; if (pluginMediaElement) { // find the javascript bridge switch (pluginMediaElement.pluginType) { case "flash": pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id); break; case "silverlight": pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id); pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS; break; } if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) { pluginMediaElement.success(pluginMediaElement, htmlMediaElement); } } }, // receives events from Flash/Silverlight and sends them out as HTML5 media events // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html fireEvent: function (id, eventName, values) { var e, i, bufferedTime, pluginMediaElement = this.pluginMediaElements[id]; pluginMediaElement.ended = false; pluginMediaElement.paused = true; // fake event object to mimic real HTML media event. e = { type: eventName, target: pluginMediaElement }; // attach all values to element and event object for (i in values) { pluginMediaElement[i] = values[i]; e[i] = values[i]; } // fake the newer W3C buffered TimeRange (loaded and total have been removed) bufferedTime = values.bufferedTime || 0; e.target.buffered = e.buffered = { start: function(index) { return 0; }, end: function (index) { return bufferedTime; }, length: 1 }; pluginMediaElement.dispatchEvent(e.type, e); } }; /* Default options */ mejs.MediaElementDefaults = { // allows testing on HTML5, flash, silverlight // auto: attempts to detect what the browser can do // auto_plugin: prefer plugins and then attempt native HTML5 // native: forces HTML5 playback // shim: disallows HTML5, will attempt either Flash or Silverlight // none: forces fallback view mode: 'auto', // remove or reorder to change plugin priority and availability plugins: ['flash','silverlight','youtube','vimeo'], // shows debug errors on screen enablePluginDebug: false, // overrides the type specified, useful for dynamic instantiation type: '', // path to Flash and Silverlight plugins pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']), // name of flash file flashName: 'flashmediaelement.swf', // streamer for RTMP streaming flashStreamer: '', // turns on the smoothing filter in Flash enablePluginSmoothing: false, // name of silverlight file silverlightName: 'silverlightmediaelement.xap', // default if the <video width> is not specified defaultVideoWidth: 480, // default if the <video height> is not specified defaultVideoHeight: 270, // overrides <video width> pluginWidth: -1, // overrides <video height> pluginHeight: -1, // additional plugin variables in 'key=value' form pluginVars: [], // rate in milliseconds for Flash and Silverlight to fire the timeupdate event // larger number is less accurate, but less strain on plugin->JavaScript bridge timerRate: 250, // initial volume for player startVolume: 0.8, success: function () { }, error: function () { } }; /* Determines if a browser supports the <video> or <audio> element and returns either the native element or a Flash/Silverlight version that mimics HTML5 MediaElement */ mejs.MediaElement = function (el, o) { return mejs.HtmlMediaElementShim.create(el,o); }; mejs.HtmlMediaElementShim = { create: function(el, o) { var options = mejs.MediaElementDefaults, htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el, tagName = htmlMediaElement.tagName.toLowerCase(), isMediaTag = (tagName === 'audio' || tagName === 'video'), src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'), poster = htmlMediaElement.getAttribute('poster'), autoplay = htmlMediaElement.getAttribute('autoplay'), preload = htmlMediaElement.getAttribute('preload'), controls = htmlMediaElement.getAttribute('controls'), playback, prop; // extend options for (prop in o) { options[prop] = o[prop]; } // clean up attributes src = (typeof src == 'undefined' || src === null || src == '') ? null : src; poster = (typeof poster == 'undefined' || poster === null) ? '' : poster; preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload; autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false'); controls = !(typeof controls == 'undefined' || controls === null || controls === 'false'); // test for HTML5 and plugin capabilities playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src); playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : ''; if (playback.method == 'native') { // second fix for android if (mejs.MediaFeatures.isBustedAndroid) { htmlMediaElement.src = playback.url; htmlMediaElement.addEventListener('click', function() { htmlMediaElement.play(); }, false); } // add methods to native HTMLMediaElement return this.updateNative(playback, options, autoplay, preload); } else if (playback.method !== '') { // create plugin to mimic HTMLMediaElement return this.createPlugin( playback, options, poster, autoplay, preload, controls); } else { // boo, no HTML5, no Flash, no Silverlight. this.createErrorMessage( playback, options, poster ); return this; } }, determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) { var mediaFiles = [], i, j, k, l, n, type, result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')}, pluginName, pluginVersions, pluginInfo, dummy; // STEP 1: Get URL and type from <video src> or <source src> // supplied type overrides <video type> and <source type> if (typeof options.type != 'undefined' && options.type !== '') { // accept either string or array of types if (typeof options.type == 'string') { mediaFiles.push({type:options.type, url:src}); } else { for (i=0; i<options.type.length; i++) { mediaFiles.push({type:options.type[i], url:src}); } } // test for src attribute first } else if (src !== null) { type = this.formatType(src, htmlMediaElement.getAttribute('type')); mediaFiles.push({type:type, url:src}); // then test for <source> elements } else { // test <source> types to see if they are usable for (i = 0; i < htmlMediaElement.childNodes.length; i++) { n = htmlMediaElement.childNodes[i]; if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') { src = n.getAttribute('src'); type = this.formatType(src, n.getAttribute('type')); mediaFiles.push({type:type, url:src}); } } } // in the case of dynamicly created players // check for audio types if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) { result.isVideo = false; } // STEP 2: Test for playback method // special case for Android which sadly doesn't implement the canPlayType function (always returns '') if (mejs.MediaFeatures.isBustedAndroid) { htmlMediaElement.canPlayType = function(type) { return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : ''; }; } // test for native playback first if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) { if (!isMediaTag) { // create a real HTML5 Media Element dummy = document.createElement( result.isVideo ? 'video' : 'audio'); htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement); htmlMediaElement.style.display = 'none'; // use this one from now on result.htmlMediaElement = htmlMediaElement = dummy; } for (i=0; i<mediaFiles.length; i++) { // normal check if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== '' // special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg') || htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') { result.method = 'native'; result.url = mediaFiles[i].url; break; } } if (result.method === 'native') { if (result.url !== null) { htmlMediaElement.src = result.url; } // if `auto_plugin` mode, then cache the native result but try plugins. if (options.mode !== 'auto_plugin') { return result; } } } // if native playback didn't work, then test plugins if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') { for (i=0; i<mediaFiles.length; i++) { type = mediaFiles[i].type; // test all plugins in order of preference [silverlight, flash] for (j=0; j<options.plugins.length; j++) { pluginName = options.plugins[j]; // test version of plugin (for future features) pluginVersions = mejs.plugins[pluginName]; for (k=0; k<pluginVersions.length; k++) { pluginInfo = pluginVersions[k]; // test if user has the correct plugin version // for youtube/vimeo if (pluginInfo.version == null || mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) { // test for plugin playback types for (l=0; l<pluginInfo.types.length; l++) { // find plugin that can play the type if (type == pluginInfo.types[l]) { result.method = pluginName; result.url = mediaFiles[i].url; return result; } } } } } } } // at this point, being in 'auto_plugin' mode implies that we tried plugins but failed. // if we have native support then return that. if (options.mode === 'auto_plugin' && result.method === 'native') { return result; } // what if there's nothing to play? just grab the first available if (result.method === '' && mediaFiles.length > 0) { result.url = mediaFiles[0].url; } return result; }, formatType: function(url, type) { var ext; // if no type is supplied, fake it with the extension if (url && !type) { return this.getTypeFromFile(url); } else { // only return the mime part of the type in case the attribute contains the codec // see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element // `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4` if (type && ~type.indexOf(';')) { return type.substr(0, type.indexOf(';')); } else { return type; } } }, getTypeFromFile: function(url) { var ext = url.substring(url.lastIndexOf('.') + 1); return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext); }, getTypeFromExtension: function(ext) { switch (ext) { case 'mp4': case 'm4v': return 'mp4'; case 'webm': case 'webma': case 'webmv': return 'webm'; case 'ogg': case 'oga': case 'ogv': return 'ogg'; default: return ext; } }, createErrorMessage: function(playback, options, poster) { var htmlMediaElement = playback.htmlMediaElement, errorContainer = document.createElement('div'); errorContainer.className = 'me-cannotplay'; try { errorContainer.style.width = htmlMediaElement.width + 'px'; errorContainer.style.height = htmlMediaElement.height + 'px'; } catch (e) {} errorContainer.innerHTML = (poster !== '') ? '<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' : '<a href="' + playback.url + '"><span>Download File</span></a>'; htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement); htmlMediaElement.style.display = 'none'; options.error(htmlMediaElement); }, createPlugin:function(playback, options, poster, autoplay, preload, controls) { var htmlMediaElement = playback.htmlMediaElement, width = 1, height = 1, pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++), pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url), container = document.createElement('div'), specialIEContainer, node, initVars; // copy tagName from html media element pluginMediaElement.tagName = htmlMediaElement.tagName // copy attributes from html media element to plugin media element for (var i = 0; i < htmlMediaElement.attributes.length; i++) { var attribute = htmlMediaElement.attributes[i]; if (attribute.specified == true) { pluginMediaElement.setAttribute(attribute.name, attribute.value); } } // check for placement inside a <p> tag (sometimes WYSIWYG editors do this) node = htmlMediaElement.parentNode; while (node !== null && node.tagName.toLowerCase() != 'body') { if (node.parentNode.tagName.toLowerCase() == 'p') { node.parentNode.parentNode.insertBefore(node, node.parentNode); break; } node = node.parentNode; } if (playback.isVideo) { width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth; height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight; // in case of '%' make sure it's encoded width = mejs.Utility.encodeUrl(width); height = mejs.Utility.encodeUrl(height); } else { if (options.enablePluginDebug) { width = 320; height = 240; } } // register plugin pluginMediaElement.success = options.success; mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement); // add container (must be added to DOM before inserting HTML for IE) container.className = 'me-plugin'; container.id = pluginid + '_container'; if (playback.isVideo) { htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement); } else { document.body.insertBefore(container, document.body.childNodes[0]); } // flash/silverlight vars initVars = [ 'id=' + pluginid, 'isvideo=' + ((playback.isVideo) ? "true" : "false"), 'autoplay=' + ((autoplay) ? "true" : "false"), 'preload=' + preload, 'width=' + width, 'startvolume=' + options.startVolume, 'timerrate=' + options.timerRate, 'flashstreamer=' + options.flashStreamer, 'height=' + height]; if (playback.url !== null) { if (playback.method == 'flash') { initVars.push('file=' + mejs.Utility.encodeUrl(playback.url)); } else { initVars.push('file=' + playback.url); } } if (options.enablePluginDebug) { initVars.push('debug=true'); } if (options.enablePluginSmoothing) { initVars.push('smoothing=true'); } if (controls) { initVars.push('controls=true'); // shows controls in the plugin if desired } if (options.pluginVars) { initVars = initVars.concat(options.pluginVars); } switch (playback.method) { case 'silverlight': container.innerHTML = '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' + '<param name="initParams" value="' + initVars.join(',') + '" />' + '<param name="windowless" value="true" />' + '<param name="background" value="black" />' + '<param name="minRuntimeVersion" value="3.0.0.0" />' + '<param name="autoUpgrade" value="true" />' + '<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' + '</object>'; break; case 'flash': if (mejs.MediaFeatures.isIE) { specialIEContainer = document.createElement('div'); container.appendChild(specialIEContainer); specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' + 'id="' + pluginid + '" width="' + width + '" height="' + height + '">' + '<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' + '<param name="flashvars" value="' + initVars.join('&amp;') + '" />' + '<param name="quality" value="high" />' + '<param name="bgcolor" value="#000000" />' + '<param name="wmode" value="transparent" />' + '<param name="allowScriptAccess" value="always" />' + '<param name="allowFullScreen" value="true" />' + '</object>'; } else { container.innerHTML = '<embed id="' + pluginid + '" name="' + pluginid + '" ' + 'play="true" ' + 'loop="false" ' + 'quality="high" ' + 'bgcolor="#000000" ' + 'wmode="transparent" ' + 'allowScriptAccess="always" ' + 'allowFullScreen="true" ' + 'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' + 'src="' + options.pluginPath + options.flashName + '" ' + 'flashvars="' + initVars.join('&') + '" ' + 'width="' + width + '" ' + 'height="' + height + '"></embed>'; } break; case 'youtube': var videoId = playback.url.substr(playback.url.lastIndexOf('=')+1); youtubeSettings = { container: container, containerId: container.id, pluginMediaElement: pluginMediaElement, pluginId: pluginid, videoId: videoId, height: height, width: width }; if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) { mejs.YouTubeApi.createFlash(youtubeSettings); } else { mejs.YouTubeApi.enqueueIframe(youtubeSettings); } break; // DEMO Code. Does NOT work. case 'vimeo': //console.log('vimeoid'); pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1); container.innerHTML = '<object width="' + width + '" height="' + height + '">' + '<param name="allowfullscreen" value="true" />' + '<param name="allowscriptaccess" value="always" />' + '<param name="flashvars" value="api=1" />' + '<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' + '</object>'; break; } // hide original element htmlMediaElement.style.display = 'none'; // FYI: options.success will be fired by the MediaPluginBridge return pluginMediaElement; }, updateNative: function(playback, options, autoplay, preload) { var htmlMediaElement = playback.htmlMediaElement, m; // add methods to video object to bring it into parity with Flash Object for (m in mejs.HtmlMediaElement) { htmlMediaElement[m] = mejs.HtmlMediaElement[m]; } /* Chrome now supports preload="none" if (mejs.MediaFeatures.isChrome) { // special case to enforce preload attribute (Chrome doesn't respect this) if (preload === 'none' && !autoplay) { // forces the browser to stop loading (note: fails in IE9) htmlMediaElement.src = ''; htmlMediaElement.load(); htmlMediaElement.canceledPreload = true; htmlMediaElement.addEventListener('play',function() { if (htmlMediaElement.canceledPreload) { htmlMediaElement.src = playback.url; htmlMediaElement.load(); htmlMediaElement.play(); htmlMediaElement.canceledPreload = false; } }, false); // for some reason Chrome forgets how to autoplay sometimes. } else if (autoplay) { htmlMediaElement.load(); htmlMediaElement.play(); } } */ // fire success code options.success(htmlMediaElement, htmlMediaElement); return htmlMediaElement; } }; /* - test on IE (object vs. embed) - determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE) - fullscreen? */ // YouTube Flash and Iframe API mejs.YouTubeApi = { isIframeStarted: false, isIframeLoaded: false, loadIframeApi: function() { if (!this.isIframeStarted) { var tag = document.createElement('script'); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); this.isIframeStarted = true; } }, iframeQueue: [], enqueueIframe: function(yt) { if (this.isLoaded) { this.createIframe(yt); } else { this.loadIframeApi(); this.iframeQueue.push(yt); } }, createIframe: function(settings) { var pluginMediaElement = settings.pluginMediaElement, player = new YT.Player(settings.containerId, { height: settings.height, width: settings.width, videoId: settings.videoId, playerVars: {controls:0}, events: { 'onReady': function() { // hook up iframe object to MEjs settings.pluginMediaElement.pluginApi = player; // init mejs mejs.MediaPluginBridge.initPlugin(settings.pluginId); // create timer setInterval(function() { mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate'); }, 250); }, 'onStateChange': function(e) { mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement); } } }); }, createEvent: function (player, pluginMediaElement, eventName) { var obj = { type: eventName, target: pluginMediaElement }; if (player && player.getDuration) { // time pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime(); pluginMediaElement.duration = obj.duration = player.getDuration(); // state obj.paused = pluginMediaElement.paused; obj.ended = pluginMediaElement.ended; // sound obj.muted = player.isMuted(); obj.volume = player.getVolume() / 100; // progress obj.bytesTotal = player.getVideoBytesTotal(); obj.bufferedBytes = player.getVideoBytesLoaded(); // fake the W3C buffered TimeRange var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration; obj.target.buffered = obj.buffered = { start: function(index) { return 0; }, end: function (index) { return bufferedTime; }, length: 1 }; } // send event up the chain pluginMediaElement.dispatchEvent(obj.type, obj); }, iFrameReady: function() { this.isLoaded = true; this.isIframeLoaded = true; while (this.iframeQueue.length > 0) { var settings = this.iframeQueue.pop(); this.createIframe(settings); } }, // FLASH! flashPlayers: {}, createFlash: function(settings) { this.flashPlayers[settings.pluginId] = settings; /* settings.container.innerHTML = '<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0" ' + 'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' + '<param name="allowScriptAccess" value="always">' + '<param name="wmode" value="transparent">' + '</object>'; */ var specialIEContainer, youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0'; if (mejs.MediaFeatures.isIE) { specialIEContainer = document.createElement('div'); settings.container.appendChild(specialIEContainer); specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' + 'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' + '<param name="movie" value="' + youtubeUrl + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowScriptAccess" value="always" />' + '<param name="allowFullScreen" value="true" />' + '</object>'; } else { settings.container.innerHTML = '<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' + 'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' + '<param name="allowScriptAccess" value="always">' + '<param name="wmode" value="transparent">' + '</object>'; } }, flashReady: function(id) { var settings = this.flashPlayers[id], player = document.getElementById(id), pluginMediaElement = settings.pluginMediaElement; // hook up and return to MediaELementPlayer.success pluginMediaElement.pluginApi = pluginMediaElement.pluginElement = player; mejs.MediaPluginBridge.initPlugin(id); // load the youtube video player.cueVideoById(settings.videoId); var callbackName = settings.containerId + '_callback' window[callbackName] = function(e) { mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement); } player.addEventListener('onStateChange', callbackName); setInterval(function() { mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate'); }, 250); }, handleStateChange: function(youTubeState, player, pluginMediaElement) { switch (youTubeState) { case -1: // not started pluginMediaElement.paused = true; pluginMediaElement.ended = true; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata'); //createYouTubeEvent(player, pluginMediaElement, 'loadeddata'); break; case 0: pluginMediaElement.paused = false; pluginMediaElement.ended = true; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended'); break; case 1: pluginMediaElement.paused = false; pluginMediaElement.ended = false; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play'); mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing'); break; case 2: pluginMediaElement.paused = true; pluginMediaElement.ended = false; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause'); break; case 3: // buffering mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress'); break; case 5: // cued? break; } } } // IFRAME function onYouTubePlayerAPIReady() { mejs.YouTubeApi.iFrameReady(); } // FLASH function onYouTubePlayerReady(id) { mejs.YouTubeApi.flashReady(id); } window.mejs = mejs; window.MediaElement = mejs.MediaElement; /*! * MediaElementPlayer * http://mediaelementjs.com/ * * Creates a controller bar for HTML5 <video> add <audio> tags * using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper) * * Copyright 2010-2012, John Dyer (http://j.hn/) * Dual licensed under the MIT or GPL Version 2 licenses. * */ if (typeof jQuery != 'undefined') { mejs.$ = jQuery; } else if (typeof ender != 'undefined') { mejs.$ = ender; } (function ($) { // default player values mejs.MepDefaults = { // url to poster (to fix iOS 3.x) poster: '', // default if the <video width> is not specified defaultVideoWidth: 480, // default if the <video height> is not specified defaultVideoHeight: 270, // if set, overrides <video width> videoWidth: -1, // if set, overrides <video height> videoHeight: -1, // default if the user doesn't specify defaultAudioWidth: 400, // default if the user doesn't specify defaultAudioHeight: 30, // default amount to move back when back key is pressed defaultSeekBackwardInterval: function(media) { return (media.duration * 0.05); }, // default amount to move forward when forward key is pressed defaultSeekForwardInterval: function(media) { return (media.duration * 0.05); }, // width of audio player audioWidth: -1, // height of audio player audioHeight: -1, // initial volume when the player starts (overrided by user cookie) startVolume: 0.8, // useful for <audio> player loops loop: false, // resize to media dimensions enableAutosize: true, // forces the hour marker (##:00:00) alwaysShowHours: false, // show framecount in timecode (##:00:00:00) showTimecodeFrameCount: false, // used when showTimecodeFrameCount is set to true framesPerSecond: 25, // automatically calculate the width of the progress bar based on the sizes of other elements autosizeProgress : true, // Hide controls when playing and mouse is not over the video alwaysShowControls: false, // force iPad's native controls iPadUseNativeControls: false, // force iPhone's native controls iPhoneUseNativeControls: false, // force Android's native controls AndroidUseNativeControls: false, // features to show features: ['playpause','current','progress','duration','tracks','volume','fullscreen'], // only for dynamic isVideo: true, // turns keyboard support on and off for this instance enableKeyboard: true, // whenthis player starts, it will pause other players pauseOtherPlayers: true, // array of keyboard actions such as play pause keyActions: [ { keys: [ 32, // SPACE 179 // GOOGLE play/pause button ], action: function(player, media) { if (media.paused || media.ended) { media.play(); } else { media.pause(); } } }, { keys: [38], // UP action: function(player, media) { var newVolume = Math.min(media.volume + 0.1, 1); media.setVolume(newVolume); } }, { keys: [40], // DOWN action: function(player, media) { var newVolume = Math.max(media.volume - 0.1, 0); media.setVolume(newVolume); } }, { keys: [ 37, // LEFT 227 // Google TV rewind ], action: function(player, media) { if (!isNaN(media.duration) && media.duration > 0) { if (player.isVideo) { player.showControls(); player.startControlsTimer(); } // 5% var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0); media.setCurrentTime(newTime); } } }, { keys: [ 39, // RIGHT 228 // Google TV forward ], action: function(player, media) { if (!isNaN(media.duration) && media.duration > 0) { if (player.isVideo) { player.showControls(); player.startControlsTimer(); } // 5% var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration); media.setCurrentTime(newTime); } } }, { keys: [70], // f action: function(player, media) { if (typeof player.enterFullScreen != 'undefined') { if (player.isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } } } } ] }; mejs.mepIndex = 0; mejs.players = []; // wraps a MediaElement object in player controls mejs.MediaElementPlayer = function(node, o) { // enforce object, even without "new" (via John Resig) if ( !(this instanceof mejs.MediaElementPlayer) ) { return new mejs.MediaElementPlayer(node, o); } var t = this; // these will be reset after the MediaElement.success fires t.$media = t.$node = $(node); t.node = t.media = t.$media[0]; // check for existing player if (typeof t.node.player != 'undefined') { return t.node.player; } else { // attach player to DOM node for reference t.node.player = t; } // try to get options from data-mejsoptions if (typeof o == 'undefined') { o = t.$node.data('mejsoptions'); } // extend default options t.options = $.extend({},mejs.MepDefaults,o); // add to player array (for focus events) mejs.players.push(t); // start up t.init(); return t; }; // actual player mejs.MediaElementPlayer.prototype = { hasFocus: false, controlsAreVisible: true, init: function() { var t = this, mf = mejs.MediaFeatures, // options for MediaElement (shim) meOptions = $.extend(true, {}, t.options, { success: function(media, domNode) { t.meReady(media, domNode); }, error: function(e) { t.handleError(e);} }), tagName = t.media.tagName.toLowerCase(); t.isDynamic = (tagName !== 'audio' && tagName !== 'video'); if (t.isDynamic) { // get video from src or href? t.isVideo = t.options.isVideo; } else { t.isVideo = (tagName !== 'audio' && t.options.isVideo); } // use native controls in iPad, iPhone, and Android if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) { // add controls and stop t.$media.attr('controls', 'controls'); // attempt to fix iOS 3 bug //t.$media.removeAttr('poster'); // no Issue found on iOS3 -ttroxell // override Apple's autoplay override for iPads if (mf.isiPad && t.media.getAttribute('autoplay') !== null) { t.media.load(); t.media.play(); } } else if (mf.isAndroid && t.AndroidUseNativeControls) { // leave default player } else { // DESKTOP: use MediaElementPlayer controls // remove native controls t.$media.removeAttr('controls'); // unique ID t.id = 'mep_' + mejs.mepIndex++; // build container t.container = $('<div id="' + t.id + '" class="mejs-container">'+ '<div class="mejs-inner">'+ '<div class="mejs-mediaelement"></div>'+ '<div class="mejs-layers"></div>'+ '<div class="mejs-controls"></div>'+ '<div class="mejs-clear"></div>'+ '</div>' + '</div>') .addClass(t.$media[0].className) .insertBefore(t.$media); // add classes for user and content t.container.addClass( (mf.isAndroid ? 'mejs-android ' : '') + (mf.isiOS ? 'mejs-ios ' : '') + (mf.isiPad ? 'mejs-ipad ' : '') + (mf.isiPhone ? 'mejs-iphone ' : '') + (t.isVideo ? 'mejs-video ' : 'mejs-audio ') ); // move the <video/video> tag into the right spot if (mf.isiOS) { // sadly, you can't move nodes in iOS, so we have to destroy and recreate it! var $newMedia = t.$media.clone(); t.container.find('.mejs-mediaelement').append($newMedia); t.$media.remove(); t.$node = t.$media = $newMedia; t.node = t.media = $newMedia[0] } else { // normal way of moving it into place (doesn't work on iOS) t.container.find('.mejs-mediaelement').append(t.$media); } // find parts t.controls = t.container.find('.mejs-controls'); t.layers = t.container.find('.mejs-layers'); // determine the size /* size priority: (1) videoWidth (forced), (2) style="width;height;" (3) width attribute, (4) defaultVideoWidth (for unspecified cases) */ var tagType = (t.isVideo ? 'video' : 'audio'), capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1); if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) { t.width = t.options[tagType + 'Width']; } else if (t.media.style.width !== '' && t.media.style.width !== null) { t.width = t.media.style.width; } else if (t.media.getAttribute('width') !== null) { t.width = t.$media.attr('width'); } else { t.width = t.options['default' + capsTagName + 'Width']; } if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) { t.height = t.options[tagType + 'Height']; } else if (t.media.style.height !== '' && t.media.style.height !== null) { t.height = t.media.style.height; } else if (t.$media[0].getAttribute('height') !== null) { t.height = t.$media.attr('height'); } else { t.height = t.options['default' + capsTagName + 'Height']; } // set the size, while we wait for the plugins to load below t.setPlayerSize(t.width, t.height); // create MediaElementShim meOptions.pluginWidth = t.height; meOptions.pluginHeight = t.width; } // create MediaElement shim mejs.MediaElement(t.$media[0], meOptions); }, showControls: function(doAnimation) { var t = this; doAnimation = typeof doAnimation == 'undefined' || doAnimation; if (t.controlsAreVisible) return; if (doAnimation) { t.controls .css('visibility','visible') .stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;}); // any additional controls people might add and want to hide t.container.find('.mejs-control') .css('visibility','visible') .stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;}); } else { t.controls .css('visibility','visible') .css('display','block'); // any additional controls people might add and want to hide t.container.find('.mejs-control') .css('visibility','visible') .css('display','block'); t.controlsAreVisible = true; } t.setControlsSize(); }, hideControls: function(doAnimation) { var t = this; doAnimation = typeof doAnimation == 'undefined' || doAnimation; if (!t.controlsAreVisible) return; if (doAnimation) { // fade out main controls t.controls.stop(true, true).fadeOut(200, function() { $(this) .css('visibility','hidden') .css('display','block'); t.controlsAreVisible = false; }); // any additional controls people might add and want to hide t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() { $(this) .css('visibility','hidden') .css('display','block'); }); } else { // hide main controls t.controls .css('visibility','hidden') .css('display','block'); // hide others t.container.find('.mejs-control') .css('visibility','hidden') .css('display','block'); t.controlsAreVisible = false; } }, controlsTimer: null, startControlsTimer: function(timeout) { var t = this; timeout = typeof timeout != 'undefined' ? timeout : 1500; t.killControlsTimer('start'); t.controlsTimer = setTimeout(function() { //console.log('timer fired'); t.hideControls(); t.killControlsTimer('hide'); }, timeout); }, killControlsTimer: function(src) { var t = this; if (t.controlsTimer !== null) { clearTimeout(t.controlsTimer); delete t.controlsTimer; t.controlsTimer = null; } }, controlsEnabled: true, disableControls: function() { var t= this; t.killControlsTimer(); t.hideControls(false); this.controlsEnabled = false; }, enableControls: function() { var t= this; t.showControls(false); t.controlsEnabled = true; }, // Sets up all controls and events meReady: function(media, domNode) { var t = this, mf = mejs.MediaFeatures, autoplayAttr = domNode.getAttribute('autoplay'), autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'), featureIndex, feature; // make sure it can't create itself again if a plugin reloads if (t.created) return; else t.created = true; t.media = media; t.domNode = domNode; if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) { // two built in features t.buildposter(t, t.controls, t.layers, t.media); t.buildkeyboard(t, t.controls, t.layers, t.media); t.buildoverlays(t, t.controls, t.layers, t.media); // grab for use by features t.findTracks(); // add user-defined features/controls for (featureIndex in t.options.features) { feature = t.options.features[featureIndex]; if (t['build' + feature]) { try { t['build' + feature](t, t.controls, t.layers, t.media); } catch (e) { // TODO: report control error //throw e; //console.log('error building ' + feature); //console.log(e); } } } t.container.trigger('controlsready'); // reset all layers and controls t.setPlayerSize(t.width, t.height); t.setControlsSize(); // controls fade if (t.isVideo) { if (mejs.MediaFeatures.hasTouch) { // for touch devices (iOS, Android) // show/hide without animation on touch t.$media.bind('touchstart', function() { // toggle controls if (t.controlsAreVisible) { t.hideControls(false); } else { if (t.controlsEnabled) { t.showControls(false); } } }); } else { // click controls var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement); // click to play/pause clickElement.click(function() { if (media.paused) { media.play(); } else { media.pause(); } }); // show/hide controls t.container .bind('mouseenter mouseover', function () { if (t.controlsEnabled) { if (!t.options.alwaysShowControls) { t.killControlsTimer('enter'); t.showControls(); t.startControlsTimer(2500); } } }) .bind('mousemove', function() { if (t.controlsEnabled) { if (!t.controlsAreVisible) { t.showControls(); } //t.killControlsTimer('move'); if (!t.options.alwaysShowControls) { t.startControlsTimer(2500); } } }) .bind('mouseleave', function () { if (t.controlsEnabled) { if (!t.media.paused && !t.options.alwaysShowControls) { t.startControlsTimer(1000); } } }); } // check for autoplay if (autoplay && !t.options.alwaysShowControls) { t.hideControls(); } // resizer if (t.options.enableAutosize) { t.media.addEventListener('loadedmetadata', function(e) { // if the <video height> was not set and the options.videoHeight was not set // then resize to the real dimensions if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) { t.setPlayerSize(e.target.videoWidth, e.target.videoHeight); t.setControlsSize(); t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight); } }, false); } } // EVENTS // FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them) media.addEventListener('play', function() { // go through all other players for (var i=0, il=mejs.players.length; i<il; i++) { var p = mejs.players[i]; if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) { p.pause(); } p.hasFocus = false; } t.hasFocus = true; },false); // ended for all t.media.addEventListener('ended', function (e) { try{ t.media.setCurrentTime(0); } catch (exp) { } t.media.pause(); if (t.setProgressRail) t.setProgressRail(); if (t.setCurrentRail) t.setCurrentRail(); if (t.options.loop) { t.media.play(); } else if (!t.options.alwaysShowControls && t.controlsEnabled) { t.showControls(); } }, false); // resize on the first play t.media.addEventListener('loadedmetadata', function(e) { if (t.updateDuration) { t.updateDuration(); } if (t.updateCurrent) { t.updateCurrent(); } if (!t.isFullScreen) { t.setPlayerSize(t.width, t.height); t.setControlsSize(); } }, false); // webkit has trouble doing this without a delay setTimeout(function () { t.setPlayerSize(t.width, t.height); t.setControlsSize(); }, 50); // adjust controls whenever window sizes (used to be in fullscreen only) $(window).resize(function() { // don't resize for fullscreen mode if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) { t.setPlayerSize(t.width, t.height); } // always adjust controls t.setControlsSize(); }); // TEMP: needs to be moved somewhere else if (t.media.pluginType == 'youtube') { t.container.find('.mejs-overlay-play').hide(); } } // force autoplay for HTML5 if (autoplay && media.pluginType == 'native') { media.load(); media.play(); } if (t.options.success) { if (typeof t.options.success == 'string') { window[t.options.success](t.media, t.domNode, t); } else { t.options.success(t.media, t.domNode, t); } } }, handleError: function(e) { var t = this; t.controls.hide(); // Tell user that the file cannot be played if (t.options.error) { t.options.error(e); } }, setPlayerSize: function(width,height) { var t = this; if (typeof width != 'undefined') t.width = width; if (typeof height != 'undefined') t.height = height; // detect 100% mode if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') { // do we have the native dimensions yet? var nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth, nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight, parentWidth = t.container.parent().width(), newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10); if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) { parentWidth = $(window).width(); newHeight = $(window).height(); } if ( newHeight != 0 ) { // set outer container size t.container .width(parentWidth) .height(newHeight); // set native <video> t.$media .width('100%') .height('100%'); // set shims t.container.find('object, embed, iframe') .width('100%') .height('100%'); // if shim is ready, send the size to the embeded plugin if (t.isVideo) { if (t.media.setVideoSize) { t.media.setVideoSize(parentWidth, newHeight); } } // set the layers t.layers.children('.mejs-layer') .width('100%') .height('100%'); } } else { t.container .width(t.width) .height(t.height); t.layers.children('.mejs-layer') .width(t.width) .height(t.height); } }, setControlsSize: function() { var t = this, usedWidth = 0, railWidth = 0, rail = t.controls.find('.mejs-time-rail'), total = t.controls.find('.mejs-time-total'), current = t.controls.find('.mejs-time-current'), loaded = t.controls.find('.mejs-time-loaded'), others = rail.siblings(); // allow the size to come from custom CSS if (t.options && !t.options.autosizeProgress) { // Also, frontends devs can be more flexible // due the opportunity of absolute positioning. railWidth = parseInt(rail.css('width')); } // attempt to autosize if (railWidth === 0 || !railWidth) { // find the size of all the other controls besides the rail others.each(function() { if ($(this).css('position') != 'absolute') { usedWidth += $(this).outerWidth(true); } }); // fit the rail into the remaining space railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width()); } // outer area rail.width(railWidth); // dark space total.width(railWidth - (total.outerWidth(true) - total.width())); if (t.setProgressRail) t.setProgressRail(); if (t.setCurrentRail) t.setCurrentRail(); }, buildposter: function(player, controls, layers, media) { var t = this, poster = $('<div class="mejs-poster mejs-layer">' + '</div>') .appendTo(layers), posterUrl = player.$media.attr('poster'); // prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster) if (player.options.poster !== '') { posterUrl = player.options.poster; } // second, try the real poster if (posterUrl !== '' && posterUrl != null) { t.setPoster(posterUrl); } else { poster.hide(); } media.addEventListener('play',function() { poster.hide(); }, false); }, setPoster: function(url) { var t = this, posterDiv = t.container.find('.mejs-poster'), posterImg = posterDiv.find('img'); if (posterImg.length == 0) { posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv); } posterImg.attr('src', url); }, buildoverlays: function(player, controls, layers, media) { if (!player.isVideo) return; var loading = $('<div class="mejs-overlay mejs-layer">'+ '<div class="mejs-overlay-loading"><span></span></div>'+ '</div>') .hide() // start out hidden .appendTo(layers), error = $('<div class="mejs-overlay mejs-layer">'+ '<div class="mejs-overlay-error"></div>'+ '</div>') .hide() // start out hidden .appendTo(layers), // this needs to come last so it's on top bigPlay = $('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+ '<div class="mejs-overlay-button"></div>'+ '</div>') .appendTo(layers) .click(function() { if (media.paused) { media.play(); } else { media.pause(); } }); /* if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) { bigPlay.remove(); loading.remove(); } */ // show/hide big play button media.addEventListener('play',function() { bigPlay.hide(); loading.hide(); controls.find('.mejs-time-buffering').hide(); error.hide(); }, false); media.addEventListener('playing', function() { bigPlay.hide(); loading.hide(); controls.find('.mejs-time-buffering').hide(); error.hide(); }, false); media.addEventListener('seeking', function() { loading.show(); controls.find('.mejs-time-buffering').show(); }, false); media.addEventListener('seeked', function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); }, false); media.addEventListener('pause',function() { if (!mejs.MediaFeatures.isiPhone) { bigPlay.show(); } }, false); media.addEventListener('waiting', function() { loading.show(); controls.find('.mejs-time-buffering').show(); }, false); // show/hide loading media.addEventListener('loadeddata',function() { // for some reason Chrome is firing this event //if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none') // return; loading.show(); controls.find('.mejs-time-buffering').show(); }, false); media.addEventListener('canplay',function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); }, false); // error handling media.addEventListener('error',function() { loading.hide(); controls.find('.mejs-time-buffering').hide(); error.show(); error.find('mejs-overlay-error').html("Error loading this resource"); }, false); }, buildkeyboard: function(player, controls, layers, media) { var t = this; // listen for key presses $(document).keydown(function(e) { if (player.hasFocus && player.options.enableKeyboard) { // find a matching key for (var i=0, il=player.options.keyActions.length; i<il; i++) { var keyAction = player.options.keyActions[i]; for (var j=0, jl=keyAction.keys.length; j<jl; j++) { if (e.keyCode == keyAction.keys[j]) { e.preventDefault(); keyAction.action(player, media, e.keyCode); return false; } } } } return true; }); // check if someone clicked outside a player region, then kill its focus $(document).click(function(event) { if ($(event.target).closest('.mejs-container').length == 0) { player.hasFocus = false; } }); }, findTracks: function() { var t = this, tracktags = t.$media.find('track'); // store for use by plugins t.tracks = []; tracktags.each(function(index, track) { track = $(track); t.tracks.push({ srclang: track.attr('srclang').toLowerCase(), src: track.attr('src'), kind: track.attr('kind'), label: track.attr('label') || '', entries: [], isLoaded: false }); }); }, changeSkin: function(className) { this.container[0].className = 'mejs-container ' + className; this.setPlayerSize(this.width, this.height); this.setControlsSize(); }, play: function() { this.media.play(); }, pause: function() { this.media.pause(); }, load: function() { this.media.load(); }, setMuted: function(muted) { this.media.setMuted(muted); }, setCurrentTime: function(time) { this.media.setCurrentTime(time); }, getCurrentTime: function() { return this.media.currentTime; }, setVolume: function(volume) { this.media.setVolume(volume); }, getVolume: function() { return this.media.volume; }, setSrc: function(src) { this.media.setSrc(src); }, remove: function() { var t = this; if (t.media.pluginType === 'flash') { t.media.remove(); } else if (t.media.pluginType === 'native') { t.$media.prop('controls', true); } // grab video and put it back in place if (!t.isDynamic) { t.$node.insertBefore(t.container) } t.container.remove(); } }; // turn into jQuery plugin if (typeof jQuery != 'undefined') { jQuery.fn.mediaelementplayer = function (options) { return this.each(function () { new mejs.MediaElementPlayer(this, options); }); }; } $(document).ready(function() { // auto enable using JSON attribute $('.mejs-player').mediaelementplayer(); }); // push out to window window.MediaElementPlayer = mejs.MediaElementPlayer; })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { playpauseText: 'Play/Pause' }); // PLAY/pause BUTTON $.extend(MediaElementPlayer.prototype, { buildplaypause: function(player, controls, layers, media) { var t = this, play = $('<div class="mejs-button mejs-playpause-button mejs-play" >' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' + '</div>') .appendTo(controls) .click(function(e) { e.preventDefault(); if (media.paused) { media.play(); } else { media.pause(); } return false; }); media.addEventListener('play',function() { play.removeClass('mejs-play').addClass('mejs-pause'); }, false); media.addEventListener('playing',function() { play.removeClass('mejs-play').addClass('mejs-pause'); }, false); media.addEventListener('pause',function() { play.removeClass('mejs-pause').addClass('mejs-play'); }, false); media.addEventListener('paused',function() { play.removeClass('mejs-pause').addClass('mejs-play'); }, false); } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { stopText: 'Stop' }); // STOP BUTTON $.extend(MediaElementPlayer.prototype, { buildstop: function(player, controls, layers, media) { var t = this, stop = $('<div class="mejs-button mejs-stop-button mejs-stop">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' + '</div>') .appendTo(controls) .click(function() { if (!media.paused) { media.pause(); } if (media.currentTime > 0) { media.setCurrentTime(0); controls.find('.mejs-time-current').width('0px'); controls.find('.mejs-time-handle').css('left', '0px'); controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) ); controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) ); layers.find('.mejs-poster').show(); } }); } }); })(mejs.$); (function($) { // progress/loaded bar $.extend(MediaElementPlayer.prototype, { buildprogress: function(player, controls, layers, media) { $('<div class="mejs-time-rail">'+ '<span class="mejs-time-total">'+ '<span class="mejs-time-buffering"></span>'+ '<span class="mejs-time-loaded"></span>'+ '<span class="mejs-time-current"></span>'+ '<span class="mejs-time-handle"></span>'+ '<span class="mejs-time-float">' + '<span class="mejs-time-float-current">00:00</span>' + '<span class="mejs-time-float-corner"></span>' + '</span>'+ '</span>'+ '</div>') .appendTo(controls); controls.find('.mejs-time-buffering').hide(); var t = this, total = controls.find('.mejs-time-total'), loaded = controls.find('.mejs-time-loaded'), current = controls.find('.mejs-time-current'), handle = controls.find('.mejs-time-handle'), timefloat = controls.find('.mejs-time-float'), timefloatcurrent = controls.find('.mejs-time-float-current'), handleMouseMove = function (e) { // mouse position relative to the object var x = e.pageX, offset = total.offset(), width = total.outerWidth(), percentage = 0, newTime = 0, pos = x - offset.left; if (x > offset.left && x <= width + offset.left && media.duration) { percentage = ((x - offset.left) / width); newTime = (percentage <= 0.02) ? 0 : percentage * media.duration; // seek to where the mouse is if (mouseIsDown) { media.setCurrentTime(newTime); } // position floating time box if (!mejs.MediaFeatures.hasTouch) { timefloat.css('left', pos); timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) ); timefloat.show(); } } }, mouseIsDown = false, mouseIsOver = false; // handle clicks //controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove); total .bind('mousedown', function (e) { // only handle left clicks if (e.which === 1) { mouseIsDown = true; handleMouseMove(e); $(document) .bind('mousemove.dur', function(e) { handleMouseMove(e); }) .bind('mouseup.dur', function (e) { mouseIsDown = false; timefloat.hide(); $(document).unbind('.dur'); }); return false; } }) .bind('mouseenter', function(e) { mouseIsOver = true; $(document).bind('mousemove.dur', function(e) { handleMouseMove(e); }); if (!mejs.MediaFeatures.hasTouch) { timefloat.show(); } }) .bind('mouseleave',function(e) { mouseIsOver = false; if (!mouseIsDown) { $(document).unbind('.dur'); timefloat.hide(); } }); // loading media.addEventListener('progress', function (e) { player.setProgressRail(e); player.setCurrentRail(e); }, false); // current time media.addEventListener('timeupdate', function(e) { player.setProgressRail(e); player.setCurrentRail(e); }, false); // store for later use t.loaded = loaded; t.total = total; t.current = current; t.handle = handle; }, setProgressRail: function(e) { var t = this, target = (e != undefined) ? e.target : t.media, percent = null; // newest HTML5 spec has buffered array (FF4, Webkit) if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) { // TODO: account for a real array with multiple values (only Firefox 4 has this so far) percent = target.buffered.end(0) / target.duration; } // Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end() // to be anything other than 0. If the byte count is available we use this instead. // Browsers that support the else if do not seem to have the bufferedBytes value and // should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8. else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) { percent = target.bufferedBytes / target.bytesTotal; } // Firefox 3 with an Ogg file seems to go this way else if (e && e.lengthComputable && e.total != 0) { percent = e.loaded/e.total; } // finally update the progress bar if (percent !== null) { percent = Math.min(1, Math.max(0, percent)); // update loaded bar if (t.loaded && t.total) { t.loaded.width(t.total.width() * percent); } } }, setCurrentRail: function() { var t = this; if (t.media.currentTime != undefined && t.media.duration) { // update bar and handle if (t.total && t.handle) { var newWidth = t.total.width() * t.media.currentTime / t.media.duration, handlePos = newWidth - (t.handle.outerWidth(true) / 2); t.current.width(newWidth); t.handle.css('left', handlePos); } } } }); })(mejs.$); (function($) { // options $.extend(mejs.MepDefaults, { duration: -1, timeAndDurationSeparator: ' <span> | </span> ' }); // current and duration 00:00 / 00:00 $.extend(MediaElementPlayer.prototype, { buildcurrent: function(player, controls, layers, media) { var t = this; $('<div class="mejs-time">'+ '<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+ '</div>') .appendTo(controls); t.currenttime = t.controls.find('.mejs-currenttime'); media.addEventListener('timeupdate',function() { player.updateCurrent(); }, false); }, buildduration: function(player, controls, layers, media) { var t = this; if (controls.children().last().find('.mejs-currenttime').length > 0) { $(t.options.timeAndDurationSeparator + '<span class="mejs-duration">' + (t.options.duration > 0 ? mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) : ((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')) ) + '</span>') .appendTo(controls.find('.mejs-time')); } else { // add class to current time controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container'); $('<div class="mejs-time mejs-duration-container">'+ '<span class="mejs-duration">' + (t.options.duration > 0 ? mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) : ((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00')) ) + '</span>' + '</div>') .appendTo(controls); } t.durationD = t.controls.find('.mejs-duration'); media.addEventListener('timeupdate',function() { player.updateDuration(); }, false); }, updateCurrent: function() { var t = this; if (t.currenttime) { t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25)); } }, updateDuration: function() { var t = this; if (t.media.duration && t.durationD) { t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25)); } } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { muteText: 'Mute Toggle', hideVolumeOnTouchDevices: true, audioVolume: 'horizontal', videoVolume: 'vertical' }); $.extend(MediaElementPlayer.prototype, { buildvolume: function(player, controls, layers, media) { // Android and iOS don't support volume controls if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices) return; var t = this, mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume, mute = (mode == 'horizontal') ? // horizontal version $('<div class="mejs-button mejs-volume-button mejs-mute">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+ '</div>' + '<div class="mejs-horizontal-volume-slider">'+ // outer background '<div class="mejs-horizontal-volume-total"></div>'+ // line background '<div class="mejs-horizontal-volume-current"></div>'+ // current volume '<div class="mejs-horizontal-volume-handle"></div>'+ // handle '</div>' ) .appendTo(controls) : // vertical version $('<div class="mejs-button mejs-volume-button mejs-mute">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+ '<div class="mejs-volume-slider">'+ // outer background '<div class="mejs-volume-total"></div>'+ // line background '<div class="mejs-volume-current"></div>'+ // current volume '<div class="mejs-volume-handle"></div>'+ // handle '</div>'+ '</div>') .appendTo(controls), volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'), volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'), volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'), volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'), positionVolumeHandle = function(volume, secondTry) { if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') { volumeSlider.show(); positionVolumeHandle(volume, true); volumeSlider.hide() return; } // correct to 0-1 volume = Math.max(0,volume); volume = Math.min(volume,1); // ajust mute button style if (volume == 0) { mute.removeClass('mejs-mute').addClass('mejs-unmute'); } else { mute.removeClass('mejs-unmute').addClass('mejs-mute'); } // position slider if (mode == 'vertical') { var // height of the full size volume slider background totalHeight = volumeTotal.height(), // top/left of full size volume slider background totalPosition = volumeTotal.position(), // the new top position based on the current volume // 70% volume on 100px height == top:30px newTop = totalHeight - (totalHeight * volume); // handle volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2)); // show the current visibility volumeCurrent.height(totalHeight - newTop ); volumeCurrent.css('top', totalPosition.top + newTop); } else { var // height of the full size volume slider background totalWidth = volumeTotal.width(), // top/left of full size volume slider background totalPosition = volumeTotal.position(), // the new left position based on the current volume newLeft = totalWidth * volume; // handle volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2)); // rezize the current part of the volume bar volumeCurrent.width( newLeft ); } }, handleVolumeMove = function(e) { var volume = null, totalOffset = volumeTotal.offset(); // calculate the new volume based on the moust position if (mode == 'vertical') { var railHeight = volumeTotal.height(), totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10), newY = e.pageY - totalOffset.top; volume = (railHeight - newY) / railHeight; // the controls just hide themselves (usually when mouse moves too far up) if (totalOffset.top == 0 || totalOffset.left == 0) return; } else { var railWidth = volumeTotal.width(), newX = e.pageX - totalOffset.left; volume = newX / railWidth; } // ensure the volume isn't outside 0-1 volume = Math.max(0,volume); volume = Math.min(volume,1); // position the slider and handle positionVolumeHandle(volume); // set the media object (this will trigger the volumechanged event) if (volume == 0) { media.setMuted(true); } else { media.setMuted(false); } media.setVolume(volume); }, mouseIsDown = false, mouseIsOver = false; // SLIDER mute .hover(function() { volumeSlider.show(); mouseIsOver = true; }, function() { mouseIsOver = false; if (!mouseIsDown && mode == 'vertical') { volumeSlider.hide(); } }); volumeSlider .bind('mouseover', function() { mouseIsOver = true; }) .bind('mousedown', function (e) { handleVolumeMove(e); $(document) .bind('mousemove.vol', function(e) { handleVolumeMove(e); }) .bind('mouseup.vol', function () { mouseIsDown = false; $(document).unbind('.vol'); if (!mouseIsOver && mode == 'vertical') { volumeSlider.hide(); } }); mouseIsDown = true; return false; }); // MUTE button mute.find('button').click(function() { media.setMuted( !media.muted ); }); // listen for volume change events from other sources media.addEventListener('volumechange', function(e) { if (!mouseIsDown) { if (media.muted) { positionVolumeHandle(0); mute.removeClass('mejs-mute').addClass('mejs-unmute'); } else { positionVolumeHandle(media.volume); mute.removeClass('mejs-unmute').addClass('mejs-mute'); } } }, false); if (t.container.is(':visible')) { // set initial volume positionVolumeHandle(player.options.startVolume); // shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements if (media.pluginType === 'native') { media.setVolume(player.options.startVolume); } } } }); })(mejs.$); (function($) { $.extend(mejs.MepDefaults, { usePluginFullScreen: true, newWindowCallback: function() { return '';}, fullscreenText: 'Fullscreen' }); $.extend(MediaElementPlayer.prototype, { isFullScreen: false, isNativeFullScreen: false, docStyleOverflow: null, isInIframe: false, buildfullscreen: function(player, controls, layers, media) { if (!player.isVideo) return; player.isInIframe = (window.location != window.parent.location); // native events if (mejs.MediaFeatures.hasTrueNativeFullScreen) { // chrome doesn't alays fire this in an iframe var target = null; if (mejs.MediaFeatures.hasMozNativeFullScreen) { target = $(document); } else { target = player.container; } target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) { if (mejs.MediaFeatures.isFullScreen()) { player.isNativeFullScreen = true; // reset the controls once we are fully in full screen player.setControlsSize(); } else { player.isNativeFullScreen = false; // when a user presses ESC // make sure to put the player back into place player.exitFullScreen(); } }); } var t = this, normalHeight = 0, normalWidth = 0, container = player.container, fullscreenBtn = $('<div class="mejs-button mejs-fullscreen-button">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' + '</div>') .appendTo(controls); if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) { fullscreenBtn.click(function() { var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen; if (isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } }); } else { var hideTimeout = null, supportsPointerEvents = (function() { // TAKEN FROM MODERNIZR var element = document.createElement('x'), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if(!('pointerEvents' in element.style)){ return false; } element.style.pointerEvents = 'auto'; element.style.pointerEvents = 'x'; documentElement.appendChild(element); supports = getComputedStyle && getComputedStyle(element, '').pointerEvents === 'auto'; documentElement.removeChild(element); return !!supports; })(); //console.log('supportsPointerEvents', supportsPointerEvents); if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :( // allows clicking through the fullscreen button and controls down directly to Flash /* When a user puts his mouse over the fullscreen button, the controls are disabled So we put a div over the video and another one on iether side of the fullscreen button that caputre mouse movement and restore the controls once the mouse moves outside of the fullscreen button */ var fullscreenIsDisabled = false, restoreControls = function() { if (fullscreenIsDisabled) { // hide the hovers videoHoverDiv.hide(); controlsLeftHoverDiv.hide(); controlsRightHoverDiv.hide(); // restore the control bar fullscreenBtn.css('pointer-events', ''); t.controls.css('pointer-events', ''); // store for later fullscreenIsDisabled = false; } }, videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls), positionHoverDivs = function() { var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'}; videoHoverDiv.css(style); controlsLeftHoverDiv.css(style); controlsRightHoverDiv.css(style); // over video, but not controls videoHoverDiv .width( t.container.width() ) .height( t.container.height() - t.controls.height() ); // over controls, but not the fullscreen button var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left; fullScreenBtnWidth = fullscreenBtn.outerWidth(true); controlsLeftHoverDiv .width( fullScreenBtnOffset ) .height( t.controls.height() ) .css({top: t.container.height() - t.controls.height()}); // after the fullscreen button controlsRightHoverDiv .width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth ) .height( t.controls.height() ) .css({top: t.container.height() - t.controls.height(), left: fullScreenBtnOffset + fullScreenBtnWidth}); }; $(document).resize(function() { positionHoverDivs(); }); // on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash fullscreenBtn .mouseover(function() { if (!t.isFullScreen) { var buttonPos = fullscreenBtn.offset(), containerPos = player.container.offset(); // move the button in Flash into place media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false); // allows click through fullscreenBtn.css('pointer-events', 'none'); t.controls.css('pointer-events', 'none'); // show the divs that will restore things videoHoverDiv.show(); controlsRightHoverDiv.show(); controlsLeftHoverDiv.show(); positionHoverDivs(); fullscreenIsDisabled = true; } }); // restore controls anytime the user enters or leaves fullscreen media.addEventListener('fullscreenchange', function(e) { restoreControls(); }); // the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events // so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button /* $(document).mousemove(function(e) { // if the mouse is anywhere but the fullsceen button, then restore it all if (fullscreenIsDisabled) { var fullscreenBtnPos = fullscreenBtn.offset(); if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) || e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true) ) { fullscreenBtn.css('pointer-events', ''); t.controls.css('pointer-events', ''); fullscreenIsDisabled = false; } } }); */ } else { // the hover state will show the fullscreen button in Flash to hover up and click fullscreenBtn .mouseover(function() { if (hideTimeout !== null) { clearTimeout(hideTimeout); delete hideTimeout; } var buttonPos = fullscreenBtn.offset(), containerPos = player.container.offset(); media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true); }) .mouseout(function() { if (hideTimeout !== null) { clearTimeout(hideTimeout); delete hideTimeout; } hideTimeout = setTimeout(function() { media.hideFullscreenButton(); }, 1500); }); } } player.fullscreenBtn = fullscreenBtn; $(document).bind('keydown',function (e) { if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) { player.exitFullScreen(); } }); }, enterFullScreen: function() { var t = this; // firefox+flash can't adjust plugin sizes without resetting :( if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) { //t.media.setFullscreen(true); //player.isFullScreen = true; return; } // store overflow docStyleOverflow = document.documentElement.style.overflow; // set it to not show scroll bars so 100% will work document.documentElement.style.overflow = 'hidden'; // store sizing normalHeight = t.container.height(); normalWidth = t.container.width(); // attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now) if (t.media.pluginType === 'native') { if (mejs.MediaFeatures.hasTrueNativeFullScreen) { mejs.MediaFeatures.requestFullScreen(t.container[0]); //return; if (t.isInIframe) { // sometimes exiting from fullscreen doesn't work // notably in Chrome <iframe>. Fixed in version 17 setTimeout(function checkFullscreen() { if (t.isNativeFullScreen) { // check if the video is suddenly not really fullscreen if ($(window).width() !== screen.width) { // manually exit t.exitFullScreen(); } else { // test again setTimeout(checkFullscreen, 500); } } }, 500); } } else if (mejs.MediaFeatures.hasSemiNativeFullScreen) { t.media.webkitEnterFullscreen(); return; } } // check for iframe launch if (t.isInIframe) { var url = t.options.newWindowCallback(this); if (url !== '') { // launch immediately if (!mejs.MediaFeatures.hasTrueNativeFullScreen) { t.pause(); window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no'); return; } else { setTimeout(function() { if (!t.isNativeFullScreen) { t.pause(); window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no'); } }, 250); } } } // full window code // make full size t.container .addClass('mejs-container-fullscreen') .width('100%') .height('100%'); //.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000}); // Only needed for safari 5.1 native full screen, can cause display issues elsewhere // Actually, it seems to be needed for IE8, too //if (mejs.MediaFeatures.hasTrueNativeFullScreen) { setTimeout(function() { t.container.css({width: '100%', height: '100%'}); t.setControlsSize(); }, 500); //} if (t.pluginType === 'native') { t.$media .width('100%') .height('100%'); } else { t.container.find('object, embed, iframe') .width('100%') .height('100%'); //if (!mejs.MediaFeatures.hasTrueNativeFullScreen) { t.media.setVideoSize($(window).width(),$(window).height()); //} } t.layers.children('div') .width('100%') .height('100%'); if (t.fullscreenBtn) { t.fullscreenBtn .removeClass('mejs-fullscreen') .addClass('mejs-unfullscreen'); } t.setControlsSize(); t.isFullScreen = true; }, exitFullScreen: function() { var t = this; // firefox can't adjust plugins if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) { t.media.setFullscreen(false); //player.isFullScreen = false; return; } // come outo of native fullscreen if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) { mejs.MediaFeatures.cancelFullScreen(); } // restore scroll bars to document document.documentElement.style.overflow = docStyleOverflow; t.container .removeClass('mejs-container-fullscreen') .width(normalWidth) .height(normalHeight); //.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1}); if (t.pluginType === 'native') { t.$media .width(normalWidth) .height(normalHeight); } else { t.container.find('object embed') .width(normalWidth) .height(normalHeight); t.media.setVideoSize(normalWidth, normalHeight); } t.layers.children('div') .width(normalWidth) .height(normalHeight); t.fullscreenBtn .removeClass('mejs-unfullscreen') .addClass('mejs-fullscreen'); t.setControlsSize(); t.isFullScreen = false; } }); })(mejs.$); (function($) { // add extra default options $.extend(mejs.MepDefaults, { // this will automatically turn on a <track> startLanguage: '', tracksText: 'Captions/Subtitles' }); $.extend(MediaElementPlayer.prototype, { hasChapters: false, buildtracks: function(player, controls, layers, media) { if (!player.isVideo) return; if (player.tracks.length == 0) return; var t= this, i, options = ''; player.chapters = $('<div class="mejs-chapters mejs-layer"></div>') .prependTo(layers).hide(); player.captions = $('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>') .prependTo(layers).hide(); player.captionsText = player.captions.find('.mejs-captions-text'); player.captionsButton = $('<div class="mejs-button mejs-captions-button">'+ '<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+ '<div class="mejs-captions-selector">'+ '<ul>'+ '<li>'+ '<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' + '<label for="' + player.id + '_captions_none">None</label>'+ '</li>' + '</ul>'+ '</div>'+ '</div>') .appendTo(controls) // hover .hover(function() { $(this).find('.mejs-captions-selector').css('visibility','visible'); }, function() { $(this).find('.mejs-captions-selector').css('visibility','hidden'); }) // handle clicks to the language radio buttons .delegate('input[type=radio]','click',function() { lang = this.value; if (lang == 'none') { player.selectedTrack = null; } else { for (i=0; i<player.tracks.length; i++) { if (player.tracks[i].srclang == lang) { player.selectedTrack = player.tracks[i]; player.captions.attr('lang', player.selectedTrack.srclang); player.displayCaptions(); break; } } } }); //.bind('mouseenter', function() { // player.captionsButton.find('.mejs-captions-selector').css('visibility','visible') //}); if (!player.options.alwaysShowControls) { // move with controls player.container .bind('mouseenter', function () { // push captions above controls player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover'); }) .bind('mouseleave', function () { if (!media.paused) { // move back to normal place player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover'); } }); } else { player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover'); } player.trackToLoad = -1; player.selectedTrack = null; player.isLoadingTrack = false; // add to list for (i=0; i<player.tracks.length; i++) { if (player.tracks[i].kind == 'subtitles') { player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label); } } player.loadNextTrack(); media.addEventListener('timeupdate',function(e) { player.displayCaptions(); }, false); media.addEventListener('loadedmetadata', function(e) { player.displayChapters(); }, false); player.container.hover( function () { // chapters if (player.hasChapters) { player.chapters.css('visibility','visible'); player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight()); } }, function () { if (player.hasChapters && !media.paused) { player.chapters.fadeOut(200, function() { $(this).css('visibility','hidden'); $(this).css('display','block'); }); } }); // check for autoplay if (player.node.getAttribute('autoplay') !== null) { player.chapters.css('visibility','hidden'); } }, loadNextTrack: function() { var t = this; t.trackToLoad++; if (t.trackToLoad < t.tracks.length) { t.isLoadingTrack = true; t.loadTrack(t.trackToLoad); } else { // add done? t.isLoadingTrack = false; } }, loadTrack: function(index){ var t = this, track = t.tracks[index], after = function() { track.isLoaded = true; // create button //t.addTrackButton(track.srclang); t.enableTrackButton(track.srclang, track.label); t.loadNextTrack(); }; $.ajax({ url: track.src, dataType: "text", success: function(d) { // parse the loaded file if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) { track.entries = mejs.TrackFormatParser.dfxp.parse(d); } else { track.entries = mejs.TrackFormatParser.webvvt.parse(d); } after(); if (track.kind == 'chapters' && t.media.duration > 0) { t.drawChapters(track); } }, error: function() { t.loadNextTrack(); } }); }, enableTrackButton: function(lang, label) { var t = this; if (label === '') { label = mejs.language.codes[lang] || lang; } t.captionsButton .find('input[value=' + lang + ']') .prop('disabled',false) .siblings('label') .html( label ); // auto select if (t.options.startLanguage == lang) { $('#' + t.id + '_captions_' + lang).click(); } t.adjustLanguageBox(); }, addTrackButton: function(lang, label) { var t = this; if (label === '') { label = mejs.language.codes[lang] || lang; } t.captionsButton.find('ul').append( $('<li>'+ '<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' + '<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+ '</li>') ); t.adjustLanguageBox(); // remove this from the dropdownlist (if it exists) t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove(); }, adjustLanguageBox:function() { var t = this; // adjust the size of the outer box t.captionsButton.find('.mejs-captions-selector').height( t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) + t.captionsButton.find('.mejs-captions-translations').outerHeight(true) ); }, displayCaptions: function() { if (typeof this.tracks == 'undefined') return; var t = this, i, track = t.selectedTrack; if (track != null && track.isLoaded) { for (i=0; i<track.entries.times.length; i++) { if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){ t.captionsText.html(track.entries.text[i]); t.captions.show().height(0); return; // exit out if one is visible; } } t.captions.hide(); } else { t.captions.hide(); } }, displayChapters: function() { var t = this, i; for (i=0; i<t.tracks.length; i++) { if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) { t.drawChapters(t.tracks[i]); t.hasChapters = true; break; } } }, drawChapters: function(chapters) { var t = this, i, dur, //width, //left, percent = 0, usedPercent = 0; t.chapters.empty(); for (i=0; i<chapters.entries.times.length; i++) { dur = chapters.entries.times[i].stop - chapters.entries.times[i].start; percent = Math.floor(dur / t.media.duration * 100); if (percent + usedPercent > 100 || // too large i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in { percent = 100 - usedPercent; } //width = Math.floor(t.width * dur / t.media.duration); //left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration); //if (left + width > t.width) { // width = t.width - left; //} t.chapters.append( $( '<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' + '<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' + '<span class="ch-title">' + chapters.entries.text[i] + '</span>' + '<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '&ndash;' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' + '</div>' + '</div>')); usedPercent += percent; } t.chapters.find('div.mejs-chapter').click(function() { t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) ); if (t.media.paused) { t.media.play(); } }); t.chapters.show(); } }); mejs.language = { codes: { af:'Afrikaans', sq:'Albanian', ar:'Arabic', be:'Belarusian', bg:'Bulgarian', ca:'Catalan', zh:'Chinese', 'zh-cn':'Chinese Simplified', 'zh-tw':'Chinese Traditional', hr:'Croatian', cs:'Czech', da:'Danish', nl:'Dutch', en:'English', et:'Estonian', tl:'Filipino', fi:'Finnish', fr:'French', gl:'Galician', de:'German', el:'Greek', ht:'Haitian Creole', iw:'Hebrew', hi:'Hindi', hu:'Hungarian', is:'Icelandic', id:'Indonesian', ga:'Irish', it:'Italian', ja:'Japanese', ko:'Korean', lv:'Latvian', lt:'Lithuanian', mk:'Macedonian', ms:'Malay', mt:'Maltese', no:'Norwegian', fa:'Persian', pl:'Polish', pt:'Portuguese', //'pt-pt':'Portuguese (Portugal)', ro:'Romanian', ru:'Russian', sr:'Serbian', sk:'Slovak', sl:'Slovenian', es:'Spanish', sw:'Swahili', sv:'Swedish', tl:'Tagalog', th:'Thai', tr:'Turkish', uk:'Ukrainian', vi:'Vietnamese', cy:'Welsh', yi:'Yiddish' } }; /* Parses WebVVT format which should be formatted as ================================ WEBVTT 1 00:00:01,1 --> 00:00:05,000 A line of text 2 00:01:15,1 --> 00:02:05,000 A second line of text =============================== Adapted from: http://www.delphiki.com/html5/playr */ mejs.TrackFormatParser = { webvvt: { // match start "chapter-" (or anythingelse) pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/, pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/, parse: function(trackText) { var i = 0, lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/), entries = {text:[], times:[]}, timecode, text; for(; i<lines.length; i++) { // check for the line number if (this.pattern_identifier.exec(lines[i])){ // skip to the next line where the start --> end time code should be i++; timecode = this.pattern_timecode.exec(lines[i]); if (timecode && i<lines.length){ i++; // grab all the (possibly multi-line) text that follows text = lines[i]; i++; while(lines[i] !== '' && i<lines.length){ text = text + '\n' + lines[i]; i++; } text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>"); // Text is in a different array so I can use .join entries.text.push(text); entries.times.push( { start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]), stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]), settings: timecode[5] }); } } } return entries; } }, // Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420 dfxp: { parse: function(trackText) { trackText = $(trackText).filter("tt"); var i = 0, container = trackText.children("div").eq(0), lines = container.find("p"), styleNode = trackText.find("#" + container.attr("style")), styles, begin, end, text, entries = {text:[], times:[]}; if (styleNode.length) { var attributes = styleNode.removeAttr("id").get(0).attributes; if (attributes.length) { styles = {}; for (i = 0; i < attributes.length; i++) { styles[attributes[i].name.split(":")[1]] = attributes[i].value; } } } for(i = 0; i<lines.length; i++) { var style; var _temp_times = { start: null, stop: null, style: null }; if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin")); if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end")); if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end")); if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin")); if (styles) { style = ""; for (var _style in styles) { style += _style + ":" + styles[_style] + ";"; } } if (style) _temp_times.style = style; if (_temp_times.start == 0) _temp_times.start = 0.200; entries.times.push(_temp_times); text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>"); entries.text.push(text); if (entries.times.start == 0) entries.times.start = 2; } return entries; } }, split2: function (text, regex) { // normal version for compliant browsers // see below for IE fix return text.split(regex); } }; // test for browsers with bad String.split method. if ('x\n\ny'.split(/\n/gi).length != 3) { // add super slow IE8 and below version mejs.TrackFormatParser.split2 = function(text, regex) { var parts = [], chunk = '', i; for (i=0; i<text.length; i++) { chunk += text.substring(i,i+1); if (regex.test(chunk)) { parts.push(chunk.replace(regex, '')); chunk = ''; } } parts.push(chunk); return parts; } } })(mejs.$); /* * ContextMenu Plugin * * */ (function($) { $.extend(mejs.MepDefaults, { 'contextMenuItems': [ // demo of a fullscreen option { render: function(player) { // check for fullscreen plugin if (typeof player.enterFullScreen == 'undefined') return null; if (player.isFullScreen) { return "Turn off Fullscreen"; } else { return "Go Fullscreen"; } }, click: function(player) { if (player.isFullScreen) { player.exitFullScreen(); } else { player.enterFullScreen(); } } } , // demo of a mute/unmute button { render: function(player) { if (player.media.muted) { return "Unmute"; } else { return "Mute"; } }, click: function(player) { if (player.media.muted) { player.setMuted(false); } else { player.setMuted(true); } } }, // separator { isSeparator: true } , // demo of simple download video { render: function(player) { return "Download Video"; }, click: function(player) { window.location.href = player.media.currentSrc; } } ]} ); $.extend(MediaElementPlayer.prototype, { buildcontextmenu: function(player, controls, layers, media) { // create context menu player.contextMenu = $('<div class="mejs-contextmenu"></div>') .appendTo($('body')) .hide(); // create events for showing context menu player.container.bind('contextmenu', function(e) { if (player.isContextMenuEnabled) { e.preventDefault(); player.renderContextMenu(e.clientX-1, e.clientY-1); return false; } }); player.container.bind('click', function() { player.contextMenu.hide(); }); player.contextMenu.bind('mouseleave', function() { //console.log('context hover out'); player.startContextMenuTimer(); }); }, isContextMenuEnabled: true, enableContextMenu: function() { this.isContextMenuEnabled = true; }, disableContextMenu: function() { this.isContextMenuEnabled = false; }, contextMenuTimeout: null, startContextMenuTimer: function() { //console.log('startContextMenuTimer'); var t = this; t.killContextMenuTimer(); t.contextMenuTimer = setTimeout(function() { t.hideContextMenu(); t.killContextMenuTimer(); }, 750); }, killContextMenuTimer: function() { var timer = this.contextMenuTimer; //console.log('killContextMenuTimer', timer); if (timer != null) { clearTimeout(timer); delete timer; timer = null; } }, hideContextMenu: function() { this.contextMenu.hide(); }, renderContextMenu: function(x,y) { // alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly var t = this, html = '', items = t.options.contextMenuItems; for (var i=0, il=items.length; i<il; i++) { if (items[i].isSeparator) { html += '<div class="mejs-contextmenu-separator"></div>'; } else { var rendered = items[i].render(t); // render can return null if the item doesn't need to be used at the moment if (rendered != null) { html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>'; } } } // position and show the context menu t.contextMenu .empty() .append($(html)) .css({top:y, left:x}) .show(); // bind events t.contextMenu.find('.mejs-contextmenu-item').each(function() { // which one is this? var $dom = $(this), itemIndex = parseInt( $dom.data('itemindex'), 10 ), item = t.options.contextMenuItems[itemIndex]; // bind extra functionality? if (typeof item.show != 'undefined') item.show( $dom , t); // bind click action $dom.click(function() { // perform click action if (typeof item.click != 'undefined') item.click(t); // close t.contextMenu.hide(); }); }); // stop the controls from hiding setTimeout(function() { t.killControlsTimer('rev3'); }, 100); } }); })(mejs.$);
JavaScript
/*! * MediaElement.js * HTML5 <video> and <audio> shim and player * http://mediaelementjs.com/ * * Creates a JavaScript object that mimics HTML5 MediaElement API * for browsers that don't understand HTML5 or can't play the provided codec * Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3 * * Copyright 2010-2012, John Dyer (http://j.hn) * Dual licensed under the MIT or GPL Version 2 licenses. * */ // Namespace var mejs = mejs || {}; // version number mejs.version = '2.9.5'; // player number (for missing, same id attr) mejs.meIndex = 0; // media types accepted by plugins mejs.plugins = { silverlight: [ {version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']} ], flash: [ {version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']} //,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!) ], youtube: [ {version: null, types: ['video/youtube', 'video/x-youtube']} ], vimeo: [ {version: null, types: ['video/vimeo']} ] }; /* Utility methods */ mejs.Utility = { encodeUrl: function(url) { return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26'); }, escapeHTML: function(s) { return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, absolutizeUrl: function(url) { var el = document.createElement('div'); el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>'; return el.firstChild.href; }, getScriptPath: function(scriptNames) { var i = 0, j, path = '', name = '', script, scripts = document.getElementsByTagName('script'), il = scripts.length, jl = scriptNames.length; for (; i < il; i++) { script = scripts[i].src; for (j = 0; j < jl; j++) { name = scriptNames[j]; if (script.indexOf(name) > -1) { path = script.substring(0, script.indexOf(name)); break; } } if (path !== '') { break; } } return path; }, secondsToTimeCode: function(time, forceHours, showFrameCount, fps) { //add framecount if (typeof showFrameCount == 'undefined') { showFrameCount=false; } else if(typeof fps == 'undefined') { fps = 25; } var hours = Math.floor(time / 3600) % 24, minutes = Math.floor(time / 60) % 60, seconds = Math.floor(time % 60), frames = Math.floor(((time % 1)*fps).toFixed(3)), result = ( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '') + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds) + ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : ''); return result; }, timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){ if (typeof showFrameCount == 'undefined') { showFrameCount=false; } else if(typeof fps == 'undefined') { fps = 25; } var tc_array = hh_mm_ss_ff.split(":"), tc_hh = parseInt(tc_array[0], 10), tc_mm = parseInt(tc_array[1], 10), tc_ss = parseInt(tc_array[2], 10), tc_ff = 0, tc_in_seconds = 0; if (showFrameCount) { tc_ff = parseInt(tc_array[3])/fps; } tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff; return tc_in_seconds; }, convertSMPTEtoSeconds: function (SMPTE) { if (typeof SMPTE != 'string') return false; SMPTE = SMPTE.replace(',', '.'); var secs = 0, decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0, multiplier = 1; SMPTE = SMPTE.split(':').reverse(); for (var i = 0; i < SMPTE.length; i++) { multiplier = 1; if (i > 0) { multiplier = Math.pow(60, i); } secs += Number(SMPTE[i]) * multiplier; } return Number(secs.toFixed(decimalLen)); }, /* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */ removeSwf: function(id) { var obj = document.getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (mejs.MediaFeatures.isIE) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { mejs.Utility.removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } }, removeObjectInIE: function(id) { var obj = document.getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } }; // Core detector, plugins are added below mejs.PluginDetector = { // main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]); hasPluginVersion: function(plugin, v) { var pv = this.plugins[plugin]; v[1] = v[1] || 0; v[2] = v[2] || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; }, // cached values nav: window.navigator, ua: window.navigator.userAgent.toLowerCase(), // stored version numbers plugins: [], // runs detectPlugin() and stores the version number addPlugin: function(p, pluginName, mimeType, activeX, axDetect) { this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect); }, // get the version number from the mimetype (all but IE) or ActiveX (IE) detectPlugin: function(pluginName, mimeType, activeX, axDetect) { var version = [0,0,0], description, i, ax; // Firefox, Webkit, Opera if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') { description = this.nav.plugins[pluginName].description; if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) { version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.'); for (i=0; i<version.length; i++) { version[i] = parseInt(version[i].match(/\d+/), 10); } } // Internet Explorer / ActiveX } else if (typeof(window.ActiveXObject) != 'undefined') { try { ax = new ActiveXObject(activeX); if (ax) { version = axDetect(ax); } } catch (e) { } } return version; } }; // Add Flash detection mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) { // adapted from SWFObject var version = [], d = ax.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } return version; }); // Add Silverlight detection mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) { // Silverlight cannot report its version number to IE // but it does have a isVersionSupported function, so we have to loop through it to get a version number. // adapted from http://www.silverlightversion.com/ var v = [0,0,0,0], loopMatch = function(ax, v, i, n) { while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){ v[i]+=n; } v[i] -= n; }; loopMatch(ax, v, 0, 1); loopMatch(ax, v, 1, 1); loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx) loopMatch(ax, v, 2, 1000); loopMatch(ax, v, 2, 100); loopMatch(ax, v, 2, 10); loopMatch(ax, v, 2, 1); loopMatch(ax, v, 3, 1); return v; }); // add adobe acrobat /* PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) { var version = [], d = ax.GetVersions().split(',')[0].split('=')[1].split('.'); if (d) { version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } return version; }); */ // necessary detection (fixes for <IE9) mejs.MediaFeatures = { init: function() { var t = this, d = document, nav = mejs.PluginDetector.nav, ua = mejs.PluginDetector.ua.toLowerCase(), i, v, html5Elements = ['source','track','audio','video']; // detect browsers (only the ones that have some kind of quirk we need to work around) t.isiPad = (ua.match(/ipad/i) !== null); t.isiPhone = (ua.match(/iphone/i) !== null); t.isiOS = t.isiPhone || t.isiPad; t.isAndroid = (ua.match(/android/i) !== null); t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null); t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1); t.isChrome = (ua.match(/chrome/gi) !== null); t.isFirefox = (ua.match(/firefox/gi) !== null); t.isWebkit = (ua.match(/webkit/gi) !== null); t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit; t.isOpera = (ua.match(/opera/gi) !== null); t.hasTouch = ('ontouchstart' in window); // create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection for (i=0; i<html5Elements.length; i++) { v = document.createElement(html5Elements[i]); } t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid); // detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails) // iOS t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined'); // Webkit/firefox t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined'); t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined'); t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen); t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen; if (t.hasMozNativeFullScreen) { t.nativeFullScreenEnabled = v.mozFullScreenEnabled; } if (this.isChrome) { t.hasSemiNativeFullScreen = false; } if (t.hasTrueNativeFullScreen) { t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange'; t.isFullScreen = function() { if (v.mozRequestFullScreen) { return d.mozFullScreen; } else if (v.webkitRequestFullScreen) { return d.webkitIsFullScreen; } } t.requestFullScreen = function(el) { if (t.hasWebkitNativeFullScreen) { el.webkitRequestFullScreen(); } else if (t.hasMozNativeFullScreen) { el.mozRequestFullScreen(); } } t.cancelFullScreen = function() { if (t.hasWebkitNativeFullScreen) { document.webkitCancelFullScreen(); } else if (t.hasMozNativeFullScreen) { document.mozCancelFullScreen(); } } } // OS X 10.5 can't do this even if it says it can :( if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) { t.hasNativeFullScreen = false; t.hasSemiNativeFullScreen = false; } } }; mejs.MediaFeatures.init(); /* extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below) */ mejs.HtmlMediaElement = { pluginType: 'native', isFullScreen: false, setCurrentTime: function (time) { this.currentTime = time; }, setMuted: function (muted) { this.muted = muted; }, setVolume: function (volume) { this.volume = volume; }, // for parity with the plugin versions stop: function () { this.pause(); }, // This can be a url string // or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}] setSrc: function (url) { // Fix for IE9 which can't set .src when there are <source> elements. Awesome, right? var existingSources = this.getElementsByTagName('source'); while (existingSources.length > 0){ this.removeChild(existingSources[0]); } if (typeof url == 'string') { this.src = url; } else { var i, media; for (i=0; i<url.length; i++) { media = url[i]; if (this.canPlayType(media.type)) { this.src = media.src; } } } }, setVideoSize: function (width, height) { this.width = width; this.height = height; } }; /* Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember] */ mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) { this.id = pluginid; this.pluginType = pluginType; this.src = mediaUrl; this.events = {}; }; // JavaScript values and ExternalInterface methods that match HTML5 video properties methods // http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html mejs.PluginMediaElement.prototype = { // special pluginElement: null, pluginType: '', isFullScreen: false, // not implemented :( playbackRate: -1, defaultPlaybackRate: -1, seekable: [], played: [], // HTML5 read-only properties paused: true, ended: false, seeking: false, duration: 0, error: null, tagName: '', // HTML5 get/set properties, but only set (updated by event handlers) muted: false, volume: 1, currentTime: 0, // HTML5 methods play: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.playVideo(); } else { this.pluginApi.playMedia(); } this.paused = false; } }, load: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { } else { this.pluginApi.loadMedia(); } this.paused = false; } }, pause: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.pauseVideo(); } else { this.pluginApi.pauseMedia(); } this.paused = true; } }, stop: function () { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.stopVideo(); } else { this.pluginApi.stopMedia(); } this.paused = true; } }, canPlayType: function(type) { var i, j, pluginInfo, pluginVersions = mejs.plugins[this.pluginType]; for (i=0; i<pluginVersions.length; i++) { pluginInfo = pluginVersions[i]; // test if user has the correct plugin version if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) { // test for plugin playback types for (j=0; j<pluginInfo.types.length; j++) { // find plugin that can play the type if (type == pluginInfo.types[j]) { return true; } } } } return false; }, positionFullscreenButton: function(x,y,visibleAndAbove) { if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) { this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove); } }, hideFullscreenButton: function() { if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) { this.pluginApi.hideFullscreenButton(); } }, // custom methods since not all JavaScript implementations support get/set // This can be a url string // or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}] setSrc: function (url) { if (typeof url == 'string') { this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url)); this.src = mejs.Utility.absolutizeUrl(url); } else { var i, media; for (i=0; i<url.length; i++) { media = url[i]; if (this.canPlayType(media.type)) { this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src)); this.src = mejs.Utility.absolutizeUrl(url); } } } }, setCurrentTime: function (time) { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { this.pluginApi.seekTo(time); } else { this.pluginApi.setCurrentTime(time); } this.currentTime = time; } }, setVolume: function (volume) { if (this.pluginApi != null) { // same on YouTube and MEjs if (this.pluginType == 'youtube') { this.pluginApi.setVolume(volume * 100); } else { this.pluginApi.setVolume(volume); } this.volume = volume; } }, setMuted: function (muted) { if (this.pluginApi != null) { if (this.pluginType == 'youtube') { if (muted) { this.pluginApi.mute(); } else { this.pluginApi.unMute(); } this.muted = muted; this.dispatchEvent('volumechange'); } else { this.pluginApi.setMuted(muted); } this.muted = muted; } }, // additional non-HTML5 methods setVideoSize: function (width, height) { //if (this.pluginType == 'flash' || this.pluginType == 'silverlight') { if ( this.pluginElement.style) { this.pluginElement.style.width = width + 'px'; this.pluginElement.style.height = height + 'px'; } if (this.pluginApi != null && this.pluginApi.setVideoSize) { this.pluginApi.setVideoSize(width, height); } //} }, setFullscreen: function (fullscreen) { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.pluginApi.setFullscreen(fullscreen); } }, enterFullScreen: function() { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.setFullscreen(true); } }, exitFullScreen: function() { if (this.pluginApi != null && this.pluginApi.setFullscreen) { this.setFullscreen(false); } }, // start: fake events addEventListener: function (eventName, callback, bubble) { this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(callback); }, removeEventListener: function (eventName, callback) { if (!eventName) { this.events = {}; return true; } var callbacks = this.events[eventName]; if (!callbacks) return true; if (!callback) { this.events[eventName] = []; return true; } for (i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { this.events[eventName].splice(i, 1); return true; } } return false; }, dispatchEvent: function (eventName) { var i, args, callbacks = this.events[eventName]; if (callbacks) { args = Array.prototype.slice.call(arguments, 1); for (i = 0; i < callbacks.length; i++) { callbacks[i].apply(null, args); } } }, // end: fake events // fake DOM attribute methods attributes: {}, hasAttribute: function(name){ return (name in this.attributes); }, removeAttribute: function(name){ delete this.attributes[name]; }, getAttribute: function(name){ if (this.hasAttribute(name)) { return this.attributes[name]; } return ''; }, setAttribute: function(name, value){ this.attributes[name] = value; }, remove: function() { mejs.Utility.removeSwf(this.pluginElement.id); } }; // Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties mejs.MediaPluginBridge = { pluginMediaElements:{}, htmlMediaElements:{}, registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) { this.pluginMediaElements[id] = pluginMediaElement; this.htmlMediaElements[id] = htmlMediaElement; }, // when Flash/Silverlight is ready, it calls out to this method initPlugin: function (id) { var pluginMediaElement = this.pluginMediaElements[id], htmlMediaElement = this.htmlMediaElements[id]; if (pluginMediaElement) { // find the javascript bridge switch (pluginMediaElement.pluginType) { case "flash": pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id); break; case "silverlight": pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id); pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS; break; } if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) { pluginMediaElement.success(pluginMediaElement, htmlMediaElement); } } }, // receives events from Flash/Silverlight and sends them out as HTML5 media events // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html fireEvent: function (id, eventName, values) { var e, i, bufferedTime, pluginMediaElement = this.pluginMediaElements[id]; pluginMediaElement.ended = false; pluginMediaElement.paused = true; // fake event object to mimic real HTML media event. e = { type: eventName, target: pluginMediaElement }; // attach all values to element and event object for (i in values) { pluginMediaElement[i] = values[i]; e[i] = values[i]; } // fake the newer W3C buffered TimeRange (loaded and total have been removed) bufferedTime = values.bufferedTime || 0; e.target.buffered = e.buffered = { start: function(index) { return 0; }, end: function (index) { return bufferedTime; }, length: 1 }; pluginMediaElement.dispatchEvent(e.type, e); } }; /* Default options */ mejs.MediaElementDefaults = { // allows testing on HTML5, flash, silverlight // auto: attempts to detect what the browser can do // auto_plugin: prefer plugins and then attempt native HTML5 // native: forces HTML5 playback // shim: disallows HTML5, will attempt either Flash or Silverlight // none: forces fallback view mode: 'auto', // remove or reorder to change plugin priority and availability plugins: ['flash','silverlight','youtube','vimeo'], // shows debug errors on screen enablePluginDebug: false, // overrides the type specified, useful for dynamic instantiation type: '', // path to Flash and Silverlight plugins pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']), // name of flash file flashName: 'flashmediaelement.swf', // streamer for RTMP streaming flashStreamer: '', // turns on the smoothing filter in Flash enablePluginSmoothing: false, // name of silverlight file silverlightName: 'silverlightmediaelement.xap', // default if the <video width> is not specified defaultVideoWidth: 480, // default if the <video height> is not specified defaultVideoHeight: 270, // overrides <video width> pluginWidth: -1, // overrides <video height> pluginHeight: -1, // additional plugin variables in 'key=value' form pluginVars: [], // rate in milliseconds for Flash and Silverlight to fire the timeupdate event // larger number is less accurate, but less strain on plugin->JavaScript bridge timerRate: 250, // initial volume for player startVolume: 0.8, success: function () { }, error: function () { } }; /* Determines if a browser supports the <video> or <audio> element and returns either the native element or a Flash/Silverlight version that mimics HTML5 MediaElement */ mejs.MediaElement = function (el, o) { return mejs.HtmlMediaElementShim.create(el,o); }; mejs.HtmlMediaElementShim = { create: function(el, o) { var options = mejs.MediaElementDefaults, htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el, tagName = htmlMediaElement.tagName.toLowerCase(), isMediaTag = (tagName === 'audio' || tagName === 'video'), src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'), poster = htmlMediaElement.getAttribute('poster'), autoplay = htmlMediaElement.getAttribute('autoplay'), preload = htmlMediaElement.getAttribute('preload'), controls = htmlMediaElement.getAttribute('controls'), playback, prop; // extend options for (prop in o) { options[prop] = o[prop]; } // clean up attributes src = (typeof src == 'undefined' || src === null || src == '') ? null : src; poster = (typeof poster == 'undefined' || poster === null) ? '' : poster; preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload; autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false'); controls = !(typeof controls == 'undefined' || controls === null || controls === 'false'); // test for HTML5 and plugin capabilities playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src); playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : ''; if (playback.method == 'native') { // second fix for android if (mejs.MediaFeatures.isBustedAndroid) { htmlMediaElement.src = playback.url; htmlMediaElement.addEventListener('click', function() { htmlMediaElement.play(); }, false); } // add methods to native HTMLMediaElement return this.updateNative(playback, options, autoplay, preload); } else if (playback.method !== '') { // create plugin to mimic HTMLMediaElement return this.createPlugin( playback, options, poster, autoplay, preload, controls); } else { // boo, no HTML5, no Flash, no Silverlight. this.createErrorMessage( playback, options, poster ); return this; } }, determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) { var mediaFiles = [], i, j, k, l, n, type, result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')}, pluginName, pluginVersions, pluginInfo, dummy; // STEP 1: Get URL and type from <video src> or <source src> // supplied type overrides <video type> and <source type> if (typeof options.type != 'undefined' && options.type !== '') { // accept either string or array of types if (typeof options.type == 'string') { mediaFiles.push({type:options.type, url:src}); } else { for (i=0; i<options.type.length; i++) { mediaFiles.push({type:options.type[i], url:src}); } } // test for src attribute first } else if (src !== null) { type = this.formatType(src, htmlMediaElement.getAttribute('type')); mediaFiles.push({type:type, url:src}); // then test for <source> elements } else { // test <source> types to see if they are usable for (i = 0; i < htmlMediaElement.childNodes.length; i++) { n = htmlMediaElement.childNodes[i]; if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') { src = n.getAttribute('src'); type = this.formatType(src, n.getAttribute('type')); mediaFiles.push({type:type, url:src}); } } } // in the case of dynamicly created players // check for audio types if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) { result.isVideo = false; } // STEP 2: Test for playback method // special case for Android which sadly doesn't implement the canPlayType function (always returns '') if (mejs.MediaFeatures.isBustedAndroid) { htmlMediaElement.canPlayType = function(type) { return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : ''; }; } // test for native playback first if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) { if (!isMediaTag) { // create a real HTML5 Media Element dummy = document.createElement( result.isVideo ? 'video' : 'audio'); htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement); htmlMediaElement.style.display = 'none'; // use this one from now on result.htmlMediaElement = htmlMediaElement = dummy; } for (i=0; i<mediaFiles.length; i++) { // normal check if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== '' // special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg') || htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') { result.method = 'native'; result.url = mediaFiles[i].url; break; } } if (result.method === 'native') { if (result.url !== null) { htmlMediaElement.src = result.url; } // if `auto_plugin` mode, then cache the native result but try plugins. if (options.mode !== 'auto_plugin') { return result; } } } // if native playback didn't work, then test plugins if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') { for (i=0; i<mediaFiles.length; i++) { type = mediaFiles[i].type; // test all plugins in order of preference [silverlight, flash] for (j=0; j<options.plugins.length; j++) { pluginName = options.plugins[j]; // test version of plugin (for future features) pluginVersions = mejs.plugins[pluginName]; for (k=0; k<pluginVersions.length; k++) { pluginInfo = pluginVersions[k]; // test if user has the correct plugin version // for youtube/vimeo if (pluginInfo.version == null || mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) { // test for plugin playback types for (l=0; l<pluginInfo.types.length; l++) { // find plugin that can play the type if (type == pluginInfo.types[l]) { result.method = pluginName; result.url = mediaFiles[i].url; return result; } } } } } } } // at this point, being in 'auto_plugin' mode implies that we tried plugins but failed. // if we have native support then return that. if (options.mode === 'auto_plugin' && result.method === 'native') { return result; } // what if there's nothing to play? just grab the first available if (result.method === '' && mediaFiles.length > 0) { result.url = mediaFiles[0].url; } return result; }, formatType: function(url, type) { var ext; // if no type is supplied, fake it with the extension if (url && !type) { return this.getTypeFromFile(url); } else { // only return the mime part of the type in case the attribute contains the codec // see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element // `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4` if (type && ~type.indexOf(';')) { return type.substr(0, type.indexOf(';')); } else { return type; } } }, getTypeFromFile: function(url) { var ext = url.substring(url.lastIndexOf('.') + 1); return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext); }, getTypeFromExtension: function(ext) { switch (ext) { case 'mp4': case 'm4v': return 'mp4'; case 'webm': case 'webma': case 'webmv': return 'webm'; case 'ogg': case 'oga': case 'ogv': return 'ogg'; default: return ext; } }, createErrorMessage: function(playback, options, poster) { var htmlMediaElement = playback.htmlMediaElement, errorContainer = document.createElement('div'); errorContainer.className = 'me-cannotplay'; try { errorContainer.style.width = htmlMediaElement.width + 'px'; errorContainer.style.height = htmlMediaElement.height + 'px'; } catch (e) {} errorContainer.innerHTML = (poster !== '') ? '<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' : '<a href="' + playback.url + '"><span>Download File</span></a>'; htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement); htmlMediaElement.style.display = 'none'; options.error(htmlMediaElement); }, createPlugin:function(playback, options, poster, autoplay, preload, controls) { var htmlMediaElement = playback.htmlMediaElement, width = 1, height = 1, pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++), pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url), container = document.createElement('div'), specialIEContainer, node, initVars; // copy tagName from html media element pluginMediaElement.tagName = htmlMediaElement.tagName // copy attributes from html media element to plugin media element for (var i = 0; i < htmlMediaElement.attributes.length; i++) { var attribute = htmlMediaElement.attributes[i]; if (attribute.specified == true) { pluginMediaElement.setAttribute(attribute.name, attribute.value); } } // check for placement inside a <p> tag (sometimes WYSIWYG editors do this) node = htmlMediaElement.parentNode; while (node !== null && node.tagName.toLowerCase() != 'body') { if (node.parentNode.tagName.toLowerCase() == 'p') { node.parentNode.parentNode.insertBefore(node, node.parentNode); break; } node = node.parentNode; } if (playback.isVideo) { width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth; height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight; // in case of '%' make sure it's encoded width = mejs.Utility.encodeUrl(width); height = mejs.Utility.encodeUrl(height); } else { if (options.enablePluginDebug) { width = 320; height = 240; } } // register plugin pluginMediaElement.success = options.success; mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement); // add container (must be added to DOM before inserting HTML for IE) container.className = 'me-plugin'; container.id = pluginid + '_container'; if (playback.isVideo) { htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement); } else { document.body.insertBefore(container, document.body.childNodes[0]); } // flash/silverlight vars initVars = [ 'id=' + pluginid, 'isvideo=' + ((playback.isVideo) ? "true" : "false"), 'autoplay=' + ((autoplay) ? "true" : "false"), 'preload=' + preload, 'width=' + width, 'startvolume=' + options.startVolume, 'timerrate=' + options.timerRate, 'flashstreamer=' + options.flashStreamer, 'height=' + height]; if (playback.url !== null) { if (playback.method == 'flash') { initVars.push('file=' + mejs.Utility.encodeUrl(playback.url)); } else { initVars.push('file=' + playback.url); } } if (options.enablePluginDebug) { initVars.push('debug=true'); } if (options.enablePluginSmoothing) { initVars.push('smoothing=true'); } if (controls) { initVars.push('controls=true'); // shows controls in the plugin if desired } if (options.pluginVars) { initVars = initVars.concat(options.pluginVars); } switch (playback.method) { case 'silverlight': container.innerHTML = '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' + '<param name="initParams" value="' + initVars.join(',') + '" />' + '<param name="windowless" value="true" />' + '<param name="background" value="black" />' + '<param name="minRuntimeVersion" value="3.0.0.0" />' + '<param name="autoUpgrade" value="true" />' + '<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' + '</object>'; break; case 'flash': if (mejs.MediaFeatures.isIE) { specialIEContainer = document.createElement('div'); container.appendChild(specialIEContainer); specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' + 'id="' + pluginid + '" width="' + width + '" height="' + height + '">' + '<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' + '<param name="flashvars" value="' + initVars.join('&amp;') + '" />' + '<param name="quality" value="high" />' + '<param name="bgcolor" value="#000000" />' + '<param name="wmode" value="transparent" />' + '<param name="allowScriptAccess" value="always" />' + '<param name="allowFullScreen" value="true" />' + '</object>'; } else { container.innerHTML = '<embed id="' + pluginid + '" name="' + pluginid + '" ' + 'play="true" ' + 'loop="false" ' + 'quality="high" ' + 'bgcolor="#000000" ' + 'wmode="transparent" ' + 'allowScriptAccess="always" ' + 'allowFullScreen="true" ' + 'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' + 'src="' + options.pluginPath + options.flashName + '" ' + 'flashvars="' + initVars.join('&') + '" ' + 'width="' + width + '" ' + 'height="' + height + '"></embed>'; } break; case 'youtube': var videoId = playback.url.substr(playback.url.lastIndexOf('=')+1); youtubeSettings = { container: container, containerId: container.id, pluginMediaElement: pluginMediaElement, pluginId: pluginid, videoId: videoId, height: height, width: width }; if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) { mejs.YouTubeApi.createFlash(youtubeSettings); } else { mejs.YouTubeApi.enqueueIframe(youtubeSettings); } break; // DEMO Code. Does NOT work. case 'vimeo': //console.log('vimeoid'); pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1); container.innerHTML = '<object width="' + width + '" height="' + height + '">' + '<param name="allowfullscreen" value="true" />' + '<param name="allowscriptaccess" value="always" />' + '<param name="flashvars" value="api=1" />' + '<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' + '</object>'; break; } // hide original element htmlMediaElement.style.display = 'none'; // FYI: options.success will be fired by the MediaPluginBridge return pluginMediaElement; }, updateNative: function(playback, options, autoplay, preload) { var htmlMediaElement = playback.htmlMediaElement, m; // add methods to video object to bring it into parity with Flash Object for (m in mejs.HtmlMediaElement) { htmlMediaElement[m] = mejs.HtmlMediaElement[m]; } /* Chrome now supports preload="none" if (mejs.MediaFeatures.isChrome) { // special case to enforce preload attribute (Chrome doesn't respect this) if (preload === 'none' && !autoplay) { // forces the browser to stop loading (note: fails in IE9) htmlMediaElement.src = ''; htmlMediaElement.load(); htmlMediaElement.canceledPreload = true; htmlMediaElement.addEventListener('play',function() { if (htmlMediaElement.canceledPreload) { htmlMediaElement.src = playback.url; htmlMediaElement.load(); htmlMediaElement.play(); htmlMediaElement.canceledPreload = false; } }, false); // for some reason Chrome forgets how to autoplay sometimes. } else if (autoplay) { htmlMediaElement.load(); htmlMediaElement.play(); } } */ // fire success code options.success(htmlMediaElement, htmlMediaElement); return htmlMediaElement; } }; /* - test on IE (object vs. embed) - determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE) - fullscreen? */ // YouTube Flash and Iframe API mejs.YouTubeApi = { isIframeStarted: false, isIframeLoaded: false, loadIframeApi: function() { if (!this.isIframeStarted) { var tag = document.createElement('script'); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); this.isIframeStarted = true; } }, iframeQueue: [], enqueueIframe: function(yt) { if (this.isLoaded) { this.createIframe(yt); } else { this.loadIframeApi(); this.iframeQueue.push(yt); } }, createIframe: function(settings) { var pluginMediaElement = settings.pluginMediaElement, player = new YT.Player(settings.containerId, { height: settings.height, width: settings.width, videoId: settings.videoId, playerVars: {controls:0}, events: { 'onReady': function() { // hook up iframe object to MEjs settings.pluginMediaElement.pluginApi = player; // init mejs mejs.MediaPluginBridge.initPlugin(settings.pluginId); // create timer setInterval(function() { mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate'); }, 250); }, 'onStateChange': function(e) { mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement); } } }); }, createEvent: function (player, pluginMediaElement, eventName) { var obj = { type: eventName, target: pluginMediaElement }; if (player && player.getDuration) { // time pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime(); pluginMediaElement.duration = obj.duration = player.getDuration(); // state obj.paused = pluginMediaElement.paused; obj.ended = pluginMediaElement.ended; // sound obj.muted = player.isMuted(); obj.volume = player.getVolume() / 100; // progress obj.bytesTotal = player.getVideoBytesTotal(); obj.bufferedBytes = player.getVideoBytesLoaded(); // fake the W3C buffered TimeRange var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration; obj.target.buffered = obj.buffered = { start: function(index) { return 0; }, end: function (index) { return bufferedTime; }, length: 1 }; } // send event up the chain pluginMediaElement.dispatchEvent(obj.type, obj); }, iFrameReady: function() { this.isLoaded = true; this.isIframeLoaded = true; while (this.iframeQueue.length > 0) { var settings = this.iframeQueue.pop(); this.createIframe(settings); } }, // FLASH! flashPlayers: {}, createFlash: function(settings) { this.flashPlayers[settings.pluginId] = settings; /* settings.container.innerHTML = '<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0" ' + 'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' + '<param name="allowScriptAccess" value="always">' + '<param name="wmode" value="transparent">' + '</object>'; */ var specialIEContainer, youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0'; if (mejs.MediaFeatures.isIE) { specialIEContainer = document.createElement('div'); settings.container.appendChild(specialIEContainer); specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' + 'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' + '<param name="movie" value="' + youtubeUrl + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowScriptAccess" value="always" />' + '<param name="allowFullScreen" value="true" />' + '</object>'; } else { settings.container.innerHTML = '<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' + 'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' + '<param name="allowScriptAccess" value="always">' + '<param name="wmode" value="transparent">' + '</object>'; } }, flashReady: function(id) { var settings = this.flashPlayers[id], player = document.getElementById(id), pluginMediaElement = settings.pluginMediaElement; // hook up and return to MediaELementPlayer.success pluginMediaElement.pluginApi = pluginMediaElement.pluginElement = player; mejs.MediaPluginBridge.initPlugin(id); // load the youtube video player.cueVideoById(settings.videoId); var callbackName = settings.containerId + '_callback' window[callbackName] = function(e) { mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement); } player.addEventListener('onStateChange', callbackName); setInterval(function() { mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate'); }, 250); }, handleStateChange: function(youTubeState, player, pluginMediaElement) { switch (youTubeState) { case -1: // not started pluginMediaElement.paused = true; pluginMediaElement.ended = true; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata'); //createYouTubeEvent(player, pluginMediaElement, 'loadeddata'); break; case 0: pluginMediaElement.paused = false; pluginMediaElement.ended = true; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended'); break; case 1: pluginMediaElement.paused = false; pluginMediaElement.ended = false; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play'); mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing'); break; case 2: pluginMediaElement.paused = true; pluginMediaElement.ended = false; mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause'); break; case 3: // buffering mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress'); break; case 5: // cued? break; } } } // IFRAME function onYouTubePlayerAPIReady() { mejs.YouTubeApi.iFrameReady(); } // FLASH function onYouTubePlayerReady(id) { mejs.YouTubeApi.flashReady(id); } window.mejs = mejs; window.MediaElement = mejs.MediaElement;
JavaScript
// needs Markdown.Converter.js at the moment (function () { var util = {}, position = {}, ui = {}, doc = window.document, re = window.RegExp, nav = window.navigator, SETTINGS = { lineLength: 72 }, // Used to work around some browser bugs where we can't use feature testing. uaSniffed = { isIE: /msie/.test(nav.userAgent.toLowerCase()), isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()), isOpera: /opera/.test(nav.userAgent.toLowerCase()) }; var defaultsStrings = { bold: "Strong <strong> Ctrl+B", boldexample: "strong text", italic: "Emphasis <em> Ctrl+I", italicexample: "emphasized text", link: "Hyperlink <a> Ctrl+L", linkdescription: "enter link description here", linkdialog: "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>", quote: "Blockquote <blockquote> Ctrl+Q", quoteexample: "Blockquote", code: "Code Sample <pre><code> Ctrl+K", codeexample: "enter code here", image: "Image <img> Ctrl+G", imagedescription: "enter image description here", imagedialog: "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br><br>Need <a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>free image hosting?</a></p>", olist: "Numbered List <ol> Ctrl+O", ulist: "Bulleted List <ul> Ctrl+U", litem: "List item", heading: "Heading <h1>/<h2> Ctrl+H", headingexample: "Heading", hr: "Horizontal Rule <hr> Ctrl+R", undo: "Undo - Ctrl+Z", redo: "Redo - Ctrl+Y", redomac: "Redo - Ctrl+Shift+Z", help: "Markdown Editing Help" }; // ------------------------------------------------------------------- // YOUR CHANGES GO HERE // // I've tried to localize the things you are likely to change to // this area. // ------------------------------------------------------------------- // The default text that appears in the dialog input box when entering // links. var imageDefaultText = "http://"; var linkDefaultText = "http://"; // ------------------------------------------------------------------- // END OF YOUR CHANGES // ------------------------------------------------------------------- // options, if given, can have the following properties: // options.helpButton = { handler: yourEventHandler } // options.strings = { italicexample: "slanted text" } // `yourEventHandler` is the click handler for the help button. // If `options.helpButton` isn't given, not help button is created. // `options.strings` can have any or all of the same properties as // `defaultStrings` above, so you can just override some string displayed // to the user on a case-by-case basis, or translate all strings to // a different language. // // For backwards compatibility reasons, the `options` argument can also // be just the `helpButton` object, and `strings.help` can also be set via // `helpButton.title`. This should be considered legacy. // // The constructed editor object has the methods: // - getConverter() returns the markdown converter object that was passed to the constructor // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called. Markdown.Editor = function (markdownConverter, idPostfix, options) { options = options || {}; if (typeof options.handler === "function") { //backwards compatible behavior options = { helpButton: options }; } options.strings = options.strings || {}; if (options.helpButton) { options.strings.help = options.strings.help || options.helpButton.title; } var getString = function (identifier) { return options.strings[identifier] || defaultsStrings[identifier]; } idPostfix = idPostfix || ""; var hooks = this.hooks = new Markdown.HookCollection(); hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used. */ this.getConverter = function () { return markdownConverter; } var that = this, panels; this.run = function () { if (panels) return; // already initialized panels = new PanelCollection(idPostfix); var commandManager = new CommandManager(hooks, getString); var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); }); var undoManager, uiManager; if (!/\?noundo/.test(doc.location.href)) { undoManager = new UndoManager(function () { previewManager.refresh(); if (uiManager) // not available on the first call uiManager.setUndoRedoButtonStates(); }, panels); this.textOperation = function (f) { undoManager.setCommandMode(); f(); that.refreshPreview(); } } uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString); uiManager.setUndoRedoButtonStates(); var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); }; forceRefresh(); }; } // before: contains all the text in the input box BEFORE the selection. // after: contains all the text in the input box AFTER the selection. function Chunks() { } // startRegex: a regular expression to find the start tag // endRegex: a regular expresssion to find the end tag Chunks.prototype.findTags = function (startRegex, endRegex) { var chunkObj = this; var regex; if (startRegex) { regex = util.extendRegExp(startRegex, "", "$"); this.before = this.before.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); regex = util.extendRegExp(startRegex, "^", ""); this.selection = this.selection.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); } if (endRegex) { regex = util.extendRegExp(endRegex, "", "$"); this.selection = this.selection.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); regex = util.extendRegExp(endRegex, "^", ""); this.after = this.after.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); } }; // If remove is false, the whitespace is transferred // to the before/after regions. // // If remove is true, the whitespace disappears. Chunks.prototype.trimWhitespace = function (remove) { var beforeReplacer, afterReplacer, that = this; if (remove) { beforeReplacer = afterReplacer = ""; } else { beforeReplacer = function (s) { that.before += s; return ""; } afterReplacer = function (s) { that.after = s + that.after; return ""; } } this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer); }; Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) { if (nLinesBefore === undefined) { nLinesBefore = 1; } if (nLinesAfter === undefined) { nLinesAfter = 1; } nLinesBefore++; nLinesAfter++; var regexText; var replacementText; // chrome bug ... documented at: http://meta.stackexchange.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985 if (navigator.userAgent.match(/Chrome/)) { "X".match(/()./); } this.selection = this.selection.replace(/(^\n*)/, ""); this.startTag = this.startTag + re.$1; this.selection = this.selection.replace(/(\n*$)/, ""); this.endTag = this.endTag + re.$1; this.startTag = this.startTag.replace(/(^\n*)/, ""); this.before = this.before + re.$1; this.endTag = this.endTag.replace(/(\n*$)/, ""); this.after = this.after + re.$1; if (this.before) { regexText = replacementText = ""; while (nLinesBefore--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.before = this.before.replace(new re(regexText + "$", ""), replacementText); } if (this.after) { regexText = replacementText = ""; while (nLinesAfter--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.after = this.after.replace(new re(regexText, ""), replacementText); } }; // end of Chunks // A collection of the important regions on the page. // Cached so we don't have to keep traversing the DOM. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around // this issue: // Internet explorer has problems with CSS sprite buttons that use HTML // lists. When you click on the background image "button", IE will // select the non-existent link text and discard the selection in the // textarea. The solution to this is to cache the textarea selection // on the button's mousedown event and set a flag. In the part of the // code where we need to grab the selection, we check for the flag // and, if it's set, use the cached area instead of querying the // textarea. // // This ONLY affects Internet Explorer (tested on versions 6, 7 // and 8) and ONLY on button clicks. Keyboard shortcuts work // normally since the focus never leaves the textarea. function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); this.preview = doc.getElementById("wmd-preview" + postfix); this.input = doc.getElementById("wmd-input" + postfix); }; // Returns true if the DOM element is visible, false if it's hidden. // Checks if display is anything other than none. util.isVisible = function (elem) { if (window.getComputedStyle) { // Most browsers return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none"; } else if (elem.currentStyle) { // IE return elem.currentStyle["display"] !== "none"; } }; // Adds a listener callback to a DOM element which is fired on a specified // event. util.addEvent = function (elem, event, listener) { if (elem.attachEvent) { // IE only. The "on" is mandatory. elem.attachEvent("on" + event, listener); } else { // Other browsers. elem.addEventListener(event, listener, false); } }; // Removes a listener callback from a DOM element which is fired on a specified // event. util.removeEvent = function (elem, event, listener) { if (elem.detachEvent) { // IE only. The "on" is mandatory. elem.detachEvent("on" + event, listener); } else { // Other browsers. elem.removeEventListener(event, listener, false); } }; // Converts \r\n and \r to \n. util.fixEolChars = function (text) { text = text.replace(/\r\n/g, "\n"); text = text.replace(/\r/g, "\n"); return text; }; // Extends a regular expression. Returns a new RegExp // using pre + regex + post as the expression. // Used in a few functions where we have a base // expression and we want to pre- or append some // conditions to it (e.g. adding "$" to the end). // The flags are unchanged. // // regex is a RegExp, pre and post are strings. util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } var pattern = regex.toString(); var flags; // Replace the flags with empty space and store them. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) { flags = flagsPart; return ""; }); // Remove the slash delimiters on the regular expression. pattern = pattern.replace(/(^\/|\/$)/g, ""); pattern = pre + pattern + post; return new re(pattern, flags); } // UNFINISHED // The assignment in the while loop makes jslint cranky. // I'll change it to a better loop later. position.getTop = function (elem, isInner) { var result = elem.offsetTop; if (!isInner) { while (elem = elem.offsetParent) { result += elem.offsetTop; } } return result; }; position.getHeight = function (elem) { return elem.offsetHeight || elem.scrollHeight; }; position.getWidth = function (elem) { return elem.offsetWidth || elem.scrollWidth; }; position.getPageSize = function () { var scrollWidth, scrollHeight; var innerWidth, innerHeight; // It's not very clear which blocks work with which browsers. if (self.innerHeight && self.scrollMaxY) { scrollWidth = doc.body.scrollWidth; scrollHeight = self.innerHeight + self.scrollMaxY; } else if (doc.body.scrollHeight > doc.body.offsetHeight) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { scrollWidth = doc.body.offsetWidth; scrollHeight = doc.body.offsetHeight; } if (self.innerHeight) { // Non-IE browser innerWidth = self.innerWidth; innerHeight = self.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { // Some versions of IE (IE 6 w/ a DOCTYPE declaration) innerWidth = doc.documentElement.clientWidth; innerHeight = doc.documentElement.clientHeight; } else if (doc.body) { // Other versions of IE innerWidth = doc.body.clientWidth; innerHeight = doc.body.clientHeight; } var maxWidth = Math.max(scrollWidth, innerWidth); var maxHeight = Math.max(scrollHeight, innerHeight); return [maxWidth, maxHeight, innerWidth, innerHeight]; }; // Handles pushing and popping TextareaStates for undo/redo commands. // I should rename the stack variables to list. function UndoManager(callback, panels) { var undoObj = this; var undoStack = []; // A stack of undo states var stackPtr = 0; // The index of the current state var mode = "none"; var lastState; // The last state var timer; // The setTimeout handle for cancelling the timer var inputStateObj; // Set the mode for later logic steps. var setMode = function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }; var refreshState = function (isInitialState) { inputStateObj = new TextareaState(panels, isInitialState); timer = undefined; }; this.setCommandMode = function () { mode = "command"; saveState(); timer = setTimeout(refreshState, 0); }; this.canUndo = function () { return stackPtr > 1; }; this.canRedo = function () { if (undoStack[stackPtr + 1]) { return true; } return false; }; // Removes the last state and restores it. this.undo = function () { if (undoObj.canUndo()) { if (lastState) { // What about setting state -1 to null or checking for undefined? lastState.restore(); lastState = null; } else { undoStack[stackPtr] = new TextareaState(panels); undoStack[--stackPtr].restore(); if (callback) { callback(); } } } mode = "none"; panels.input.focus(); refreshState(); }; // Redo an action. this.redo = function () { if (undoObj.canRedo()) { undoStack[++stackPtr].restore(); if (callback) { callback(); } } mode = "none"; panels.input.focus(); refreshState(); }; // Push the input area state to the stack. var saveState = function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }; var handleCtrlYZ = function (event) { var handled = false; if ((event.ctrlKey || event.metaKey) && !event.altKey) { // IE and Opera do not support charCode. var keyCode = event.charCode || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); switch (keyCodeChar.toLowerCase()) { case "y": undoObj.redo(); handled = true; break; case "z": if (!event.shiftKey) { undoObj.undo(); } else { undoObj.redo(); } handled = true; break; } } if (handled) { if (event.preventDefault) { event.preventDefault(); } if (window.event) { window.event.returnValue = false; } return; } }; // Set the mode depending on what is going on in the input area. var handleModeChange = function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }; var setEventHandlers = function () { util.addEvent(panels.input, "keypress", function (event) { // keyCode 89: y // keyCode 90: z if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.keyCode == 89 || event.keyCode == 90)) { event.preventDefault(); } }); var handlePaste = function () { if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) { if (timer == undefined) { mode = "paste"; saveState(); refreshState(); } } }; util.addEvent(panels.input, "keydown", handleCtrlYZ); util.addEvent(panels.input, "keydown", handleModeChange); util.addEvent(panels.input, "mousedown", function () { setMode("moving"); }); panels.input.onpaste = handlePaste; panels.input.ondrop = handlePaste; }; var init = function () { setEventHandlers(); refreshState(true); saveState(); }; init(); } // end of UndoManager // The input textarea state/contents. // This is used to implement undo/redo by the undo manager. function TextareaState(panels, isInitialState) { // Aliases var stateObj = this; var inputArea = panels.input; this.init = function () { if (!util.isVisible(inputArea)) { return; } if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box return; } this.setInputAreaSelectionStartEnd(); this.scrollTop = inputArea.scrollTop; if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) { this.text = inputArea.value; } } // Sets the selected text in the input box after we've performed an // operation. this.setInputAreaSelection = function () { if (!util.isVisible(inputArea)) { return; } if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) { inputArea.focus(); inputArea.selectionStart = stateObj.start; inputArea.selectionEnd = stateObj.end; inputArea.scrollTop = stateObj.scrollTop; } else if (doc.selection) { if (doc.activeElement && doc.activeElement !== inputArea) { return; } inputArea.focus(); var range = inputArea.createTextRange(); range.moveStart("character", -inputArea.value.length); range.moveEnd("character", -inputArea.value.length); range.moveEnd("character", stateObj.end); range.moveStart("character", stateObj.start); range.select(); } }; this.setInputAreaSelectionStartEnd = function () { if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) { stateObj.start = inputArea.selectionStart; stateObj.end = inputArea.selectionEnd; } else if (doc.selection) { stateObj.text = util.fixEolChars(inputArea.value); // IE loses the selection in the textarea when buttons are // clicked. On IE we cache the selection. Here, if something is cached, // we take it. var range = panels.ieCachedRange || doc.selection.createRange(); var fixedRange = util.fixEolChars(range.text); var marker = "\x07"; var markedRange = marker + fixedRange + marker; range.text = markedRange; var inputText = util.fixEolChars(inputArea.value); range.moveStart("character", -markedRange.length); range.text = fixedRange; stateObj.start = inputText.indexOf(marker); stateObj.end = inputText.lastIndexOf(marker) - marker.length; var len = stateObj.text.length - util.fixEolChars(inputArea.value).length; if (len) { range.moveStart("character", -fixedRange.length); while (len--) { fixedRange += "\n"; stateObj.end += 1; } range.text = fixedRange; } if (panels.ieCachedRange) stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange panels.ieCachedRange = null; this.setInputAreaSelection(); } }; // Restore this state into the input area. this.restore = function () { if (stateObj.text != undefined && stateObj.text != inputArea.value) { inputArea.value = stateObj.text; } this.setInputAreaSelection(); inputArea.scrollTop = stateObj.scrollTop; }; // Gets a collection of HTML chunks from the inptut textarea. this.getChunks = function () { var chunk = new Chunks(); chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start)); chunk.startTag = ""; chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end)); chunk.endTag = ""; chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end)); chunk.scrollTop = stateObj.scrollTop; return chunk; }; // Sets the TextareaState properties given a chunk of markdown. this.setChunks = function (chunk) { chunk.before = chunk.before + chunk.startTag; chunk.after = chunk.endTag + chunk.after; this.start = chunk.before.length; this.end = chunk.before.length + chunk.selection.length; this.text = chunk.before + chunk.selection + chunk.after; this.scrollTop = chunk.scrollTop; }; this.init(); }; function PreviewManager(converter, panels, previewRefreshCallback) { var managerObj = this; var timeout; var elapsedTime; var oldInputText; var maxDelay = 3000; var startType = "delayed"; // The other legal value is "manual" // Adds event listeners to elements var setupEvents = function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }; var getDocScrollTop = function () { var result = 0; if (window.innerHeight) { result = window.pageYOffset; } else if (doc.documentElement && doc.documentElement.scrollTop) { result = doc.documentElement.scrollTop; } else if (doc.body) { result = doc.body.scrollTop; } return result; }; var makePreviewHtml = function () { // If there is no registered preview panel // there is nothing to do. if (!panels.preview) return; var text = panels.input.value; if (text && text == oldInputText) { return; // Input text hasn't changed. } else { oldInputText = text; } var prevTime = new Date().getTime(); text = converter.makeHtml(text); // Calculate the processing time of the HTML creation. // It's used as the delay time in the event listener. var currTime = new Date().getTime(); elapsedTime = currTime - prevTime; pushPreviewHtml(text); }; // setTimeout is already used. Used as an event listener. var applyTimeout = function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }; var getScaleFactor = function (panel) { if (panel.scrollHeight <= panel.clientHeight) { return 1; } return panel.scrollTop / (panel.scrollHeight - panel.clientHeight); }; var setPanelScrollTops = function () { if (panels.preview) { panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview); } }; this.refresh = function (requiresRefresh) { if (requiresRefresh) { oldInputText = ""; makePreviewHtml(); } else { applyTimeout(); } }; this.processingTime = function () { return elapsedTime; }; var isFirstTimeFilled = true; // IE doesn't let you use innerHTML if the element is contained somewhere in a table // (which is the case for inline editing) -- in that case, detach the element, set the // value, and reattach. Yes, that *is* ridiculous. var ieSafePreviewSet = function (text) { var preview = panels.preview; var parent = preview.parentNode; var sibling = preview.nextSibling; parent.removeChild(preview); preview.innerHTML = text; if (!sibling) parent.appendChild(preview); else parent.insertBefore(preview, sibling); } var nonSuckyBrowserPreviewSet = function (text) { panels.preview.innerHTML = text; } var previewSetter; var previewSet = function (text) { if (previewSetter) return previewSetter(text); try { nonSuckyBrowserPreviewSet(text); previewSetter = nonSuckyBrowserPreviewSet; } catch (e) { previewSetter = ieSafePreviewSet; previewSetter(text); } }; var pushPreviewHtml = function (text) { var emptyTop = position.getTop(panels.input) - getDocScrollTop(); if (panels.preview) { previewSet(text); previewRefreshCallback(); } setPanelScrollTops(); if (isFirstTimeFilled) { isFirstTimeFilled = false; return; } var fullTop = position.getTop(panels.input) - getDocScrollTop(); if (uaSniffed.isIE) { setTimeout(function () { window.scrollBy(0, fullTop - emptyTop); }, 0); } else { window.scrollBy(0, fullTop - emptyTop); } }; var init = function () { setupEvents(panels.input, applyTimeout); makePreviewHtml(); if (panels.preview) { panels.preview.scrollTop = 0; } }; init(); }; // Creates the background behind the hyperlink text entry box. // And download dialog // Most of this has been moved to CSS but the div creation and // browser-specific hacks remain here. ui.createBackground = function () { var background = doc.createElement("div"), style = background.style; background.className = "wmd-prompt-background"; style.position = "absolute"; style.top = "0"; style.zIndex = "1000"; if (uaSniffed.isIE) { style.filter = "alpha(opacity=50)"; } else { style.opacity = "0.5"; } var pageSize = position.getPageSize(); style.height = pageSize[1] + "px"; if (uaSniffed.isIE) { style.left = doc.documentElement.scrollLeft; style.width = doc.documentElement.clientWidth; } else { style.left = "0"; style.width = "100%"; } doc.body.appendChild(background); return background; }; // This simulates a modal dialog box and asks for the URL when you // click the hyperlink or image buttons. // // text: The html for the input box. // defaultInputText: The default value that appears in the input box. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel // was chosen). ui.prompt = function (text, defaultInputText, callback) { // These variables need to be declared at this level since they are used // in multiple functions. var dialog; // The dialog box. var input; // The text box where you enter the hyperlink. if (defaultInputText === undefined) { defaultInputText = ""; } // Used as a keydown event handler. Esc dismisses the prompt. // Key code 27 is ESC. var checkEscape = function (key) { var code = (key.charCode || key.keyCode); if (code === 27) { if (key.stopPropagation) key.stopPropagation(); close(true); return false; } }; // Dismisses the hyperlink input box. // isCancel is true if we don't care about the input text. // isCancel is false if we are going to keep the text. var close = function (isCancel) { util.removeEvent(doc.body, "keyup", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }; // Create the text input box form/window. var createDialog = function () { // The main dialog box. dialog = doc.createElement("div"); dialog.className = "wmd-prompt-dialog"; dialog.style.padding = "10px;"; dialog.style.position = "fixed"; dialog.style.width = "400px"; dialog.style.zIndex = "1001"; // The dialog text. var question = doc.createElement("div"); question.innerHTML = text; question.style.padding = "5px"; dialog.appendChild(question); // The web form container for the text box and buttons. var form = doc.createElement("form"), style = form.style; form.onsubmit = function () { return close(false); }; style.padding = "0"; style.margin = "0"; style.cssFloat = "left"; style.width = "100%"; style.textAlign = "center"; style.position = "relative"; dialog.appendChild(form); // The input text box input = doc.createElement("input"); input.type = "text"; input.value = defaultInputText; style = input.style; style.display = "block"; style.width = "80%"; style.marginLeft = style.marginRight = "auto"; form.appendChild(input); // The ok button var okButton = doc.createElement("input"); okButton.type = "button"; okButton.onclick = function () { return close(false); }; okButton.value = "OK"; style = okButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; // The cancel button var cancelButton = doc.createElement("input"); cancelButton.type = "button"; cancelButton.onclick = function () { return close(true); }; cancelButton.value = "Cancel"; style = cancelButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; form.appendChild(okButton); form.appendChild(cancelButton); util.addEvent(doc.body, "keyup", checkEscape); dialog.style.top = "50%"; dialog.style.left = "50%"; dialog.style.display = "block"; if (uaSniffed.isIE_5or6) { dialog.style.position = "absolute"; dialog.style.top = doc.documentElement.scrollTop + 200 + "px"; dialog.style.left = "50%"; } doc.body.appendChild(dialog); // This has to be done AFTER adding the dialog to the form if you // want it to be centered. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px"; dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px"; }; // Why is this in a zero-length timeout? // Is it working around a browser bug? setTimeout(function () { createDialog(); var defTextLen = defaultInputText.length; if (input.selectionStart !== undefined) { input.selectionStart = 0; input.selectionEnd = defTextLen; } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(false); range.moveStart("character", -defTextLen); range.moveEnd("character", defTextLen); range.select(); } input.focus(); }, 0); }; function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, getString) { var inputBox = panels.input, buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements. makeSpritedButtonRow(); var keyEvent = "keydown"; if (uaSniffed.isOpera) { keyEvent = "keypress"; } util.addEvent(inputBox, keyEvent, function (key) { // Check to see if we have a button key and, if so execute the callback. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) { var keyCode = key.charCode || key.keyCode; var keyCodeStr = String.fromCharCode(keyCode).toLowerCase(); switch (keyCodeStr) { case "b": doClick(buttons.bold); break; case "i": doClick(buttons.italic); break; case "l": doClick(buttons.link); break; case "q": doClick(buttons.quote); break; case "k": doClick(buttons.code); break; case "g": doClick(buttons.image); break; case "o": doClick(buttons.olist); break; case "u": doClick(buttons.ulist); break; case "h": doClick(buttons.heading); break; case "r": doClick(buttons.hr); break; case "y": doClick(buttons.redo); break; case "z": if (key.shiftKey) { doClick(buttons.redo); } else { doClick(buttons.undo); } break; default: return; } if (key.preventDefault) { key.preventDefault(); } if (window.event) { window.event.returnValue = false; } } }); // Auto-indent on shift-enter util.addEvent(inputBox, "keyup", function (key) { if (key.shiftKey && !key.ctrlKey && !key.metaKey) { var keyCode = key.charCode || key.keyCode; // Character 13 is Enter if (keyCode === 13) { var fakeButton = {}; fakeButton.textOp = bindCommand("doAutoindent"); doClick(fakeButton); } } }); // special handler because IE clears the context of the textbox on ESC if (uaSniffed.isIE) { util.addEvent(inputBox, "keydown", function (key) { var code = key.keyCode; if (code === 27) { return false; } }); } // Perform the button's action. function doClick(button) { inputBox.focus(); if (button.textOp) { if (undoManager) { undoManager.setCommandMode(); } var state = new TextareaState(panels); if (!state) { return; } var chunks = state.getChunks(); // Some commands launch a "modal" prompt dialog. Javascript // can't really make a modal dialog box and the WMD code // will continue to execute while the dialog is displayed. // This prevents the dialog pattern I'm used to and means // I can't do something like this: // // var link = CreateLinkDialog(); // makeMarkdownLink(link); // // Instead of this straightforward method of handling a // dialog I have to pass any code which would execute // after the dialog is dismissed (e.g. link creation) // in a function parameter. // // Yes this is awkward and I think it sucks, but there's // no real workaround. Only the image and link code // create dialogs and require the function pointers. var fixupInputArea = function () { inputBox.focus(); if (chunks) { state.setChunks(chunks); } state.restore(); previewManager.refresh(); }; var noCleanup = button.textOp(chunks, fixupInputArea); if (!noCleanup) { fixupInputArea(); } } if (button.execute) { button.execute(undoManager); } }; function setupButton(button, isEnabled) { var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var image = button.getElementsByTagName("span")[0]; if (isEnabled) { image.style.backgroundPosition = button.XShift + " " + normalYShift; button.onmouseover = function () { image.style.backgroundPosition = this.XShift + " " + highlightYShift; }; button.onmouseout = function () { image.style.backgroundPosition = this.XShift + " " + normalYShift; }; // IE tries to select the background image "button" text (it's // implemented in a list item) so we have to cache the selection // on mousedown. if (uaSniffed.isIE) { button.onmousedown = function () { if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection return; } panels.ieCachedRange = document.selection.createRange(); panels.ieCachedScrollTop = panels.input.scrollTop; }; } if (!button.isHelp) { button.onclick = function () { if (this.onmouseout) { this.onmouseout(); } doClick(this); return false; } } } else { image.style.backgroundPosition = button.XShift + " " + disabledYShift; button.onmouseover = button.onmouseout = button.onclick = function () { }; } } function bindCommand(method) { if (typeof method === "string") method = commandManager[method]; return function () { method.apply(commandManager, arguments); } } function makeSpritedButtonRow() { var buttonBar = panels.buttonBar; var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var buttonRow = document.createElement("ul"); buttonRow.id = "wmd-button-row" + postfix; buttonRow.className = 'wmd-button-row'; buttonRow = buttonBar.appendChild(buttonRow); var xPosition = 0; var makeButton = function (id, title, XShift, textOp) { var button = document.createElement("li"); button.className = "wmd-button"; button.style.left = xPosition + "px"; xPosition += 25; var buttonImage = document.createElement("span"); button.id = id + postfix; button.appendChild(buttonImage); button.title = title; button.XShift = XShift; if (textOp) button.textOp = textOp; setupButton(button, true); buttonRow.appendChild(button); return button; }; var makeSpacer = function (num) { var spacer = document.createElement("li"); spacer.className = "wmd-spacer wmd-spacer" + num; spacer.id = "wmd-spacer" + num + postfix; buttonRow.appendChild(spacer); xPosition += 25; } buttons.bold = makeButton("wmd-bold-button", getString("bold"), "0px", bindCommand("doBold")); buttons.italic = makeButton("wmd-italic-button", getString("italic"), "-20px", bindCommand("doItalic")); makeSpacer(1); buttons.link = makeButton("wmd-link-button", getString("link"), "-40px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, false); })); buttons.quote = makeButton("wmd-quote-button", getString("quote"), "-60px", bindCommand("doBlockquote")); buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode")); buttons.image = makeButton("wmd-image-button", getString("image"), "-100px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, true); })); makeSpacer(2); buttons.olist = makeButton("wmd-olist-button", getString("olist"), "-120px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, true); })); buttons.ulist = makeButton("wmd-ulist-button", getString("ulist"), "-140px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, false); })); buttons.heading = makeButton("wmd-heading-button", getString("heading"), "-160px", bindCommand("doHeading")); buttons.hr = makeButton("wmd-hr-button", getString("hr"), "-180px", bindCommand("doHorizontalRule")); makeSpacer(3); buttons.undo = makeButton("wmd-undo-button", getString("undo"), "-200px", null); buttons.undo.execute = function (manager) { if (manager) manager.undo(); }; var redoTitle = /win/.test(nav.platform.toLowerCase()) ? getString("redo") : getString("redomac"); // mac and other non-Windows platforms buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null); buttons.redo.execute = function (manager) { if (manager) manager.redo(); }; if (helpOptions) { var helpButton = document.createElement("li"); var helpButtonImage = document.createElement("span"); helpButton.appendChild(helpButtonImage); helpButton.className = "wmd-button wmd-help-button"; helpButton.id = "wmd-help-button" + postfix; helpButton.XShift = "-240px"; helpButton.isHelp = true; helpButton.style.right = "0px"; helpButton.title = getString("help"); helpButton.onclick = helpOptions.handler; setupButton(helpButton, true); buttonRow.appendChild(helpButton); buttons.help = helpButton; } setUndoRedoButtonStates(); } function setUndoRedoButtonStates() { if (undoManager) { setupButton(buttons.undo, undoManager.canUndo()); setupButton(buttons.redo, undoManager.canRedo()); } }; this.setUndoRedoButtonStates = setUndoRedoButtonStates; } function CommandManager(pluginHooks, getString) { this.hooks = pluginHooks; this.getString = getString; } var commandProto = CommandManager.prototype; // The markdown symbols - 4 spaces = code, > = blockquote, etc. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)"; // Remove markdown symbols from the chunk selection. commandProto.unwrap = function (chunk) { var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g"); chunk.selection = chunk.selection.replace(txt, "$1 $2"); }; commandProto.wrap = function (chunk, len) { this.unwrap(chunk); var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"), that = this; chunk.selection = chunk.selection.replace(regex, function (line, marked) { if (new re("^" + that.prefixes, "").test(line)) { return line; } return marked + "\n"; }); chunk.selection = chunk.selection.replace(/\s+$/, ""); }; commandProto.doBold = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 2, this.getString("boldexample")); }; commandProto.doItalic = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 1, this.getString("italicexample")); }; // chunk: The selected region that will be enclosed with */** // nStars: 1 for italics, 2 for bold // insertText: If you just click the button without highlighting text, this gets inserted commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) { // Get rid of whitespace and fixup newlines. chunk.trimWhitespace(); chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n"); // Look for stars before and after. Is the chunk already marked up? // note that these regex matches cannot fail var starsBefore = /(\**$)/.exec(chunk.before)[0]; var starsAfter = /(^\**)/.exec(chunk.after)[0]; var prevStars = Math.min(starsBefore.length, starsAfter.length); // Remove stars if we have to since the button acts as a toggle. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) { chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), ""); chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), ""); } else if (!chunk.selection && starsAfter) { // It's not really clear why this code is necessary. It just moves // some arbitrary stuff around. chunk.after = chunk.after.replace(/^([*_]*)/, ""); chunk.before = chunk.before.replace(/(\s?)$/, ""); var whitespace = re.$1; chunk.before = chunk.before + starsAfter + whitespace; } else { // In most cases, if you don't have any selected text and click the button // you'll get a selected, marked up region with the default text inserted. if (!chunk.selection && !starsAfter) { chunk.selection = insertText; } // Add the true markup. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ? chunk.before = chunk.before + markup; chunk.after = markup + chunk.after; } return; }; commandProto.stripLinkDefs = function (text, defsToAdd) { text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, function (totalMatch, id, link, newlines, title) { defsToAdd[id] = totalMatch.replace(/\s*$/, ""); if (newlines) { // Strip the title and return that separately. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, ""); return newlines + title; } return ""; }); return text; }; commandProto.addLinkDef = function (chunk, linkDef) { var refNumber = 0; // The current reference number var defsToAdd = {}; // // Start with a clean slate by removing all previous link definitions. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd); chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd); chunk.after = this.stripLinkDefs(chunk.after, defsToAdd); var defs = ""; var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g; var addDefNumber = function (def) { refNumber++; def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:"); defs += "\n" + def; }; // note that // a) the recursive call to getLink cannot go infinite, because by definition // of regex, inner is always a proper substring of wholeMatch, and // b) more than one level of nesting is neither supported by the regex // nor making a lot of sense (the only use case for nesting is a linked image) var getLink = function (wholeMatch, before, inner, afterInner, id, end) { inner = inner.replace(regex, getLink); if (defsToAdd[id]) { addDefNumber(defsToAdd[id]); return before + inner + afterInner + refNumber + end; } return wholeMatch; }; chunk.before = chunk.before.replace(regex, getLink); if (linkDef) { addDefNumber(linkDef); } else { chunk.selection = chunk.selection.replace(regex, getLink); } var refOut = refNumber; chunk.after = chunk.after.replace(regex, getLink); if (chunk.after) { chunk.after = chunk.after.replace(/\n*$/, ""); } if (!chunk.after) { chunk.selection = chunk.selection.replace(/\n*$/, ""); } chunk.after += "\n\n" + defs; return refOut; }; // takes the line as entered into the add link/as image dialog and makes // sure the URL and the optinal title are "nice". function properlyEncoded(linkdef) { return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) { var inQueryString = false; // Having `[^\w\d-./]` in there is just a shortcut that lets us skip // the most common characters in URLs. Replacing that it with `.` would not change // the result, because encodeURI returns those characters unchanged, but it // would mean lots of unnecessary replacement calls. Having `[` and `]` in that // section as well means we do *not* enocde square brackets. These characters are // a strange beast in URLs, but if anything, this causes URLs to be more readable, // and we leave it to the browser to make sure that these links are handled without // problems. link = link.replace(/%(?:[\da-fA-F]{2})|\?|\+|[^\w\d-./[\]]/g, function (match) { // Valid percent encoding. Could just return it as is, but we follow RFC3986 // Section 2.1 which says "For consistency, URI producers and normalizers // should use uppercase hexadecimal digits for all percent-encodings." // Note that we also handle (illegal) stand-alone percent characters by // replacing them with "%25" if (match.length === 3 && match.charAt(0) == "%") { return match.toUpperCase(); } switch (match) { case "?": inQueryString = true; return "?"; break; // In the query string, a plus and a space are identical -- normalize. // Not strictly necessary, but identical behavior to the previous version // of this function. case "+": if (inQueryString) return "%20"; break; } return encodeURI(match); }) if (title) { title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, ""); title = title.replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return title ? link + ' "' + title + '"' : link; }); } commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) { chunk.trimWhitespace(); chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/); var background; if (chunk.endTag.length > 1 && chunk.startTag.length > 0) { chunk.startTag = chunk.startTag.replace(/!?\[/, ""); chunk.endTag = ""; this.addLinkDef(chunk, null); } else { // We're moving start and end tag back into the selection, since (as we're in the else block) we're not // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the // link text. linkEnteredCallback takes care of escaping any brackets. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag; chunk.startTag = chunk.endTag = ""; if (/\n\n/.test(chunk.selection)) { this.addLinkDef(chunk, null); return; } var that = this; // The function to be executed when you enter a link and press OK or Cancel. // Marks up the link and adds the ref. var linkEnteredCallback = function (link) { background.parentNode.removeChild(background); if (link !== null) { // ( $1 // [^\\] anything that's not a backslash // (?:\\\\)* an even number (this includes zero) of backslashes // ) // (?= followed by // [[\]] an opening or closing bracket // ) // // In other words, a non-escaped bracket. These have to be escaped now to make sure they // don't count as the end of the link or similar. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets), // the bracket in one match may be the "not a backslash" character in the next match, so it // should not be consumed by the first match. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the // start of the string, so this also works if the selection begins with a bracket. We cannot solve // this by anchoring with ^, because in the case that the selection starts with two brackets, this // would mean a zero-width match at the start. Since zero-width matches advance the string position, // the first bracket could then not act as the "not a backslash" for the second. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1); var linkDef = " [999]: " + properlyEncoded(link); var num = that.addLinkDef(chunk, linkDef); chunk.startTag = isImage ? "![" : "["; chunk.endTag = "][" + num + "]"; if (!chunk.selection) { if (isImage) { chunk.selection = that.getString("imagedescription"); } else { chunk.selection = that.getString("linkdescription"); } } } postProcessing(); }; background = ui.createBackground(); if (isImage) { if (!this.hooks.insertImageDialog(linkEnteredCallback)) ui.prompt(this.getString("imagedialog"), imageDefaultText, linkEnteredCallback); } else { ui.prompt(this.getString("linkdialog"), linkDefaultText, linkEnteredCallback); } return true; } }; // When making a list, hitting shift-enter will put your cursor on the next line // at the current indent level. commandProto.doAutoindent = function (chunk, postProcessing) { var commandMgr = this, fakeSelection = false; chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n"); // There's no selection, end the cursor wasn't at the end of the line: // The user wants to split the current list item / code line / blockquote line // (for the latter it doesn't really matter) in two. Temporarily select the // (rest of the) line to achieve this. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) { chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) { chunk.selection = wholeMatch; return ""; }); fakeSelection = true; } if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doList) { commandMgr.doList(chunk); } } if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doBlockquote) { commandMgr.doBlockquote(chunk); } } if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { if (commandMgr.doCode) { commandMgr.doCode(chunk); } } if (fakeSelection) { chunk.after = chunk.selection + chunk.after; chunk.selection = ""; } }; commandProto.doBlockquote = function (chunk, postProcessing) { chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/, function (totalMatch, newlinesBefore, text, newlinesAfter) { chunk.before += newlinesBefore; chunk.after = newlinesAfter + chunk.after; return text; }); chunk.before = chunk.before.replace(/(>[ \t]*)$/, function (totalMatch, blankLine) { chunk.selection = blankLine + chunk.selection; return ""; }); chunk.selection = chunk.selection.replace(/^(\s|>)+$/, ""); chunk.selection = chunk.selection || this.getString("quoteexample"); // The original code uses a regular expression to find out how much of the // text *directly before* the selection already was a blockquote: /* if (chunk.before) { chunk.before = chunk.before.replace(/\n?$/, "\n"); } chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/, function (totalMatch) { chunk.startTag = totalMatch; return ""; }); */ // This comes down to: // Go backwards as many lines a possible, such that each line // a) starts with ">", or // b) is almost empty, except for whitespace, or // c) is preceeded by an unbroken chain of non-empty lines // leading up to a line that starts with ">" and at least one more character // and in addition // d) at least one line fulfills a) // // Since this is essentially a backwards-moving regex, it's susceptible to // catstrophic backtracking and can cause the browser to hang; // see e.g. http://meta.stackexchange.com/questions/9807. // // Hence we replaced this by a simple state machine that just goes through the // lines and checks for a), b), and c). var match = "", leftOver = "", line; if (chunk.before) { var lines = chunk.before.replace(/\n$/, "").split("\n"); var inChain = false; for (var i = 0; i < lines.length; i++) { var good = false; line = lines[i]; inChain = inChain && line.length > 0; // c) any non-empty line continues the chain if (/^>/.test(line)) { // a) good = true; if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain inChain = true; } else if (/^[ \t]*$/.test(line)) { // b) good = true; } else { good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain } if (good) { match += line + "\n"; } else { leftOver += match + line; match = "\n"; } } if (!/(^|\n)>/.test(match)) { // d) leftOver += match; match = ""; } } chunk.startTag = match; chunk.before = leftOver; // end of change if (chunk.after) { chunk.after = chunk.after.replace(/^\n?/, "\n"); } chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/, function (totalMatch) { chunk.endTag = totalMatch; return ""; } ); var replaceBlanksInTags = function (useBracket) { var replacement = useBracket ? "> " : ""; if (chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } if (chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } }; if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) { this.wrap(chunk, SETTINGS.lineLength - 2); chunk.selection = chunk.selection.replace(/^/gm, "> "); replaceBlanksInTags(true); chunk.skipLines(); } else { chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, ""); this.unwrap(chunk); replaceBlanksInTags(false); if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n"); } if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n"); } } chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection); if (!/\n/.test(chunk.selection)) { chunk.selection = chunk.selection.replace(/^(> *)/, function (wholeMatch, blanks) { chunk.startTag += blanks; return ""; }); } }; commandProto.doCode = function (chunk, postProcessing) { var hasTextBefore = /\S[ ]*$/.test(chunk.before); var hasTextAfter = /^[ ]*\S/.test(chunk.after); // Use 'four space' markdown if the selection is on its own // line or is multiline. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) { chunk.before = chunk.before.replace(/[ ]{4}$/, function (totalMatch) { chunk.selection = totalMatch + chunk.selection; return ""; }); var nLinesBack = 1; var nLinesForward = 1; if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { nLinesBack = 0; } if (/^\n(\t|[ ]{4,})/.test(chunk.after)) { nLinesForward = 0; } chunk.skipLines(nLinesBack, nLinesForward); if (!chunk.selection) { chunk.startTag = " "; chunk.selection = this.getString("codeexample"); } else { if (/^[ ]{0,3}\S/m.test(chunk.selection)) { if (/\n/.test(chunk.selection)) chunk.selection = chunk.selection.replace(/^/gm, " "); else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior chunk.before += " "; } else { chunk.selection = chunk.selection.replace(/^(?:[ ]{4}|[ ]{0,3}\t)/gm, ""); } } } else { // Use backticks (`) to delimit the code block. chunk.trimWhitespace(); chunk.findTags(/`/, /`/); if (!chunk.startTag && !chunk.endTag) { chunk.startTag = chunk.endTag = "`"; if (!chunk.selection) { chunk.selection = this.getString("codeexample"); } } else if (chunk.endTag && !chunk.startTag) { chunk.before += chunk.endTag; chunk.endTag = ""; } else { chunk.startTag = chunk.endTag = ""; } } }; commandProto.doList = function (chunk, postProcessing, isNumberedList) { // These are identical except at the very beginning and end. // Should probably use the regex extension function to make this clearer. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/; var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/; // The default bullet is a dash but others are possible. // This has nothing to do with the particular HTML bullet, // it's just a markdown bullet. var bullet = "-"; // The number in a numbered list. var num = 1; // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list. var getItemPrefix = function () { var prefix; if (isNumberedList) { prefix = " " + num + ". "; num++; } else { prefix = " " + bullet + " "; } return prefix; }; // Fixes the prefixes of the other list items. var getPrefixedItem = function (itemText) { // The numbering flag is unset when called by autoindent. if (isNumberedList === undefined) { isNumberedList = /^\s*\d/.test(itemText); } // Renumber/bullet the list element. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm, function (_) { return getItemPrefix(); }); return itemText; }; chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null); if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) { chunk.before += chunk.startTag; chunk.startTag = ""; } if (chunk.startTag) { var hasDigits = /\d+[.]/.test(chunk.startTag); chunk.startTag = ""; chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n"); this.unwrap(chunk); chunk.skipLines(); if (hasDigits) { // Have to renumber the bullet points if this is a numbered list. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem); } if (isNumberedList == hasDigits) { return; } } var nLinesUp = 1; chunk.before = chunk.before.replace(previousItemsRegex, function (itemText) { if (/^\s*([*+-])/.test(itemText)) { bullet = re.$1; } nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); if (!chunk.selection) { chunk.selection = this.getString("litem"); } var prefix = getItemPrefix(); var nLinesDown = 1; chunk.after = chunk.after.replace(nextItemsRegex, function (itemText) { nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); chunk.trimWhitespace(true); chunk.skipLines(nLinesUp, nLinesDown, true); chunk.startTag = prefix; var spaces = prefix.replace(/./g, " "); this.wrap(chunk, SETTINGS.lineLength - spaces.length); chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces); }; commandProto.doHeading = function (chunk, postProcessing) { // Remove leading/trailing whitespace and reduce internal spaces to single spaces. chunk.selection = chunk.selection.replace(/\s+/g, " "); chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, ""); // If we clicked the button with no selected text, we just // make a level 2 hash header around some default text. if (!chunk.selection) { chunk.startTag = "## "; chunk.selection = this.getString("headingexample"); chunk.endTag = " ##"; return; } var headerLevel = 0; // The existing header level of the selected text. // Remove any existing hash heading markdown and save the header level. chunk.findTags(/#+[ ]*/, /[ ]*#+/); if (/#+/.test(chunk.startTag)) { headerLevel = re.lastMatch.length; } chunk.startTag = chunk.endTag = ""; // Try to get the current header level by looking for - and = in the line // below the selection. chunk.findTags(null, /\s?(-+|=+)/); if (/=+/.test(chunk.endTag)) { headerLevel = 1; } if (/-+/.test(chunk.endTag)) { headerLevel = 2; } // Skip to the next line so we can create the header markdown. chunk.startTag = chunk.endTag = ""; chunk.skipLines(1, 1); // We make a level 2 header if there is no current header. // If there is a header level, we substract one from the header level. // If it's already a level 1 header, it's removed. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1; if (headerLevelToCreate > 0) { // The button only creates level 1 and 2 underline headers. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner? var headerChar = headerLevelToCreate >= 2 ? "-" : "="; var len = chunk.selection.length; if (len > SETTINGS.lineLength) { len = SETTINGS.lineLength; } chunk.endTag = "\n"; while (len--) { chunk.endTag += headerChar; } } }; commandProto.doHorizontalRule = function (chunk, postProcessing) { chunk.startTag = "----------\n"; chunk.selection = ""; chunk.skipLines(2, 1, true); } })();
JavaScript
(function () { var output, Converter; if (typeof exports === "object" && typeof require === "function") { // we're in a CommonJS (e.g. Node.js) module output = exports; Converter = require("./Markdown.Converter").Converter; } else { output = window.Markdown; Converter = output.Converter; } output.getSanitizingConverter = function () { var converter = new Converter(); converter.hooks.chain("postConversion", sanitizeHtml); converter.hooks.chain("postConversion", balanceTags); return converter; } function sanitizeHtml(html) { return html.replace(/<[^>]*>?/gi, sanitizeTag); } // (tags that can be opened/closed) | (tags that stand alone) var basic_tag_whitelist = /^(<\/?(b|blockquote|code|del|dd|dl|dt|em|h1|h2|h3|i|kbd|li|ol(?: start="\d+")?|p|pre|s|sup|sub|strong|strike|ul)>|<(br|hr)\s?\/?>)$/i; // <a href="url..." optional title>|</a> var a_white = /^(<a\shref="((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)*[\]$]+"(\stitle="[^"<>]+")?\s?>|<\/a>)$/i; // <img src="url..." optional width optional height optional alt optional title var img_white = /^(<img\ssrc="(https?:\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)*[\]$]+"(\swidth="\d{1,3}")?(\sheight="\d{1,3}")?(\salt="[^"<>]*")?(\stitle="[^"<>]*")?\s?\/?>)$/i; function sanitizeTag(tag) { if (tag.match(basic_tag_whitelist) || tag.match(a_white) || tag.match(img_white)) return tag; else return ""; } /// <summary> /// attempt to balance HTML tags in the html string /// by removing any unmatched opening or closing tags /// IMPORTANT: we *assume* HTML has *already* been /// sanitized and is safe/sane before balancing! /// /// adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593 /// </summary> function balanceTags(html) { if (html == "") return ""; var re = /<\/?\w+[^>]*(\s|$|>)/g; // convert everything to lower case; this makes // our case insensitive comparisons easier var tags = html.toLowerCase().match(re); // no HTML tags present? nothing to do; exit now var tagcount = (tags || []).length; if (tagcount == 0) return html; var tagname, tag; var ignoredtags = "<p><img><br><li><hr>"; var match; var tagpaired = []; var tagremove = []; var needsRemoval = false; // loop through matched tags in forward order for (var ctag = 0; ctag < tagcount; ctag++) { tagname = tags[ctag].replace(/<\/?(\w+).*/, "$1"); // skip any already paired tags // and skip tags in our ignore list; assume they're self-closed if (tagpaired[ctag] || ignoredtags.search("<" + tagname + ">") > -1) continue; tag = tags[ctag]; match = -1; if (!/^<\//.test(tag)) { // this is an opening tag // search forwards (next tags), look for closing tags for (var ntag = ctag + 1; ntag < tagcount; ntag++) { if (!tagpaired[ntag] && tags[ntag] == "</" + tagname + ">") { match = ntag; break; } } } if (match == -1) needsRemoval = tagremove[ctag] = true; // mark for removal else tagpaired[match] = true; // mark paired } if (!needsRemoval) return html; // delete all orphaned tags from the string var ctag = 0; html = html.replace(re, function (match) { var res = tagremove[ctag] ? "" : match; ctag++; return res; }); return html; } })();
JavaScript
exports.Converter = require("./Markdown.Converter").Converter; exports.getSanitizingConverter = require("./Markdown.Sanitizer").getSanitizingConverter;
JavaScript
"use strict"; var Markdown; if (typeof exports === "object" && typeof require === "function") // we're in a CommonJS (e.g. Node.js) module Markdown = exports; else Markdown = {}; // The following text is included for historical reasons, but should // be taken with a pinch of salt; it's not all true anymore. // // Wherever possible, Showdown is a straight, line-by-line port // of the Perl version of Markdown. // // This is not a normal parser design; it's basically just a // series of string substitutions. It's hard to read and // maintain this way, but keeping Showdown close to the original // design makes it easier to port new features. // // More importantly, Showdown behaves like markdown.pl in most // edge cases. So web applications can do client-side preview // in Javascript, and then build identical HTML on the server. // // This port needs the new RegExp functionality of ECMA 262, // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers // should do fine. Even with the new regular expression features, // We do a lot of work to emulate Perl's regex functionality. // The tricky changes in this file mostly have the "attacklab:" // label. Major or self-explanatory changes don't. // // Smart diff tools like Araxis Merge will be able to match up // this file with markdown.pl in a useful way. A little tweaking // helps: in a copy of markdown.pl, replace "#" with "//" and // replace "$text" with "text". Be sure to ignore whitespace // and line endings. // // // Usage: // // var text = "Markdown *rocks*."; // // var converter = new Markdown.Converter(); // var html = converter.makeHtml(text); // // alert(html); // // Note: move the sample code to the bottom of this // file before uncommenting it. // (function () { function identity(x) { return x; } function returnFalse(x) { return false; } function HookCollection() { } HookCollection.prototype = { chain: function (hookname, func) { var original = this[hookname]; if (!original) throw new Error("unknown hook " + hookname); if (original === identity) this[hookname] = func; else this[hookname] = function (text) { var args = Array.prototype.slice.call(arguments, 0); args[0] = original.apply(null, args); return func.apply(null, args); }; }, set: function (hookname, func) { if (!this[hookname]) throw new Error("unknown hook " + hookname); this[hookname] = func; }, addNoop: function (hookname) { this[hookname] = identity; }, addFalse: function (hookname) { this[hookname] = returnFalse; } }; Markdown.HookCollection = HookCollection; // g_urls and g_titles allow arbitrary user-entered strings as keys. This // caused an exception (and hence stopped the rendering) when the user entered // e.g. [push] or [__proto__]. Adding a prefix to the actual key prevents this // (since no builtin property starts with "s_"). See // http://meta.stackexchange.com/questions/64655/strange-wmd-bug // (granted, switching from Array() to Object() alone would have left only __proto__ // to be a problem) function SaveHash() { } SaveHash.prototype = { set: function (key, value) { this["s_" + key] = value; }, get: function (key) { return this["s_" + key]; } }; Markdown.Converter = function (OPTIONS) { var pluginHooks = this.hooks = new HookCollection(); // given a URL that was encountered by itself (without markup), should return the link text that's to be given to this link pluginHooks.addNoop("plainLinkText"); // called with the orignal text as given to makeHtml. The result of this plugin hook is the actual markdown source that will be cooked pluginHooks.addNoop("preConversion"); // called with the text once all normalizations have been completed (tabs to spaces, line endings, etc.), but before any conversions have pluginHooks.addNoop("postNormalization"); // Called with the text before / after creating block elements like code blocks and lists. Note that this is called recursively // with inner content, e.g. it's called with the full text, and then only with the content of a blockquote. The inner // call will receive outdented text. pluginHooks.addNoop("preBlockGamut"); pluginHooks.addNoop("postBlockGamut"); // called with the text of a single block element before / after the span-level conversions (bold, code spans, etc.) have been made pluginHooks.addNoop("preSpanGamut"); pluginHooks.addNoop("postSpanGamut"); // called with the final cooked HTML code. The result of this plugin hook is the actual output of makeHtml pluginHooks.addNoop("postConversion"); // // Private state of the converter instance: // // Global hashes, used by various utility routines var g_urls; var g_titles; var g_html_blocks; // Used to track when we're inside an ordered or unordered list // (see _ProcessListItems() for details): var g_list_level; OPTIONS = OPTIONS || {}; var asciify = identity, deasciify = identity; if (OPTIONS.nonAsciiLetters) { /* In JavaScript regular expressions, \w only denotes [a-zA-Z0-9_]. * That's why there's inconsistent handling e.g. with intra-word bolding * of Japanese words. That's why we do the following if OPTIONS.nonAsciiLetters * is true: * * Before doing bold and italics, we find every instance * of a unicode word character in the Markdown source that is not * matched by \w, and the letter "Q". We take the character's code point * and encode it in base 51, using the "digits" * * A, B, ..., P, R, ..., Y, Z, a, b, ..., y, z * * delimiting it with "Q" on both sides. For example, the source * * > In Chinese, the smurfs are called 藍精靈, meaning "blue spirits". * * turns into * * > In Chinese, the smurfs are called QNIhQQMOIQQOuUQ, meaning "blue spirits". * * Since everything that is a letter in Unicode is now a letter (or * several letters) in ASCII, \w and \b should always do the right thing. * * After the bold/italic conversion, we decode again; since "Q" was encoded * alongside all non-ascii characters (as "QBfQ"), and the conversion * will not generate "Q", the only instances of that letter should be our * encoded characters. And since the conversion will not break words, the * "Q...Q" should all still be in one piece. * * We're using "Q" as the delimiter because it's probably one of the * rarest characters, and also because I can't think of any special behavior * that would ever be triggered by this letter (to use a silly example, if we * delimited with "H" on the left and "P" on the right, then "Ψ" would be * encoded as "HTTP", which may cause special behavior). The latter would not * actually be a huge issue for bold/italic, but may be if we later use it * in other places as well. * */ (function () { var lettersThatJavaScriptDoesNotKnowAndQ = /[Q\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376-\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0523\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0621-\u064a\u0660-\u0669\u066e-\u066f\u0671-\u06d3\u06d5\u06e5-\u06e6\u06ee-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07c0-\u07ea\u07f4-\u07f5\u07fa\u0904-\u0939\u093d\u0950\u0958-\u0961\u0966-\u096f\u0971-\u0972\u097b-\u097f\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc-\u09dd\u09df-\u09e1\u09e6-\u09f1\u0a05-\u0a0a\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a66-\u0a6f\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0-\u0ae1\u0ae6-\u0aef\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32-\u0b33\u0b35-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b66-\u0b6f\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0be6-\u0bef\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58-\u0c59\u0c60-\u0c61\u0c66-\u0c6f\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0-\u0ce1\u0ce6-\u0cef\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d3d\u0d60-\u0d61\u0d66-\u0d6f\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32-\u0e33\u0e40-\u0e46\u0e50-\u0e59\u0e81-\u0e82\u0e84\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa-\u0eab\u0ead-\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0ed0-\u0ed9\u0edc-\u0edd\u0f00\u0f20-\u0f29\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8b\u1000-\u102a\u103f-\u1049\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070\u1075-\u1081\u108e\u1090-\u1099\u10a0-\u10c5\u10d0-\u10fa\u10fc\u1100-\u1159\u115f-\u11a2\u11a8-\u11f9\u1200-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u1676\u1681-\u169a\u16a0-\u16ea\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u17e0-\u17e9\u1810-\u1819\u1820-\u1877\u1880-\u18a8\u18aa\u1900-\u191c\u1946-\u196d\u1970-\u1974\u1980-\u19a9\u19c1-\u19c7\u19d0-\u19d9\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b50-\u1b59\u1b83-\u1ba0\u1bae-\u1bb9\u1c00-\u1c23\u1c40-\u1c49\u1c4d-\u1c7d\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u203f-\u2040\u2054\u2071\u207f\u2090-\u2094\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2183-\u2184\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2c6f\u2c71-\u2c7d\u2c80-\u2ce4\u2d00-\u2d25\u2d30-\u2d65\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3006\u3031-\u3035\u303b-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31b7\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fc3\ua000-\ua48c\ua500-\ua60c\ua610-\ua62b\ua640-\ua65f\ua662-\ua66e\ua67f-\ua697\ua717-\ua71f\ua722-\ua788\ua78b-\ua78c\ua7fb-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8d0-\ua8d9\ua900-\ua925\ua930-\ua946\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa50-\uaa59\uac00-\ud7a3\uf900-\ufa2d\ufa30-\ufa6a\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe33-\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]/g; var cp_Q = "Q".charCodeAt(0); var cp_A = "A".charCodeAt(0); var cp_Z = "Z".charCodeAt(0); var dist_Za = "a".charCodeAt(0) - cp_Z - 1; asciify = function(text) { return text.replace(lettersThatJavaScriptDoesNotKnowAndQ, function (m) { var c = m.charCodeAt(0); var s = ""; var v; while (c > 0) { v = (c % 51) + cp_A; if (v >= cp_Q) v++; if (v > cp_Z) v += dist_Za; s = String.fromCharCode(v) + s; c = c / 51 | 0; } return "Q" + s + "Q"; }) }; deasciify = function(text) { return text.replace(/Q([A-PR-Za-z]{1,3})Q/g, function (m, s) { var c = 0; var v; for (var i = 0; i < s.length; i++) { v = s.charCodeAt(i); if (v > cp_Z) v -= dist_Za; if (v > cp_Q) v--; v -= cp_A; c = (c * 51) + v; } return String.fromCharCode(c); }) } })(); } var _DoItalicsAndBold = OPTIONS.asteriskIntraWordEmphasis ? _DoItalicsAndBold_AllowIntrawordWithAsterisk : _DoItalicsAndBoldStrict; this.makeHtml = function (text) { // // Main function. The order in which other subs are called here is // essential. Link and image substitutions need to happen before // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a> // and <img> tags get encoded. // // This will only happen if makeHtml on the same converter instance is called from a plugin hook. // Don't do that. if (g_urls) throw new Error("Recursive call to converter.makeHtml"); // Create the private state objects. g_urls = new SaveHash(); g_titles = new SaveHash(); g_html_blocks = []; g_list_level = 0; text = pluginHooks.preConversion(text); // attacklab: Replace ~ with ~T // This lets us use tilde as an escape char to avoid md5 hashes // The choice of character is arbitray; anything that isn't // magic in Markdown will work. text = text.replace(/~/g, "~T"); // attacklab: Replace $ with ~D // RegExp interprets $ as a special character // when it's in a replacement string text = text.replace(/\$/g, "~D"); // Standardize line endings text = text.replace(/\r\n/g, "\n"); // DOS to Unix text = text.replace(/\r/g, "\n"); // Mac to Unix // Make sure text begins and ends with a couple of newlines: text = "\n\n" + text + "\n\n"; // Convert all tabs to spaces. text = _Detab(text); // Strip any lines consisting only of spaces and tabs. // This makes subsequent regexen easier to write, because we can // match consecutive blank lines with /\n+/ instead of something // contorted like /[ \t]*\n+/ . text = text.replace(/^[ \t]+$/mg, ""); text = pluginHooks.postNormalization(text); // Turn block-level HTML blocks into hash entries text = _HashHTMLBlocks(text); // Strip link definitions, store in hashes. text = _StripLinkDefinitions(text); text = _RunBlockGamut(text); text = _UnescapeSpecialChars(text); // attacklab: Restore dollar signs text = text.replace(/~D/g, "$$"); // attacklab: Restore tildes text = text.replace(/~T/g, "~"); text = pluginHooks.postConversion(text); g_html_blocks = g_titles = g_urls = null; return text; }; function _StripLinkDefinitions(text) { // // Strips link definitions from text, stores the URLs and titles in // hash references. // // Link defs are in the form: ^[id]: url "optional title" /* text = text.replace(/ ^[ ]{0,3}\[([^\[\]]+)\]: // id = $1 attacklab: g_tab_width - 1 [ \t]* \n? // maybe *one* newline [ \t]* <?(\S+?)>? // url = $2 (?=\s|$) // lookahead for whitespace instead of the lookbehind removed below [ \t]* \n? // maybe one newline [ \t]* ( // (potential) title = $3 (\n*) // any lines skipped = $4 attacklab: lookbehind removed [ \t]+ ["(] (.+?) // title = $5 [")] [ \t]* )? // title is optional (?:\n+|$) /gm, function(){...}); */ text = text.replace(/^[ ]{0,3}\[([^\[\]]+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?(?=\s|$)[ \t]*\n?[ \t]*((\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm, function (wholeMatch, m1, m2, m3, m4, m5) { m1 = m1.toLowerCase(); g_urls.set(m1, _EncodeAmpsAndAngles(m2)); // Link IDs are case-insensitive if (m4) { // Oops, found blank lines, so it's not a title. // Put back the parenthetical statement we stole. return m3; } else if (m5) { g_titles.set(m1, m5.replace(/"/g, "&quot;")); } // Completely remove the definition from the text return ""; } ); return text; } function _HashHTMLBlocks(text) { // Hashify HTML blocks: // We only want to do this for block-level HTML tags, such as headers, // lists, and tables. That's because we still want to wrap <p>s around // "paragraphs" that are wrapped in non-block-level tags, such as anchors, // phrase emphasis, and spans. The list of tags we're looking for is // hard-coded: var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del" var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math" // First, look for nested blocks, e.g.: // <div> // <div> // tags for inner block must be indented. // </div> // </div> // // The outermost tags must start at the left margin for this to match, and // the inner nested divs must be indented. // We need to do this before the next, more liberal match, because the next // match will start at the first `<div>` and stop at the first `</div>`. // attacklab: This regex can be expensive when it fails. /* text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_a) // start tag = $2 \b // word break // attacklab: hack around khtml/pcre bug... [^\r]*?\n // any number of lines, minimally matching </\2> // the matching end tag [ \t]* // trailing spaces/tabs (?=\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm, hashMatch); // // Now match more liberally, simply from `\n<tag>` to `</tag>\n` // /* text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_b) // start tag = $2 \b // word break // attacklab: hack around khtml/pcre bug... [^\r]*? // any number of lines, minimally matching .*</\2> // the matching end tag [ \t]* // trailing spaces/tabs (?=\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm, hashMatch); // Special case just for <hr />. It was easier to make a special case than // to make the other regex more complicated. /* text = text.replace(/ \n // Starting after a blank line [ ]{0,3} ( // save in $1 (<(hr) // start tag = $2 \b // word break ([^<>])*? \/?>) // the matching end tag [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/\n[ ]{0,3}((<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashMatch); // Special case for standalone HTML comments: /* text = text.replace(/ \n\n // Starting after a blank line [ ]{0,3} // attacklab: g_tab_width - 1 ( // save in $1 <! (--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--) // see http://www.w3.org/TR/html-markup/syntax.html#comments and http://meta.stackexchange.com/q/95256 > [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/\n\n[ ]{0,3}(<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>[ \t]*(?=\n{2,}))/g, hashMatch); // PHP and ASP-style processor instructions (<?...?> and <%...%>) /* text = text.replace(/ (?: \n\n // Starting after a blank line ) ( // save in $1 [ ]{0,3} // attacklab: g_tab_width - 1 (?: <([?%]) // $2 [^\r]*? \2> ) [ \t]* (?=\n{2,}) // followed by a blank line ) /g,hashMatch); */ text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashMatch); return text; } function hashBlock(text) { text = text.replace(/(^\n+|\n+$)/g, ""); // Replace the element text with a marker ("~KxK" where x is its key) return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n"; } function hashMatch(wholeMatch, m1) { return hashBlock(m1); } var blockGamutHookCallback = function (t) { return _RunBlockGamut(t); } function _RunBlockGamut(text, doNotUnhash) { // // These are all the transformations that form block-level // tags like paragraphs, headers, and list items. // text = pluginHooks.preBlockGamut(text, blockGamutHookCallback); text = _DoHeaders(text); // Do Horizontal Rules: var replacement = "<hr />\n"; text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, replacement); text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm, replacement); text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm, replacement); text = _DoLists(text); text = _DoCodeBlocks(text); text = _DoBlockQuotes(text); text = pluginHooks.postBlockGamut(text, blockGamutHookCallback); // We already ran _HashHTMLBlocks() before, in Markdown(), but that // was to escape raw HTML in the original Markdown source. This time, // we're escaping the markup we've just created, so that we don't wrap // <p> tags around block-level tags. text = _HashHTMLBlocks(text); text = _FormParagraphs(text, doNotUnhash); return text; } function _RunSpanGamut(text) { // // These are all the transformations that occur *within* block-level // tags like paragraphs, headers, and list items. // text = pluginHooks.preSpanGamut(text); text = _DoCodeSpans(text); text = _EscapeSpecialCharsWithinTagAttributes(text); text = _EncodeBackslashEscapes(text); // Process anchor and image tags. Images must come first, // because ![foo][f] looks like an anchor. text = _DoImages(text); text = _DoAnchors(text); // Make links out of things like `<http://example.com/>` // Must come after _DoAnchors(), because you can use < and > // delimiters in inline links like [this](<url>). text = _DoAutoLinks(text); text = text.replace(/~P/g, "://"); // put in place to prevent autolinking; reset now text = _EncodeAmpsAndAngles(text); text = _DoItalicsAndBold(text); // Do hard breaks: text = text.replace(/ +\n/g, " <br>\n"); text = pluginHooks.postSpanGamut(text); return text; } function _EscapeSpecialCharsWithinTagAttributes(text) { // // Within tags -- meaning between < and > -- encode [\ ` * _] so they // don't conflict with their use in Markdown for code, italics and strong. // // Build a regex to find HTML tags and comments. See Friedl's // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. // SE: changed the comment part of the regex var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>)/gi; text = text.replace(regex, function (wholeMatch) { var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`"); tag = escapeCharacters(tag, wholeMatch.charAt(1) == "!" ? "\\`*_/" : "\\`*_"); // also escape slashes in comments to prevent autolinking there -- http://meta.stackexchange.com/questions/95987 return tag; }); return text; } function _DoAnchors(text) { if (text.indexOf("[") === -1) return text; // // Turn Markdown link shortcuts into XHTML <a> tags. // // // First, handle reference-style links: [link text] [id] // /* text = text.replace(/ ( // wrap whole match in $1 \[ ( (?: \[[^\]]*\] // allow brackets nested one level | [^\[] // or anything else )* ) \] [ ]? // one optional space (?:\n[ ]*)? // one optional newline followed by spaces \[ (.*?) // id = $3 \] ) ()()()() // pad remaining backreferences /g, writeAnchorTag); */ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag); // // Next, inline-style links: [link text](url "optional title") // /* text = text.replace(/ ( // wrap whole match in $1 \[ ( (?: \[[^\]]*\] // allow brackets nested one level | [^\[\]] // or anything else )* ) \] \( // literal paren [ \t]* () // no id, so leave $3 empty <?( // href = $4 (?: \([^)]*\) // allow one level of (correctly nested) parens (think MSDN) | [^()\s] )*? )>? [ \t]* ( // $5 (['"]) // quote char = $6 (.*?) // Title = $7 \6 // matching quote [ \t]* // ignore any spaces/tabs between closing quote and ) )? // title is optional \) ) /g, writeAnchorTag); */ text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?((?:\([^)]*\)|[^()\s])*?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag); // // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link test][1] // or [link test](/foo) // /* text = text.replace(/ ( // wrap whole match in $1 \[ ([^\[\]]+) // link text = $2; can't contain '[' or ']' \] ) ()()()()() // pad rest of backreferences /g, writeAnchorTag); */ text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); return text; } function writeAnchorTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) { if (m7 == undefined) m7 = ""; var whole_match = m1; var link_text = m2.replace(/:\/\//g, "~P"); // to prevent auto-linking withing the link. will be converted back after the auto-linker runs var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (url == "") { if (link_id == "") { // lower-case and turn embedded newlines into spaces link_id = link_text.toLowerCase().replace(/ ?\n/g, " "); } url = "#" + link_id; if (g_urls.get(link_id) != undefined) { url = g_urls.get(link_id); if (g_titles.get(link_id) != undefined) { title = g_titles.get(link_id); } } else { if (whole_match.search(/\(\s*\)$/m) > -1) { // Special case for explicit empty url url = ""; } else { return whole_match; } } } url = attributeSafeUrl(url); var result = "<a href=\"" + url + "\""; if (title != "") { title = attributeEncode(title); title = escapeCharacters(title, "*_"); result += " title=\"" + title + "\""; } result += ">" + link_text + "</a>"; return result; } function _DoImages(text) { if (text.indexOf("![") === -1) return text; // // Turn Markdown image shortcuts into <img> tags. // // // First, handle reference-style labeled images: ![alt text][id] // /* text = text.replace(/ ( // wrap whole match in $1 !\[ (.*?) // alt text = $2 \] [ ]? // one optional space (?:\n[ ]*)? // one optional newline followed by spaces \[ (.*?) // id = $3 \] ) ()()()() // pad rest of backreferences /g, writeImageTag); */ text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag); // // Next, handle inline images: ![alt text](url "optional title") // Don't forget: encode * and _ /* text = text.replace(/ ( // wrap whole match in $1 !\[ (.*?) // alt text = $2 \] \s? // One optional whitespace character \( // literal paren [ \t]* () // no id, so leave $3 empty <?(\S+?)>? // src url = $4 [ \t]* ( // $5 (['"]) // quote char = $6 (.*?) // title = $7 \6 // matching quote [ \t]* )? // title is optional \) ) /g, writeImageTag); */ text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag); return text; } function attributeEncode(text) { // unconditionally replace angle brackets here -- what ends up in an attribute (e.g. alt or title) // never makes sense to have verbatim HTML in it (and the sanitizer would totally break it) return text.replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); } function writeImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) { var whole_match = m1; var alt_text = m2; var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (!title) title = ""; if (url == "") { if (link_id == "") { // lower-case and turn embedded newlines into spaces link_id = alt_text.toLowerCase().replace(/ ?\n/g, " "); } url = "#" + link_id; if (g_urls.get(link_id) != undefined) { url = g_urls.get(link_id); if (g_titles.get(link_id) != undefined) { title = g_titles.get(link_id); } } else { return whole_match; } } alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()"); url = escapeCharacters(url, "*_"); var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\""; // attacklab: Markdown.pl adds empty title attributes to images. // Replicate this bug. //if (title != "") { title = attributeEncode(title); title = escapeCharacters(title, "*_"); result += " title=\"" + title + "\""; //} result += " />"; return result; } function _DoHeaders(text) { // Setext-style headers: // Header 1 // ======== // // Header 2 // -------- // text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm, function (wholeMatch, m1) { return "<h1>" + _RunSpanGamut(m1) + "</h1>\n\n"; } ); text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, function (matchFound, m1) { return "<h2>" + _RunSpanGamut(m1) + "</h2>\n\n"; } ); // atx-style headers: // # Header 1 // ## Header 2 // ## Header 2 with closing hashes ## // ... // ###### Header 6 // /* text = text.replace(/ ^(\#{1,6}) // $1 = string of #'s [ \t]* (.+?) // $2 = Header text [ \t]* \#* // optional closing #'s (not counted) \n+ /gm, function() {...}); */ text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, function (wholeMatch, m1, m2) { var h_level = m1.length; return "<h" + h_level + ">" + _RunSpanGamut(m2) + "</h" + h_level + ">\n\n"; } ); return text; } function _DoLists(text, isInsideParagraphlessListItem) { // // Form HTML ordered (numbered) and unordered (bulleted) lists. // // attacklab: add sentinel to hack around khtml/safari bug: // http://bugs.webkit.org/show_bug.cgi?id=11231 text += "~0"; // Re-usable pattern to match any entirel ul or ol list: /* var whole_list = / ( // $1 = whole list ( // $2 [ ]{0,3} // attacklab: g_tab_width - 1 ([*+-]|\d+[.]) // $3 = first list item marker [ \t]+ ) [^\r]+? ( // $4 ~0 // sentinel for workaround; should be $ | \n{2,} (?=\S) (?! // Negative lookahead for another list item marker [ \t]* (?:[*+-]|\d+[.])[ \t]+ ) ) ) /g */ var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; if (g_list_level) { text = text.replace(whole_list, function (wholeMatch, m1, m2) { var list = m1; var list_type = (m2.search(/[*+-]/g) > -1) ? "ul" : "ol"; var first_number; if (list_type === "ol") first_number = parseInt(m2, 10) var result = _ProcessListItems(list, list_type, isInsideParagraphlessListItem); // Trim any trailing whitespace, to put the closing `</$list_type>` // up on the preceding line, to get it past the current stupid // HTML block parser. This is a hack to work around the terrible // hack that is the HTML block parser. result = result.replace(/\s+$/, ""); var opening = "<" + list_type; if (first_number && first_number !== 1) opening += " start=\"" + first_number + "\""; result = opening + ">" + result + "</" + list_type + ">\n"; return result; }); } else { whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; text = text.replace(whole_list, function (wholeMatch, m1, m2, m3) { var runup = m1; var list = m2; var list_type = (m3.search(/[*+-]/g) > -1) ? "ul" : "ol"; var first_number; if (list_type === "ol") first_number = parseInt(m3, 10) var result = _ProcessListItems(list, list_type); var opening = "<" + list_type; if (first_number && first_number !== 1) opening += " start=\"" + first_number + "\""; result = runup + opening + ">\n" + result + "</" + list_type + ">\n"; return result; }); } // attacklab: strip sentinel text = text.replace(/~0/, ""); return text; } var _listItemMarkers = { ol: "\\d+[.]", ul: "[*+-]" }; function _ProcessListItems(list_str, list_type, isInsideParagraphlessListItem) { // // Process the contents of a single ordered or unordered list, splitting it // into individual list items. // // list_type is either "ul" or "ol". // The $g_list_level global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // // We do this because when we're not inside a list, we want to treat // something like this: // // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. "1." or "a.". g_list_level++; // trim trailing blank lines: list_str = list_str.replace(/\n{2,}$/, "\n"); // attacklab: add sentinel to emulate \z list_str += "~0"; // In the original attacklab showdown, list_type was not given to this function, and anything // that matched /[*+-]|\d+[.]/ would just create the next <li>, causing this mismatch: // // Markdown rendered by WMD rendered by MarkdownSharp // ------------------------------------------------------------------ // 1. first 1. first 1. first // 2. second 2. second 2. second // - third 3. third * third // // We changed this to behave identical to MarkdownSharp. This is the constructed RegEx, // with {MARKER} being one of \d+[.] or [*+-], depending on list_type: /* list_str = list_str.replace(/ (^[ \t]*) // leading whitespace = $1 ({MARKER}) [ \t]+ // list marker = $2 ([^\r]+? // list item text = $3 (\n+) ) (?= (~0 | \2 ({MARKER}) [ \t]+) ) /gm, function(){...}); */ var marker = _listItemMarkers[list_type]; var re = new RegExp("(^[ \\t]*)(" + marker + ")[ \\t]+([^\\r]+?(\\n+))(?=(~0|\\1(" + marker + ")[ \\t]+))", "gm"); var last_item_had_a_double_newline = false; list_str = list_str.replace(re, function (wholeMatch, m1, m2, m3) { var item = m3; var leading_space = m1; var ends_with_double_newline = /\n\n$/.test(item); var contains_double_newline = ends_with_double_newline || item.search(/\n{2,}/) > -1; if (contains_double_newline || last_item_had_a_double_newline) { item = _RunBlockGamut(_Outdent(item), /* doNotUnhash = */true); } else { // Recursion for sub-lists: item = _DoLists(_Outdent(item), /* isInsideParagraphlessListItem= */ true); item = item.replace(/\n$/, ""); // chomp(item) if (!isInsideParagraphlessListItem) // only the outer-most item should run this, otherwise it's run multiple times for the inner ones item = _RunSpanGamut(item); } last_item_had_a_double_newline = ends_with_double_newline; return "<li>" + item + "</li>\n"; } ); // attacklab: strip sentinel list_str = list_str.replace(/~0/g, ""); g_list_level--; return list_str; } function _DoCodeBlocks(text) { // // Process Markdown `<pre><code>` blocks. // /* text = text.replace(/ (?:\n\n|^) ( // $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{4}|\t) // Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width .*\n+ )+ ) (\n*[ ]{0,3}[^ \t\n]|(?=~0)) // attacklab: g_tab_width /g ,function(){...}); */ // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug text += "~0"; text = text.replace(/(?:\n\n|^\n?)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g, function (wholeMatch, m1, m2) { var codeblock = m1; var nextChar = m2; codeblock = _EncodeCode(_Outdent(codeblock)); codeblock = _Detab(codeblock); codeblock = codeblock.replace(/^\n+/g, ""); // trim leading newlines codeblock = codeblock.replace(/\n+$/g, ""); // trim trailing whitespace codeblock = "<pre><code>" + codeblock + "\n</code></pre>"; return "\n\n" + codeblock + "\n\n" + nextChar; } ); // attacklab: strip sentinel text = text.replace(/~0/, ""); return text; } function _DoCodeSpans(text) { // // * Backtick quotes are used for <code></code> spans. // // * You can use multiple backticks as the delimiters if you want to // include literal backticks in the code span. So, this input: // // Just type ``foo `bar` baz`` at the prompt. // // Will translate to: // // <p>Just type <code>foo `bar` baz</code> at the prompt.</p> // // There's no arbitrary limit to the number of backticks you // can use as delimters. If you need three consecutive backticks // in your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // // ... type `` `bar` `` ... // // Turns to: // // ... type <code>`bar`</code> ... // /* text = text.replace(/ (^|[^\\`]) // Character before opening ` can't be a backslash or backtick (`+) // $2 = Opening run of ` (?!`) // and no more backticks -- match the full run ( // $3 = The code block [^\r]*? [^`] // attacklab: work around lack of lookbehind ) \2 // Matching closer (?!`) /gm, function(){...}); */ text = text.replace(/(^|[^\\`])(`+)(?!`)([^\r]*?[^`])\2(?!`)/gm, function (wholeMatch, m1, m2, m3, m4) { var c = m3; c = c.replace(/^([ \t]*)/g, ""); // leading whitespace c = c.replace(/[ \t]*$/g, ""); // trailing whitespace c = _EncodeCode(c); c = c.replace(/:\/\//g, "~P"); // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. Will be converted back after the auto-linker runs. return m1 + "<code>" + c + "</code>"; } ); return text; } function _EncodeCode(text) { // // Encode/escape certain characters inside Markdown code runs. // The point is that in code, these characters are literals, // and lose their special Markdown meanings. // // Encode all ampersands; HTML entities are not // entities within a Markdown code span. text = text.replace(/&/g, "&amp;"); // Do the angle bracket song and dance: text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); // Now, escape characters that are magic in Markdown: text = escapeCharacters(text, "\*_{}[]\\", false); // jj the line above breaks this: //--- //* Item // 1. Subitem // special char: * //--- return text; } function _DoItalicsAndBoldStrict(text) { if (text.indexOf("*") === -1 && text.indexOf("_") === - 1) return text; text = asciify(text); // <strong> must go first: // (^|[\W_]) Start with a non-letter or beginning of string. Store in \1. // (?:(?!\1)|(?=^)) Either the next character is *not* the same as the previous, // or we started at the end of the string (in which case the previous // group had zero width, so we're still there). Because the next // character is the marker, this means that if there are e.g. multiple // underscores in a row, we can only match the left-most ones (which // prevents foo___bar__ from getting bolded) // (\*|_) The marker character itself, asterisk or underscore. Store in \2. // \2 The marker again, since bold needs two. // (?=\S) The first bolded character cannot be a space. // ([^\r]*?\S) The actual bolded string. At least one character, and it cannot *end* // with a space either. Note that like in many other places, [^\r] is // just a workaround for JS' lack of single-line regexes; it's equivalent // to a . in an /s regex, because the string cannot contain any \r (they // are removed in the normalizing step). // \2\2 The marker character, twice -- end of bold. // (?!\2) Not followed by another marker character (ensuring that we match the // rightmost two in a longer row)... // (?=[\W_]|$) ...but by any other non-word character or the end of string. text = text.replace(/(^|[\W_])(?:(?!\1)|(?=^))(\*|_)\2(?=\S)([^\r]*?\S)\2\2(?!\2)(?=[\W_]|$)/g, "$1<strong>$3</strong>"); // This is almost identical to the <strong> regex, except 1) there's obviously just one marker // character, and 2) the italicized string cannot contain the marker character. text = text.replace(/(^|[\W_])(?:(?!\1)|(?=^))(\*|_)(?=\S)((?:(?!\2)[^\r])*?\S)\2(?!\2)(?=[\W_]|$)/g, "$1<em>$3</em>"); return deasciify(text); } function _DoItalicsAndBold_AllowIntrawordWithAsterisk(text) { if (text.indexOf("*") === -1 && text.indexOf("_") === - 1) return text; text = asciify(text); // <strong> must go first: // (?=[^\r][*_]|[*_]) Optimization only, to find potentially relevant text portions faster. Minimally slower in Chrome, but much faster in IE. // ( Store in \1. This is the last character before the delimiter // ^ Either we're at the start of the string (i.e. there is no last character)... // | ... or we allow one of the following: // (?= (lookahead; we're not capturing this, just listing legal possibilities) // \W__ If the delimiter is __, then this last character must be non-word non-underscore (extra-word emphasis only) // | // (?!\*)[\W_]\*\* If the delimiter is **, then this last character can be non-word non-asterisk (extra-word emphasis)... // | // \w\*\*\w ...or it can be word/underscore, but only if the first bolded character is such a character as well (intra-word emphasis) // ) // [^\r] actually capture the character (can't use `.` since it could be \n) // ) // (\*\*|__) Store in \2: the actual delimiter // (?!\2) not followed by the delimiter again (at most one more asterisk/underscore is allowed) // (?=\S) the first bolded character can't be a space // ( Store in \3: the bolded string // // (?:| Look at all bolded characters except for the last one. Either that's empty, meaning only a single character was bolded... // [^\r]*? ... otherwise take arbitrary characters, minimally matching; that's all bolded characters except for the last *two* // (?!\2) the last two characters cannot be the delimiter itself (because that would mean four underscores/asterisks in a row) // [^\r] capture the next-to-last bolded character // ) // (?= lookahead at the very last bolded char and what comes after // \S_ for underscore-bolding, it can be any non-space // | // \w for asterisk-bolding (otherwise the previous alternative would've matched, since \w implies \S), either the last char is word/underscore... // | // \S\*\*(?:[\W_]|$) ... or it's any other non-space, but in that case the character *after* the delimiter may not be a word character // ) // . actually capture the last character (can use `.` this time because the lookahead ensures \S in all cases) // ) // (?= lookahead; list the legal possibilities for the closing delimiter and its following character // __(?:\W|$) for underscore-bolding, the following character (if any) must be non-word non-underscore // | // \*\*(?:[^*]|$) for asterisk-bolding, any non-asterisk is allowed (note we already ensured above that it's not a word character if the last bolded character wasn't one) // ) // \2 actually capture the closing delimiter (and make sure that it matches the opening one) text = text.replace(/(?=[^\r][*_]|[*_])(^|(?=\W__|(?!\*)[\W_]\*\*|\w\*\*\w)[^\r])(\*\*|__)(?!\2)(?=\S)((?:|[^\r]*?(?!\2)[^\r])(?=\S_|\w|\S\*\*(?:[\W_]|$)).)(?=__(?:\W|$)|\*\*(?:[^*]|$))\2/g, "$1<strong>$3</strong>"); // now <em>: // (?=[^\r][*_]|[*_]) Optimization, see above. // ( Store in \1. This is the last character before the delimiter // ^ Either we're at the start of the string (i.e. there is no last character)... // | ... or we allow one of the following: // (?= (lookahead; we're not capturing this, just listing legal possibilities) // \W_ If the delimiter is _, then this last character must be non-word non-underscore (extra-word emphasis only) // | // (?!\*) otherwise, we list two possiblities for * as the delimiter; in either case, the last characters cannot be an asterisk itself // (?: // [\W_]\* this last character can be non-word (extra-word emphasis)... // | // \D\*(?=\w)\D ...or it can be word (otherwise the first alternative would've matched), but only if // a) the first italicized character is such a character as well (intra-word emphasis), and // b) neither character on either side of the asterisk is a digit // ) // ) // [^\r] actually capture the character (can't use `.` since it could be \n) // ) // (\*|_) Store in \2: the actual delimiter // (?!\2\2\2) not followed by more than two more instances of the delimiter // (?=\S) the first italicized character can't be a space // ( Store in \3: the italicized string // (?:(?!\2)[^\r])*? arbitrary characters except for the delimiter itself, minimally matching // (?= lookahead at the very last italicized char and what comes after // [^\s_]_ for underscore-italicizing, it can be any non-space non-underscore // | // (?=\w)\D\*\D for asterisk-italicizing, either the last char is word/underscore *and* neither character on either side of the asterisk is a digit... // | // [^\s*]\*(?:[\W_]|$) ... or that last char is any other non-space non-asterisk, but then the character after the delimiter (if any) must be non-word // ) // . actually capture the last character (can use `.` this time because the lookahead ensures \S in all cases) // ) // (?= lookahead; list the legal possibilities for the closing delimiter and its following character // _(?:\W|$) for underscore-italicizing, the following character (if any) must be non-word non-underscore // | // \*(?:[^*]|$) for asterisk-italicizing, any non-asterisk is allowed; all other restrictions have already been ensured in the previous lookahead // ) // \2 actually capture the closing delimiter (and make sure that it matches the opening one) text = text.replace(/(?=[^\r][*_]|[*_])(^|(?=\W_|(?!\*)(?:[\W_]\*|\D\*(?=\w)\D))[^\r])(\*|_)(?!\2\2\2)(?=\S)((?:(?!\2)[^\r])*?(?=[^\s_]_|(?=\w)\D\*\D|[^\s*]\*(?:[\W_]|$)).)(?=_(?:\W|$)|\*(?:[^*]|$))\2/g, "$1<em>$3</em>"); return deasciify(text); } function _DoBlockQuotes(text) { /* text = text.replace(/ ( // Wrap whole match in $1 ( ^[ \t]*>[ \t]? // '>' at the start of a line .+\n // rest of the first line (.+\n)* // subsequent consecutive lines \n* // blanks )+ ) /gm, function(){...}); */ text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, function (wholeMatch, m1) { var bq = m1; // attacklab: hack around Konqueror 3.5.4 bug: // "----------bug".replace(/^-/g,"") == "bug" bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0"); // trim one level of quoting // attacklab: clean up hack bq = bq.replace(/~0/g, ""); bq = bq.replace(/^[ \t]+$/gm, ""); // trim whitespace-only lines bq = _RunBlockGamut(bq); // recurse bq = bq.replace(/(^|\n)/g, "$1 "); // These leading spaces screw with <pre> content, so we need to fix that: bq = bq.replace( /(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) { var pre = m1; // attacklab: hack around Konqueror 3.5.4 bug: pre = pre.replace(/^ /mg, "~0"); pre = pre.replace(/~0/g, ""); return pre; }); return hashBlock("<blockquote>\n" + bq + "\n</blockquote>"); } ); return text; } function _FormParagraphs(text, doNotUnhash) { // // Params: // $text - string to process with html <p> tags // // Strip leading and trailing lines: text = text.replace(/^\n+/g, ""); text = text.replace(/\n+$/g, ""); var grafs = text.split(/\n{2,}/g); var grafsOut = []; var markerRe = /~K(\d+)K/; // // Wrap <p> tags. // var end = grafs.length; for (var i = 0; i < end; i++) { var str = grafs[i]; // if this is an HTML marker, copy it if (markerRe.test(str)) { grafsOut.push(str); } else if (/\S/.test(str)) { str = _RunSpanGamut(str); str = str.replace(/^([ \t]*)/g, "<p>"); str += "</p>" grafsOut.push(str); } } // // Unhashify HTML blocks // if (!doNotUnhash) { end = grafsOut.length; for (var i = 0; i < end; i++) { var foundAny = true; while (foundAny) { // we may need several runs, since the data may be nested foundAny = false; grafsOut[i] = grafsOut[i].replace(/~K(\d+)K/g, function (wholeMatch, id) { foundAny = true; return g_html_blocks[id]; }); } } } return grafsOut.join("\n\n"); } function _EncodeAmpsAndAngles(text) { // Smart processing for ampersands and angle brackets that need to be encoded. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: // http://bumppo.net/projects/amputator/ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&amp;"); // Encode naked <'s text = text.replace(/<(?![a-z\/?!]|~D)/gi, "&lt;"); return text; } function _EncodeBackslashEscapes(text) { // // Parameter: String. // Returns: The string, with after processing the following backslash // escape sequences. // // attacklab: The polite way to do this is with the new // escapeCharacters() function: // // text = escapeCharacters(text,"\\",true); // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); // // ...but we're sidestepping its use of the (slow) RegExp constructor // as an optimization for Firefox. This function gets called a LOT. text = text.replace(/\\(\\)/g, escapeCharacters_callback); text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, escapeCharacters_callback); return text; } var charInsideUrl = "[-A-Z0-9+&@#/%?=~_|[\\]()!:,.;]", charEndingUrl = "[-A-Z0-9+&@#/%=~_|[\\])]", autoLinkRegex = new RegExp("(=\"|<)?\\b(https?|ftp)(://" + charInsideUrl + "*" + charEndingUrl + ")(?=$|\\W)", "gi"), endCharRegex = new RegExp(charEndingUrl, "i"); function handleTrailingParens(wholeMatch, lookbehind, protocol, link) { if (lookbehind) return wholeMatch; if (link.charAt(link.length - 1) !== ")") return "<" + protocol + link + ">"; var parens = link.match(/[()]/g); var level = 0; for (var i = 0; i < parens.length; i++) { if (parens[i] === "(") { if (level <= 0) level = 1; else level++; } else { level--; } } var tail = ""; if (level < 0) { var re = new RegExp("\\){1," + (-level) + "}$"); link = link.replace(re, function (trailingParens) { tail = trailingParens; return ""; }); } if (tail) { var lastChar = link.charAt(link.length - 1); if (!endCharRegex.test(lastChar)) { tail = lastChar + tail; link = link.substr(0, link.length - 1); } } return "<" + protocol + link + ">" + tail; } function _DoAutoLinks(text) { // note that at this point, all other URL in the text are already hyperlinked as <a href=""></a> // *except* for the <http://www.foo.com> case // automatically add < and > around unadorned raw hyperlinks // must be preceded by a non-word character (and not by =" or <) and followed by non-word/EOF character // simulating the lookbehind in a consuming way is okay here, since a URL can neither and with a " nor // with a <, so there is no risk of overlapping matches. text = text.replace(autoLinkRegex, handleTrailingParens); // autolink anything like <http://example.com> var replacer = function (wholematch, m1) { var url = attributeSafeUrl(m1); return "<a href=\"" + url + "\">" + pluginHooks.plainLinkText(m1) + "</a>"; }; text = text.replace(/<((https?|ftp):[^'">\s]+)>/gi, replacer); // Email addresses: <address@domain.foo> /* text = text.replace(/ < (?:mailto:)? ( [-.\w]+ \@ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ ) > /gi, _DoAutoLinks_callback()); */ /* disabling email autolinking, since we don't do that on the server, either text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, function(wholeMatch,m1) { return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); } ); */ return text; } function _UnescapeSpecialChars(text) { // // Swap back in all the special characters we've hidden. // text = text.replace(/~E(\d+)E/g, function (wholeMatch, m1) { var charCodeToReplace = parseInt(m1); return String.fromCharCode(charCodeToReplace); } ); return text; } function _Outdent(text) { // // Remove one level of line-leading tabs or spaces // // attacklab: hack around Konqueror 3.5.4 bug: // "----------bug".replace(/^-/g,"") == "bug" text = text.replace(/^(\t|[ ]{1,4})/gm, "~0"); // attacklab: g_tab_width // attacklab: clean up hack text = text.replace(/~0/g, "") return text; } function _Detab(text) { if (!/\t/.test(text)) return text; var spaces = [" ", " ", " ", " "], skew = 0, v; return text.replace(/[\n\t]/g, function (match, offset) { if (match === "\n") { skew = offset + 1; return match; } v = (offset - skew) % 4; skew = offset + 1; return spaces[v]; }); } // // attacklab: Utility functions // function attributeSafeUrl(url) { url = attributeEncode(url); url = escapeCharacters(url, "*_:()[]") return url; } function escapeCharacters(text, charsToEscape, afterBackslash) { // First we have to escape the escape characters so that // we can build a character class out of them var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])"; if (afterBackslash) { regexString = "\\\\" + regexString; } var regex = new RegExp(regexString, "g"); text = text.replace(regex, escapeCharacters_callback); return text; } function escapeCharacters_callback(wholeMatch, m1) { var charCodeToEscape = m1.charCodeAt(0); return "~E" + charCodeToEscape + "E"; } }; // end of the Markdown.Converter constructor })();
JavaScript
// Usage: // // var myConverter = new Markdown.Editor(myConverter, null, { strings: Markdown.local.fr }); (function () { Markdown.local = Markdown.local || {}; Markdown.local.fr = { bold: "Gras <strong> Ctrl+B", boldexample: "texte en gras", italic: "Italique <em> Ctrl+I", italicexample: "texte en italique", link: "Hyperlien <a> Ctrl+L", linkdescription: "description de l'hyperlien", linkdialog: "<p><b>Insérer un hyperlien</b></p><p>http://example.com/ \"titre optionnel\"</p>", quote: "Citation <blockquote> Ctrl+Q", quoteexample: "Citation", code: "Extrait de code <pre><code> Ctrl+K", codeexample: "votre extrait de code", image: "Image <img> Ctrl+G", imagedescription: "description de l'image", imagedialog: "<p><b>Insérer une image</b></p><p>http://example.com/images/diagram.jpg \"titre optionnel\"<br><br><a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>Vous chercher un hébergement d'image grauit ?</a></p>", olist: "Liste numérotée <ol> Ctrl+O", ulist: "Liste à point <ul> Ctrl+U", litem: "Elément de liste", heading: "Titre <h1>/<h2> Ctrl+H", headingexample: "Titre", hr: "Trait horizontal <hr> Ctrl+R", undo: "Annuler - Ctrl+Z", redo: "Refaire - Ctrl+Y", redomac: "Refaire - Ctrl+Shift+Z", help: "Aide sur Markdown" }; })();
JavaScript
// NOTE: This is just a demo -- in a production environment, // be sure to spend a few more thoughts on sanitizing user input. // (also, you probably wouldn't use a get request) var http = require("http"), url = require("url"), querystring = require("querystring"), Converter = require("../../Markdown.Converter").Converter, getSanitizingConverter = require("../../Markdown.Sanitizer").getSanitizingConverter, conv = new Converter(), saneConv = getSanitizingConverter(); http.createServer(function (req, res) { var route = url.parse(req.url); if (route.pathname !== "/") { res.writeHead(404); res.end("Page not found"); return; } var query = querystring.parse(route.query); res.writeHead(200, { "Content-type": "text/html" }); res.write("<html><body>"); var markdown = query.md || "## Hello!\n\n<marquee>I'm walking</marquee>\n\nVisit [Stack Overflow](http://stackoverflow.com)\n\n<b><i>This is never closed!"; res.write("<h1>Your output, sanitized:</h1>\n" + saneConv.makeHtml(markdown)) res.write("<h1>Your output, unsanitized:</h1>\n" + conv.makeHtml(markdown)) res.write( "<h1>Enter Markdown</h1>\n" + "<form method='get' action='/'>" + "<textarea cols=50 rows=10 name='md'>" + markdown.replace(/</g, "&lt;") + "</textarea><br>" + "<input type='submit' value='Convert!'>" + "</form>" ); res.end("</body></html>"); }).listen(8000);
JavaScript
#pragma strict var maximumGrid : int; var existGrid : Vector3 []; var gridData : grid []; var curentGrid : Vector3 ; var nextGrid : Vector3; var gridObject : GameObject; function Grid (curGrid : Vector3, posGrid : int) { var outPutGrid : Vector3; if (curGrid.x%2 == 0){ switch(posGrid){ case 0: outPutGrid = Vector3(curGrid.x-1,curGrid.y,curGrid.z); break; case 1: outPutGrid = Vector3(curGrid.x,curGrid.y,curGrid.z+1); break; case 2: outPutGrid = Vector3(curGrid.x+1,curGrid.y,curGrid.z); break; case 3: outPutGrid = Vector3(curGrid.x+1,curGrid.y,curGrid.z-1); break; case 4: outPutGrid = Vector3(curGrid.x,curGrid.y,curGrid.z-1); break; default: outPutGrid = Vector3(curGrid.x-1,curGrid.y,curGrid.z-1); break; } }else{ switch(posGrid){ case 0: outPutGrid = Vector3(curGrid.x-1,curGrid.y,curGrid.z+1); break; case 1: outPutGrid = Vector3(curGrid.x,curGrid.y,curGrid.z+1); break; case 2: outPutGrid = Vector3(curGrid.x+1,curGrid.y,curGrid.z+1); break; case 3: outPutGrid = Vector3(curGrid.x+1,curGrid.y,curGrid.z); break; case 4: outPutGrid = Vector3(curGrid.x,curGrid.y,curGrid.z-1); break; default: outPutGrid = Vector3(curGrid.x-1,curGrid.y,curGrid.z); break; } } return outPutGrid ; } function GridCheck(gridChecked : Vector3, arrayGrid : Array){ var overlap : boolean = false; //Debug.Log(gridChecked + "-"+arrayGrid.join(",")); for(var i : int = 0; i<arrayGrid.length; i++){ if(arrayGrid[i] == gridChecked){ overlap = true; i = arrayGrid.length; Debug.Log("overlap"); } } return overlap; } function OverlapCounter(){ var outputNum: int; for(var i : int = 0 ; i < existGrid.length; i ++){ for (var j : int = 0; j < existGrid.length; j ++){ if (existGrid[i] == existGrid[j]){ outputNum ++; } } } return outputNum-existGrid.length; } function GridGenerator (maxGrid : int) { for (var i : int;i<maxGrid;i++){ var overlap : String = "false"; var gridArray = new Array (); //var gridArray1 = new Array(); gridArray = existGrid; var gridArray1 = gridData; var gridCreated : GameObject = Instantiate (gridObject,transform.position,transform.rotation); var gridScript : grid = gridCreated.GetComponent(grid); var nextGridPos : int = Random.Range(0,6); var j : int = 0; var pos : Vector3 = Grid(curentGrid,nextGridPos); while(GridCheck(pos,gridArray)){ overlap = "true"; //random direction on overlap nextGridPos += 1;//<---- bagian yang di ganti if(nextGridPos>6){ nextGridPos = 0; } j++; if(j>=6){ break; } pos = Grid(curentGrid,nextGridPos); } Debug.Log(""+nextGridPos+" "+ overlap); curentGrid = pos; gridScript.toGrid = nextGridPos; if(gridArray.length>0){ } gridArray.Add(pos); existGrid = gridArray; gridScript.posX = pos.x; gridScript.posY = pos.y; gridScript.posZ = pos.z; } } function GridIni() { var gridArray = new Array (curentGrid); existGrid = gridArray; } function Start () { GridGenerator(maximumGrid); Debug.Log(OverlapCounter()); } function Update () { }
JavaScript
#pragma strict var maxHp : int = 200; var curHp : int = 200; var point : int = 0; function Start () { curHp = maxHp; } function Update () { }
JavaScript
private var motor : CharacterMotor; // Use this for initialization function Awake () { motor = GetComponent(CharacterMotor); } // Update is called once per frame function Update () { // Get the input vector from kayboard or analog stick var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); if (directionVector != Vector3.zero) { // Get the length of the directon vector and then normalize it // Dividing by the length is cheaper than normalizing when we already have the length anyway var directionLength = directionVector.magnitude; directionVector = directionVector / directionLength; // Make sure the length is no bigger than 1 directionLength = Mathf.Min(1, directionLength); // Make the input vector more sensitive towards the extremes and less sensitive in the middle // This makes it easier to control slow speeds when using analog sticks directionLength = directionLength * directionLength; // Multiply the normalized direction vector by the modified length directionVector = directionVector * directionLength; } // Apply the direction to the CharacterMotor motor.inputMoveDirection = transform.rotation * directionVector; motor.inputJump = Input.GetButton("Jump"); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterMotor) @script AddComponentMenu ("Character/FPS Input Controller")
JavaScript
var cameraTransform : Transform; private var _target : Transform; // The distance in the x-z plane to the target var distance = 7.0; // the height we want the camera to be above the target var height = 3.0; var angularSmoothLag = 0.3; var angularMaxSpeed = 15.0; var heightSmoothLag = 0.3; var snapSmoothLag = 0.2; var snapMaxSpeed = 720.0; var clampHeadPositionScreenSpace = 0.75; var lockCameraTimeout = 0.2; private var headOffset = Vector3.zero; private var centerOffset = Vector3.zero; private var heightVelocity = 0.0; private var angleVelocity = 0.0; private var snap = false; private var controller : ThirdPersonController; private var targetHeight = 100000.0; function Awake () { if(!cameraTransform && Camera.main) cameraTransform = Camera.main.transform; if(!cameraTransform) { Debug.Log("Please assign a camera to the ThirdPersonCamera script."); enabled = false; } _target = transform; if (_target) { controller = _target.GetComponent(ThirdPersonController); } if (controller) { var characterController : CharacterController = _target.collider; centerOffset = characterController.bounds.center - _target.position; headOffset = centerOffset; headOffset.y = characterController.bounds.max.y - _target.position.y; } else Debug.Log("Please assign a target to the camera that has a ThirdPersonController script attached."); Cut(_target, centerOffset); } function DebugDrawStuff () { Debug.DrawLine(_target.position, _target.position + headOffset); } function AngleDistance (a : float, b : float) { a = Mathf.Repeat(a, 360); b = Mathf.Repeat(b, 360); return Mathf.Abs(b - a); } function Apply (dummyTarget : Transform, dummyCenter : Vector3) { // Early out if we don't have a target if (!controller) return; var targetCenter = _target.position + centerOffset; var targetHead = _target.position + headOffset; // DebugDrawStuff(); // Calculate the current & target rotation angles var originalTargetAngle = _target.eulerAngles.y; var currentAngle = cameraTransform.eulerAngles.y; // Adjust real target angle when camera is locked var targetAngle = originalTargetAngle; // When pressing Fire2 (alt) the camera will snap to the target direction real quick. // It will stop snapping when it reaches the target if (Input.GetButton("Fire2")) snap = true; if (snap) { // We are close to the target, so we can stop snapping now! if (AngleDistance (currentAngle, originalTargetAngle) < 3.0) snap = false; currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed); } // Normal camera motion else { if (controller.GetLockCameraTimer () < lockCameraTimeout) { targetAngle = currentAngle; } // Lock the camera when moving backwards! // * It is really confusing to do 180 degree spins when turning around. if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ()) targetAngle += 180; currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed); } // When jumping don't move camera upwards but only down! if (controller.IsJumping ()) { // We'd be moving the camera upwards, do that only if it's really high var newTargetHeight = targetCenter.y + height; if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5) targetHeight = targetCenter.y + height; } // When walking always update the target height else { targetHeight = targetCenter.y + height; } // Damp the height var currentHeight = cameraTransform.position.y; currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag); // Convert the angle into a rotation, by which we then reposition the camera var currentRotation = Quaternion.Euler (0, currentAngle, 0); // Set the position of the camera on the x-z plane to: // distance meters behind the target cameraTransform.position = targetCenter; cameraTransform.position += currentRotation * Vector3.back * distance; // Set the height of the camera cameraTransform.position.y = currentHeight; // Always look at the target SetUpRotation(targetCenter, targetHead); } function LateUpdate () { Apply (transform, Vector3.zero); } function Cut (dummyTarget : Transform, dummyCenter : Vector3) { var oldHeightSmooth = heightSmoothLag; var oldSnapMaxSpeed = snapMaxSpeed; var oldSnapSmooth = snapSmoothLag; snapMaxSpeed = 10000; snapSmoothLag = 0.001; heightSmoothLag = 0.001; snap = true; Apply (transform, Vector3.zero); heightSmoothLag = oldHeightSmooth; snapMaxSpeed = oldSnapMaxSpeed; snapSmoothLag = oldSnapSmooth; } function SetUpRotation (centerPos : Vector3, headPos : Vector3) { // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course. // * When jumping up and down we don't want to center the guy in screen space. // This is important to give a feel for how high you jump and avoiding large camera movements. // // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth. // // So here is what we will do: // // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis // 2. When grounded we make him be centered // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold // 4. When landing we smoothly interpolate towards centering him on screen var cameraPos = cameraTransform.position; var offsetToCenter = centerPos - cameraPos; // Generate base rotation only around y-axis var yRotation = Quaternion.LookRotation(Vector3(offsetToCenter.x, 0, offsetToCenter.z)); var relativeOffset = Vector3.forward * distance + Vector3.down * height; cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset); // Calculate the projected center position and top position in world space var centerRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, 0.5, 1)); var topRay = cameraTransform.camera.ViewportPointToRay(Vector3(.5, clampHeadPositionScreenSpace, 1)); var centerRayPos = centerRay.GetPoint(distance); var topRayPos = topRay.GetPoint(distance); var centerToTopAngle = Vector3.Angle(centerRay.direction, topRay.direction); var heightToAngle = centerToTopAngle / (centerRayPos.y - topRayPos.y); var extraLookAngle = heightToAngle * (centerRayPos.y - centerPos.y); if (extraLookAngle < centerToTopAngle) { extraLookAngle = 0; } else { extraLookAngle = extraLookAngle - centerToTopAngle; cameraTransform.rotation *= Quaternion.Euler(-extraLookAngle, 0, 0); } } function GetCenterOffset () { return centerOffset; }
JavaScript
// Require a character controller to be attached to the same game object @script RequireComponent(CharacterController) public var idleAnimation : AnimationClip; public var walkAnimation : AnimationClip; public var runAnimation : AnimationClip; public var jumpPoseAnimation : AnimationClip; public var walkMaxAnimationSpeed : float = 0.75; public var trotMaxAnimationSpeed : float = 1.0; public var runMaxAnimationSpeed : float = 1.0; public var jumpAnimationSpeed : float = 1.15; public var landAnimationSpeed : float = 1.0; private var _animation : Animation; enum CharacterState { Idle = 0, Walking = 1, Trotting = 2, Running = 3, Jumping = 4, } private var _characterState : CharacterState; // The speed when walking var walkSpeed = 2.0; // after trotAfterSeconds of walking we trot with trotSpeed var trotSpeed = 4.0; // when pressing "Fire3" button (cmd) we start running var runSpeed = 6.0; var inAirControlAcceleration = 3.0; // How high do we jump when pressing jump and letting go immediately var jumpHeight = 0.5; // The gravity for the character var gravity = 20.0; // The gravity in controlled descent mode var speedSmoothing = 10.0; var rotateSpeed = 500.0; var trotAfterSeconds = 3.0; var canJump = true; private var jumpRepeatTime = 0.05; private var jumpTimeout = 0.15; private var groundedTimeout = 0.25; // The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around. private var lockCameraTimer = 0.0; // The current move direction in x-z private var moveDirection = Vector3.zero; // The current vertical speed private var verticalSpeed = 0.0; // The current x-z move speed private var moveSpeed = 0.0; // The last collision flags returned from controller.Move private var collisionFlags : CollisionFlags; // Are we jumping? (Initiated with jump button and not grounded yet) private var jumping = false; private var jumpingReachedApex = false; // Are we moving backwards (This locks the camera to not do a 180 degree spin) private var movingBack = false; // Is the user pressing any keys? private var isMoving = false; // When did the user start walking (Used for going into trot after a while) private var walkTimeStart = 0.0; // Last time the jump button was clicked down private var lastJumpButtonTime = -10.0; // Last time we performed a jump private var lastJumpTime = -1.0; // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.) private var lastJumpStartHeight = 0.0; private var inAirVelocity = Vector3.zero; private var lastGroundedTime = 0.0; private var isControllable = true; function Awake () { moveDirection = transform.TransformDirection(Vector3.forward); _animation = GetComponent(Animation); if(!_animation) Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird."); /* public var idleAnimation : AnimationClip; public var walkAnimation : AnimationClip; public var runAnimation : AnimationClip; public var jumpPoseAnimation : AnimationClip; */ if(!idleAnimation) { _animation = null; Debug.Log("No idle animation found. Turning off animations."); } if(!walkAnimation) { _animation = null; Debug.Log("No walk animation found. Turning off animations."); } if(!runAnimation) { _animation = null; Debug.Log("No run animation found. Turning off animations."); } if(!jumpPoseAnimation && canJump) { _animation = null; Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations."); } } function UpdateSmoothedMovementDirection () { var cameraTransform = Camera.main.transform; var grounded = IsGrounded(); // Forward vector relative to the camera along the x-z plane var forward = cameraTransform.TransformDirection(Vector3.forward); forward.y = 0; forward = forward.normalized; // Right vector relative to the camera // Always orthogonal to the forward vector var right = Vector3(forward.z, 0, -forward.x); var v = Input.GetAxisRaw("Vertical"); var h = Input.GetAxisRaw("Horizontal"); // Are we moving backwards or looking backwards if (v < -0.2) movingBack = true; else movingBack = false; var wasMoving = isMoving; isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1; // Target direction relative to the camera var targetDirection = h * right + v * forward; // Grounded controls if (grounded) { // Lock camera for short period when transitioning moving & standing still lockCameraTimer += Time.deltaTime; if (isMoving != wasMoving) lockCameraTimer = 0.0; // We store speed and direction seperately, // so that when the character stands still we still have a valid forward direction // moveDirection is always normalized, and we only update it if there is user input. if (targetDirection != Vector3.zero) { // If we are really slow, just snap to the target direction if (moveSpeed < walkSpeed * 0.9 && grounded) { moveDirection = targetDirection.normalized; } // Otherwise smoothly turn towards it else { moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000); moveDirection = moveDirection.normalized; } } // Smooth the speed based on the current target direction var curSmooth = speedSmoothing * Time.deltaTime; // Choose target speed //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0); _characterState = CharacterState.Idle; // Pick speed modifier if (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift)) { targetSpeed *= runSpeed; _characterState = CharacterState.Running; } else if (Time.time - trotAfterSeconds > walkTimeStart) { targetSpeed *= trotSpeed; _characterState = CharacterState.Trotting; } else { targetSpeed *= walkSpeed; _characterState = CharacterState.Walking; } moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth); // Reset walk time start when we slow down if (moveSpeed < walkSpeed * 0.3) walkTimeStart = Time.time; } // In air controls else { // Lock camera while in air if (jumping) lockCameraTimer = 0.0; if (isMoving) inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration; } } function ApplyJumping () { // Prevent jumping too fast after each other if (lastJumpTime + jumpRepeatTime > Time.time) return; if (IsGrounded()) { // Jump // - Only when pressing the button down // - With a timeout so you can press the button slightly before landing if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) { verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight); SendMessage("DidJump", SendMessageOptions.DontRequireReceiver); } } } function ApplyGravity () { if (isControllable) // don't move player at all if not controllable. { // Apply gravity var jumpButton = Input.GetButton("Jump"); // When we reach the apex of the jump we send out a message if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0) { jumpingReachedApex = true; SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver); } if (IsGrounded ()) verticalSpeed = 0.0; else verticalSpeed -= gravity * Time.deltaTime; } } function CalculateJumpVerticalSpeed (targetJumpHeight : float) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 * targetJumpHeight * gravity); } function DidJump () { jumping = true; jumpingReachedApex = false; lastJumpTime = Time.time; lastJumpStartHeight = transform.position.y; lastJumpButtonTime = -10; _characterState = CharacterState.Jumping; } function Update() { if (!isControllable) { // kill all inputs if not controllable. Input.ResetInputAxes(); } if (Input.GetButtonDown ("Jump")) { lastJumpButtonTime = Time.time; } UpdateSmoothedMovementDirection(); // Apply gravity // - extra power jump modifies gravity // - controlledDescent mode modifies gravity ApplyGravity (); // Apply jumping logic ApplyJumping (); // Calculate actual motion var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity; movement *= Time.deltaTime; // Move the controller var controller : CharacterController = GetComponent(CharacterController); collisionFlags = controller.Move(movement); // ANIMATION sector if(_animation) { if(_characterState == CharacterState.Jumping) { if(!jumpingReachedApex) { _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } else { _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed; _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever; _animation.CrossFade(jumpPoseAnimation.name); } } else { if(controller.velocity.sqrMagnitude < 0.1) { _animation.CrossFade(idleAnimation.name); } else { if(_characterState == CharacterState.Running) { _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed); _animation.CrossFade(runAnimation.name); } else if(_characterState == CharacterState.Trotting) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } else if(_characterState == CharacterState.Walking) { _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed); _animation.CrossFade(walkAnimation.name); } } } } // ANIMATION sector // Set rotation to the move direction if (IsGrounded()) { transform.rotation = Quaternion.LookRotation(moveDirection); } else { var xzMove = movement; xzMove.y = 0; if (xzMove.sqrMagnitude > 0.001) { transform.rotation = Quaternion.LookRotation(xzMove); } } // We are in jump mode but just became grounded if (IsGrounded()) { lastGroundedTime = Time.time; inAirVelocity = Vector3.zero; if (jumping) { jumping = false; SendMessage("DidLand", SendMessageOptions.DontRequireReceiver); } } } function OnControllerColliderHit (hit : ControllerColliderHit ) { // Debug.DrawRay(hit.point, hit.normal); if (hit.moveDirection.y > 0.01) return; } function GetSpeed () { return moveSpeed; } function IsJumping () { return jumping; } function IsGrounded () { return (collisionFlags & CollisionFlags.CollidedBelow) != 0; } function GetDirection () { return moveDirection; } function IsMovingBackwards () { return movingBack; } function GetLockCameraTimer () { return lockCameraTimer; } function IsMoving () : boolean { return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5; } function HasJumpReachedApex () { return jumpingReachedApex; } function IsGroundedWithTimeout () { return lastGroundedTime + groundedTimeout > Time.time; } function Reset () { gameObject.tag = "Player"; }
JavaScript
#pragma strict #pragma implicit #pragma downcast // Does this script currently respond to input? var canControl : boolean = true; var useFixedUpdate : boolean = true; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The current global direction we want the character to move in. @System.NonSerialized var inputMoveDirection : Vector3 = Vector3.zero; // Is the jump button held down? We use this interface instead of checking // for the jump button directly so this script can also be used by AIs. @System.NonSerialized var inputJump : boolean = false; class CharacterMotorMovement { // The maximum horizontal speed when moving var maxForwardSpeed : float = 10.0; var maxSidewaysSpeed : float = 10.0; var maxBackwardsSpeed : float = 10.0; // Curve for multiplying speed based on slope (negative = downwards) var slopeSpeedMultiplier : AnimationCurve = AnimationCurve(Keyframe(-90, 1), Keyframe(0, 1), Keyframe(90, 0)); // How fast does the character change speeds? Higher is faster. var maxGroundAcceleration : float = 30.0; var maxAirAcceleration : float = 20.0; // The gravity for the character var gravity : float = 10.0; var maxFallSpeed : float = 20.0; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The last collision flags returned from controller.Move @System.NonSerialized var collisionFlags : CollisionFlags; // We will keep track of the character's current velocity, @System.NonSerialized var velocity : Vector3; // This keeps track of our current velocity while we're not grounded @System.NonSerialized var frameVelocity : Vector3 = Vector3.zero; @System.NonSerialized var hitPoint : Vector3 = Vector3.zero; @System.NonSerialized var lastHitPoint : Vector3 = Vector3(Mathf.Infinity, 0, 0); } var movement : CharacterMotorMovement = CharacterMotorMovement(); enum MovementTransferOnJump { None, // The jump is not affected by velocity of floor at all. InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop. PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing. PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor. } // We will contain all the jumping related variables in one helper class for clarity. class CharacterMotorJumping { // Can the character jump? var enabled : boolean = true; // How high do we jump when pressing jump and letting go immediately var baseHeight : float = 1.0; // We add extraHeight units (meters) on top when holding the button down longer while jumping var extraHeight : float = 4.1; // How much does the character jump out perpendicular to the surface on walkable surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. var perpAmount : float = 0.0; // How much does the character jump out perpendicular to the surface on too steep surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. var steepPerpAmount : float = 0.5; // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // Are we jumping? (Initiated with jump button and not grounded yet) // To see if we are just in the air (initiated by jumping OR falling) see the grounded variable. @System.NonSerialized var jumping : boolean = false; @System.NonSerialized var holdingJumpButton : boolean = false; // the time we jumped at (Used to determine for how long to apply extra jump power after jumping.) @System.NonSerialized var lastStartTime : float = 0.0; @System.NonSerialized var lastButtonDownTime : float = -100; @System.NonSerialized var jumpDir : Vector3 = Vector3.up; } var jumping : CharacterMotorJumping = CharacterMotorJumping(); class CharacterMotorMovingPlatform { var enabled : boolean = true; var movementTransfer : MovementTransferOnJump = MovementTransferOnJump.PermaTransfer; @System.NonSerialized var hitPlatform : Transform; @System.NonSerialized var activePlatform : Transform; @System.NonSerialized var activeLocalPoint : Vector3; @System.NonSerialized var activeGlobalPoint : Vector3; @System.NonSerialized var activeLocalRotation : Quaternion; @System.NonSerialized var activeGlobalRotation : Quaternion; @System.NonSerialized var lastMatrix : Matrix4x4; @System.NonSerialized var platformVelocity : Vector3; @System.NonSerialized var newPlatform : boolean; } var movingPlatform : CharacterMotorMovingPlatform = CharacterMotorMovingPlatform(); class CharacterMotorSliding { // Does the character slide on too steep surfaces? var enabled : boolean = true; // How fast does the character slide on steep surfaces? var slidingSpeed : float = 15; // How much can the player control the sliding direction? // If the value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed. var sidewaysControl : float = 1.0; // How much can the player influence the sliding speed? // If the value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%. var speedControl : float = 0.4; } var sliding : CharacterMotorSliding = CharacterMotorSliding(); @System.NonSerialized var grounded : boolean = true; @System.NonSerialized var groundNormal : Vector3 = Vector3.zero; private var lastGroundNormal : Vector3 = Vector3.zero; private var tr : Transform; private var controller : CharacterController; function Awake () { controller = GetComponent (CharacterController); tr = transform; } private function UpdateFunction () { // We copy the actual velocity into a temporary variable that we can manipulate. var velocity : Vector3 = movement.velocity; // Update velocity based on input velocity = ApplyInputVelocityChange(velocity); // Apply gravity and jumping force velocity = ApplyGravityAndJumping (velocity); // Moving platform support var moveDistance : Vector3 = Vector3.zero; if (MoveWithPlatform()) { var newGlobalPoint : Vector3 = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint); moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint); if (moveDistance != Vector3.zero) controller.Move(moveDistance); // Support moving platform rotation as well: var newGlobalRotation : Quaternion = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation; var rotationDiff : Quaternion = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation); var yRotation = rotationDiff.eulerAngles.y; if (yRotation != 0) { // Prevent rotation of the local up vector tr.Rotate(0, yRotation, 0); } } // Save lastPosition for velocity calculation. var lastPosition : Vector3 = tr.position; // We always want the movement to be framerate independent. Multiplying by Time.deltaTime does this. var currentMovementOffset : Vector3 = velocity * Time.deltaTime; // Find out how much we need to push towards the ground to avoid loosing grouning // when walking down a step or over a sharp change in slope. var pushDownOffset : float = Mathf.Max(controller.stepOffset, Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude); if (grounded) currentMovementOffset -= pushDownOffset * Vector3.up; // Reset variables that will be set by collision function movingPlatform.hitPlatform = null; groundNormal = Vector3.zero; // Move our character! movement.collisionFlags = controller.Move (currentMovementOffset); movement.lastHitPoint = movement.hitPoint; lastGroundNormal = groundNormal; if (movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) { if (movingPlatform.hitPlatform != null) { movingPlatform.activePlatform = movingPlatform.hitPlatform; movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix; movingPlatform.newPlatform = true; } } // Calculate the velocity based on the current and previous position. // This means our velocity will only be the amount the character actually moved as a result of collisions. var oldHVelocity : Vector3 = new Vector3(velocity.x, 0, velocity.z); movement.velocity = (tr.position - lastPosition) / Time.deltaTime; var newHVelocity : Vector3 = new Vector3(movement.velocity.x, 0, movement.velocity.z); // The CharacterController can be moved in unwanted directions when colliding with things. // We want to prevent this from influencing the recorded velocity. if (oldHVelocity == Vector3.zero) { movement.velocity = new Vector3(0, movement.velocity.y, 0); } else { var projectedNewVelocity : float = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude; movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up; } if (movement.velocity.y < velocity.y - 0.001) { if (movement.velocity.y < 0) { // Something is forcing the CharacterController down faster than it should. // Ignore this movement.velocity.y = velocity.y; } else { // The upwards movement of the CharacterController has been blocked. // This is treated like a ceiling collision - stop further jumping here. jumping.holdingJumpButton = false; } } // We were grounded but just loosed grounding if (grounded && !IsGroundedTest()) { grounded = false; // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; movement.velocity += movingPlatform.platformVelocity; } SendMessage("OnFall", SendMessageOptions.DontRequireReceiver); // We pushed the character down to ensure it would stay on the ground if there was any. // But there wasn't so now we cancel the downwards offset to make the fall smoother. tr.position += pushDownOffset * Vector3.up; } // We were not grounded but just landed on something else if (!grounded && IsGroundedTest()) { grounded = true; jumping.jumping = false; SubtractNewPlatformVelocity(); SendMessage("OnLand", SendMessageOptions.DontRequireReceiver); } // Moving platforms support if (MoveWithPlatform()) { // Use the center of the lower half sphere of the capsule as reference point. // This works best when the character is standing on moving tilting platforms. movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height*0.5 + controller.radius); movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint); // Support moving platform rotation as well: movingPlatform.activeGlobalRotation = tr.rotation; movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation; } } function FixedUpdate () { if (movingPlatform.enabled) { if (movingPlatform.activePlatform != null) { if (!movingPlatform.newPlatform) { var lastVelocity : Vector3 = movingPlatform.platformVelocity; movingPlatform.platformVelocity = ( movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) - movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) ) / Time.deltaTime; } movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix; movingPlatform.newPlatform = false; } else { movingPlatform.platformVelocity = Vector3.zero; } } if (useFixedUpdate) UpdateFunction(); } function Update () { if (!useFixedUpdate) UpdateFunction(); } private function ApplyInputVelocityChange (velocity : Vector3) { if (!canControl) inputMoveDirection = Vector3.zero; // Find desired velocity var desiredVelocity : Vector3; if (grounded && TooSteep()) { // The direction we're sliding in desiredVelocity = Vector3(groundNormal.x, 0, groundNormal.z).normalized; // Find the input movement direction projected onto the sliding direction var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity); // Add the sliding direction, the spped control, and the sideways control vectors desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl; // Multiply with the sliding speed desiredVelocity *= sliding.slidingSpeed; } else desiredVelocity = GetDesiredHorizontalVelocity(); if (movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) { desiredVelocity += movement.frameVelocity; desiredVelocity.y = 0; } if (grounded) desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal); else velocity.y = 0; // Enforce max velocity change var maxVelocityChange : float = GetMaxAcceleration(grounded) * Time.deltaTime; var velocityChangeVector : Vector3 = (desiredVelocity - velocity); if (velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange) { velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange; } // If we're in the air and don't have control, don't apply any velocity change at all. // If we're on the ground and don't have control we do apply it - it will correspond to friction. if (grounded || canControl) velocity += velocityChangeVector; if (grounded) { // When going uphill, the CharacterController will automatically move up by the needed amount. // Not moving it upwards manually prevent risk of lifting off from the ground. // When going downhill, DO move down manually, as gravity is not enough on steep hills. velocity.y = Mathf.Min(velocity.y, 0); } return velocity; } private function ApplyGravityAndJumping (velocity : Vector3) { if (!inputJump || !canControl) { jumping.holdingJumpButton = false; jumping.lastButtonDownTime = -100; } if (inputJump && jumping.lastButtonDownTime < 0 && canControl) jumping.lastButtonDownTime = Time.time; if (grounded) velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime; else { velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime; // When jumping up we don't apply gravity for some time when the user is holding the jump button. // This gives more control over jump height by pressing the button longer. if (jumping.jumping && jumping.holdingJumpButton) { // Calculate the duration that the extra jump force should have effect. // If we're still less than that duration after the jumping time, apply the force. if (Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) { // Negate the gravity we just applied, except we push in jumpDir rather than jump upwards. velocity += jumping.jumpDir * movement.gravity * Time.deltaTime; } } // Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity. velocity.y = Mathf.Max (velocity.y, -movement.maxFallSpeed); } if (grounded) { // Jump only if the jump button was pressed down in the last 0.2 seconds. // We use this check instead of checking if it's pressed down right now // because players will often try to jump in the exact moment when hitting the ground after a jump // and if they hit the button a fraction of a second too soon and no new jump happens as a consequence, // it's confusing and it feels like the game is buggy. if (jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2)) { grounded = false; jumping.jumping = true; jumping.lastStartTime = Time.time; jumping.lastButtonDownTime = -100; jumping.holdingJumpButton = true; // Calculate the jumping direction if (TooSteep()) jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount); else jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount); // Apply the jumping force to the velocity. Cancel any vertical velocity first. velocity.y = 0; velocity += jumping.jumpDir * CalculateJumpVerticalSpeed (jumping.baseHeight); // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; velocity += movingPlatform.platformVelocity; } SendMessage("OnJump", SendMessageOptions.DontRequireReceiver); } else { jumping.holdingJumpButton = false; } } return velocity; } function OnControllerColliderHit (hit : ControllerColliderHit) { if (hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0) { if ((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero) groundNormal = hit.normal; else groundNormal = lastGroundNormal; movingPlatform.hitPlatform = hit.collider.transform; movement.hitPoint = hit.point; movement.frameVelocity = Vector3.zero; } } private function SubtractNewPlatformVelocity () { // When landing, subtract the velocity of the new ground from the character's velocity // since movement in ground is relative to the movement of the ground. if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { // If we landed on a new platform, we have to wait for two FixedUpdates // before we know the velocity of the platform under the character if (movingPlatform.newPlatform) { var platform : Transform = movingPlatform.activePlatform; yield WaitForFixedUpdate(); yield WaitForFixedUpdate(); if (grounded && platform == movingPlatform.activePlatform) yield 1; } movement.velocity -= movingPlatform.platformVelocity; } } private function MoveWithPlatform () : boolean { return ( movingPlatform.enabled && (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked) && movingPlatform.activePlatform != null ); } private function GetDesiredHorizontalVelocity () { // Find desired velocity var desiredLocalDirection : Vector3 = tr.InverseTransformDirection(inputMoveDirection); var maxSpeed : float = MaxSpeedInDirection(desiredLocalDirection); if (grounded) { // Modify max speed on slopes based on slope speed multiplier curve var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y) * Mathf.Rad2Deg; maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle); } return tr.TransformDirection(desiredLocalDirection * maxSpeed); } private function AdjustGroundVelocityToNormal (hVelocity : Vector3, groundNormal : Vector3) : Vector3 { var sideways : Vector3 = Vector3.Cross(Vector3.up, hVelocity); return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude; } private function IsGroundedTest () { return (groundNormal.y > 0.01); } function GetMaxAcceleration (grounded : boolean) : float { // Maximum acceleration on ground and in air if (grounded) return movement.maxGroundAcceleration; else return movement.maxAirAcceleration; } function CalculateJumpVerticalSpeed (targetJumpHeight : float) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt (2 * targetJumpHeight * movement.gravity); } function IsJumping () { return jumping.jumping; } function IsSliding () { return (grounded && sliding.enabled && TooSteep()); } function IsTouchingCeiling () { return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0; } function IsGrounded () { return grounded; } function TooSteep () { return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad)); } function GetDirection () { return inputMoveDirection; } function SetControllable (controllable : boolean) { canControl = controllable; } // Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed. // The function returns the length of the resulting vector. function MaxSpeedInDirection (desiredMovementDirection : Vector3) : float { if (desiredMovementDirection == Vector3.zero) return 0; else { var zAxisEllipseMultiplier : float = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed; var temp : Vector3 = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized; var length : float = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed; return length; } } function SetVelocity (velocity : Vector3) { grounded = false; movement.velocity = velocity; movement.frameVelocity = Vector3.zero; SendMessage("OnExternalVelocity"); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterController) @script AddComponentMenu ("Character/Character Motor")
JavaScript
// This makes the character turn to face the current movement speed per default. var autoRotate : boolean = true; var maxRotationSpeed : float = 360; private var motor : CharacterMotor; // Use this for initialization function Awake () { motor = GetComponent(CharacterMotor); } // Update is called once per frame function Update () { // Get the input vector from kayboard or analog stick var directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0); if (directionVector != Vector3.zero) { // Get the length of the directon vector and then normalize it // Dividing by the length is cheaper than normalizing when we already have the length anyway var directionLength = directionVector.magnitude; directionVector = directionVector / directionLength; // Make sure the length is no bigger than 1 directionLength = Mathf.Min(1, directionLength); // Make the input vector more sensitive towards the extremes and less sensitive in the middle // This makes it easier to control slow speeds when using analog sticks directionLength = directionLength * directionLength; // Multiply the normalized direction vector by the modified length directionVector = directionVector * directionLength; } // Rotate the input vector into camera space so up is camera's up and right is camera's right directionVector = Camera.main.transform.rotation * directionVector; // Rotate input vector to be perpendicular to character's up vector var camToCharacterSpace = Quaternion.FromToRotation(-Camera.main.transform.forward, transform.up); directionVector = (camToCharacterSpace * directionVector); // Apply the direction to the CharacterMotor motor.inputMoveDirection = directionVector; motor.inputJump = Input.GetButton("Jump"); // Set rotation to the move direction if (autoRotate && directionVector.sqrMagnitude > 0.01) { var newForward : Vector3 = ConstantSlerp( transform.forward, directionVector, maxRotationSpeed * Time.deltaTime ); newForward = ProjectOntoPlane(newForward, transform.up); transform.rotation = Quaternion.LookRotation(newForward, transform.up); } } function ProjectOntoPlane (v : Vector3, normal : Vector3) { return v - Vector3.Project(v, normal); } function ConstantSlerp (from : Vector3, to : Vector3, angle : float) { var value : float = Mathf.Min(1, angle / Vector3.Angle(from, to)); return Vector3.Slerp(from, to, value); } // Require a character controller to be attached to the same game object @script RequireComponent (CharacterMotor) @script AddComponentMenu ("Character/Platform Input Controller")
JavaScript
#pragma strict var gridX : float; var gridY : float; var gridZ : float; function Start () { } function Update () { }
JavaScript
#pragma strict @script ExecuteInEditMode() var posX : int; var posY : int; var posZ : int; var fromDir : int; var toGrid : int; var arrow : Transform; function GridPos (){ var grid : GridManager = GameObject.Find('_GamesSystem').GetComponent(GridManager); var x : float = grid.gridX * posX; var y : float = grid.gridY * posY; var z : float ; if (posX %2 != 0){ z = grid.gridZ * posZ + grid.gridZ/2; } else { z = grid.gridZ * posZ; } transform.position = Vector3(x, y, z); } function AdjustArrow(){ switch(toGrid){ case 0: arrow.eulerAngles.y = -60; break; case 1: arrow.eulerAngles.y = 0; break; case 2: arrow.eulerAngles.y = 60; break; case 3: arrow.eulerAngles.y = 120; break; case 4: arrow.eulerAngles.y = 180; break; default: arrow.eulerAngles.y = 240; break; } //Debug.Log(arrow.localEulerAngles.y); } function Start () { } function Update (){ GridPos(); AdjustArrow(); }
JavaScript
InputText = function(scene) { this.scene = scene; this.isFocused = true; this.boxWidth = 400; this.boxHeight = 70; this.boxDepth = 70; this.textColor = 0xffffff; this.textMaterial = new THREE.MeshBasicMaterial( { color: this.textColor, overdraw: true } ); this.letterSize = 50; this.letterDepth = 3; this.textFont = 'helvetiker'; this.textWeight = 'normal'; this.textStyle = 'normal'; this.letters = []; this.boxColor = 0xff0000; this.boxOpacity = 0.7; this.boxGeometry = new THREE.CubeGeometry( this.boxWidth, this.boxHeight, this.boxDepth ); this.boxMesh = new THREE.Mesh( this.boxGeometry, new THREE.MeshBasicMaterial( { color: this.boxColor, opacity: this.boxOpacity, transparent: true } ) ); //test this.boxMesh.rotation.x = (45/180)*3.14; this.boxMesh.rotation.y = (45/180)*3.14; //END test this.scene.add(this.boxMesh); this.OnKeyDown = function (event) { if(this.isFocused) { var evt = event || window.event; var keycode = 0; if (evt) keycode = evt.which || evt.keyCode; var prevLetter = this.letters[this.letters.length-1]; if(keycode == 8) { if(prevLetter) { this.letters.splice(this.letters.indexOf(prevLetter), 1); this.boxMesh.remove(prevLetter.mesh); } evt.preventDefault(); } } } this.OnKeyPress = function (event) { if(this.isFocused) { var evt = event || window.event; var keycode = 0; if (evt) keycode = evt.which || evt.keyCode; var prevLetter = this.letters[this.letters.length-1]; if(keycode >= 9 && keycode <= 46 && keycode != 32){ } else { var charFromCode = String.fromCharCode(keycode); var textMesh = new THREE.Mesh(new THREE.TextGeometry( charFromCode, {size: this.letterSize, height: this.letterDepth, curveSegments: 1, font: this.textFont, weight: this.textWeight, style: this.textStyle } ), this.textMaterial); var letterXpos = -this.boxWidth/2 + 10; if(prevLetter) { letterXpos = prevLetter.mesh.position.x + this.letterSize + 10; } textMesh.position.x = letterXpos; textMesh.position.y = -this.boxHeight/2 + 15; this.boxMesh.add(textMesh); this.letters.push(new InputLetter(charFromCode, textMesh)); } } } this.getValue = function() { var result = ''; for(var i = 0; i < this.letters.length; i++) { result += this.letters[i].letter; } return result; } document.addEventListener( 'keydown', bindFn( this, this.OnKeyDown ), false ); document.addEventListener( 'keypress', bindFn( this, this.OnKeyPress ), false ); } InputLetter = function(letter, mesh) { this.mesh = mesh; this.letter = letter; }
JavaScript
DropDownList = function(scene, camera, items) { this.scene = scene; this.camera = camera; this.listItems = items; this.selectedIndex = 0; this.selectedItem = this.listItems[this.selectedIndex]; this.mainBoxColor = 0x00ff00; this.mainBoxOpacity = 0.5; this.mainBoxWidth = 400; this.mainBoxHeight = 70; this.mainBoxDepth = 70; this.selectedItem; this.mainBoxMesh; this.mainBoxGeometry; this.mainBoxMaterial; this.itemsMeshes = []; this.projector = new THREE.Projector(); this.expand = function () { this.mainBoxMesh.add(this.itemsBoxMesh); } this.collapse = function () { this.mainBoxMesh.remove(this.itemsBoxMesh); } this.createItemsBoxMesh = function() { this.itemsBoxMaterial = new THREE.MeshBasicMaterial( {opacity: 0.0, transparent: true} ); this.itemsBoxGeometry = new THREE.CubeGeometry( 0, 0, 0 ); this.itemsBoxMesh = new THREE.Mesh( this.itemsBoxGeometry, this.itemsBoxMaterial ); for(var listItem in this.listItems) { this.listItems[listItem].PreInit(this); } for(var listItem in this.listItems) { this.listItems[listItem].Init(this); this.itemsBoxMesh.add(this.listItems[listItem].itemBoxMesh); if(listItem == 0) { this.listItems[listItem].itemBoxMesh.position.y = -this.listItems[listItem].itemBoxHeight/2 - 20; } else { this.listItems[listItem].itemBoxMesh.position.y = this.listItems[parseInt(listItem)-1].itemBoxMesh.position.y - this.listItems[listItem].itemBoxHeight - 20; } this.itemsMeshes.push(this.listItems[listItem].itemBoxMesh); } this.mainBoxMaterial = new THREE.MeshBasicMaterial( { color: this.mainBoxColor, opacity: this.mainBoxOpacity, transparent: true } ); this.mainBoxGeometry = new THREE.CubeGeometry( this.mainBoxWidth, this.mainBoxHeight, this.mainBoxDepth ); this.mainBoxMesh = new THREE.Mesh( this.mainBoxGeometry, this.mainBoxMaterial ); this.itemsMeshes.push(this.mainBoxMesh); //test this.mainBoxMesh.position.x = Math.random() * 2000 - 1000; this.mainBoxMesh.position.y = Math.random() * 2000 - 1000; this.mainBoxMesh.position.z = Math.random() * 2000 - 1000; //END test this.itemsBoxMesh.position.y = -this.mainBoxHeight/2; } this.createItemsBoxMesh(); this.scene.add(this.mainBoxMesh); this.OnClick = function(event) { event.preventDefault(); var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 ); this.projector.unprojectVector( vector, this.camera ); var ray = new THREE.Ray( this.camera.position, vector.subSelf( this.camera.position ).normalize() ); var intersects = ray.intersectObjects( this.itemsMeshes ); if ( intersects.length > 0 ) { var clickedMesh = intersects[ 0 ].object; if(clickedMesh == this.mainBoxMesh) { this.expand(); } else { var clickedIndex = this.itemsMeshes.indexOf(clickedMesh); if(this.selectedItem && this.selectedItem.textMeshInHeader) { this.mainBoxMesh.remove(this.selectedItem.textMeshInHeader); } this.selectedItem = this.listItems[clickedIndex]; this.selectedItem.textMeshInHeader = cloneMesh(this.selectedItem.itemTextMesh); this.mainBoxMesh.add(this.selectedItem.textMeshInHeader); this.collapse(); } } } document.addEventListener( 'click', bindFn( this, this.OnClick ), false ); } ListItem = function(text, value) { this.text = text; this.value = value; this.dropDownList; this.itemBoxColor = 0x0000ff; this.itemBoxOpacity = 0.7; this.textColor = 0xffffff; this.letterSize = 50; this.letterDepth = 5; this.textFont = 'helvetiker'; this.textWeight = 'normal'; this.textStyle = 'normal'; this.itemBoxXoffset = 10; this.itemBoxYoffset = 20; this.textMeshInHeader; this.PreInit = function(dropDownList) { this.dropDownList = dropDownList; this.itemTextMaterial = new THREE.MeshBasicMaterial( { color: this.textColor, overdraw: true } ); this.itemTextGeometry = new THREE.TextGeometry( this.text, {size: this.letterSize, height: this.letterDepth, curveSegments: 1, font: this.textFont, weight: this.textWeight, style: this.textStyle } ) this.itemTextMesh = new THREE.Mesh(this.itemTextGeometry, this.itemTextMaterial); this.itemTextGeometry.computeBoundingBox(); this.itemTextWidth = this.itemTextGeometry.boundingBox.max.x - this.itemTextGeometry.boundingBox.min.x; this.itemTextHeight = this.itemTextGeometry.boundingBox.max.y - this.itemTextGeometry.boundingBox.min.y; this.itemTextDepth = this.itemTextGeometry.boundingBox.max.z - this.itemTextGeometry.boundingBox.min.z; this.itemBoxWidth = this.itemTextWidth + 2*this.itemBoxXoffset; this.itemBoxHeight = this.itemTextHeight + 2*this.itemBoxYoffset; this.itemBoxDepth = 50;//this.itemTextGeometry.boundingBox.max.z - this.itemTextGeometry.boundingBox.min.z; if(this.itemBoxWidth > dropDownList.mainBoxWidth) { dropDownList.mainBoxWidth = this.itemBoxWidth; } } this.Init = function(dropDownList) { this.itemBoxMaterial = new THREE.MeshBasicMaterial( { color: this.itemBoxColor, opacity: this.itemBoxOpacity, transparent: true } ); this.itemBoxGeometry = new THREE.CubeGeometry( dropDownList.mainBoxWidth, this.itemBoxHeight, this.itemBoxDepth ); this.itemBoxMesh = new THREE.Mesh( this.itemBoxGeometry, this.itemBoxMaterial ); this.itemBoxMesh.add(this.itemTextMesh); this.itemTextMesh.position.x = -dropDownList.mainBoxWidth/2 + this.itemBoxXoffset; this.itemTextMesh.position.y = -this.itemTextHeight/2; //THREE.GeometryUtils.merge(this.itemBoxGeometry, this.itemTextGeometry); } }
JavaScript
function bindFn( scope, fn ) { return function () { fn.apply( scope, arguments ); }; }; function cloneMesh(mesh) { var result = new THREE.Mesh(mesh.geometry, mesh.material); result.position = mesh.position; return result; }
JavaScript
var postTitle=new Array(); var postUrl=new Array(); var postMp3=new Array(); var postDate=new Array(); var postYear=new Array(); var postMonth=new Array(); var postYearMonth=new Array(); var postYearMonth2=new Array(); var postTanggal=new Array(); var postLabels=new Array(); var postBaru=new Array(); var sortBy="titleasc"; var tocLoaded=true; var numChars=500; var postFilter=""; var numberfeed=0; var month2=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]; function request() { var scriptArgs = document.getElementById("searchScript").getAttribute("data"); //var scripts = document.getElementsByTagName("script"); //var scriptArgs = scripts[ scripts.length - 1 ].innerHTML.replace(/[s]/g,''); return scriptArgs.split("=").pop(); } var postSearchLabel = request(); function loadtoc(a) { function b() { if("entry" in a.feed) { var d=a.feed.entry.length;//alert(d); numberfeed=d; ii=0; for(var h=0;h<d;h++) { var m=a.feed.entry[h]; var e=m.title.$t; var l=m.published.$t.substring(0,10); var p=m.published.$t.substring(5,7); var g=m.published.$t.substring(8,10); var n=m.published.$t.substring(0,4)+" "+month2[parseInt(p,10)-1]; var c="/"+m.published.$t.substring(0,4)+"_"+p+"_01_archive.html"; var j; for(var f=0;f<m.link.length;f++) { if(m.link[f].rel=="alternate") { j=m.link[f].href; break } } var o=""; for(var f=0;f<m.link.length;f++) { if(m.link[f].rel=="enclosure") { o=m.link[f].href; break } } var c=""; if("category" in m) { for(var f=0;f<m.category.length;f++) { c=m.category[f].term; var ff=c.lastIndexOf(";"); if(ff!=-1) { c=c.substring(0,f) } postLabels[ii]=c;ii++; } } postTitle.push(e); postDate.push(l); postUrl.push(j); postYearMonth.push(n); postYearMonth2.push(c); postTanggal.push(g) } } } b(); displayToc2() } function displayToc2() { var a=0; var b=0; while(b<postTitle.length) { temp1=postYearMonth[b]; // document.write("<p/>"); document.write('<p><a href="'+postYearMonth2[b]+'">'+temp1+"</a></p><ul>"); firsti=a; do { if(postLabels[a]==postSearchLabel) { document.write("<li>"); document.write("["+postTanggal[a]+'] <a href="'+postUrl[a]+'">'+postTitle[a]+"</a>"); document.write("</li>"); } a=a+1 } while(postYearMonth[a]==temp1); b=a; document.write("</ul>"); if(b>postTitle.length){break} } };
JavaScript
var postTitle=new Array(); var postUrl=new Array(); var postMp3=new Array(); var postDate=new Array(); var postLabels=new Array(); var postBaru=new Array(); var sortBy="titleasc"; var tocLoaded=false; var numChars=250; var postFilter=""; var numberfeed=0; function loadtoc(a) { function b() { if("entry" in a.feed) { var d=a.feed.entry.length; numberfeed=d; ii=0; for(var h=0;h<d;h++) { var n=a.feed.entry[h]; var e=n.title.$t; var m=n.published.$t.substring(0,10); var j; for(var g=0;g<n.link.length;g++) { if(n.link[g].rel=="alternate") { j=n.link[g].href; break } } var o=""; for(var g=0;g<n.link.length;g++) { if(n.link[g].rel=="enclosure") { o=n.link[g].href; break } } var c=""; if("category" in n) { for(var g=0;g<n.category.length;g++) { c=n.category[g].term; var f=c.lastIndexOf(";"); if(f!=-1) { c=c.substring(0,f) } postLabels[ii]=c; postTitle[ii]=e; postDate[ii]=m; postUrl[ii]=j; postMp3[ii]=o; if(h<10){postBaru[ii]=true}else{postBaru[ii]=false}ii=ii+1}}}}}b();sortBy="titleasc";sortPosts(sortBy);sortlabel();tocLoaded=true;displayToc2()}function filterPosts(a){scroll(0,0);postFilter=a;displayToc(postFilter)}function allPosts(){sortlabel();postFilter="";displayToc(postFilter)}function sortPosts(d){function c(e,g){var f=postTitle[e];postTitle[e]=postTitle[g];postTitle[g]=f;var f=postDate[e];postDate[e]=postDate[g];postDate[g]=f;var f=postUrl[e];postUrl[e]=postUrl[g];postUrl[g]=f;var f=postLabels[e];postLabels[e]=postLabels[g];postLabels[g]=f;var f=postMp3[e];postMp3[e]=postMp3[g];postMp3[g]=f;var f=postBaru[e];postBaru[e]=postBaru[g];postBaru[g]=f}for(var b=0;b<postTitle.length-1;b++){for(var a=b+1;a<postTitle.length;a++){if(d=="titleasc"){if(postTitle[b]>postTitle[a]){c(b,a)}}if(d=="titledesc"){if(postTitle[b]<postTitle[a]){c(b,a)}}if(d=="dateoldest"){if(postDate[b]>postDate[a]){c(b,a)}}if(d=="datenewest"){if(postDate[b]<postDate[a]){c(b,a)}}if(d=="orderlabel"){if(postLabels[b]>postLabels[a]){c(b,a)}}}}}function sortlabel(){sortBy="orderlabel";sortPosts(sortBy);var a=0;var b=0;while(b<postTitle.length){temp1=postLabels[b];firsti=a;do{a=a+1}while(postLabels[a]==temp1);b=a;sortPosts2(firsti,a);if(b>postTitle.length){break}}}function sortPosts2(d,c){function e(f,h){var g=postTitle[f];postTitle[f]=postTitle[h];postTitle[h]=g;var g=postDate[f];postDate[f]=postDate[h];postDate[h]=g;var g=postUrl[f];postUrl[f]=postUrl[h];postUrl[h]=g;var g=postLabels[f];postLabels[f]=postLabels[h];postLabels[h]=g;var g=postMp3[f];postMp3[f]=postMp3[h];postMp3[h]=g;var g=postBaru[f];postBaru[f]=postBaru[h];postBaru[h]=g}for(var b=d;b<c-1;b++){for(var a=b+1;a<c;a++){if(postTitle[b]>postTitle[a]){e(b,a)}}}}function displayToc(a){var l=0;var h="";var e="Judul Artikel";var m="Klik untuk sortir berdasarkan judul";var d="Tanggal";var k="Klik untuk Sortir bedasarkan tanggal";var c="Kategori";var j="";if(sortBy=="titleasc"){m+=" (descending)";k+=" (newest first)"}if(sortBy=="titledesc"){m+=" (ascending)";k+=" (newest first)"}if(sortBy=="dateoldest"){m+=" (ascending)";k+=" (newest first)"}if(sortBy=="datenewest"){m+=" (ascending)";k+=" (oldest first)"}if(postFilter!=""){j="Klik untuk menampilkan semua"}h+="<table>";h+="<tr>";h+='<td class="toc-header-col1">';h+='<a href="javascript:toggleTitleSort();" title="'+m+'">'+e+"</a>";h+="</td>";h+='<td class="toc-header-col2">';h+='<a href="javascript:toggleDateSort();" title="'+k+'">'+d+"</a>";h+="</td>";h+='<td class="toc-header-col3">';h+='<a href="javascript:allPosts();" title="'+j+'">'+c+"</a>";h+="</td>";h+='<td class="toc-header-col4">';h+="Download MP3";h+="</td>";h+="</tr>";for(var g=0;g<postTitle.length;g++){if(a==""){h+='<tr><td class="toc-entry-col1"><a href="'+postUrl[g]+'">'+postTitle[g]+'</a></td><td class="toc-entry-col2">'+postDate[g]+'</td><td class="toc-entry-col3">'+postLabels[g]+'</td><td class="toc-entry-col4"><a href="'+postMp3[g]+'">Download</a></td></tr>';l++}else{z=postLabels[g].lastIndexOf(a);if(z!=-1){h+='<tr><td class="toc-entry-col1"><a href="'+postUrl[g]+'">'+postTitle[g]+'</a></td><td class="toc-entry-col2">'+postDate[g]+'</td><td class="toc-entry-col3">'+postLabels[g]+'</td><td class="toc-entry-col4"><a href="'+postMp3[g]+'">Download</a></td></tr>';l++}}}h+="</table>";if(l==postTitle.length){var f='<span class="toc-note">Menampilkan Semua '+postTitle.length+" Artikel<br/></span>"}else{var f='<span class="toc-note">Menampilkan '+l+" artikel dengan kategori '";f+=postFilter+"' dari "+postTitle.length+" Total Artikel<br/></span>"}var b=document.getElementById("toc");b.innerHTML=f+h}function displayToc2(){var a=0;var b=0;while(b<postTitle.length){temp1=postLabels[b];if(temp1.indexOf("Ustadz")==-1){if(temp1.indexOf("Syeikh")==-1){document.write("<p/>");document.write('<p><a href="/search/label/'+temp1+'">'+temp1+"</a></p><ol>")}}firsti=a;do{if(temp1.indexOf("Ustadz")==-1){if(temp1.indexOf("Syeikh")==-1){document.write("<li>");document.write('<a href="'+postUrl[a]+'">'+postTitle[a]+"</a>");if(postBaru[a]==true){document.write(' - <strong><em><span style="color: rgb(255, 0, 0);">New !!</span> </em></strong>')}document.write("</li>")}}a=a+1}while(postLabels[a]==temp1);b=a;if(temp1.indexOf("Ustadz")==-1){if(temp1.indexOf("Syeikh")==-1){document.write("</ol>")}}sortPosts2(firsti,a);if(b>postTitle.length){break}}}function toggleTitleSort(){if(sortBy=="titleasc"){sortBy="titledesc"}else{sortBy="titleasc"}sortPosts(sortBy);displayToc(postFilter)}function toggleDateSort(){if(sortBy=="datenewest"){sortBy="dateoldest"}else{sortBy="datenewest"}sortPosts(sortBy);displayToc(postFilter)}function showToc(){if(tocLoaded){displayToc(postFilter);var a=document.getElementById("toclink")}else{alert("Just wait... TOC is loading")}}function hideToc(){var a=document.getElementById("toc");a.innerHTML="";var b=document.getElementById("toclink");b.innerHTML='<a href="#" onclick="scroll(0,0); showToc(); Effect.toggle(\'toc-result\',\'blind\');">?? Menampilkan Daftar Isi</a> <img src="http://radiorodja.googlepages.com/new_1.gif"/>'}function looptemp2(){for(var a=0;a<numberfeed;a++){document.write("<br>");document.write('Post Link : <a href="'+postUrl[a]+'">'+postTitle[a]+"</a><br>");document.write('Download mp3 : <a href="'+postMp3[a]+'">'+postTitle[a]+"</a><br>");document.write("<br>")}};
JavaScript
// http://mrl.nyu.edu/~perlin/noise/ var ImprovedNoise = function () { var p = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10, 23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87, 174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211, 133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5, 202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119, 248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232, 178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249, 14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205, 93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]; for (var i=0; i < 256 ; i++) { p[256+i] = p[i]; } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp(t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } return { noise: function (x, y, z) { var floorX = ~~x, floorY = ~~y, floorZ = ~~z; var X = floorX & 255, Y = floorY & 255, Z = floorZ & 255; x -= floorX; y -= floorY; z -= floorZ; var xMinus1 = x -1, yMinus1 = y - 1, zMinus1 = z - 1; var u = fade(x), v = fade(y), w = fade(z); var A = p[X]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], xMinus1, y, z)), lerp(u, grad(p[AB], x, yMinus1, z), grad(p[BB], xMinus1, yMinus1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, zMinus1), grad(p[BA+1], xMinus1, y, z-1)), lerp(u, grad(p[AB+1], x, yMinus1, zMinus1), grad(p[BB+1], xMinus1, yMinus1, zMinus1)))); } } }
JavaScript
/** * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com */ /*global THREE, console */ // This set of controls performs orbiting, dollying (zooming), and panning. It maintains // the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is // supported. // // Orbit - left mouse / touch: one finger move // Zoom - middle mouse, or mousewheel / touch: two finger spread or squish // Pan - right mouse, or arrow keys / touch: three finter swipe // // This is a drop-in replacement for (most) TrackballControls used in examples. // That is, include this js file and wherever you see: // controls = new THREE.TrackballControls( camera ); // controls.target.z = 150; // Simple substitute "OrbitControls" and the control should work as-is. THREE.OrbitControls = function ( object, domElement ) { this.object = object; this.domElement = ( domElement !== undefined ) ? domElement : document; // API // Set to false to disable this control this.enabled = true; // "target" sets the location of focus, where the control orbits around // and where it pans with respect to. this.target = new THREE.Vector3(); // center is old, deprecated; use "target" instead this.center = this.target; // This option actually enables dollying in and out; left as "zoom" for // backwards compatibility this.noZoom = false; this.zoomSpeed = 1.0; // Limits to how far you can dolly in and out this.minDistance = 0; this.maxDistance = Infinity; // Set to true to disable this control this.noRotate = false; this.rotateSpeed = 1.0; // Set to true to disable this control this.noPan = false; this.keyPanSpeed = 7.0; // pixels moved per arrow key push // Set to true to automatically rotate around the target this.autoRotate = false; this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 // How far you can orbit vertically, upper and lower limits. // Range is 0 to Math.PI radians. this.minPolarAngle = 0; // radians this.maxPolarAngle = Math.PI; // radians // Set to true to disable use of the keys this.noKeys = false; // The four arrow keys this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; //////////// // internals var scope = this; var EPS = 0.000001; var rotateStart = new THREE.Vector2(); var rotateEnd = new THREE.Vector2(); var rotateDelta = new THREE.Vector2(); var panStart = new THREE.Vector2(); var panEnd = new THREE.Vector2(); var panDelta = new THREE.Vector2(); var panOffset = new THREE.Vector3(); var offset = new THREE.Vector3(); var dollyStart = new THREE.Vector2(); var dollyEnd = new THREE.Vector2(); var dollyDelta = new THREE.Vector2(); var phiDelta = 0; var thetaDelta = 0; var scale = 1; var pan = new THREE.Vector3(); var lastPosition = new THREE.Vector3(); var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; var state = STATE.NONE; // for reset this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); // events var changeEvent = { type: 'change' }; var startEvent = { type: 'start'}; var endEvent = { type: 'end'}; this.rotateLeft = function ( angle ) { if ( angle === undefined ) { angle = getAutoRotationAngle(); } thetaDelta -= angle; }; this.rotateUp = function ( angle ) { if ( angle === undefined ) { angle = getAutoRotationAngle(); } phiDelta -= angle; }; // pass in distance in world space to move left this.panLeft = function ( distance ) { var te = this.object.matrix.elements; // get X column of matrix panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] ); panOffset.multiplyScalar( - distance ); pan.add( panOffset ); }; // pass in distance in world space to move up this.panUp = function ( distance ) { var te = this.object.matrix.elements; // get Y column of matrix panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] ); panOffset.multiplyScalar( distance ); pan.add( panOffset ); }; // pass in x,y of change desired in pixel space, // right and down are positive this.pan = function ( deltaX, deltaY ) { var element = scope.domElement === document ? scope.domElement.body : scope.domElement; if ( scope.object.fov !== undefined ) { // perspective var position = scope.object.position; var offset = position.clone().sub( scope.target ); var targetDistance = offset.length(); // half of the fov is center to top of screen targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); // we actually don't use screenWidth, since perspective camera is fixed to screen height scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight ); scope.panUp( 2 * deltaY * targetDistance / element.clientHeight ); } else if ( scope.object.top !== undefined ) { // orthographic scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth ); scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight ); } else { // camera neither orthographic or perspective console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); } }; this.dollyIn = function ( dollyScale ) { if ( dollyScale === undefined ) { dollyScale = getZoomScale(); } scale /= dollyScale; }; this.dollyOut = function ( dollyScale ) { if ( dollyScale === undefined ) { dollyScale = getZoomScale(); } scale *= dollyScale; }; this.update = function () { var position = this.object.position; offset.copy( position ).sub( this.target ); // angle from z-axis around y-axis var theta = Math.atan2( offset.x, offset.z ); // angle from y-axis var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); if ( this.autoRotate ) { this.rotateLeft( getAutoRotationAngle() ); } theta += thetaDelta; phi += phiDelta; // restrict phi to be between desired limits phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); // restrict phi to be betwee EPS and PI-EPS phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); var radius = offset.length() * scale; // restrict radius to be between desired limits radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); // move target to panned location this.target.add( pan ); offset.x = radius * Math.sin( phi ) * Math.sin( theta ); offset.y = radius * Math.cos( phi ); offset.z = radius * Math.sin( phi ) * Math.cos( theta ); position.copy( this.target ).add( offset ); this.object.lookAt( this.target ); thetaDelta = 0; phiDelta = 0; scale = 1; pan.set( 0, 0, 0 ); if ( lastPosition.distanceTo( this.object.position ) > 0 ) { this.dispatchEvent( changeEvent ); lastPosition.copy( this.object.position ); } }; this.reset = function () { state = STATE.NONE; this.target.copy( this.target0 ); this.object.position.copy( this.position0 ); this.update(); }; function getAutoRotationAngle() { return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; } function getZoomScale() { return Math.pow( 0.95, scope.zoomSpeed ); } function onMouseDown( event ) { if ( scope.enabled === false ) return; event.preventDefault(); if ( event.button === 0 ) { if ( scope.noRotate === true ) return; state = STATE.ROTATE; rotateStart.set( event.clientX, event.clientY ); } else if ( event.button === 1 ) { if ( scope.noZoom === true ) return; state = STATE.DOLLY; dollyStart.set( event.clientX, event.clientY ); } else if ( event.button === 2 ) { if ( scope.noPan === true ) return; state = STATE.PAN; panStart.set( event.clientX, event.clientY ); } scope.domElement.addEventListener( 'mousemove', onMouseMove, false ); scope.domElement.addEventListener( 'mouseup', onMouseUp, false ); scope.dispatchEvent( startEvent ); } function onMouseMove( event ) { if ( scope.enabled === false ) return; event.preventDefault(); var element = scope.domElement === document ? scope.domElement.body : scope.domElement; if ( state === STATE.ROTATE ) { if ( scope.noRotate === true ) return; rotateEnd.set( event.clientX, event.clientY ); rotateDelta.subVectors( rotateEnd, rotateStart ); // rotating across whole screen goes 360 degrees around scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); // rotating up and down along whole screen attempts to go 360, but limited to 180 scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); rotateStart.copy( rotateEnd ); } else if ( state === STATE.DOLLY ) { if ( scope.noZoom === true ) return; dollyEnd.set( event.clientX, event.clientY ); dollyDelta.subVectors( dollyEnd, dollyStart ); if ( dollyDelta.y > 0 ) { scope.dollyIn(); } else { scope.dollyOut(); } dollyStart.copy( dollyEnd ); } else if ( state === STATE.PAN ) { if ( scope.noPan === true ) return; panEnd.set( event.clientX, event.clientY ); panDelta.subVectors( panEnd, panStart ); scope.pan( panDelta.x, panDelta.y ); panStart.copy( panEnd ); } scope.update(); } function onMouseUp( /* event */ ) { if ( scope.enabled === false ) return; scope.domElement.removeEventListener( 'mousemove', onMouseMove, false ); scope.domElement.removeEventListener( 'mouseup', onMouseUp, false ); scope.dispatchEvent( endEvent ); state = STATE.NONE; } function onMouseWheel( event ) { if ( scope.enabled === false || scope.noZoom === true ) return; event.preventDefault(); var delta = 0; if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 delta = event.wheelDelta; } else if ( event.detail !== undefined ) { // Firefox delta = - event.detail; } if ( delta > 0 ) { scope.dollyOut(); } else { scope.dollyIn(); } scope.update(); scope.dispatchEvent( startEvent ); scope.dispatchEvent( endEvent ); } function onKeyDown( event ) { if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; switch ( event.keyCode ) { case scope.keys.UP: scope.pan( 0, scope.keyPanSpeed ); scope.update(); break; case scope.keys.BOTTOM: scope.pan( 0, - scope.keyPanSpeed ); scope.update(); break; case scope.keys.LEFT: scope.pan( scope.keyPanSpeed, 0 ); scope.update(); break; case scope.keys.RIGHT: scope.pan( - scope.keyPanSpeed, 0 ); scope.update(); break; } } function touchstart( event ) { if ( scope.enabled === false ) return; switch ( event.touches.length ) { case 1: // one-fingered touch: rotate if ( scope.noRotate === true ) return; state = STATE.TOUCH_ROTATE; rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; case 2: // two-fingered touch: dolly if ( scope.noZoom === true ) return; state = STATE.TOUCH_DOLLY; var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; var distance = Math.sqrt( dx * dx + dy * dy ); dollyStart.set( 0, distance ); break; case 3: // three-fingered touch: pan if ( scope.noPan === true ) return; state = STATE.TOUCH_PAN; panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; default: state = STATE.NONE; } scope.dispatchEvent( startEvent ); } function touchmove( event ) { if ( scope.enabled === false ) return; event.preventDefault(); event.stopPropagation(); var element = scope.domElement === document ? scope.domElement.body : scope.domElement; switch ( event.touches.length ) { case 1: // one-fingered touch: rotate if ( scope.noRotate === true ) return; if ( state !== STATE.TOUCH_ROTATE ) return; rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); rotateDelta.subVectors( rotateEnd, rotateStart ); // rotating across whole screen goes 360 degrees around scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); // rotating up and down along whole screen attempts to go 360, but limited to 180 scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); rotateStart.copy( rotateEnd ); scope.update(); break; case 2: // two-fingered touch: dolly if ( scope.noZoom === true ) return; if ( state !== STATE.TOUCH_DOLLY ) return; var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; var distance = Math.sqrt( dx * dx + dy * dy ); dollyEnd.set( 0, distance ); dollyDelta.subVectors( dollyEnd, dollyStart ); if ( dollyDelta.y > 0 ) { scope.dollyOut(); } else { scope.dollyIn(); } dollyStart.copy( dollyEnd ); scope.update(); break; case 3: // three-fingered touch: pan if ( scope.noPan === true ) return; if ( state !== STATE.TOUCH_PAN ) return; panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); panDelta.subVectors( panEnd, panStart ); scope.pan( panDelta.x, panDelta.y ); panStart.copy( panEnd ); scope.update(); break; default: state = STATE.NONE; } } function touchend( /* event */ ) { if ( scope.enabled === false ) return; scope.dispatchEvent( endEvent ); state = STATE.NONE; } this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); this.domElement.addEventListener( 'mousedown', onMouseDown, false ); this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox this.domElement.addEventListener( 'touchstart', touchstart, false ); this.domElement.addEventListener( 'touchend', touchend, false ); this.domElement.addEventListener( 'touchmove', touchmove, false ); window.addEventListener( 'keydown', onKeyDown, false ); }; THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype );
JavaScript
/* * Cloth Simulation using a relaxed constrains solver */ // Suggested Readings // Advanced Character Physics by Thomas Jakobsen Character // http://freespace.virgin.net/hugo.elias/models/m_cloth.htm // http://en.wikipedia.org/wiki/Cloth_modeling // http://cg.alexandra.dk/tag/spring-mass-system/ // Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf var DAMPING = 0.03; var DRAG = 1 - DAMPING; var MASS = .1; var restDistance = 25; var xSegs = 10; // var ySegs = 10; // var clothFunction = plane(restDistance * xSegs, restDistance * ySegs); var cloth = new Cloth(xSegs, ySegs); var GRAVITY = 981 * 1.4; // var gravity = new THREE.Vector3( 0, -GRAVITY, 0 ).multiplyScalar(MASS); var TIMESTEP = 18 / 1000; var TIMESTEP_SQ = TIMESTEP * TIMESTEP; var pins = []; var wind = true; var windStrength = 2; var windForce = new THREE.Vector3(0,0,0); var ballPosition = new THREE.Vector3(0, -45, 0); var ballSize = 60; //40 var tmpForce = new THREE.Vector3(); var lastTime; function plane(width, height) { return function(u, v) { var x = (u-0.5) * width; var y = (v+0.5) * height; var z = 0; return new THREE.Vector3(x, y, z); }; } function Particle(x, y, z, mass) { this.position = clothFunction(x, y); // position this.previous = clothFunction(x, y); // previous this.original = clothFunction(x, y); this.a = new THREE.Vector3(0, 0, 0); // acceleration this.mass = mass; this.invMass = 1 / mass; this.tmp = new THREE.Vector3(); this.tmp2 = new THREE.Vector3(); } // Force -> Acceleration Particle.prototype.addForce = function(force) { this.a.add( this.tmp2.copy(force).multiplyScalar(this.invMass) ); }; // Performs verlet integration Particle.prototype.integrate = function(timesq) { var newPos = this.tmp.subVectors(this.position, this.previous); newPos.multiplyScalar(DRAG).add(this.position); newPos.add(this.a.multiplyScalar(timesq)); this.tmp = this.previous; this.previous = this.position; this.position = newPos; this.a.set(0, 0, 0); } var diff = new THREE.Vector3(); function satisifyConstrains(p1, p2, distance) { diff.subVectors(p2.position, p1.position); var currentDist = diff.length(); if (currentDist==0) return; // prevents division by 0 var correction = diff.multiplyScalar(1 - distance/currentDist); var correctionHalf = correction.multiplyScalar(0.5); p1.position.add(correctionHalf); p2.position.sub(correctionHalf); } function Cloth(w, h) { w = w || 10; h = h || 10; this.w = w; this.h = h; var particles = []; var constrains = []; var u, v; // Create particles for (v=0;v<=h;v++) { for (u=0;u<=w;u++) { particles.push( new Particle(u/w, v/h, 0, MASS) ); } } // Structural for (v=0;v<h;v++) { for (u=0;u<w;u++) { constrains.push([ particles[index(u, v)], particles[index(u, v+1)], restDistance ]); constrains.push([ particles[index(u, v)], particles[index(u+1, v)], restDistance ]); } } for (u=w, v=0;v<h;v++) { constrains.push([ particles[index(u, v)], particles[index(u, v+1)], restDistance ]); } for (v=h, u=0;u<w;u++) { constrains.push([ particles[index(u, v)], particles[index(u+1, v)], restDistance ]); } // While many system uses shear and bend springs, // the relax constrains model seem to be just fine // using structural springs. // Shear // var diagonalDist = Math.sqrt(restDistance * restDistance * 2); // for (v=0;v<h;v++) { // for (u=0;u<w;u++) { // constrains.push([ // particles[index(u, v)], // particles[index(u+1, v+1)], // diagonalDist // ]); // constrains.push([ // particles[index(u+1, v)], // particles[index(u, v+1)], // diagonalDist // ]); // } // } this.particles = particles; this.constrains = constrains; function index(u, v) { return u + v * (w + 1); } this.index = index; } function simulate(time) { if (!lastTime) { lastTime = time; return; } var i, il, particles, particle, pt, constrains, constrain; // Aerodynamics forces if (wind) { var face, faces = clothGeometry.faces, normal; particles = cloth.particles; for (i=0,il=faces.length;i<il;i++) { face = faces[i]; normal = face.normal; tmpForce.copy(normal).normalize().multiplyScalar(normal.dot(windForce)); particles[face.a].addForce(tmpForce); particles[face.b].addForce(tmpForce); particles[face.c].addForce(tmpForce); } } for (particles = cloth.particles, i=0, il = particles.length ;i<il;i++) { particle = particles[i]; particle.addForce(gravity); particle.integrate(TIMESTEP_SQ); } // Start Constrains constrains = cloth.constrains, il = constrains.length; for (i=0;i<il;i++) { constrain = constrains[i]; satisifyConstrains(constrain[0], constrain[1], constrain[2]); } // Ball Constrains ballPosition.z = -Math.sin(Date.now()/600) * 90 ; //+ 40; ballPosition.x = Math.cos(Date.now()/400) * 70 if (sphere.visible) for (particles = cloth.particles, i=0, il = particles.length ;i<il;i++) { particle = particles[i]; pos = particle.position; diff.subVectors(pos, ballPosition); if (diff.length() < ballSize) { // collided diff.normalize().multiplyScalar(ballSize); pos.copy(ballPosition).add(diff); } } // Floor Constains for (particles = cloth.particles, i=0, il = particles.length ;i<il;i++) { particle = particles[i]; pos = particle.position; if (pos.y < -250) { pos.y = -250; } } // Pin Constrains for (i=0, il=pins.length;i<il;i++) { var xy = pins[i]; var p = particles[xy]; p.position.copy(p.original); p.previous.copy(p.original); } }
JavaScript
/** * @author alteredq / http://alteredqualia.com/ */ THREE.PDBLoader = function () {}; THREE.PDBLoader.prototype = { constructor: THREE.OBJLoader, load: function ( url, callback ) { var worker, scope = this; this.loadAjaxPDB( this, url, callback ); }, loadAjaxPDB: function ( context, url, callback, callbackProgress ) { var xhr = new XMLHttpRequest(); var length = 0; xhr.onreadystatechange = function () { if ( xhr.readyState === xhr.DONE ) { if ( xhr.status === 200 || xhr.status === 0 ) { if ( xhr.responseText ) { var json = context.parsePDB( xhr.responseText ); context.createModel( json, callback ); } else { console.warn( "THREE.PDBLoader: [" + url + "] seems to be unreachable or file there is empty" ); } } else { console.error( "THREE.PDBLoader: Couldn't load [" + url + "] [" + xhr.status + "]" ); } } else if ( xhr.readyState === xhr.LOADING ) { if ( callbackProgress ) { if ( length === 0 ) { length = xhr.getResponseHeader( "Content-Length" ); } callbackProgress( { total: length, loaded: xhr.responseText.length } ); } } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) { length = xhr.getResponseHeader( "Content-Length" ); } }; xhr.open( "GET", url, true ); if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); xhr.setRequestHeader( "Content-Type", "text/plain" ); xhr.send( null ); }, // Based on CanvasMol PDB parser parsePDB: function ( text ) { function trim( text ) { return text.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function capitalize( text ) { return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase(); } function hash( s, e ) { return "s" + Math.min( s, e ) + "e" + Math.max( s, e ); } function parseBond( start, length ) { var eatom = parseInt( lines[ i ].substr( start, length ) ); if( eatom ) { var h = hash( satom, eatom ); if ( bhash[ h ] == undefined ) { bonds.push( [ satom - 1, eatom - 1, 1 ] ); bhash[ h ] = bonds.length - 1; } else { // doesn't really work as almost all PDBs // have just normal bonds appearing multiple // times instead of being double/triple bonds //bonds[bhash[h]][2] += 1; } } } var CPK = {"h":[255,255,255],"he":[217,255,255],"li":[204,128,255],"be":[194,255,0],"b":[255,181,181],"c":[144,144,144],"n":[48,80,248],"o":[255,13,13],"f":[144,224,80],"ne":[179,227,245],"na":[171,92,242],"mg":[138,255,0],"al":[191,166,166],"si":[240,200,160],"p":[255,128,0],"s":[255,255,48],"cl":[31,240,31],"ar":[128,209,227],"k":[143,64,212],"ca":[61,255,0],"sc":[230,230,230],"ti":[191,194,199],"v":[166,166,171],"cr":[138,153,199],"mn":[156,122,199],"fe":[224,102,51],"co":[240,144,160],"ni":[80,208,80],"cu":[200,128,51],"zn":[125,128,176],"ga":[194,143,143],"ge":[102,143,143],"as":[189,128,227],"se":[255,161,0],"br":[166,41,41],"kr":[92,184,209],"rb":[112,46,176],"sr":[0,255,0],"y":[148,255,255],"zr":[148,224,224],"nb":[115,194,201],"mo":[84,181,181],"tc":[59,158,158],"ru":[36,143,143],"rh":[10,125,140],"pd":[0,105,133],"ag":[192,192,192],"cd":[255,217,143],"in":[166,117,115],"sn":[102,128,128],"sb":[158,99,181],"te":[212,122,0],"i":[148,0,148],"xe":[66,158,176],"cs":[87,23,143],"ba":[0,201,0],"la":[112,212,255],"ce":[255,255,199],"pr":[217,255,199],"nd":[199,255,199],"pm":[163,255,199],"sm":[143,255,199],"eu":[97,255,199],"gd":[69,255,199],"tb":[48,255,199],"dy":[31,255,199],"ho":[0,255,156],"er":[0,230,117],"tm":[0,212,82],"yb":[0,191,56],"lu":[0,171,36],"hf":[77,194,255],"ta":[77,166,255],"w":[33,148,214],"re":[38,125,171],"os":[38,102,150],"ir":[23,84,135],"pt":[208,208,224],"au":[255,209,35],"hg":[184,184,208],"tl":[166,84,77],"pb":[87,89,97],"bi":[158,79,181],"po":[171,92,0],"at":[117,79,69],"rn":[66,130,150],"fr":[66,0,102],"ra":[0,125,0],"ac":[112,171,250],"th":[0,186,255],"pa":[0,161,255],"u":[0,143,255],"np":[0,128,255],"pu":[0,107,255],"am":[84,92,242],"cm":[120,92,227],"bk":[138,79,227],"cf":[161,54,212],"es":[179,31,212],"fm":[179,31,186],"md":[179,13,166],"no":[189,13,135],"lr":[199,0,102],"rf":[204,0,89],"db":[209,0,79],"sg":[217,0,69],"bh":[224,0,56],"hs":[230,0,46],"mt":[235,0,38], "ds":[235,0,38],"rg":[235,0,38],"cn":[235,0,38],"uut":[235,0,38],"uuq":[235,0,38],"uup":[235,0,38],"uuh":[235,0,38],"uus":[235,0,38],"uuo":[235,0,38]}; var atoms = []; var bonds = []; var histogram = {}; var bhash = {}; var lines = text.split( "\n" ); var x, y, z, e; for( var i = 0, il = lines.length; i < il; ++ i ) { if( lines[i].substr(0,4)=="ATOM" || lines[i].substr(0,6)=="HETATM" ) { x = parseFloat( lines[i].substr(30,7) ); y = parseFloat( lines[i].substr(38,7) ); z = parseFloat( lines[i].substr(46,7) ); e = trim( lines[i].substr(76,2) ).toLowerCase(); if ( e=="" ) e = trim(lines[i].substr(12,2)).toLowerCase(); atoms.push( [ x,y,z, CPK[e], capitalize(e) ] ); if (histogram[e]==undefined) histogram[e] = 1; else histogram[e] += 1; } else if(lines[i].substr(0,6)=="CONECT") { var satom = parseInt( lines[i].substr(6,5) ); parseBond(11,5); parseBond(16,5); parseBond(21,5); parseBond(26,5); } } return { "ok": true, "atoms": atoms, "bonds": bonds, "histogram": histogram }; }, createModel: function ( json, callback ) { var scope = this, geometryAtoms = new THREE.Geometry(), geometryBonds = new THREE.Geometry(); geometryAtoms.elements = []; var atoms = json.atoms; var bonds = json.bonds; for ( var i = 0; i < atoms.length; i ++ ) { var atom = atoms[ i ]; var x = atom[ 0 ]; var y = atom[ 1 ]; var z = atom[ 2 ]; var position = new THREE.Vector3( x, y, z ); geometryAtoms.vertices.push( position ); var r = atom[ 3 ][ 0 ] / 255; var g = atom[ 3 ][ 1 ] / 255; var b = atom[ 3 ][ 2 ] / 255; var color = new THREE.Color(); color.setRGB( r, g, b ); geometryAtoms.colors.push( color ); geometryAtoms.elements.push( atom[ 4 ] ); } for ( var i = 0; i < bonds.length; i ++ ) { var bond = bonds[ i ]; var start = bond[ 0 ]; var end = bond[ 1 ]; var vertex1 = geometryAtoms.vertices[ start ]; var vertex2 = geometryAtoms.vertices[ end ]; geometryBonds.vertices.push( vertex1.clone() ); geometryBonds.vertices.push( vertex2.clone() ); } callback( geometryAtoms, geometryBonds ); } }
JavaScript
var LZMA = LZMA || {}; LZMA.OutWindow = function(){ this._windowSize = 0; }; LZMA.OutWindow.prototype.create = function(windowSize){ if ( (!this._buffer) || (this._windowSize !== windowSize) ){ this._buffer = []; } this._windowSize = windowSize; this._pos = 0; this._streamPos = 0; }; LZMA.OutWindow.prototype.flush = function(){ var size = this._pos - this._streamPos; if (size !== 0){ while(size --){ this._stream.writeByte(this._buffer[this._streamPos ++]); } if (this._pos >= this._windowSize){ this._pos = 0; } this._streamPos = this._pos; } }; LZMA.OutWindow.prototype.releaseStream = function(){ this.flush(); this._stream = null; }; LZMA.OutWindow.prototype.setStream = function(stream){ this.releaseStream(); this._stream = stream; }; LZMA.OutWindow.prototype.init = function(solid){ if (!solid){ this._streamPos = 0; this._pos = 0; } }; LZMA.OutWindow.prototype.copyBlock = function(distance, len){ var pos = this._pos - distance - 1; if (pos < 0){ pos += this._windowSize; } while(len --){ if (pos >= this._windowSize){ pos = 0; } this._buffer[this._pos ++] = this._buffer[pos ++]; if (this._pos >= this._windowSize){ this.flush(); } } }; LZMA.OutWindow.prototype.putByte = function(b){ this._buffer[this._pos ++] = b; if (this._pos >= this._windowSize){ this.flush(); } }; LZMA.OutWindow.prototype.getByte = function(distance){ var pos = this._pos - distance - 1; if (pos < 0){ pos += this._windowSize; } return this._buffer[pos]; }; LZMA.RangeDecoder = function(){ }; LZMA.RangeDecoder.prototype.setStream = function(stream){ this._stream = stream; }; LZMA.RangeDecoder.prototype.releaseStream = function(){ this._stream = null; }; LZMA.RangeDecoder.prototype.init = function(){ var i = 5; this._code = 0; this._range = -1; while(i --){ this._code = (this._code << 8) | this._stream.readByte(); } }; LZMA.RangeDecoder.prototype.decodeDirectBits = function(numTotalBits){ var result = 0, i = numTotalBits, t; while(i --){ this._range >>>= 1; t = (this._code - this._range) >>> 31; this._code -= this._range & (t - 1); result = (result << 1) | (1 - t); if ( (this._range & 0xff000000) === 0){ this._code = (this._code << 8) | this._stream.readByte(); this._range <<= 8; } } return result; }; LZMA.RangeDecoder.prototype.decodeBit = function(probs, index){ var prob = probs[index], newBound = (this._range >>> 11) * prob; if ( (this._code ^ 0x80000000) < (newBound ^ 0x80000000) ){ this._range = newBound; probs[index] += (2048 - prob) >>> 5; if ( (this._range & 0xff000000) === 0){ this._code = (this._code << 8) | this._stream.readByte(); this._range <<= 8; } return 0; } this._range -= newBound; this._code -= newBound; probs[index] -= prob >>> 5; if ( (this._range & 0xff000000) === 0){ this._code = (this._code << 8) | this._stream.readByte(); this._range <<= 8; } return 1; }; LZMA.initBitModels = function(probs, len){ while(len --){ probs[len] = 1024; } }; LZMA.BitTreeDecoder = function(numBitLevels){ this._models = []; this._numBitLevels = numBitLevels; }; LZMA.BitTreeDecoder.prototype.init = function(){ LZMA.initBitModels(this._models, 1 << this._numBitLevels); }; LZMA.BitTreeDecoder.prototype.decode = function(rangeDecoder){ var m = 1, i = this._numBitLevels; while(i --){ m = (m << 1) | rangeDecoder.decodeBit(this._models, m); } return m - (1 << this._numBitLevels); }; LZMA.BitTreeDecoder.prototype.reverseDecode = function(rangeDecoder){ var m = 1, symbol = 0, i = 0, bit; for (; i < this._numBitLevels; ++ i){ bit = rangeDecoder.decodeBit(this._models, m); m = (m << 1) | bit; symbol |= bit << i; } return symbol; }; LZMA.reverseDecode2 = function(models, startIndex, rangeDecoder, numBitLevels){ var m = 1, symbol = 0, i = 0, bit; for (; i < numBitLevels; ++ i){ bit = rangeDecoder.decodeBit(models, startIndex + m); m = (m << 1) | bit; symbol |= bit << i; } return symbol; }; LZMA.LenDecoder = function(){ this._choice = []; this._lowCoder = []; this._midCoder = []; this._highCoder = new LZMA.BitTreeDecoder(8); this._numPosStates = 0; }; LZMA.LenDecoder.prototype.create = function(numPosStates){ for (; this._numPosStates < numPosStates; ++ this._numPosStates){ this._lowCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); this._midCoder[this._numPosStates] = new LZMA.BitTreeDecoder(3); } }; LZMA.LenDecoder.prototype.init = function(){ var i = this._numPosStates; LZMA.initBitModels(this._choice, 2); while(i --){ this._lowCoder[i].init(); this._midCoder[i].init(); } this._highCoder.init(); }; LZMA.LenDecoder.prototype.decode = function(rangeDecoder, posState){ if (rangeDecoder.decodeBit(this._choice, 0) === 0){ return this._lowCoder[posState].decode(rangeDecoder); } if (rangeDecoder.decodeBit(this._choice, 1) === 0){ return 8 + this._midCoder[posState].decode(rangeDecoder); } return 16 + this._highCoder.decode(rangeDecoder); }; LZMA.Decoder2 = function(){ this._decoders = []; }; LZMA.Decoder2.prototype.init = function(){ LZMA.initBitModels(this._decoders, 0x300); }; LZMA.Decoder2.prototype.decodeNormal = function(rangeDecoder){ var symbol = 1; do{ symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); }while(symbol < 0x100); return symbol & 0xff; }; LZMA.Decoder2.prototype.decodeWithMatchByte = function(rangeDecoder, matchByte){ var symbol = 1, matchBit, bit; do{ matchBit = (matchByte >> 7) & 1; matchByte <<= 1; bit = rangeDecoder.decodeBit(this._decoders, ( (1 + matchBit) << 8) + symbol); symbol = (symbol << 1) | bit; if (matchBit !== bit){ while(symbol < 0x100){ symbol = (symbol << 1) | rangeDecoder.decodeBit(this._decoders, symbol); } break; } }while(symbol < 0x100); return symbol & 0xff; }; LZMA.LiteralDecoder = function(){ }; LZMA.LiteralDecoder.prototype.create = function(numPosBits, numPrevBits){ var i; if (this._coders && (this._numPrevBits === numPrevBits) && (this._numPosBits === numPosBits) ){ return; } this._numPosBits = numPosBits; this._posMask = (1 << numPosBits) - 1; this._numPrevBits = numPrevBits; this._coders = []; i = 1 << (this._numPrevBits + this._numPosBits); while(i --){ this._coders[i] = new LZMA.Decoder2(); } }; LZMA.LiteralDecoder.prototype.init = function(){ var i = 1 << (this._numPrevBits + this._numPosBits); while(i --){ this._coders[i].init(); } }; LZMA.LiteralDecoder.prototype.getDecoder = function(pos, prevByte){ return this._coders[( (pos & this._posMask) << this._numPrevBits) + ( (prevByte & 0xff) >>> (8 - this._numPrevBits) )]; }; LZMA.Decoder = function(){ this._outWindow = new LZMA.OutWindow(); this._rangeDecoder = new LZMA.RangeDecoder(); this._isMatchDecoders = []; this._isRepDecoders = []; this._isRepG0Decoders = []; this._isRepG1Decoders = []; this._isRepG2Decoders = []; this._isRep0LongDecoders = []; this._posSlotDecoder = []; this._posDecoders = []; this._posAlignDecoder = new LZMA.BitTreeDecoder(4); this._lenDecoder = new LZMA.LenDecoder(); this._repLenDecoder = new LZMA.LenDecoder(); this._literalDecoder = new LZMA.LiteralDecoder(); this._dictionarySize = -1; this._dictionarySizeCheck = -1; this._posSlotDecoder[0] = new LZMA.BitTreeDecoder(6); this._posSlotDecoder[1] = new LZMA.BitTreeDecoder(6); this._posSlotDecoder[2] = new LZMA.BitTreeDecoder(6); this._posSlotDecoder[3] = new LZMA.BitTreeDecoder(6); }; LZMA.Decoder.prototype.setDictionarySize = function(dictionarySize){ if (dictionarySize < 0){ return false; } if (this._dictionarySize !== dictionarySize){ this._dictionarySize = dictionarySize; this._dictionarySizeCheck = Math.max(this._dictionarySize, 1); this._outWindow.create( Math.max(this._dictionarySizeCheck, 4096) ); } return true; }; LZMA.Decoder.prototype.setLcLpPb = function(lc, lp, pb){ var numPosStates = 1 << pb; if (lc > 8 || lp > 4 || pb > 4){ return false; } this._literalDecoder.create(lp, lc); this._lenDecoder.create(numPosStates); this._repLenDecoder.create(numPosStates); this._posStateMask = numPosStates - 1; return true; }; LZMA.Decoder.prototype.init = function(){ var i = 4; this._outWindow.init(false); LZMA.initBitModels(this._isMatchDecoders, 192); LZMA.initBitModels(this._isRep0LongDecoders, 192); LZMA.initBitModels(this._isRepDecoders, 12); LZMA.initBitModels(this._isRepG0Decoders, 12); LZMA.initBitModels(this._isRepG1Decoders, 12); LZMA.initBitModels(this._isRepG2Decoders, 12); LZMA.initBitModels(this._posDecoders, 114); this._literalDecoder.init(); while(i --){ this._posSlotDecoder[i].init(); } this._lenDecoder.init(); this._repLenDecoder.init(); this._posAlignDecoder.init(); this._rangeDecoder.init(); }; LZMA.Decoder.prototype.decode = function(inStream, outStream, outSize){ var state = 0, rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0, nowPos64 = 0, prevByte = 0, posState, decoder2, len, distance, posSlot, numDirectBits; this._rangeDecoder.setStream(inStream); this._outWindow.setStream(outStream); this.init(); while(outSize < 0 || nowPos64 < outSize){ posState = nowPos64 & this._posStateMask; if (this._rangeDecoder.decodeBit(this._isMatchDecoders, (state << 4) + posState) === 0){ decoder2 = this._literalDecoder.getDecoder(nowPos64 ++, prevByte); if (state >= 7){ prevByte = decoder2.decodeWithMatchByte(this._rangeDecoder, this._outWindow.getByte(rep0) ); }else{ prevByte = decoder2.decodeNormal(this._rangeDecoder); } this._outWindow.putByte(prevByte); state = state < 4? 0: state - (state < 10? 3: 6); }else{ if (this._rangeDecoder.decodeBit(this._isRepDecoders, state) === 1){ len = 0; if (this._rangeDecoder.decodeBit(this._isRepG0Decoders, state) === 0){ if (this._rangeDecoder.decodeBit(this._isRep0LongDecoders, (state << 4) + posState) === 0){ state = state < 7? 9: 11; len = 1; } }else{ if (this._rangeDecoder.decodeBit(this._isRepG1Decoders, state) === 0){ distance = rep1; }else{ if (this._rangeDecoder.decodeBit(this._isRepG2Decoders, state) === 0){ distance = rep2; }else{ distance = rep3; rep3 = rep2; } rep2 = rep1; } rep1 = rep0; rep0 = distance; } if (len === 0){ len = 2 + this._repLenDecoder.decode(this._rangeDecoder, posState); state = state < 7? 8: 11; } }else{ rep3 = rep2; rep2 = rep1; rep1 = rep0; len = 2 + this._lenDecoder.decode(this._rangeDecoder, posState); state = state < 7? 7: 10; posSlot = this._posSlotDecoder[len <= 5? len - 2: 3].decode(this._rangeDecoder); if (posSlot >= 4){ numDirectBits = (posSlot >> 1) - 1; rep0 = (2 | (posSlot & 1) ) << numDirectBits; if (posSlot < 14){ rep0 += LZMA.reverseDecode2(this._posDecoders, rep0 - posSlot - 1, this._rangeDecoder, numDirectBits); }else{ rep0 += this._rangeDecoder.decodeDirectBits(numDirectBits - 4) << 4; rep0 += this._posAlignDecoder.reverseDecode(this._rangeDecoder); if (rep0 < 0){ if (rep0 === -1){ break; } return false; } } }else{ rep0 = posSlot; } } if (rep0 >= nowPos64 || rep0 >= this._dictionarySizeCheck){ return false; } this._outWindow.copyBlock(rep0, len); nowPos64 += len; prevByte = this._outWindow.getByte(0); } } this._outWindow.flush(); this._outWindow.releaseStream(); this._rangeDecoder.releaseStream(); return true; }; LZMA.Decoder.prototype.setDecoderProperties = function(properties){ var value, lc, lp, pb, dictionarySize; if (properties.size < 5){ return false; } value = properties.readByte(); lc = value % 9; value = ~~(value / 9); lp = value % 5; pb = ~~(value / 5); if ( !this.setLcLpPb(lc, lp, pb) ){ return false; } dictionarySize = properties.readByte(); dictionarySize |= properties.readByte() << 8; dictionarySize |= properties.readByte() << 16; dictionarySize += properties.readByte() * 16777216; return this.setDictionarySize(dictionarySize); }; LZMA.decompress = function(properties, inStream, outStream, outSize){ var decoder = new LZMA.Decoder(); if ( !decoder.setDecoderProperties(properties) ){ throw "Incorrect stream properties"; } if ( !decoder.decode(inStream, outStream, outSize) ){ throw "Error in data stream"; } return true; };
JavaScript
importScripts( "lzma.js", "ctm.js" ); self.onmessage = function( event ) { var files = []; for ( var i = 0; i < event.data.offsets.length; i ++ ) { var stream = new CTM.Stream( event.data.data ); stream.offset = event.data.offsets[ i ]; files[ i ] = new CTM.File( stream ); } self.postMessage( files ); self.close(); }
JavaScript
/* Copyright (c) 2011 Juan Mellado Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* References: - "OpenCTM: The Open Compressed Triangle Mesh file format" by Marcus Geelnard http://openctm.sourceforge.net/ */ var CTM = CTM || {}; CTM.CompressionMethod = { RAW: 0x00574152, MG1: 0x0031474d, MG2: 0x0032474d }; CTM.Flags = { NORMALS: 0x00000001 }; CTM.File = function(stream){ this.load(stream); }; CTM.File.prototype.load = function(stream){ this.header = new CTM.FileHeader(stream); this.body = new CTM.FileBody(this.header); this.getReader().read(stream, this.body); }; CTM.File.prototype.getReader = function(){ var reader; switch(this.header.compressionMethod){ case CTM.CompressionMethod.RAW: reader = new CTM.ReaderRAW(); break; case CTM.CompressionMethod.MG1: reader = new CTM.ReaderMG1(); break; case CTM.CompressionMethod.MG2: reader = new CTM.ReaderMG2(); break; } return reader; }; CTM.FileHeader = function(stream){ stream.readInt32(); //magic "OCTM" this.fileFormat = stream.readInt32(); this.compressionMethod = stream.readInt32(); this.vertexCount = stream.readInt32(); this.triangleCount = stream.readInt32(); this.uvMapCount = stream.readInt32(); this.attrMapCount = stream.readInt32(); this.flags = stream.readInt32(); this.comment = stream.readString(); }; CTM.FileHeader.prototype.hasNormals = function(){ return this.flags & CTM.Flags.NORMALS; }; CTM.FileBody = function(header){ var i = header.triangleCount * 3, v = header.vertexCount * 3, n = header.hasNormals()? header.vertexCount * 3: 0, u = header.vertexCount * 2, a = header.vertexCount * 4, j = 0; var data = new ArrayBuffer( (i + v + n + (u * header.uvMapCount) + (a * header.attrMapCount) ) * 4); this.indices = new Uint32Array(data, 0, i); this.vertices = new Float32Array(data, i * 4, v); if ( header.hasNormals() ){ this.normals = new Float32Array(data, (i + v) * 4, n); } if (header.uvMapCount){ this.uvMaps = []; for (j = 0; j < header.uvMapCount; ++ j){ this.uvMaps[j] = {uv: new Float32Array(data, (i + v + n + (j * u) ) * 4, u) }; } } if (header.attrMapCount){ this.attrMaps = []; for (j = 0; j < header.attrMapCount; ++ j){ this.attrMaps[j] = {attr: new Float32Array(data, (i + v + n + (u * header.uvMapCount) + (j * a) ) * 4, a) }; } } }; CTM.FileMG2Header = function(stream){ stream.readInt32(); //magic "MG2H" this.vertexPrecision = stream.readFloat32(); this.normalPrecision = stream.readFloat32(); this.lowerBoundx = stream.readFloat32(); this.lowerBoundy = stream.readFloat32(); this.lowerBoundz = stream.readFloat32(); this.higherBoundx = stream.readFloat32(); this.higherBoundy = stream.readFloat32(); this.higherBoundz = stream.readFloat32(); this.divx = stream.readInt32(); this.divy = stream.readInt32(); this.divz = stream.readInt32(); this.sizex = (this.higherBoundx - this.lowerBoundx) / this.divx; this.sizey = (this.higherBoundy - this.lowerBoundy) / this.divy; this.sizez = (this.higherBoundz - this.lowerBoundz) / this.divz; }; CTM.ReaderRAW = function(){ }; CTM.ReaderRAW.prototype.read = function(stream, body){ this.readIndices(stream, body.indices); this.readVertices(stream, body.vertices); if (body.normals){ this.readNormals(stream, body.normals); } if (body.uvMaps){ this.readUVMaps(stream, body.uvMaps); } if (body.attrMaps){ this.readAttrMaps(stream, body.attrMaps); } }; CTM.ReaderRAW.prototype.readIndices = function(stream, indices){ stream.readInt32(); //magic "INDX" stream.readArrayInt32(indices); }; CTM.ReaderRAW.prototype.readVertices = function(stream, vertices){ stream.readInt32(); //magic "VERT" stream.readArrayFloat32(vertices); }; CTM.ReaderRAW.prototype.readNormals = function(stream, normals){ stream.readInt32(); //magic "NORM" stream.readArrayFloat32(normals); }; CTM.ReaderRAW.prototype.readUVMaps = function(stream, uvMaps){ var i = 0; for (; i < uvMaps.length; ++ i){ stream.readInt32(); //magic "TEXC" uvMaps[i].name = stream.readString(); uvMaps[i].filename = stream.readString(); stream.readArrayFloat32(uvMaps[i].uv); } }; CTM.ReaderRAW.prototype.readAttrMaps = function(stream, attrMaps){ var i = 0; for (; i < attrMaps.length; ++ i){ stream.readInt32(); //magic "ATTR" attrMaps[i].name = stream.readString(); stream.readArrayFloat32(attrMaps[i].attr); } }; CTM.ReaderMG1 = function(){ }; CTM.ReaderMG1.prototype.read = function(stream, body){ this.readIndices(stream, body.indices); this.readVertices(stream, body.vertices); if (body.normals){ this.readNormals(stream, body.normals); } if (body.uvMaps){ this.readUVMaps(stream, body.uvMaps); } if (body.attrMaps){ this.readAttrMaps(stream, body.attrMaps); } }; CTM.ReaderMG1.prototype.readIndices = function(stream, indices){ stream.readInt32(); //magic "INDX" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(indices, 3); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); CTM.restoreIndices(indices, indices.length); }; CTM.ReaderMG1.prototype.readVertices = function(stream, vertices){ stream.readInt32(); //magic "VERT" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(vertices, 1); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); }; CTM.ReaderMG1.prototype.readNormals = function(stream, normals){ stream.readInt32(); //magic "NORM" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(normals, 3); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); }; CTM.ReaderMG1.prototype.readUVMaps = function(stream, uvMaps){ var i = 0; for (; i < uvMaps.length; ++ i){ stream.readInt32(); //magic "TEXC" uvMaps[i].name = stream.readString(); uvMaps[i].filename = stream.readString(); stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); } }; CTM.ReaderMG1.prototype.readAttrMaps = function(stream, attrMaps){ var i = 0; for (; i < attrMaps.length; ++ i){ stream.readInt32(); //magic "ATTR" attrMaps[i].name = stream.readString(); stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); } }; CTM.ReaderMG2 = function(){ }; CTM.ReaderMG2.prototype.read = function(stream, body){ this.MG2Header = new CTM.FileMG2Header(stream); this.readVertices(stream, body.vertices); this.readIndices(stream, body.indices); if (body.normals){ this.readNormals(stream, body); } if (body.uvMaps){ this.readUVMaps(stream, body.uvMaps); } if (body.attrMaps){ this.readAttrMaps(stream, body.attrMaps); } }; CTM.ReaderMG2.prototype.readVertices = function(stream, vertices){ stream.readInt32(); //magic "VERT" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(vertices, 3); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); var gridIndices = this.readGridIndices(stream, vertices); CTM.restoreVertices(vertices, this.MG2Header, gridIndices, this.MG2Header.vertexPrecision); }; CTM.ReaderMG2.prototype.readGridIndices = function(stream, vertices){ stream.readInt32(); //magic "GIDX" stream.readInt32(); //packed size var gridIndices = new Uint32Array(vertices.length / 3); var interleaved = new CTM.InterleavedStream(gridIndices, 1); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); CTM.restoreGridIndices(gridIndices, gridIndices.length); return gridIndices; }; CTM.ReaderMG2.prototype.readIndices = function(stream, indices){ stream.readInt32(); //magic "INDX" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(indices, 3); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); CTM.restoreIndices(indices, indices.length); }; CTM.ReaderMG2.prototype.readNormals = function(stream, body){ stream.readInt32(); //magic "NORM" stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(body.normals, 3); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); var smooth = CTM.calcSmoothNormals(body.indices, body.vertices); CTM.restoreNormals(body.normals, smooth, this.MG2Header.normalPrecision); }; CTM.ReaderMG2.prototype.readUVMaps = function(stream, uvMaps){ var i = 0; for (; i < uvMaps.length; ++ i){ stream.readInt32(); //magic "TEXC" uvMaps[i].name = stream.readString(); uvMaps[i].filename = stream.readString(); var precision = stream.readFloat32(); stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(uvMaps[i].uv, 2); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); CTM.restoreMap(uvMaps[i].uv, 2, precision); } }; CTM.ReaderMG2.prototype.readAttrMaps = function(stream, attrMaps){ var i = 0; for (; i < attrMaps.length; ++ i){ stream.readInt32(); //magic "ATTR" attrMaps[i].name = stream.readString(); var precision = stream.readFloat32(); stream.readInt32(); //packed size var interleaved = new CTM.InterleavedStream(attrMaps[i].attr, 4); LZMA.decompress(stream, stream, interleaved, interleaved.data.length); CTM.restoreMap(attrMaps[i].attr, 4, precision); } }; CTM.restoreIndices = function(indices, len){ var i = 3; if (len > 0){ indices[2] += indices[0]; indices[1] += indices[0]; } for (; i < len; i += 3){ indices[i] += indices[i - 3]; if (indices[i] === indices[i - 3]){ indices[i + 1] += indices[i - 2]; }else{ indices[i + 1] += indices[i]; } indices[i + 2] += indices[i]; } }; CTM.restoreGridIndices = function(gridIndices, len){ var i = 1; for (; i < len; ++ i){ gridIndices[i] += gridIndices[i - 1]; } }; CTM.restoreVertices = function(vertices, grid, gridIndices, precision){ var gridIdx, delta, x, y, z, intVertices = new Uint32Array(vertices.buffer, vertices.byteOffset, vertices.length), ydiv = grid.divx, zdiv = ydiv * grid.divy, prevGridIdx = 0x7fffffff, prevDelta = 0, i = 0, j = 0, len = gridIndices.length; for (; i < len; j += 3){ x = gridIdx = gridIndices[i ++]; z = ~~(x / zdiv); x -= ~~(z * zdiv); y = ~~(x / ydiv); x -= ~~(y * ydiv); delta = intVertices[j]; if (gridIdx === prevGridIdx){ delta += prevDelta; } vertices[j] = grid.lowerBoundx + x * grid.sizex + precision * delta; vertices[j + 1] = grid.lowerBoundy + y * grid.sizey + precision * intVertices[j + 1]; vertices[j + 2] = grid.lowerBoundz + z * grid.sizez + precision * intVertices[j + 2]; prevGridIdx = gridIdx; prevDelta = delta; } }; CTM.restoreNormals = function(normals, smooth, precision){ var ro, phi, theta, sinPhi, nx, ny, nz, by, bz, len, intNormals = new Uint32Array(normals.buffer, normals.byteOffset, normals.length), i = 0, k = normals.length, PI_DIV_2 = 3.141592653589793238462643 * 0.5; for (; i < k; i += 3){ ro = intNormals[i] * precision; phi = intNormals[i + 1]; if (phi === 0){ normals[i] = smooth[i] * ro; normals[i + 1] = smooth[i + 1] * ro; normals[i + 2] = smooth[i + 2] * ro; }else{ if (phi <= 4){ theta = (intNormals[i + 2] - 2) * PI_DIV_2; }else{ theta = ( (intNormals[i + 2] * 4 / phi) - 2) * PI_DIV_2; } phi *= precision * PI_DIV_2; sinPhi = ro * Math.sin(phi); nx = sinPhi * Math.cos(theta); ny = sinPhi * Math.sin(theta); nz = ro * Math.cos(phi); bz = smooth[i + 1]; by = smooth[i] - smooth[i + 2]; len = Math.sqrt(2 * bz * bz + by * by); if (len > 1e-20){ by /= len; bz /= len; } normals[i] = smooth[i] * nz + (smooth[i + 1] * bz - smooth[i + 2] * by) * ny - bz * nx; normals[i + 1] = smooth[i + 1] * nz - (smooth[i + 2] + smooth[i] ) * bz * ny + by * nx; normals[i + 2] = smooth[i + 2] * nz + (smooth[i] * by + smooth[i + 1] * bz) * ny + bz * nx; } } }; CTM.restoreMap = function(map, count, precision){ var delta, value, intMap = new Uint32Array(map.buffer, map.byteOffset, map.length), i = 0, j, len = map.length; for (; i < count; ++ i){ delta = 0; for (j = i; j < len; j += count){ value = intMap[j]; delta += value & 1? -( (value + 1) >> 1): value >> 1; map[j] = delta * precision; } } }; CTM.calcSmoothNormals = function(indices, vertices){ var smooth = new Float32Array(vertices.length), indx, indy, indz, nx, ny, nz, v1x, v1y, v1z, v2x, v2y, v2z, len, i, k; for (i = 0, k = indices.length; i < k;){ indx = indices[i ++] * 3; indy = indices[i ++] * 3; indz = indices[i ++] * 3; v1x = vertices[indy] - vertices[indx]; v2x = vertices[indz] - vertices[indx]; v1y = vertices[indy + 1] - vertices[indx + 1]; v2y = vertices[indz + 1] - vertices[indx + 1]; v1z = vertices[indy + 2] - vertices[indx + 2]; v2z = vertices[indz + 2] - vertices[indx + 2]; nx = v1y * v2z - v1z * v2y; ny = v1z * v2x - v1x * v2z; nz = v1x * v2y - v1y * v2x; len = Math.sqrt(nx * nx + ny * ny + nz * nz); if (len > 1e-10){ nx /= len; ny /= len; nz /= len; } smooth[indx] += nx; smooth[indx + 1] += ny; smooth[indx + 2] += nz; smooth[indy] += nx; smooth[indy + 1] += ny; smooth[indy + 2] += nz; smooth[indz] += nx; smooth[indz + 1] += ny; smooth[indz + 2] += nz; } for (i = 0, k = smooth.length; i < k; i += 3){ len = Math.sqrt(smooth[i] * smooth[i] + smooth[i + 1] * smooth[i + 1] + smooth[i + 2] * smooth[i + 2]); if(len > 1e-10){ smooth[i] /= len; smooth[i + 1] /= len; smooth[i + 2] /= len; } } return smooth; }; CTM.isLittleEndian = (function(){ var buffer = new ArrayBuffer(2), bytes = new Uint8Array(buffer), ints = new Uint16Array(buffer); bytes[0] = 1; return ints[0] === 1; }()); CTM.InterleavedStream = function(data, count){ this.data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); this.offset = CTM.isLittleEndian? 3: 0; this.count = count * 4; this.len = this.data.length; }; CTM.InterleavedStream.prototype.writeByte = function(value){ this.data[this.offset] = value; this.offset += this.count; if (this.offset >= this.len){ this.offset -= this.len - 4; if (this.offset >= this.count){ this.offset -= this.count + (CTM.isLittleEndian? 1: -1); } } }; CTM.Stream = function(data){ this.data = data; this.offset = 0; }; CTM.Stream.prototype.TWO_POW_MINUS23 = Math.pow(2, -23); CTM.Stream.prototype.TWO_POW_MINUS126 = Math.pow(2, -126); CTM.Stream.prototype.readByte = function(){ return this.data[this.offset ++] & 0xff; }; CTM.Stream.prototype.readInt32 = function(){ var i = this.readByte(); i |= this.readByte() << 8; i |= this.readByte() << 16; return i | (this.readByte() << 24); }; CTM.Stream.prototype.readFloat32 = function(){ var m = this.readByte(); m += this.readByte() << 8; var b1 = this.readByte(); var b2 = this.readByte(); m += (b1 & 0x7f) << 16; var e = ( (b2 & 0x7f) << 1) | ( (b1 & 0x80) >>> 7); var s = b2 & 0x80? -1: 1; if (e === 255){ return m !== 0? NaN: s * Infinity; } if (e > 0){ return s * (1 + (m * this.TWO_POW_MINUS23) ) * Math.pow(2, e - 127); } if (m !== 0){ return s * m * this.TWO_POW_MINUS126; } return s * 0; }; CTM.Stream.prototype.readString = function(){ var len = this.readInt32(); this.offset += len; return String.fromCharCode.apply(null,this.data.subarray(this.offset - len, this.offset)); }; CTM.Stream.prototype.readArrayInt32 = function(array){ var i = 0, len = array.length; while(i < len){ array[i ++] = this.readInt32(); } return array; }; CTM.Stream.prototype.readArrayFloat32 = function(array){ var i = 0, len = array.length; while(i < len){ array[i ++] = this.readFloat32(); } return array; };
JavaScript
/** * @author Wei Meng / http://about.me/menway * * Description: A THREE loader for PLY ASCII files (known as the Polygon File Format or the Stanford Triangle Format). * * Currently only supports ASCII encoded files. * * Limitations: ASCII decoding assumes file is UTF-8. * * Usage: * var loader = new THREE.PLYLoader(); * loader.addEventListener( 'load', function ( event ) { * * var geometry = event.content; * scene.add( new THREE.Mesh( geometry ) ); * * } ); * loader.load( './models/ply/ascii/dolphins.ply' ); */ THREE.PLYLoader = function () {}; THREE.PLYLoader.prototype = { constructor: THREE.PLYLoader, load: function ( url, callback ) { var scope = this; var request = new XMLHttpRequest(); request.addEventListener( 'load', function ( event ) { var geometry = scope.parse( event.target.response ); scope.dispatchEvent( { type: 'load', content: geometry } ); if ( callback ) callback( geometry ); }, false ); request.addEventListener( 'progress', function ( event ) { scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } ); }, false ); request.addEventListener( 'error', function () { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } ); }, false ); request.open( 'GET', url, true ); request.responseType = "arraybuffer"; request.send( null ); }, bin2str: function (buf) { var array_buffer = new Uint8Array(buf); var str = ''; for(var i = 0; i < buf.byteLength; i++) { str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian } return str; }, isASCII: function( data ){ var header = this.parseHeader( this.bin2str( data ) ); return header.format === "ascii"; }, parse: function ( data ) { if ( data instanceof ArrayBuffer ) { return this.isASCII( data ) ? this.parseASCII( this.bin2str( data ) ) : this.parseBinary( data ); } else { return this.parseASCII( data ); } }, parseHeader: function ( data ) { var patternHeader = /ply([\s\S]*)end_header\n/; var headerText = ""; if ( ( result = patternHeader.exec( data ) ) != null ) { headerText = result [ 1 ]; } var header = new Object(); header.comments = []; header.elements = []; header.headerLength = result[0].length; var lines = headerText.split( '\n' ); var currentElement = undefined; var lineType, lineValues; function make_ply_element_property(propertValues) { var property = Object(); property.type = propertValues[0] if ( property.type === "list" ) { property.name = propertValues[3] property.countType = propertValues[1] property.itemType = propertValues[2] } else { property.name = propertValues[1] } return property } for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim() if ( line === "" ) { continue; } lineValues = line.split( /\s+/ ); lineType = lineValues.shift() line = lineValues.join(" ") switch( lineType ) { case "format": header.format = lineValues[0]; header.version = lineValues[1]; break; case "comment": header.comments.push(line); break; case "element": if ( !(currentElement === undefined) ) { header.elements.push(currentElement); } currentElement = Object(); currentElement.name = lineValues[0]; currentElement.count = parseInt( lineValues[1] ); currentElement.properties = []; break; case "property": currentElement.properties.push( make_ply_element_property( lineValues ) ); break; default: console.log("unhandled", lineType, lineValues); } } if ( !(currentElement === undefined) ) { header.elements.push(currentElement); } return header; }, parseASCIINumber: function ( n, type ) { switch( type ) { case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint': case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32': return parseInt( n ); case 'float': case 'double': case 'float32': case 'float64': return parseFloat( n ); } }, parseASCIIElement: function ( properties, line ) { values = line.split( /\s+/ ); var element = Object(); for ( var i = 0; i < properties.length; i ++ ) { if ( properties[i].type === "list" ) { var list = []; var n = this.parseASCIINumber( values.shift(), properties[i].countType ); for ( j = 0; j < n; j ++ ) { list.push( this.parseASCIINumber( values.shift(), properties[i].itemType ) ); } element[ properties[i].name ] = list; } else { element[ properties[i].name ] = this.parseASCIINumber( values.shift(), properties[i].type ); } } return element; }, parseASCII: function ( data ) { // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format) var geometry = new THREE.Geometry(); var result; var header = this.parseHeader( data ); var patternBody = /end_header\n([\s\S]*)$/; var body = ""; if ( ( result = patternBody.exec( data ) ) != null ) { body = result [ 1 ]; } var lines = body.split( '\n' ); var currentElement = 0; var currentElementCount = 0; geometry.useColor = false; for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim() if ( line === "" ) { continue; } if ( currentElementCount >= header.elements[currentElement].count ) { currentElement++; currentElementCount = 0; } var element = this.parseASCIIElement( header.elements[currentElement].properties, line ); this.handleElement( geometry, header.elements[currentElement].name, element ); currentElementCount++; } return this.postProcess( geometry ); }, postProcess: function ( geometry ) { if ( geometry.useColor ) { for ( var i = 0; i < geometry.faces.length; i ++ ) { geometry.faces[i].vertexColors = [ geometry.colors[geometry.faces[i].a], geometry.colors[geometry.faces[i].b], geometry.colors[geometry.faces[i].c] ]; } geometry.elementsNeedUpdate = true; } geometry.computeCentroids(); geometry.computeBoundingSphere(); return geometry; }, handleElement: function ( geometry, elementName, element ) { if ( elementName === "vertex" ) { geometry.vertices.push( new THREE.Vector3( element.x, element.y, element.z ) ); if ( 'red' in element && 'green' in element && 'blue' in element ) { geometry.useColor = true; color = new THREE.Color(); color.setRGB( element.red / 255.0, element.green / 255.0, element.blue / 255.0 ); geometry.colors.push( color ); } } else if ( elementName === "face" ) { geometry.faces.push( new THREE.Face3( element.vertex_indices[0], element.vertex_indices[1], element.vertex_indices[2] ) ); } }, binaryRead: function ( dataview, at, type, little_endian ) { switch( type ) { // corespondences for non-specific length types here match rply: case 'int8': case 'char': return [ dataview.getInt8( at ), 1 ]; case 'uint8': case 'uchar': return [ dataview.getUint8( at ), 1 ]; case 'int16': case 'short': return [ dataview.getInt16( at, little_endian ), 2 ]; case 'uint16': case 'ushort': return [ dataview.getUint16( at, little_endian ), 2 ]; case 'int32': case 'int': return [ dataview.getInt32( at, little_endian ), 4 ]; case 'uint32': case 'uint': return [ dataview.getUint32( at, little_endian ), 4 ]; case 'float32': case 'float': return [ dataview.getFloat32( at, little_endian ), 4 ]; case 'float64': case 'double': return [ dataview.getFloat64( at, little_endian ), 8 ]; } }, binaryReadElement: function ( dataview, at, properties, little_endian ) { var element = Object(); var result, read = 0; for ( var i = 0; i < properties.length; i ++ ) { if ( properties[i].type === "list" ) { var list = []; result = this.binaryRead( dataview, at+read, properties[i].countType, little_endian ); var n = result[0]; read += result[1]; for ( j = 0; j < n; j ++ ) { result = this.binaryRead( dataview, at+read, properties[i].itemType, little_endian ); list.push( result[0] ); read += result[1]; } element[ properties[i].name ] = list; } else { result = this.binaryRead( dataview, at+read, properties[i].type, little_endian ); element[ properties[i].name ] = result[0]; read += result[1]; } } return [ element, read ]; }, parseBinary: function ( data ) { var geometry = new THREE.Geometry(); var header = this.parseHeader( this.bin2str( data ) ); var little_endian = (header.format === "binary_little_endian"); var body = new DataView( data, header.headerLength ); var result, loc = 0; for ( var currentElement = 0; currentElement < header.elements.length; currentElement ++ ) { for ( var currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount ++ ) { result = this.binaryReadElement( body, loc, header.elements[currentElement].properties, little_endian ); loc += result[1]; var element = result[0]; this.handleElement( geometry, header.elements[currentElement].name, element ); } } return this.postProcess( geometry ); } }; THREE.EventDispatcher.prototype.apply( THREE.PLYLoader.prototype );
JavaScript
/** * @author aleeper / http://adamleeper.com/ * @author mrdoob / http://mrdoob.com/ * @author gero3 / https://github.com/gero3 * * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs. * * Supports both binary and ASCII encoded files, with automatic detection of type. * * Limitations: * Binary decoding ignores header. There doesn't seem to be much of a use for it. * There is perhaps some question as to how valid it is to always assume little-endian-ness. * ASCII decoding assumes file is UTF-8. Seems to work for the examples... * * Usage: * var loader = new THREE.STLLoader(); * loader.addEventListener( 'load', function ( event ) { * * var geometry = event.content; * scene.add( new THREE.Mesh( geometry ) ); * * } ); * loader.load( './models/stl/slotted_disk.stl' ); */ THREE.STLLoader = function () {}; THREE.STLLoader.prototype = { constructor: THREE.STLLoader }; THREE.STLLoader.prototype.load = function ( url, callback ) { var scope = this; var xhr = new XMLHttpRequest(); function onloaded( event ) { if ( event.target.status === 200 || event.target.status === 0 ) { var geometry = scope.parse( event.target.response || event.target.responseText ); scope.dispatchEvent( { type: 'load', content: geometry } ); if ( callback ) callback( geometry ); } else { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']', response: event.target.responseText } ); } } xhr.addEventListener( 'load', onloaded, false ); xhr.addEventListener( 'progress', function ( event ) { scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } ); }, false ); xhr.addEventListener( 'error', function () { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } ); }, false ); if ( xhr.overrideMimeType ) xhr.overrideMimeType( 'text/plain; charset=x-user-defined' ); xhr.open( 'GET', url, true ); xhr.responseType = 'arraybuffer'; xhr.send( null ); }; THREE.STLLoader.prototype.parse = function ( data ) { var isBinary = function () { var expect, face_size, n_faces, reader; reader = new DataView( binData ); face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8); n_faces = reader.getUint32(80,true); expect = 80 + (32 / 8) + (n_faces * face_size); return expect === reader.byteLength; }; var binData = this.ensureBinary( data ); return isBinary() ? this.parseBinary( binData ) : this.parseASCII( this.ensureString( data ) ); }; THREE.STLLoader.prototype.parseBinary = function (data) { var face, geometry, n_faces, reader, length, normal, i, dataOffset, faceLength, start, vertexstart; reader = new DataView( data ); n_faces = reader.getUint32(80,true); geometry = new THREE.Geometry(); dataOffset = 84; faceLength = 12 * 4 + 2; for (face = 0; face < n_faces; face++) { start = dataOffset + face * faceLength; normal = new THREE.Vector3( reader.getFloat32(start,true), reader.getFloat32(start + 4,true), reader.getFloat32(start + 8,true) ); for (i = 1; i <= 3; i++) { vertexstart = start + i * 12; geometry.vertices.push( new THREE.Vector3( reader.getFloat32(vertexstart,true), reader.getFloat32(vertexstart +4,true), reader.getFloat32(vertexstart + 8,true) ) ); } length = geometry.vertices.length; geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal)); } geometry.computeCentroids(); geometry.computeBoundingSphere(); return geometry; }; THREE.STLLoader.prototype.parseASCII = function (data) { var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text; geometry = new THREE.Geometry(); patternFace = /facet([\s\S]*?)endfacet/g; while ( ( result = patternFace.exec( data ) ) !== null ) { text = result[0]; patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; while ( ( result = patternNormal.exec( text ) ) !== null ) { normal = new THREE.Vector3( parseFloat( result[ 1 ] ), parseFloat( result[ 3 ] ), parseFloat( result[ 5 ] ) ); } patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; while ( ( result = patternVertex.exec( text ) ) !== null ) { geometry.vertices.push( new THREE.Vector3( parseFloat( result[ 1 ] ), parseFloat( result[ 3 ] ), parseFloat( result[ 5 ] ) ) ); } length = geometry.vertices.length; geometry.faces.push( new THREE.Face3( length - 3, length - 2, length - 1, normal ) ); } geometry.computeCentroids(); geometry.computeBoundingBox(); geometry.computeBoundingSphere(); return geometry; }; THREE.STLLoader.prototype.ensureString = function (buf) { if (typeof buf !== "string"){ var array_buffer = new Uint8Array(buf); var str = ''; for(var i = 0; i < buf.byteLength; i++) { str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian } return str; } else { return buf; } }; THREE.STLLoader.prototype.ensureBinary = function (buf) { if (typeof buf === "string"){ var array_buffer = new Uint8Array(buf.length); for(var i = 0; i < buf.length; i++) { array_buffer[i] = buf.charCodeAt(i) & 0xff; // implicitly assumes little-endian } return array_buffer.buffer || array_buffer; } else { return buf; } }; THREE.EventDispatcher.prototype.apply( THREE.STLLoader.prototype ); if ( typeof DataView === 'undefined'){ DataView = function(buffer, byteOffset, byteLength){ this.buffer = buffer; this.byteOffset = byteOffset || 0; this.byteLength = byteLength || buffer.byteLength || buffer.length; this._isString = typeof buffer === "string"; } DataView.prototype = { _getCharCodes:function(buffer,start,length){ start = start || 0; length = length || buffer.length; var end = start + length; var codes = []; for (var i = start; i < end; i++) { codes.push(buffer.charCodeAt(i) & 0xff); } return codes; }, _getBytes: function (length, byteOffset, littleEndian) { var result; // Handle the lack of endianness if (littleEndian === undefined) { littleEndian = this._littleEndian; } // Handle the lack of byteOffset if (byteOffset === undefined) { byteOffset = this.byteOffset; } else { byteOffset = this.byteOffset + byteOffset; } if (length === undefined) { length = this.byteLength - byteOffset; } // Error Checking if (typeof byteOffset !== 'number') { throw new TypeError('DataView byteOffset is not a number'); } if (length < 0 || byteOffset + length > this.byteLength) { throw new Error('DataView length or (byteOffset+length) value is out of bounds'); } if (this.isString){ result = this._getCharCodes(this.buffer, byteOffset, byteOffset + length); } else { result = this.buffer.slice(byteOffset, byteOffset + length); } if (!littleEndian && length > 1) { if (!(result instanceof Array)) { result = Array.prototype.slice.call(result); } result.reverse(); } return result; }, // Compatibility functions on a String Buffer getFloat64: function (byteOffset, littleEndian) { var b = this._getBytes(8, byteOffset, littleEndian), sign = 1 - (2 * (b[7] >> 7)), exponent = ((((b[7] << 1) & 0xff) << 3) | (b[6] >> 4)) - ((1 << 10) - 1), // Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead mantissa = ((b[6] & 0x0f) * Math.pow(2, 48)) + (b[5] * Math.pow(2, 40)) + (b[4] * Math.pow(2, 32)) + (b[3] * Math.pow(2, 24)) + (b[2] * Math.pow(2, 16)) + (b[1] * Math.pow(2, 8)) + b[0]; if (exponent === 1024) { if (mantissa !== 0) { return NaN; } else { return sign * Infinity; } } if (exponent === -1023) { // Denormalized return sign * mantissa * Math.pow(2, -1022 - 52); } return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent); }, getFloat32: function (byteOffset, littleEndian) { var b = this._getBytes(4, byteOffset, littleEndian), sign = 1 - (2 * (b[3] >> 7)), exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127, mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; if (exponent === 128) { if (mantissa !== 0) { return NaN; } else { return sign * Infinity; } } if (exponent === -127) { // Denormalized return sign * mantissa * Math.pow(2, -126 - 23); } return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent); }, getInt32: function (byteOffset, littleEndian) { var b = this._getBytes(4, byteOffset, littleEndian); return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0]; }, getUint32: function (byteOffset, littleEndian) { return this.getInt32(byteOffset, littleEndian) >>> 0; }, getInt16: function (byteOffset, littleEndian) { return (this.getUint16(byteOffset, littleEndian) << 16) >> 16; }, getUint16: function (byteOffset, littleEndian) { var b = this._getBytes(2, byteOffset, littleEndian); return (b[1] << 8) | b[0]; }, getInt8: function (byteOffset) { return (this.getUint8(byteOffset) << 24) >> 24; }, getUint8: function (byteOffset) { return this._getBytes(1, byteOffset)[0]; } }; }
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ THREE.OBJLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.OBJLoader.prototype = { constructor: THREE.OBJLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { onLoad( scope.parse( text ) ); } ); }, parse: function ( text ) { function vector( x, y, z ) { return new THREE.Vector3( parseFloat( x ), parseFloat( y ), parseFloat( z ) ); } function uv( u, v ) { return new THREE.Vector2( parseFloat( u ), parseFloat( v ) ); } function face3( a, b, c, normals ) { return new THREE.Face3( a, b, c, normals ); } var object = new THREE.Object3D(); var geometry, material, mesh; function parseVertexIndex( index ) { index = parseInt( index ); return index >= 0 ? index - 1 : index + vertices.length; } function parseNormalIndex( index ) { index = parseInt( index ); return index >= 0 ? index - 1 : index + normals.length; } function parseUVIndex( index ) { index = parseInt( index ); return index >= 0 ? index - 1 : index + uvs.length; } function add_face( a, b, c, normals_inds ) { if ( normals_inds === undefined ) { geometry.faces.push( face3( vertices[ parseVertexIndex( a ) ] - 1, vertices[ parseVertexIndex( b ) ] - 1, vertices[ parseVertexIndex( c ) ] - 1 ) ); } else { geometry.faces.push( face3( vertices[ parseVertexIndex( a ) ] - 1, vertices[ parseVertexIndex( b ) ] - 1, vertices[ parseVertexIndex( c ) ] - 1, [ normals[ parseNormalIndex( normals_inds[ 0 ] ) ].clone(), normals[ parseNormalIndex( normals_inds[ 1 ] ) ].clone(), normals[ parseNormalIndex( normals_inds[ 2 ] ) ].clone() ] ) ); } } function add_uvs( a, b, c ) { geometry.faceVertexUvs[ 0 ].push( [ uvs[ parseUVIndex( a ) ].clone(), uvs[ parseUVIndex( b ) ].clone(), uvs[ parseUVIndex( c ) ].clone() ] ); } function handle_face_line(faces, uvs, normals_inds) { if ( faces[ 3 ] === undefined ) { add_face( faces[ 0 ], faces[ 1 ], faces[ 2 ], normals_inds ); if ( uvs !== undefined && uvs.length > 0 ) { add_uvs( uvs[ 0 ], uvs[ 1 ], uvs[ 2 ] ); } } else { if ( normals_inds !== undefined && normals_inds.length > 0 ) { add_face( faces[ 0 ], faces[ 1 ], faces[ 3 ], [ normals_inds[ 0 ], normals_inds[ 1 ], normals_inds[ 3 ] ] ); add_face( faces[ 1 ], faces[ 2 ], faces[ 3 ], [ normals_inds[ 1 ], normals_inds[ 2 ], normals_inds[ 3 ] ] ); } else { add_face( faces[ 0 ], faces[ 1 ], faces[ 3 ] ); add_face( faces[ 1 ], faces[ 2 ], faces[ 3 ] ); } if ( uvs !== undefined && uvs.length > 0 ) { add_uvs( uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ); add_uvs( uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ); } } } // create mesh if no objects in text if ( /^o /gm.test( text ) === false ) { geometry = new THREE.Geometry(); material = new THREE.MeshLambertMaterial(); mesh = new THREE.Mesh( geometry, material ); object.add( mesh ); } var vertices = []; var normals = []; var uvs = []; // v float float float var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vn float float float var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vt float float var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // f vertex vertex vertex ... var face_pattern1 = /f( +-?\d+)( +-?\d+)( +-?\d+)( +-?\d+)?/; // f vertex/uv vertex/uv vertex/uv ... var face_pattern2 = /f( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))?/; // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... var face_pattern3 = /f( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))?/; // f vertex//normal vertex//normal vertex//normal ... var face_pattern4 = /f( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))?/ // var lines = text.split( '\n' ); for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim(); var result; if ( line.length === 0 || line.charAt( 0 ) === '#' ) { continue; } else if ( ( result = vertex_pattern.exec( line ) ) !== null ) { // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] vertices.push( geometry.vertices.push( vector( result[ 1 ], result[ 2 ], result[ 3 ] ) ) ); } else if ( ( result = normal_pattern.exec( line ) ) !== null ) { // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] normals.push( vector( result[ 1 ], result[ 2 ], result[ 3 ] ) ); } else if ( ( result = uv_pattern.exec( line ) ) !== null ) { // ["vt 0.1 0.2", "0.1", "0.2"] uvs.push( uv( result[ 1 ], result[ 2 ] ) ); } else if ( ( result = face_pattern1.exec( line ) ) !== null ) { // ["f 1 2 3", "1", "2", "3", undefined] handle_face_line( [ result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ] ] ); } else if ( ( result = face_pattern2.exec( line ) ) !== null ) { // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ], //faces [ result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ] //uv ); } else if ( ( result = face_pattern3.exec( line ) ) !== null ) { // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 6 ], result[ 10 ], result[ 14 ] ], //faces [ result[ 3 ], result[ 7 ], result[ 11 ], result[ 15 ] ], //uv [ result[ 4 ], result[ 8 ], result[ 12 ], result[ 16 ] ] //normal ); } else if ( ( result = face_pattern4.exec( line ) ) !== null ) { // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ], //faces [ ], //uv [ result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ] //normal ); } else if ( /^o /.test( line ) ) { geometry = new THREE.Geometry(); material = new THREE.MeshLambertMaterial(); mesh = new THREE.Mesh( geometry, material ); mesh.name = line.substring( 2 ).trim(); object.add( mesh ); } else if ( /^g /.test( line ) ) { // group } else if ( /^usemtl /.test( line ) ) { // material material.name = line.substring( 7 ).trim(); } else if ( /^mtllib /.test( line ) ) { // mtl file } else if ( /^s /.test( line ) ) { // smooth shading } else { // console.log( "THREE.OBJLoader: Unhandled line " + line ); } } var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { var geometry = children[ i ].geometry; geometry.computeCentroids(); geometry.computeFaceNormals(); geometry.computeBoundingSphere(); } return object; } };
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ THREE.BabylonLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.BabylonLoader.prototype = { constructor: THREE.ObjectLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); } ); }, setCrossOrigin: function ( value ) { this.crossOrigin = value; }, parse: function ( json ) { var materials = this.parseMaterials( json.materials ); var scene = this.parseObjects( json, materials ); return scene; }, parseMaterials: function ( json ) { var materials = {}; for ( var i = 0, l = json.length; i < l; i ++ ) { var data = json[ i ]; var material = new THREE.MeshPhongMaterial(); material.name = data.name; material.ambient.fromArray( data.ambient ); material.color.fromArray( data.diffuse ); material.emissive.fromArray( data.emissive ); material.specular.fromArray( data.specular ); material.shininess = data.specularPower; material.opacity = data.alpha; materials[ data.id ] = material; } return materials; }, parseObjects: function ( json, materials ) { var objects = {}; var scene = new THREE.Scene(); var lights = json.lights; for ( var i = 0, l = lights.length; i < l; i ++ ) { var data = lights[ i ]; var light; switch ( data.type ) { case 0: light = new THREE.PointLight(); break; case 1: light = new THREE.DirectionalLight(); break; case 2: light = new THREE.SpotLight(); break; case 3: light = new THREE.HemisphereLight(); break; } light.name = data.name; light.position.set( data.position[ 0 ], data.position[ 1 ], - data.position[ 2 ] ); light.color.fromArray( data.diffuse ); if ( data.intensity ) light.intensity = data.intensity; objects[ data.id ] = light; scene.add( light ); } var meshes = json.meshes; for ( var i = 0, l = meshes.length; i < l; i ++ ) { var data = meshes[ i ]; var object; if ( data.indices !== null ) { var geometry = new THREE.BufferGeometry(); geometry.attributes.index = { itemSize: 1, array: new Uint16Array( data.indices ) }; geometry.attributes.position = { itemSize: 3, array: new Float32Array( data.positions ) }; var positions = geometry.attributes.position.array; for ( var j = 2, jl = positions.length; j < jl; j += 3 ) { positions[ j ] = - positions[ j ]; } geometry.attributes.normal = { itemSize: 3, array: new Float32Array( data.normals ) }; var normals = geometry.attributes.normal.array; for ( var j = 2, jl = normals.length; j < jl; j += 3 ) { normals[ j ] = - normals[ j ]; } geometry.attributes.uv = { itemSize: 2, array: new Float32Array( data.uvs ) }; var subMeshes = data.subMeshes; if ( subMeshes !== null ) { for ( var j = 0, jl = subMeshes.length; j < jl; j ++ ) { var subMesh = subMeshes[ j ]; geometry.offsets.push( { start: subMesh.indexStart, index: 0, count: subMesh.indexCount } ); } } else { geometry.offsets.push( { start: 0, index: 0, count: data.indices.length } ); } var material = materials[ data.materialId ]; object = new THREE.Mesh( geometry, material ); } else { object = new THREE.Object3D(); } object.name = data.name; object.position.set( data.position[ 0 ], data.position[ 1 ], - data.position[ 2 ] ); object.rotation.fromArray( data.rotation ); object.scale.fromArray( data.scaling ); if ( data.parentId !== undefined && data.parentId !== '' ) { objects[ data.parentId ].add( object ); } else { scene.add( object ); } objects[ data.id ] = object; } return scene; } };
JavaScript
/** * @author Alexander Gessler / http://www.greentoken.de/ * https://github.com/acgessler * * Loader for models imported with Open Asset Import Library (http://assimp.sf.net) * through assimp2json (https://github.com/acgessler/assimp2json). * * Supports any input format that assimp supports, including 3ds, obj, dae, blend, * fbx, x, ms3d, lwo (and many more). * * See webgl_loader_assimp2json example. */ THREE.AssimpJSONLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.AssimpJSONLoader.prototype = { constructor: THREE.AssimpJSONLoader, texturePath : '', load: function ( url, onLoad, onProgress, onError, texturePath ) { var scope = this; this.texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url ); var loader = new THREE.XHRLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { var scene = scope.parse( JSON.parse( text ) ); onLoad( scene ); } ); }, setCrossOrigin: function ( value ) { this.crossOrigin = value; }, extractUrlBase: function ( url ) { // from three/src/loaders/Loader.js var parts = url.split( '/' ); parts.pop(); return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/'; }, parse: function ( json ) { var meshes = this.parseList ( json.meshes, this.parseMesh ); var materials = this.parseList ( json.materials, this.parseMaterial ); return this.parseObject( json, json.rootnode, meshes, materials ); }, parseList : function(json, handler) { var meshes = new Array(json.length); for(var i = 0; i < json.length; ++i) { meshes[i] = handler.call(this, json[i]); } return meshes; }, parseMesh : function(json) { var vertex, geometry, i, e, in_data, src; geometry = new THREE.Geometry(); // read vertex positions for(in_data = json.vertices, i = 0, e = in_data.length; i < e; ) { geometry.vertices.push( new THREE.Vector3( in_data[ i++ ], in_data[ i++ ], in_data[ i++ ] ) ); } // read faces var cnt = 0; for(in_data = json.faces, i = 0, e = in_data.length; i < e; ++i) { face = new THREE.Face3(); src = in_data[i]; face.a = src[0]; face.b = src[1]; face.c = src[2]; face.materialIndex = 0; //json.materialindex; geometry.faces.push(face); } // read texture coordinates - three.js attaches them to its faces for(i = 0, e = json.texturecoords.length; i < e; ++i) { function convertTextureCoords(in_uv, out_faces, out_vertex_uvs) { var i, e, face, a, b, c; for(i = 0, e = out_faces.length; i < e; ++i) { face = out_faces[i]; a = face.a * 2; b = face.b * 2; c = face.c * 2; out_vertex_uvs.push([ new THREE.Vector2( in_uv[ a ], in_uv[ a + 1 ] ), new THREE.Vector2( in_uv[ b ], in_uv[ b + 1 ] ), new THREE.Vector2( in_uv[ c ], in_uv[ c + 1 ] ) ]); } } convertTextureCoords(json.texturecoords[i], geometry.faces, geometry.faceVertexUvs[i]); } // read normals - three.js also attaches them to its faces if(json.normals) { function convertNormals(in_nor, out_faces) { var i, e, face, a, b, c; for(i = 0, e = out_faces.length; i < e; ++i) { face = out_faces[i]; a = face.a * 3; b = face.b * 3; c = face.c * 3; face.vertexNormals = [ new THREE.Vector3( in_nor[ a ], in_nor[ a + 1 ], in_nor[ a + 2 ] ), new THREE.Vector3( in_nor[ b ], in_nor[ b + 1 ], in_nor[ b + 2 ] ), new THREE.Vector3( in_nor[ c ], in_nor[ c + 1 ], in_nor[ c + 2 ] ) ]; } } convertNormals(json.normals, geometry.faces); } // read vertex colors - three.js also attaches them to its faces if(json.colors && json.colors[0]) { function convertColors(in_color, out_faces) { var i, e, face, a, b, c; function makeColor(start) { var col = new THREE.Color( ); col.setRGB( arr[0], arr[1], arr[2] ); // TODO: what about alpha? return col; } for(i = 0, e = out_faces.length; i < e; ++i) { face = out_faces[i]; a = face.a * 4; b = face.b * 4; c = face.c * 4; face.vertexColors = [ makeColor( a ), makeColor( b ), makeColor( c ) ]; } } convertColors(json.colors[0], geometry.faces); } geometry.computeCentroids(); //geometry.computeFaceNormals(); //geometry.computeVertexNormals(); //geometry.computeTangents(); geometry.computeBoundingSphere(); // TODO: tangents return geometry; }, parseMaterial : function(json) { var mat = null, scope = this, i, prop, has_textures = [], init_props = { shading : THREE.SmoothShading }; function toColor(value_arr) { var col = new THREE.Color(); col.setRGB(value_arr[0],value_arr[1],value_arr[2]); return col; } function defaultTexture() { var im = new Image(); im.width = 1; im.height = 1; return new THREE.Texture(im); } for (var i in json.properties) { prop = json.properties[i]; if(prop.key === '$tex.file') { // prop.semantic gives the type of the texture // 1: diffuse // 2: specular mao // 5: height map (bumps) // 6: normal map // more values (i.e. emissive, environment) are known by assimp and may be relevant if(prop.semantic === 1 || prop.semantic === 5 || prop.semantic === 6 || prop.semantic === 2) { (function(semantic) { var loader = new THREE.TextureLoader(scope.manager), keyname; if(semantic === 1) { keyname = 'map'; } else if(semantic === 5) { keyname = 'bumpMap'; } else if(semantic === 6) { keyname = 'normalMap'; } else if(semantic === 2) { keyname = 'specularMap'; } has_textures.push(keyname); loader.setCrossOrigin(this.crossOrigin); loader.load(scope.texturePath + '/' + prop.value, function(tex) { if(tex) { // TODO: read texture settings from assimp. // Wrapping is the default, though. tex.wrapS = tex.wrapT = THREE.RepeatWrapping; mat[keyname] = tex; mat.needsUpdate = true; } }); })(prop.semantic); } } else if(prop.key === '?mat.name') { init_props.name = prop.value; } else if(prop.key === '$clr.diffuse') { init_props.color = toColor(prop.value); } else if(prop.key === '$clr.specular') { init_props.specular = toColor(prop.value); } else if(prop.key === '$clr.ambient') { init_props.ambient = toColor(prop.value); } else if(prop.key === '$clr.emissive') { init_props.emissive = toColor(prop.value); } else if(prop.key === '$mat.shadingm') { // aiShadingMode_Flat if (prop.value === 1) { init_props.shading = THREE.FlatShading; } } else if (prop.key === '$mat.shininess') { init_props.shininess = prop.value; } } if(!init_props.ambient) { init_props.ambient = init_props.color; } // note: three.js does not like it when a texture is added after the geometry // has been rendered once, see http://stackoverflow.com/questions/16531759/. // for this reason we fill all slots upfront with default textures if(has_textures.length) { for(i = has_textures.length-1; i >= 0; --i) { init_props[has_textures[i]] = defaultTexture(); } } mat = new THREE.MeshPhongMaterial( init_props ); return mat; }, parseObject : function(json, node, meshes, materials) { var obj = new THREE.Object3D() , i , idx ; obj.name = node.name || ""; obj.matrix = new THREE.Matrix4().fromArray(node.transformation).transpose(); obj.matrix.decompose( obj.position, obj.quaternion, obj.scale ); for(i = 0; node.meshes && i < node.meshes.length; ++i) { idx = node.meshes[i]; obj.add(new THREE.Mesh( meshes[idx], materials[json.meshes[idx].materialindex] )); } for(i = 0; node.children && i < node.children.length; ++i) { obj.add(this.parseObject(json, node.children[i], meshes, materials)); } return obj; }, };
JavaScript
/** * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com */ THREE.ColladaLoader = function () { var COLLADA = null; var scene = null; var daeScene; var readyCallbackFunc = null; var sources = {}; var images = {}; var animations = {}; var controllers = {}; var geometries = {}; var materials = {}; var effects = {}; var cameras = {}; var lights = {}; var animData; var visualScenes; var baseUrl; var morphs; var skins; var flip_uv = true; var preferredShading = THREE.SmoothShading; var options = { // Force Geometry to always be centered at the local origin of the // containing Mesh. centerGeometry: false, // Axis conversion is done for geometries, animations, and controllers. // If we ever pull cameras or lights out of the COLLADA file, they'll // need extra work. convertUpAxis: false, subdivideFaces: true, upAxis: 'Y', // For reflective or refractive materials we'll use this cubemap defaultEnvMap: null }; var colladaUnit = 1.0; var colladaUp = 'Y'; var upConversion = null; function load ( url, readyCallback, progressCallback ) { var length = 0; if ( document.implementation && document.implementation.createDocument ) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if( request.readyState == 4 ) { if( request.status == 0 || request.status == 200 ) { if ( request.responseXML ) { readyCallbackFunc = readyCallback; parse( request.responseXML, undefined, url ); } else if ( request.responseText ) { readyCallbackFunc = readyCallback; var xmlParser = new DOMParser(); var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" ); parse( responseXML, undefined, url ); } else { console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" ); } } } else if ( request.readyState == 3 ) { if ( progressCallback ) { if ( length == 0 ) { length = request.getResponseHeader( "Content-Length" ); } progressCallback( { total: length, loaded: request.responseText.length } ); } } } request.open( "GET", url, true ); request.send( null ); } else { alert( "Don't know how to parse XML!" ); } } function parse( doc, callBack, url ) { COLLADA = doc; callBack = callBack || readyCallbackFunc; if ( url !== undefined ) { var parts = url.split( '/' ); parts.pop(); baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/'; } parseAsset(); setUpConversion(); images = parseLib( "library_images image", _Image, "image" ); materials = parseLib( "library_materials material", Material, "material" ); effects = parseLib( "library_effects effect", Effect, "effect" ); geometries = parseLib( "library_geometries geometry", Geometry, "geometry" ); cameras = parseLib( "library_cameras camera", Camera, "camera" ); lights = parseLib( "library_lights light", Light, "light" ); controllers = parseLib( "library_controllers controller", Controller, "controller" ); animations = parseLib( "library_animations animation", Animation, "animation" ); visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" ); morphs = []; skins = []; daeScene = parseScene(); scene = new THREE.Object3D(); for ( var i = 0; i < daeScene.nodes.length; i ++ ) { scene.add( createSceneGraph( daeScene.nodes[ i ] ) ); } // unit conversion scene.scale.multiplyScalar( colladaUnit ); createAnimations(); var result = { scene: scene, morphs: morphs, skins: skins, animations: animData, dae: { images: images, materials: materials, cameras: cameras, lights: lights, effects: effects, geometries: geometries, controllers: controllers, animations: animations, visualScenes: visualScenes, scene: daeScene } }; if ( callBack ) { callBack( result ); } return result; } function setPreferredShading ( shading ) { preferredShading = shading; } function parseAsset () { var elements = COLLADA.querySelectorAll('asset'); var element = elements[0]; if ( element && element.childNodes ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'unit': var meter = child.getAttribute( 'meter' ); if ( meter ) { colladaUnit = parseFloat( meter ); } break; case 'up_axis': colladaUp = child.textContent.charAt(0); break; } } } } function parseLib ( q, classSpec, prefix ) { var elements = COLLADA.querySelectorAll(q); var lib = {}; var i = 0; var elementsLength = elements.length; for ( var j = 0; j < elementsLength; j ++ ) { var element = elements[j]; var daeElement = ( new classSpec() ).parse( element ); if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ ); lib[ daeElement.id ] = daeElement; } return lib; } function parseScene() { var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0]; if ( sceneElement ) { var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' ); return visualScenes[ url.length > 0 ? url : 'visual_scene0' ]; } else { return null; } } function createAnimations() { animData = []; // fill in the keys recurseHierarchy( scene ); } function recurseHierarchy( node ) { var n = daeScene.getChildById( node.name, true ), newData = null; if ( n && n.keys ) { newData = { fps: 60, hierarchy: [ { node: n, keys: n.keys, sids: n.sids } ], node: node, name: 'animation_' + node.name, length: 0 }; animData.push(newData); for ( var i = 0, il = n.keys.length; i < il; i++ ) { newData.length = Math.max( newData.length, n.keys[i].time ); } } else { newData = { hierarchy: [ { keys: [], sids: [] } ] } } for ( var i = 0, il = node.children.length; i < il; i++ ) { var d = recurseHierarchy( node.children[i] ); for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) { newData.hierarchy.push( { keys: [], sids: [] } ); } } return newData; } function calcAnimationBounds () { var start = 1000000; var end = -start; var frames = 0; var ID; for ( var id in animations ) { var animation = animations[ id ]; ID = ID || animation.id; for ( var i = 0; i < animation.sampler.length; i ++ ) { var sampler = animation.sampler[ i ]; sampler.create(); start = Math.min( start, sampler.startTime ); end = Math.max( end, sampler.endTime ); frames = Math.max( frames, sampler.input.length ); } } return { start:start, end:end, frames:frames,ID:ID }; } function createMorph ( geometry, ctrl ) { var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl; if ( !morphCtrl || !morphCtrl.morph ) { console.log("could not find morph controller!"); return; } var morph = morphCtrl.morph; for ( var i = 0; i < morph.targets.length; i ++ ) { var target_id = morph.targets[ i ]; var daeGeometry = geometries[ target_id ]; if ( !daeGeometry.mesh || !daeGeometry.mesh.primitives || !daeGeometry.mesh.primitives.length ) { continue; } var target = daeGeometry.mesh.primitives[ 0 ].geometry; if ( target.vertices.length === geometry.vertices.length ) { geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } ); } } geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } ); }; function createSkin ( geometry, ctrl, applyBindShape ) { var skinCtrl = controllers[ ctrl.url ]; if ( !skinCtrl || !skinCtrl.skin ) { console.log( "could not find skin controller!" ); return; } if ( !ctrl.skeleton || !ctrl.skeleton.length ) { console.log( "could not find the skeleton for the skin!" ); return; } var skin = skinCtrl.skin; var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] ); var hierarchy = []; applyBindShape = applyBindShape !== undefined ? applyBindShape : true; var bones = []; geometry.skinWeights = []; geometry.skinIndices = []; //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 ); //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights ); /* geometry.animation = { name: 'take_001', fps: 30, length: 2, JIT: true, hierarchy: hierarchy }; */ if ( applyBindShape ) { for ( var i = 0; i < geometry.vertices.length; i ++ ) { geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix ); } } } function setupSkeleton ( node, bones, frame, parent ) { node.world = node.world || new THREE.Matrix4(); node.localworld = node.localworld || new THREE.Matrix4(); node.world.copy( node.matrix ); node.localworld.copy( node.matrix ); if ( node.channels && node.channels.length ) { var channel = node.channels[ 0 ]; var m = channel.sampler.output[ frame ]; if ( m instanceof THREE.Matrix4 ) { node.world.copy( m ); node.localworld.copy(m); if(frame == 0) node.matrix.copy(m); } } if ( parent ) { node.world.multiplyMatrices( parent, node.world ); } bones.push( node ); for ( var i = 0; i < node.nodes.length; i ++ ) { setupSkeleton( node.nodes[ i ], bones, frame, node.world ); } } function setupSkinningMatrices ( bones, skin ) { // FIXME: this is dumb... for ( var i = 0; i < bones.length; i ++ ) { var bone = bones[ i ]; var found = -1; if ( bone.type != 'JOINT' ) continue; for ( var j = 0; j < skin.joints.length; j ++ ) { if ( bone.sid == skin.joints[ j ] ) { found = j; break; } } if ( found >= 0 ) { var inv = skin.invBindMatrices[ found ]; bone.invBindMatrix = inv; bone.skinningMatrix = new THREE.Matrix4(); bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi) bone.animatrix = new THREE.Matrix4(); bone.animatrix.copy(bone.localworld); bone.weights = []; for ( var j = 0; j < skin.weights.length; j ++ ) { for (var k = 0; k < skin.weights[ j ].length; k ++ ) { var w = skin.weights[ j ][ k ]; if ( w.joint == found ) { bone.weights.push( w ); } } } } else { console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." ); bone.skinningMatrix = new THREE.Matrix4(); bone.weights = []; } } } //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix function flattenSkeleton(skeleton) { var list = []; var walk = function(parentid, node, list) { var bone = {}; bone.name = node.sid; bone.parent = parentid; bone.matrix = node.matrix; var data = [new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3()]; bone.matrix.decompose(data[0],data[1],data[2]); bone.pos = [data[0].x,data[0].y,data[0].z]; bone.scl = [data[2].x,data[2].y,data[2].z]; bone.rotq = [data[1].x,data[1].y,data[1].z,data[1].w]; list.push(bone); for(var i in node.nodes) { walk(node.sid,node.nodes[i],list); } }; walk(-1,skeleton,list); return list; } //Move the vertices into the pose that is proper for the start of the animation function skinToBindPose(geometry,skeleton,skinController) { var bones = []; setupSkeleton( skeleton, bones, -1 ); setupSkinningMatrices( bones, skinController.skin ); v = new THREE.Vector3(); var skinned = []; for(var i =0; i < geometry.vertices.length; i++) { skinned.push(new THREE.Vector3()); } for ( i = 0; i < bones.length; i ++ ) { if ( bones[ i ].type != 'JOINT' ) continue; for ( j = 0; j < bones[ i ].weights.length; j ++ ) { w = bones[ i ].weights[ j ]; vidx = w.index; weight = w.weight; o = geometry.vertices[vidx]; s = skinned[vidx]; v.x = o.x; v.y = o.y; v.z = o.z; v.applyMatrix4( bones[i].skinningMatrix ); s.x += (v.x * weight); s.y += (v.y * weight); s.z += (v.z * weight); } } for(var i =0; i < geometry.vertices.length; i++) { geometry.vertices[i] = skinned[i]; } } function applySkin ( geometry, instanceCtrl, frame ) { // TODO: get this from the renderer or options var maxbones = 30; var skinController = controllers[ instanceCtrl.url ]; frame = frame !== undefined ? frame : 40; if ( !skinController || !skinController.skin ) { console.log( 'ColladaLoader: Could not find skin controller.' ); return; } if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) { console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' ); return; } var animationBounds = calcAnimationBounds(); var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) || daeScene.getChildBySid( instanceCtrl.skeleton[0], true ); //flatten the skeleton into a list of bones var bonelist = flattenSkeleton(skeleton); var joints = skinController.skin.joints; //sort that list so that the order reflects the order in the joint list var sortedbones = []; for(var i = 0; i < joints.length; i++) { for(var j =0; j < bonelist.length; j++) { if(bonelist[j].name == joints[i]) { sortedbones[i] = bonelist[j]; } } } //hook up the parents by index instead of name for(var i = 0; i < sortedbones.length; i++) { for(var j =0; j < sortedbones.length; j++) { if(sortedbones[i].parent == sortedbones[j].name) { sortedbones[i].parent = j; } } } var i, j, w, vidx, weight; var v = new THREE.Vector3(), o, s; // move vertices to bind shape for ( i = 0; i < geometry.vertices.length; i ++ ) { geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix ); } var skinIndices = []; var skinWeights = []; var weights = skinController.skin.weights; //hook up the skin weights // TODO - this might be a good place to choose greatest 4 weights for(var i =0; i < weights.length; i++) { var indicies = new THREE.Vector4(weights[i][0]?weights[i][0].joint:0,weights[i][1]?weights[i][1].joint:0,weights[i][2]?weights[i][2].joint:0,weights[i][3]?weights[i][3].joint:0); var weight = new THREE.Vector4(weights[i][0]?weights[i][0].weight:0,weights[i][1]?weights[i][1].weight:0,weights[i][2]?weights[i][2].weight:0,weights[i][3]?weights[i][3].weight:0); skinIndices.push(indicies); skinWeights.push(weight); } geometry.skinIndices = skinIndices; geometry.skinWeights = skinWeights; geometry.bones = sortedbones; // process animation, or simply pose the rig if no animation //create an animation for the animated bones //NOTE: this has no effect when using morphtargets var animationdata = {"name":animationBounds.ID,"fps":30,"length":animationBounds.frames/30,"hierarchy":[]}; for(var j =0; j < sortedbones.length; j++) { animationdata.hierarchy.push({parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[]}); } //if using hardware skinning, move the vertices into the binding pose if(sortedbones.length < maxbones) { skinToBindPose(geometry,skeleton,skinController); } for ( frame = 0; frame < animationBounds.frames; frame ++ ) { var bones = []; var skinned = []; // process the frame and setup the rig with a fresh // transform, possibly from the bone's animation channel(s) setupSkeleton( skeleton, bones, frame ); setupSkinningMatrices( bones, skinController.skin ); //if using hardware skinning, just hook up the animiation data if(sortedbones.length < maxbones) { for(var i = 0; i < bones.length; i ++) { for(var j = 0; j < animationdata.hierarchy.length; j ++) { if(animationdata.hierarchy[j].name == bones[i].sid) { var key = {}; key.time = (frame/30); key.matrix = bones[i].animatrix; if(frame == 0) bones[i].matrix = key.matrix; var data = [new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3()]; key.matrix.decompose(data[0],data[1],data[2]); key.pos = [data[0].x,data[0].y,data[0].z]; key.scl = [data[2].x,data[2].y,data[2].z]; key.rot = data[1]; animationdata.hierarchy[j].keys.push(key); } } } geometry.animation = animationdata; } else { // otherwise, process the animation into morphtargets for ( i = 0; i < geometry.vertices.length; i++ ) { skinned.push( new THREE.Vector3() ); } for ( i = 0; i < bones.length; i ++ ) { if ( bones[ i ].type != 'JOINT' ) continue; for ( j = 0; j < bones[ i ].weights.length; j ++ ) { w = bones[ i ].weights[ j ]; vidx = w.index; weight = w.weight; o = geometry.vertices[vidx]; s = skinned[vidx]; v.x = o.x; v.y = o.y; v.z = o.z; v.applyMatrix4( bones[i].skinningMatrix ); s.x += (v.x * weight); s.y += (v.y * weight); s.z += (v.z * weight); } } geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } ); } } }; function createSceneGraph ( node, parent ) { var obj = new THREE.Object3D(); var skinned = false; var skinController; var morphController; var i, j; // FIXME: controllers for ( i = 0; i < node.controllers.length; i ++ ) { var controller = controllers[ node.controllers[ i ].url ]; switch ( controller.type ) { case 'skin': if ( geometries[ controller.skin.source ] ) { var inst_geom = new InstanceGeometry(); inst_geom.url = controller.skin.source; inst_geom.instance_material = node.controllers[ i ].instance_material; node.geometries.push( inst_geom ); skinned = true; skinController = node.controllers[ i ]; } else if ( controllers[ controller.skin.source ] ) { // urgh: controller can be chained // handle the most basic case... var second = controllers[ controller.skin.source ]; morphController = second; // skinController = node.controllers[i]; if ( second.morph && geometries[ second.morph.source ] ) { var inst_geom = new InstanceGeometry(); inst_geom.url = second.morph.source; inst_geom.instance_material = node.controllers[ i ].instance_material; node.geometries.push( inst_geom ); } } break; case 'morph': if ( geometries[ controller.morph.source ] ) { var inst_geom = new InstanceGeometry(); inst_geom.url = controller.morph.source; inst_geom.instance_material = node.controllers[ i ].instance_material; node.geometries.push( inst_geom ); morphController = node.controllers[ i ]; } console.log( 'ColladaLoader: Morph-controller partially supported.' ); default: break; } } // geometries var double_sided_materials = {}; for ( i = 0; i < node.geometries.length; i ++ ) { var instance_geometry = node.geometries[i]; var instance_materials = instance_geometry.instance_material; var geometry = geometries[ instance_geometry.url ]; var used_materials = {}; var used_materials_array = []; var num_materials = 0; var first_material; if ( geometry ) { if ( !geometry.mesh || !geometry.mesh.primitives ) continue; if ( obj.name.length == 0 ) { obj.name = geometry.id; } // collect used fx for this geometry-instance if ( instance_materials ) { for ( j = 0; j < instance_materials.length; j ++ ) { var instance_material = instance_materials[ j ]; var mat = materials[ instance_material.target ]; var effect_id = mat.instance_effect.url; var shader = effects[ effect_id ].shader; var material3js = shader.material; if ( geometry.doubleSided ) { if ( !( instance_material.symbol in double_sided_materials ) ) { var _copied_material = material3js.clone(); _copied_material.side = THREE.DoubleSide; double_sided_materials[ instance_material.symbol ] = _copied_material; } material3js = double_sided_materials[ instance_material.symbol ]; } material3js.opacity = !material3js.opacity ? 1 : material3js.opacity; used_materials[ instance_material.symbol ] = num_materials; used_materials_array.push( material3js ); first_material = material3js; first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name; num_materials ++; } } var mesh; var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } ); var geom = geometry.mesh.geometry3js; if ( num_materials > 1 ) { material = new THREE.MeshFaceMaterial( used_materials_array ); for ( j = 0; j < geom.faces.length; j ++ ) { var face = geom.faces[ j ]; face.materialIndex = used_materials[ face.daeMaterial ] } } if ( skinController !== undefined ) { applySkin( geom, skinController ); if(geom.morphTargets.length > 0) { material.morphTargets = true; material.skinning = false; } else { material.morphTargets = false; material.skinning = true; } mesh = new THREE.SkinnedMesh( geom, material, false ); //mesh.skeleton = skinController.skeleton; //mesh.skinController = controllers[ skinController.url ]; //mesh.skinInstanceController = skinController; mesh.name = 'skin_' + skins.length; //mesh.animationHandle.setKey(0); skins.push( mesh ); } else if ( morphController !== undefined ) { createMorph( geom, morphController ); material.morphTargets = true; mesh = new THREE.Mesh( geom, material ); mesh.name = 'morph_' + morphs.length; morphs.push( mesh ); } else { mesh = new THREE.Mesh( geom, material ); // mesh.geom.name = geometry.id; } node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh; } } for ( i = 0; i < node.cameras.length; i ++ ) { var instance_camera = node.cameras[i]; var cparams = cameras[instance_camera.url]; obj = new THREE.PerspectiveCamera(cparams.fov, parseFloat(cparams.aspect_ratio), parseFloat(cparams.znear), parseFloat(cparams.zfar)); } for ( i = 0; i < node.lights.length; i ++ ) { var instance_light = node.lights[i]; var lparams = lights[instance_light.url]; if ( lparams && lparams.technique ) { var color = lparams.color.getHex(); var intensity = lparams.intensity; var distance = 0; var angle = lparams.falloff_angle; var exponent; // Intentionally undefined, don't know what this is yet switch ( lparams.technique ) { case 'directional': obj = new THREE.DirectionalLight( color, intensity, distance ); break; case 'point': obj = new THREE.PointLight( color, intensity, distance ); break; case 'spot': obj = new THREE.SpotLight( color, intensity, distance, angle, exponent ); break; case 'ambient': obj = new THREE.AmbientLight( color ); break; } } } obj.name = node.name || node.id || ""; obj.layer = node.layer || ""; obj.matrix = node.matrix; obj.matrix.decompose( obj.position, obj.quaternion, obj.scale ); if ( options.centerGeometry && obj.geometry ) { var delta = THREE.GeometryUtils.center( obj.geometry ); delta.multiply( obj.scale ); delta.applyQuaternion( obj.quaternion ); obj.position.sub( delta ); } for ( i = 0; i < node.nodes.length; i ++ ) { obj.add( createSceneGraph( node.nodes[i], node ) ); } return obj; }; function getJointId( skin, id ) { for ( var i = 0; i < skin.joints.length; i ++ ) { if ( skin.joints[ i ] == id ) { return i; } } }; function getLibraryNode( id ) { var nodes = COLLADA.querySelectorAll('library_nodes node'); for ( var i = 0; i < nodes.length; i++ ) { var attObj = nodes[i].attributes.getNamedItem('id'); if ( attObj && attObj.value === id ) { return nodes[i]; } } return undefined; }; function getChannelsForNode (node ) { var channels = []; var startTime = 1000000; var endTime = -1000000; for ( var id in animations ) { var animation = animations[id]; for ( var i = 0; i < animation.channel.length; i ++ ) { var channel = animation.channel[i]; var sampler = animation.sampler[i]; var id = channel.target.split('/')[0]; if ( id == node.id ) { sampler.create(); channel.sampler = sampler; startTime = Math.min(startTime, sampler.startTime); endTime = Math.max(endTime, sampler.endTime); channels.push(channel); } } } if ( channels.length ) { node.startTime = startTime; node.endTime = endTime; } return channels; }; function calcFrameDuration( node ) { var minT = 10000000; for ( var i = 0; i < node.channels.length; i ++ ) { var sampler = node.channels[i].sampler; for ( var j = 0; j < sampler.input.length - 1; j ++ ) { var t0 = sampler.input[ j ]; var t1 = sampler.input[ j + 1 ]; minT = Math.min( minT, t1 - t0 ); } } return minT; }; function calcMatrixAt( node, t ) { var animated = {}; var i, j; for ( i = 0; i < node.channels.length; i ++ ) { var channel = node.channels[ i ]; animated[ channel.sid ] = channel; } var matrix = new THREE.Matrix4(); for ( i = 0; i < node.transforms.length; i ++ ) { var transform = node.transforms[ i ]; var channel = animated[ transform.sid ]; if ( channel !== undefined ) { var sampler = channel.sampler; var value; for ( j = 0; j < sampler.input.length - 1; j ++ ) { if ( sampler.input[ j + 1 ] > t ) { value = sampler.output[ j ]; //console.log(value.flatten) break; } } if ( value !== undefined ) { if ( value instanceof THREE.Matrix4 ) { matrix.multiplyMatrices( matrix, value ); } else { // FIXME: handle other types matrix.multiplyMatrices( matrix, transform.matrix ); } } else { matrix.multiplyMatrices( matrix, transform.matrix ); } } else { matrix.multiplyMatrices( matrix, transform.matrix ); } } return matrix; }; function bakeAnimations ( node ) { if ( node.channels && node.channels.length ) { var keys = [], sids = []; for ( var i = 0, il = node.channels.length; i < il; i++ ) { var channel = node.channels[i], fullSid = channel.fullSid, sampler = channel.sampler, input = sampler.input, transform = node.getTransformBySid( channel.sid ), member; if ( channel.arrIndices ) { member = []; for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) { member[ j ] = getConvertedIndex( channel.arrIndices[ j ] ); } } else { member = getConvertedMember( channel.member ); } if ( transform ) { if ( sids.indexOf( fullSid ) === -1 ) { sids.push( fullSid ); } for ( var j = 0, jl = input.length; j < jl; j++ ) { var time = input[j], data = sampler.getData( transform.type, j ), key = findKey( keys, time ); if ( !key ) { key = new Key( time ); var timeNdx = findTimeNdx( keys, time ); keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key ); } key.addTarget( fullSid, transform, member, data ); } } else { console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id ); } } // post process for ( var i = 0; i < sids.length; i++ ) { var sid = sids[ i ]; for ( var j = 0; j < keys.length; j++ ) { var key = keys[ j ]; if ( !key.hasTarget( sid ) ) { interpolateKeys( keys, key, j, sid ); } } } node.keys = keys; node.sids = sids; } }; function findKey ( keys, time) { var retVal = null; for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) { var key = keys[i]; if ( key.time === time ) { retVal = key; } else if ( key.time > time ) { break; } } return retVal; }; function findTimeNdx ( keys, time) { var ndx = -1; for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) { var key = keys[i]; if ( key.time >= time ) { ndx = i; } } return ndx; }; function interpolateKeys ( keys, key, ndx, fullSid ) { var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ), nextKey = getNextKeyWith( keys, fullSid, ndx+1 ); if ( prevKey && nextKey ) { var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time), prevTarget = prevKey.getTarget( fullSid ), nextData = nextKey.getTarget( fullSid ).data, prevData = prevTarget.data, data; if ( prevTarget.type === 'matrix' ) { data = prevData; } else if ( prevData.length ) { data = []; for ( var i = 0; i < prevData.length; ++i ) { data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale; } } else { data = prevData + ( nextData - prevData ) * scale; } key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data ); } }; // Get next key with given sid function getNextKeyWith( keys, fullSid, ndx ) { for ( ; ndx < keys.length; ndx++ ) { var key = keys[ ndx ]; if ( key.hasTarget( fullSid ) ) { return key; } } return null; }; // Get previous key with given sid function getPrevKeyWith( keys, fullSid, ndx ) { ndx = ndx >= 0 ? ndx : ndx + keys.length; for ( ; ndx >= 0; ndx-- ) { var key = keys[ ndx ]; if ( key.hasTarget( fullSid ) ) { return key; } } return null; }; function _Image() { this.id = ""; this.init_from = ""; }; _Image.prototype.parse = function(element) { this.id = element.getAttribute('id'); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeName == 'init_from' ) { this.init_from = child.textContent; } } return this; }; function Controller() { this.id = ""; this.name = ""; this.type = ""; this.skin = null; this.morph = null; }; Controller.prototype.parse = function( element ) { this.id = element.getAttribute('id'); this.name = element.getAttribute('name'); this.type = "none"; for ( var i = 0; i < element.childNodes.length; i++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'skin': this.skin = (new Skin()).parse(child); this.type = child.nodeName; break; case 'morph': this.morph = (new Morph()).parse(child); this.type = child.nodeName; break; default: break; } } return this; }; function Morph() { this.method = null; this.source = null; this.targets = null; this.weights = null; }; Morph.prototype.parse = function( element ) { var sources = {}; var inputs = []; var i; this.method = element.getAttribute( 'method' ); this.source = element.getAttribute( 'source' ).replace( /^#/, '' ); for ( i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'source': var source = ( new Source() ).parse( child ); sources[ source.id ] = source; break; case 'targets': inputs = this.parseInputs( child ); break; default: console.log( child.nodeName ); break; } } for ( i = 0; i < inputs.length; i ++ ) { var input = inputs[ i ]; var source = sources[ input.source ]; switch ( input.semantic ) { case 'MORPH_TARGET': this.targets = source.read(); break; case 'MORPH_WEIGHT': this.weights = source.read(); break; default: break; } } return this; }; Morph.prototype.parseInputs = function(element) { var inputs = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1) continue; switch ( child.nodeName ) { case 'input': inputs.push( (new Input()).parse(child) ); break; default: break; } } return inputs; }; function Skin() { this.source = ""; this.bindShapeMatrix = null; this.invBindMatrices = []; this.joints = []; this.weights = []; }; Skin.prototype.parse = function( element ) { var sources = {}; var joints, weights; this.source = element.getAttribute( 'source' ).replace( /^#/, '' ); this.invBindMatrices = []; this.joints = []; this.weights = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'bind_shape_matrix': var f = _floats(child.textContent); this.bindShapeMatrix = getConvertedMat4( f ); break; case 'source': var src = new Source().parse(child); sources[ src.id ] = src; break; case 'joints': joints = child; break; case 'vertex_weights': weights = child; break; default: console.log( child.nodeName ); break; } } this.parseJoints( joints, sources ); this.parseWeights( weights, sources ); return this; }; Skin.prototype.parseJoints = function ( element, sources ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'input': var input = ( new Input() ).parse( child ); var source = sources[ input.source ]; if ( input.semantic == 'JOINT' ) { this.joints = source.read(); } else if ( input.semantic == 'INV_BIND_MATRIX' ) { this.invBindMatrices = source.read(); } break; default: break; } } }; Skin.prototype.parseWeights = function ( element, sources ) { var v, vcount, inputs = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'input': inputs.push( ( new Input() ).parse( child ) ); break; case 'v': v = _ints( child.textContent ); break; case 'vcount': vcount = _ints( child.textContent ); break; default: break; } } var index = 0; for ( var i = 0; i < vcount.length; i ++ ) { var numBones = vcount[i]; var vertex_weights = []; for ( var j = 0; j < numBones; j++ ) { var influence = {}; for ( var k = 0; k < inputs.length; k ++ ) { var input = inputs[ k ]; var value = v[ index + input.offset ]; switch ( input.semantic ) { case 'JOINT': influence.joint = value;//this.joints[value]; break; case 'WEIGHT': influence.weight = sources[ input.source ].data[ value ]; break; default: break; } } vertex_weights.push( influence ); index += inputs.length; } for ( var j = 0; j < vertex_weights.length; j ++ ) { vertex_weights[ j ].index = i; } this.weights.push( vertex_weights ); } }; function VisualScene () { this.id = ""; this.name = ""; this.nodes = []; this.scene = new THREE.Object3D(); }; VisualScene.prototype.getChildById = function( id, recursive ) { for ( var i = 0; i < this.nodes.length; i ++ ) { var node = this.nodes[ i ].getChildById( id, recursive ); if ( node ) { return node; } } return null; }; VisualScene.prototype.getChildBySid = function( sid, recursive ) { for ( var i = 0; i < this.nodes.length; i ++ ) { var node = this.nodes[ i ].getChildBySid( sid, recursive ); if ( node ) { return node; } } return null; }; VisualScene.prototype.parse = function( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); this.nodes = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'node': this.nodes.push( ( new Node() ).parse( child ) ); break; default: break; } } return this; }; function Node() { this.id = ""; this.name = ""; this.sid = ""; this.nodes = []; this.controllers = []; this.transforms = []; this.geometries = []; this.channels = []; this.matrix = new THREE.Matrix4(); }; Node.prototype.getChannelForTransform = function( transformSid ) { for ( var i = 0; i < this.channels.length; i ++ ) { var channel = this.channels[i]; var parts = channel.target.split('/'); var id = parts.shift(); var sid = parts.shift(); var dotSyntax = (sid.indexOf(".") >= 0); var arrSyntax = (sid.indexOf("(") >= 0); var arrIndices; var member; if ( dotSyntax ) { parts = sid.split("."); sid = parts.shift(); member = parts.shift(); } else if ( arrSyntax ) { arrIndices = sid.split("("); sid = arrIndices.shift(); for ( var j = 0; j < arrIndices.length; j ++ ) { arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) ); } } if ( sid == transformSid ) { channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices }; return channel; } } return null; }; Node.prototype.getChildById = function ( id, recursive ) { if ( this.id == id ) { return this; } if ( recursive ) { for ( var i = 0; i < this.nodes.length; i ++ ) { var n = this.nodes[ i ].getChildById( id, recursive ); if ( n ) { return n; } } } return null; }; Node.prototype.getChildBySid = function ( sid, recursive ) { if ( this.sid == sid ) { return this; } if ( recursive ) { for ( var i = 0; i < this.nodes.length; i ++ ) { var n = this.nodes[ i ].getChildBySid( sid, recursive ); if ( n ) { return n; } } } return null; }; Node.prototype.getTransformBySid = function ( sid ) { for ( var i = 0; i < this.transforms.length; i ++ ) { if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ]; } return null; }; Node.prototype.parse = function( element ) { var url; this.id = element.getAttribute('id'); this.sid = element.getAttribute('sid'); this.name = element.getAttribute('name'); this.type = element.getAttribute('type'); this.layer = element.getAttribute('layer'); this.type = this.type == 'JOINT' ? this.type : 'NODE'; this.nodes = []; this.transforms = []; this.geometries = []; this.cameras = []; this.lights = []; this.controllers = []; this.matrix = new THREE.Matrix4(); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'node': this.nodes.push( ( new Node() ).parse( child ) ); break; case 'instance_camera': this.cameras.push( ( new InstanceCamera() ).parse( child ) ); break; case 'instance_controller': this.controllers.push( ( new InstanceController() ).parse( child ) ); break; case 'instance_geometry': this.geometries.push( ( new InstanceGeometry() ).parse( child ) ); break; case 'instance_light': this.lights.push( ( new InstanceLight() ).parse( child ) ); break; case 'instance_node': url = child.getAttribute( 'url' ).replace( /^#/, '' ); var iNode = getLibraryNode( url ); if ( iNode ) { this.nodes.push( ( new Node() ).parse( iNode )) ; } break; case 'rotate': case 'translate': case 'scale': case 'matrix': case 'lookat': case 'skew': this.transforms.push( ( new Transform() ).parse( child ) ); break; case 'extra': break; default: console.log( child.nodeName ); break; } } this.channels = getChannelsForNode( this ); bakeAnimations( this ); this.updateMatrix(); return this; }; Node.prototype.updateMatrix = function () { this.matrix.identity(); for ( var i = 0; i < this.transforms.length; i ++ ) { this.transforms[ i ].apply( this.matrix ); } }; function Transform () { this.sid = ""; this.type = ""; this.data = []; this.obj = null; }; Transform.prototype.parse = function ( element ) { this.sid = element.getAttribute( 'sid' ); this.type = element.nodeName; this.data = _floats( element.textContent ); this.convert(); return this; }; Transform.prototype.convert = function () { switch ( this.type ) { case 'matrix': this.obj = getConvertedMat4( this.data ); break; case 'rotate': this.angle = THREE.Math.degToRad( this.data[3] ); case 'translate': fixCoords( this.data, -1 ); this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] ); break; case 'scale': fixCoords( this.data, 1 ); this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] ); break; default: console.log( 'Can not convert Transform of type ' + this.type ); break; } }; Transform.prototype.apply = function () { var m1 = new THREE.Matrix4(); return function ( matrix ) { switch ( this.type ) { case 'matrix': matrix.multiply( this.obj ); break; case 'translate': matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) ); break; case 'rotate': matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) ); break; case 'scale': matrix.scale( this.obj ); break; } }; }(); Transform.prototype.update = function ( data, member ) { var members = [ 'X', 'Y', 'Z', 'ANGLE' ]; switch ( this.type ) { case 'matrix': if ( ! member ) { this.obj.copy( data ); } else if ( member.length === 1 ) { switch ( member[ 0 ] ) { case 0: this.obj.n11 = data[ 0 ]; this.obj.n21 = data[ 1 ]; this.obj.n31 = data[ 2 ]; this.obj.n41 = data[ 3 ]; break; case 1: this.obj.n12 = data[ 0 ]; this.obj.n22 = data[ 1 ]; this.obj.n32 = data[ 2 ]; this.obj.n42 = data[ 3 ]; break; case 2: this.obj.n13 = data[ 0 ]; this.obj.n23 = data[ 1 ]; this.obj.n33 = data[ 2 ]; this.obj.n43 = data[ 3 ]; break; case 3: this.obj.n14 = data[ 0 ]; this.obj.n24 = data[ 1 ]; this.obj.n34 = data[ 2 ]; this.obj.n44 = data[ 3 ]; break; } } else if ( member.length === 2 ) { var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 ); this.obj[ propName ] = data; } else { console.log('Incorrect addressing of matrix in transform.'); } break; case 'translate': case 'scale': if ( Object.prototype.toString.call( member ) === '[object Array]' ) { member = members[ member[ 0 ] ]; } switch ( member ) { case 'X': this.obj.x = data; break; case 'Y': this.obj.y = data; break; case 'Z': this.obj.z = data; break; default: this.obj.x = data[ 0 ]; this.obj.y = data[ 1 ]; this.obj.z = data[ 2 ]; break; } break; case 'rotate': if ( Object.prototype.toString.call( member ) === '[object Array]' ) { member = members[ member[ 0 ] ]; } switch ( member ) { case 'X': this.obj.x = data; break; case 'Y': this.obj.y = data; break; case 'Z': this.obj.z = data; break; case 'ANGLE': this.angle = THREE.Math.degToRad( data ); break; default: this.obj.x = data[ 0 ]; this.obj.y = data[ 1 ]; this.obj.z = data[ 2 ]; this.angle = THREE.Math.degToRad( data[ 3 ] ); break; } break; } }; function InstanceController() { this.url = ""; this.skeleton = []; this.instance_material = []; }; InstanceController.prototype.parse = function ( element ) { this.url = element.getAttribute('url').replace(/^#/, ''); this.skeleton = []; this.instance_material = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType !== 1 ) continue; switch ( child.nodeName ) { case 'skeleton': this.skeleton.push( child.textContent.replace(/^#/, '') ); break; case 'bind_material': var instances = child.querySelectorAll('instance_material'); for ( var j = 0; j < instances.length; j ++ ){ var instance = instances[j]; this.instance_material.push( (new InstanceMaterial()).parse(instance) ); } break; case 'extra': break; default: break; } } return this; }; function InstanceMaterial () { this.symbol = ""; this.target = ""; }; InstanceMaterial.prototype.parse = function ( element ) { this.symbol = element.getAttribute('symbol'); this.target = element.getAttribute('target').replace(/^#/, ''); return this; }; function InstanceGeometry() { this.url = ""; this.instance_material = []; }; InstanceGeometry.prototype.parse = function ( element ) { this.url = element.getAttribute('url').replace(/^#/, ''); this.instance_material = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1 ) continue; if ( child.nodeName == 'bind_material' ) { var instances = child.querySelectorAll('instance_material'); for ( var j = 0; j < instances.length; j ++ ) { var instance = instances[j]; this.instance_material.push( (new InstanceMaterial()).parse(instance) ); } break; } } return this; }; function Geometry() { this.id = ""; this.mesh = null; }; Geometry.prototype.parse = function ( element ) { this.id = element.getAttribute('id'); extractDoubleSided( this, element ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; switch ( child.nodeName ) { case 'mesh': this.mesh = (new Mesh(this)).parse(child); break; case 'extra': // console.log( child ); break; default: break; } } return this; }; function Mesh( geometry ) { this.geometry = geometry.id; this.primitives = []; this.vertices = null; this.geometry3js = null; }; Mesh.prototype.parse = function( element ) { this.primitives = []; var i, j; for ( i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'source': _source( child ); break; case 'vertices': this.vertices = ( new Vertices() ).parse( child ); break; case 'triangles': this.primitives.push( ( new Triangles().parse( child ) ) ); break; case 'polygons': this.primitives.push( ( new Polygons().parse( child ) ) ); break; case 'polylist': this.primitives.push( ( new Polylist().parse( child ) ) ); break; default: break; } } this.geometry3js = new THREE.Geometry(); var vertexData = sources[ this.vertices.input['POSITION'].source ].data; for ( i = 0; i < vertexData.length; i += 3 ) { this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() ); } for ( i = 0; i < this.primitives.length; i ++ ) { var primitive = this.primitives[ i ]; primitive.setVertices( this.vertices ); this.handlePrimitive( primitive, this.geometry3js ); } this.geometry3js.computeCentroids(); this.geometry3js.computeFaceNormals(); if ( this.geometry3js.calcNormals ) { this.geometry3js.computeVertexNormals(); delete this.geometry3js.calcNormals; } // this.geometry3js.computeBoundingBox(); return this; }; Mesh.prototype.handlePrimitive = function( primitive, geom ) { var j, k, pList = primitive.p, inputs = primitive.inputs; var input, index, idx32; var source, numParams; var vcIndex = 0, vcount = 3, maxOffset = 0; var texture_sets = []; for ( j = 0; j < inputs.length; j ++ ) { input = inputs[ j ]; var offset = input.offset + 1; maxOffset = (maxOffset < offset)? offset : maxOffset; switch ( input.semantic ) { case 'TEXCOORD': texture_sets.push( input.set ); break; } } for ( var pCount = 0; pCount < pList.length; ++pCount ) { var p = pList[ pCount ], i = 0; while ( i < p.length ) { var vs = []; var ns = []; var ts = null; var cs = []; if ( primitive.vcount ) { vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount; } else { vcount = p.length / maxOffset; } for ( j = 0; j < vcount; j ++ ) { for ( k = 0; k < inputs.length; k ++ ) { input = inputs[ k ]; source = sources[ input.source ]; index = p[ i + ( j * maxOffset ) + input.offset ]; numParams = source.accessor.params.length; idx32 = index * numParams; switch ( input.semantic ) { case 'VERTEX': vs.push( index ); break; case 'NORMAL': ns.push( getConvertedVec3( source.data, idx32 ) ); break; case 'TEXCOORD': ts = ts || { }; if ( ts[ input.set ] === undefined ) ts[ input.set ] = []; // invert the V ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) ); break; case 'COLOR': cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) ); break; default: break; } } } if ( ns.length == 0 ) { // check the vertices inputs input = this.vertices.input.NORMAL; if ( input ) { source = sources[ input.source ]; numParams = source.accessor.params.length; for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) { ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) ); } } else { geom.calcNormals = true; } } if ( !ts ) { ts = { }; // check the vertices inputs input = this.vertices.input.TEXCOORD; if ( input ) { texture_sets.push( input.set ); source = sources[ input.source ]; numParams = source.accessor.params.length; for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) { idx32 = vs[ ndx ] * numParams; if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ]; // invert the V ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) ); } } } if ( cs.length == 0 ) { // check the vertices inputs input = this.vertices.input.COLOR; if ( input ) { source = sources[ input.source ]; numParams = source.accessor.params.length; for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) { idx32 = vs[ ndx ] * numParams; cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) ); } } } var face = null, faces = [], uv, uvArr; if ( vcount === 3 ) { faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) ); } else if ( vcount === 4 ) { faces.push( new THREE.Face3( vs[0], vs[1], vs[3], [ns[0], ns[1], ns[3]], cs.length ? [cs[0], cs[1], cs[3]] : new THREE.Color() ) ); faces.push( new THREE.Face3( vs[1], vs[2], vs[3], [ns[1], ns[2], ns[3]], cs.length ? [cs[1], cs[2], cs[3]] : new THREE.Color() ) ); } else if ( vcount > 4 && options.subdivideFaces ) { var clr = cs.length ? cs : new THREE.Color(), vec1, vec2, vec3, v1, v2, norm; // subdivide into multiple Face3s for ( k = 1; k < vcount - 1; ) { // FIXME: normals don't seem to be quite right faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) ); } } if ( faces.length ) { for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) { face = faces[ndx]; face.daeMaterial = primitive.material; geom.faces.push( face ); for ( k = 0; k < texture_sets.length; k++ ) { uv = ts[ texture_sets[k] ]; if ( vcount > 4 ) { // Grab the right UVs for the vertices in this face uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ]; } else if ( vcount === 4 ) { if ( ndx === 0 ) { uvArr = [ uv[0], uv[1], uv[3] ]; } else { uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ]; } } else { uvArr = [ uv[0], uv[1], uv[2] ]; } if ( geom.faceVertexUvs[k] === undefined ) { geom.faceVertexUvs[k] = []; } geom.faceVertexUvs[k].push( uvArr ); } } } else { console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id ); } i += maxOffset * vcount; } } }; function Polygons () { this.material = ""; this.count = 0; this.inputs = []; this.vcount = null; this.p = []; this.geometry = new THREE.Geometry(); }; Polygons.prototype.setVertices = function ( vertices ) { for ( var i = 0; i < this.inputs.length; i ++ ) { if ( this.inputs[ i ].source == vertices.id ) { this.inputs[ i ].source = vertices.input[ 'POSITION' ].source; } } }; Polygons.prototype.parse = function ( element ) { this.material = element.getAttribute( 'material' ); this.count = _attr_as_int( element, 'count', 0 ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'input': this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) ); break; case 'vcount': this.vcount = _ints( child.textContent ); break; case 'p': this.p.push( _ints( child.textContent ) ); break; case 'ph': console.warn( 'polygon holes not yet supported!' ); break; default: break; } } return this; }; function Polylist () { Polygons.call( this ); this.vcount = []; }; Polylist.prototype = Object.create( Polygons.prototype ); function Triangles () { Polygons.call( this ); this.vcount = 3; }; Triangles.prototype = Object.create( Polygons.prototype ); function Accessor() { this.source = ""; this.count = 0; this.stride = 0; this.params = []; }; Accessor.prototype.parse = function ( element ) { this.params = []; this.source = element.getAttribute( 'source' ); this.count = _attr_as_int( element, 'count', 0 ); this.stride = _attr_as_int( element, 'stride', 0 ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeName == 'param' ) { var param = {}; param[ 'name' ] = child.getAttribute( 'name' ); param[ 'type' ] = child.getAttribute( 'type' ); this.params.push( param ); } } return this; }; function Vertices() { this.input = {}; }; Vertices.prototype.parse = function ( element ) { this.id = element.getAttribute('id'); for ( var i = 0; i < element.childNodes.length; i ++ ) { if ( element.childNodes[i].nodeName == 'input' ) { var input = ( new Input() ).parse( element.childNodes[ i ] ); this.input[ input.semantic ] = input; } } return this; }; function Input () { this.semantic = ""; this.offset = 0; this.source = ""; this.set = 0; }; Input.prototype.parse = function ( element ) { this.semantic = element.getAttribute('semantic'); this.source = element.getAttribute('source').replace(/^#/, ''); this.set = _attr_as_int(element, 'set', -1); this.offset = _attr_as_int(element, 'offset', 0); if ( this.semantic == 'TEXCOORD' && this.set < 0 ) { this.set = 0; } return this; }; function Source ( id ) { this.id = id; this.type = null; }; Source.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; switch ( child.nodeName ) { case 'bool_array': this.data = _bools( child.textContent ); this.type = child.nodeName; break; case 'float_array': this.data = _floats( child.textContent ); this.type = child.nodeName; break; case 'int_array': this.data = _ints( child.textContent ); this.type = child.nodeName; break; case 'IDREF_array': case 'Name_array': this.data = _strings( child.textContent ); this.type = child.nodeName; break; case 'technique_common': for ( var j = 0; j < child.childNodes.length; j ++ ) { if ( child.childNodes[ j ].nodeName == 'accessor' ) { this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] ); break; } } break; default: // console.log(child.nodeName); break; } } return this; }; Source.prototype.read = function () { var result = []; //for (var i = 0; i < this.accessor.params.length; i++) { var param = this.accessor.params[ 0 ]; //console.log(param.name + " " + param.type); switch ( param.type ) { case 'IDREF': case 'Name': case 'name': case 'float': return this.data; case 'float4x4': for ( var j = 0; j < this.data.length; j += 16 ) { var s = this.data.slice( j, j + 16 ); var m = getConvertedMat4( s ); result.push( m ); } break; default: console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' ); break; } //} return result; }; function Material () { this.id = ""; this.name = ""; this.instance_effect = null; }; Material.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { if ( element.childNodes[ i ].nodeName == 'instance_effect' ) { this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] ); break; } } return this; }; function ColorOrTexture () { this.color = new THREE.Color(); this.color.setRGB( Math.random(), Math.random(), Math.random() ); this.color.a = 1.0; this.texture = null; this.texcoord = null; this.texOpts = null; }; ColorOrTexture.prototype.isColor = function () { return ( this.texture == null ); }; ColorOrTexture.prototype.isTexture = function () { return ( this.texture != null ); }; ColorOrTexture.prototype.parse = function ( element ) { if (element.nodeName == 'transparent') { this.opaque = element.getAttribute('opaque'); } for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'color': var rgba = _floats( child.textContent ); this.color = new THREE.Color(); this.color.setRGB( rgba[0], rgba[1], rgba[2] ); this.color.a = rgba[3]; break; case 'texture': this.texture = child.getAttribute('texture'); this.texcoord = child.getAttribute('texcoord'); // Defaults from: // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension this.texOpts = { offsetU: 0, offsetV: 0, repeatU: 1, repeatV: 1, wrapU: 1, wrapV: 1 }; this.parseTexture( child ); break; default: break; } } return this; }; ColorOrTexture.prototype.parseTexture = function ( element ) { if ( ! element.childNodes ) return this; // This should be supported by Maya, 3dsMax, and MotionBuilder if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) { element = element.childNodes[1]; if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) { element = element.childNodes[1]; } } for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'offsetU': case 'offsetV': case 'repeatU': case 'repeatV': this.texOpts[ child.nodeName ] = parseFloat( child.textContent ); break; case 'wrapU': case 'wrapV': // some dae have a value of true which becomes NaN via parseInt if ( child.textContent.toUpperCase() === 'TRUE' ) { this.texOpts[ child.nodeName ] = 1; } else { this.texOpts[ child.nodeName ] = parseInt( child.textContent ); } break; default: this.texOpts[ child.nodeName ] = child.textContent; break; } } return this; }; function Shader ( type, effect ) { this.type = type; this.effect = effect; this.material = null; }; Shader.prototype.parse = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'ambient': case 'emission': case 'diffuse': case 'specular': case 'transparent': case 'bump': this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child ); break; case 'shininess': case 'reflectivity': case 'index_of_refraction': case 'transparency': var f = child.querySelectorAll('float'); if ( f.length > 0 ) this[ child.nodeName ] = parseFloat( f[ 0 ].textContent ); break; default: break; } } this.create(); return this; }; Shader.prototype.create = function() { var props = {}; var transparent = false; if (this['transparency'] !== undefined && this['transparent'] !== undefined) { // convert transparent color RBG to average value var transparentColor = this['transparent']; var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency; if (transparencyLevel > 0) { transparent = true; props[ 'transparent' ] = true; props[ 'opacity' ] = 1 - transparencyLevel; } } var keys = { 'diffuse':'map', 'ambient':"lightMap" , 'specular':'specularMap', 'emission':'emissionMap', 'bump':'normalMap' }; for ( var prop in this ) { switch ( prop ) { case 'ambient': case 'emission': case 'diffuse': case 'specular': case 'bump': var cot = this[ prop ]; if ( cot instanceof ColorOrTexture ) { if ( cot.isTexture() ) { var samplerId = cot.texture; var surfaceId = this.effect.sampler[samplerId]; if ( surfaceId !== undefined && surfaceId.source !== undefined ) { var surface = this.effect.surface[surfaceId.source]; var image = images[surface.init_from]; if (image) { var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from); texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping; texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping; texture.offset.x = cot.texOpts.offsetU; texture.offset.y = cot.texOpts.offsetV; texture.repeat.x = cot.texOpts.repeatU; texture.repeat.y = cot.texOpts.repeatV; props[keys[prop]] = texture; // Texture with baked lighting? if (prop === 'emission') props['emissive'] = 0xffffff; } } } else if ( prop === 'diffuse' || !transparent ) { if ( prop === 'emission' ) { props[ 'emissive' ] = cot.color.getHex(); } else { props[ prop ] = cot.color.getHex(); } } } break; case 'shininess': props[ prop ] = this[ prop ]; break; case 'reflectivity': props[ prop ] = this[ prop ]; if( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap; props['combine'] = THREE.MixOperation; //mix regular shading with reflective component break; case 'index_of_refraction': props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap; break; case 'transparency': // gets figured out up top break; default: break; } } props[ 'shading' ] = preferredShading; props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide; switch ( this.type ) { case 'constant': if (props.emissive != undefined) props.color = props.emissive; this.material = new THREE.MeshBasicMaterial( props ); break; case 'phong': case 'blinn': if (props.diffuse != undefined) props.color = props.diffuse; this.material = new THREE.MeshPhongMaterial( props ); break; case 'lambert': default: if (props.diffuse != undefined) props.color = props.diffuse; this.material = new THREE.MeshLambertMaterial( props ); break; } return this.material; }; function Surface ( effect ) { this.effect = effect; this.init_from = null; this.format = null; }; Surface.prototype.parse = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'init_from': this.init_from = child.textContent; break; case 'format': this.format = child.textContent; break; default: console.log( "unhandled Surface prop: " + child.nodeName ); break; } } return this; }; function Sampler2D ( effect ) { this.effect = effect; this.source = null; this.wrap_s = null; this.wrap_t = null; this.minfilter = null; this.magfilter = null; this.mipfilter = null; }; Sampler2D.prototype.parse = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'source': this.source = child.textContent; break; case 'minfilter': this.minfilter = child.textContent; break; case 'magfilter': this.magfilter = child.textContent; break; case 'mipfilter': this.mipfilter = child.textContent; break; case 'wrap_s': this.wrap_s = child.textContent; break; case 'wrap_t': this.wrap_t = child.textContent; break; default: console.log( "unhandled Sampler2D prop: " + child.nodeName ); break; } } return this; }; function Effect () { this.id = ""; this.name = ""; this.shader = null; this.surface = {}; this.sampler = {}; }; Effect.prototype.create = function () { if ( this.shader == null ) { return null; } }; Effect.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); extractDoubleSided( this, element ); this.shader = null; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'profile_COMMON': this.parseTechnique( this.parseProfileCOMMON( child ) ); break; default: break; } } return this; }; Effect.prototype.parseNewparam = function ( element ) { var sid = element.getAttribute( 'sid' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'surface': this.surface[sid] = ( new Surface( this ) ).parse( child ); break; case 'sampler2D': this.sampler[sid] = ( new Sampler2D( this ) ).parse( child ); break; case 'extra': break; default: console.log( child.nodeName ); break; } } }; Effect.prototype.parseProfileCOMMON = function ( element ) { var technique; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'profile_COMMON': this.parseProfileCOMMON( child ); break; case 'technique': technique = child; break; case 'newparam': this.parseNewparam( child ); break; case 'image': var _image = ( new _Image() ).parse( child ); images[ _image.id ] = _image; break; case 'extra': break; default: console.log( child.nodeName ); break; } } return technique; }; Effect.prototype.parseTechnique= function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'constant': case 'lambert': case 'blinn': case 'phong': this.shader = ( new Shader( child.nodeName, this ) ).parse( child ); break; case 'extra': this.parseExtra(child); break; default: break; } } }; Effect.prototype.parseExtra = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'technique': this.parseExtraTechnique( child ); break; default: break; } } }; Effect.prototype.parseExtraTechnique= function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[i]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'bump': this.shader.parse( element ); break; default: break; } } }; function InstanceEffect () { this.url = ""; }; InstanceEffect.prototype.parse = function ( element ) { this.url = element.getAttribute( 'url' ).replace( /^#/, '' ); return this; }; function Animation() { this.id = ""; this.name = ""; this.source = {}; this.sampler = []; this.channel = []; }; Animation.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); this.source = {}; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'animation': var anim = ( new Animation() ).parse( child ); for ( var src in anim.source ) { this.source[ src ] = anim.source[ src ]; } for ( var j = 0; j < anim.channel.length; j ++ ) { this.channel.push( anim.channel[ j ] ); this.sampler.push( anim.sampler[ j ] ); } break; case 'source': var src = ( new Source() ).parse( child ); this.source[ src.id ] = src; break; case 'sampler': this.sampler.push( ( new Sampler( this ) ).parse( child ) ); break; case 'channel': this.channel.push( ( new Channel( this ) ).parse( child ) ); break; default: break; } } return this; }; function Channel( animation ) { this.animation = animation; this.source = ""; this.target = ""; this.fullSid = null; this.sid = null; this.dotSyntax = null; this.arrSyntax = null; this.arrIndices = null; this.member = null; }; Channel.prototype.parse = function ( element ) { this.source = element.getAttribute( 'source' ).replace( /^#/, '' ); this.target = element.getAttribute( 'target' ); var parts = this.target.split( '/' ); var id = parts.shift(); var sid = parts.shift(); var dotSyntax = ( sid.indexOf(".") >= 0 ); var arrSyntax = ( sid.indexOf("(") >= 0 ); if ( dotSyntax ) { parts = sid.split("."); this.sid = parts.shift(); this.member = parts.shift(); } else if ( arrSyntax ) { var arrIndices = sid.split("("); this.sid = arrIndices.shift(); for (var j = 0; j < arrIndices.length; j ++ ) { arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') ); } this.arrIndices = arrIndices; } else { this.sid = sid; } this.fullSid = sid; this.dotSyntax = dotSyntax; this.arrSyntax = arrSyntax; return this; }; function Sampler ( animation ) { this.id = ""; this.animation = animation; this.inputs = []; this.input = null; this.output = null; this.strideOut = null; this.interpolation = null; this.startTime = null; this.endTime = null; this.duration = 0; }; Sampler.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.inputs = []; for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'input': this.inputs.push( (new Input()).parse( child ) ); break; default: break; } } return this; }; Sampler.prototype.create = function () { for ( var i = 0; i < this.inputs.length; i ++ ) { var input = this.inputs[ i ]; var source = this.animation.source[ input.source ]; switch ( input.semantic ) { case 'INPUT': this.input = source.read(); break; case 'OUTPUT': this.output = source.read(); this.strideOut = source.accessor.stride; break; case 'INTERPOLATION': this.interpolation = source.read(); break; case 'IN_TANGENT': break; case 'OUT_TANGENT': break; default: console.log(input.semantic); break; } } this.startTime = 0; this.endTime = 0; this.duration = 0; if ( this.input.length ) { this.startTime = 100000000; this.endTime = -100000000; for ( var i = 0; i < this.input.length; i ++ ) { this.startTime = Math.min( this.startTime, this.input[ i ] ); this.endTime = Math.max( this.endTime, this.input[ i ] ); } this.duration = this.endTime - this.startTime; } }; Sampler.prototype.getData = function ( type, ndx ) { var data; if ( type === 'matrix' && this.strideOut === 16 ) { data = this.output[ ndx ]; } else if ( this.strideOut > 1 ) { data = []; ndx *= this.strideOut; for ( var i = 0; i < this.strideOut; ++i ) { data[ i ] = this.output[ ndx + i ]; } if ( this.strideOut === 3 ) { switch ( type ) { case 'rotate': case 'translate': fixCoords( data, -1 ); break; case 'scale': fixCoords( data, 1 ); break; } } else if ( this.strideOut === 4 && type === 'matrix' ) { fixCoords( data, -1 ); } } else { data = this.output[ ndx ]; } return data; }; function Key ( time ) { this.targets = []; this.time = time; }; Key.prototype.addTarget = function ( fullSid, transform, member, data ) { this.targets.push( { sid: fullSid, member: member, transform: transform, data: data } ); }; Key.prototype.apply = function ( opt_sid ) { for ( var i = 0; i < this.targets.length; ++i ) { var target = this.targets[ i ]; if ( !opt_sid || target.sid === opt_sid ) { target.transform.update( target.data, target.member ); } } }; Key.prototype.getTarget = function ( fullSid ) { for ( var i = 0; i < this.targets.length; ++i ) { if ( this.targets[ i ].sid === fullSid ) { return this.targets[ i ]; } } return null; }; Key.prototype.hasTarget = function ( fullSid ) { for ( var i = 0; i < this.targets.length; ++i ) { if ( this.targets[ i ].sid === fullSid ) { return true; } } return false; }; // TODO: Currently only doing linear interpolation. Should support full COLLADA spec. Key.prototype.interpolate = function ( nextKey, time ) { for ( var i = 0, l = this.targets.length; i < l; i ++ ) { var target = this.targets[ i ], nextTarget = nextKey.getTarget( target.sid ), data; if ( target.transform.type !== 'matrix' && nextTarget ) { var scale = ( time - this.time ) / ( nextKey.time - this.time ), nextData = nextTarget.data, prevData = target.data; if ( scale < 0 ) scale = 0; if ( scale > 1 ) scale = 1; if ( prevData.length ) { data = []; for ( var j = 0; j < prevData.length; ++j ) { data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale; } } else { data = prevData + ( nextData - prevData ) * scale; } } else { data = target.data; } target.transform.update( data, target.member ); } }; // Camera function Camera() { this.id = ""; this.name = ""; this.technique = ""; }; Camera.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'optics': this.parseOptics( child ); break; default: break; } } return this; }; Camera.prototype.parseOptics = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { if ( element.childNodes[ i ].nodeName == 'technique_common' ) { var technique = element.childNodes[ i ]; for ( var j = 0; j < technique.childNodes.length; j ++ ) { this.technique = technique.childNodes[ j ].nodeName; if ( this.technique == 'perspective' ) { var perspective = technique.childNodes[ j ]; for ( var k = 0; k < perspective.childNodes.length; k ++ ) { var param = perspective.childNodes[ k ]; switch ( param.nodeName ) { case 'yfov': this.yfov = param.textContent; break; case 'xfov': this.xfov = param.textContent; break; case 'znear': this.znear = param.textContent; break; case 'zfar': this.zfar = param.textContent; break; case 'aspect_ratio': this.aspect_ratio = param.textContent; break; } } } else if ( this.technique == 'orthographic' ) { var orthographic = technique.childNodes[ j ]; for ( var k = 0; k < orthographic.childNodes.length; k ++ ) { var param = orthographic.childNodes[ k ]; switch ( param.nodeName ) { case 'xmag': this.xmag = param.textContent; break; case 'ymag': this.ymag = param.textContent; break; case 'znear': this.znear = param.textContent; break; case 'zfar': this.zfar = param.textContent; break; case 'aspect_ratio': this.aspect_ratio = param.textContent; break; } } } } } } return this; }; function InstanceCamera() { this.url = ""; }; InstanceCamera.prototype.parse = function ( element ) { this.url = element.getAttribute('url').replace(/^#/, ''); return this; }; // Light function Light() { this.id = ""; this.name = ""; this.technique = ""; }; Light.prototype.parse = function ( element ) { this.id = element.getAttribute( 'id' ); this.name = element.getAttribute( 'name' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; if ( child.nodeType != 1 ) continue; switch ( child.nodeName ) { case 'technique_common': this.parseCommon( child ); break; case 'technique': this.parseTechnique( child ); break; default: break; } } return this; }; Light.prototype.parseCommon = function ( element ) { for ( var i = 0; i < element.childNodes.length; i ++ ) { switch ( element.childNodes[ i ].nodeName ) { case 'directional': case 'point': case 'spot': case 'ambient': this.technique = element.childNodes[ i ].nodeName; var light = element.childNodes[ i ]; for ( var j = 0; j < light.childNodes.length; j ++ ) { var child = light.childNodes[j]; switch ( child.nodeName ) { case 'color': var rgba = _floats( child.textContent ); this.color = new THREE.Color(0); this.color.setRGB( rgba[0], rgba[1], rgba[2] ); this.color.a = rgba[3]; break; case 'falloff_angle': this.falloff_angle = parseFloat( child.textContent ); break; } } } } return this; }; Light.prototype.parseTechnique = function ( element ) { this.profile = element.getAttribute( 'profile' ); for ( var i = 0; i < element.childNodes.length; i ++ ) { var child = element.childNodes[ i ]; switch ( child.nodeName ) { case 'intensity': this.intensity = parseFloat(child.textContent); break; } } return this; }; function InstanceLight() { this.url = ""; }; InstanceLight.prototype.parse = function ( element ) { this.url = element.getAttribute('url').replace(/^#/, ''); return this; }; function _source( element ) { var id = element.getAttribute( 'id' ); if ( sources[ id ] != undefined ) { return sources[ id ]; } sources[ id ] = ( new Source(id )).parse( element ); return sources[ id ]; }; function _nsResolver( nsPrefix ) { if ( nsPrefix == "dae" ) { return "http://www.collada.org/2005/11/COLLADASchema"; } return null; }; function _bools( str ) { var raw = _strings( str ); var data = []; for ( var i = 0, l = raw.length; i < l; i ++ ) { data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false ); } return data; }; function _floats( str ) { var raw = _strings(str); var data = []; for ( var i = 0, l = raw.length; i < l; i ++ ) { data.push( parseFloat( raw[ i ] ) ); } return data; }; function _ints( str ) { var raw = _strings( str ); var data = []; for ( var i = 0, l = raw.length; i < l; i ++ ) { data.push( parseInt( raw[ i ], 10 ) ); } return data; }; function _strings( str ) { return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : []; }; function _trimString( str ) { return str.replace( /^\s+/, "" ).replace( /\s+$/, "" ); }; function _attr_as_float( element, name, defaultValue ) { if ( element.hasAttribute( name ) ) { return parseFloat( element.getAttribute( name ) ); } else { return defaultValue; } }; function _attr_as_int( element, name, defaultValue ) { if ( element.hasAttribute( name ) ) { return parseInt( element.getAttribute( name ), 10) ; } else { return defaultValue; } }; function _attr_as_string( element, name, defaultValue ) { if ( element.hasAttribute( name ) ) { return element.getAttribute( name ); } else { return defaultValue; } }; function _format_float( f, num ) { if ( f === undefined ) { var s = '0.'; while ( s.length < num + 2 ) { s += '0'; } return s; } num = num || 2; var parts = f.toString().split( '.' ); parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0"; while( parts[ 1 ].length < num ) { parts[ 1 ] += '0'; } return parts.join( '.' ); }; function extractDoubleSided( obj, element ) { obj.doubleSided = false; var node = element.querySelectorAll('extra double_sided')[0]; if ( node ) { if ( node && parseInt( node.textContent, 10 ) === 1 ) { obj.doubleSided = true; } } }; // Up axis conversion function setUpConversion() { if ( !options.convertUpAxis || colladaUp === options.upAxis ) { upConversion = null; } else { switch ( colladaUp ) { case 'X': upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ'; break; case 'Y': upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ'; break; case 'Z': upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY'; break; } } }; function fixCoords( data, sign ) { if ( !options.convertUpAxis || colladaUp === options.upAxis ) { return; } switch ( upConversion ) { case 'XtoY': var tmp = data[ 0 ]; data[ 0 ] = sign * data[ 1 ]; data[ 1 ] = tmp; break; case 'XtoZ': var tmp = data[ 2 ]; data[ 2 ] = data[ 1 ]; data[ 1 ] = data[ 0 ]; data[ 0 ] = tmp; break; case 'YtoX': var tmp = data[ 0 ]; data[ 0 ] = data[ 1 ]; data[ 1 ] = sign * tmp; break; case 'YtoZ': var tmp = data[ 1 ]; data[ 1 ] = sign * data[ 2 ]; data[ 2 ] = tmp; break; case 'ZtoX': var tmp = data[ 0 ]; data[ 0 ] = data[ 1 ]; data[ 1 ] = data[ 2 ]; data[ 2 ] = tmp; break; case 'ZtoY': var tmp = data[ 1 ]; data[ 1 ] = data[ 2 ]; data[ 2 ] = sign * tmp; break; } }; function getConvertedVec3( data, offset ) { var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ]; fixCoords( arr, -1 ); return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] ); }; function getConvertedMat4( data ) { if ( options.convertUpAxis ) { // First fix rotation and scale // Columns first var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ]; fixCoords( arr, -1 ); data[ 0 ] = arr[ 0 ]; data[ 4 ] = arr[ 1 ]; data[ 8 ] = arr[ 2 ]; arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ]; fixCoords( arr, -1 ); data[ 1 ] = arr[ 0 ]; data[ 5 ] = arr[ 1 ]; data[ 9 ] = arr[ 2 ]; arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ]; fixCoords( arr, -1 ); data[ 2 ] = arr[ 0 ]; data[ 6 ] = arr[ 1 ]; data[ 10 ] = arr[ 2 ]; // Rows second arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ]; fixCoords( arr, -1 ); data[ 0 ] = arr[ 0 ]; data[ 1 ] = arr[ 1 ]; data[ 2 ] = arr[ 2 ]; arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ]; fixCoords( arr, -1 ); data[ 4 ] = arr[ 0 ]; data[ 5 ] = arr[ 1 ]; data[ 6 ] = arr[ 2 ]; arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ]; fixCoords( arr, -1 ); data[ 8 ] = arr[ 0 ]; data[ 9 ] = arr[ 1 ]; data[ 10 ] = arr[ 2 ]; // Now fix translation arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ]; fixCoords( arr, -1 ); data[ 3 ] = arr[ 0 ]; data[ 7 ] = arr[ 1 ]; data[ 11 ] = arr[ 2 ]; } return new THREE.Matrix4( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15] ); }; function getConvertedIndex( index ) { if ( index > -1 && index < 3 ) { var members = ['X', 'Y', 'Z'], indices = { X: 0, Y: 1, Z: 2 }; index = getConvertedMember( members[ index ] ); index = indices[ index ]; } return index; }; function getConvertedMember( member ) { if ( options.convertUpAxis ) { switch ( member ) { case 'X': switch ( upConversion ) { case 'XtoY': case 'XtoZ': case 'YtoX': member = 'Y'; break; case 'ZtoX': member = 'Z'; break; } break; case 'Y': switch ( upConversion ) { case 'XtoY': case 'YtoX': case 'ZtoX': member = 'X'; break; case 'XtoZ': case 'YtoZ': case 'ZtoY': member = 'Z'; break; } break; case 'Z': switch ( upConversion ) { case 'XtoZ': member = 'X'; break; case 'YtoZ': case 'ZtoX': case 'ZtoY': member = 'Y'; break; } break; } } return member; }; return { load: load, parse: parse, setPreferredShading: setPreferredShading, applySkin: applySkin, geometries : geometries, options: options }; };
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ THREE.OBJLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.OBJLoader.prototype = { constructor: THREE.OBJLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader( scope.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { onLoad( scope.parse( text ) ); } ); }, parse: function ( text ) { var object, objects = []; var geometry, material, mesh; function parseVertexIndex( value ) { var index = parseInt( value ); return ( index >= 0 ? index - 1 : index + vertices.length / 3 ) * 3; } function parseNormalIndex( value ) { var index = parseInt( value ); return ( index >= 0 ? index - 1 : index + normals.length / 3 ) * 3; } function parseUVIndex( value ) { var index = parseInt( value ); return ( index >= 0 ? index - 1 : index + uvs.length / 2 ) * 2; } function addVertex( a, b, c ) { geometry.vertices.push( vertices[ a ], vertices[ a + 1 ], vertices[ a + 2 ], vertices[ b ], vertices[ b + 1 ], vertices[ b + 2 ], vertices[ c ], vertices[ c + 1 ], vertices[ c + 2 ] ); } function addNormal( a, b, c ) { geometry.normals.push( normals[ a ], normals[ a + 1 ], normals[ a + 2 ], normals[ b ], normals[ b + 1 ], normals[ b + 2 ], normals[ c ], normals[ c + 1 ], normals[ c + 2 ] ); } function addUV( a, b, c ) { geometry.uvs.push( uvs[ a ], uvs[ a + 1 ], uvs[ b ], uvs[ b + 1 ], uvs[ c ], uvs[ c + 1 ] ); } function handleFace( a, b, c, d ) { var ia = parseVertexIndex( a ); var ib = parseVertexIndex( b ); var ic = parseVertexIndex( c ); if ( d === undefined ) { addVertex( ia, ib, ic ); } else { var id = parseVertexIndex( d ); addVertex( ia, ib, id ); addVertex( ib, ic, id ); } } function handleUV( a, b, c, d ) { var ia = parseUVIndex( a ); var ib = parseUVIndex( b ); var ic = parseUVIndex( c ); if ( d === undefined ) { addUV( ia, ib, ic ); } else { var id = parseUVIndex( d ); addUV( ia, ib, id ); addUV( ib, ic, id ); } } function handleNormal( a, b, c, d ) { var ia = parseNormalIndex( a ); var ib = parseNormalIndex( b ); var ic = parseNormalIndex( c ); if ( d === undefined ) { addNormal( ia, ib, ic ); } else { var id = parseNormalIndex( d ); addNormal( ia, ib, id ); addNormal( ib, ic, id ); } } // create mesh if no objects in text if ( /^o /gm.test( text ) === false ) { geometry = { vertices: [], normals: [], uvs: [] }; material = { name: '' }; object = { name: '', geometry: geometry, material: material }; objects.push( object ); } var vertices = []; var normals = []; var uvs = []; // v float float float var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vn float float float var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vt float float var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // f vertex vertex vertex ... var face_pattern1 = /f( +-?\d+)( +-?\d+)( +-?\d+)( +-?\d+)?/; // f vertex/uv vertex/uv vertex/uv ... var face_pattern2 = /f( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+))?/; // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... var face_pattern3 = /f( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))( +(-?\d+)\/(-?\d+)\/(-?\d+))?/; // f vertex//normal vertex//normal vertex//normal ... var face_pattern4 = /f( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))( +(-?\d+)\/\/(-?\d+))?/ // var lines = text.split( '\n' ); for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim(); var result; if ( line.length === 0 || line.charAt( 0 ) === '#' ) { continue; } else if ( ( result = vertex_pattern.exec( line ) ) !== null ) { // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ); } else if ( ( result = normal_pattern.exec( line ) ) !== null ) { // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] normals.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ); } else if ( ( result = uv_pattern.exec( line ) ) !== null ) { // ["vt 0.1 0.2", "0.1", "0.2"] uvs.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ) ); } else if ( ( result = face_pattern1.exec( line ) ) !== null ) { // ["f 1 2 3", "1", "2", "3", undefined] handleFace( result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ] ); } else if ( ( result = face_pattern2.exec( line ) ) !== null ) { // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] handleFace( result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ); handleUV( result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ); } else if ( ( result = face_pattern3.exec( line ) ) !== null ) { // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] handleFace( result[ 2 ], result[ 6 ], result[ 10 ], result[ 14 ] ); handleUV( result[ 3 ], result[ 7 ], result[ 11 ], result[ 15 ] ); handleNormal( result[ 4 ], result[ 8 ], result[ 12 ], result[ 16 ] ); } else if ( ( result = face_pattern4.exec( line ) ) !== null ) { // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] handleFace( result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ); handleNormal( result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ); } else if ( /^o /.test( line ) ) { geometry = { vertices: [], normals: [], uvs: [] }; material = { name: '' }; object = { name: line.substring( 2 ).trim(), geometry: geometry }; objects.push( object ) } else if ( /^g /.test( line ) ) { // group } else if ( /^usemtl /.test( line ) ) { // material material.name = line.substring( 7 ).trim(); } else if ( /^mtllib /.test( line ) ) { // mtl file } else if ( /^s /.test( line ) ) { // smooth shading } else { // console.log( "THREE.OBJLoader: Unhandled line " + line ); } } var container = new THREE.Object3D(); for ( var i = 0, l = objects.length; i < l; i ++ ) { var object = objects[ i ]; var geometry = new THREE.Geometry2( object.geometry.vertices.length / 3 ); geometry.vertices.set( object.geometry.vertices ); geometry.normals.set( object.geometry.normals ); geometry.uvs.set( object.geometry.uvs ); var material = new THREE.MeshLambertMaterial(); material.name = object.material.name; var mesh = new THREE.Mesh( geometry, material ); mesh.name = object.name; container.add( mesh ); } return container; } };
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ THREE.VRMLLoader = function () {}; THREE.VRMLLoader.prototype = { constructor: THREE.VRMLLoader, // for IndexedFaceSet support isRecordingPoints: false, isRecordingFaces: false, points: [], indexes : [], // for Background support isRecordingAngles: false, isRecordingColors: false, angles: [], colors: [], recordingFieldname: null, load: function ( url, callback ) { var scope = this; var request = new XMLHttpRequest(); request.addEventListener( 'load', function ( event ) { var object = scope.parse( event.target.responseText ); scope.dispatchEvent( { type: 'load', content: object } ); if ( callback ) callback( object ); }, false ); request.addEventListener( 'progress', function ( event ) { scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } ); }, false ); request.addEventListener( 'error', function () { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } ); }, false ); request.open( 'GET', url, true ); request.send( null ); }, parse: function ( data ) { var parseV1 = function ( lines, scene ) { console.warn( 'VRML V1.0 not supported yet' ); }; var parseV2 = function ( lines, scene ) { var defines = {}; var float_pattern = /(\b|\-|\+)([\d\.e]+)/; var float3_pattern = /([\d\.\+\-e]+),?\s+([\d\.\+\-e]+),?\s+([\d\.\+\-e]+)/; /** * Interpolates colors a and b following their relative distance * expressed by t. * * @param float a * @param float b * @param float t * @returns {Color} */ var interpolateColors = function(a, b, t) { var deltaR = a.r - b.r; var deltaG = a.g - b.g; var deltaB = a.b - b.b; var c = new THREE.Color(); c.r = a.r - t * deltaR; c.g = a.g - t * deltaG; c.b = a.b - t * deltaB; return c; }; /** * Vertically paints the faces interpolating between the * specified colors at the specified angels. This is used for the Background * node, but could be applied to other nodes with multiple faces as well. * * When used with the Background node, default is directionIsDown is true if * interpolating the skyColor down from the Zenith. When interpolationg up from * the Nadir i.e. interpolating the groundColor, the directionIsDown is false. * * The first angle is never specified, it is the Zenith (0 rad). Angles are specified * in radians. The geometry is thought a sphere, but could be anything. The color interpolation * is linear along the Y axis in any case. * * You must specify one more color than you have angles at the beginning of the colors array. * This is the color of the Zenith (the top of the shape). * * @param geometry * @param radius * @param angles * @param colors * @param boolean directionIsDown Whether to work bottom up or top down. */ var paintFaces = function (geometry, radius, angles, colors, directionIsDown) { var f, n, p, vertexIndex, color; var direction = directionIsDown ? 1 : -1; var faceIndices = [ 'a', 'b', 'c', 'd' ]; var coord = [ ], aColor, bColor, t = 1, A = {}, B = {}, applyColor = false, colorIndex; for ( var k = 0; k < angles.length; k++ ) { var vec = { }; // push the vector at which the color changes vec.y = direction * ( Math.cos( angles[k] ) * radius); vec.x = direction * ( Math.sin( angles[k] ) * radius); coord.push( vec ); } // painting the colors on the faces for ( var i = 0; i < geometry.faces.length ; i++ ) { f = geometry.faces[ i ]; n = ( f instanceof THREE.Face3 ) ? 3 : 4; for ( var j = 0; j < n; j++ ) { vertexIndex = f[ faceIndices[ j ] ]; p = geometry.vertices[ vertexIndex ]; for ( var index = 0; index < colors.length; index++ ) { // linear interpolation between aColor and bColor, calculate proportion // A is previous point (angle) if ( index === 0 ) { A.x = 0; A.y = directionIsDown ? radius : -1 * radius; } else { A.x = coord[ index-1 ].x; A.y = coord[ index-1 ].y; } // B is current point (angle) B = coord[index]; if ( undefined !== B ) { // p has to be between the points A and B which we interpolate applyColor = directionIsDown ? p.y <= A.y && p.y > B.y : p.y >= A.y && p.y < B.y; if (applyColor) { bColor = colors[ index + 1 ]; aColor = colors[ index ]; // below is simple linear interpolation t = Math.abs( p.y - A.y ) / ( A.y - B.y ); // to make it faster, you can only calculate this if the y coord changes, the color is the same for points with the same y color = interpolateColors( aColor, bColor, t ); f.vertexColors[ j ] = color; } } else if ( undefined === f.vertexColors[ j ] ) { colorIndex = directionIsDown ? colors.length -1 : 0; f.vertexColors[ j ] = colors[ colorIndex ]; } } } } }; var parseProperty = function (node, line) { var parts = [], part, property = {}, fieldName; /** * Expression for matching relevant information, such as a name or value, but not the separators * @type {RegExp} */ var regex = /[^\s,\[\]]+/g; var point, index, angles, colors; while (null != ( part = regex.exec(line) ) ) { parts.push(part[0]); } fieldName = parts[0]; // trigger several recorders switch (fieldName) { case 'skyAngle': case 'groundAngle': this.recordingFieldname = fieldName; this.isRecordingAngles = true; this.angles = []; break; case 'skyColor': case 'groundColor': this.recordingFieldname = fieldName; this.isRecordingColors = true; this.colors = []; break; case 'point': this.recordingFieldname = fieldName; this.isRecordingPoints = true; this.points = []; break; case 'coordIndex': this.recordingFieldname = fieldName; this.isRecordingFaces = true; this.indexes = []; break; } if (this.isRecordingFaces) { // the parts hold the indexes as strings if (parts.length > 0) { index = []; for (var ind = 0;ind < parts.length; ind++) { // the part should either be positive integer or -1 if (!/(-?\d+)/.test( parts[ind]) ) { continue; } // end of current face if (parts[ind] === "-1") { if (index.length > 0) { this.indexes.push(index); } // start new one index = []; } else { index.push(parseInt( parts[ind]) ); } } } // end if (/]/.exec(line)) { this.isRecordingFaces = false; node.coordIndex = this.indexes; } } else if (this.isRecordingPoints) { parts = float3_pattern.exec(line); // parts may be empty on first and last line if (null != parts) { point = { x: parseFloat(parts[1]), y: parseFloat(parts[2]), z: parseFloat(parts[3]) }; this.points.push(point); } // end if ( /]/.exec(line) ) { this.isRecordingPoints = false; node.points = this.points; } } else if ( this.isRecordingAngles ) { // the parts hold the angles as strings if ( parts.length > 0 ) { for ( var ind = 0;ind < parts.length; ind++ ) { // the part should be a float if ( ! float_pattern.test( parts[ind] ) ) { continue; } this.angles.push( parseFloat( parts[ind] ) ); } } // end if ( /]/.exec(line) ) { this.isRecordingAngles = false; node[this.recordingFieldname] = this.angles; } } else if (this.isRecordingColors) { // this is the float3 regex with the g modifier added, you could also explode the line by comma first (faster probably) var float3_repeatable = /([\d\.\+\-e]+),?\s+([\d\.\+\-e]+),?\s+([\d\.\+\-e]+)/g; while( null !== (parts = float3_repeatable.exec(line) ) ) { color = { r: parseFloat(parts[1]), g: parseFloat(parts[2]), b: parseFloat(parts[3]) }; this.colors.push(color); } // end if (/]/.exec(line)) { this.isRecordingColors = false; node[this.recordingFieldname] = this.colors; } } else if ( parts[parts.length -1] !== 'NULL' && fieldName !== 'children') { switch (fieldName) { case 'diffuseColor': case 'emissiveColor': case 'specularColor': case 'color': if (parts.length != 4) { console.warn('Invalid color format detected for ' + fieldName ); break; } property = { 'r' : parseFloat(parts[1]), 'g' : parseFloat(parts[2]), 'b' : parseFloat(parts[3]) } break; case 'translation': case 'scale': case 'size': if (parts.length != 4) { console.warn('Invalid vector format detected for ' + fieldName); break; } property = { 'x' : parseFloat(parts[1]), 'y' : parseFloat(parts[2]), 'z' : parseFloat(parts[3]) } break; case 'radius': case 'topRadius': case 'bottomRadius': case 'height': case 'transparency': case 'shininess': case 'ambientIntensity': if (parts.length != 2) { console.warn('Invalid single float value specification detected for ' + fieldName); break; } property = parseFloat(parts[1]); break; case 'rotation': if (parts.length != 5) { console.warn('Invalid quaternion format detected for ' + fieldName); break; } property = { 'x' : parseFloat(parts[1]), 'y' : parseFloat(parts[2]), 'z' : parseFloat(parts[3]), 'w' : parseFloat(parts[4]) } break; case 'ccw': case 'solid': case 'colorPerVertex': case 'convex': if (parts.length != 2) { console.warn('Invalid format detected for ' + fieldName); break; } property = parts[1] === 'TRUE' ? true : false; break; } node[fieldName] = property; } return property; }; var getTree = function ( lines ) { var tree = { 'string': 'Scene', children: [] }; var current = tree; var matches; var specification; for ( var i = 0; i < lines.length; i ++ ) { var comment = ''; var line = lines[ i ]; // omit whitespace only lines if ( null !== ( result = /^\s+?$/g.exec( line ) ) ) { continue; } line = line.trim(); // skip empty lines if (line === '') { continue; } if ( /#/.exec( line ) ) { var parts = line.split('#'); // discard everything after the #, it is a comment line = parts[0]; // well, let's also keep the comment comment = parts[1]; } if ( matches = /([^\s]*){1}\s?{/.exec( line ) ) { // first subpattern should match the Node name var block = { 'nodeType' : matches[1], 'string': line, 'parent': current, 'children': [],'comment' : comment}; current.children.push( block ); current = block; if ( /}/.exec( line ) ) { // example: geometry Box { size 1 1 1 } # all on the same line specification = /{(.*)}/.exec( line )[ 1 ]; // todo: remove once new parsing is complete? block.children.push( specification ); parseProperty(current, specification); current = current.parent; } } else if ( /}/.exec( line ) ) { current = current.parent; } else if ( line !== '' ) { parseProperty(current, line); // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way current.children.push( line ); } } return tree; } var parseNode = function ( data, parent ) { // console.log( data ); if ( typeof data === 'string' ) { if ( /USE/.exec( data ) ) { var defineKey = /USE\s+?(\w+)/.exec( data )[ 1 ]; if (undefined == defines[defineKey]) { console.warn(defineKey + ' is not defined.'); } else { if ( /appearance/.exec( data ) && defineKey ) { parent.material = defines[ defineKey ].clone(); } else if ( /geometry/.exec( data ) && defineKey ) { parent.geometry = defines[ defineKey ].clone(); // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it if (undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false) { parent.geometry.solid = false; parent.material.side = THREE.DoubleSide; } } else if (defineKey){ var object = defines[ defineKey ].clone(); parent.add( object ); } } } return; } var object = parent; if ( 'Transform' === data.nodeType || 'Group' === data.nodeType ) { object = new THREE.Object3D(); if ( /DEF/.exec( data.string ) ) { object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ]; defines[ object.name ] = object; } if ( undefined !== data['translation'] ) { var t = data.translation; object.position.set(t.x, t.y, t.z); } if ( undefined !== data.rotation ) { var r = data.rotation; object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w ); } if ( undefined !== data.scale ) { var s = data.scale; object.scale.set( s.x, s.y, s.z ); } parent.add( object ); } else if ( 'Shape' === data.nodeType ) { object = new THREE.Mesh(); if ( /DEF/.exec( data.string ) ) { object.name = /DEF (\w+)/.exec( data.string )[ 1 ]; defines[ object.name ] = object; } parent.add( object ); } else if ( 'Background' === data.nodeType ) { var segments = 20; // sky (full sphere): var radius = 2e4; var skyGeometry = new THREE.SphereGeometry( radius, segments, segments ); var skyMaterial = new THREE.MeshBasicMaterial( { color: 'white', vertexColors: THREE.VertexColors, shading: THREE.NoShading } ); skyMaterial.side = THREE.BackSide; skyMaterial.fog = false; skyMaterial.color = new THREE.Color(); paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true ); var sky = new THREE.Mesh( skyGeometry, skyMaterial ); scene.add( sky ); // ground (half sphere): radius = 1.2e4; var groundGeometry = new THREE.SphereGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI ); var groundMaterial = new THREE.MeshBasicMaterial( { color: 'white', vertexColors: THREE.VertexColors, shading: THREE.NoShading } ); groundMaterial.side = THREE.BackSide; groundMaterial.fog = false; groundMaterial.color = new THREE.Color(); paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false ); var ground = new THREE.Mesh( groundGeometry, groundMaterial ); scene.add( ground ); } else if ( /geometry/.exec( data.string ) ) { if ( 'Box' === data.nodeType ) { var s = data.size; parent.geometry = new THREE.BoxGeometry( s.x, s.y, s.z ); } else if ( 'Cylinder' === data.nodeType ) { parent.geometry = new THREE.CylinderGeometry( data.radius, data.radius, data.height ); } else if ( 'Cone' === data.nodeType ) { parent.geometry = new THREE.CylinderGeometry( data.topRadius, data.bottomRadius, data.height ); } else if ( 'Sphere' === data.nodeType ) { parent.geometry = new THREE.SphereGeometry( data.radius ); } else if ( 'IndexedFaceSet' === data.nodeType ) { var geometry = new THREE.Geometry(); var indexes; for ( var i = 0, j = data.children.length; i < j; i++ ) { var child = data.children[ i ]; var vec; if ( 'Coordinate' === child.nodeType ) { for ( var k = 0, l = child.points.length; k < l; k++ ) { var point = child.points[ k ]; vec = new THREE.Vector3( point.x, point.y, point.z ); geometry.vertices.push( vec ); } break; } } var skip = 0; // read this: http://math.hws.edu/eck/cs424/notes2013/16_Threejs_Advanced.html for ( var i = 0, j = data.coordIndex.length; i < j; i++ ) { indexes = data.coordIndex[i]; // vrml support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here skip = 0; // todo: this is the time to check if the faces are ordered ccw or not (cw) // Face3 only works with triangles, but IndexedFaceSet allows shapes with more then three vertices, build them of triangles while ( indexes.length >= 3 && skip < ( indexes.length -2 ) ) { var face = new THREE.Face3( indexes[0], indexes[skip + 1], indexes[skip + 2], null // normal, will be added later // todo: pass in the color, if a color index is present ); skip++; geometry.faces.push( face ); } } if ( false === data.solid ) { parent.material.side = THREE.DoubleSide; } // we need to store it on the geometry for use with defines geometry.solid = data.solid; geometry.computeFaceNormals(); //geometry.computeVertexNormals(); // does not show geometry.computeBoundingSphere(); // see if it's a define if ( /DEF/.exec( data.string ) ) { geometry.name = /DEF (\w+)/.exec( data.string )[ 1 ]; defines[ geometry.name ] = geometry; } parent.geometry = geometry; } return; } else if ( /appearance/.exec( data.string ) ) { for ( var i = 0; i < data.children.length; i ++ ) { var child = data.children[ i ]; if ( 'Material' === child.nodeType ) { var material = new THREE.MeshPhongMaterial(); if ( undefined !== child.diffuseColor ) { var d = child.diffuseColor; material.color.setRGB( d.r, d.g, d.b ); } if ( undefined !== child.emissiveColor ) { var e = child.emissiveColor; material.emissive.setRGB( e.r, e.g, e.b ); } if ( undefined !== child.specularColor ) { var s = child.specularColor; material.specular.setRGB( s.r, s.g, s.b ); } if ( undefined !== child.transparency ) { var t = child.transparency; // transparency is opposite of opacity material.opacity = Math.abs( 1 - t ); material.transparent = true; } if ( /DEF/.exec( data.string ) ) { material.name = /DEF (\w+)/.exec( data.string )[ 1 ]; defines[ material.name ] = material; } parent.material = material; // material found, stop looping break; } } return; } for ( var i = 0, l = data.children.length; i < l; i ++ ) { var child = data.children[ i ]; parseNode( data.children[ i ], object ); } } parseNode( getTree( lines ), scene ); }; var scene = new THREE.Scene(); var lines = data.split( '\n' ); var header = lines.shift(); if ( /V1.0/.exec( header ) ) { parseV1( lines, scene ); } else if ( /V2.0/.exec( header ) ) { parseV2( lines, scene ); } return scene; } }; THREE.EventDispatcher.prototype.apply( THREE.VRMLLoader.prototype );
JavaScript
/** * Loads a Wavefront .obj file with materials * * @author mrdoob / http://mrdoob.com/ * @author angelxuanchang */ THREE.OBJMTLLoader = function () {}; THREE.OBJMTLLoader.prototype = { constructor: THREE.OBJMTLLoader, load: function ( url, mtlurl, onLoad, onProgress, onError ) { var scope = this; var mtlLoader = new THREE.MTLLoader( url.substr( 0, url.lastIndexOf( "/" ) + 1 ) ); mtlLoader.load( mtlurl, function ( materials ) { var materialsCreator = materials; materialsCreator.preload(); var loader = new THREE.XHRLoader( scope.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { var object = scope.parse( text ); object.traverse( function ( object ) { if ( object instanceof THREE.Mesh ) { if ( object.material.name ) { var material = materialsCreator.create( object.material.name ); if ( material ) object.material = material; } } } ); onLoad( object ); } ); } ); }, /** * Parses loaded .obj file * @param data - content of .obj file * @param mtllibCallback - callback to handle mtllib declaration (optional) * @return {THREE.Object3D} - Object3D (with default material) */ parse: function ( data, mtllibCallback ) { function vector( x, y, z ) { return new THREE.Vector3( x, y, z ); } function uv( u, v ) { return new THREE.Vector2( u, v ); } function face3( a, b, c, normals ) { return new THREE.Face3( a, b, c, normals ); } var face_offset = 0; function meshN( meshName, materialName ) { if ( vertices.length > 0 ) { geometry.vertices = vertices; geometry.mergeVertices(); geometry.computeCentroids(); geometry.computeFaceNormals(); geometry.computeBoundingSphere(); object.add( mesh ); geometry = new THREE.Geometry(); mesh = new THREE.Mesh( geometry, material ); verticesCount = 0; } if ( meshName !== undefined ) mesh.name = meshName; if ( materialName !== undefined ) { material = new THREE.MeshLambertMaterial(); material.name = materialName; mesh.material = material; } } var group = new THREE.Object3D(); var object = group; var geometry = new THREE.Geometry(); var material = new THREE.MeshLambertMaterial(); var mesh = new THREE.Mesh( geometry, material ); var vertices = []; var verticesCount = 0; var normals = []; var uvs = []; function add_face( a, b, c, normals_inds ) { if ( normals_inds === undefined ) { geometry.faces.push( face3( parseInt( a ) - (face_offset + 1), parseInt( b ) - (face_offset + 1), parseInt( c ) - (face_offset + 1) ) ); } else { geometry.faces.push( face3( parseInt( a ) - (face_offset + 1), parseInt( b ) - (face_offset + 1), parseInt( c ) - (face_offset + 1), [ normals[ parseInt( normals_inds[ 0 ] ) - 1 ].clone(), normals[ parseInt( normals_inds[ 1 ] ) - 1 ].clone(), normals[ parseInt( normals_inds[ 2 ] ) - 1 ].clone() ] ) ); } } function add_uvs( a, b, c ) { geometry.faceVertexUvs[ 0 ].push( [ uvs[ parseInt( a ) - 1 ].clone(), uvs[ parseInt( b ) - 1 ].clone(), uvs[ parseInt( c ) - 1 ].clone() ] ); } function handle_face_line(faces, uvs, normals_inds) { if ( faces[ 3 ] === undefined ) { add_face( faces[ 0 ], faces[ 1 ], faces[ 2 ], normals_inds ); if (!(uvs === undefined) && uvs.length > 0) { add_uvs( uvs[ 0 ], uvs[ 1 ], uvs[ 2 ] ); } } else { if (!(normals_inds === undefined) && normals_inds.length > 0) { add_face( faces[ 0 ], faces[ 1 ], faces[ 3 ], [ normals_inds[ 0 ], normals_inds[ 1 ], normals_inds[ 3 ] ]); add_face( faces[ 1 ], faces[ 2 ], faces[ 3 ], [ normals_inds[ 1 ], normals_inds[ 2 ], normals_inds[ 3 ] ]); } else { add_face( faces[ 0 ], faces[ 1 ], faces[ 3 ]); add_face( faces[ 1 ], faces[ 2 ], faces[ 3 ]); } if (!(uvs === undefined) && uvs.length > 0) { add_uvs( uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ); add_uvs( uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ); } } } // v float float float var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vn float float float var normal_pattern = /vn( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // vt float float var uv_pattern = /vt( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/; // f vertex vertex vertex ... var face_pattern1 = /f( +\d+)( +\d+)( +\d+)( +\d+)?/; // f vertex/uv vertex/uv vertex/uv ... var face_pattern2 = /f( +(\d+)\/(\d+))( +(\d+)\/(\d+))( +(\d+)\/(\d+))( +(\d+)\/(\d+))?/; // f vertex/uv/normal vertex/uv/normal vertex/uv/normal ... var face_pattern3 = /f( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))?/; // f vertex//normal vertex//normal vertex//normal ... var face_pattern4 = /f( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))?/ // var lines = data.split( "\n" ); for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim(); var result; if ( line.length === 0 || line.charAt( 0 ) === '#' ) { continue; } else if ( ( result = vertex_pattern.exec( line ) ) !== null ) { // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] vertices.push( vector( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ) ); } else if ( ( result = normal_pattern.exec( line ) ) !== null ) { // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] normals.push( vector( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ) ); } else if ( ( result = uv_pattern.exec( line ) ) !== null ) { // ["vt 0.1 0.2", "0.1", "0.2"] uvs.push( uv( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ) ) ); } else if ( ( result = face_pattern1.exec( line ) ) !== null ) { // ["f 1 2 3", "1", "2", "3", undefined] handle_face_line([ result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ] ]); } else if ( ( result = face_pattern2.exec( line ) ) !== null ) { // ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3", undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ], //faces [ result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ] //uv ); } else if ( ( result = face_pattern3.exec( line ) ) !== null ) { // ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3", undefined, undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 6 ], result[ 10 ], result[ 14 ] ], //faces [ result[ 3 ], result[ 7 ], result[ 11 ], result[ 15 ] ], //uv [ result[ 4 ], result[ 8 ], result[ 12 ], result[ 16 ] ] //normal ); } else if ( ( result = face_pattern4.exec( line ) ) !== null ) { // ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3", undefined, undefined, undefined] handle_face_line( [ result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ] ], //faces [ ], //uv [ result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ] ] //normal ); } else if ( /^o /.test( line ) ) { // object meshN(); face_offset = face_offset + vertices.length; vertices = []; object = new THREE.Object3D(); object.name = line.substring( 2 ).trim(); group.add( object ); } else if ( /^g /.test( line ) ) { // group meshN( line.substring( 2 ).trim(), undefined ); } else if ( /^usemtl /.test( line ) ) { // material meshN( undefined, line.substring( 7 ).trim() ); } else if ( /^mtllib /.test( line ) ) { // mtl file if ( mtllibCallback ) { var mtlfile = line.substring( 7 ); mtlfile = mtlfile.trim(); mtllibCallback( mtlfile ); } } else if ( /^s /.test( line ) ) { // Smooth shading } else { console.log( "THREE.OBJMTLLoader: Unhandled line " + line ); } } //Add last object meshN(undefined, undefined); return group; } }; THREE.EventDispatcher.prototype.apply( THREE.OBJMTLLoader.prototype );
JavaScript
/** * Loads a Wavefront .mtl file specifying materials * * @author angelxuanchang */ THREE.MTLLoader = function( baseUrl, options, crossOrigin ) { this.baseUrl = baseUrl; this.options = options; this.crossOrigin = crossOrigin; }; THREE.MTLLoader.prototype = { constructor: THREE.MTLLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.XHRLoader(); loader.setCrossOrigin( this.crossOrigin ); loader.load( url, function ( text ) { onLoad( scope.parse( text ) ); } ); }, /** * Parses loaded MTL file * @param text - Content of MTL file * @return {THREE.MTLLoader.MaterialCreator} */ parse: function ( text ) { var lines = text.split( "\n" ); var info = {}; var delimiter_pattern = /\s+/; var materialsInfo = {}; for ( var i = 0; i < lines.length; i ++ ) { var line = lines[ i ]; line = line.trim(); if ( line.length === 0 || line.charAt( 0 ) === '#' ) { // Blank line or comment ignore continue; } var pos = line.indexOf( ' ' ); var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line; key = key.toLowerCase(); var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : ""; value = value.trim(); if ( key === "newmtl" ) { // New material info = { name: value }; materialsInfo[ value ] = info; } else if ( info ) { if ( key === "ka" || key === "kd" || key === "ks" ) { var ss = value.split( delimiter_pattern, 3 ); info[ key ] = [ parseFloat( ss[0] ), parseFloat( ss[1] ), parseFloat( ss[2] ) ]; } else { info[ key ] = value; } } } var materialCreator = new THREE.MTLLoader.MaterialCreator( this.baseUrl, this.options ); materialCreator.setMaterials( materialsInfo ); return materialCreator; } }; /** * Create a new THREE-MTLLoader.MaterialCreator * @param baseUrl - Url relative to which textures are loaded * @param options - Set of options on how to construct the materials * side: Which side to apply the material * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide * wrap: What type of wrapping to apply for textures * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255 * Default: false, assumed to be already normalized * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's * Default: false * invertTransparency: If transparency need to be inverted (inversion is needed if d = 0 is fully opaque) * Default: false (d = 1 is fully opaque) * @constructor */ THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) { this.baseUrl = baseUrl; this.options = options; this.materialsInfo = {}; this.materials = {}; this.materialsArray = []; this.nameLookup = {}; this.side = ( this.options && this.options.side )? this.options.side: THREE.FrontSide; this.wrap = ( this.options && this.options.wrap )? this.options.wrap: THREE.RepeatWrapping; }; THREE.MTLLoader.MaterialCreator.prototype = { constructor: THREE.MTLLoader.MaterialCreator, setMaterials: function( materialsInfo ) { this.materialsInfo = this.convert( materialsInfo ); this.materials = {}; this.materialsArray = []; this.nameLookup = {}; }, convert: function( materialsInfo ) { if ( !this.options ) return materialsInfo; var converted = {}; for ( var mn in materialsInfo ) { // Convert materials info into normalized form based on options var mat = materialsInfo[ mn ]; var covmat = {}; converted[ mn ] = covmat; for ( var prop in mat ) { var save = true; var value = mat[ prop ]; var lprop = prop.toLowerCase(); switch ( lprop ) { case 'kd': case 'ka': case 'ks': // Diffuse color (color under white light) using RGB values if ( this.options && this.options.normalizeRGB ) { value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ]; } if ( this.options && this.options.ignoreZeroRGBs ) { if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 1 ] === 0 ) { // ignore save = false; } } break; case 'd': // According to MTL format (http://paulbourke.net/dataformats/mtl/): // d is dissolve for current material // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent) if ( this.options && this.options.invertTransparency ) { value = 1 - value; } break; default: break; } if ( save ) { covmat[ lprop ] = value; } } } return converted; }, preload: function () { for ( var mn in this.materialsInfo ) { this.create( mn ); } }, getIndex: function( materialName ) { return this.nameLookup[ materialName ]; }, getAsArray: function() { var index = 0; for ( var mn in this.materialsInfo ) { this.materialsArray[ index ] = this.create( mn ); this.nameLookup[ mn ] = index; index ++; } return this.materialsArray; }, create: function ( materialName ) { if ( this.materials[ materialName ] === undefined ) { this.createMaterial_( materialName ); } return this.materials[ materialName ]; }, createMaterial_: function ( materialName ) { // Create material var mat = this.materialsInfo[ materialName ]; var params = { name: materialName, side: this.side }; for ( var prop in mat ) { var value = mat[ prop ]; switch ( prop.toLowerCase() ) { // Ns is material specular exponent case 'kd': // Diffuse color (color under white light) using RGB values params[ 'diffuse' ] = new THREE.Color().fromArray( value ); break; case 'ka': // Ambient color (color under shadow) using RGB values params[ 'ambient' ] = new THREE.Color().fromArray( value ); break; case 'ks': // Specular color (color when light is reflected from shiny surface) using RGB values params[ 'specular' ] = new THREE.Color().fromArray( value ); break; case 'map_kd': // Diffuse texture map params[ 'map' ] = this.loadTexture( this.baseUrl + value ); params[ 'map' ].wrapS = this.wrap; params[ 'map' ].wrapT = this.wrap; break; case 'ns': // The specular exponent (defines the focus of the specular highlight) // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000. params['shininess'] = value; break; case 'd': // According to MTL format (http://paulbourke.net/dataformats/mtl/): // d is dissolve for current material // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent) if ( value < 1 ) { params['transparent'] = true; params['opacity'] = value; } break; default: break; } } if ( params[ 'diffuse' ] ) { if ( !params[ 'ambient' ]) params[ 'ambient' ] = params[ 'diffuse' ]; params[ 'color' ] = params[ 'diffuse' ]; } this.materials[ materialName ] = new THREE.MeshPhongMaterial( params ); return this.materials[ materialName ]; }, loadTexture: function ( url, mapping, onLoad, onError ) { var isCompressed = /\.dds$/i.test( url ); if ( isCompressed ) { var texture = THREE.ImageUtils.loadCompressedTexture( url, mapping, onLoad, onError ); } else { var image = new Image(); var texture = new THREE.Texture( image, mapping ); var loader = new THREE.ImageLoader(); loader.crossOrigin = this.crossOrigin; loader.load( url, function ( image ) { texture.image = THREE.MTLLoader.ensurePowerOfTwo_( image ); texture.needsUpdate = true; if ( onLoad ) onLoad( texture ); } ); } return texture; } }; THREE.MTLLoader.ensurePowerOfTwo_ = function ( image ) { if ( ! THREE.Math.isPowerOfTwo( image.width ) || ! THREE.Math.isPowerOfTwo( image.height ) ) { var canvas = document.createElement( "canvas" ); canvas.width = THREE.MTLLoader.nextHighestPowerOfTwo_( image.width ); canvas.height = THREE.MTLLoader.nextHighestPowerOfTwo_( image.height ); var ctx = canvas.getContext("2d"); ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height ); return canvas; } return image; }; THREE.MTLLoader.nextHighestPowerOfTwo_ = function( x ) { --x; for ( var i = 1; i < 32; i <<= 1 ) { x = x | x >> i; } return x + 1; }; THREE.EventDispatcher.prototype.apply( THREE.MTLLoader.prototype );
JavaScript
/** * @author mrdoob / http://mrdoob.com/ */ THREE.VTKLoader = function () {}; THREE.VTKLoader.prototype = { constructor: THREE.VTKLoader, load: function ( url, callback ) { var scope = this; var request = new XMLHttpRequest(); request.addEventListener( 'load', function ( event ) { var geometry = scope.parse( event.target.responseText ); scope.dispatchEvent( { type: 'load', content: geometry } ); if ( callback ) callback( geometry ); }, false ); request.addEventListener( 'progress', function ( event ) { scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } ); }, false ); request.addEventListener( 'error', function () { scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } ); }, false ); request.open( 'GET', url, true ); request.send( null ); }, parse: function ( data ) { var geometry = new THREE.Geometry(); var vertex = function ( x, y, z ) { geometry.vertices.push( new THREE.Vector3( x, y, z ) ); } var face3 = function ( a, b, c ) { geometry.faces.push( new THREE.Face3( a, b, c ) ); } var pattern, result; // float float float pattern = /([\+|\-]?[\d]+[\.][\d|\-|e]+)[ ]+([\+|\-]?[\d]+[\.][\d|\-|e]+)[ ]+([\+|\-]?[\d]+[\.][\d|\-|e]+)/g; while ( ( result = pattern.exec( data ) ) !== null ) { // ["1.0 2.0 3.0", "1.0", "2.0", "3.0"] vertex( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) ); } // 3 int int int pattern = /3[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)/g; while ( ( result = pattern.exec( data ) ) !== null ) { // ["3 1 2 3", "1", "2", "3"] face3( parseInt( result[ 1 ] ), parseInt( result[ 2 ] ), parseInt( result[ 3 ] ) ); } // 4 int int int int pattern = /4[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)[ ]+([\d]+)/g; while ( ( result = pattern.exec( data ) ) !== null ) { // ["4 1 2 3 4", "1", "2", "3", "4"] face3( parseInt( result[ 1 ] ), parseInt( result[ 2 ] ), parseInt( result[ 4 ] ) ); face3( parseInt( result[ 2 ] ), parseInt( result[ 3 ] ), parseInt( result[ 4 ] ) ); } geometry.computeCentroids(); geometry.computeFaceNormals(); geometry.computeVertexNormals(); geometry.computeBoundingSphere(); return geometry; } }; THREE.EventDispatcher.prototype.apply( THREE.VTKLoader.prototype );
JavaScript
// Copyright (c) 2013 Fabrice Robinet // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* The Abstract Loader has two modes: #1: [static] load all the JSON at once [as of now] #2: [stream] stream and parse JSON progressively [not yet supported] Whatever is the mechanism used to parse the JSON (#1 or #2), The loader starts by resolving the paths to binaries and referenced json files (by replace the value of the path property with an absolute path if it was relative). In case #1: it is guaranteed to call the concrete loader implementation methods in a order that solves the dependencies between the entries. only the nodes requires an extra pass to set up the hirerarchy. In case #2: the concrete implementation will have to solve the dependencies. no order is guaranteed. When case #1 is used the followed dependency order is: scenes -> nodes -> meshes -> materials -> techniques -> shaders -> buffers -> cameras -> lights The readers starts with the leafs, i.e: shaders, techniques, materials, meshes, buffers, cameras, lights, nodes, scenes For each called handle method called the client should return true if the next handle can be call right after returning, or false if a callback on client side will notify the loader that the next handle method can be called. */ var global = window; (function (root, factory) { if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. factory(module.exports); } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], function () { return factory(root); }); } else { // Browser globals factory(root); } }(this, function (root) { "use strict"; var categoriesDepsOrder = ["buffers", "bufferViews", "images", "videos", "samplers", "textures", "shaders", "programs", "techniques", "materials", "accessors", "meshes", "cameras", "lights", "skins", "nodes", "scenes", "animations"]; var glTFParser = Object.create(Object.prototype, { _rootDescription: { value: null, writable: true }, rootDescription: { set: function(value) { this._rootDescription = value; }, get: function() { return this._rootDescription; } }, baseURL: { value: null, writable: true }, //detect absolute path following the same protocol than window.location _isAbsolutePath: { value: function(path) { var isAbsolutePathRegExp = new RegExp("^"+window.location.protocol, "i"); return path.match(isAbsolutePathRegExp) ? true : false; } }, resolvePathIfNeeded: { value: function(path) { if (this._isAbsolutePath(path)) { return path; } return this.baseURL + path; } }, _resolvePathsForCategories: { value: function(categories) { categories.forEach( function(category) { var descriptions = this.json[category]; if (descriptions) { var descriptionKeys = Object.keys(descriptions); descriptionKeys.forEach( function(descriptionKey) { var description = descriptions[descriptionKey]; description.path = this.resolvePathIfNeeded(description.path); }, this); } }, this); } }, _json: { value: null, writable: true }, json: { enumerable: true, get: function() { return this._json; }, set: function(value) { if (this._json !== value) { this._json = value; this._resolvePathsForCategories(["buffers", "shaders", "images", "videos"]); } } }, _path: { value: null, writable: true }, getEntryDescription: { value: function (entryID, entryType) { var entries = null; var category = entryType; entries = this.rootDescription[category]; if (!entries) { console.log("ERROR:CANNOT find expected category named:"+category); return null; } return entries ? entries[entryID] : null; } }, _stepToNextCategory: { value: function() { this._state.categoryIndex = this.getNextCategoryIndex(this._state.categoryIndex + 1); if (this._state.categoryIndex !== -1) { this._state.categoryState.index = 0; return true; } return false; } }, _stepToNextDescription: { enumerable: false, value: function() { var categoryState = this._state.categoryState; var keys = categoryState.keys; if (!keys) { console.log("INCONSISTENCY ERROR"); return false; } categoryState.index++; categoryState.keys = null; if (categoryState.index >= keys.length) { return this._stepToNextCategory(); } return false; } }, hasCategory: { value: function(category) { return this.rootDescription[category] ? true : false; } }, _handleState: { value: function() { var methodForType = { "buffers" : this.handleBuffer, "bufferViews" : this.handleBufferView, "shaders" : this.handleShader, "programs" : this.handleProgram, "techniques" : this.handleTechnique, "materials" : this.handleMaterial, "meshes" : this.handleMesh, "cameras" : this.handleCamera, "lights" : this.handleLight, "nodes" : this.handleNode, "scenes" : this.handleScene, "images" : this.handleImage, "animations" : this.handleAnimation, "accessors" : this.handleAccessor, "skins" : this.handleSkin, "samplers" : this.handleSampler, "textures" : this.handleTexture, "videos" : this.handleVideo }; var success = true; while (this._state.categoryIndex !== -1) { var category = categoriesDepsOrder[this._state.categoryIndex]; var categoryState = this._state.categoryState; var keys = categoryState.keys; if (!keys) { categoryState.keys = keys = Object.keys(this.rootDescription[category]); if (keys) { if (keys.length == 0) { this._stepToNextDescription(); continue; } } } var type = category; var entryID = keys[categoryState.index]; var description = this.getEntryDescription(entryID, type); if (!description) { if (this.handleError) { this.handleError("INCONSISTENCY ERROR: no description found for entry "+entryID); success = false; break; } } else { if (methodForType[type]) { if (methodForType[type].call(this, entryID, description, this._state.userInfo) === false) { success = false; break; } } this._stepToNextDescription(); } } if (this.handleLoadCompleted) { this.handleLoadCompleted(success); } } }, _loadJSONIfNeeded: { enumerable: true, value: function(callback) { var self = this; //FIXME: handle error if (!this._json) { var jsonPath = this._path; var i = jsonPath.lastIndexOf("/"); this.baseURL = (i !== 0) ? jsonPath.substring(0, i + 1) : ''; var jsonfile = new XMLHttpRequest(); jsonfile.open("GET", jsonPath, true); jsonfile.addEventListener( 'load', function ( event ) { self.json = JSON.parse(jsonfile.responseText); if (callback) { callback(self.json); } }, false ); jsonfile.send(null); } else { if (callback) { callback(this.json); } } } }, /* load JSON and assign it as description to the reader */ _buildLoader: { value: function(callback) { var self = this; function JSONReady(json) { self.rootDescription = json; if (callback) callback(this); } this._loadJSONIfNeeded(JSONReady); } }, _state: { value: null, writable: true }, _getEntryType: { value: function(entryID) { var rootKeys = categoriesDepsOrder; for (var i = 0 ; i < rootKeys.length ; i++) { var rootValues = this.rootDescription[rootKeys[i]]; if (rootValues) { return rootKeys[i]; } } return null; } }, getNextCategoryIndex: { value: function(currentIndex) { for (var i = currentIndex ; i < categoriesDepsOrder.length ; i++) { if (this.hasCategory(categoriesDepsOrder[i])) { return i; } } return -1; } }, load: { enumerable: true, value: function(userInfo, options) { var self = this; this._buildLoader(function loaderReady(reader) { var startCategory = self.getNextCategoryIndex.call(self,0); if (startCategory !== -1) { self._state = { "userInfo" : userInfo, "options" : options, "categoryIndex" : startCategory, "categoryState" : { "index" : "0" } }; self._handleState(); } }); } }, initWithPath: { value: function(path) { this._path = path; this._json = null; return this; } }, //this is meant to be global and common for all instances _knownURLs: { writable: true, value: {} }, //to be invoked by subclass, so that ids can be ensured to not overlap loaderContext: { value: function() { if (typeof this._knownURLs[this._path] === "undefined") { this._knownURLs[this._path] = Object.keys(this._knownURLs).length; } return "__" + this._knownURLs[this._path]; } }, initWithJSON: { value: function(json, baseURL) { this.json = json; this.baseURL = baseURL; if (!baseURL) { console.log("WARNING: no base URL passed to Reader:initWithJSON"); } return this; } } }); if(root) { root.glTFParser = glTFParser; } return glTFParser; }));
JavaScript
/** * @author Tony Parisi / http://www.tonyparisi.com/ */ THREE.GLTFLoaderUtils = Object.create(Object, { // errors MISSING_DESCRIPTION: { value: "MISSING_DESCRIPTION" }, INVALID_PATH: { value: "INVALID_PATH" }, INVALID_TYPE: { value: "INVALID_TYPE" }, XMLHTTPREQUEST_STATUS_ERROR: { value: "XMLHTTPREQUEST_STATUS_ERROR" }, NOT_FOUND: { value: "NOT_FOUND" }, // misc constants ARRAY_BUFFER: { value: "ArrayBuffer" }, _streams : { value:{}, writable: true }, _streamsStatus: { value: {}, writable: true }, _resources: { value: {}, writable: true }, _resourcesStatus: { value: {}, writable: true }, // initialization init: { value: function() { this._streams = {}; this._streamsStatus = {}; this._resources = {}; this._resourcesStatus = {}; } }, //manage entries _containsResource: { enumerable: false, value: function(resourceID) { return this._resources[resourceID] ? true : false; } }, _storeResource: { enumerable: false, value: function(resourceID, resource) { if (!resourceID) { console.log("ERROR: entry does not contain id, cannot store"); return; } if (this._containsResource[resourceID]) { console.log("WARNING: resource:"+resourceID+" is already stored, overriding"); } this._resources[resourceID] = resource; } }, _getResource: { enumerable: false, value: function(resourceID) { return this._resources[resourceID]; } }, _loadStream: { value: function(path, type, delegate) { var self = this; if (!type) { delegate.handleError(THREE.GLTFLoaderUtils.INVALID_TYPE, null); return; } if (!path) { delegate.handleError(THREE.GLTFLoaderUtils.INVALID_PATH); return; } var xhr = new XMLHttpRequest(); xhr.open('GET', path, true); xhr.responseType = (type === this.ARRAY_BUFFER) ? "arraybuffer" : "text"; //if this is not specified, 1 "big blob" scenes fails to load. xhr.setRequestHeader("If-Modified-Since", "Sat, 01 Jan 1970 00:00:00 GMT"); xhr.addEventListener( 'load', function ( event ) { delegate.streamAvailable(path, xhr.response); }, false ); xhr.addEventListener( 'error', function ( event ) { delegate.handleError(THREE.GLTFLoaderUtils.XMLHTTPREQUEST_STATUS_ERROR, xhr.status); }, false ); xhr.send(null); } }, send: { value: 0, writable: true }, requested: { value: 0, writable: true }, _handleRequest: { value: function(request) { var resourceStatus = this._resourcesStatus[request.id]; if (resourceStatus) { this._resourcesStatus[request.id]++; } else { this._resourcesStatus[request.id] = 1; } var streamStatus = this._streamsStatus[request.path]; if (streamStatus && streamStatus.status === "loading" ) { streamStatus.requests.push(request); return; } this._streamsStatus[request.path] = { status : "loading", requests : [request] }; var self = this; var processResourceDelegate = {}; processResourceDelegate.streamAvailable = function(path, res_) { var streamStatus = self._streamsStatus[path]; var requests = streamStatus.requests; requests.forEach( function(req_) { var subArray = res_.slice(req_.range[0], req_.range[1]); var convertedResource = req_.delegate.convert(subArray, req_.ctx); self._storeResource(req_.id, convertedResource); req_.delegate.resourceAvailable(convertedResource, req_.ctx); --self._resourcesStatus[req_.id]; }, this); delete self._streamsStatus[path]; }; processResourceDelegate.handleError = function(errorCode, info) { request.delegate.handleError(errorCode, info); } this._loadStream(request.path, request.type, processResourceDelegate); } }, _elementSizeForGLType: { value: function(glType) { switch (glType) { case WebGLRenderingContext.FLOAT : return Float32Array.BYTES_PER_ELEMENT; case WebGLRenderingContext.UNSIGNED_BYTE : return Uint8Array.BYTES_PER_ELEMENT; case WebGLRenderingContext.UNSIGNED_SHORT : return Uint16Array.BYTES_PER_ELEMENT; case WebGLRenderingContext.FLOAT_VEC2 : return Float32Array.BYTES_PER_ELEMENT * 2; case WebGLRenderingContext.FLOAT_VEC3 : return Float32Array.BYTES_PER_ELEMENT * 3; case WebGLRenderingContext.FLOAT_VEC4 : return Float32Array.BYTES_PER_ELEMENT * 4; case WebGLRenderingContext.FLOAT_MAT3 : return Float32Array.BYTES_PER_ELEMENT * 9; case WebGLRenderingContext.FLOAT_MAT4 : return Float32Array.BYTES_PER_ELEMENT * 16; default: return null; } } }, _handleWrappedBufferViewResourceLoading: { value: function(wrappedBufferView, delegate, ctx) { var bufferView = wrappedBufferView.bufferView; var buffer = bufferView.buffer; var byteOffset = wrappedBufferView.byteOffset + bufferView.description.byteOffset; var range = [byteOffset , (this._elementSizeForGLType(wrappedBufferView.type) * wrappedBufferView.count) + byteOffset]; this._handleRequest({ "id" : wrappedBufferView.id, "range" : range, "type" : buffer.description.type, "path" : buffer.description.path, "delegate" : delegate, "ctx" : ctx }, null); } }, getBuffer: { value: function(wrappedBufferView, delegate, ctx) { var savedBuffer = this._getResource(wrappedBufferView.id); if (savedBuffer) { return savedBuffer; } else { this._handleWrappedBufferViewResourceLoading(wrappedBufferView, delegate, ctx); } return null; } }, getFile: { value: function(request, delegate, ctx) { request.delegate = delegate; request.ctx = ctx; this._handleRequest({ "id" : request.id, "path" : request.path, "range" : [0], "type" : "text", "delegate" : delegate, "ctx" : ctx }, null); return null; } }, });
JavaScript
/** * @author Tony Parisi / http://www.tonyparisi.com/ */ THREE.glTFAnimator = ( function () { var animators = []; return { add : function(animator) { animators.push(animator); }, remove: function(animator) { var i = animators.indexOf(animator); if ( i !== -1 ) { animators.splice( i, 1 ); } }, update : function() { for (i = 0; i < animators.length; i++) { animators[i].update(); } }, }; })(); // Construction/initialization THREE.glTFAnimation = function(interps) { this.running = false; this.loop = false; this.duration = 0; this.startTime = 0; this.interps = []; if (interps) { this.createInterpolators(interps); } } THREE.glTFAnimation.prototype.createInterpolators = function(interps) { var i, len = interps.length; for (i = 0; i < len; i++) { var interp = new THREE.glTFInterpolator(interps[i]); this.interps.push(interp); this.duration = Math.max(this.duration, interp.duration); } } // Start/stop THREE.glTFAnimation.prototype.play = function() { if (this.running) return; this.startTime = Date.now(); this.running = true; THREE.glTFAnimator.add(this); } THREE.glTFAnimation.prototype.stop = function() { this.running = false; THREE.glTFAnimator.remove(this); } // Update - drive key frame evaluation THREE.glTFAnimation.prototype.update = function() { if (!this.running) return; var now = Date.now(); var deltat = (now - this.startTime) / 1000; var t = deltat % this.duration; var nCycles = Math.floor(deltat / this.duration); if (nCycles >= 1 && !this.loop) { this.running = false; var i, len = this.interps.length; for (i = 0; i < len; i++) { this.interps[i].interp(this.duration); } this.stop(); return; } else { var i, len = this.interps.length; for (i = 0; i < len; i++) { this.interps[i].interp(t); } } } //Interpolator class //Construction/initialization THREE.glTFInterpolator = function(param) { this.keys = param.keys; this.values = param.values; this.count = param.count; this.type = param.type; this.path = param.path; this.isRot = false; var node = param.target; node.updateMatrix(); node.matrixAutoUpdate = true; this.targetNode = node; switch (param.path) { case "translation" : this.target = node.position; this.originalValue = node.position.clone(); break; case "rotation" : this.target = node.quaternion; this.originalValue = node.quaternion.clone(); this.isRot = true; break; case "scale" : this.target = node.scale; this.originalValue = node.scale.clone(); break; } this.duration = this.keys[this.count - 1]; this.vec1 = new THREE.Vector3; this.vec2 = new THREE.Vector3; this.vec3 = new THREE.Vector3; this.quat1 = new THREE.Quaternion; this.quat2 = new THREE.Quaternion; this.quat3 = new THREE.Quaternion; } //Interpolation and tweening methods THREE.glTFInterpolator.prototype.interp = function(t) { var i, j; if (t == this.keys[0]) { if (this.isRot) { this.quat3.set(this.values[0], this.values[1], this.values[2], this.values[3]); } else { this.vec3.set(this.values[0], this.values[1], this.values[2]); } } else if (t < this.keys[0]) { if (this.isRot) { this.quat1.set(this.originalValue.x, this.originalValue.y, this.originalValue.z, this.originalValue.w); this.quat2.set(this.values[0], this.values[1], this.values[2], this.values[3]); THREE.Quaternion.slerp(this.quat1, this.quat2, this.quat3, t / this.keys[0]); } else { this.vec3.set(this.originalValue.x, this.originalValue.y, this.originalValue.z); this.vec2.set(this.values[0], this.values[1], this.values[2]); this.vec3.lerp(this.vec2, t / this.keys[0]); } } else if (t >= this.keys[this.count - 1]) { if (this.isRot) { this.quat3.set(this.values[(this.count - 1) * 4], this.values[(this.count - 1) * 4 + 1], this.values[(this.count - 1) * 4 + 2], this.values[(this.count - 1) * 4 + 3]); } else { this.vec3.set(this.values[(this.count - 1) * 3], this.values[(this.count - 1) * 3 + 1], this.values[(this.count - 1) * 3 + 2]); } } else { for (i = 0; i < this.count - 1; i++) { var key1 = this.keys[i]; var key2 = this.keys[i + 1]; if (t >= key1 && t <= key2) { if (this.isRot) { this.quat1.set(this.values[i * 4], this.values[i * 4 + 1], this.values[i * 4 + 2], this.values[i * 4 + 3]); this.quat2.set(this.values[(i + 1) * 4], this.values[(i + 1) * 4 + 1], this.values[(i + 1) * 4 + 2], this.values[(i + 1) * 4 + 3]); THREE.Quaternion.slerp(this.quat1, this.quat2, this.quat3, (t - key1) / (key2 - key1)); } else { this.vec3.set(this.values[i * 3], this.values[i * 3 + 1], this.values[i * 3 + 2]); this.vec2.set(this.values[(i + 1) * 3], this.values[(i + 1) * 3 + 1], this.values[(i + 1) * 3 + 2]); this.vec3.lerp(this.vec2, (t - key1) / (key2 - key1)); } } } } if (this.target) { this.copyValue(this.target); } } THREE.glTFInterpolator.prototype.copyValue = function(target) { if (this.isRot) { target.copy(this.quat3); } else { target.copy(this.vec3); } }
JavaScript
/** * @author Tony Parisi / http://www.tonyparisi.com/ */ THREE.glTFLoader = function (showStatus) { this.useBufferGeometry = (THREE.glTFLoader.useBufferGeometry !== undefined ) ? THREE.glTFLoader.useBufferGeometry : true; this.meshesRequested = 0; this.meshesLoaded = 0; this.pendingMeshes = []; this.animationsRequested = 0; this.animationsLoaded = 0; this.animations = []; this.shadersRequested = 0; this.shadersLoaded = 0; this.shaders = {}; THREE.Loader.call( this, showStatus ); } THREE.glTFLoader.prototype = new THREE.Loader(); THREE.glTFLoader.prototype.constructor = THREE.glTFLoader; THREE.glTFLoader.prototype.load = function( url, callback ) { var theLoader = this; // Utilities function RgbArraytoHex(colorArray) { if(!colorArray) return 0xFFFFFFFF; var r = Math.floor(colorArray[0] * 255), g = Math.floor(colorArray[1] * 255), b = Math.floor(colorArray[2] * 255), a = 255; var color = (a << 24) + (r << 16) + (g << 8) + b; return color; } function convertAxisAngleToQuaternion(rotations, count) { var q = new THREE.Quaternion; var axis = new THREE.Vector3; var euler = new THREE.Vector3; var i; for (i = 0; i < count; i++) { axis.set(rotations[i * 4], rotations[i * 4 + 1], rotations[i * 4 + 2]).normalize(); var angle = rotations[i * 4 + 3]; q.setFromAxisAngle(axis, angle); rotations[i * 4] = q.x; rotations[i * 4 + 1] = q.y; rotations[i * 4 + 2] = q.z; rotations[i * 4 + 3] = q.w; } } function componentsPerElementForGLType(glType) { switch (glType) { case WebGLRenderingContext.FLOAT : case WebGLRenderingContext.UNSIGNED_BYTE : case WebGLRenderingContext.UNSIGNED_SHORT : return 1; case WebGLRenderingContext.FLOAT_VEC2 : return 2; case WebGLRenderingContext.FLOAT_VEC3 : return 3; case WebGLRenderingContext.FLOAT_VEC4 : return 4; case WebGLRenderingContext.FLOAT_MAT4 : return 16; default: return null; } } function LoadTexture(src) { if(!src) { return null; } return THREE.ImageUtils.loadTexture(src); } // Geometry processing var ClassicGeometry = function() { if (theLoader.useBufferGeometry) { this.geometry = new THREE.BufferGeometry; } else { this.geometry = new THREE.Geometry; } this.totalAttributes = 0; this.loadedAttributes = 0; this.indicesLoaded = false; this.finished = false; this.onload = null; this.uvs = null; this.indexArray = null; }; ClassicGeometry.prototype.constructor = ClassicGeometry; ClassicGeometry.prototype.buildArrayGeometry = function() { // Build indexed mesh var geometry = this.geometry; var normals = geometry.normals; var indexArray = this.indexArray; var uvs = this.uvs; var a, b, c; var i, l; var faceNormals = null; var faceTexcoords = null; for(i = 0, l = this.indexArray.length; i < l; i += 3) { a = indexArray[i]; b = indexArray[i+1]; c = indexArray[i+2]; if(normals) { faceNormals = [normals[a], normals[b], normals[c]]; } geometry.faces.push( new THREE.Face3( a, b, c, faceNormals, null, null ) ); if(uvs) { geometry.faceVertexUvs[0].push([ uvs[a], uvs[b], uvs[c] ]); } } // Allow Three.js to calculate some values for us geometry.computeBoundingBox(); geometry.computeBoundingSphere(); geometry.computeCentroids(); geometry.computeFaceNormals(); if(!normals) { geometry.computeVertexNormals(); } } ClassicGeometry.prototype.buildBufferGeometry = function() { // Build indexed mesh var geometry = this.geometry; geometry.attributes.index = { itemSize: 1, array : this.indexArray }; var offset = { start: 0, index: 0, count: this.indexArray.length }; geometry.offsets.push( offset ); geometry.computeBoundingSphere(); } ClassicGeometry.prototype.checkFinished = function() { if(this.indexArray && this.loadedAttributes === this.totalAttributes) { if (theLoader.useBufferGeometry) { this.buildBufferGeometry(); } else { this.buildArrayGeometry(); } this.finished = true; if(this.onload) { this.onload(); } } }; // Delegate for processing index buffers var IndicesDelegate = function() {}; IndicesDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error console.log("ERROR(IndicesDelegate):"+errorCode+":"+info); }; IndicesDelegate.prototype.convert = function(resource, ctx) { return new Uint16Array(resource, 0, ctx.indices.count); }; IndicesDelegate.prototype.resourceAvailable = function(glResource, ctx) { var geometry = ctx.geometry; geometry.indexArray = glResource; geometry.checkFinished(); return true; }; var indicesDelegate = new IndicesDelegate(); var IndicesContext = function(indices, geometry) { this.indices = indices; this.geometry = geometry; }; // Delegate for processing vertex attribute buffers var VertexAttributeDelegate = function() {}; VertexAttributeDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error console.log("ERROR(VertexAttributeDelegate):"+errorCode+":"+info); }; VertexAttributeDelegate.prototype.convert = function(resource, ctx) { return resource; }; VertexAttributeDelegate.prototype.arrayResourceAvailable = function(glResource, ctx) { var geom = ctx.geometry; var attribute = ctx.attribute; var semantic = ctx.semantic; var floatArray; var i, l; //FIXME: Float32 is assumed here, but should be checked. if(semantic == "POSITION") { // TODO: Should be easy to take strides into account here floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); for(i = 0, l = floatArray.length; i < l; i += 3) { geom.geometry.vertices.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) ); } } else if(semantic == "NORMAL") { geom.geometry.normals = []; floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); for(i = 0, l = floatArray.length; i < l; i += 3) { geom.geometry.normals.push( new THREE.Vector3( floatArray[i], floatArray[i+1], floatArray[i+2] ) ); } } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { geom.uvs = []; floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); for(i = 0, l = floatArray.length; i < l; i += 2) { geom.uvs.push( new THREE.Vector2( floatArray[i], 1.0 - floatArray[i+1] ) ); } } else if (semantic == "WEIGHT") { nComponents = componentsPerElementForGLType(attribute.type); floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); for(i = 0, l = floatArray.length; i < l; i += 4) { geom.geometry.skinWeights.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) ); } } else if (semantic == "JOINT") { nComponents = componentsPerElementForGLType(attribute.type); floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); for(i = 0, l = floatArray.length; i < l; i += 4) { geom.geometry.skinIndices.push( new THREE.Vector4( floatArray[i], floatArray[i+1], floatArray[i+2], floatArray[i+3] ) ); } } } VertexAttributeDelegate.prototype.bufferResourceAvailable = function(glResource, ctx) { var geom = ctx.geometry; var attribute = ctx.attribute; var semantic = ctx.semantic; var floatArray; var i, l; var nComponents; //FIXME: Float32 is assumed here, but should be checked. if(semantic == "POSITION") { // TODO: Should be easy to take strides into account here floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); geom.geometry.attributes.position = { itemSize: 3, array : floatArray }; } else if(semantic == "NORMAL") { floatArray = new Float32Array(glResource, 0, attribute.count * componentsPerElementForGLType(attribute.type)); geom.geometry.attributes.normal = { itemSize: 3, array : floatArray }; } else if ((semantic == "TEXCOORD_0") || (semantic == "TEXCOORD" )) { nComponents = componentsPerElementForGLType(attribute.type); floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); // N.B.: flip Y value... should we just set texture.flipY everywhere? for (i = 0; i < floatArray.length / 2; i++) { floatArray[i*2+1] = 1.0 - floatArray[i*2+1]; } geom.geometry.attributes.uv = { itemSize: nComponents, array : floatArray }; } else if (semantic == "WEIGHT") { nComponents = componentsPerElementForGLType(attribute.type); floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); geom.geometry.attributes.skinWeight = { itemSize: nComponents, array : floatArray }; } else if (semantic == "JOINT") { nComponents = componentsPerElementForGLType(attribute.type); floatArray = new Float32Array(glResource, 0, attribute.count * nComponents); geom.geometry.attributes.skinIndex = { itemSize: nComponents, array : floatArray }; } } VertexAttributeDelegate.prototype.resourceAvailable = function(glResource, ctx) { if (theLoader.useBufferGeometry) { this.bufferResourceAvailable(glResource, ctx); } else { this.arrayResourceAvailable(glResource, ctx); } var geom = ctx.geometry; geom.loadedAttributes++; geom.checkFinished(); return true; }; var vertexAttributeDelegate = new VertexAttributeDelegate(); var VertexAttributeContext = function(attribute, semantic, geometry) { this.attribute = attribute; this.semantic = semantic; this.geometry = geometry; }; var Mesh = function() { this.primitives = []; this.materialsPending = []; this.loadedGeometry = 0; this.onCompleteCallbacks = []; }; Mesh.prototype.addPrimitive = function(geometry, material) { var self = this; geometry.onload = function() { self.loadedGeometry++; self.checkComplete(); }; this.primitives.push({ geometry: geometry, material: material, mesh: null }); }; Mesh.prototype.onComplete = function(callback) { this.onCompleteCallbacks.push(callback); this.checkComplete(); }; Mesh.prototype.checkComplete = function() { var self = this; if(this.onCompleteCallbacks.length && this.primitives.length == this.loadedGeometry) { this.onCompleteCallbacks.forEach(function(callback) { callback(self); }); this.onCompleteCallbacks = []; } }; Mesh.prototype.attachToNode = function(threeNode) { // Assumes that the geometry is complete this.primitives.forEach(function(primitive) { /*if(!primitive.mesh) { primitive.mesh = new THREE.Mesh(primitive.geometry, primitive.material); }*/ var material = primitive.material; if (!(material instanceof THREE.Material)) { material = theLoader.createShaderMaterial(material); } var threeMesh = new THREE.Mesh(primitive.geometry.geometry, material); threeMesh.castShadow = true; threeNode.add(threeMesh); }); }; // Delayed-loaded material var Material = function(params) { this.params = params; }; // Delegate for processing animation parameter buffers var AnimationParameterDelegate = function() {}; AnimationParameterDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error console.log("ERROR(AnimationParameterDelegate):"+errorCode+":"+info); }; AnimationParameterDelegate.prototype.convert = function(resource, ctx) { var parameter = ctx.parameter; var glResource = null; switch (parameter.type) { case WebGLRenderingContext.FLOAT : case WebGLRenderingContext.FLOAT_VEC2 : case WebGLRenderingContext.FLOAT_VEC3 : case WebGLRenderingContext.FLOAT_VEC4 : glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); break; default: break; } return glResource; }; AnimationParameterDelegate.prototype.resourceAvailable = function(glResource, ctx) { var animation = ctx.animation; var parameter = ctx.parameter; parameter.data = glResource; animation.handleParameterLoaded(parameter); return true; }; var animationParameterDelegate = new AnimationParameterDelegate(); var AnimationParameterContext = function(parameter, animation) { this.parameter = parameter; this.animation = animation; }; // Animations var Animation = function() { // create Three.js keyframe here this.totalParameters = 0; this.loadedParameters = 0; this.parameters = {}; this.finishedLoading = false; this.onload = null; }; Animation.prototype.constructor = Animation; Animation.prototype.handleParameterLoaded = function(parameter) { this.parameters[parameter.name] = parameter; this.loadedParameters++; this.checkFinished(); }; Animation.prototype.checkFinished = function() { if(this.loadedParameters === this.totalParameters) { // Build animation this.finishedLoading = true; if (this.onload) { this.onload(); } } }; // Delegate for processing inverse bind matrices buffer var InverseBindMatricesDelegate = function() {}; InverseBindMatricesDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error console.log("ERROR(InverseBindMatricesDelegate):"+errorCode+":"+info); }; InverseBindMatricesDelegate.prototype.convert = function(resource, ctx) { var parameter = ctx.parameter; var glResource = null; switch (parameter.type) { case WebGLRenderingContext.FLOAT_MAT4 : glResource = new Float32Array(resource, 0, parameter.count * componentsPerElementForGLType(parameter.type)); break; default: break; } return glResource; }; InverseBindMatricesDelegate.prototype.resourceAvailable = function(glResource, ctx) { var skin = ctx.skin; skin.inverseBindMatrices = glResource; return true; }; var inverseBindMatricesDelegate = new InverseBindMatricesDelegate(); var InverseBindMatricesContext = function(param, skin) { this.parameter = param; this.skin = skin; }; // Delegate for processing shaders from external files var ShaderDelegate = function() {}; ShaderDelegate.prototype.handleError = function(errorCode, info) { // FIXME: report error console.log("ERROR(ShaderDelegate):"+errorCode+":"+info); }; ShaderDelegate.prototype.convert = function(resource, ctx) { return resource; } ShaderDelegate.prototype.resourceAvailable = function(data, ctx) { theLoader.shadersLoaded++; theLoader.shaders[ctx.id] = data; return true; }; var shaderDelegate = new ShaderDelegate(); var ShaderContext = function(id, path) { this.id = id; this.path = path; }; // Resource management var ResourceEntry = function(entryID, object, description) { this.entryID = entryID; this.object = object; this.description = description; }; var Resources = function() { this._entries = {}; }; Resources.prototype.setEntry = function(entryID, object, description) { if (!entryID) { console.error("No EntryID provided, cannot store", description); return; } if (this._entries[entryID]) { console.warn("entry["+entryID+"] is being overwritten"); } this._entries[entryID] = new ResourceEntry(entryID, object, description ); }; Resources.prototype.getEntry = function(entryID) { return this._entries[entryID]; }; Resources.prototype.clearEntries = function() { this._entries = {}; }; LoadDelegate = function() { } LoadDelegate.prototype.loadCompleted = function(callback, obj) { callback.call(Window, obj); } // Loader var ThreeGLTFLoader = Object.create(glTFParser, { load: { enumerable: true, value: function(userInfo, options) { this.resources = new Resources(); this.cameras = []; this.lights = []; this.animations = []; this.joints = {}; this.skeltons = {}; THREE.GLTFLoaderUtils.init(); glTFParser.load.call(this, userInfo, options); } }, cameras: { enumerable: true, writable: true, value : [] }, lights: { enumerable: true, writable: true, value : [] }, animations: { enumerable: true, writable: true, value : [] }, // Implement WebGLTFLoader handlers handleBuffer: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); description.type = "ArrayBuffer"; return true; } }, handleBufferView: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); var buffer = this.resources.getEntry(description.buffer); description.type = "ArrayBufferView"; var bufferViewEntry = this.resources.getEntry(entryID); bufferViewEntry.buffer = buffer; return true; } }, handleShader: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); var shaderRequest = { id : entryID, path : description.path, }; var shaderContext = new ShaderContext(entryID, description.path); theLoader.shadersRequested++; THREE.GLTFLoaderUtils.getFile(shaderRequest, shaderDelegate, shaderContext); return true; } }, handleProgram: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); return true; } }, handleTechnique: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); return true; } }, createShaderMaterial : { value: function(material) { var fragmentShader = theLoader.shaders[material.params.fragmentShader]; if (!fragmentShader) { console.log("ERROR: Missing fragment shader definition:", material.params.fragmentShader); return new THREE.MeshPhongMaterial; } var vertexShader = theLoader.shaders[material.params.vertexShader]; if (!fragmentShader) { console.log("ERROR: Missing vertex shader definition:", material.params.vertexShader); return new THREE.MeshPhongMaterial; } var uniforms = {}; var shaderMaterial = new THREE.ShaderMaterial( { fragmentShader: fragmentShader, vertexShader: vertexShader, uniforms: uniforms, } ); return new THREE.MeshPhongMaterial(material.params); } }, createShaderParams : { value: function(materialId, values, params, instanceProgram) { var program = this.resources.getEntry(instanceProgram.program); if (program) { params.fragmentShader = program.description.fragmentShader; params.vertexShader = program.description.vertexShader; params.attributes = instanceProgram.attributes; params.uniforms = instanceProgram.uniforms; } } }, threeJSMaterialType : { value: function(materialId, technique, values, params) { var materialType = THREE.MeshPhongMaterial; var defaultPass = null; if (technique && technique.description && technique.description.passes) defaultPass = technique.description.passes.defaultPass; if (defaultPass) { if (defaultPass.details && defaultPass.details.commonProfile) { var profile = technique.description.passes.defaultPass.details.commonProfile; if (profile) { switch (profile.lightingModel) { case 'Blinn' : case 'Phong' : materialType = THREE.MeshPhongMaterial; break; case 'Lambert' : materialType = THREE.MeshLambertMaterial; break; default : materialType = THREE.MeshBasicMaterial; break; } if (profile.extras && profile.extras.doubleSided) { params.side = THREE.DoubleSide; } } } else if (defaultPass.instanceProgram) { var instanceProgram = defaultPass.instanceProgram; this.createShaderParams(materialId, values, params, instanceProgram); var loadshaders = true; if (loadshaders) { materialType = Material; } } } var texturePath = null; var textureParams = null; var diffuse = values.diffuse; if (diffuse) { var texture = diffuse; if (texture) { var textureEntry = this.resources.getEntry(texture); if (textureEntry) { { var imageEntry = this.resources.getEntry(textureEntry.description.source); if (imageEntry) { texturePath = imageEntry.description.path; } var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); if (samplerEntry) { textureParams = samplerEntry.description; } } } } } var texture = LoadTexture(texturePath); if (texture && textureParams) { if (textureParams.wrapS == WebGLRenderingContext.REPEAT) texture.wrapS = THREE.RepeatWrapping; if (textureParams.wrapT == WebGLRenderingContext.REPEAT) texture.wrapT = THREE.RepeatWrapping; if (textureParams.magFilter == WebGLRenderingContext.LINEAR) texture.magFilter = THREE.LinearFilter; // if (textureParams.minFilter == "LINEAR") // texture.minFilter = THREE.LinearFilter; params.map = texture; } var envMapPath = null; var envMapParams = null; var reflective = values.reflective; if (reflective) { var texture = reflective; if (texture) { var textureEntry = this.resources.getEntry(texture); if (textureEntry) { { var imageEntry = this.resources.getEntry(textureEntry.description.source); if (imageEntry) { envMapPath = imageEntry.description.path; } var samplerEntry = this.resources.getEntry(textureEntry.description.sampler); if (samplerEntry) { envMapParams = samplerEntry.description; } } } } } var texture = LoadTexture(envMapPath); if (texture && envMapParams) { if (envMapParams.wrapS == WebGLRenderingContext.REPEAT) texture.wrapS = THREE.RepeatWrapping; if (envMapParams.wrapT == WebGLRenderingContext.REPEAT) texture.wrapT = THREE.RepeatWrapping; if (envMapParams.magFilter == WebGLRenderingContext.LINEAR) texture.magFilter = THREE.LinearFilter; // if (envMapParams.minFilter == WebGLRenderingContext.LINEAR) // texture.minFilter = THREE.LinearFilter; params.envMap = texture; } var shininess = values.shininesss || values.shininess; // N.B.: typo in converter! if (shininess) { shininess = shininess; } var diffuseColor = !texturePath ? diffuse : null; var opacity = 1.0; if (values.hasOwnProperty("transparency")) { var USE_A_ONE = true; // for now, hack because file format isn't telling us opacity = USE_A_ONE ? values.transparency : (1.0 - values.transparency); } // if (diffuseColor) diffuseColor = [0, 1, 0]; params.color = RgbArraytoHex(diffuseColor); params.opacity = opacity; params.transparent = opacity < 1.0; // hack hack hack if (texturePath && texturePath.toLowerCase().indexOf(".png") != -1) params.transparent = true; if (!(shininess === undefined)) { params.shininess = shininess; } if (!(values.ambient === undefined) && !(typeof(values.ambient) == 'string')) { params.ambient = RgbArraytoHex(values.ambient); } if (!(values.emission === undefined)) { params.emissive = RgbArraytoHex(values.emission); } if (!(values.specular === undefined)) { params.specular = RgbArraytoHex(values.specular); } return materialType; } }, handleMaterial: { value: function(entryID, description, userInfo) { //this should be rewritten using the meta datas that actually create the shader. //here we will infer what needs to be pass to Three.js by looking inside the technique parameters. var technique = this.resources.getEntry(description.instanceTechnique.technique); var materialParams = {}; var values = description.instanceTechnique.values; var materialType = this.threeJSMaterialType(entryID, technique, values, materialParams); var material = new materialType(materialParams); this.resources.setEntry(entryID, material, description); return true; } }, handleMesh: { value: function(entryID, description, userInfo) { var mesh = new Mesh(); this.resources.setEntry(entryID, mesh, description); var primitivesDescription = description.primitives; if (!primitivesDescription) { //FIXME: not implemented in delegate console.log("MISSING_PRIMITIVES for mesh:"+ entryID); return false; } for (var i = 0 ; i < primitivesDescription.length ; i++) { var primitiveDescription = primitivesDescription[i]; if (primitiveDescription.primitive === WebGLRenderingContext.TRIANGLES) { var geometry = new ClassicGeometry(); var materialEntry = this.resources.getEntry(primitiveDescription.material); mesh.addPrimitive(geometry, materialEntry.object); var indices = this.resources.getEntry(primitiveDescription.indices); var bufferEntry = this.resources.getEntry(indices.description.bufferView); var indicesObject = { bufferView : bufferEntry, byteOffset : indices.description.byteOffset, count : indices.description.count, id : indices.entryID, type : indices.description.type }; var indicesContext = new IndicesContext(indicesObject, geometry); var alreadyProcessedIndices = THREE.GLTFLoaderUtils.getBuffer(indicesObject, indicesDelegate, indicesContext); /*if(alreadyProcessedIndices) { indicesDelegate.resourceAvailable(alreadyProcessedIndices, indicesContext); }*/ // Load Vertex Attributes var allAttributes = Object.keys(primitiveDescription.attributes); allAttributes.forEach( function(semantic) { geometry.totalAttributes++; var attribute; var attributeID = primitiveDescription.attributes[semantic]; var attributeEntry = this.resources.getEntry(attributeID); if (!attributeEntry) { //let's just use an anonymous object for the attribute attribute = description.attributes[attributeID]; attribute.id = attributeID; this.resources.setEntry(attributeID, attribute, attribute); var bufferEntry = this.resources.getEntry(attribute.bufferView); attributeEntry = this.resources.getEntry(attributeID); } else { attribute = attributeEntry.object; attribute.id = attributeID; var bufferEntry = this.resources.getEntry(attribute.bufferView); } var attributeObject = { bufferView : bufferEntry, byteOffset : attribute.byteOffset, byteStride : attribute.byteStride, count : attribute.count, max : attribute.max, min : attribute.min, type : attribute.type, id : attributeID }; var attribContext = new VertexAttributeContext(attributeObject, semantic, geometry); var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(attributeObject, vertexAttributeDelegate, attribContext); /*if(alreadyProcessedAttribute) { vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext); }*/ }, this); } } return true; } }, handleCamera: { value: function(entryID, description, userInfo) { var camera; if (description.type == "perspective") { var znear = description.perspective.znear; var zfar = description.perspective.zfar; var yfov = description.perspective.yfov; var xfov = description.perspective.xfov; var aspect_ratio = description.perspective.aspect_ratio; if (!aspect_ratio) aspect_ratio = 1; if (yfov === undefined) { if (xfov) { // According to COLLADA spec... // aspect_ratio = xfov / yfov yfov = xfov / aspect_ratio; } } if (yfov) { camera = new THREE.PerspectiveCamera(yfov, aspect_ratio, znear, zfar); } } else { camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, znear, zfar ); } if (camera) { this.resources.setEntry(entryID, camera, description); } return true; } }, handleLight: { value: function(entryID, description, userInfo) { var light = null; var type = description.type; if (type && description[type]) { var lparams = description[type]; var color = RgbArraytoHex(lparams.color); switch (type) { case "directional" : light = new THREE.DirectionalLight(color); light.position.set(0, 0, 1); break; case "point" : light = new THREE.PointLight(color); break; case "spot " : light = new THREE.SpotLight(color); light.position.set(0, 0, 1); break; case "ambient" : light = new THREE.AmbientLight(color); break; } } if (light) { this.resources.setEntry(entryID, light, description); } return true; } }, addPendingMesh: { value: function(mesh, threeNode) { theLoader.pendingMeshes.push({ mesh: mesh, node: threeNode }); } }, handleNode: { value: function(entryID, description, userInfo) { var threeNode = null; if (description.jointId) { threeNode = new THREE.Bone(); threeNode.jointId = description.jointId; this.joints[description.jointId] = entryID; } else { threeNode = new THREE.Object3D(); } threeNode.name = description.name; this.resources.setEntry(entryID, threeNode, description); var m = description.matrix; if(m) { threeNode.matrixAutoUpdate = false; threeNode.applyMatrix(new THREE.Matrix4( m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15] )); } else { var t = description.translation; var r = description.rotation; var s = description.scale; var position = t ? new THREE.Vector3(t[0], t[1], t[2]) : new THREE.Vector3; if (r) { convertAxisAngleToQuaternion(r, 1); } var rotation = r ? new THREE.Quaternion(r[0], r[1], r[2], r[3]) : new THREE.Quaternion; var scale = s ? new THREE.Vector3(s[0], s[1], s[2]) : new THREE.Vector3; var matrix = new THREE.Matrix4; matrix.compose(position, rotation, scale); threeNode.matrixAutoUpdate = false; threeNode.applyMatrix(matrix); } var self = this; // Iterate through all node meshes and attach the appropriate objects //FIXME: decision needs to be made between these 2 ways, probably meshes will be discarded. var meshEntry; if (description.mesh) { meshEntry = this.resources.getEntry(description.mesh); theLoader.meshesRequested++; meshEntry.object.onComplete(function(mesh) { self.addPendingMesh(mesh, threeNode); theLoader.meshesLoaded++; theLoader.checkComplete(); }); } if (description.meshes) { description.meshes.forEach( function(meshID) { meshEntry = this.resources.getEntry(meshID); theLoader.meshesRequested++; meshEntry.object.onComplete(function(mesh) { self.addPendingMesh(mesh, threeNode); theLoader.meshesLoaded++; theLoader.checkComplete(); }); }, this); } if (description.instanceSkin) { var skinEntry = this.resources.getEntry(description.instanceSkin.skin); if (skinEntry) { var skin = skinEntry.object; description.instanceSkin.skin = skin; threeNode.instanceSkin = description.instanceSkin; var sources = description.instanceSkin.sources; skin.meshes = []; sources.forEach( function(meshID) { meshEntry = this.resources.getEntry(meshID); theLoader.meshesRequested++; meshEntry.object.onComplete(function(mesh) { skin.meshes.push(mesh); theLoader.meshesLoaded++; theLoader.checkComplete(); }); }, this); } } if (description.camera) { var cameraEntry = this.resources.getEntry(description.camera); if (cameraEntry) { threeNode.add(cameraEntry.object); this.cameras.push(cameraEntry.object); } } if (description.light) { var lightEntry = this.resources.getEntry(description.light); if (lightEntry) { threeNode.add(lightEntry.object); this.lights.push(lightEntry.object); } } return true; } }, buildNodeHirerachy: { value: function(nodeEntryId, parentThreeNode) { var nodeEntry = this.resources.getEntry(nodeEntryId); var threeNode = nodeEntry.object; parentThreeNode.add(threeNode); var children = nodeEntry.description.children; if (children) { children.forEach( function(childID) { this.buildNodeHirerachy(childID, threeNode); }, this); } return threeNode; } }, buildSkin: { value: function(node) { var skin = node.instanceSkin.skin; if (skin) { node.instanceSkin.skeletons.forEach(function(skeleton) { var nodeEntry = this.resources.getEntry(skeleton); if (nodeEntry) { var rootSkeleton = nodeEntry.object; var dobones = true; var i, len = skin.meshes.length; for (i = 0; i < len; i++) { var mesh = skin.meshes[i]; var threeMesh = null; mesh.primitives.forEach(function(primitive) { var material = primitive.material; if (!(material instanceof THREE.Material)) { material = this.createShaderMaterial(material); } threeMesh = new THREE.SkinnedMesh(primitive.geometry.geometry, material, false); threeMesh.add(rootSkeleton); var geometry = primitive.geometry.geometry; var j; if (geometry.vertices) { for ( j = 0; j < geometry.vertices.length; j ++ ) { geometry.vertices[j].applyMatrix4( skin.bindShapeMatrix ); } } else if (geometry.attributes.position) { var a = geometry.attributes.position.array; var v = new THREE.Vector3; for ( j = 0; j < a.length / 3; j++ ) { v.set(a[j * 3], a[j * 3 + 1], a[j * 3 + 2]); v.applyMatrix4( skin.bindShapeMatrix ); a[j * 3] = v.x; a[j * 3 + 1] = v.y; a[j * 3 + 2] = v.z; } } if (threeMesh && dobones) { material.skinning = true; threeMesh.boneInverses = []; var jointsIds = skin.jointsIds; var joints = []; var i, len = jointsIds.length; for (i = 0; i < len; i++) { var jointId = jointsIds[i]; var nodeForJoint = this.joints[jointId]; var joint = this.resources.getEntry(nodeForJoint).object; if (joint) { joint.skin = threeMesh; joints.push(joint); threeMesh.bones.push(joint); var m = skin.inverseBindMatrices; var mat = new THREE.Matrix4( m[i * 16 + 0], m[i * 16 + 4], m[i * 16 + 8], m[i * 16 + 12], m[i * 16 + 1], m[i * 16 + 5], m[i * 16 + 9], m[i * 16 + 13], m[i * 16 + 2], m[i * 16 + 6], m[i * 16 + 10], m[i * 16 + 14], m[i * 16 + 3], m[i * 16 + 7], m[i * 16 + 11], m[i * 16 + 15] ); threeMesh.boneInverses.push(mat); threeMesh.pose(); } else { console.log("WARNING: jointId:"+jointId+" cannot be found in skeleton:"+skeleton); } } } if (threeMesh) { threeMesh.castShadow = true; node.add(threeMesh); } }, this); } } }, this); } } }, buildSkins: { value: function(node) { if (node.instanceSkin) this.buildSkin(node); var children = node.children; if (children) { children.forEach( function(child) { this.buildSkins(child); }, this); } } }, createMeshAnimations : { value : function(root) { this.buildSkins(root); } }, handleScene: { value: function(entryID, description, userInfo) { if (!description.nodes) { console.log("ERROR: invalid file required nodes property is missing from scene"); return false; } description.nodes.forEach( function(nodeUID) { this.buildNodeHirerachy(nodeUID, userInfo.rootObj); }, this); if (this.delegate) { this.delegate.loadCompleted(userInfo.callback, userInfo.rootObj); } return true; } }, handleImage: { value: function(entryID, description, userInfo) { this.resources.setEntry(entryID, null, description); return true; } }, addNodeAnimationChannel : { value : function(name, channel, interp) { if (!this.nodeAnimationChannels) this.nodeAnimationChannels = {}; if (!this.nodeAnimationChannels[name]) { this.nodeAnimationChannels[name] = []; } this.nodeAnimationChannels[name].push(interp); }, }, createAnimations : { value : function() { for (var name in this.nodeAnimationChannels) { var nodeAnimationChannels = this.nodeAnimationChannels[name]; var i, len = nodeAnimationChannels.length; //console.log(" animation channels for node " + name); //for (i = 0; i < len; i++) { // console.log(nodeAnimationChannels[i]); //} var anim = new THREE.glTFAnimation(nodeAnimationChannels); anim.name = "animation_" + name; this.animations.push(anim); } } }, buildAnimation: { value : function(animation) { var interps = []; var i, len = animation.channels.length; for (i = 0; i < len; i++) { var channel = animation.channels[i]; var sampler = animation.samplers[channel.sampler]; if (sampler) { var input = animation.parameters[sampler.input]; if (input && input.data) { var output = animation.parameters[sampler.output]; if (output && output.data) { var target = channel.target; var node = this.resources.getEntry(target.id); if (node) { var path = target.path; if (path == "rotation") { convertAxisAngleToQuaternion(output.data, output.count); } var interp = { keys : input.data, values : output.data, count : input.count, target : node.object, path : path, type : sampler.interpolation }; this.addNodeAnimationChannel(target.id, channel, interp); interps.push(interp); } } } } } } }, handleAnimation: { value: function(entryID, description, userInfo) { var self = this; theLoader.animationsRequested++; var animation = new Animation(); animation.name = entryID; animation.onload = function() { // self.buildAnimation(animation); theLoader.animationsLoaded++; theLoader.animations.push(animation); theLoader.checkComplete(); }; animation.channels = description.channels; animation.samplers = description.samplers; this.resources.setEntry(entryID, animation, description); var parameters = description.parameters; if (!parameters) { //FIXME: not implemented in delegate console.log("MISSING_PARAMETERS for animation:"+ entryID); return false; } // Load parameter buffers var params = Object.keys(parameters); params.forEach( function(param) { animation.totalParameters++; var parameter = parameters[param]; var accessor = this.resources.getEntry(parameter); if (!accessor) debugger; accessor = accessor.object; var bufferView = this.resources.getEntry(accessor.bufferView); var paramObject = { bufferView : bufferView, byteOffset : accessor.byteOffset, count : accessor.count, type : accessor.type, id : accessor.bufferView, name : param }; var paramContext = new AnimationParameterContext(paramObject, animation); var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, animationParameterDelegate, paramContext); /*if(alreadyProcessedAttribute) { vertexAttributeDelegate.resourceAvailable(alreadyProcessedAttribute, attribContext); }*/ }, this); return true; } }, handleAccessor: { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, description, description); return true; } }, handleSkin: { value: function(entryID, description, userInfo) { // Save skin entry var skin = { }; var m = description.bindShapeMatrix; skin.bindShapeMatrix = new THREE.Matrix4( m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15] ); skin.jointsIds = description.joints; var inverseBindMatricesDescription = description.inverseBindMatrices; skin.inverseBindMatricesDescription = inverseBindMatricesDescription; skin.inverseBindMatricesDescription.id = entryID + "_inverseBindMatrices"; var bufferEntry = this.resources.getEntry(inverseBindMatricesDescription.bufferView); var paramObject = { bufferView : bufferEntry, byteOffset : inverseBindMatricesDescription.byteOffset, count : inverseBindMatricesDescription.count, type : inverseBindMatricesDescription.type, id : inverseBindMatricesDescription.bufferView, name : skin.inverseBindMatricesDescription.id }; var context = new InverseBindMatricesContext(paramObject, skin); var alreadyProcessedAttribute = THREE.GLTFLoaderUtils.getBuffer(paramObject, inverseBindMatricesDelegate, context); var bufferView = this.resources.getEntry(skin.inverseBindMatricesDescription.bufferView); skin.inverseBindMatricesDescription.bufferView = bufferView.object; this.resources.setEntry(entryID, skin, description); return true; } }, handleSampler: { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, description, description); return true; } }, handleTexture: { value: function(entryID, description, userInfo) { // Save attribute entry this.resources.setEntry(entryID, null, description); return true; } }, handleError: { value: function(msg) { throw new Error(msg); return true; } }, _delegate: { value: new LoadDelegate, writable: true }, delegate: { enumerable: true, get: function() { return this._delegate; }, set: function(value) { this._delegate = value; } } }); // Loader var Context = function(rootObj, callback) { this.rootObj = rootObj; this.callback = callback; }; var rootObj = new THREE.Object3D(); var self = this; var loader = Object.create(ThreeGLTFLoader); loader.initWithPath(url); loader.load(new Context(rootObj, function(obj) { }), null); this.loader = loader; this.callback = callback; this.rootObj = rootObj; return rootObj; } THREE.glTFLoader.prototype.callLoadedCallback = function() { var result = { scene : this.rootObj, cameras : this.loader.cameras, animations : this.loader.animations, }; this.callback(result); } THREE.glTFLoader.prototype.checkComplete = function() { if (this.meshesLoaded == this.meshesRequested && this.shadersLoaded == this.shadersRequested && this.animationsLoaded == this.animationsRequested) { for (var i = 0; i < this.pendingMeshes.length; i++) { var pending = this.pendingMeshes[i]; pending.mesh.attachToNode(pending.node); } for (var i = 0; i < this.animationsLoaded; i++) { var animation = this.animations[i]; this.loader.buildAnimation(animation); } this.loader.createAnimations(); this.loader.createMeshAnimations(this.rootObj); this.callLoadedCallback(); } }
JavaScript
/** * @author alteredq / http://alteredqualia.com/ * @author mr.doob / http://mrdoob.com/ */ var Detector = { canvas: !! window.CanvasRenderingContext2D, webgl: ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )(), workers: !! window.Worker, fileapi: window.File && window.FileReader && window.FileList && window.Blob, getWebGLErrorMessage: function () { var element = document.createElement( 'div' ); element.id = 'webgl-error-message'; element.style.fontFamily = 'monospace'; element.style.fontSize = '13px'; element.style.fontWeight = 'normal'; element.style.textAlign = 'center'; element.style.background = '#fff'; element.style.color = '#000'; element.style.padding = '1.5em'; element.style.width = '400px'; element.style.margin = '5em auto 0'; if ( ! this.webgl ) { element.innerHTML = window.WebGLRenderingContext ? [ 'Your graphics card does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br />', 'Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.' ].join( '\n' ) : [ 'Your browser does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br/>', 'Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.' ].join( '\n' ); } return element; }, addGetWebGLMessage: function ( parameters ) { var parent, id, element; parameters = parameters || {}; parent = parameters.parent !== undefined ? parameters.parent : document.body; id = parameters.id !== undefined ? parameters.id : 'oldie'; element = Detector.getWebGLErrorMessage(); element.id = id; parent.appendChild( element ); } };
JavaScript
{ "metadata" : { "formatVersion" : 3.1, "sourceFile" : "female02.obj", "generatedBy" : "OBJConverter", "vertices" : 3274, "faces" : 6233, "normals" : 3292, "uvs" : 4935, "materials" : 6 }, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "_03_-_Default1noCulli__03_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "03_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 15597568, "DbgIndex" : 1, "DbgName" : "_02_-_Default1noCulli__02_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "02_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 60928, "DbgIndex" : 2, "DbgName" : "FrontColorNoCullingID__02_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.8, 0.8, 0.8], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "02_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 238, "DbgIndex" : 3, "DbgName" : "FrontColorNoCullingID__03_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.8, 0.8, 0.8], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "03_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 15658496, "DbgIndex" : 4, "DbgName" : "_01_-_Default1noCulli__01_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "01_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 61166, "DbgIndex" : 5, "DbgName" : "FrontColorNoCullingID__01_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.8, 0.8, 0.8], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "01_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }], "buffers": "Female02_bin.bin" }
JavaScript
{ "metadata" : { "formatVersion" : 3.1, "sourceFile" : "male02.obj", "generatedBy" : "OBJConverter", "vertices" : 2746, "faces" : 5004, "normals" : 2769, "uvs" : 3275, "materials" : 5 }, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "male-02-1noCullingID_male-02-1noCulling.JP", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "male-02-1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 15597568, "DbgIndex" : 1, "DbgName" : "orig_02_-_Defaul1noCu_orig_02_-_Defaul1noCu", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "orig_02_-_Defaul1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 60928, "DbgIndex" : 2, "DbgName" : "FrontColorNoCullingID_orig_02_-_Defaul1noCu", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.8, 0.8, 0.8], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "orig_02_-_Defaul1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 238, "DbgIndex" : 3, "DbgName" : "_01_-_Default1noCulli__01_-_Default1noCulli", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.64, 0.64, 0.64], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "01_-_Default1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }, { "DbgColor" : 15658496, "DbgIndex" : 4, "DbgName" : "FrontColorNoCullingID_male-02-1noCulling.JP", "colorAmbient" : [0.0, 0.0, 0.0], "colorDiffuse" : [0.8, 0.8, 0.8], "colorSpecular" : [0.165, 0.165, 0.165], "illumination" : 2, "mapDiffuse" : "male-02-1noCulling.JPG", "opticalDensity" : 1.0, "specularCoef" : 154.901961, "transparency" : 1.0 }], "buffers": "Male02_bin.bin" }
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 UNDEF = "undefined", OBJECT = "object", SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", EXPRESS_INSTALL_ID = "SWFObjectExprInst", ON_READY_STATE_CHANGE = "onreadystatechange", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], regObjArr = [], objIdArr = [], listenersArr = [], storedAltContent, storedAltContentId, storedCallbackFn, storedCallbackObj, isDomLoaded = false, isExpressInstallActive = false, dynamicStylesheet, dynamicStylesheetMedia, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(), /* Cross-browser onDomLoad - Will fire an event as soon as the DOM of a web page is loaded - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/ - Regular onload serves as fallback */ onDomLoad = function() { if (!ua.w3) { return; } if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically callDomLoadFunctions(); } if (!isDomLoaded) { if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false); } if (ua.ie && ua.win) { doc.attachEvent(ON_READY_STATE_CHANGE, function() { if (doc.readyState == "complete") { doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee); callDomLoadFunctions(); } }); if (win == top) { // if not inside an iframe (function(){ if (isDomLoaded) { return; } try { doc.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } } if (ua.wk) { (function(){ if (isDomLoaded) { return; } if (!/loaded|complete/.test(doc.readyState)) { setTimeout(arguments.callee, 0); return; } callDomLoadFunctions(); })(); } addLoadEvent(callDomLoadFunctions); } }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span")); t.parentNode.removeChild(t); } catch (e) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Cross-browser onload - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/ - Will fire an event as soon as a web page including all of its assets are loaded */ function addLoadEvent(fn) { if (typeof win.addEventListener != UNDEF) { win.addEventListener("load", fn, false); } else if (typeof doc.addEventListener != UNDEF) { doc.addEventListener("load", fn, false); } else if (typeof win.attachEvent != UNDEF) { addListener(win, "onload", fn); } else if (typeof win.onload == "function") { var fnOld = win.onload; win.onload = function() { fnOld(); fn(); }; } else { win.onload = fn; } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } else { matchVersions(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; matchVersions(); })(); } else { matchVersions(); } } /* Perform Flash Player and SWF version matching; static publishing only */ function matchVersions() { var rl = regObjArr.length; if (rl > 0) { for (var i = 0; i < rl; i++) { // for each registered object element var id = regObjArr[i].id; var cb = regObjArr[i].callbackFn; var cbObj = {success:false, id:id}; if (ua.pv[0] > 0) { var obj = getElementById(id); if (obj) { if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match! setVisibility(id, true); if (cb) { cbObj.success = true; cbObj.ref = getObjectById(id); cb(cbObj); } } else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported var att = {}; att.data = regObjArr[i].expressInstall; att.width = obj.getAttribute("width") || "0"; att.height = obj.getAttribute("height") || "0"; if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); } if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); } // parse HTML object param element's name-value pairs var par = {}; var p = obj.getElementsByTagName("param"); var pl = p.length; for (var j = 0; j < pl; j++) { if (p[j].getAttribute("name").toLowerCase() != "movie") { par[p[j].getAttribute("name")] = p[j].getAttribute("value"); } } showExpressInstall(att, par, id, cb); } else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF displayAltContent(obj); if (cb) { cb(cbObj); } } } } else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content) setVisibility(id, true); if (cb) { var o = getObjectById(id); // test whether there is an HTML object element or not if (o && typeof o.SetVariable != UNDEF) { cbObj.success = true; cbObj.ref = o; } cb(cbObj); } } } } } function getObjectById(objectIdStr) { var r = null; var o = getElementById(objectIdStr); if (o && o.nodeName == "OBJECT") { if (typeof o.SetVariable != UNDEF) { r = o; } else { var n = o.getElementsByTagName(OBJECT)[0]; if (n) { r = n; } } } return r; } /* Requirements for Adobe Express Install - only one instance can be active at a time - fp 6.0.65 or higher - Win/Mac OS only - no Webkit engines older than version 312 */ function canExpressInstall() { return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312); } /* Show the Adobe Express Install dialog - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75 */ function showExpressInstall(att, par, replaceElemIdStr, callbackFn) { isExpressInstallActive = true; storedCallbackFn = callbackFn || null; storedCallbackObj = {success:false, id:replaceElemIdStr}; var obj = getElementById(replaceElemIdStr); if (obj) { if (obj.nodeName == "OBJECT") { // static publishing storedAltContent = abstractAltContent(obj); storedAltContentId = null; } else { // dynamic publishing storedAltContent = obj; storedAltContentId = replaceElemIdStr; } att.id = EXPRESS_INSTALL_ID; if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; } if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; } doc.title = doc.title.slice(0, 47) + " - Flash Player Installation"; var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn", fv = "MMredirectURL=" + encodeURI(window.location).toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title; if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + fv; } else { par.flashvars = fv; } // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work if (ua.ie && ua.win && obj.readyState != 4) { var newObj = createElement("div"); replaceElemIdStr += "SWFObjectNew"; newObj.setAttribute("id", replaceElemIdStr); obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } createSWF(att, par, replaceElemIdStr); } } /* Functions to abstract and display alternative content */ function displayAltContent(obj) { if (ua.ie && ua.win && obj.readyState != 4) { // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it, // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work var el = createElement("div"); obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content el.parentNode.replaceChild(abstractAltContent(obj), el); obj.style.display = "none"; (function(){ if (obj.readyState == 4) { obj.parentNode.removeChild(obj); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.replaceChild(abstractAltContent(obj), obj); } } function abstractAltContent(obj) { var ac = createElement("div"); if (ua.win && ua.ie) { ac.innerHTML = obj.innerHTML; } else { var nestedObj = obj.getElementsByTagName(OBJECT)[0]; if (nestedObj) { var c = nestedObj.childNodes; if (c) { var cl = c.length; for (var i = 0; i < cl; i++) { if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) { ac.appendChild(c[i].cloneNode(true)); } } } } } return ac; } /* Cross-browser dynamic SWF creation */ function createSWF(attObj, parObj, id) { var r, el = getElementById(id); if (ua.wk && ua.wk < 312) { return r; } if (el) { if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content attObj.id = id; } if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML var att = ""; for (var i in attObj) { if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries if (i.toLowerCase() == "data") { parObj.movie = attObj[i]; } else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword att += ' class="' + attObj[i] + '"'; } else if (i.toLowerCase() != "classid") { att += ' ' + i + '="' + attObj[i] + '"'; } } } var par = ""; for (var j in parObj) { if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries par += '<param name="' + j + '" value="' + parObj[j] + '" />'; } } el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>'; objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only) r = getElementById(attObj.id); } else { // well-behaving browsers var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); for (var m in attObj) { if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword o.setAttribute("class", attObj[m]); } else if (m.toLowerCase() != "classid") { // filter out IE specific attribute o.setAttribute(m, attObj[m]); } } } for (var n in parObj) { if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element createObjParam(o, n, parObj[n]); } } el.parentNode.replaceChild(o, el); r = o; } } return r; } function createObjParam(el, pName, pValue) { var p = createElement("param"); p.setAttribute("name", pName); p.setAttribute("value", pValue); el.appendChild(p); } /* Cross-browser SWF removal - Especially needed to safely and completely remove a SWF in Internet Explorer */ function removeSWF(id) { var obj = getElementById(id); if (obj && obj.nodeName == "OBJECT") { if (ua.ie && ua.win) { obj.style.display = "none"; (function(){ if (obj.readyState == 4) { removeObjectInIE(id); } else { setTimeout(arguments.callee, 10); } })(); } else { obj.parentNode.removeChild(obj); } } } function removeObjectInIE(id) { var obj = getElementById(id); if (obj) { for (var i in obj) { if (typeof obj[i] == "function") { obj[i] = null; } } obj.parentNode.removeChild(obj); } } /* Functions to optimize JavaScript compression */ function getElementById(id) { var el = null; try { el = doc.getElementById(id); } catch (e) {} return el; } function createElement(el) { return doc.createElement(el); } /* Updated attachEvent function for Internet Explorer - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks */ function addListener(target, eventType, fn) { target.attachEvent(eventType, fn); listenersArr[listenersArr.length] = [target, eventType, fn]; } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } /* Cross-browser dynamic CSS creation - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php */ function createCSS(sel, decl, media, newStyle) { if (ua.ie && ua.mac) { return; } var h = doc.getElementsByTagName("head")[0]; if (!h) { return; } // to also support badly authored HTML pages that lack a head element var m = (media && typeof media == "string") ? media : "screen"; if (newStyle) { dynamicStylesheet = null; dynamicStylesheetMedia = null; } if (!dynamicStylesheet || dynamicStylesheetMedia != m) { // create dynamic stylesheet + get a global reference to it var s = createElement("style"); s.setAttribute("type", "text/css"); s.setAttribute("media", m); dynamicStylesheet = h.appendChild(s); if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) { dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1]; } dynamicStylesheetMedia = m; } // add style rule if (ua.ie && ua.win) { if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) { dynamicStylesheet.addRule(sel, decl); } } else { if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) { dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}")); } } } function setVisibility(id, isVisible) { if (!autoHideShow) { return; } var v = isVisible ? "visible" : "hidden"; if (isDomLoaded && getElementById(id)) { getElementById(id).style.visibility = v; } else { createCSS("#" + id, "visibility:" + v); } } /* Filter to avoid XSS attacks */ function urlEncodeIfNecessary(s) { var regex = /[\\\"<>\.;]/; var hasBadChars = regex.exec(s) != null; return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s; } /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only) */ var cleanup = function() { if (ua.ie && ua.win) { window.attachEvent("onunload", function() { // remove listeners to avoid memory leaks var ll = listenersArr.length; for (var i = 0; i < ll; i++) { listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]); } // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect var il = objIdArr.length; for (var j = 0; j < il; j++) { removeSWF(objIdArr[j]); } // cleanup library's main closures to avoid memory leaks for (var k in ua) { ua[k] = null; } ua = null; for (var l in swfobject) { swfobject[l] = null; } swfobject = null; }); } }(); return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) { if (ua.w3 && objectIdStr && swfVersionStr) { var regObj = {}; regObj.id = objectIdStr; regObj.swfVersion = swfVersionStr; regObj.expressInstall = xiSwfUrlStr; regObj.callbackFn = callbackFn; regObjArr[regObjArr.length] = regObj; setVisibility(objectIdStr, false); } else if (callbackFn) { callbackFn({success:false, id:objectIdStr}); } }, getObjectById: function(objectIdStr) { if (ua.w3) { return getObjectById(objectIdStr); } }, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var callbackObj = {success:false, id:replaceElemIdStr}; if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) { setVisibility(replaceElemIdStr, false); addDomLoadEvent(function() { widthStr += ""; // auto-convert to string heightStr += ""; var att = {}; if (attObj && typeof attObj === OBJECT) { for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs att[i] = attObj[i]; } } att.data = swfUrlStr; att.width = widthStr; att.height = heightStr; var par = {}; if (parObj && typeof parObj === OBJECT) { for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs par[j] = parObj[j]; } } if (flashvarsObj && typeof flashvarsObj === OBJECT) { for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs if (typeof par.flashvars != UNDEF) { par.flashvars += "&" + k + "=" + flashvarsObj[k]; } else { par.flashvars = k + "=" + flashvarsObj[k]; } } } if (hasPlayerVersion(swfVersionStr)) { // create SWF var obj = createSWF(att, par, replaceElemIdStr); if (att.id == replaceElemIdStr) { setVisibility(replaceElemIdStr, true); } callbackObj.success = true; callbackObj.ref = obj; } else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install att.data = xiSwfUrlStr; showExpressInstall(att, par, replaceElemIdStr, callbackFn); return; } else { // show alternative content setVisibility(replaceElemIdStr, true); } if (callbackFn) { callbackFn(callbackObj); } }); } else if (callbackFn) { callbackFn(callbackObj); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) { if (ua.w3 && canExpressInstall()) { showExpressInstall(att, par, replaceElemIdStr, callbackFn); } }, removeSWF: function(objElemIdStr) { if (ua.w3) { removeSWF(objElemIdStr); } }, createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) { if (ua.w3) { createCSS(selStr, declStr, mediaStr, newStyleBoolean); } }, addDomLoadEvent: addDomLoadEvent, addLoadEvent: addLoadEvent, getQueryParamValue: function(param) { var q = doc.location.search || doc.location.hash; if (q) { if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark if (param == null) { return urlEncodeIfNecessary(q); } var pairs = q.split("&"); for (var i = 0; i < pairs.length; i++) { if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) { return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1))); } } } return ""; }, // For internal usage only expressInstallCallback: function() { if (isExpressInstallActive) { var obj = getElementById(EXPRESS_INSTALL_ID); if (obj && storedAltContent) { obj.parentNode.replaceChild(storedAltContent, obj); if (storedAltContentId) { setVisibility(storedAltContentId, true); if (ua.ie && ua.win) { storedAltContent.style.display = "block"; } } if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); } } isExpressInstallActive = false; } } }; }();
JavaScript
BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, ie8: false, firefox: false, safari: false, opera: false, version: -1 }; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; // Flag to denote the existence of onhashchange var browserHasHashChange = false; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); if (browser.version == 8) { browser.ie = false; browser.ie8 = true; } } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } function hashChangeHandler() { currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } // Get the Flash player object for performing ExternalInterface callbacks. // Updated for changes to SWFObject2. function getPlayer(id) { var i; if (id && document.getElementById(id)) { var r = document.getElementById(id); if (typeof r.SetVariable != "undefined") { return r; } else { var o = r.getElementsByTagName("object"); var e = r.getElementsByTagName("embed"); for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") return o[i]; } for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") return e[i]; } } } else { var o = document.getElementsByTagName("object"); var e = document.getElementsByTagName("embed"); for (i = 0; i < e.length; i++) { if (typeof e[i].browserURLChange != "undefined") { return e[i]; } } for (i = 0; i < o.length; i++) { if (typeof o[i].browserURLChange != "undefined") { return o[i]; } } } return undefined; } function getPlayers() { var i; var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); for (i = 0; i < tmp.length; i++) { if (typeof tmp[i].browserURLChange != "undefined") players.push(tmp[i]); } } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari && !browserHasHashChange) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, just tell the browser to go there setHash(flexAppUrl); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; currentHref = document.location.href; } } } } if (browser.safari && !browserHasHashChange) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); var flexAppUrl = getHash(); if (browser.version < 528.16 /* Anything earlier than Safari 4.0 */) { // If it did change and we're running Safari 3.x or earlier, // then we have to look the old state up in our hand-maintained // array since document.location.hash won't have changed, // then call back into BrowserManager. currentHistoryLength = history.length; flexAppUrl = historyHash[currentHistoryLength]; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox && !browserHasHashChange) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } } var _initialize = function () { browserHasHashChange = ("onhashchange" in document.body); if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; iframe.src = 'javascript:false;'; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari && !browserHasHashChange) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browserHasHashChange) document.body.onhashchange = hashChangeHandler; } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; }, getUserAgent: function() { return navigator.userAgent; }, getPlatform: function() { return navigator.platform; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );
JavaScript
function toggleWriteability(id_of_patient, checked) { document.getElementById(id_of_patient).disabled = checked; } // vim: et sw=4 sts=4
JavaScript
/** * 점수관리를 위한 스크립트 * date : 2014.11.3 * 작성자 : kyun */ //var btnlist, btninput, btnview, btnmodify, btndelete; function general() { btnlist=document.getElementById('btnlist'); if(btnlist!=null) { btnlist.onclick=function() { var frm=document.hiddenFrm; frm.action='../3jsp/list.jsp'; frm.submit(); } } //사용됨 btninput=document.getElementById('btninput'); if(btninput!=null) { btninput.onclick=function() { var frm=document.hiddenFrm; frm.action='../3jsp/input.jsp'; frm.submit(); //location.href=url+'input.jsp'; } } //사용됨 btnminput=document.getElementById('btnminput'); if(btnminput!=null) { btnminput.onclick=function() { var frm=document.hiddenFrm; frm.action='../3jsp/masterinput.jsp'; frm.submit(); //location.href=url+'input.jsp'; } } btnview=document.getElementById('btnview'); if(btnview!=null) { btnview.onclick=function() { location.href='../3jsp/view.jsp'; } } btnmodify=document.getElementById('btnmodify'); if(btnmodify!=null) { btnmodify.onclick=function() { location.href='../3jsp/modify.jsp'; } } btndelete=document.getElementById('btndelete'); if(btndelete!=null) { btndelete.onclick=function() { var b = confirm("정말 ?!!"); if(b) { var rno=document.hiddenFrm.rno.value; location.href='../3jsp/delete_result.jsp&rno='+rno; } else { alert("그래~ 삭제하지마..ㅋㅋ"); } } } } //사용됨 function saveda() { btnsave=document.getElementById('btnsave'); if(btnsave!=null) { btnsave.onclick=function() { var f= document.hiddenFrm; if(f.pwd.value=='') { alert('비밀번호 입력해주세요'); f.pwd.focus(); } else { f.action='../3jsp/input_result.jsp' f.submit(); } } } } //사용됨 function msaveda() { btnmsave=document.getElementById('btnmsave'); if(btnmsave!=null) { btnmsave.onclick=function() { var f= document.hiddenFrm; f.action='../3jsp/masterinput_result.jsp' f.submit(); } } } function goPage(page){ var mf = document.hiddenFrm; mf.nowPage.value = page; mf.find.value = document.master_list_frm.find.value; mf.action = 'list.jsp'; mf.submit(); //alert(page); //location.href=url + 'view.jsp&page=' + page; } function goview(page, rno) { var mf = document.hiddenfrm; mf.nowPage.value = page; mf.rno.value=rno; mf.find.value = document.score_list_frm.find.value; mf.action = 'index.jsp?inc=../score/view.jsp'; mf.submit(); } function deleteinit() { general(); } //사용됨 function inputinit() { btnlist=document.getElementById('btnlist'); if(btnlist!=null) { btnlist.onclick=function() { var frm=document.hiddenFrm; frm.action='../3jsp/list.jsp'; alert("입력을 취소하시겠습니다?"+"\n"+"작성된 글은 지워집니다.") frm.submit(); } } saveda(); msaveda(); } //사용됨 function listinit() { general(); } function modifyinit() { btnlist=document.getElementById('btnlist'); if(btnlist!=null) { btnlist.onclick=function() { var frm=document.hiddenFrm; frm.action='../3jsp/list.jsp'; alert("수정을 취소하시겠습니다?"+"\n"+"변경된 내용은 지워집니다.") frm.submit(); } } saveda(); } function viewinit() { general(); }
JavaScript
/** * */ function evenetcheckinit() { document.getElementById('btn1').onclick=cfunc; document.getElementById('btn2').onclick=cfunc; document.getElementById('btn3').onclick=cfunc; } function func(event) { var n = event.srcElement.name; var v = event.srcElement.value; alert('name = ' + n + ' value = ' + v); }
JavaScript
/** * */ function gugudaninit() { var d = document.frm.dan; document.getElementById("btngu").onclick=function() { if(d.value=='') { alret("빈칸이군요!!"); d.focus(); } else { document.frm.submit(); } } }
JavaScript
/** * 4칙연산 */ function iftest4() { /*btn 버튼에 클릭되면*/ var b = document.getElementById('btn') b.onclick=function() { var f=document.frm; var s1=Number(f.su1.value); var s2=Number(f.su2.value); var op=f.oper.value; var r=0; if(op=='+') { r=s1+s2; } else if(op=='-') { r=s1+s2; } else if(op=='*') { r=s1+s2; } else if(op=='/') { r=s1+s2; } else { alert("연산자를 쫌 ..."); return; } alert(r); } }
JavaScript
/** * 홀짝수 판별 */ function iftest3() { /*btn 버튼에 클릭되면*/ var b = document.getElementById('btn') b.onclick=function() { var f=document.frm; var s=Number(f.su.value); if(s%2==0) { alert(s+"는 짝수입니다."); } else { alert(s+"는 홀수입니다."); } } }
JavaScript
/** * 점수관리를 위한 스크립트 * date : 2014.11.3 * 작성자 : kyun */ //var btnlist, btninput, btnview, btnmodify, btndelete; var url='index.jsp?inc=../score/'; function general() { btnlist=document.getElementById('btnlist'); if(btnlist!=null) { btnlist.onclick=function() { var frm=document.hiddenFrm; frm.action=url+'list.jsp'; frm.submit(); } } btninput=document.getElementById('btninput'); if(btninput!=null) { btninput.onclick=function() { var frm=document.hiddenfrm; frm.action=url+'input.jsp'; frm.submit(); //location.href=url+'input.jsp'; } } btnview=document.getElementById('btnview'); if(btnview!=null) { btnview.onclick=function() { location.href=url+'view.jsp'; } } btnmodify=document.getElementById('btnmodify'); if(btnmodify!=null) { btnmodify.onclick=function() { location.href=url+'modify.jsp'; } } btndelete=document.getElementById('btndelete'); if(btndelete!=null) { btndelete.onclick=function() { var b = confirm("정말 ?!!"); if(b) { var rno=document.hiddenFrm.rno.value; location.href=url+'delete_result.jsp&rno='+rno; } else { alert("그래~ 삭제하지마..ㅋㅋ"); } } } } function saveda() { document.getElementById('btnsave').onclick=function() { if(document.getElementById('btnsave')!=null) { var f= document.frm; if(f.mid.value=='') { alert('아이디입력 ㄱㄱ'); f.mid.focus(); } else { f.submit(); } } } } function goPage(page){ var mf = document.hiddenfrm; mf.nowPage.value = page; mf.find.value = document.score_list_frm.find.value; mf.action = 'index.jsp?inc=../score/list.jsp'; mf.submit(); //alert(page); //location.href=url + 'view.jsp&page=' + page; } function goview(page, rno) { var mf = document.hiddenfrm; mf.nowPage.value = page; mf.rno.value=rno; mf.find.value = document.score_list_frm.find.value; mf.action = 'index.jsp?inc=../score/view.jsp'; mf.submit(); } function deleteinit() { general(); } function inputinit() { general(); saveda(); } function listinit() { general(); } function modifyinit() { general(); saveda(); } function viewinit() { general(); }
JavaScript
/** * */ function iftest2() { /*btn 버튼에 클릭되면*/ var b = document.getElementById('btn') b.onclick=function() { var f=document.frm; var s1=Number(f.su1.value); var s2=Number(f.su2.value); var tot=s1+s2; var avg=tot/2; alert("합 : "+tot+"\n평균 : "+avg); } }
JavaScript
/** * */ function init() { document.getElementById('but1').onclick=coFunc; document.getElementById('but2').onclick=deFunc; } function coFunc() { var f = document.frm; f.tar.value=f.ori.value; } function deFunc() { var f = document.frm; f.ori.value=''; f.tar.value=''; f.ori.focus(); }
JavaScript