code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* For FCKeditor 2.3
*
*
* File Name: ja.js
* Japanese language file for the youtube plugin.
*
* File Authors:
* Uprush (uprushworld@yahoo.co.jp) 2007/10/30
*/
FCKLang['YouTubeTip'] = 'YouTube挿入/編集' ;
FCKLang['DlgYouTubeTitle'] = 'YouTubeプロパティ' ;
FCKLang['DlgYouTubeCode'] = 'URLを挿入してください。' ;
FCKLang['DlgYouTubeSecurity'] = 'URLが正しくありません。' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = '幅' ;
FCKLang['DlgYouTubeHeight'] = '縦' ;
FCKLang['DlgYouTubeQuality'] = '画質' ;
FCKLang['DlgYouTubeLow'] = '低' ;
FCKLang['DlgYouTubeHigh'] = '高(可能であれば)' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: en.js
* English language file for the youtube plugin.
*
* File Authors:
* Uprush (uprushworld@yahoo.co.jp) 2007/10/30
*/
FCKLang['YouTubeTip'] = 'Insert/Edit YouTube' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube Property' ;
FCKLang['DlgYouTubeCode'] = '"Please insert the URL of YouTube videos."' ;
FCKLang['DlgYouTubeSecurity'] = 'Invalid URL.' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = 'Width' ;
FCKLang['DlgYouTubeHeight'] = 'Height' ;
FCKLang['DlgYouTubeQuality'] = 'Quality' ;
FCKLang['DlgYouTubeLow'] = 'Low' ;
FCKLang['DlgYouTubeHigh'] = 'High (If available)' ;
| JavaScript |
// Register the related commands.
FCKCommands.RegisterCommand( 'YouTube', new FCKDialogCommand( FCKLang['DlgYouTubeTitle'], FCKLang['DlgYouTubeTitle'], FCKConfig.PluginsPath + 'youtube/youtube.html', 450, 350 ) ) ;
// Create the "YouTube" toolbar button.
var oFindItem = new FCKToolbarButton( 'YouTube', FCKLang['YouTubeTip'] ) ;
oFindItem.IconPath = FCKConfig.PluginsPath + 'youtube/youtube.gif' ;
FCKToolbarItems.RegisterItem( 'YouTube', oFindItem ) ; // 'YouTube' is the name used in the Toolbar config.
| JavaScript |
CKEDITOR.plugins.add('pyroimages',
{
requires: ['iframedialog'],
init : function(editor)
{
CKEDITOR.dialog.addIframe('pyroimage_dialog', 'Image', BASE_URI + 'mod_file_manager/image_manager_editor/index',800,400)
editor.addCommand('pyroimages', {exec:pyroimage_onclick});
editor.ui.addButton('pyroimages',{ label:'Upload or insert images from library', command:'pyroimages', icon:this.path+'images/icon.png' });
editor.on('selectionChange', function(evt)
{
/*
* Despite our initial hope, document.queryCommandEnabled() does not work
* for this in Firefox. So we must detect the state by element paths.
*/
var command = editor.getCommand('pyroimages'),
element = evt.data.path.lastElement.getAscendant('img', true);
// If nothing or a valid document
if ( ! element || (element.getName() == 'img' && element.hasClass('pyro-image')))
{
command.setState(CKEDITOR.TRISTATE_OFF);
}
else
{
command.setState(CKEDITOR.TRISTATE_DISABLED);
}
});
}
});
function pyroimage_onclick(e)
{
update_instance();
// run when pyro button is clicked]
CKEDITOR.currentInstance.openDialog('pyroimage_dialog')
} | JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('uicolor',{requires:['dialog'],lang:['en'],init:function(a){if(CKEDITOR.env.ie6Compat)return;a.addCommand('uicolor',new CKEDITOR.dialogCommand('uicolor'));a.ui.addButton('UIColor',{label:a.lang.uicolor.title,command:'uicolor',icon:this.path+'uicolor.gif'});CKEDITOR.dialog.add('uicolor',this.path+'dialogs/uicolor.js');CKEDITOR.scriptLoader.load(CKEDITOR.getUrl('plugins/uicolor/yui/yui.js'));a.element.getDocument().appendStyleSheet(CKEDITOR.getUrl('plugins/uicolor/yui/assets/yui.css'));}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
CKEDITOR.plugins.add('pyrofiles',
{
init : function(editor)
{
// Add the link and unlink buttons.
CKEDITOR.dialog.addIframe('pyrofiles_dialog', 'Files', BASE_URI + 'index.php/admin/wysiwyg/files',700,400);
editor.addCommand('pyrofiles', {exec:pyrofiles_onclick} );
editor.ui.addButton('pyrofiles',{ label:'Upload or insert files from library.', command:'pyrofiles', icon:this.path+'images/icon.png' });
// Register selection change handler for the unlink button.
editor.on( 'selectionChange', function( evt )
{
/*
* Despite our initial hope, files.queryCommandEnabled() does not work
* for this in Firefox. So we must detect the state by element paths.
*/
var command = editor.getCommand( 'pyrofiles' ),
element = evt.data.path.lastElement.getAscendant( 'a', true );
// If nothing or a valid files
if ( ! element || (element.getName() == 'a' && ! element.hasClass('pyro-files')))
{
command.setState(CKEDITOR.TRISTATE_OFF);
}
else
{
command.setState(CKEDITOR.TRISTATE_DISABLED);
}
});
}
} );
function pyrofiles_onclick(e)
{
update_instance();
// run when pyro button is clicked]
CKEDITOR.currentInstance.openDialog('pyrofiles_dialog')
} | JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
};
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.4',revision:'5825',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf('://')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf('://')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
if ( CKEDITOR.loader )
CKEDITOR.loader.load( 'core/ckeditor' );
else
{
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
}
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.4',revision:'5825',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf('://')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf('://')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor_basic';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
| JavaScript |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Dutch language.
*/
/**#@+
@type String
@example
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['nl'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'ltr',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'Tekstverwerker, %1, druk op ALT 0 voor hulp.',
// ARIA descriptions.
toolbar : 'Werkbalk',
editor : 'Tekstverwerker',
// Toolbar buttons without dialogs.
source : 'Code',
newPage : 'Nieuwe pagina',
save : 'Opslaan',
preview : 'Voorbeeld',
cut : 'Knippen',
copy : 'Kopiëren',
paste : 'Plakken',
print : 'Printen',
underline : 'Onderstreept',
bold : 'Vet',
italic : 'Schuingedrukt',
selectAll : 'Alles selecteren',
removeFormat : 'Opmaak verwijderen',
strike : 'Doorhalen',
subscript : 'Subscript',
superscript : 'Superscript',
horizontalrule : 'Horizontale lijn invoegen',
pagebreak : 'Pagina-einde invoegen',
unlink : 'Link verwijderen',
undo : 'Ongedaan maken',
redo : 'Opnieuw uitvoeren',
// Common messages and labels.
common :
{
browseServer : 'Bladeren op server',
url : 'URL',
protocol : 'Protocol',
upload : 'Upload',
uploadSubmit : 'Naar server verzenden',
image : 'Afbeelding',
flash : 'Flash',
form : 'Formulier',
checkbox : 'Aanvinkvakje',
radio : 'Selectievakje',
textField : 'Tekstveld',
textarea : 'Tekstvak',
hiddenField : 'Verborgen veld',
button : 'Knop',
select : 'Selectieveld',
imageButton : 'Afbeeldingsknop',
notSet : '<niet ingevuld>',
id : 'Kenmerk',
name : 'Naam',
langDir : 'Schrijfrichting',
langDirLtr : 'Links naar rechts (LTR)',
langDirRtl : 'Rechts naar links (RTL)',
langCode : 'Taalcode',
longDescr : 'Lange URL-omschrijving',
cssClass : 'Stylesheet-klassen',
advisoryTitle : 'Aanbevolen titel',
cssStyle : 'Stijl',
ok : 'OK',
cancel : 'Annuleren',
close : 'Sluiten',
preview : 'Voorbeeld',
generalTab : 'Algemeen',
advancedTab : 'Geavanceerd',
validateNumberFailed : 'Deze waarde is geen geldig getal.',
confirmNewPage : 'Alle aangebrachte wijzigingen gaan verloren. Weet u zeker dat u een nieuwe pagina wilt openen?',
confirmCancel : 'Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?',
options : 'Opties',
target : 'Doel',
targetNew : 'Nieuw venster (_blank)',
targetTop : 'Hele venster (_top)',
targetSelf : 'Zelfde venster (_self)',
targetParent : 'Origineel venster (_parent)',
langDirLTR : 'Links naar rechts (LTR)',
langDirRTL : 'Rechts naar links (RTL)',
styles : 'Stijlen',
cssClasses : 'Stylesheet klassen',
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, niet beschikbaar</span>'
},
contextmenu :
{
options : 'Context menu opties'
},
// Special char dialog.
specialChar :
{
toolbar : 'Speciaal teken invoegen',
title : 'Selecteer speciaal teken',
options : 'Speciale tekens opties'
},
// Link dialog.
link :
{
toolbar : 'Link invoegen/wijzigen',
other : '<ander>',
menu : 'Link wijzigen',
title : 'Link',
info : 'Linkomschrijving',
target : 'Doel',
upload : 'Upload',
advanced : 'Geavanceerd',
type : 'Linktype',
toUrl : 'URL',
toAnchor : 'Interne link in pagina',
toEmail : 'E-mail',
targetFrame : '<frame>',
targetPopup : '<popup window>',
targetFrameName : 'Naam doelframe',
targetPopupName : 'Naam popupvenster',
popupFeatures : 'Instellingen popupvenster',
popupResizable : 'Herschaalbaar',
popupStatusBar : 'Statusbalk',
popupLocationBar: 'Locatiemenu',
popupToolbar : 'Menubalk',
popupMenuBar : 'Menubalk',
popupFullScreen : 'Volledig scherm (IE)',
popupScrollBars : 'Schuifbalken',
popupDependent : 'Afhankelijk (Netscape)',
popupWidth : 'Breedte',
popupLeft : 'Positie links',
popupHeight : 'Hoogte',
popupTop : 'Positie boven',
id : 'Id',
langDir : 'Schrijfrichting',
langDirLTR : 'Links naar rechts (LTR)',
langDirRTL : 'Rechts naar links (RTL)',
acccessKey : 'Toegangstoets',
name : 'Naam',
langCode : 'Schrijfrichting',
tabIndex : 'Tabvolgorde',
advisoryTitle : 'Aanbevolen titel',
advisoryContentType : 'Aanbevolen content-type',
cssClasses : 'Stylesheet-klassen',
charset : 'Karakterset van gelinkte bron',
styles : 'Stijl',
selectAnchor : 'Kies een interne link',
anchorName : 'Op naam interne link',
anchorId : 'Op kenmerk interne link',
emailAddress : 'E-mailadres',
emailSubject : 'Onderwerp bericht',
emailBody : 'Inhoud bericht',
noAnchors : '(Geen interne links in document gevonden)',
noUrl : 'Geef de link van de URL',
noEmail : 'Geef een e-mailadres'
},
// Anchor dialog
anchor :
{
toolbar : 'Interne link',
menu : 'Eigenschappen interne link',
title : 'Eigenschappen interne link',
name : 'Naam interne link',
errorName : 'Geef de naam van de interne link op'
},
// List style dialog
list:
{
numberedTitle : 'Eigenschappen genummerde lijst',
bulletedTitle : 'Eigenschappen lijst met opsommingstekens',
type : 'Type',
start : 'Start',
validateStartNumber :'Starnummer van de lijst moet een heel nummer zijn.',
circle : 'Cirkel',
disc : 'Schijf',
square : 'Vierkant',
none : 'Geen',
notset : '<niet gezet>',
armenian : 'Armeense numering',
georgian : 'Greorgische numering (an, ban, gan, etc.)',
lowerRoman : 'Romeins kleine letters (i, ii, iii, iv, v, etc.)',
upperRoman : 'Romeins hoofdletters (I, II, III, IV, V, etc.)',
lowerAlpha : 'Kleine letters (a, b, c, d, e, etc.)',
upperAlpha : 'Hoofdletters (A, B, C, D, E, etc.)',
lowerGreek : 'Grieks kleine letters (alpha, beta, gamma, etc.)',
decimal : 'Cijfers (1, 2, 3, etc.)',
decimalLeadingZero : 'Cijfers beginnen met nul (01, 02, 03, etc.)'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'Zoeken en vervangen',
find : 'Zoeken',
replace : 'Vervangen',
findWhat : 'Zoeken naar:',
replaceWith : 'Vervangen met:',
notFoundMsg : 'De opgegeven tekst is niet gevonden.',
matchCase : 'Hoofdlettergevoelig',
matchWord : 'Hele woord moet voorkomen',
matchCyclic : 'Doorlopend zoeken',
replaceAll : 'Alles vervangen',
replaceSuccessMsg : '%1 resulaten vervangen.'
},
// Table Dialog
table :
{
toolbar : 'Tabel',
title : 'Eigenschappen tabel',
menu : 'Eigenschappen tabel',
deleteTable : 'Tabel verwijderen',
rows : 'Rijen',
columns : 'Kolommen',
border : 'Breedte rand',
align : 'Uitlijning',
alignLeft : 'Links',
alignCenter : 'Centreren',
alignRight : 'Rechts',
width : 'Breedte',
widthPx : 'pixels',
widthPc : 'procent',
widthUnit : 'eenheid breedte',
height : 'Hoogte',
cellSpace : 'Afstand tussen cellen',
cellPad : 'Ruimte in de cel',
caption : 'Naam',
summary : 'Samenvatting',
headers : 'Koppen',
headersNone : 'Geen',
headersColumn : 'Eerste kolom',
headersRow : 'Eerste rij',
headersBoth : 'Beide',
invalidRows : 'Het aantal rijen moet een getal zijn groter dan 0.',
invalidCols : 'Het aantal kolommen moet een getal zijn groter dan 0.',
invalidBorder : 'De rand breedte moet een getal zijn.',
invalidWidth : 'De tabel breedte moet een getal zijn.',
invalidHeight : 'De tabel hoogte moet een getal zijn.',
invalidCellSpacing : 'Afstand tussen cellen moet een getal zijn.',
invalidCellPadding : 'Ruimte in de cel moet een getal zijn.',
cell :
{
menu : 'Cel',
insertBefore : 'Voeg cel in voor',
insertAfter : 'Voeg cel in achter',
deleteCell : 'Cellen verwijderen',
merge : 'Cellen samenvoegen',
mergeRight : 'Voeg samen naar rechts',
mergeDown : 'Voeg samen naar beneden',
splitHorizontal : 'Splits cellen horizontaal',
splitVertical : 'Splits cellen verticaal',
title : 'Cel eigenschappen',
cellType : 'Cel type',
rowSpan : 'Rijen samenvoegen',
colSpan : 'Kolommen samenvoegen',
wordWrap : 'Automatische terugloop',
hAlign : 'Horizontale uitlijning',
vAlign : 'Verticale uitlijning',
alignTop : 'Boven',
alignMiddle : 'Midden',
alignBottom : 'Onder',
alignBaseline : 'Basislijn',
bgColor : 'Achtergrondkleur',
borderColor : 'Kleur rand',
data : 'Inhoud',
header : 'Kop',
yes : 'Ja',
no : 'Nee',
invalidWidth : 'De celbreedte moet een getal zijn.',
invalidHeight : 'De celhoogte moet een getal zijn.',
invalidRowSpan : 'Rijen samenvoegen moet een heel getal zijn.',
invalidColSpan : 'Kolommen samenvoegen moet een heel getal zijn.',
chooseColor : 'Kies'
},
row :
{
menu : 'Rij',
insertBefore : 'Voeg rij in voor',
insertAfter : 'Voeg rij in achter',
deleteRow : 'Rijen verwijderen'
},
column :
{
menu : 'Kolom',
insertBefore : 'Voeg kolom in voor',
insertAfter : 'Voeg kolom in achter',
deleteColumn : 'Kolommen verwijderen'
}
},
// Button Dialog.
button :
{
title : 'Eigenschappen knop',
text : 'Tekst (waarde)',
type : 'Soort',
typeBtn : 'Knop',
typeSbm : 'Versturen',
typeRst : 'Leegmaken'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'Eigenschappen aanvinkvakje',
radioTitle : 'Eigenschappen selectievakje',
value : 'Waarde',
selected : 'Geselecteerd'
},
// Form Dialog.
form :
{
title : 'Eigenschappen formulier',
menu : 'Eigenschappen formulier',
action : 'Actie',
method : 'Methode',
encoding : 'Codering'
},
// Select Field Dialog.
select :
{
title : 'Eigenschappen selectieveld',
selectInfo : 'Informatie',
opAvail : 'Beschikbare opties',
value : 'Waarde',
size : 'Grootte',
lines : 'Regels',
chkMulti : 'Gecombineerde selecties toestaan',
opText : 'Tekst',
opValue : 'Waarde',
btnAdd : 'Toevoegen',
btnModify : 'Wijzigen',
btnUp : 'Omhoog',
btnDown : 'Omlaag',
btnSetValue : 'Als geselecteerde waarde instellen',
btnDelete : 'Verwijderen'
},
// Textarea Dialog.
textarea :
{
title : 'Eigenschappen tekstvak',
cols : 'Kolommen',
rows : 'Rijen'
},
// Text Field Dialog.
textfield :
{
title : 'Eigenschappen tekstveld',
name : 'Naam',
value : 'Waarde',
charWidth : 'Breedte (tekens)',
maxChars : 'Maximum aantal tekens',
type : 'Soort',
typeText : 'Tekst',
typePass : 'Wachtwoord'
},
// Hidden Field Dialog.
hidden :
{
title : 'Eigenschappen verborgen veld',
name : 'Naam',
value : 'Waarde'
},
// Image Dialog.
image :
{
title : 'Eigenschappen afbeelding',
titleButton : 'Eigenschappen afbeeldingsknop',
menu : 'Eigenschappen afbeelding',
infoTab : 'Informatie afbeelding',
btnUpload : 'Naar server verzenden',
upload : 'Upload',
alt : 'Alternatieve tekst',
width : 'Breedte',
height : 'Hoogte',
lockRatio : 'Afmetingen vergrendelen',
unlockRatio : 'Afmetingen ontgrendelen',
resetSize : 'Afmetingen resetten',
border : 'Rand',
hSpace : 'HSpace',
vSpace : 'VSpace',
align : 'Uitlijning',
alignLeft : 'Links',
alignRight : 'Rechts',
alertUrl : 'Geef de URL van de afbeelding',
linkTab : 'Link',
button2Img : 'Wilt u de geselecteerde afbeeldingsknop vervangen door een eenvoudige afbeelding?',
img2Button : 'Wilt u de geselecteerde afbeelding vervangen door een afbeeldingsknop?',
urlMissing : 'De URL naar de afbeelding ontbreekt.',
validateWidth : 'Breedte moet een heel nummer zijn.',
validateHeight : 'Hoogte moet een heel nummer zijn.',
validateBorder : 'Rand moet een heel nummer zijn.',
validateHSpace : 'HSpace moet een heel nummer zijn.',
validateVSpace : 'VSpace moet een heel nummer zijn.'
},
// Flash Dialog
flash :
{
properties : 'Eigenschappen Flash',
propertiesTab : 'Eigenschappen',
title : 'Eigenschappen Flash',
chkPlay : 'Automatisch afspelen',
chkLoop : 'Herhalen',
chkMenu : 'Flashmenu\'s inschakelen',
chkFull : 'Schermvullend toestaan',
scale : 'Schaal',
scaleAll : 'Alles tonen',
scaleNoBorder : 'Geen rand',
scaleFit : 'Precies passend',
access : 'Script toegang',
accessAlways : 'Altijd',
accessSameDomain: 'Zelfde domeinnaam',
accessNever : 'Nooit',
align : 'Uitlijning',
alignLeft : 'Links',
alignAbsBottom : 'Absoluut-onder',
alignAbsMiddle : 'Absoluut-midden',
alignBaseline : 'Basislijn',
alignBottom : 'Beneden',
alignMiddle : 'Midden',
alignRight : 'Rechts',
alignTextTop : 'Boven tekst',
alignTop : 'Boven',
quality : 'Kwaliteit',
qualityBest : 'Beste',
qualityHigh : 'Hoog',
qualityAutoHigh : 'Automatisch hoog',
qualityMedium : 'Gemiddeld',
qualityAutoLow : 'Automatisch laag',
qualityLow : 'Laag',
windowModeWindow: 'Venster',
windowModeOpaque: 'Ondoorzichtig',
windowModeTransparent : 'Doorzichtig',
windowMode : 'Venster modus',
flashvars : 'Variabelen voor Flash',
bgcolor : 'Achtergrondkleur',
width : 'Breedte',
height : 'Hoogte',
hSpace : 'HSpace',
vSpace : 'VSpace',
validateSrc : 'Geef de link van de URL',
validateWidth : 'De breedte moet een getal zijn.',
validateHeight : 'De hoogte moet een getal zijn.',
validateHSpace : 'De HSpace moet een getal zijn.',
validateVSpace : 'De VSpace moet een getal zijn.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'Spellingscontrole',
title : 'Spellingscontrole',
notAvailable : 'Excuses, deze dienst is momenteel niet beschikbaar.',
errorLoading : 'Er is een fout opgetreden bij het laden van de diesnt: %s.',
notInDic : 'Niet in het woordenboek',
changeTo : 'Wijzig in',
btnIgnore : 'Negeren',
btnIgnoreAll : 'Alles negeren',
btnReplace : 'Vervangen',
btnReplaceAll : 'Alles vervangen',
btnUndo : 'Ongedaan maken',
noSuggestions : '-Geen suggesties-',
progress : 'Bezig met spellingscontrole...',
noMispell : 'Klaar met spellingscontrole: geen fouten gevonden',
noChanges : 'Klaar met spellingscontrole: geen woorden aangepast',
oneChange : 'Klaar met spellingscontrole: één woord aangepast',
manyChanges : 'Klaar met spellingscontrole: %1 woorden aangepast',
ieSpellDownload : 'De spellingscontrole niet geïnstalleerd. Wilt u deze nu downloaden?'
},
smiley :
{
toolbar : 'Smiley',
title : 'Smiley invoegen',
options : 'Smiley opties'
},
elementsPath :
{
eleLabel : 'Elementenpad',
eleTitle : '%1 element'
},
numberedlist : 'Genummerde lijst',
bulletedlist : 'Opsomming',
indent : 'Inspringen vergroten',
outdent : 'Inspringen verkleinen',
justify :
{
left : 'Links uitlijnen',
center : 'Centreren',
right : 'Rechts uitlijnen',
block : 'Uitvullen'
},
blockquote : 'Citaatblok',
clipboard :
{
title : 'Plakken',
cutError : 'De beveiligingsinstelling van de browser verhinderen het automatisch knippen. Gebruik de sneltoets Ctrl/Cmd+X van het toetsenbord.',
copyError : 'De beveiligingsinstelling van de browser verhinderen het automatisch kopiëren. Gebruik de sneltoets Ctrl/Cmd+C van het toetsenbord.',
pasteMsg : 'Plak de tekst in het volgende vak gebruik makend van uw toetsenbord (<strong>Ctrl/Cmd+V</strong>) en klik op <strong>OK</strong>.',
securityMsg : 'Door de beveiligingsinstellingen van uw browser is het niet mogelijk om direct vanuit het klembord in de editor te plakken. Middels opnieuw plakken in dit venster kunt u de tekst alsnog plakken in de editor.',
pasteArea : 'Plakgebied'
},
pastefromword :
{
confirmCleanup : 'De tekst die u plakte lijkt gekopieerd te zijn vanuit Word. Wilt u de tekst opschonen voordat deze geplakt wordt?',
toolbar : 'Plakken als Word-gegevens',
title : 'Plakken als Word-gegevens',
error : 'Het was niet mogelijk om de geplakte tekst op te schonen door een interne fout'
},
pasteText :
{
button : 'Plakken als platte tekst',
title : 'Plakken als platte tekst'
},
templates :
{
button : 'Sjablonen',
title : 'Inhoud sjabonen',
options : 'Template opties',
insertOption : 'Vervang de huidige inhoud',
selectPromptMsg : 'Selecteer het sjabloon dat in de editor geopend moet worden (de actuele inhoud gaat verloren):',
emptyListMsg : '(Geen sjablonen gedefinieerd)'
},
showBlocks : 'Toon blokken',
stylesCombo :
{
label : 'Stijl',
panelTitle : 'Opmaakstijlen',
panelTitle1 : 'Blok stijlen',
panelTitle2 : 'In-line stijlen',
panelTitle3 : 'Object stijlen'
},
format :
{
label : 'Opmaak',
panelTitle : 'Opmaak',
tag_p : 'Normaal',
tag_pre : 'Met opmaak',
tag_address : 'Adres',
tag_h1 : 'Kop 1',
tag_h2 : 'Kop 2',
tag_h3 : 'Kop 3',
tag_h4 : 'Kop 4',
tag_h5 : 'Kop 5',
tag_h6 : 'Kop 6',
tag_div : 'Normaal (DIV)'
},
div :
{
title : 'Div aanmaken',
toolbar : 'Div aanmaken',
cssClassInputLabel : 'Stylesheet klassen',
styleSelectLabel : 'Stijl',
IdInputLabel : 'Id',
languageCodeInputLabel : ' Taalcode',
inlineStyleInputLabel : 'Inline stijl',
advisoryTitleInputLabel : 'informatieve titel',
langDirLabel : 'Schrijfrichting',
langDirLTRLabel : 'Links naar rechts (LTR)',
langDirRTLLabel : 'Rechts naar links (RTL)',
edit : 'Div wijzigen',
remove : 'Div verwijderen'
},
font :
{
label : 'Lettertype',
voiceLabel : 'Lettertype',
panelTitle : 'Lettertype'
},
fontSize :
{
label : 'Lettergrootte',
voiceLabel : 'Lettergrootte',
panelTitle : 'Lettergrootte'
},
colorButton :
{
textColorTitle : 'Tekstkleur',
bgColorTitle : 'Achtergrondkleur',
panelTitle : 'Kleuren',
auto : 'Automatisch',
more : 'Meer kleuren...'
},
colors :
{
'000' : 'Zwart',
'800000' : 'Kastanjebruin',
'8B4513' : 'Chocoladebruin',
'2F4F4F' : 'Donkerleigrijs',
'008080' : 'Blauwgroen',
'000080' : 'Marine',
'4B0082' : 'Indigo',
'696969' : 'Donkergrijs',
'B22222' : 'Baksteen',
'A52A2A' : 'Bruin',
'DAA520' : 'Donkergeel',
'006400' : 'Donkergroen',
'40E0D0' : 'Turquoise',
'0000CD' : 'Middenblauw',
'800080' : 'Paars',
'808080' : 'Grijs',
'F00' : 'Rood',
'FF8C00' : 'Donkeroranje',
'FFD700' : 'Goud',
'008000' : 'Groen',
'0FF' : 'Cyaan',
'00F' : 'Blauw',
'EE82EE' : 'Violet',
'A9A9A9' : 'Donkergrijs',
'FFA07A' : 'Lichtzalm',
'FFA500' : 'Oranje',
'FFFF00' : 'Geel',
'00FF00' : 'Felgroen',
'AFEEEE' : 'Lichtturquoise',
'ADD8E6' : 'Lichtblauw',
'DDA0DD' : 'Pruim',
'D3D3D3' : 'Lichtgrijs',
'FFF0F5' : 'Linnen',
'FAEBD7' : 'Ivoor',
'FFFFE0' : 'Lichtgeel',
'F0FFF0' : 'Honingdauw',
'F0FFFF' : 'Azuur',
'F0F8FF' : 'Licht hemelsblauw',
'E6E6FA' : 'Lavendel',
'FFF' : 'Wit'
},
scayt :
{
title : 'Controleer de spelling tijdens het typen',
opera_title : 'Niet ondersteund door Opera',
enable : 'SCAYT inschakelen',
disable : 'SCAYT uitschakelen',
about : 'Over SCAYT',
toggle : 'SCAYT in/uitschakelen',
options : 'Opties',
langs : 'Talen',
moreSuggestions : 'Meer suggesties',
ignore : 'Negeren',
ignoreAll : 'Alles negeren',
addWord : 'Woord toevoegen',
emptyDic : 'De naam van het woordenboek mag niet leeg zijn.',
optionsTab : 'Opties',
allCaps : 'Negeer woorden helemaal in hoofdletters',
ignoreDomainNames : 'Negeer domeinnamen',
mixedCase : 'Negeer woorden met hoofd- en kleine letters',
mixedWithDigits : 'Negeer woorden met cijfers',
languagesTab : 'Talen',
dictionariesTab : 'Woordenboeken',
dic_field_name : 'Naam woordenboek',
dic_create : 'Aanmaken',
dic_restore : 'Terugzetten',
dic_delete : 'Verwijderen',
dic_rename : 'Hernoemen',
dic_info : 'Initieel wordt het gebruikerswoordenboek opgeslagen in een cookie. Cookies zijn echter beperkt in grootte. Zodra het gebruikerswoordenboek het punt bereikt waarop het niet meer in een cookie opgeslagen kan worden, dan wordt het woordenboek op de server opgeslagen. Om je persoonlijke woordenboek op je eigen server op te slaan, moet je een mapnaam opgeven. Indien je al een woordenboek hebt opgeslagen, typ dan de naam en klik op de Terugzetten knop.',
aboutTab : 'Over'
},
about :
{
title : 'Over CKEditor',
dlgTitle : 'Over CKEditor',
moreInfo : 'Voor licentie informatie, bezoek onze website:',
copy : 'Copyright © $1. Alle rechten voorbehouden.'
},
maximize : 'Maximaliseren',
minimize : 'Minimaliseren',
fakeobjects :
{
anchor : 'Anker',
flash : 'Flash animatie',
div : 'Pagina einde',
unknown : 'Onbekend object'
},
resize : 'Sleep om te herschalen',
colordialog :
{
title : 'Selecteer kleur',
options : 'Kleuropties',
highlight : 'Actief',
selected : 'Geselecteerd',
clear : 'Wissen'
},
toolbarCollapse : 'Werkbalk inklappen',
toolbarExpand : 'Werkbalk uitklappen',
bidi :
{
ltr : 'Schrijfrichting van links naar rechts',
rtl : 'Schrijfrichting van rechts naar links'
}
};
| JavaScript |
var txtbox = new function()
{
var valueold = '';
var newvalue = '';
var id = '';
var flag = true;
function default_value()
{
$('#'+this.divid).html(newvalue) ;
}
function new_value()
{
$('#'+this.divid).html(newvalue) ;
}
return {
divid: '' ,
edit:function(divid, song, chart)
{
this.divid = divid ;
if(flag)
{
valueold = $('#'+divid).html() ;
var str = '<input type="text" name="txtbox_name" id="txtbox_name" value="'+valueold+'" size=15 /><a href="javascript:txtbox.save('+song +','+chart +');"> Save</a>|<a href="javascript:txtbox.cancel();"> Cancel</a>';
$('#'+divid).html(str);
flag = false;
}
},
save:function (song, chart)
{
newvalue = $("#txtbox_name").val() ;
$.post(url+'chart/addvote',{'new_vote':newvalue, 'old_vote':valueold, 'song_id':song, 'chart_id':chart}, function(res)
{
if(res==1)
{
$('#'+txtbox.divid).html(newvalue) ;
}
else
{
$('#'+txtbox.divid).html(valueold) ;
}
});
flag = true ;
},
cancel:function ()
{
$('#'+this.divid).html(valueold) ;
flag = true ;
}
};
}; | JavaScript |
function remove_tip(){
$('#JT').remove()
}
function add_tip(linkId){
title = $("#"+linkId).attr('title');
content = $("#content"+linkId).html();
if(title == false)title=" ";
var de = document.documentElement;
var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var hasArea = w - getAbsoluteLeft(linkId);
var clickElementy = getAbsoluteTop(linkId) + 70; //set y position
$("body").append("<div id='JT' style='width:250px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'>"+content+"</div></div>");//right side
var arrowOffset = getElementWidth(linkId) + 11;
var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
$('#JT').show();
//$('#JT_copy').load(url);
}
function getElementWidth(objectId) {
x = document.getElementById(objectId);
return x.offsetWidth;
}
function getAbsoluteLeft(objectId) {
// Get an object left position from the upper left viewport corner
o = document.getElementById(objectId)
oLeft = o.offsetLeft // Get left position from the parent object
while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
oParent = o.offsetParent // Get parent object reference
oLeft += oParent.offsetLeft // Add parent left position
o = oParent
}
return oLeft
}
function getAbsoluteTop(objectId) {
// Get an object top position from the upper left viewport corner
o = document.getElementById(objectId)
oTop = o.offsetTop // Get top position from the parent object
while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
oParent = o.offsetParent // Get parent object reference
oTop += oParent.offsetTop // Add parent top position
o = oParent
}
return oTop
}
function parseQuery ( query ) {
var Params = new Object ();
if ( ! query ) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) continue;
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
function blockEvents(evt) {
if(evt.target){
evt.preventDefault();
}else{
evt.returnValue = false;
}
} | JavaScript |
// This file is part of the jQuery formatCurrency Plugin.
//
// The jQuery formatCurrency Plugin is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The jQuery formatCurrency Plugin is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the jQuery formatCurrency Plugin. If not, see <http://www.gnu.org/licenses/>.
(function($) {
$.formatCurrency = {};
$.formatCurrency.regions = [];
// default Region is en
$.formatCurrency.regions[''] = {
symbol: '',
positiveFormat: '%s%n',
negativeFormat: '(%s%n)',
decimalSymbol: '.',
digitGroupSymbol: ',',
groupDigits: true
};
$.fn.formatCurrency = function(destination, settings) {
if (arguments.length == 1 && typeof destination !== "string") {
settings = destination;
destination = false;
}
// initialize defaults
var defaults = {
name: "formatCurrency",
colorize: false,
region: '',
global: true,
roundToDecimalPlace: 0, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ...
eventOnDecimalsEntered: false
};
// initialize default region
defaults = $.extend(defaults, $.formatCurrency.regions['']);
// override defaults with settings passed in
settings = $.extend(defaults, settings);
// check for region setting
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function() {
$this = $(this);
// get number
var num = '0';
num = $this[$this.is('input, select, textarea') ? 'val' : 'html']();
//identify '(123)' as a negative number
if (num.search('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
num = num.replace(settings.regex, '');
if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) {
return;
}
if (settings.decimalSymbol != '.') {
num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arithmetic
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (settings.roundToDecimalPlace >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(settings.roundToDecimalPlace); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
if (settings.groupDigits) {
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
}
}
if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
num += settings.decimalSymbol + decimals;
}
// format symbol/negative
var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
var money = format.replace(/%s/g, settings.symbol);
money = money.replace(/%n/g, num);
// setup destination
var $destination = $([]);
if (!destination) {
$destination = $this;
} else {
$destination = $(destination);
}
// set destination
$destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money);
if (
hasDecimals &&
settings.eventOnDecimalsEntered &&
originalDecimals.length > settings.roundToDecimalPlace
) {
$destination.trigger('decimalsEntered', originalDecimals);
}
// colorize
if (settings.colorize) {
$destination.css('color', isPositive ? 'black' : 'red');
}
});
};
// Remove all non numbers from text
$.fn.toNumber = function(settings) {
var defaults = $.extend({
name: "toNumber",
region: '',
global: true
}, $.formatCurrency.regions['']);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function() {
var method = $(this).is('input, select, textarea') ? 'val' : 'html';
$(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, ''));
});
};
// returns the value from the first element as a number
$.fn.asNumber = function(settings) {
var defaults = $.extend({
name: "asNumber",
region: '',
parse: true,
parseType: 'Float',
global: true
}, $.formatCurrency.regions['']);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
settings.parseType = validateParseType(settings.parseType);
var method = $(this).is('input, select, textarea') ? 'val' : 'html';
var num = $(this)[method]();
num = num ? num : "";
num = num.replace('(', '(-');
num = num.replace(settings.regex, '');
if (!settings.parse) {
return num;
}
if (num.length == 0) {
num = '0';
}
if (settings.decimalSymbol != '.') {
num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arthmetic
}
return window['parse' + settings.parseType](num);
};
function getRegionOrCulture(region) {
var regionInfo = $.formatCurrency.regions[region];
if (regionInfo) {
return regionInfo;
}
else {
if (/(\w+)-(\w+)/g.test(region)) {
var culture = region.replace(/(\w+)-(\w+)/g, "$1");
return $.formatCurrency.regions[culture];
}
}
// fallback to extend(null) (i.e. nothing)
return null;
}
function validateParseType(parseType) {
switch (parseType.toLowerCase()) {
case 'int':
return 'Int';
case 'float':
return 'Float';
default:
throw 'invalid parseType';
}
}
function generateRegex(settings) {
if (settings.symbol === '') {
return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
}
else {
var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.');
return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
}
}
})(jQuery); | JavaScript |
/*
* Flexigrid for jQuery - v1.1
*
* Copyright (c) 2008 Paulo P. Marinas (code.google.com/p/flexigrid/)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
*/
(function ($) {
$.addFlex = function (t, p) {
if (t.grid) return false; //return if already exist
p = $.extend({ //apply default properties
height: 200, //default height
width: 'auto', //auto width
striped: true, //apply odd even stripes
novstripe: false,
minwidth: 30, //min width of columns
minheight: 80, //min height of columns
resizable: true, //allow table resizing
url: false, //URL if using data from AJAX
method: 'POST', //data sending method
dataType: 'xml', //type of data for AJAX, either xml or json
errormsg: 'Connection Error',
usepager: false,
nowrap: true,
page: 1, //current page
total: 1, //total pages
useRp: true, //use the results per page select box
rp: 15, //results per page
rpOptions: [10, 15, 20, 30, 50], //allowed per-page values
title: false,
pagestat: 'Displaying {from} to {to} of {total} items',
pagetext: 'Page',
outof: 'of',
findtext: 'Find',
procmsg: 'Processing, please wait ...',
query: '',
qtype: '',
nomsg: 'No items',
minColToggle: 1, //minimum allowed column to be hidden
showToggleBtn: true, //show or hide column toggle popup
hideOnSubmit: true,
autoload: true,
blockOpacity: 0.5,
preProcess: false,
onDragCol: false,
onToggleCol: false,
onChangeSort: false,
onSuccess: false,
onError: false,
onSubmit: false //using a custom populate function
}, p);
$(t).show() //show if hidden
.attr({
cellPadding: 0,
cellSpacing: 0,
border: 0
}) //remove padding and spacing
.removeAttr('width'); //remove width properties
//create grid class
var g = {
hset: {},
rePosDrag: function () {
var cdleft = 0 - this.hDiv.scrollLeft;
if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2);
$(g.cDrag).css({
top: g.hDiv.offsetTop + 1
});
var cdpad = this.cdpad;
$('div', g.cDrag).hide();
$('thead tr:first th:visible', this.hDiv).each(function () {
var n = $('thead tr:first th:visible', g.hDiv).index(this);
var cdpos = parseInt($('div', this).width());
if (cdleft == 0) cdleft -= Math.floor(p.cgwidth / 2);
cdpos = cdpos + cdleft + cdpad;
if (isNaN(cdpos)) {
cdpos = 0;
}
$('div:eq(' + n + ')', g.cDrag).css({
'left': cdpos + 'px'
}).show();
cdleft = cdpos;
});
},
fixHeight: function (newH) {
newH = false;
if (!newH) newH = $(g.bDiv).height();
var hdHeight = $(this.hDiv).height();
$('div', this.cDrag).each(
function () {
$(this).height(newH + hdHeight);
}
);
var nd = parseInt($(g.nDiv).height());
if (nd > newH) $(g.nDiv).height(newH).width(200);
else $(g.nDiv).height('auto').width('auto');
$(g.block).css({
height: newH,
marginBottom: (newH * -1)
});
var hrH = g.bDiv.offsetTop + newH;
if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop;
$(g.rDiv).css({
height: hrH
});
},
dragStart: function (dragtype, e, obj) { //default drag function start
if (dragtype == 'colresize') {//column resize
$(g.nDiv).hide();
$(g.nBtn).hide();
var n = $('div', this.cDrag).index(obj);
var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width();
$(obj).addClass('dragging').siblings().hide();
$(obj).prev().addClass('dragging').show();
this.colresize = {
startX: e.pageX,
ol: parseInt(obj.style.left),
ow: ow,
n: n
};
$('body').css('cursor', 'col-resize');
} else if (dragtype == 'vresize') {//table resize
var hgo = false;
$('body').css('cursor', 'row-resize');
if (obj) {
hgo = true;
$('body').css('cursor', 'col-resize');
}
this.vresize = {
h: p.height,
sy: e.pageY,
w: p.width,
sx: e.pageX,
hgo: hgo
};
} else if (dragtype == 'colMove') {//column header drag
$(g.nDiv).hide();
$(g.nBtn).hide();
this.hset = $(this.hDiv).offset();
this.hset.right = this.hset.left + $('table', this.hDiv).width();
this.hset.bottom = this.hset.top + $('table', this.hDiv).height();
this.dcol = obj;
this.dcoln = $('th', this.hDiv).index(obj);
this.colCopy = document.createElement("div");
this.colCopy.className = "colCopy";
this.colCopy.innerHTML = obj.innerHTML;
if ($.browser.msie) {
this.colCopy.className = "colCopy ie";
}
$(this.colCopy).css({
position: 'absolute',
float: 'left',
display: 'none',
textAlign: obj.align
});
$('body').append(this.colCopy);
$(this.cDrag).hide();
}
$('body').noSelect();
},
dragMove: function (e) {
if (this.colresize) {//column resize
var n = this.colresize.n;
var diff = e.pageX - this.colresize.startX;
var nleft = this.colresize.ol + diff;
var nw = this.colresize.ow + diff;
if (nw > p.minwidth) {
$('div:eq(' + n + ')', this.cDrag).css('left', nleft);
this.colresize.nw = nw;
}
} else if (this.vresize) {//table resize
var v = this.vresize;
var y = e.pageY;
var diff = y - v.sy;
if (!p.defwidth) p.defwidth = p.width;
if (p.width != 'auto' && !p.nohresize && v.hgo) {
var x = e.pageX;
var xdiff = x - v.sx;
var newW = v.w + xdiff;
if (newW > p.defwidth) {
this.gDiv.style.width = newW + 'px';
p.width = newW;
}
}
var newH = v.h + diff;
if ((newH > p.minheight || p.height < p.minheight) && !v.hgo) {
this.bDiv.style.height = newH + 'px';
p.height = newH;
this.fixHeight(newH);
}
v = null;
} else if (this.colCopy) {
$(this.dcol).addClass('thMove').removeClass('thOver');
if (e.pageX > this.hset.right || e.pageX < this.hset.left || e.pageY > this.hset.bottom || e.pageY < this.hset.top) {
//this.dragEnd();
$('body').css('cursor', 'move');
} else {
$('body').css('cursor', 'pointer');
}
$(this.colCopy).css({
top: e.pageY + 10,
left: e.pageX + 20,
display: 'block'
});
}
},
dragEnd: function () {
if (this.colresize) {
var n = this.colresize.n;
var nw = this.colresize.nw;
$('th:visible div:eq(' + n + ')', this.hDiv).css('width', nw);
$('tr', this.bDiv).each(
function () {
$('td:visible div:eq(' + n + ')', this).css('width', nw);
}
);
this.hDiv.scrollLeft = this.bDiv.scrollLeft;
$('div:eq(' + n + ')', this.cDrag).siblings().show();
$('.dragging', this.cDrag).removeClass('dragging');
this.rePosDrag();
this.fixHeight();
this.colresize = false;
} else if (this.vresize) {
this.vresize = false;
} else if (this.colCopy) {
$(this.colCopy).remove();
if (this.dcolt != null) {
if (this.dcoln > this.dcolt) $('th:eq(' + this.dcolt + ')', this.hDiv).before(this.dcol);
else $('th:eq(' + this.dcolt + ')', this.hDiv).after(this.dcol);
this.switchCol(this.dcoln, this.dcolt);
$(this.cdropleft).remove();
$(this.cdropright).remove();
this.rePosDrag();
if (p.onDragCol) {
p.onDragCol(this.dcoln, this.dcolt);
}
}
this.dcol = null;
this.hset = null;
this.dcoln = null;
this.dcolt = null;
this.colCopy = null;
$('.thMove', this.hDiv).removeClass('thMove');
$(this.cDrag).show();
}
$('body').css('cursor', 'default');
$('body').noSelect(false);
},
toggleCol: function (cid, visible) {
var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0];
var n = $('thead th', g.hDiv).index(ncol);
var cb = $('input[value=' + cid + ']', g.nDiv)[0];
if (visible == null) {
visible = ncol.hidden;
}
if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) {
return false;
}
if (visible) {
ncol.hidden = false;
$(ncol).show();
cb.checked = true;
} else {
ncol.hidden = true;
$(ncol).hide();
cb.checked = false;
}
$('tbody tr', t).each(
function () {
if (visible) {
$('td:eq(' + n + ')', this).show();
} else {
$('td:eq(' + n + ')', this).hide();
}
}
);
this.rePosDrag();
if (p.onToggleCol) {
p.onToggleCol(cid, visible);
}
return visible;
},
switchCol: function (cdrag, cdrop) { //switch columns
$('tbody tr', t).each(
function () {
if (cdrag > cdrop) $('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this));
else $('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this));
}
);
//switch order in nDiv
if (cdrag > cdrop) {
$('tr:eq(' + cdrop + ')', this.nDiv).before($('tr:eq(' + cdrag + ')', this.nDiv));
} else {
$('tr:eq(' + cdrop + ')', this.nDiv).after($('tr:eq(' + cdrag + ')', this.nDiv));
}
if ($.browser.msie && $.browser.version < 7.0) {
$('tr:eq(' + cdrop + ') input', this.nDiv)[0].checked = true;
}
this.hDiv.scrollLeft = this.bDiv.scrollLeft;
},
scroll: function () {
this.hDiv.scrollLeft = this.bDiv.scrollLeft;
this.rePosDrag();
},
addData: function (data) { //parse data
if (p.dataType == 'json') {
data = $.extend({rows: [], page: 0, total: 0}, data);
}
if (p.preProcess) {
data = p.preProcess(data);
}
$('.pReload', this.pDiv).removeClass('loading');
this.loading = false;
if (!data) {
$('.pPageStat', this.pDiv).html(p.errormsg);
return false;
}
if (p.dataType == 'xml') {
p.total = +$('rows total', data).text();
} else {
p.total = data.total;
}
if (p.total == 0) {
$('tr, a, td, div', t).unbind();
$(t).empty();
p.pages = 1;
p.page = 1;
this.buildpager();
$('.pPageStat', this.pDiv).html(p.nomsg);
return false;
}
p.pages = Math.ceil(p.total / p.rp);
if (p.dataType == 'xml') {
p.page = +$('rows page', data).text();
} else {
p.page = data.page;
}
this.buildpager();
//build new body
var tbody = document.createElement('tbody');
if (p.dataType == 'json') {
$.each(data.rows, function (i, row) {
var tr = document.createElement('tr');
if (i % 2 && p.striped) {
tr.className = 'erow';
}
if (row.id) {
tr.id = 'row' + row.id;
}
$('thead tr:first th', g.hDiv).each( //add cell
function () {
var td = document.createElement('td');
var idx = $(this).attr('axis').substr(3);
td.align = this.align;
// If the json elements aren't named (which is typical), use numeric order
if (typeof row.cell[idx] != "undefined") {
td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : '';//null-check for Opera-browser
} else {
td.innerHTML = row.cell[p.colModel[idx].name];
}
$(td).attr('abbr', $(this).attr('abbr'));
$(tr).append(td);
td = null;
}
);
if ($('thead', this.gDiv).length < 1) {//handle if grid has no headers
for (idx = 0; idx < cell.length; idx++) {
var td = document.createElement('td');
// If the json elements aren't named (which is typical), use numeric order
if (typeof row.cell[idx] != "undefined") {
td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : '';//null-check for Opera-browser
} else {
td.innerHTML = row.cell[p.colModel[idx].name];
}
$(tr).append(td);
td = null;
}
}
$(tbody).append(tr);
tr = null;
});
} else if (p.dataType == 'xml') {
var i = 1;
$("rows row", data).each(function () {
i++;
var tr = document.createElement('tr');
if (i % 2 && p.striped) {
tr.className = 'erow';
}
var nid = $(this).attr('id');
if (nid) {
tr.id = 'row' + nid;
}
nid = null;
var robj = this;
$('thead tr:first th', g.hDiv).each(function () {
var td = document.createElement('td');
var idx = $(this).attr('axis').substr(3);
td.align = this.align;
td.innerHTML = $("cell:eq(" + idx + ")", robj).text();
$(td).attr('abbr', $(this).attr('abbr'));
$(tr).append(td);
td = null;
});
if ($('thead', this.gDiv).length < 1) {//handle if grid has no headers
$('cell', this).each(function () {
var td = document.createElement('td');
td.innerHTML = $(this).text();
$(tr).append(td);
td = null;
});
}
$(tbody).append(tr);
tr = null;
robj = null;
});
}
$('tr', t).unbind();
$(t).empty();
$(t).append(tbody);
this.addCellProp();
this.addRowProp();
this.rePosDrag();
tbody = null;
data = null;
i = null;
if (p.onSuccess) {
p.onSuccess(this);
}
if (p.hideOnSubmit) {
$(g.block).remove();
}
this.hDiv.scrollLeft = this.bDiv.scrollLeft;
if ($.browser.opera) {
$(t).css('visibility', 'visible');
}
},
changeSort: function (th) { //change sortorder
if (this.loading) {
return true;
}
$(g.nDiv).hide();
$(g.nBtn).hide();
if (p.sortname == $(th).attr('abbr')) {
if (p.sortorder == 'asc') {
p.sortorder = 'desc';
} else {
p.sortorder = 'asc';
}
}
$(th).addClass('sorted').siblings().removeClass('sorted');
$('.sdesc', this.hDiv).removeClass('sdesc');
$('.sasc', this.hDiv).removeClass('sasc');
$('div', th).addClass('s' + p.sortorder);
p.sortname = $(th).attr('abbr');
if (p.onChangeSort) {
p.onChangeSort(p.sortname, p.sortorder);
} else {
this.populate();
}
},
buildpager: function () { //rebuild pager based on new properties
$('.pcontrol input', this.pDiv).val(p.page);
$('.pcontrol span', this.pDiv).html(p.pages);
var r1 = (p.page - 1) * p.rp + 1;
var r2 = r1 + p.rp - 1;
if (p.total < r2) {
r2 = p.total;
}
var stat = p.pagestat;
stat = stat.replace(/{from}/, r1);
stat = stat.replace(/{to}/, r2);
stat = stat.replace(/{total}/, p.total);
$('.pPageStat', this.pDiv).html(stat);
},
populate: function () { //get latest data
if (this.loading) {
return true;
}
if (p.onSubmit) {
var gh = p.onSubmit();
if (!gh) {
return false;
}
}
this.loading = true;
if (!p.url) {
return false;
}
$('.pPageStat', this.pDiv).html(p.procmsg);
$('.pReload', this.pDiv).addClass('loading');
$(g.block).css({
top: g.bDiv.offsetTop
});
if (p.hideOnSubmit) {
$(this.gDiv).prepend(g.block);
}
if ($.browser.opera) {
$(t).css('visibility', 'hidden');
}
if (!p.newp) {
p.newp = 1;
}
if (p.page > p.pages) {
p.page = p.pages;
}
var param = [{
name: 'page',
value: p.newp
}, {
name: 'rp',
value: p.rp
}, {
name: 'sortname',
value: p.sortname
}, {
name: 'sortorder',
value: p.sortorder
}, {
name: 'query',
value: p.query
}, {
name: 'qtype',
value: p.qtype
}];
if (p.params) {
for (var pi = 0; pi < p.params.length; pi++) {
param[param.length] = p.params[pi];
}
}
$.ajax({
type: p.method,
url: p.url,
data: param,
dataType: p.dataType,
success: function (data) {
g.addData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
},
doSearch: function () {
p.query = $('input[name=q]', g.sDiv).val();
p.qtype = $('select[name=qtype]', g.sDiv).val();
p.newp = 1;
this.populate();
},
changePage: function (ctype) { //change page
if (this.loading) {
return true;
}
switch (ctype) {
case 'first':
p.newp = 1;
break;
case 'prev':
if (p.page > 1) {
p.newp = parseInt(p.page) - 1;
}
break;
case 'next':
if (p.page < p.pages) {
p.newp = parseInt(p.page) + 1;
}
break;
case 'last':
p.newp = p.pages;
break;
case 'input':
var nv = parseInt($('.pcontrol input', this.pDiv).val());
if (isNaN(nv)) {
nv = 1;
}
if (nv < 1) {
nv = 1;
} else if (nv > p.pages) {
nv = p.pages;
}
$('.pcontrol input', this.pDiv).val(nv);
p.newp = nv;
break;
}
if (p.newp == p.page) {
return false;
}
if (p.onChangePage) {
p.onChangePage(p.newp);
} else {
this.populate();
}
},
addCellProp: function () {
$('tbody tr td', g.bDiv).each(function () {
var tdDiv = document.createElement('div');
var n = $('td', $(this).parent()).index(this);
var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
if (pth != null) {
if (p.sortname == $(pth).attr('abbr') && p.sortname) {
this.className = 'sorted';
}
$(tdDiv).css({
textAlign: pth.align,
width: $('div:first', pth)[0].style.width
});
if (pth.hidden) {
$(this).css('display', 'none');
}
}
if (p.nowrap == false) {
$(tdDiv).css('white-space', 'normal');
}
if (this.innerHTML == '') {
this.innerHTML = ' ';
}
tdDiv.innerHTML = this.innerHTML;
var prnt = $(this).parent()[0];
var pid = false;
if (prnt.id) {
pid = prnt.id.substr(3);
}
if (pth != null) {
if (pth.process) pth.process(tdDiv, pid);
}
$(this).empty().append(tdDiv).removeAttr('width'); //wrap content
});
},
getCellDim: function (obj) {// get cell prop for editable event
var ht = parseInt($(obj).height());
var pht = parseInt($(obj).parent().height());
var wt = parseInt(obj.style.width);
var pwt = parseInt($(obj).parent().width());
var top = obj.offsetParent.offsetTop;
var left = obj.offsetParent.offsetLeft;
var pdl = parseInt($(obj).css('paddingLeft'));
var pdt = parseInt($(obj).css('paddingTop'));
return {
ht: ht,
wt: wt,
top: top,
left: left,
pdl: pdl,
pdt: pdt,
pht: pht,
pwt: pwt
};
},
addRowProp: function () {
$('tbody tr', g.bDiv).each(function () {
$(this).click(function (e) {
var obj = (e.target || e.srcElement);
if (obj.href || obj.type) return true;
$(this).toggleClass('trSelected');
if (p.singleSelect) $(this).siblings().removeClass('trSelected');
}).mousedown(function (e) {
if (e.shiftKey) {
$(this).toggleClass('trSelected');
g.multisel = true;
this.focus();
$(g.gDiv).noSelect();
}
}).mouseup(function () {
if (g.multisel) {
g.multisel = false;
$(g.gDiv).noSelect(false);
}
}).hover(function (e) {
if (g.multisel) {
$(this).toggleClass('trSelected');
}
}, function () {});
if ($.browser.msie && $.browser.version < 7.0) {
$(this).hover(function () {
$(this).addClass('trOver');
}, function () {
$(this).removeClass('trOver');
});
}
});
},
pager: 0
};
if (p.colModel) { //create model if any
thead = document.createElement('thead');
var tr = document.createElement('tr');
for (var i = 0; i < p.colModel.length; i++) {
var cm = p.colModel[i];
var th = document.createElement('th');
th.innerHTML = cm.display;
if (cm.name && cm.sortable) {
$(th).attr('abbr', cm.name);
}
$(th).attr('axis', 'col' + i);
if (cm.align) {
th.align = cm.align;
}
if (cm.width) {
$(th).attr('width', cm.width);
}
if ($(cm).attr('hide')) {
th.hidden = true;
}
if (cm.process) {
th.process = cm.process;
}
$(tr).append(th);
}
$(thead).append(tr);
$(t).prepend(thead);
} // end if p.colmodel
//init divs
g.gDiv = document.createElement('div'); //create global container
g.mDiv = document.createElement('div'); //create title container
g.hDiv = document.createElement('div'); //create header container
g.bDiv = document.createElement('div'); //create body container
g.vDiv = document.createElement('div'); //create grip
g.rDiv = document.createElement('div'); //create horizontal resizer
g.cDrag = document.createElement('div'); //create column drag
g.block = document.createElement('div'); //creat blocker
g.nDiv = document.createElement('div'); //create column show/hide popup
g.nBtn = document.createElement('div'); //create column show/hide button
g.iDiv = document.createElement('div'); //create editable layer
g.tDiv = document.createElement('div'); //create toolbar
g.sDiv = document.createElement('div');
g.pDiv = document.createElement('div'); //create pager container
if (!p.usepager) {
g.pDiv.style.display = 'none';
}
g.hTable = document.createElement('table');
g.gDiv.className = 'flexigrid';
if (p.width != 'auto') {
g.gDiv.style.width = p.width + 'px';
}
//add conditional classes
if ($.browser.msie) {
$(g.gDiv).addClass('ie');
}
if (p.novstripe) {
$(g.gDiv).addClass('novstripe');
}
$(t).before(g.gDiv);
$(g.gDiv).append(t);
//set toolbar
if (p.buttons) {
g.tDiv.className = 'tDiv';
var tDiv2 = document.createElement('div');
tDiv2.className = 'tDiv2';
for (var i = 0; i < p.buttons.length; i++) {
var btn = p.buttons[i];
if (!btn.separator) {
var btnDiv = document.createElement('div');
btnDiv.className = 'fbutton';
btnDiv.innerHTML = "<div><span>" + btn.name + "</span></div>";
if (btn.bclass) $('span', btnDiv).addClass(btn.bclass).css({
paddingLeft: 20
});
btnDiv.onpress = btn.onpress;
btnDiv.name = btn.name;
if (btn.onpress) {
$(btnDiv).click(function () {
this.onpress(this.name, g.gDiv);
});
}
$(tDiv2).append(btnDiv);
if ($.browser.msie && $.browser.version < 7.0) {
$(btnDiv).hover(function () {
$(this).addClass('fbOver');
}, function () {
$(this).removeClass('fbOver');
});
}
} else {
$(tDiv2).append("<div class='btnseparator'></div>");
}
}
$(g.tDiv).append(tDiv2);
$(g.tDiv).append("<div style='clear:both'></div>");
$(g.gDiv).prepend(g.tDiv);
}
g.hDiv.className = 'hDiv';
$(t).before(g.hDiv);
g.hTable.cellPadding = 0;
g.hTable.cellSpacing = 0;
$(g.hDiv).append('<div class="hDivBox"></div>');
$('div', g.hDiv).append(g.hTable);
var thead = $("thead:first", t).get(0);
if (thead) $(g.hTable).append(thead);
thead = null;
if (!p.colmodel) var ci = 0;
$('thead tr:first th', g.hDiv).each(function () {
var thdiv = document.createElement('div');
if ($(this).attr('abbr')) {
$(this).click(function (e) {
if (!$(this).hasClass('thOver')) return false;
var obj = (e.target || e.srcElement);
if (obj.href || obj.type) return true;
g.changeSort(this);
});
if ($(this).attr('abbr') == p.sortname) {
this.className = 'sorted';
thdiv.className = 's' + p.sortorder;
}
}
if (this.hidden) {
$(this).hide();
}
if (!p.colmodel) {
$(this).attr('axis', 'col' + ci++);
}
$(thdiv).css({
textAlign: this.align,
width: this.width + 'px'
});
thdiv.innerHTML = this.innerHTML;
$(this).empty().append(thdiv).removeAttr('width').mousedown(function (e) {
g.dragStart('colMove', e, this);
}).hover(function () {
if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) {
$(this).addClass('thOver');
}
if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
$('div', this).addClass('s' + p.sortorder);
} else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
$('div', this).removeClass('s' + p.sortorder).addClass('s' + no);
}
if (g.colCopy) {
var n = $('th', g.hDiv).index(this);
if (n == g.dcoln) {
return false;
}
if (n < g.dcoln) {
$(this).append(g.cdropleft);
} else {
$(this).append(g.cdropright);
}
g.dcolt = n;
} else if (!g.colresize) {
var nv = $('th:visible', g.hDiv).index(this);
var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left'));
var nw = jQuery(g.nBtn).outerWidth();
var nl = onl - nw + Math.floor(p.cgwidth / 2);
$(g.nDiv).hide();
$(g.nBtn).hide();
$(g.nBtn).css({
'left': nl,
top: g.hDiv.offsetTop
}).show();
var ndw = parseInt($(g.nDiv).width());
$(g.nDiv).css({
top: g.bDiv.offsetTop
});
if ((nl + ndw) > $(g.gDiv).width()) {
$(g.nDiv).css('left', onl - ndw + 1);
} else {
$(g.nDiv).css('left', nl);
}
if ($(this).hasClass('sorted')) {
$(g.nBtn).addClass('srtd');
} else {
$(g.nBtn).removeClass('srtd');
}
}
}, function () {
$(this).removeClass('thOver');
if ($(this).attr('abbr') != p.sortname) {
$('div', this).removeClass('s' + p.sortorder);
} else if ($(this).attr('abbr') == p.sortname) {
var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
$('div', this).addClass('s' + p.sortorder).removeClass('s' + no);
}
if (g.colCopy) {
$(g.cdropleft).remove();
$(g.cdropright).remove();
g.dcolt = null;
}
}); //wrap content
});
//set bDiv
g.bDiv.className = 'bDiv';
$(t).before(g.bDiv);
$(g.bDiv).css({
height: (p.height == 'auto') ? 'auto' : p.height + "px"
}).scroll(function (e) {
g.scroll()
}).append(t);
if (p.height == 'auto') {
$('table', g.bDiv).addClass('autoht');
}
//add td & row properties
g.addCellProp();
g.addRowProp();
//set cDrag
var cdcol = $('thead tr:first th:first', g.hDiv).get(0);
if (cdcol != null) {
g.cDrag.className = 'cDrag';
g.cdpad = 0;
g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth')));
g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth')));
g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft')));
g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight')));
g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth')));
g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth')));
g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft')));
g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight')));
$(g.bDiv).before(g.cDrag);
var cdheight = $(g.bDiv).height();
var hdheight = $(g.hDiv).height();
$(g.cDrag).css({
top: -hdheight + 'px'
});
$('thead tr:first th', g.hDiv).each(function () {
var cgDiv = document.createElement('div');
$(g.cDrag).append(cgDiv);
if (!p.cgwidth) {
p.cgwidth = $(cgDiv).width();
}
$(cgDiv).css({
height: cdheight + hdheight
}).mousedown(function (e) {
g.dragStart('colresize', e, this);
});
if ($.browser.msie && $.browser.version < 7.0) {
g.fixHeight($(g.gDiv).height());
$(cgDiv).hover(function () {
g.fixHeight();
$(this).addClass('dragging')
}, function () {
if (!g.colresize) $(this).removeClass('dragging')
});
}
});
}
//add strip
if (p.striped) {
$('tbody tr:odd', g.bDiv).addClass('erow');
}
if (p.resizable && p.height != 'auto') {
g.vDiv.className = 'vGrip';
$(g.vDiv).mousedown(function (e) {
g.dragStart('vresize', e)
}).html('<span></span>');
$(g.bDiv).after(g.vDiv);
}
if (p.resizable && p.width != 'auto' && !p.nohresize) {
g.rDiv.className = 'hGrip';
$(g.rDiv).mousedown(function (e) {
g.dragStart('vresize', e, true);
}).html('<span></span>').css('height', $(g.gDiv).height());
if ($.browser.msie && $.browser.version < 7.0) {
$(g.rDiv).hover(function () {
$(this).addClass('hgOver');
}, function () {
$(this).removeClass('hgOver');
});
}
$(g.gDiv).append(g.rDiv);
}
// add pager
if (p.usepager) {
g.pDiv.className = 'pDiv';
g.pDiv.innerHTML = '<div class="pDiv2"></div>';
$(g.bDiv).after(g.pDiv);
var html = ' <div class="pGroup"> <div class="pFirst pButton"><span></span></div><div class="pPrev pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">' + p.pagetext + ' <input type="text" size="4" value="1" /> ' + p.outof + ' <span> 1 </span></span></div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pNext pButton"><span></span></div><div class="pLast pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pReload pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pPageStat"></span></div>';
$('div', g.pDiv).html(html);
$('.pReload', g.pDiv).click(function () {
g.populate()
});
$('.pFirst', g.pDiv).click(function () {
g.changePage('first')
});
$('.pPrev', g.pDiv).click(function () {
g.changePage('prev')
});
$('.pNext', g.pDiv).click(function () {
g.changePage('next')
});
$('.pLast', g.pDiv).click(function () {
g.changePage('last')
});
$('.pcontrol input', g.pDiv).keydown(function (e) {
if (e.keyCode == 13) g.changePage('input')
});
if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function () {
$(this).addClass('pBtnOver');
}, function () {
$(this).removeClass('pBtnOver');
});
if (p.useRp) {
var opt = '',
sel = '';
for (var nx = 0; nx < p.rpOptions.length; nx++) {
if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"';
else sel = '';
opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + " </option>";
}
$('.pDiv2', g.pDiv).prepend("<div class='pGroup'><select name='rp'>" + opt + "</select></div> <div class='btnseparator'></div>");
$('select', g.pDiv).change(function () {
if (p.onRpChange) {
p.onRpChange(+this.value);
} else {
p.newp = 1;
p.rp = +this.value;
g.populate();
}
});
}
//add search button
if (p.searchitems) {
$('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>");
$('.pSearch', g.pDiv).click(function () {
$(g.sDiv).slideToggle('fast', function () {
$('.sDiv:visible input:first', g.gDiv).trigger('focus');
});
});
//add search box
g.sDiv.className = 'sDiv';
var sitems = p.searchitems;
var sopt = '', sel = '';
for (var s = 0; s < sitems.length; s++) {
if (p.qtype == '' && sitems[s].isdefault == true) {
p.qtype = sitems[s].name;
sel = 'selected="selected"';
} else {
sel = '';
}
sopt += "<option value='" + sitems[s].name + "' " + sel + " >" + sitems[s].display + " </option>";
}
if (p.qtype == '') {
p.qtype = sitems[0].name;
}
$(g.sDiv).append("<div class='sDiv2'>" + p.findtext +
" <input type='text' value='" + p.query +"' size='30' name='q' class='qsbox' /> "+
" <select name='qtype'>" + sopt + "</select></div>");
//Split into separate selectors because of bug in jQuery 1.3.2
$('input[name=q]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('select[name=qtype]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('input[value=Clear]', g.sDiv).click(function () {
$('input[name=q]', g.sDiv).val('');
p.query = '';
g.doSearch();
});
$(g.bDiv).after(g.sDiv);
}
}
$(g.pDiv, g.sDiv).append("<div style='clear:both'></div>");
// add title
if (p.title) {
g.mDiv.className = 'mDiv';
g.mDiv.innerHTML = '<div class="ftitle">' + p.title + '</div>';
$(g.gDiv).prepend(g.mDiv);
if (p.showTableToggleBtn) {
$(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>');
$('div.ptogtitle', g.mDiv).click(function () {
$(g.gDiv).toggleClass('hideBody');
$(this).toggleClass('vsble');
});
}
}
//setup cdrops
g.cdropleft = document.createElement('span');
g.cdropleft.className = 'cdropleft';
g.cdropright = document.createElement('span');
g.cdropright.className = 'cdropright';
//add block
g.block.className = 'gBlock';
var gh = $(g.bDiv).height();
var gtop = g.bDiv.offsetTop;
$(g.block).css({
width: g.bDiv.style.width,
height: gh,
background: 'white',
position: 'relative',
marginBottom: (gh * -1),
zIndex: 1,
top: gtop,
left: '0px'
});
$(g.block).fadeTo(0, p.blockOpacity);
// add column control
if ($('th', g.hDiv).length) {
g.nDiv.className = 'nDiv';
g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>";
$(g.nDiv).css({
marginBottom: (gh * -1),
display: 'none',
top: gtop
}).noSelect();
var cn = 0;
$('th div', g.hDiv).each(function () {
var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0];
var chk = 'checked="checked"';
if (kcol.style.display == 'none') {
chk = '';
}
$('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>');
cn++;
});
if ($.browser.msie && $.browser.version < 7.0) $('tr', g.nDiv).hover(function () {
$(this).addClass('ndcolover');
}, function () {
$(this).removeClass('ndcolover');
});
$('td.ndcol2', g.nDiv).click(function () {
if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false;
return g.toggleCol($(this).prev().find('input').val());
});
$('input.togCol', g.nDiv).click(function () {
if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false;
$(this).parent().next().trigger('click');
});
$(g.gDiv).prepend(g.nDiv);
$(g.nBtn).addClass('nBtn')
.html('<div></div>')
.attr('title', 'Hide/Show Columns')
.click(function () {
$(g.nDiv).toggle();
return true;
}
);
if (p.showToggleBtn) {
$(g.gDiv).prepend(g.nBtn);
}
}
// add date edit layer
$(g.iDiv).addClass('iDiv').css({
display: 'none'
});
$(g.bDiv).append(g.iDiv);
// add flexigrid events
$(g.bDiv).hover(function () {
$(g.nDiv).hide();
$(g.nBtn).hide();
}, function () {
if (g.multisel) {
g.multisel = false;
}
});
$(g.gDiv).hover(function () {}, function () {
$(g.nDiv).hide();
$(g.nBtn).hide();
});
//add document events
$(document).mousemove(function (e) {
g.dragMove(e)
}).mouseup(function (e) {
g.dragEnd()
}).hover(function () {}, function () {
g.dragEnd()
});
//browser adjustments
if ($.browser.msie && $.browser.version < 7.0) {
$('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv).css({
width: '100%'
});
$(g.gDiv).addClass('ie6');
if (p.width != 'auto') {
$(g.gDiv).addClass('ie6fullwidthbug');
}
}
g.rePosDrag();
g.fixHeight();
//make grid functions accessible
t.p = p;
t.grid = g;
// load data
if (p.url && p.autoload) {
g.populate();
}
return t;
};
var docloaded = false;
$(document).ready(function () {
docloaded = true
});
$.fn.flexigrid = function (p) {
return this.each(function () {
if (!docloaded) {
$(this).hide();
var t = this;
$(document).ready(function () {
$.addFlex(t, p);
});
} else {
$.addFlex(this, p);
}
});
}; //end flexigrid
$.fn.flexReload = function (p) { // function to reload grid
return this.each(function () {
if (this.grid && this.p.url) this.grid.populate();
});
}; //end flexReload
$.fn.flexOptions = function (p) { //function to update general options
return this.each(function () {
if (this.grid) $.extend(this.p, p);
});
}; //end flexOptions
$.fn.flexToggleCol = function (cid, visible) { // function to reload grid
return this.each(function () {
if (this.grid) this.grid.toggleCol(cid, visible);
});
}; //end flexToggleCol
$.fn.flexAddData = function (data) { // function to add data to grid
return this.each(function () {
if (this.grid) this.grid.addData(data);
});
};
$.fn.noSelect = function (p) { //no select plugin by me :-)
var prevent = (p == null) ? true : p;
if (prevent) {
return this.each(function () {
if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
return false;
});
else if ($.browser.mozilla) {
$(this).css('MozUserSelect', 'none');
$('body').trigger('focus');
} else if ($.browser.opera) $(this).bind('mousedown', function () {
return false;
});
else $(this).attr('unselectable', 'on');
});
} else {
return this.each(function () {
if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
else if ($.browser.opera) $(this).unbind('mousedown');
else $(this).removeAttr('unselectable', 'on');
});
}
}; //end noSelect
})(jQuery); | JavaScript |
(function($){
$.fn.idTabs = function()
{
//Setup Tabs
var ul = $('ul', this); //Save scope
var self = this;
var list = $('li', ul).bind('click', function()
{
var elm = $(this);
// we set selected_section to keep active tab opened after form submit
// we do it for all forms to fix settings_dev situation: forms under tabs
if ($(self).hasClass('cm-track')) {
$('input[name=selected_section]').val(this.id);
}
if (elm.hasClass('cm-js') == false) {
return true;
}
/*if (hndl[$(ul).attr('id')]) {
if (hndl[$(ul).attr('id')](elm.attr('id')) == false) {
return false;
}
}*/
var id = '#content_' + this.id;
var aList = []; //save tabs
var idList = []; //save possible elements
$('li', ul).each(function()
{
if(this.id) {
aList[aList.length] = this;
idList[idList.length] = '#content_' + this.id;
}
});
//Clear tabs, and hide all
for (i in aList) {
$(aList[i]).removeClass('cm-active');
}
for (i in idList) {
$(idList[i]).hide();
}
//Select clicked tab and show content
elm.addClass('cm-active');
// Switch buttons block only if:
// 1. Current tab is in form and this form has cm-toggle-button class on buttons block or current tab does not belong to any form
// 2. Current tab lays on is first-level tab
var id_obj = $(id);
if (($('.cm-toggle-button', id_obj.parents('form')).length > 0 || id_obj.parents('form').length == 0) && id_obj.parents('.cm-tabs-content').length == 1) {
if (id_obj.hasClass('cm-hide-save-button')) {
$('.cm-toggle-button').hide();
} else {
$('.cm-toggle-button').show();
}
}
// Create tab content if it is not exist
if (elm.hasClass('cm-ajax') && id_obj.length == 0) {
$(self).after('<div id="' + id.substr(1) + '"></div>');
id_obj = $(id);
jQuery.ajaxRequest($('a', elm).attr('href'), {result_ids: id.substr(1), callback: [id_obj, 'initTab']});
return false;
} else {
id_obj.initTab();
if (typeof(disable_ajax_preload) == 'undefined' || !disable_ajax_preload) {
//jQuery.loadAjaxLinks($('a.cm-ajax-update', id_obj));
}
}
return false; //Option for changing url
});
//Select default tab
var test;
if ((test = list.filter('.cm-active')).length) {
test.click(); //Select tab with class 'cm-active'
} else {
list.filter(':first').click(); //Select first tab
}
$('li.cm-ajax.cm-js').not('.cm-active').each(function(){
var self = $(this);
if (!self.data('passed') && $('a', self).attr('href')) {
self.data('passed', true);
var id = 'content_' + this.id;
self.parents('.cm-j-tabs').eq(0).next().prepend('<div id="' + id + '"></div>');
$('#' + id).hide();
jQuery.ajaxRequest($('a', self).attr('href'), {result_ids: id, hidden: true, repeat_on_error: true});
}
});
return this; //Chainable
};
$(function(){ $(".cm-j-tabs").each(function(){ $(this).idTabs(); }); });
})(jQuery);
jQuery.fn.extend({
initTab: function ()
{
this.show();
control_buttons_container = $('.buttons-bg');
if (control_buttons_container.length) {
control_buttons_floating = $('.cm-buttons-floating', control_buttons_container);
if (control_buttons_container.length != control_buttons_floating.length) {
control_buttons_container.each(function () {
if (!$('.cm-buttons-floating', this).length) {
if ($('.cm-popup-box', this).length) {
$('.cm-popup-box', this).each(function () {
if ($('iframe', this).length) {
$(this).appendTo(document.body);
} else {
$(this).appendTo($(this).parents('.buttons-bg:first').parent());
}
});
}
$(this).wrapInner('<div class="cm-buttons-placeholder"></div>');
$(this).append('<div class="cm-buttons-floating hidden"></div>');
}
});
control_buttons_container = $('.buttons-bg');
control_buttons_floating = $('.cm-buttons-floating', control_buttons_container);
}
jQuery.buttonsPlaceholderToggle();
}
}
}); | JavaScript |
//Javasript name: My Date Time Picker
//Date created: 16-Nov-2003 23:19
//Creator: TengYong Ng
//Website: http://www.rainforestnet.com
//Copyright (c) 2003 TengYong Ng
//FileName: DateTimePicker_css.js
//Version: 2.2.0
// Note: Permission given to use and modify this script in ANY kind of applications if
// header lines are left unchanged.
//Permission is granted to redistribute and modify this javascript under the terms of the GNU General Public License 3.0.
//New Css style version added by Yvan Lavoie (Québec, Canada) 29-Jan-2009
//Formatted for JSLint compatibility by Labsmedia.com (30-Dec-2010)
//Global variables
var winCal;
var dtToday;
var Cal;
var MonthName;
var WeekDayName1;
var WeekDayName2;
var exDateTime;//Existing Date and Time
var selDate;//selected date. version 1.7
var calSpanID = "calBorder"; // span ID
var domStyle = null; // span DOM object with style
var cnLeft = "0";//left coordinate of calendar span
var cnTop = "0";//top coordinate of calendar span
var xpos = 0; // mouse x position
var ypos = 0; // mouse y position
var calHeight = 0; // calendar height
var CalWidth = 208;// calendar width
var CellWidth = 30;// width of day cell.
var TimeMode = 24;// TimeMode value. 12 or 24
var StartYear = 1940; //First Year in drop down year selection
var EndYear = 5; // The last year of pickable date. if current year is 2011, the last year that still picker will be 2016 (2011+5)
var CalPosOffsetX = -10; //X position offset relative to calendar icon, can be negative value
var CalPosOffsetY = 40; //Y position offset relative to calendar icon, can be negative value
//Configurable parameters
//var WindowTitle = "DateTime Picker";//Date Time Picker title.
var SpanBorderColor = "#E5E5E5";//span border color
var SpanBgColor = "#FFFFFF"; //span background color
var MonthYearColor = "#cc0033"; //Font Color of Month and Year in Calendar header.
var WeekHeadColor = "#18861B"; //var WeekHeadColor="#18861B";//Background Color in Week header.
var SundayColor = "#C0F64F"; //var SundayColor="#C0F64F";//Background color of Sunday.
var SaturdayColor = "#C0F64F"; //Background color of Saturday.
var WeekDayColor = "#FFEDA6"; //Background color of weekdays.
var FontColor = "blue"; //color of font in Calendar day cell.
var TodayColor = "#ffbd35"; //var TodayColor="#FFFF33";//Background color of today.
var SelDateColor = "#8DD53C"; //var SelDateColor = "#8DD53C";//Backgrond color of selected date in textbox.
var YrSelColor = "#cc0033"; //color of font of Year selector.
var MthSelColor = "#cc0033"; //color of font of Month selector if "MonthSelector" is "arrow".
var HoverColor = "#E0FF38"; //color when mouse move over.
var DisableColor = "#999966"; //color of disabled cell.
var CalBgColor = "#ffffff"; //Background color of Calendar window.
var WeekChar = 2;//number of character for week day. if 2 then Mo,Tu,We. if 3 then Mon,Tue,Wed.
var DateSeparator = "-";//Date Separator, you can change it to "-" if you want.
var ShowLongMonth = true;//Show long month name in Calendar header. example: "January".
var ShowMonthYear = true;//Show Month and Year in Calendar header.
var ThemeBg = "";//Background image of Calendar window.
var PrecedeZero = true;//Preceding zero [true|false]
var MondayFirstDay = true;//true:Use Monday as first day; false:Sunday as first day. [true|false] //added in version 1.7
var UseImageFiles = true;//Use image files with "arrows" and "close" button
var DisableBeforeToday = false; //Make date before today unclickable.
var imageFilesPath = url + "templates/images/date_picker/";
//use the Month and Weekday in your preferred language.
var MonthName = ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"];
var WeekDayName1 = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var WeekDayName2 = ["T2", "T3", "T4", "T5", "T6", "T7", "CN"];
//end Configurable parameters
//end Global variable
// Calendar prototype
function Calendar(pDate, pCtrl)
{
//Properties
this.Date = pDate.getDate();//selected date
this.Month = pDate.getMonth();//selected month number
this.Year = pDate.getFullYear();//selected year in 4 digits
this.Hours = pDate.getHours();
if (pDate.getMinutes() < 10)
{
this.Minutes = "0" + pDate.getMinutes();
}
else
{
this.Minutes = pDate.getMinutes();
}
if (pDate.getSeconds() < 10)
{
this.Seconds = "0" + pDate.getSeconds();
}
else
{
this.Seconds = pDate.getSeconds();
}
this.MyWindow = winCal;
this.Ctrl = pCtrl;
this.Format = "ddMMyyyy";
this.Separator = DateSeparator;
this.ShowTime = false;
this.Scroller = "DROPDOWN";
if (pDate.getHours() < 12)
{
this.AMorPM = "AM";
}
else
{
this.AMorPM = "PM";
}
this.ShowSeconds = false;
}
Calendar.prototype.GetMonthIndex = function (shortMonthName)
{
for (var i = 0; i < 12; i += 1)
{
if (MonthName[i].substring(0, 3).toUpperCase() === shortMonthName.toUpperCase())
{
return i;
}
}
};
Calendar.prototype.IncYear = function () {
if (Cal.Year <= dtToday.getFullYear()+EndYear)
Cal.Year += 1;
};
Calendar.prototype.DecYear = function () {
if (Cal.Year > StartYear)
Cal.Year -= 1;
};
Calendar.prototype.IncMonth = function() {
if (Cal.Year <= dtToday.getFullYear() + EndYear) {
Cal.Month += 1;
if (Cal.Month >= 12) {
Cal.Month = 0;
Cal.IncYear();
}
}
};
Calendar.prototype.DecMonth = function() {
if (Cal.Year >= StartYear) {
Cal.Month -= 1;
if (Cal.Month < 0) {
Cal.Month = 11;
Cal.DecYear();
}
}
};
Calendar.prototype.SwitchMth = function (intMth)
{
Cal.Month = parseInt(intMth, 10);
};
Calendar.prototype.SwitchYear = function (intYear)
{
Cal.Year = parseInt(intYear, 10);
};
Calendar.prototype.SetHour = function (intHour)
{
var MaxHour,
MinHour,
HourExp = new RegExp("^\\d\\d"),
SingleDigit = new RegExp("\\d");
if (TimeMode === 24)
{
MaxHour = 23;
MinHour = 0;
}
else if (TimeMode === 12)
{
MaxHour = 12;
MinHour = 1;
}
else
{
alert("TimeMode can only be 12 or 24");
}
if ((HourExp.test(intHour) || SingleDigit.test(intHour)) && (parseInt(intHour, 10) > MaxHour))
{
intHour = MinHour;
}
else if ((HourExp.test(intHour) || SingleDigit.test(intHour)) && (parseInt(intHour, 10) < MinHour))
{
intHour = MaxHour;
}
if (SingleDigit.test(intHour))
{
intHour = "0" + intHour;
}
if (HourExp.test(intHour) && (parseInt(intHour, 10) <= MaxHour) && (parseInt(intHour, 10) >= MinHour))
{
if ((TimeMode === 12) && (Cal.AMorPM === "PM"))
{
if (parseInt(intHour, 10) === 12)
{
Cal.Hours = 12;
}
else
{
Cal.Hours = parseInt(intHour, 10) + 12;
}
}
else if ((TimeMode === 12) && (Cal.AMorPM === "AM"))
{
if (intHour === 12)
{
intHour -= 12;
}
Cal.Hours = parseInt(intHour, 10);
}
else if (TimeMode === 24)
{
Cal.Hours = parseInt(intHour, 10);
}
}
};
Calendar.prototype.SetMinute = function (intMin)
{
var MaxMin = 59,
MinMin = 0,
SingleDigit = new RegExp("\\d"),
SingleDigit2 = new RegExp("^\\d{1}$"),
MinExp = new RegExp("^\\d{2}$"),
strMin = 0;
if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) > MaxMin))
{
intMin = MinMin;
}
else if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) < MinMin))
{
intMin = MaxMin;
}
strMin = intMin + "";
if (SingleDigit2.test(intMin))
{
strMin = "0" + strMin;
}
if ((MinExp.test(intMin) || SingleDigit.test(intMin)) && (parseInt(intMin, 10) <= 59) && (parseInt(intMin, 10) >= 0))
{
Cal.Minutes = strMin;
}
};
Calendar.prototype.SetSecond = function (intSec)
{
var MaxSec = 59,
MinSec = 0,
SingleDigit = new RegExp("\\d"),
SingleDigit2 = new RegExp("^\\d{1}$"),
SecExp = new RegExp("^\\d{2}$"),
strSec = 0;
if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) > MaxSec))
{
intSec = MinSec;
}
else if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) < MinSec))
{
intSec = MaxSec;
}
strSec = intSec + "";
if (SingleDigit2.test(intSec))
{
strSec = "0" + strSec;
}
if ((SecExp.test(intSec) || SingleDigit.test(intSec)) && (parseInt(intSec, 10) <= 59) && (parseInt(intSec, 10) >= 0))
{
Cal.Seconds = strSec;
}
};
Calendar.prototype.SetAmPm = function (pvalue)
{
this.AMorPM = pvalue;
if (pvalue === "PM")
{
this.Hours = parseInt(this.Hours, 10) + 12;
if (this.Hours === 24)
{
this.Hours = 12;
}
}
else if (pvalue === "AM")
{
this.Hours -= 12;
}
};
Calendar.prototype.getShowHour = function ()
{
var finalHour;
if (TimeMode === 12)
{
if (parseInt(this.Hours, 10) === 0)
{
this.AMorPM = "AM";
finalHour = parseInt(this.Hours, 10) + 12;
}
else if (parseInt(this.Hours, 10) === 12)
{
this.AMorPM = "PM";
finalHour = 12;
}
else if (this.Hours > 12)
{
this.AMorPM = "PM";
if ((this.Hours - 12) < 10)
{
finalHour = "0" + ((parseInt(this.Hours, 10)) - 12);
}
else
{
finalHour = parseInt(this.Hours, 10) - 12;
}
}
else
{
this.AMorPM = "AM";
if (this.Hours < 10)
{
finalHour = "0" + parseInt(this.Hours, 10);
}
else
{
finalHour = this.Hours;
}
}
}
else if (TimeMode === 24)
{
if (this.Hours < 10)
{
finalHour = "0" + parseInt(this.Hours, 10);
}
else
{
finalHour = this.Hours;
}
}
return finalHour;
};
Calendar.prototype.getShowAMorPM = function ()
{
return this.AMorPM;
};
Calendar.prototype.GetMonthName = function (IsLong)
{
var Month = MonthName[this.Month];
if (IsLong)
{
return Month;
}
else
{
return Month.substr(0, 3);
}
};
Calendar.prototype.GetMonDays = function() { //Get number of days in a month
var DaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (Cal.IsLeapYear()) {
DaysInMonth[1] = 29;
}
return DaysInMonth[this.Month];
};
Calendar.prototype.IsLeapYear = function ()
{
if ((this.Year % 4) === 0)
{
if ((this.Year % 100 === 0) && (this.Year % 400) !== 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
};
Calendar.prototype.FormatDate = function (pDate)
{
var MonthDigit = this.Month + 1;
if (PrecedeZero === true)
{
if ((pDate < 10) && String(pDate).length===1) //length checking added in version 2.2
{
pDate = "0" + pDate;
}
if (MonthDigit < 10)
{
MonthDigit = "0" + MonthDigit;
}
}
switch (this.Format.toUpperCase())
{
case "DDMMYYYY":
return (pDate + DateSeparator + MonthDigit + DateSeparator + this.Year);
case "DDMMMYYYY":
return (pDate + DateSeparator + this.GetMonthName(false) + DateSeparator + this.Year);
case "MMDDYYYY":
return (MonthDigit + DateSeparator + pDate + DateSeparator + this.Year);
case "MMMDDYYYY":
return (this.GetMonthName(false) + DateSeparator + pDate + DateSeparator + this.Year);
case "YYYYMMDD":
return (this.Year + DateSeparator + MonthDigit + DateSeparator + pDate);
case "YYMMDD":
return (String(this.Year).substring(2, 4) + DateSeparator + MonthDigit + DateSeparator + pDate);
case "YYMMMDD":
return (String(this.Year).substring(2, 4) + DateSeparator + this.GetMonthName(false) + DateSeparator + pDate);
case "YYYYMMMDD":
return (this.Year + DateSeparator + this.GetMonthName(false) + DateSeparator + pDate);
default:
return (pDate + DateSeparator + (this.Month + 1) + DateSeparator + this.Year);
}
};
// end Calendar prototype
function GenCell(pValue, pHighLight, pColor, pClickable)
{ //Generate table cell with value
var PValue,
PCellStr,
PClickable,
vTimeStr;
if (!pValue)
{
PValue = "";
}
else
{
PValue = pValue;
}
if (pColor === undefined)
pColor = CalBgColor;
if (pClickable !== undefined){
PClickable = pClickable;
}
else{
PClickable = true;
}
if (Cal.ShowTime)
{
vTimeStr = ' ' + Cal.Hours + ':' + Cal.Minutes;
if (Cal.ShowSeconds)
{
vTimeStr += ':' + Cal.Seconds;
}
if (TimeMode === 12)
{
vTimeStr += ' ' + Cal.AMorPM;
}
}
else
{
vTimeStr = "";
}
if (PValue !== "")
{
if (PClickable === true) {
if (Cal.ShowTime === true)
{ PCellStr = "<td id='c" + PValue + "' class='calTD' style='text-align:center;cursor:pointer;background-color:"+pColor+"' onmousedown='selectDate(this," + PValue + ");'>" + PValue + "</td>"; }
else { PCellStr = "<td class='calTD' style='text-align:center;cursor:pointer;background-color:" + pColor + "' onmouseover='changeBorder(this, 0);' onmouseout=\"changeBorder(this, 1, '" + pColor + "');\" onClick=\"javascript:callback('" + Cal.Ctrl + "','" + Cal.FormatDate(PValue) + "');\">" + PValue + "</td>"; }
}
else
{ PCellStr = "<td style='text-align:center;background-color:"+pColor+"' class='calTD'>"+PValue+"</td>"; }
}
else
{ PCellStr = "<td style='text-align:center;background-color:"+pColor+"' class='calTD'> </td>"; }
return PCellStr;
}
function RenderCssCal(bNewCal)
{
if (typeof bNewCal === "undefined" || bNewCal !== true)
{
bNewCal = false;
}
var vCalHeader,
vCalData,
vCalTime = "",
vCalClosing = "",
winCalData = "",
CalDate,
i,
j,
SelectStr,
vDayCount = 0,
vFirstDay,
WeekDayName = [],//Added version 1.7
strCell,
showHour,
ShowArrows = false,
HourCellWidth = "35px", //cell width with seconds.
SelectAm,
SelectPm,
funcCalback,
headID,
e,
cssStr,
style,
cssText,
span;
calHeight = 0; // reset the window height on refresh
// Set the default cursor for the calendar
winCalData = "<span style='cursor:auto;'>";
vCalHeader = "<table style='background-color:"+CalBgColor+";width:200px;padding:0;margin:5px auto 5px auto'><tbody>";
//Table for Month & Year Selector
vCalHeader += "<tr><td colspan='7'><table border='0' width='200px' cellpadding='0' cellspacing='0'><tr>";
//******************Month and Year selector in dropdown list************************
if (Cal.Scroller === "DROPDOWN")
{
vCalHeader += "<td align='center'><select name='MonthSelector' onChange='javascript:Cal.SwitchMth(this.selectedIndex);RenderCssCal();'>";
for (i = 0; i < 12; i += 1)
{
if (i === Cal.Month)
{
SelectStr = "Selected";
}
else
{
SelectStr = "";
}
vCalHeader += "<option " + SelectStr + " value=" + i + ">" + MonthName[i] + "</option>";
}
vCalHeader += "</select></td>";
//Year selector
vCalHeader += "<td align='center'><select name='YearSelector' size='1' onChange='javascript:Cal.SwitchYear(this.value);RenderCssCal();'>";
for (i = StartYear; i <= (dtToday.getFullYear() + EndYear); i += 1)
{
if (i === Cal.Year)
{
SelectStr = 'selected="selected"';
}
else
{
SelectStr = '';
}
vCalHeader += "<option " + SelectStr + " value=" + i + ">" + i + "</option>\n";
}
vCalHeader += "</select></td>\n";
calHeight += 30;
}
//******************End Month and Year selector in dropdown list*********************
//******************Month and Year selector in arrow*********************************
else if (Cal.Scroller === "ARROW")
{
if (UseImageFiles)
{
vCalHeader += "<td><img onmousedown='javascript:Cal.DecYear();RenderCssCal();' src='"+imageFilesPath+"cal_fastreverse.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n";//Year scroller (decrease 1 year)
vCalHeader += "<td><img onmousedown='javascript:Cal.DecMonth();RenderCssCal();' src='" + imageFilesPath + "cal_reverse.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Month scroller (decrease 1 month)
vCalHeader += "<td width='70%' class='calR' style='color:"+YrSelColor+"'>"+ Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td>"; //Month and Year
vCalHeader += "<td><img onmousedown='javascript:Cal.IncMonth();RenderCssCal();' src='" + imageFilesPath + "cal_forward.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Month scroller (increase 1 month)
vCalHeader += "<td><img onmousedown='javascript:Cal.IncYear();RenderCssCal();' src='" + imageFilesPath + "cal_fastforward.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n"; //Year scroller (increase 1 year)
calHeight += 22;
}
else
{
vCalHeader += "<td><span id='dec_year' title='reverse year' onmousedown='javascript:Cal.DecYear();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white; color:" + YrSelColor + "'>-</span></td>";//Year scroller (decrease 1 year)
vCalHeader += "<td><span id='dec_month' title='reverse month' onmousedown='javascript:Cal.DecMonth();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'><</span></td>\n";//Month scroller (decrease 1 month)
vCalHeader += "<td width='70%' class='calR' style='color:" + YrSelColor + "'>" + Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td>\n"; //Month and Year
vCalHeader += "<td><span id='inc_month' title='forward month' onmousedown='javascript:Cal.IncMonth();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'>></span></td>\n";//Month scroller (increase 1 month)
vCalHeader += "<td><span id='inc_year' title='forward year' onmousedown='javascript:Cal.IncYear();RenderCssCal();' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white; color:" + YrSelColor + "'>+</span></td>\n";//Year scroller (increase 1 year)
calHeight += 22;
}
}
vCalHeader += "</tr></table></td></tr>";
//******************End Month and Year selector in arrow******************************
//Calendar header shows Month and Year
if (ShowMonthYear && Cal.Scroller === "DROPDOWN")
{
vCalHeader += "<tr><td colspan='7' class='calR' style='color:" + MonthYearColor + "'>" + Cal.GetMonthName(ShowLongMonth) + " " + Cal.Year + "</td></tr>";
calHeight += 19;
}
//Week day header
vCalHeader += "<tr><td colspan=\"7\"><table style='border-spacing:1px;border-collapse:separate;'><tr>";
if (MondayFirstDay === true)
{
WeekDayName = WeekDayName2;
}
else
{
WeekDayName = WeekDayName1;
}
for (i = 0; i < 7; i += 1)
{
vCalHeader += "<td style='background-color:"+WeekHeadColor+";width:"+CellWidth+"px;color:#FFFFFF' class='calTD'>" + WeekDayName[i].substr(0, WeekChar) + "</td>";
}
calHeight += 19;
vCalHeader += "</tr>";
//Calendar detail
CalDate = new Date(Cal.Year, Cal.Month);
CalDate.setDate(1);
vFirstDay = CalDate.getDay();
//Added version 1.7
if (MondayFirstDay === true)
{
vFirstDay -= 1;
if (vFirstDay === -1)
{
vFirstDay = 6;
}
}
//Added version 1.7
vCalData = "<tr>";
calHeight += 19;
for (i = 0; i < vFirstDay; i += 1)
{
vCalData = vCalData + GenCell();
vDayCount = vDayCount + 1;
}
//Added version 1.7
for (j = 1; j <= Cal.GetMonDays(); j += 1)
{
if ((vDayCount % 7 === 0) && (j > 1))
{
vCalData = vCalData + "<tr>";
}
vDayCount = vDayCount + 1;
//added version 2.1.2
if (DisableBeforeToday === true && ((j < dtToday.getDate()) && (Cal.Month === dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Month < dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()) || (Cal.Year < dtToday.getFullYear())))
{
strCell = GenCell(j, false, DisableColor, false);//Before today's date is not clickable
}
//if End Year + Current Year = Cal.Year. Disable.
else if (Cal.Year > (dtToday.getFullYear()+EndYear))
{
strCell = GenCell(j, false, DisableColor, false);
}
else if ((j === dtToday.getDate()) && (Cal.Month === dtToday.getMonth()) && (Cal.Year === dtToday.getFullYear()))
{
strCell = GenCell(j, true, TodayColor);//Highlight today's date
}
else
{
if ((j === selDate.getDate()) && (Cal.Month === selDate.getMonth()) && (Cal.Year === selDate.getFullYear())){
//modified version 1.7
strCell = GenCell(j, true, SelDateColor);
}
else
{
if (MondayFirstDay === true)
{
if (vDayCount % 7 === 0)
{
strCell = GenCell(j, false, SundayColor);
}
else if ((vDayCount + 1) % 7 === 0)
{
strCell = GenCell(j, false, SaturdayColor);
}
else
{
strCell = GenCell(j, null, WeekDayColor);
}
}
else
{
if (vDayCount % 7 === 0)
{
strCell = GenCell(j, false, SaturdayColor);
}
else if ((vDayCount + 6) % 7 === 0)
{
strCell = GenCell(j, false, SundayColor);
}
else
{
strCell = GenCell(j, null, WeekDayColor);
}
}
}
}
vCalData = vCalData + strCell;
if ((vDayCount % 7 === 0) && (j < Cal.GetMonDays()))
{
vCalData = vCalData + "</tr>";
calHeight += 19;
}
}
// finish the table proper
if (vDayCount % 7 !== 0)
{
while (vDayCount % 7 !== 0)
{
vCalData = vCalData + GenCell();
vDayCount = vDayCount + 1;
}
}
vCalData = vCalData + "</table></td></tr>";
//Time picker
if (Cal.ShowTime === true)
{
showHour = Cal.getShowHour();
if (Cal.ShowSeconds === false && TimeMode === 24)
{
ShowArrows = true;
HourCellWidth = "10px";
}
vCalTime = "<tr><td colspan='7' style=\"text-align:center;\"><table border='0' width='199px' cellpadding='0' cellspacing='0'><tbody><tr><td height='5px' width='" + HourCellWidth + "'> </td>";
if (ShowArrows && UseImageFiles) //this is where the up and down arrow control the hour.
{
vCalTime += "<td style='vertical-align:middle;'><table cellspacing='0' cellpadding='0' style='line-height:0pt;width:100%;'><tr><td style='text-align:center;'><img onclick='nextStep(\"Hour\", \"plus\");' onmousedown='startSpin(\"Hour\", \"plus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_plus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr><tr><td style='text-align:center;'><img onclick='nextStep(\"Hour\", \"minus\");' onmousedown='startSpin(\"Hour\", \"minus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_minus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr></table></td>\n";
}
vCalTime += "<td width='22px'><input type='text' name='hour' maxlength=2 size=1 style=\"WIDTH:22px\" value=" + showHour + " onkeyup=\"javascript:Cal.SetHour(this.value)\">";
vCalTime += "</td><td style='font-weight:bold;text-align:center;'>:</td><td width='22px'>";
vCalTime += "<input type='text' name='minute' maxlength=2 size=1 style=\"WIDTH: 22px\" value=" + Cal.Minutes + " onkeyup=\"javascript:Cal.SetMinute(this.value)\">";
if (Cal.ShowSeconds)
{
vCalTime += "</td><td style='font-weight:bold;'>:</td><td width='22px'>";
vCalTime += "<input type='text' name='second' maxlength=2 size=1 style=\"WIDTH: 22px\" value=" + Cal.Seconds + " onkeyup=\"javascript:Cal.SetSecond(parseInt(this.value,10))\">";
}
if (TimeMode === 12)
{
SelectAm = (Cal.AMorPM === "AM") ? "Selected" : "";
SelectPm = (Cal.AMorPM === "PM") ? "Selected" : "";
vCalTime += "</td><td>";
vCalTime += "<select name=\"ampm\" onChange=\"javascript:Cal.SetAmPm(this.options[this.selectedIndex].value);\">\n";
vCalTime += "<option " + SelectAm + " value=\"AM\">AM</option>";
vCalTime += "<option " + SelectPm + " value=\"PM\">PM<option>";
vCalTime += "</select>";
}
if (ShowArrows && UseImageFiles) //this is where the up and down arrow to change the "Minute".
{
vCalTime += "</td>\n<td style='vertical-align:middle;'><table cellspacing='0' cellpadding='0' style='line-height:0pt;width:100%'><tr><td style='text-align:center;'><img onclick='nextStep(\"Minute\", \"plus\");' onmousedown='startSpin(\"Minute\", \"plus\");' onmouseup='stopSpin();' src='" + imageFilesPath + "cal_plus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr><tr><td style='text-align:center;'><img onmousedown='startSpin(\"Minute\", \"minus\");' onmouseup='stopSpin();' onclick='nextStep(\"Minute\",\"minus\");' src='" + imageFilesPath + "cal_minus.gif' width='13px' height='9px' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td></tr></table>";
}
vCalTime += "</td>\n<td align='right' valign='bottom' width='" + HourCellWidth + "px'></td></tr>";
vCalTime += "<tr><td colspan='7' style=\"text-align:center;\"><input style='width:60px;font-size:12px;' onClick='javascript:closewin(\"" + Cal.Ctrl + "\");' type=\"button\" value=\"OK\"> <input style='width:60px;font-size:12px;' onClick='javascript: winCal.style.visibility = \"hidden\"' type=\"button\" value=\"Cancel\"></td></tr>";
}
else //if not to show time.
{
vCalTime += "\n<tr>\n<td colspan='7' style=\"text-align:right;\">";
//close button
if (UseImageFiles) {
vCalClosing += "<img onmousedown='javascript:closewin(\"" + Cal.Ctrl + "\"); stopSpin();' src='"+imageFilesPath+"cal_close.gif' width='16px' height='16px' onmouseover='changeBorder(this,0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>";
}
else {
vCalClosing += "<span id='close_cal' title='close'onmousedown='javascript:closewin(\"" + Cal.Ctrl + "\");stopSpin();' onmouseover='changeBorder(this, 0)'onmouseout='changeBorder(this, 1)' style='border:1px solid white; font-family: Arial;font-size: 10pt;'>x</span></td>";
}
vCalClosing += "</tr>";
}
vCalClosing += "</tbody></table></td></tr>";
calHeight += 31;
vCalClosing += "</tbody></table>\n</span>";
//end time picker
funcCalback = "function callback(id, datum) {";
funcCalback += " var CalId = document.getElementById(id);if (datum=== 'undefined') { var d = new Date(); datum = d.getDate() + '/' +(d.getMonth()+1) + '/' + d.getFullYear(); } window.calDatum=datum;CalId.value=datum;";
funcCalback += " if(Cal.ShowTime){";
funcCalback += " CalId.value+=' '+Cal.getShowHour()+':'+Cal.Minutes;";
funcCalback += " if (Cal.ShowSeconds) CalId.value+=':'+Cal.Seconds;";
funcCalback += " if (TimeMode === 12) CalId.value+=''+Cal.getShowAMorPM();";
funcCalback += "}if(CalId.onchange===true) CalId.onchange();CalId.focus();winCal.style.visibility='hidden';}";
// determines if there is enough space to open the cal above the position where it is called
if (ypos > calHeight)
{
ypos = ypos - calHeight;
}
if (!winCal)
{
headID = document.getElementsByTagName("head")[0];
// add javascript function to the span cal
e = document.createElement("script");
e.type = "text/javascript";
e.language = "javascript";
e.text = funcCalback;
headID.appendChild(e);
// add stylesheet to the span cal
cssStr = ".calTD {font-family: verdana; font-size: 12px; text-align: center; border:0; }\n";
cssStr += ".calR {font-family: verdana; font-size: 12px; text-align: center; font-weight: bold;}";
style = document.createElement("style");
style.type = "text/css";
style.rel = "stylesheet";
if (style.styleSheet)
{ // IE
style.styleSheet.cssText = cssStr;
}
else
{ // w3c
cssText = document.createTextNode(cssStr);
style.appendChild(cssText);
}
headID.appendChild(style);
// create the outer frame that allows the cal. to be moved
span = document.createElement("span");
span.id = calSpanID;
span.style.position = "absolute";
span.style.left = (xpos + CalPosOffsetX) + 'px';
span.style.top = (ypos - CalPosOffsetY) + 'px';
span.style.width = CalWidth + 'px';
span.style.border = "solid 1pt " + SpanBorderColor;
span.style.padding = "0";
span.style.cursor = "move";
span.style.backgroundColor = SpanBgColor;
span.style.zIndex = 100;
document.body.appendChild(span);
winCal = document.getElementById(calSpanID);
}
else
{
winCal.style.visibility = "visible";
winCal.style.Height = calHeight;
// set the position for a new calendar only
if (bNewCal === true)
{
winCal.style.left = (xpos + CalPosOffsetX) + 'px';
winCal.style.top = (ypos - CalPosOffsetY) + 'px';
}
}
winCal.innerHTML = winCalData + vCalHeader + vCalData + vCalTime + vCalClosing;
return true;
}
function NewCssCal(pCtrl, pFormat, pScroller, pShowTime, pTimeMode, pShowSeconds)
{
// get current date and time
dtToday = new Date();
Cal = new Calendar(dtToday);
if (pShowTime !== undefined)
{
if (pShowTime) {
Cal.ShowTime = true;
}
else {
Cal.ShowTime = false;
}
if (pTimeMode)
{
pTimeMode = parseInt(pTimeMode, 10);
}
if (pTimeMode === 12 || pTimeMode === 24)
{
TimeMode = pTimeMode;
}
else
{
TimeMode = 24;
}
if (pShowSeconds !== undefined)
{
if (pShowSeconds)
{
Cal.ShowSeconds = true;
}
else
{
Cal.ShowSeconds = false;
}
}
else
{
Cal.ShowSeconds = false;
}
}
if (pCtrl !== undefined)
{
Cal.Ctrl = pCtrl;
}
if (pFormat !== undefined)
{
Cal.Format = pFormat.toUpperCase();
}
else
{
Cal.Format = "MMDDYYYY";
}
if (pScroller !== undefined)
{
if (pScroller.toUpperCase() === "ARROW")
{
Cal.Scroller = "ARROW";
}
else
{
Cal.Scroller = "DROPDOWN";
}
}
exDateTime = document.getElementById(pCtrl).value; //Existing Date Time value in textbox.
if (exDateTime)
{ //Parse existing Date String
var Sp1 = exDateTime.indexOf(DateSeparator, 0),//Index of Date Separator 1
Sp2 = exDateTime.indexOf(DateSeparator, parseInt(Sp1, 10) + 1),//Index of Date Separator 2
tSp1,//Index of Time Separator 1
tSp2,//Index of Time Separator 2
strMonth,
strDate,
strYear,
intMonth,
YearPattern,
strHour,
strMinute,
strSecond,
winHeight,
offset = parseInt(Cal.Format.toUpperCase().lastIndexOf("M"), 10) - parseInt(Cal.Format.toUpperCase().indexOf("M"), 10) - 1,
strAMPM = "";
//parse month
if (Cal.Format.toUpperCase() === "DDMMYYYY" || Cal.Format.toUpperCase() === "DDMMMYYYY")
{
if (DateSeparator === "")
{
strMonth = exDateTime.substring(2, 4 + offset);
strDate = exDateTime.substring(0, 2);
strYear = exDateTime.substring(4 + offset, 8 + offset);
}
else
{
if (exDateTime.indexOf("D*") !== -1)
{ //DTG
strMonth = exDateTime.substring(8, 11);
strDate = exDateTime.substring(0, 2);
strYear = "20" + exDateTime.substring(11, 13); //Hack, nur für Jahreszahlen ab 2000
}
else
{
strMonth = exDateTime.substring(Sp1 + 1, Sp2);
strDate = exDateTime.substring(0, Sp1);
strYear = exDateTime.substring(Sp2 + 1, Sp2 + 5);
}
}
}
else if (Cal.Format.toUpperCase() === "MMDDYYYY" || Cal.Format.toUpperCase() === "MMMDDYYYY"){
if (DateSeparator === ""){
strMonth = exDateTime.substring(0, 2 + offset);
strDate = exDateTime.substring(2 + offset, 4 + offset);
strYear = exDateTime.substring(4 + offset, 8 + offset);
}
else{
strMonth = exDateTime.substring(0, Sp1);
strDate = exDateTime.substring(Sp1 + 1, Sp2);
strYear = exDateTime.substring(Sp2 + 1, Sp2 + 5);
}
}
else if (Cal.Format.toUpperCase() === "YYYYMMDD" || Cal.Format.toUpperCase() === "YYYYMMMDD")
{
if (DateSeparator === ""){
strMonth = exDateTime.substring(4, 6 + offset);
strDate = exDateTime.substring(6 + offset, 8 + offset);
strYear = exDateTime.substring(0, 4);
}
else{
strMonth = exDateTime.substring(Sp1 + 1, Sp2);
strDate = exDateTime.substring(Sp2 + 1, Sp2 + 3);
strYear = exDateTime.substring(0, Sp1);
}
}
else if (Cal.Format.toUpperCase() === "YYMMDD" || Cal.Format.toUpperCase() === "YYMMMDD")
{
if (DateSeparator === "")
{
strMonth = exDateTime.substring(2, 4 + offset);
strDate = exDateTime.substring(4 + offset, 6 + offset);
strYear = exDateTime.substring(0, 2);
}
else
{
strMonth = exDateTime.substring(Sp1 + 1, Sp2);
strDate = exDateTime.substring(Sp2 + 1, Sp2 + 3);
strYear = exDateTime.substring(0, Sp1);
}
}
if (isNaN(strMonth)){
intMonth = Cal.GetMonthIndex(strMonth);
}
else{
intMonth = parseInt(strMonth, 10) - 1;
}
if ((parseInt(intMonth, 10) >= 0) && (parseInt(intMonth, 10) < 12)) {
Cal.Month = intMonth;
}
//end parse month
//parse year
YearPattern = /^\d{4}$/;
if (YearPattern.test(strYear)) {
if ((parseInt(strYear, 10)>=StartYear) && (parseInt(strYear, 10)<= (dtToday.getFullYear()+EndYear)))
Cal.Year = parseInt(strYear, 10);
}
//end parse year
//parse Date
if ((parseInt(strDate, 10) <= Cal.GetMonDays()) && (parseInt(strDate, 10) >= 1)) {
Cal.Date = strDate;
}
//end parse Date
//parse time
if (Cal.ShowTime === true)
{
//parse AM or PM
if (TimeMode === 12)
{
strAMPM = exDateTime.substring(exDateTime.length - 2, exDateTime.length);
Cal.AMorPM = strAMPM;
}
tSp1 = exDateTime.indexOf(":", 0);
tSp2 = exDateTime.indexOf(":", (parseInt(tSp1, 10) + 1));
if (tSp1 > 0)
{
strHour = exDateTime.substring(tSp1, tSp1 - 2);
Cal.SetHour(strHour);
strMinute = exDateTime.substring(tSp1 + 1, tSp1 + 3);
Cal.SetMinute(strMinute);
strSecond = exDateTime.substring(tSp2 + 1, tSp2 + 3);
Cal.SetSecond(strSecond);
}
else if (exDateTime.indexOf("D*") !== -1)
{ //DTG
strHour = exDateTime.substring(2, 4);
Cal.SetHour(strHour);
strMinute = exDateTime.substring(4, 6);
Cal.SetMinute(strMinute);
}
}
}
selDate = new Date(Cal.Year, Cal.Month, Cal.Date);//version 1.7
RenderCssCal(true);
}
function closewin(id) {
if (Cal.ShowTime === true) {
var MaxYear = dtToday.getFullYear() + EndYear;
var beforeToday =
(Cal.Date < dtToday.getDate()) &&
(Cal.Month === dtToday.getMonth()) &&
(Cal.Year === dtToday.getFullYear())
||
(Cal.Month < dtToday.getMonth()) &&
(Cal.Year === dtToday.getFullYear())
||
(Cal.Year < dtToday.getFullYear());
if ((Cal.Year <= MaxYear) && (Cal.Year >= StartYear) && (Cal.Month === selDate.getMonth()) && (Cal.Year === selDate.getFullYear())) {
if (DisableBeforeToday === true) {
if (beforeToday === false) {
callback(id, Cal.FormatDate(Cal.Date));
}
}
else
callback(id, Cal.FormatDate(Cal.Date));
}
}
var CalId = document.getElementById(id);
CalId.focus();
winCal.style.visibility = 'hidden';
}
function changeBorder(element, col, oldBgColor)
{
if (col === 0)
{
element.style.background = HoverColor;
element.style.borderColor = "black";
element.style.cursor = "pointer";
}
else
{
if (oldBgColor)
{
element.style.background = oldBgColor;
}
else
{
element.style.background = "white";
}
element.style.borderColor = "white";
element.style.cursor = "auto";
}
}
function selectDate(element, date) {
Cal.Date = date;
selDate = new Date(Cal.Year, Cal.Month, Cal.Date);
element.style.background = SelDateColor;
RenderCssCal();
}
function pickIt(evt)
{
var objectID,
dom,
de,
b;
// accesses the element that generates the event and retrieves its ID
if (document.addEventListener)
{ // w3c
objectID = evt.target.id;
if (objectID.indexOf(calSpanID) !== -1)
{
dom = document.getElementById(objectID);
cnLeft = evt.pageX;
cnTop = evt.pageY;
if (dom.offsetLeft)
{
cnLeft = (cnLeft - dom.offsetLeft);
cnTop = (cnTop - dom.offsetTop);
}
}
// get mouse position on click
xpos = (evt.pageX);
ypos = (evt.pageY);
}
else
{ // IE
objectID = event.srcElement.id;
cnLeft = event.offsetX;
cnTop = (event.offsetY);
// get mouse position on click
de = document.documentElement;
b = document.body;
xpos = event.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
ypos = event.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
}
// verify if this is a valid element to pick
if (objectID.indexOf(calSpanID) !== -1)
{
domStyle = document.getElementById(objectID).style;
}
if (domStyle)
{
domStyle.zIndex = 100;
return false;
}
else
{
domStyle = null;
return;
}
}
function dragIt(evt)
{
if (domStyle)
{
if (document.addEventListener)
{ //for IE
domStyle.left = (event.clientX - cnLeft + document.body.scrollLeft) + 'px';
domStyle.top = (event.clientY - cnTop + document.body.scrollTop) + 'px';
}
else
{ //Firefox
domStyle.left = (evt.clientX - cnLeft + document.body.scrollLeft) + 'px';
domStyle.top = (evt.clientY - cnTop + document.body.scrollTop) + 'px';
}
}
}
// performs a single increment or decrement
function nextStep(whatSpinner, direction)
{
if (whatSpinner === "Hour")
{
if (direction === "plus")
{
Cal.SetHour(Cal.Hours + 1);
RenderCssCal();
}
else if (direction === "minus")
{
Cal.SetHour(Cal.Hours - 1);
RenderCssCal();
}
}
else if (whatSpinner === "Minute")
{
if (direction === "plus")
{
Cal.SetMinute(parseInt(Cal.Minutes, 10) + 1);
RenderCssCal();
}
else if (direction === "minus")
{
Cal.SetMinute(parseInt(Cal.Minutes, 10) - 1);
RenderCssCal();
}
}
}
// starts the time spinner
function startSpin(whatSpinner, direction)
{
document.thisLoop = setInterval(function ()
{
nextStep(whatSpinner, direction);
}, 125); //125 ms
}
//stops the time spinner
function stopSpin()
{
clearInterval(document.thisLoop);
}
function dropIt()
{
stopSpin();
if (domStyle)
{
domStyle = null;
}
}
// Default events configuration
document.onmousedown = pickIt;
document.onmousemove = dragIt;
document.onmouseup = dropIt;
| JavaScript |
/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.5 (23.06.2009)
*/
/**
* Changes from the previous version:
* 1. Added better JSON handling that allows to use 'application/javascript' as a response
* 2. Added demo for usage with jQuery UI dialog
* 3. Fixed IE "mixed content" issue when used with secure connections
*
* For the full changelog please visit:
* http://valums.com/ajax-upload-changelog/
*/
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
// Get Offset using getBoundingClientRect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
// pageX/Y is not supported in IE
// http://www.quirksmode.org/dom/w3c_cssom.html
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'width': '220px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
// Remove ie6 "This page contains both secure and nonsecure items" prompt
// http://tinyurl.com/77w9wh
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})(); | JavaScript |
/*
* jQuery UI Datepicker 1.8.5
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Datepicker
*
* Depends:
* jquery.ui.core.js
*/
(function( $, undefined ) {
$.extend($.ui, { datepicker: { version: "1.8.5" } });
var PROP_NAME = 'datepicker';
var dpuuid = new Date().getTime();
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this.debug = false; // Change this to true to start debugging
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
closeText: 'Done', // Display text for close link
prevText: '', // Display text for previous month link
nextText: '', // Display text for next month link
currentText: 'Today', // Display text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12'], // For formatting
dayNames: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // For formatting
dayNamesShort: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // For formatting
dayNamesMin: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'], // Column headings for days starting at Sunday
weekHeader: 'Wk', // Column header for week of the year
dateFormat: 'yy/mm/dd', // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: '' // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'fadeIn', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: '', // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: 'c-10:c+10', // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: '+10', // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with '+' for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: 'fast', // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: '', // Selector for an alternate field to store selected dates into
altFormat: '', // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false // True to size the input for the date format, false to leave as is
};
$.extend(this._defaults, this.regional['']);
this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
@param settings object - the new settings to use as defaults (anonymous object)
@return the manager object */
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this date picker instance (anonymous) */
_attachDatepicker: function(target, settings) {
// check for settings on the control itself - in namespace 'date:'
var inlineSettings = null;
for (var attrName in this._defaults) {
var attrValue = target.getAttribute('date:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
var inline = (nodeName == 'div' || nodeName == 'span');
if (!target.id) {
this.uuid += 1;
target.id = 'dp' + this.uuid;
}
var inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {}, inlineSettings || {});
if (nodeName == 'input') {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_])/g, '\\\\$1'); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName))
return;
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp).
bind("setData.datepicker", function(event, key, value) {
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key) {
return this._get(inst, key);
});
this._autoSize(inst);
$.data(target, PROP_NAME, inst);
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var appendText = this._get(inst, 'appendText');
var isRTL = this._get(inst, 'isRTL');
if (inst.append)
inst.append.remove();
if (appendText) {
inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
input[isRTL ? 'before' : 'after'](inst.append);
}
input.unbind('focus', this._showDatepicker);
if (inst.trigger)
inst.trigger.remove();
var showOn = this._get(inst, 'showOn');
if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
var buttonText = this._get(inst, 'buttonText');
var buttonImage = this._get(inst, 'buttonImage');
inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
$('<img/>').addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$('<button type="button"></button>').addClass(this._triggerClass).
html(buttonImage == '' ? buttonText : $('<img/>').attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? 'before' : 'after'](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
$.datepicker._hideDatepicker();
else
$.datepicker._showDatepicker(input[0]);
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, 'autoSize') && !inst.inline) {
var date = new Date(2009, 12 - 1, 20); // Ensure double digits
var dateFormat = this._get(inst, 'dateFormat');
if (dateFormat.match(/[DM]/)) {
var findMax = function(names) {
var max = 0;
var maxI = 0;
for (var i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
'monthNames' : 'monthNamesShort'))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
}
inst.input.attr('size', this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName))
return;
divSpan.addClass(this.markerClassName).append(inst.dpDiv).
bind("setData.datepicker", function(event, key, value){
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key){
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
},
/* Pop-up the date picker in a "dialog" box.
@param input element - ignored
@param date string or Date - the initial date to display
@param onSelect function - the function to call when a date is selected
@param settings object - update the dialog date picker instance's settings (anonymous object)
@param pos int[2] - coordinates for the dialog's position within the screen or
event - with x/y coordinates or
leave empty for default (screen centre)
@return the manager object */
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
var id = 'dp' + this.uuid;
this._dialogInput = $('<input type="text" id="' + id +
'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');
this._dialogInput.keydown(this._doKeyDown);
$('body').append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
var browserWidth = document.documentElement.clientWidth;
var browserHeight = document.documentElement.clientHeight;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI)
$.blockUI(this.dpDiv);
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
@param target element - the target input field or division or span */
_destroyDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName == 'input') {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind('focus', this._showDatepicker).
unbind('keydown', this._doKeyDown).
unbind('keypress', this._doKeyPress).
unbind('keyup', this._doKeyUp);
} else if (nodeName == 'div' || nodeName == 'span')
$target.removeClass(this.markerClassName).empty();
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = false;
inst.trigger.filter('button').
each(function() { this.disabled = false; }).end().
filter('img').css({opacity: '1.0', cursor: ''});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().removeClass('ui-state-disabled');
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = true;
inst.trigger.filter('button').
each(function() { this.disabled = true; }).end().
filter('img').css({opacity: '0.5', cursor: 'default'});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().addClass('ui-state-disabled');
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
@param target element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target)
return true;
}
return false;
},
/* Retrieve the instance data for the target control.
@param target element - the target input field or division or span
@return object - the associated instance data
@throws error if a jQuery problem getting data */
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw 'Missing instance data for this datepicker';
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
@param target element - the target input field or division or span
@param name object - the new settings to update or
string - the name of the setting to change or retrieve,
when retrieving also 'all' for all instance settings or
'defaults' for all global defaults
@param value any - the new value for the setting
(omit if above is an object or to retrieve a value) */
_optionDatepicker: function(target, name, value) {
var inst = this._getInst(target);
if (arguments.length == 2 && typeof name == 'string') {
return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
(inst ? (name == 'all' ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
var settings = name || {};
if (typeof name == 'string') {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst == inst) {
this._hideDatepicker();
}
var date = this._getDateDatepicker(target, true);
extendRemove(inst.settings, settings);
this._attachments($(target), inst);
this._autoSize(inst);
this._setDateDatepicker(target, date);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
@param target element - the target input field or division or span */
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
@param target element - the target input field or division or span
@param date Date - the new date */
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
@param target element - the target input field or division or span
@param noDefault boolean - true if no default date is to be used
@return Date - the current date */
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline)
this._setDateFromField(inst, noDefault);
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var inst = $.datepicker._getInst(event.target);
var handled = true;
var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
inst._keyEvent = true;
if ($.datepicker._datepickerShowing)
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: var sel = $('td.' + $.datepicker._dayOverClass, inst.dpDiv).
add($('td.' + $.datepicker._currentClass, inst.dpDiv));
if (sel[0])
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
else
$.datepicker._hideDatepicker();
return false; // don't submit the form
break; // select the value on enter
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, 'constrainInput')) {
var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var inst = $.datepicker._getInst(event.target);
if (inst.input.val() != inst.lastVal) {
try {
var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (event) {
$.datepicker.log(event);
}
}
return true;
},
/* Pop-up the date picker for a given input field.
@param input element - the input field attached to the date picker or
event - if triggered by focus */
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
input = $('input', input.parentNode)[0];
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
return;
var inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst != inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
}
var beforeShow = $.datepicker._get(inst, 'beforeShow');
extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) // hide cursor
input.value = '';
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css('position') == 'fixed';
return !isFixed;
});
if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
$.datepicker._pos[0] -= document.documentElement.scrollLeft;
$.datepicker._pos[1] -= document.documentElement.scrollTop;
}
var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
// determine sizing offscreen
inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
left: offset.left + 'px', top: offset.top + 'px'});
if (!inst.inline) {
var showAnim = $.datepicker._get(inst, 'showAnim');
var duration = $.datepicker._get(inst, 'duration');
var postProcess = function() {
$.datepicker._datepickerShowing = true;
var borders = $.datepicker._getBorders(inst.dpDiv);
inst.dpDiv.find('iframe.ui-datepicker-cover'). // IE6- only
css({left: -borders[0], top: -borders[1],
width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
};
inst.dpDiv.zIndex($(input).zIndex()+1);
if ($.effects && $.effects[showAnim])
inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
if (!showAnim || !duration)
postProcess();
if (inst.input.is(':visible') && !inst.input.is(':disabled'))
inst.input.focus();
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
var self = this;
var borders = $.datepicker._getBorders(inst.dpDiv);
inst.dpDiv.empty().append(this._generateHTML(inst))
.find('iframe.ui-datepicker-cover') // IE6- only
.css({left: -borders[0], top: -borders[1],
width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
.end()
.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
.bind('mouseout', function(){
$(this).removeClass('ui-state-hover');
if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
})
.bind('mouseover', function(){
if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
$(this).addClass('ui-state-hover');
if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
}
})
.end()
.find('.' + this._dayOverClass + ' a')
.trigger('mouseover')
.end();
var numMonths = this._getNumberOfMonths(inst);
var cols = numMonths[1];
var width = 17;
if (cols > 1)
inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
else
inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
'Class']('ui-datepicker-multi');
inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
'Class']('ui-datepicker-rtl');
if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
inst.input.is(':visible') && !inst.input.is(':disabled'))
inst.input.focus();
},
/* Retrieve the size of left and top borders for an element.
@param elem (jQuery object) the element of interest
@return (number[2]) the left and top borders */
_getBorders: function(elem) {
var convert = function(value) {
return {thin: 1, medium: 2, thick: 3}[value] || value;
};
return [parseFloat(convert(elem.css('border-left-width'))),
parseFloat(convert(elem.css('border-top-width')))];
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth();
var dpHeight = inst.dpDiv.outerHeight();
var inputWidth = inst.input ? inst.input.outerWidth() : 0;
var inputHeight = inst.input ? inst.input.outerHeight() : 0;
var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var inst = this._getInst(obj);
var isRTL = this._get(inst, 'isRTL');
while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
@param input element - the input field attached to the date picker */
_hideDatepicker: function(input) {
var inst = this._curInst;
if (!inst || (input && inst != $.data(input, PROP_NAME)))
return;
if (this._datepickerShowing) {
var showAnim = this._get(inst, 'showAnim');
var duration = this._get(inst, 'duration');
var postProcess = function() {
$.datepicker._tidyDialog(inst);
this._curInst = null;
};
if ($.effects && $.effects[showAnim])
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
if (!showAnim)
postProcess();
var onClose = this._get(inst, 'onClose');
if (onClose)
onClose.apply((inst.input ? inst.input[0] : null),
[(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
this._datepickerShowing = false;
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst)
return;
var $target = $(event.target);
if ($target[0].id != $.datepicker._mainDivId &&
$target.parents('#' + $.datepicker._mainDivId).length == 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.hasClass($.datepicker._triggerClass) &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
$.datepicker._hideDatepicker();
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
}
else {
var date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id);
var inst = this._getInst(target[0]);
inst._selectingMonthYear = false;
inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Restore input focus after not changing month/year. */
_clickMonthYear: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (inst.input && inst._selectingMonthYear) {
setTimeout(function() {
inst.input.focus();
}, 0);
}
inst._selectingMonthYear = !inst._selectingMonthYear;
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
var inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $('a', td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
this._selectDate(target, '');
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input)
inst.input.val(dateStr);
this._updateAlternate(inst);
var onSelect = this._get(inst, 'onSelect');
if (onSelect)
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
else if (inst.input)
inst.input.trigger('change'); // fire the change event
if (inst.inline)
this._updateDatepicker(inst);
else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) != 'object')
inst.input.focus(); // restore focus
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altField = this._get(inst, 'altField');
if (altField) { // update alternate field too
var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
var date = this._getDate(inst);
var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
@param date Date - the date to customise
@return [boolean, string] - is this date selectable?, what is its CSS class? */
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ''];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
@param date Date - the date to get the week for
@return number - the number of the week within the year that contains this date */
iso8601Week: function(date) {
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
See formatDate below for the possible formats.
@param format string - the expected format of the date
@param value string - the date in the above format
@param settings Object - attributes include:
shortYearCutoff number - the cutoff year for determining the century (optional)
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return Date - the extracted date value or null if value is blank */
parseDate: function (format, value, settings) {
if (format == null || value == null)
throw 'Invalid arguments';
value = (typeof value == 'object' ? value.toString() : value + '');
if (value == '')
return null;
var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
var year = -1;
var month = -1;
var day = -1;
var doy = -1;
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Extract a number from the string value
var getNumber = function(match) {
lookAhead(match);
var size = (match == '@' ? 14 : (match == '!' ? 20 :
(match == 'y' ? 4 : (match == 'o' ? 3 : 2))));
var digits = new RegExp('^\\d{1,' + size + '}');
var num = value.substring(iValue).match(digits);
if (!num)
throw 'Missing number at position ' + iValue;
iValue += num[0].length;
return parseInt(num[0], 10);
};
// Extract a name from the string value and convert to an index
var getName = function(match, shortNames, longNames) {
var names = (lookAhead(match) ? longNames : shortNames);
for (var i = 0; i < names.length; i++) {
if (value.substr(iValue, names[i].length).toLowerCase() == names[i].toLowerCase()) {
iValue += names[i].length;
return i + 1;
}
}
throw 'Unknown name at position ' + iValue;
};
// Confirm that a literal character matches the string value
var checkLiteral = function() {
if (value.charAt(iValue) != format.charAt(iFormat))
throw 'Unexpected literal at position ' + iValue;
iValue++;
};
var iValue = 0;
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
checkLiteral();
else
switch (format.charAt(iFormat)) {
case 'd':
day = getNumber('d');
break;
case 'D':
getName('D', dayNamesShort, dayNames);
break;
case 'o':
doy = getNumber('o');
break;
case 'm':
month = getNumber('m');
break;
case 'M':
month = getName('M', monthNamesShort, monthNames);
break;
case 'y':
year = getNumber('y');
break;
case '@':
var date = new Date(getNumber('@'));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case '!':
var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'"))
checkLiteral();
else
literal = true;
break;
default:
checkLiteral();
}
}
if (year == -1)
year = new Date().getFullYear();
else if (year < 100)
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
if (doy > -1) {
month = 1;
day = doy;
do {
var dim = this._getDaysInMonth(year, month - 1);
if (day <= dim)
break;
month++;
day -= dim;
} while (true);
}
var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
throw 'Invalid date'; // E.g. 31/02/*
return date;
},
/* Standard date formats. */
ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
COOKIE: 'D, dd M yy',
ISO_8601: 'yy-mm-dd',
RFC_822: 'D, d M y',
RFC_850: 'DD, dd-M-y',
RFC_1036: 'D, d M y',
RFC_1123: 'D, d M yy',
RFC_2822: 'D, d M yy',
RSS: 'D, d M y', // RFC 822
TICKS: '!',
TIMESTAMP: '@',
W3C: 'yy-mm-dd', // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
o - day of year (no leading zeros)
oo - day of year (three digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
@ - Unix timestamp (ms since 01/01/1970)
! - Windows ticks (100ns since 01/01/0001)
'...' - literal text
'' - single quote
@param format string - the desired format of the date
@param date Date - the date value to format
@param settings Object - attributes include:
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return string - the date in the above format */
formatDate: function (format, date, settings) {
if (!date)
return '';
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Format a number, with leading zero if necessary
var formatNumber = function(match, value, len) {
var num = '' + value;
if (lookAhead(match))
while (num.length < len)
num = '0' + num;
return num;
};
// Format a name, short or long as requested
var formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
};
var output = '';
var literal = false;
if (date)
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
output += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd':
output += formatNumber('d', date.getDate(), 2);
break;
case 'D':
output += formatName('D', date.getDay(), dayNamesShort, dayNames);
break;
case 'o':
output += formatNumber('o',
(date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3);
break;
case 'm':
output += formatNumber('m', date.getMonth() + 1, 2);
break;
case 'M':
output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
break;
case 'y':
output += (lookAhead('y') ? date.getFullYear() :
(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
break;
case '@':
output += date.getTime();
break;
case '!':
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'"))
output += "'";
else
literal = true;
break;
default:
output += format.charAt(iFormat);
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var chars = '';
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
for (var iFormat = 0; iFormat < format.length; iFormat++)
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
chars += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd': case 'm': case 'y': case '@':
chars += '0123456789';
break;
case 'D': case 'M':
return null; // Accept anything
case "'":
if (lookAhead("'"))
chars += "'";
else
literal = true;
break;
default:
chars += format.charAt(iFormat);
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() == inst.lastVal) {
return;
}
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.lastVal = inst.input ? inst.input.val() : null;
var date, defaultDate;
date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
this.log(event);
dates = (noDefault ? '' : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
};
var offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
var matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || 'd') {
case 'd' : case 'D' :
day += parseInt(matches[1],10); break;
case 'w' : case 'W' :
day += parseInt(matches[1],10) * 7; break;
case 'm' : case 'M' :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case 'y': case 'Y' :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
};
date = (date == null ? defaultDate : (typeof date == 'string' ? offsetString(date) :
(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
if (date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
return this._daylightSavingAdjust(date);
},
/* Handle switch to/from daylight saving.
Hours may be non-zero on daylight saving cut-over:
> 12 when midnight changeover, but then cannot generate
midnight datetime, so jump to 1AM, otherwise reset.
@param date (Date) the date to check
@return (Date) the corrected date */
_daylightSavingAdjust: function(date) {
if (!date) return null;
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !(date);
var origMonth = inst.selectedMonth;
var origYear = inst.selectedYear;
date = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = date.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
this._notifyChange(inst);
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? '' : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var today = new Date();
today = this._daylightSavingAdjust(
new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
var isRTL = this._get(inst, 'isRTL');
var showButtonPanel = this._get(inst, 'showButtonPanel');
var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
var numMonths = this._getNumberOfMonths(inst);
var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
var stepMonths = this._get(inst, 'stepMonths');
var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
var drawMonth = inst.drawMonth - showCurrentAtPos;
var drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
var prevText = this._get(inst, 'prevText');
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '"></span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
var nextText = this._get(inst, 'nextText');
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '"></span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
var currentText = this._get(inst, 'currentText');
var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._gotoToday(\'#' + inst.id + '\');"' +
'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
var firstDay = parseInt(this._get(inst, 'firstDay'),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
var showWeek = this._get(inst, 'showWeek');
var dayNames = this._get(inst, 'dayNames');
var dayNamesShort = this._get(inst, 'dayNamesShort');
var dayNamesMin = this._get(inst, 'dayNamesMin');
var monthNames = this._get(inst, 'monthNames');
var monthNamesShort = this._get(inst, 'monthNamesShort');
var beforeShowDay = this._get(inst, 'beforeShowDay');
var showOtherMonths = this._get(inst, 'showOtherMonths');
var selectOtherMonths = this._get(inst, 'selectOtherMonths');
var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
var defaultDate = this._getDefaultDate(inst);
var html = '';
for (var row = 0; row < numMonths[0]; row++) {
var group = '';
for (var col = 0; col < numMonths[1]; col++) {
var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
var cornerClass = ' ui-corner-all';
var calender = '';
if (isMultiMonth) {
calender += '<div class="ui-datepicker-group';
if (numMonths[1] > 1)
switch (col) {
case 0: calender += ' ui-datepicker-group-first';
cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
case numMonths[1]-1: calender += ' ui-datepicker-group-last';
cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
}
calender += '">';
}
calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
'</div><table class="ui-datepicker-calendar"><thead>' +
'<tr>';
var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
for (var dow = 0; dow < 7; dow++) { // days of the week
var day = (dow + firstDay) % 7;
thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
}
calender += thead + '</tr></thead><tbody>';
var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += '<tr>';
var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
this._get(inst, 'calculateWeek')(printDate) + '</td>');
for (var dow = 0; dow < 7; dow++) { // create date picker days
var daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
var otherMonth = (printDate.getMonth() != drawMonth);
var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += '<td class="' +
((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
' ' + this._dayOverClass : '') + // highlight selected day
(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days
(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
(printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
(unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions
(otherMonth && !showOtherMonths ? ' ' : // display for other months
(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
(printDate.getTime() == selectedDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
(otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + '</tr>';
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
group += calender;
}
html += group;
}
html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var changeMonth = this._get(inst, 'changeMonth');
var changeYear = this._get(inst, 'changeYear');
var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
var html = '<div class="ui-datepicker-title">';
var monthHtml = '';
// month selection
if (secondary || !changeMonth)
monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
else {
var inMinYear = (minDate && minDate.getFullYear() == drawYear);
var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
monthHtml += '<select class="ui-datepicker-month" ' +
'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
'>';
for (var month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) &&
(!inMaxYear || month <= maxDate.getMonth()))
monthHtml += '<option value="' + month + '"' +
(month == drawMonth ? ' selected="selected"' : '') +
'>' + monthNamesShort[month] + '</option>';
}
monthHtml += '</select>';
}
if (!showMonthAfterYear)
html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : '');
// year selection
if (secondary || !changeYear)
html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
else {
// determine range of years to display
var years = this._get(inst, 'yearRange').split(':');
var thisYear = new Date().getFullYear();
var determineYear = function(value) {
var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
var year = determineYear(years[0]);
var endYear = Math.max(year, determineYear(years[1] || ''));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
html += '<select class="ui-datepicker-year" ' +
'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
'>';
for (; year <= endYear; year++) {
html += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
html += '</select>';
}
html += this._get(inst, 'yearSuffix');
if (showMonthAfterYear)
html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml;
html += '</div>'; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period == 'Y' ? offset : 0);
var month = inst.drawMonth + (period == 'M' ? offset : 0);
var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
(period == 'D' ? offset : 0);
var date = this._restrictMinMax(inst,
this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period == 'M' || period == 'Y')
this._notifyChange(inst);
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
return date;
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, 'onChangeMonthYear');
if (onChange)
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, 'numberOfMonths');
return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - new Date(year, month, 32).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst);
var date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0)
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, 'shortYearCutoff');
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day == 'object' ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
}
});
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props)
if (props[name] == null || props[name] == undefined)
target[name] = props[name];
return target;
};
/* Determine whether an object is an array. */
function isArray(a) {
return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick).
find('body').append($.datepicker.dpDiv);
$.datepicker.initialized = true;
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
return this.each(function() {
typeof options == 'string' ?
$.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.8.5";
// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window['DP_jQuery_' + dpuuid] = $;
})(jQuery);
| JavaScript |
// Ẩn. Hiển thị Menu trái
function clickHide(type){
if (type == 1){
$('td.colum_left_lage').css('display','none');
$('td.colum_left_small').css('display','table-cell');
//nv_setCookie( 'colum_left_lage', '0', 86400000);
}
else {
if (type == 2){
$('td.colum_left_small').css('display','none');
$('td.colum_left_lage').css('display','table-cell');
//nv_setCookie( 'colum_left_lage', '1', 86400000);
}
}
}
// show or hide menu
function show_menu(){
var showmenu = ( nv_getCookie( 'colum_left_lage' ) ) ? ( nv_getCookie('colum_left_lage')) : '1';
if (showmenu == '1') {
$('td.colum_left_small').hide();
$('td.colum_left_lage').show();
}else {
$('td.colum_left_small').show();
$('td.colum_left_lage').hide();
}
}
// Submit button form
$(document).ready(function() {
$('#bt_del').bind('click', function()
{
$('#adminform').submit();
});
}); | JavaScript |
/*
* jqModal - Minimalist Modaling with jQuery
* (http://dev.iceburg.net/jquery/jqModal/)
*
* Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* $Version: 03/01/2009 +r14
*/
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};
$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};
$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
if(c.modal) {if(!A[0])L('bind');A.push(s);}
else if(c.overlay > 0)h.w.jqmAddClose(o);
else o=F;
h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
else if(cc)h.w.jqmAddClose($(cc,h.w));
if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
(c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery); | JavaScript |
Calendar.LANG("ro", "Română", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Astăzi",
today: "Astăzi", // appears in bottom bar
wk: "săp.",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Ianuarie",
"Februarie",
"Martie",
"Aprilie",
"Mai",
"Iunie",
"Iulie",
"August",
"Septembrie",
"Octombrie",
"Noiembrie",
"Decembrie" ],
smn : [ "Ian",
"Feb",
"Mar",
"Apr",
"Mai",
"Iun",
"Iul",
"Aug",
"Sep",
"Oct",
"Noi",
"Dec" ],
dn : [ "Duminică",
"Luni",
"Marţi",
"Miercuri",
"Joi",
"Vineri",
"Sâmbătă",
"Duminică" ],
sdn : [ "Du",
"Lu",
"Ma",
"Mi",
"Jo",
"Vi",
"Sâ",
"Du" ]
});
| JavaScript |
Calendar.LANG("cn", "中文", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "今天",
today: "今天", // appears in bottom bar
wk: "周",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "AM",
PM: "PM",
mn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
smn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
dn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ],
sdn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ]
});
| JavaScript |
Calendar.LANG("ru", "русский", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Сегодня",
today: "Сегодня", // appears in bottom bar
wk: "нед",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "январь",
"февраль",
"март",
"апрель",
"май",
"июнь",
"июль",
"август",
"сентябрь",
"октябрь",
"ноябрь",
"декабрь" ],
smn : [ "янв",
"фев",
"мар",
"апр",
"май",
"июн",
"июл",
"авг",
"сен",
"окт",
"ноя",
"дек" ],
dn : [ "воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота",
"воскресенье" ],
sdn : [ "вск",
"пон",
"втр",
"срд",
"чет",
"пят",
"суб",
"вск" ]
});
| JavaScript |
Calendar.LANG("fr", "Français", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday : "Aujourd'hui",
today: "Aujourd'hui", // appears in bottom bar
wk: "sm.",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Janvier",
"Février",
"Mars",
"Avril",
"Mai",
"Juin",
"Juillet",
"Août",
"Septembre",
"Octobre",
"Novembre",
"Décembre" ],
smn : [ "Jan",
"Fév",
"Mar",
"Avr",
"Mai",
"Juin",
"Juil",
"Aou",
"Sep",
"Oct",
"Nov",
"Déc" ],
dn : [ "Dimanche",
"Lundi",
"Mardi",
"Mercredi",
"Jeudi",
"Vendredi",
"Samedi",
"Dimanche" ],
sdn : [ "Di",
"Lu",
"Ma",
"Me",
"Je",
"Ve",
"Sa",
"Di" ]
});
| JavaScript |
Calendar.LANG("pt", "Portuguese", {
fdow: 1, // primeiro dia da semana para esse local; 0 = Domingo, 1 = Segunda, etc.
goToday: "Dia de Hoje",
today: "Hoje",
wk: "sm",
weekend: "0,6", // 0 = Domingo, 1 = Segunda, etc.
AM: "am",
PM: "pm",
mn : [ "Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro" ],
smn : [ "Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez" ],
dn : [ "Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sábado",
"Domingo" ],
sdn : [ "Dom",
"Seg",
"Ter",
"Qua",
"Qui",
"Sex",
"Sab",
"Dom" ]
});
| JavaScript |
Calendar.LANG("cz", "Czech", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Ukaž dnešek",
today: "Dnes", // appears in bottom bar
wk: "týd",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Leden",
"Únor",
"Březen",
"Duben",
"Květen",
"Červen",
"Červenec",
"Srpen",
"Září",
"Říjen",
"Listopad",
"Prosinec" ],
smn : [ "Led",
"Úno",
"Bře",
"Dub",
"Kvě",
"Črn",
"Črc",
"Srp",
"Zář",
"Říj",
"Lis",
"Pro" ],
dn : [ "Neděle",
"Pondělí",
"Úterý",
"Středa",
"Čtvrtek",
"Pátek",
"Sobota",
"Neděle" ],
sdn : [ "Ne",
"Po",
"Út",
"St",
"Čt",
"Pá",
"So",
"Ne" ]
});
| JavaScript |
Calendar.LANG("de", "Deutsch", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday : "Heute ausw\u00e4hlen",
today: "Heute", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember" ],
smn : [ "Jan",
"Feb",
"M\u00e4r",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez" ],
dn : [ "Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
"Sonntag" ],
sdn : [ "So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa",
"So" ]
});
| JavaScript |
Calendar.LANG("jp", "Japanese", {
fdow: 1, // 地元の週の初めの日; 0 = 日曜日, 1 = 月曜日, 等.
goToday: "本日へ",
today: "本日", // ボットンバーに表示
wk: "週",
weekend: "0,6", // 0 = 日曜日, 1 = 月曜日, 等.
AM: "am",
PM: "pm",
mn : [ "1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月" ],
smn : [ "1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月" ],
dn : [ "日曜日",
"月曜日",
"火曜日",
"水曜日",
"木曜日",
"金曜日",
"土曜日",
"日曜日" ],
sdn : [ "日",
"月",
"火",
"水",
"木",
"金",
"土",
"日" ]
});
| JavaScript |
Calendar.LANG("it", "Italiano", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Vai a oggi",
today: "Oggi", // appears in bottom bar
wk: "set",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Gennaio",
"Febbraio",
"Marzo",
"Aprile",
"Maggio",
"Giugno",
"Luglio",
"Agosto",
"Settembre",
"Ottobre",
"Novembre",
"Dicembre" ],
smn : [ "Gen",
"Feb",
"Mar",
"Apr",
"Mag",
"Giu",
"Lug",
"Ago",
"Set",
"Ott",
"Nov",
"Dic" ],
dn : [ "Domenica",
"Lunedì",
"Martedì",
"Mercoledì",
"Giovedi",
"Venerdì",
"Sabato",
"Domenica" ],
sdn : [ "Do",
"Lu",
"Ma",
"Me",
"Gi",
"Ve",
"Sa",
"Do" ]
});
| JavaScript |
Calendar.LANG("es", "Español", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Ir a Hoy",
today: "Hoy", // appears in bottom bar
wk: "sem",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre" ],
smn : [ "Ene",
"Feb",
"Mar",
"Abr",
"May",
"Jun",
"Jul",
"Ago",
"Sep",
"Oct",
"Nov",
"Dic" ],
dn : [ "Domingo",
"Lunes",
"Martes",
"Miercoles",
"Jueves",
"Viernes",
"Sabado",
"Domingo" ],
sdn : [ "Do",
"Lu",
"Ma",
"Mi",
"Ju",
"Vi",
"Sa",
"Do" ]
});
| JavaScript |
// autor: Piotr kwiatkowski
// www: http://pasjonata.net
Calendar.LANG("pl", "Polish", {
fdow: 1, // pierwszy dzień tygodnia; 0 = Niedziela, 1 = Poniedziałek, itd.
goToday: "Idzie Dzisiaj",
today: "Dziś",
wk: "wk",
weekend: "0,6", // 0 = Niedziela, 1 = Poniedziałek, itd.
AM: "am",
PM: "pm",
mn : [ "Styczeń",
"Luty",
"Marzec",
"Kwiecień",
"Maj",
"Czerwiec",
"Lipiec",
"Sierpień",
"Wrzesień",
"Październik",
"Listopad",
"Grudzień" ],
smn : [ "Sty",
"Lut",
"Mar",
"Kwi",
"Maj",
"Cze",
"Lip",
"Sie",
"Wrz",
"Paź",
"Lis",
"Gru" ],
dn : [ "Niedziela",
"Poniedziałek",
"Wtorek",
"Środa",
"Czwartek",
"Piątek",
"Sobota",
"Niedziela" ],
sdn : [ "Ni",
"Po",
"Wt",
"Śr",
"Cz",
"Pi",
"So",
"Ni" ]
});
| JavaScript |
Calendar.LANG("en", "English", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Go Today",
today: "Today", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December" ],
smn : [ "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec" ],
dn : [ "Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" ],
sdn : [ "Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su" ]
});
| JavaScript |
var makelist = {
listid : '' ,
listname : '',
init:function(id, name)
{
this.listid = listid ;
this.listname = listname ;
},
add : function (id)
{
//list proid
var listid = document.getElementById("proid").value ;
if(listid=='')
listid = id ;
else
listid = listid + "," + id ;
document.getElementById("proid").value = listid;
},
remove:function (items)
{
var listid = document.getElementById("proid").value ;
var arrID = listid.split(",") ;
arrID.splice(items,1);
listid = arrID.toString();
document.getElementById("proid").value = listid;
},
chkid : function (id)
{
var listid = document.getElementById("proid").value ;
var arrID = listid.split(",") ;
for(var i =0; i<arrID.length;i++)
{
if(arrID[i]==id) return true;
}
return false ;
},
render:function ()
{
var lsid = document.getElementById('proid').value;
if(lsid=='') return ;
document.getElementById('proid').value = '';
var xmlhttp = ajax.isdom("get_product.php?mode=proname&lsid="+lsid);
var proname = xmlhttp.responseText ;
var arr = proname.split("~");
for(var i=0;i<arr.length;i++)
{
var pro = arr[i].split("|");
appendOptionLast(pro[1], pro[0]);
add_proid(pro[0]) ;
}
} ,
add_product:function (url)
{
var obj = showpopup(url) ;
if (obj == null) return ;
if(ckhexist(obj.orgid))
alert("Product is exist") ;
else
{
add_proid(obj.orgid) ;
appendOptionLast(obj.orgname, obj.orgid) ;
}
},
remove_product:function ()
{
var items = removeOptionSelected();
remove_proid(items) ;
}
};
var count1 = 0;
var count2 = 0;
var opts = {} ;
var insertOptionBefore = function (num)
{
var elSel = document.getElementById('product_name');
if (elSel.selectedIndex >= 0) {
var elOptNew = document.createElement('option');
elOptNew.text = 'Insert' + num;
elOptNew.value = 'insert' + num;
var elOptOld = elSel.options[elSel.selectedIndex];
try {
elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew, elSel.selectedIndex); // IE only
}
}
}
var removeOptionSelected = function ()
{
var elSel = document.getElementById('product_name');
for (var i = elSel.length - 1; i>=0; i--) {
if (elSel.options[i].selected) {
elSel.remove(i);
return i ;
}
}
return;
}
var appendOptionLast = function (text, value)
{
var elOptNew = document.createElement('option');
elOptNew.text = text ;
elOptNew.value = value ;
var elSel = document.getElementById('product_name');
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}
}
var removeOptionLast = function ()
{
var elSel = document.getElementById('product_name');
if (elSel.length > 0)
{
elSel.remove(elSel.length - 1);
}
} | JavaScript |
/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
;(function($) {
$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function(input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {
case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data){
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;
var v = selected.result;
//var id = selected.value;
previousValue = v;
if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function(i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join( options.multipleSeparator );
}
v += options.multipleSeparator;
//id += options.multipleSeparator;
}
$input.val(v);
//$("#"+ options.fieldID).val(id) ;
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}
var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue )
return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value)
return [""];
if (!options.multiple)
return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function(word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
if (words.length == 1)
return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else {
$input.val( "" );
$input.trigger("result", null);
}
}
}
);
}
};
function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure)
{
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
type: 'POST',
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function(options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase)
s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word"){
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){
length++;
}
data[q] = value;
}
function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush(){
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI'){
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});
if( options.width > 0 )
element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}
function moveSelect(step)
{
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available)
{
return options.max && options.max < available
? options.max
: available;
}
function fillList()
{
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}
return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}
}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};
$.fn.selection = function(start, end) {
if (start !== undefined) {
return this.each(function() {
if( this.createTextRange ){
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if( this.setSelectionRange ){
this.setSelectionRange(start, end);
} else if( this.selectionStart ){
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if ( field.createTextRange ) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if( field.selectionStart !== undefined ){
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery); | JavaScript |
/*
* Inline Form Validation Engine 2.0 Beta, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (form.data('jqv') === undefined || form.data('jqv') == null ) {
methods._saveOptions(form, options);
// bind all formError elements to close on click
$(".formError").live("click", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).remove();
});
});
}
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
if (!options.binded) {
if(options.bindMethod == "bind"){
// bind fields
form.find("[class*=validate]").not("[type=checkbox]").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").bind("click", methods._onFieldEvent);
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
}else if(options.bindMethod == "live"){
// bind fields with LIVE (for persistant state)
form.find("[class*=validate]").not("[type=checkbox]").live(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent);
// bind form.submit
form.live("submit", methods._onSubmitEvent);
}
options.binded = true;
}
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
if (options.binded) {
// unbind fields
form.find("[class*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").unbind("click", methods._onFieldEvent);
// unbind form.submit
form.unbind("submit", methods.onAjaxFormComplete);
// unbind live fields (kill)
form.find("[class*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").die("click", methods._onFieldEvent);
// unbind form.submit
form.die("submit", methods.onAjaxFormComplete);
form.removeData('jqv');
}
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
return methods._validateFields(this);
},
/**
* Validates one field, shows prompt accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validateField: function(el) {
var options = $(this).data('jqv');
return methods._validateField($(el), options);
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: this methods performs fields and form ajax validations(if setup)
*
* @return true if the form validates, false if it fails, undefined if ajax is used for form validation
*/
validateform: function() {
return methods._onSubmitEvent(this);
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form');
var options = form.data('jqv');
// No option, take default one
if(!options) options = methods._saveOptions(this, options);
if(promptPosition)
options.promptPosition=promptPosition;
options.showArrow = showArrow===true;
methods._showPrompt(this, promptText, type, false, options);
},
/**
* Closes all error prompts on the page
*/
hidePrompt: function() {
var promptClass = "."+ $(this).attr("id").replace(":","_") + "formError"
$(promptClass).fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
if($(this).is("form")){
var closingtag = "parentForm"+$(this).attr('id');
}else{
var closingtag = $(this).attr('id') +"formError"
}
$('.'+closingtag).fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
$('.formError').fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function() {
var field = $(this);
var form = field.closest('form');
var options = form.data('jqv');
// validate the current field
methods._validateField(field, options);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
// validate each field (- skip field ajax validation, no necessary since we will perform an ajax form validation)
var r=methods._validateFields(form, true);
var options = form.data('jqv');
// validate the form using AJAX
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
return false;
}
if(options.onValidationComplete) {
options.onValidationComplete(form, r);
return false;
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (value === false) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form, skipAjaxFieldValidation) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// first, evaluate status of non ajax fields
form.find('[class*=validate]').not(':hidden').each( function() {
var field = $(this);
// fields being valiated though ajax are marked with 'ajaxed',
// skip them
if (!field.hasClass("ajaxed"))
errorFound |= methods._validateField(field, options, skipAjaxFieldValidation);
});
// second, check to see if all ajax calls completed ok
errorFound |= !methods._checkAjaxStatus(options);
// thrird, check status and scroll the container accordingly
if (errorFound) {
if (options.scroll) {
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
// look for the visually top prompt
var destination = Number.MAX_VALUE;
var lst = $(".formError:not('.greenPopup')");
for (var i = 0; i < lst.length; i++) {
var d = $(lst[i]).offset().top;
if (d < destination)
destination = d;
}
if (!options.isOverflown)
$("html:not(:animated),body:not(:animated)").animate({
scrollTop: destination
}, 1100);
else {
var overflowDIV = $(options.overflownDIV);
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({
scrollTop: destination
}, 1100);
}
}
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
$.ajax({
type: "GET",
url: form.attr("action"),
cache: false,
dataType: "json",
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if (json !== true) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
if (value[1] === true) {
if (msg == "")
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "pass", false, options);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "", false, options);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, "", options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return true if field is valid
*/
_validateField: function(field, options, skipAjaxFieldValidation) {
if (!field.attr("id"))
$.error("jQueryValidate: an ID attribute is required for this field: " + field.attr("name") + " class:" +
field.attr("class"));
var rulesParsing = field.attr('class');
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (getRules === null)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var required = false;
options.isError = false;
options.showArrow = true;
optional = false;
for (var i = 0; i < rules.length; i++) {
var errorMsg = undefined;
switch (rules[i]) {
case "optional":
optional = true;
break;
case "required":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;
case "custom":
errorMsg = methods._customRegex(field, rules, i, options);
break;
case "ajax":
if(skipAjaxFieldValidation===false) {
// ajax has its own prompts handling technique
methods._ajax(field, rules, i, options);
isAjaxValidator = true;
}
break;
case "minSize":
errorMsg = methods._minSize(field, rules, i, options);
break;
case "maxSize":
errorMsg = methods._maxSize(field, rules, i, options);
break;
case "min":
errorMsg = methods._min(field, rules, i, options);
break;
case "max":
errorMsg = methods._max(field, rules, i, options);
break;
case "past":
errorMsg = methods._past(field, rules, i, options);
break;
case "future":
errorMsg = methods._future(field, rules, i, options);
break;
case "maxCheckbox":
errorMsg = methods._maxCheckbox(field, rules, i, options);
field = $($("input[name='" + fieldName + "']"));
break;
case "minCheckbox":
errorMsg = methods._minCheckbox(field, rules, i, options);
field = $($("input[name='" + fieldName + "']"));
break;
case "equals":
errorMsg = methods._equals(field, rules, i, options);
break;
case "funcCall":
errorMsg = methods._funcCall(field, rules, i, options);
break;
default:
//$.error("jQueryValidator rule not found"+rules[i]);
}
if (errorMsg !== undefined) {
promptText += errorMsg + "<br/>";
options.isError = true;
}
}
// If the rules required is not added, an empty field is not validated
if(!required && !optional ){
if(field.val() == "") options.isError = false;
}
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.attr("type");
if ((fieldType == "radio" || fieldType == "checkbox") && $("input[name='" + fieldName + "']").size() > 1) {
field = $($("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (!isAjaxValidator) {
if (options.isError)
methods._showPrompt(field, promptText, "", false, options);
else
methods._closePrompt(field);
}
return options.isError;
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_required: function(field, rules, i, options) {
switch (field.attr("type")) {
case "text":
case "password":
case "textarea":
case "file":
default:
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "radio":
case "checkbox":
var name = field.attr("name");
if ($("input[name='" + name + "']:checked").size() === 0) {
if ($("input[name='" + name + "']").size() === 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
// required for <select>
case "select-one":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "select-multiple":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.find("option:selected").val())
return options.allrules[rules[i]].alertText;
break;
}
},
/**
* Validate Regex rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_customRegex: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
if(rule===undefined) {
alert("jqv:custom rule not found "+customRule);
return;
}
var ex=rule.regex;
if(ex===undefined) {
alert("jqv:custom regex not found "+customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.attr('value')))
return options.allrules[customRule].alertText;
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn = window[functionName];
if (typeof(fn) === 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.attr('value') != $("#" + equalsField).attr('value'))
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.attr('value').length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.attr('value').length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.attr('value'));
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.attr('value'));
if (len >max ) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p);
var vdate = methods._parseDate(field.attr('value'));
if (vdate > pdate ) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p);
var vdate = methods._parseDate(field.attr('value'));
if (vdate < pdate ) {
var rule = options.allrules.future;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = $("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = $("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " +
options.allrules.minCheckbox.alertText2;
}
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
if (!extraData)
extraData = "";
if (!options.isError) {
$.ajax({
type: "GET",
url: rule.url,
cache: false,
dataType: "json",
data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.attr("value") + "&extraData=" + extraData,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {
// build the loading prompt
var loadingText = rule.alertTextLoad;
if (loadingText)
methods._showPrompt(field, loadingText, "load", true, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
if (status === false) {
// Houston we got a problem
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
var promptText = rule.alertText;
methods._showPrompt(errorField, promptText, "", true, options);
} else {
if (options.ajaxValidCache[errorFieldId] !== undefined)
options.ajaxValidCache[errorFieldId] = true;
// see if we should display a green prompt
var alertTextOk = rule.alertTextOk;
if (alertTextOk)
methods._showPrompt(errorField, alertTextOk, "pass", true, options);
else
methods._closePrompt(errorField);
}
}
}
});
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if(data.status === 0 && transport === null)
alert("The page is not served from a server! ajax call failed");
else if(console)
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if(dateParts!==d)
dateParts = d.split("/");
return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options) {
var prompt = methods._getPrompt(field);
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(field.attr("id").replace(":","_") + "formError");
// add a class name to identify the parent form of the prompt
if(field.is(":input")) prompt.addClass("parentForm"+field.parents('form').attr("id").replace(":","_"));
prompt.addClass("formError");
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
switch (options.promptPosition) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
//Cedric: Needed if a container is in position:relative
// insert prompt in the form or in the overflown container?
if (options.isOverflown)
field.before(prompt);
else
$("body").append(prompt);
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
});
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options) {
if (prompt) {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
prompt.animate({
"top": pos.callerTopPosition,
"marginTop": pos.marginTopSize
});
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.remove();
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var className = "." + field.attr("id").replace(":","_") + "formError";
var match = $(className)[0];
if (match)
return $(match);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function(field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var promptHeight = promptElmt.height();
var overflow = options.isOverflown;
if (overflow) {
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
} else {
var offset = field.offset();
promptTopPosition = offset.top;
promptleftPosition = offset.left;
marginTopSize = 0;
}
switch (options.promptPosition) {
default:
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - 30;
else {
promptleftPosition += fieldWidth - 30;
promptTopPosition += -promptHeight;
}
break;
case "topLeft":
promptTopPosition += -promptHeight - 10;
break;
case "centerRight":
promptleftPosition += fieldWidth + 13;
break;
case "bottomLeft":
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - 30;
promptTopPosition += field.height() + 5;
}
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
var userOptions = $.extend({
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight
promptPosition: "topRight",
bindMethod:"bind",
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when the form is displayed within a scrolling DIV
isOverflown: false,
overflownDIV: "",
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
allrules: allRules,
// true when form and fields are binded
binded: false,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {}
}, options);
form.data('jqv', userOptions);
return userOptions;
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if(!form[0]) return false; // stop here if the form does not exist
if (typeof(method) === 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if(method != "showPrompt" && method != "hidePrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
})(jQuery);
| JavaScript |
/**
* jquery.Jcrop.js v0.9.12
* jQuery Image Cropping Plugin - released under MIT License
* Author: Kelly Hallman <khallman@gmail.com>
* http://github.com/tapmodo/Jcrop
* Copyright (c) 2008-2013 Tapmodo Interactive LLC {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* }}}
*/
(function ($) {
$.Jcrop = function (obj, opt) {
var options = $.extend({}, $.Jcrop.defaults),
docOffset,
_ua = navigator.userAgent.toLowerCase(),
is_msie = /msie/.test(_ua),
ie6mode = /msie [1-6]\./.test(_ua);
// Internal Methods {{{
function px(n) {
return Math.round(n) + 'px';
}
function cssClass(cl) {
return options.baseClass + '-' + cl;
}
function supportsColorFade() {
return $.fx.step.hasOwnProperty('backgroundColor');
}
function getPos(obj) //{{{
{
var pos = $(obj).offset();
return [pos.left, pos.top];
}
//}}}
function mouseAbs(e) //{{{
{
return [(e.pageX - docOffset[0]), (e.pageY - docOffset[1])];
}
//}}}
function setOptions(opt) //{{{
{
if (typeof(opt) !== 'object') opt = {};
options = $.extend(options, opt);
$.each(['onChange','onSelect','onRelease','onDblClick'],function(i,e) {
if (typeof(options[e]) !== 'function') options[e] = function () {};
});
}
//}}}
function startDragMode(mode, pos, touch) //{{{
{
docOffset = getPos($img);
Tracker.setCursor(mode === 'move' ? mode : mode + '-resize');
if (mode === 'move') {
return Tracker.activateHandlers(createMover(pos), doneSelect, touch);
}
var fc = Coords.getFixed();
var opp = oppLockCorner(mode);
var opc = Coords.getCorner(oppLockCorner(opp));
Coords.setPressed(Coords.getCorner(opp));
Coords.setCurrent(opc);
Tracker.activateHandlers(dragmodeHandler(mode, fc), doneSelect, touch);
}
//}}}
function dragmodeHandler(mode, f) //{{{
{
return function (pos) {
if (!options.aspectRatio) {
switch (mode) {
case 'e':
pos[1] = f.y2;
break;
case 'w':
pos[1] = f.y2;
break;
case 'n':
pos[0] = f.x2;
break;
case 's':
pos[0] = f.x2;
break;
}
} else {
switch (mode) {
case 'e':
pos[1] = f.y + 1;
break;
case 'w':
pos[1] = f.y + 1;
break;
case 'n':
pos[0] = f.x + 1;
break;
case 's':
pos[0] = f.x + 1;
break;
}
}
Coords.setCurrent(pos);
Selection.update();
};
}
//}}}
function createMover(pos) //{{{
{
var lloc = pos;
KeyManager.watchKeys();
return function (pos) {
Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
lloc = pos;
Selection.update();
};
}
//}}}
function oppLockCorner(ord) //{{{
{
switch (ord) {
case 'n':
return 'sw';
case 's':
return 'nw';
case 'e':
return 'nw';
case 'w':
return 'ne';
case 'ne':
return 'sw';
case 'nw':
return 'se';
case 'se':
return 'nw';
case 'sw':
return 'ne';
}
}
//}}}
function createDragger(ord) //{{{
{
return function (e) {
if (options.disabled) {
return false;
}
if ((ord === 'move') && !options.allowMove) {
return false;
}
// Fix position of crop area when dragged the very first time.
// Necessary when crop image is in a hidden element when page is loaded.
docOffset = getPos($img);
btndown = true;
startDragMode(ord, mouseAbs(e));
e.stopPropagation();
e.preventDefault();
return false;
};
}
//}}}
function presize($obj, w, h) //{{{
{
var nw = $obj.width(),
nh = $obj.height();
if ((nw > w) && w > 0) {
nw = w;
nh = (w / $obj.width()) * $obj.height();
}
if ((nh > h) && h > 0) {
nh = h;
nw = (h / $obj.height()) * $obj.width();
}
xscale = $obj.width() / nw;
yscale = $obj.height() / nh;
$obj.width(nw).height(nh);
}
//}}}
function unscale(c) //{{{
{
return {
x: c.x * xscale,
y: c.y * yscale,
x2: c.x2 * xscale,
y2: c.y2 * yscale,
w: c.w * xscale,
h: c.h * yscale
};
}
//}}}
function doneSelect(pos) //{{{
{
var c = Coords.getFixed();
if ((c.w > options.minSelect[0]) && (c.h > options.minSelect[1])) {
Selection.enableHandles();
Selection.done();
} else {
Selection.release();
}
Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default');
}
//}}}
function newSelection(e) //{{{
{
if (options.disabled) {
return false;
}
if (!options.allowSelect) {
return false;
}
btndown = true;
docOffset = getPos($img);
Selection.disableHandles();
Tracker.setCursor('crosshair');
var pos = mouseAbs(e);
Coords.setPressed(pos);
Selection.update();
Tracker.activateHandlers(selectDrag, doneSelect, e.type.substring(0,5)==='touch');
KeyManager.watchKeys();
e.stopPropagation();
e.preventDefault();
return false;
}
//}}}
function selectDrag(pos) //{{{
{
Coords.setCurrent(pos);
Selection.update();
}
//}}}
function newTracker() //{{{
{
var trk = $('<div></div>').addClass(cssClass('tracker'));
if (is_msie) {
trk.css({
opacity: 0,
backgroundColor: 'white'
});
}
return trk;
}
//}}}
// }}}
// Initialization {{{
// Sanitize some options {{{
if (typeof(obj) !== 'object') {
obj = $(obj)[0];
}
if (typeof(opt) !== 'object') {
opt = {};
}
// }}}
setOptions(opt);
// Initialize some jQuery objects {{{
// The values are SET on the image(s) for the interface
// If the original image has any of these set, they will be reset
// However, if you destroy() the Jcrop instance the original image's
// character in the DOM will be as you left it.
var img_css = {
border: 'none',
visibility: 'visible',
margin: 0,
padding: 0,
position: 'absolute',
top: 0,
left: 0
};
var $origimg = $(obj),
img_mode = true;
if (obj.tagName == 'IMG') {
// Fix size of crop image.
// Necessary when crop image is within a hidden element when page is loaded.
if ($origimg[0].width != 0 && $origimg[0].height != 0) {
// Obtain dimensions from contained img element.
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
// Obtain dimensions from temporary image in case the original is not loaded yet (e.g. IE 7.0).
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
}
var $img = $origimg.clone().removeAttr('id').css(img_css).show();
$img.width($origimg.width());
$img.height($origimg.height());
$origimg.after($img).hide();
} else {
$img = $origimg.css(img_css).show();
img_mode = false;
if (options.shade === null) { options.shade = true; }
}
presize($img, options.boxWidth, options.boxHeight);
var boundx = $img.width(),
boundy = $img.height(),
$div = $('<div />').width(boundx).height(boundy).addClass(cssClass('holder')).css({
position: 'relative',
backgroundColor: options.bgColor
}).insertAfter($origimg).append($img);
if (options.addClass) {
$div.addClass(options.addClass);
}
var $img2 = $('<div />'),
$img_holder = $('<div />')
.width('100%').height('100%').css({
zIndex: 310,
position: 'absolute',
overflow: 'hidden'
}),
$hdl_holder = $('<div />')
.width('100%').height('100%').css('zIndex', 320),
$sel = $('<div />')
.css({
position: 'absolute',
zIndex: 600
}).dblclick(function(){
var c = Coords.getFixed();
options.onDblClick.call(api,c);
}).insertBefore($img).append($img_holder, $hdl_holder);
if (img_mode) {
$img2 = $('<img />')
.attr('src', $img.attr('src')).css(img_css).width(boundx).height(boundy),
$img_holder.append($img2);
}
if (ie6mode) {
$sel.css({
overflowY: 'hidden'
});
}
var bound = options.boundary;
var $trk = newTracker().width(boundx + (bound * 2)).height(boundy + (bound * 2)).css({
position: 'absolute',
top: px(-bound),
left: px(-bound),
zIndex: 290
}).mousedown(newSelection);
/* }}} */
// Set more variables {{{
var bgcolor = options.bgColor,
bgopacity = options.bgOpacity,
xlimit, ylimit, xmin, ymin, xscale, yscale, enabled = true,
btndown, animating, shift_down;
docOffset = getPos($img);
// }}}
// }}}
// Internal Modules {{{
// Touch Module {{{
var Touch = (function () {
// Touch support detection function adapted (under MIT License)
// from code by Jeffrey Sambells - http://github.com/iamamused/
function hasTouchSupport() {
var support = {}, events = ['touchstart', 'touchmove', 'touchend'],
el = document.createElement('div'), i;
try {
for(i=0; i<events.length; i++) {
var eventName = events[i];
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
support[events[i]] = isSupported;
}
return support.touchstart && support.touchend && support.touchmove;
}
catch(err) {
return false;
}
}
function detectSupport() {
if ((options.touchSupport === true) || (options.touchSupport === false)) return options.touchSupport;
else return hasTouchSupport();
}
return {
createDragger: function (ord) {
return function (e) {
if (options.disabled) {
return false;
}
if ((ord === 'move') && !options.allowMove) {
return false;
}
docOffset = getPos($img);
btndown = true;
startDragMode(ord, mouseAbs(Touch.cfilter(e)), true);
e.stopPropagation();
e.preventDefault();
return false;
};
},
newSelection: function (e) {
return newSelection(Touch.cfilter(e));
},
cfilter: function (e){
e.pageX = e.originalEvent.changedTouches[0].pageX;
e.pageY = e.originalEvent.changedTouches[0].pageY;
return e;
},
isSupported: hasTouchSupport,
support: detectSupport()
};
}());
// }}}
// Coords Module {{{
var Coords = (function () {
var x1 = 0,
y1 = 0,
x2 = 0,
y2 = 0,
ox, oy;
function setPressed(pos) //{{{
{
pos = rebound(pos);
x2 = x1 = pos[0];
y2 = y1 = pos[1];
}
//}}}
function setCurrent(pos) //{{{
{
pos = rebound(pos);
ox = pos[0] - x2;
oy = pos[1] - y2;
x2 = pos[0];
y2 = pos[1];
}
//}}}
function getOffset() //{{{
{
return [ox, oy];
}
//}}}
function moveOffset(offset) //{{{
{
var ox = offset[0],
oy = offset[1];
if (0 > x1 + ox) {
ox -= ox + x1;
}
if (0 > y1 + oy) {
oy -= oy + y1;
}
if (boundy < y2 + oy) {
oy += boundy - (y2 + oy);
}
if (boundx < x2 + ox) {
ox += boundx - (x2 + ox);
}
x1 += ox;
x2 += ox;
y1 += oy;
y2 += oy;
}
//}}}
function getCorner(ord) //{{{
{
var c = getFixed();
switch (ord) {
case 'ne':
return [c.x2, c.y];
case 'nw':
return [c.x, c.y];
case 'se':
return [c.x2, c.y2];
case 'sw':
return [c.x, c.y2];
}
}
//}}}
function getFixed() //{{{
{
if (!options.aspectRatio) {
return getRect();
}
// This function could use some optimization I think...
var aspect = options.aspectRatio,
min_x = options.minSize[0] / xscale,
//min_y = options.minSize[1]/yscale,
max_x = options.maxSize[0] / xscale,
max_y = options.maxSize[1] / yscale,
rw = x2 - x1,
rh = y2 - y1,
rwa = Math.abs(rw),
rha = Math.abs(rh),
real_ratio = rwa / rha,
xx, yy, w, h;
if (max_x === 0) {
max_x = boundx * 10;
}
if (max_y === 0) {
max_y = boundy * 10;
}
if (real_ratio < aspect) {
yy = y2;
w = rha * aspect;
xx = rw < 0 ? x1 - w : w + x1;
if (xx < 0) {
xx = 0;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
} else if (xx > boundx) {
xx = boundx;
h = Math.abs((xx - x1) / aspect);
yy = rh < 0 ? y1 - h : h + y1;
}
} else {
xx = x2;
h = rwa / aspect;
yy = rh < 0 ? y1 - h : y1 + h;
if (yy < 0) {
yy = 0;
w = Math.abs((yy - y1) * aspect);
xx = rw < 0 ? x1 - w : w + x1;
} else if (yy > boundy) {
yy = boundy;
w = Math.abs(yy - y1) * aspect;
xx = rw < 0 ? x1 - w : w + x1;
}
}
// Magic %-)
if (xx > x1) { // right side
if (xx - x1 < min_x) {
xx = x1 + min_x;
} else if (xx - x1 > max_x) {
xx = x1 + max_x;
}
if (yy > y1) {
yy = y1 + (xx - x1) / aspect;
} else {
yy = y1 - (xx - x1) / aspect;
}
} else if (xx < x1) { // left side
if (x1 - xx < min_x) {
xx = x1 - min_x;
} else if (x1 - xx > max_x) {
xx = x1 - max_x;
}
if (yy > y1) {
yy = y1 + (x1 - xx) / aspect;
} else {
yy = y1 - (x1 - xx) / aspect;
}
}
if (xx < 0) {
x1 -= xx;
xx = 0;
} else if (xx > boundx) {
x1 -= xx - boundx;
xx = boundx;
}
if (yy < 0) {
y1 -= yy;
yy = 0;
} else if (yy > boundy) {
y1 -= yy - boundy;
yy = boundy;
}
return makeObj(flipCoords(x1, y1, xx, yy));
}
//}}}
function rebound(p) //{{{
{
if (p[0] < 0) p[0] = 0;
if (p[1] < 0) p[1] = 0;
if (p[0] > boundx) p[0] = boundx;
if (p[1] > boundy) p[1] = boundy;
return [Math.round(p[0]), Math.round(p[1])];
}
//}}}
function flipCoords(x1, y1, x2, y2) //{{{
{
var xa = x1,
xb = x2,
ya = y1,
yb = y2;
if (x2 < x1) {
xa = x2;
xb = x1;
}
if (y2 < y1) {
ya = y2;
yb = y1;
}
return [xa, ya, xb, yb];
}
//}}}
function getRect() //{{{
{
var xsize = x2 - x1,
ysize = y2 - y1,
delta;
if (xlimit && (Math.abs(xsize) > xlimit)) {
x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
}
if (ylimit && (Math.abs(ysize) > ylimit)) {
y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
}
if (ymin / yscale && (Math.abs(ysize) < ymin / yscale)) {
y2 = (ysize > 0) ? (y1 + ymin / yscale) : (y1 - ymin / yscale);
}
if (xmin / xscale && (Math.abs(xsize) < xmin / xscale)) {
x2 = (xsize > 0) ? (x1 + xmin / xscale) : (x1 - xmin / xscale);
}
if (x1 < 0) {
x2 -= x1;
x1 -= x1;
}
if (y1 < 0) {
y2 -= y1;
y1 -= y1;
}
if (x2 < 0) {
x1 -= x2;
x2 -= x2;
}
if (y2 < 0) {
y1 -= y2;
y2 -= y2;
}
if (x2 > boundx) {
delta = x2 - boundx;
x1 -= delta;
x2 -= delta;
}
if (y2 > boundy) {
delta = y2 - boundy;
y1 -= delta;
y2 -= delta;
}
if (x1 > boundx) {
delta = x1 - boundy;
y2 -= delta;
y1 -= delta;
}
if (y1 > boundy) {
delta = y1 - boundy;
y2 -= delta;
y1 -= delta;
}
return makeObj(flipCoords(x1, y1, x2, y2));
}
//}}}
function makeObj(a) //{{{
{
return {
x: a[0],
y: a[1],
x2: a[2],
y2: a[3],
w: a[2] - a[0],
h: a[3] - a[1]
};
}
//}}}
return {
flipCoords: flipCoords,
setPressed: setPressed,
setCurrent: setCurrent,
getOffset: getOffset,
moveOffset: moveOffset,
getCorner: getCorner,
getFixed: getFixed
};
}());
//}}}
// Shade Module {{{
var Shade = (function() {
var enabled = false,
holder = $('<div />').css({
position: 'absolute',
zIndex: 240,
opacity: 0
}),
shades = {
top: createShade(),
left: createShade().height(boundy),
right: createShade().height(boundy),
bottom: createShade()
};
function resizeShades(w,h) {
shades.left.css({ height: px(h) });
shades.right.css({ height: px(h) });
}
function updateAuto()
{
return updateShade(Coords.getFixed());
}
function updateShade(c)
{
shades.top.css({
left: px(c.x),
width: px(c.w),
height: px(c.y)
});
shades.bottom.css({
top: px(c.y2),
left: px(c.x),
width: px(c.w),
height: px(boundy-c.y2)
});
shades.right.css({
left: px(c.x2),
width: px(boundx-c.x2)
});
shades.left.css({
width: px(c.x)
});
}
function createShade() {
return $('<div />').css({
position: 'absolute',
backgroundColor: options.shadeColor||options.bgColor
}).appendTo(holder);
}
function enableShade() {
if (!enabled) {
enabled = true;
holder.insertBefore($img);
updateAuto();
Selection.setBgOpacity(1,0,1);
$img2.hide();
setBgColor(options.shadeColor||options.bgColor,1);
if (Selection.isAwake())
{
setOpacity(options.bgOpacity,1);
}
else setOpacity(1,1);
}
}
function setBgColor(color,now) {
colorChangeMacro(getShades(),color,now);
}
function disableShade() {
if (enabled) {
holder.remove();
$img2.show();
enabled = false;
if (Selection.isAwake()) {
Selection.setBgOpacity(options.bgOpacity,1,1);
} else {
Selection.setBgOpacity(1,1,1);
Selection.disableHandles();
}
colorChangeMacro($div,0,1);
}
}
function setOpacity(opacity,now) {
if (enabled) {
if (options.bgFade && !now) {
holder.animate({
opacity: 1-opacity
},{
queue: false,
duration: options.fadeTime
});
}
else holder.css({opacity:1-opacity});
}
}
function refreshAll() {
options.shade ? enableShade() : disableShade();
if (Selection.isAwake()) setOpacity(options.bgOpacity);
}
function getShades() {
return holder.children();
}
return {
update: updateAuto,
updateRaw: updateShade,
getShades: getShades,
setBgColor: setBgColor,
enable: enableShade,
disable: disableShade,
resize: resizeShades,
refresh: refreshAll,
opacity: setOpacity
};
}());
// }}}
// Selection Module {{{
var Selection = (function () {
var awake,
hdep = 370,
borders = {},
handle = {},
dragbar = {},
seehandles = false;
// Private Methods
function insertBorder(type) //{{{
{
var jq = $('<div />').css({
position: 'absolute',
opacity: options.borderOpacity
}).addClass(cssClass(type));
$img_holder.append(jq);
return jq;
}
//}}}
function dragDiv(ord, zi) //{{{
{
var jq = $('<div />').mousedown(createDragger(ord)).css({
cursor: ord + '-resize',
position: 'absolute',
zIndex: zi
}).addClass('ord-'+ord);
if (Touch.support) {
jq.bind('touchstart.jcrop', Touch.createDragger(ord));
}
$hdl_holder.append(jq);
return jq;
}
//}}}
function insertHandle(ord) //{{{
{
var hs = options.handleSize,
div = dragDiv(ord, hdep++).css({
opacity: options.handleOpacity
}).addClass(cssClass('handle'));
if (hs) { div.width(hs).height(hs); }
return div;
}
//}}}
function insertDragbar(ord) //{{{
{
return dragDiv(ord, hdep++).addClass('jcrop-dragbar');
}
//}}}
function createDragbars(li) //{{{
{
var i;
for (i = 0; i < li.length; i++) {
dragbar[li[i]] = insertDragbar(li[i]);
}
}
//}}}
function createBorders(li) //{{{
{
var cl,i;
for (i = 0; i < li.length; i++) {
switch(li[i]){
case'n': cl='hline'; break;
case's': cl='hline bottom'; break;
case'e': cl='vline right'; break;
case'w': cl='vline'; break;
}
borders[li[i]] = insertBorder(cl);
}
}
//}}}
function createHandles(li) //{{{
{
var i;
for (i = 0; i < li.length; i++) {
handle[li[i]] = insertHandle(li[i]);
}
}
//}}}
function moveto(x, y) //{{{
{
if (!options.shade) {
$img2.css({
top: px(-y),
left: px(-x)
});
}
$sel.css({
top: px(y),
left: px(x)
});
}
//}}}
function resize(w, h) //{{{
{
$sel.width(Math.round(w)).height(Math.round(h));
}
//}}}
function refresh() //{{{
{
var c = Coords.getFixed();
Coords.setPressed([c.x, c.y]);
Coords.setCurrent([c.x2, c.y2]);
updateVisible();
}
//}}}
// Internal Methods
function updateVisible(select) //{{{
{
if (awake) {
return update(select);
}
}
//}}}
function update(select) //{{{
{
var c = Coords.getFixed();
resize(c.w, c.h);
moveto(c.x, c.y);
if (options.shade) Shade.updateRaw(c);
awake || show();
if (select) {
options.onSelect.call(api, unscale(c));
} else {
options.onChange.call(api, unscale(c));
}
}
//}}}
function setBgOpacity(opacity,force,now) //{{{
{
if (!awake && !force) return;
if (options.bgFade && !now) {
$img.animate({
opacity: opacity
},{
queue: false,
duration: options.fadeTime
});
} else {
$img.css('opacity', opacity);
}
}
//}}}
function show() //{{{
{
$sel.show();
if (options.shade) Shade.opacity(bgopacity);
else setBgOpacity(bgopacity,true);
awake = true;
}
//}}}
function release() //{{{
{
disableHandles();
$sel.hide();
if (options.shade) Shade.opacity(1);
else setBgOpacity(1);
awake = false;
options.onRelease.call(api);
}
//}}}
function showHandles() //{{{
{
if (seehandles) {
$hdl_holder.show();
}
}
//}}}
function enableHandles() //{{{
{
seehandles = true;
if (options.allowResize) {
$hdl_holder.show();
return true;
}
}
//}}}
function disableHandles() //{{{
{
seehandles = false;
$hdl_holder.hide();
}
//}}}
function animMode(v) //{{{
{
if (v) {
animating = true;
disableHandles();
} else {
animating = false;
enableHandles();
}
}
//}}}
function done() //{{{
{
animMode(false);
refresh();
}
//}}}
// Insert draggable elements {{{
// Insert border divs for outline
if (options.dragEdges && $.isArray(options.createDragbars))
createDragbars(options.createDragbars);
if ($.isArray(options.createHandles))
createHandles(options.createHandles);
if (options.drawBorders && $.isArray(options.createBorders))
createBorders(options.createBorders);
//}}}
// This is a hack for iOS5 to support drag/move touch functionality
$(document).bind('touchstart.jcrop-ios',function(e) {
if ($(e.currentTarget).hasClass('jcrop-tracker')) e.stopPropagation();
});
var $track = newTracker().mousedown(createDragger('move')).css({
cursor: 'move',
position: 'absolute',
zIndex: 360
});
if (Touch.support) {
$track.bind('touchstart.jcrop', Touch.createDragger('move'));
}
$img_holder.append($track);
disableHandles();
return {
updateVisible: updateVisible,
update: update,
release: release,
refresh: refresh,
isAwake: function () {
return awake;
},
setCursor: function (cursor) {
$track.css('cursor', cursor);
},
enableHandles: enableHandles,
enableOnly: function () {
seehandles = true;
},
showHandles: showHandles,
disableHandles: disableHandles,
animMode: animMode,
setBgOpacity: setBgOpacity,
done: done
};
}());
//}}}
// Tracker Module {{{
var Tracker = (function () {
var onMove = function () {},
onDone = function () {},
trackDoc = options.trackDocument;
function toFront(touch) //{{{
{
$trk.css({
zIndex: 450
});
if (touch)
$(document)
.bind('touchmove.jcrop', trackTouchMove)
.bind('touchend.jcrop', trackTouchEnd);
else if (trackDoc)
$(document)
.bind('mousemove.jcrop',trackMove)
.bind('mouseup.jcrop',trackUp);
}
//}}}
function toBack() //{{{
{
$trk.css({
zIndex: 290
});
$(document).unbind('.jcrop');
}
//}}}
function trackMove(e) //{{{
{
onMove(mouseAbs(e));
return false;
}
//}}}
function trackUp(e) //{{{
{
e.preventDefault();
e.stopPropagation();
if (btndown) {
btndown = false;
onDone(mouseAbs(e));
if (Selection.isAwake()) {
options.onSelect.call(api, unscale(Coords.getFixed()));
}
toBack();
onMove = function () {};
onDone = function () {};
}
return false;
}
//}}}
function activateHandlers(move, done, touch) //{{{
{
btndown = true;
onMove = move;
onDone = done;
toFront(touch);
return false;
}
//}}}
function trackTouchMove(e) //{{{
{
onMove(mouseAbs(Touch.cfilter(e)));
return false;
}
//}}}
function trackTouchEnd(e) //{{{
{
return trackUp(Touch.cfilter(e));
}
//}}}
function setCursor(t) //{{{
{
$trk.css('cursor', t);
}
//}}}
if (!trackDoc) {
$trk.mousemove(trackMove).mouseup(trackUp).mouseout(trackUp);
}
$img.before($trk);
return {
activateHandlers: activateHandlers,
setCursor: setCursor
};
}());
//}}}
// KeyManager Module {{{
var KeyManager = (function () {
var $keymgr = $('<input type="radio" />').css({
position: 'fixed',
left: '-120px',
width: '12px'
}).addClass('jcrop-keymgr'),
$keywrap = $('<div />').css({
position: 'absolute',
overflow: 'hidden'
}).append($keymgr);
function watchKeys() //{{{
{
if (options.keySupport) {
$keymgr.show();
$keymgr.focus();
}
}
//}}}
function onBlur(e) //{{{
{
$keymgr.hide();
}
//}}}
function doNudge(e, x, y) //{{{
{
if (options.allowMove) {
Coords.moveOffset([x, y]);
Selection.updateVisible(true);
}
e.preventDefault();
e.stopPropagation();
}
//}}}
function parseKey(e) //{{{
{
if (e.ctrlKey || e.metaKey) {
return true;
}
shift_down = e.shiftKey ? true : false;
var nudge = shift_down ? 10 : 1;
switch (e.keyCode) {
case 37:
doNudge(e, -nudge, 0);
break;
case 39:
doNudge(e, nudge, 0);
break;
case 38:
doNudge(e, 0, -nudge);
break;
case 40:
doNudge(e, 0, nudge);
break;
case 27:
if (options.allowSelect) Selection.release();
break;
case 9:
return true;
}
return false;
}
//}}}
if (options.keySupport) {
$keymgr.keydown(parseKey).blur(onBlur);
if (ie6mode || !options.fixedSupport) {
$keymgr.css({
position: 'absolute',
left: '-20px'
});
$keywrap.append($keymgr).insertBefore($img);
} else {
$keymgr.insertBefore($img);
}
}
return {
watchKeys: watchKeys
};
}());
//}}}
// }}}
// API methods {{{
function setClass(cname) //{{{
{
$div.removeClass().addClass(cssClass('holder')).addClass(cname);
}
//}}}
function animateTo(a, callback) //{{{
{
var x1 = a[0] / xscale,
y1 = a[1] / yscale,
x2 = a[2] / xscale,
y2 = a[3] / yscale;
if (animating) {
return;
}
var animto = Coords.flipCoords(x1, y1, x2, y2),
c = Coords.getFixed(),
initcr = [c.x, c.y, c.x2, c.y2],
animat = initcr,
interv = options.animationDelay,
ix1 = animto[0] - initcr[0],
iy1 = animto[1] - initcr[1],
ix2 = animto[2] - initcr[2],
iy2 = animto[3] - initcr[3],
pcent = 0,
velocity = options.swingSpeed;
x1 = animat[0];
y1 = animat[1];
x2 = animat[2];
y2 = animat[3];
Selection.animMode(true);
var anim_timer;
function queueAnimator() {
window.setTimeout(animator, interv);
}
var animator = (function () {
return function () {
pcent += (100 - pcent) / velocity;
animat[0] = Math.round(x1 + ((pcent / 100) * ix1));
animat[1] = Math.round(y1 + ((pcent / 100) * iy1));
animat[2] = Math.round(x2 + ((pcent / 100) * ix2));
animat[3] = Math.round(y2 + ((pcent / 100) * iy2));
if (pcent >= 99.8) {
pcent = 100;
}
if (pcent < 100) {
setSelectRaw(animat);
queueAnimator();
} else {
Selection.done();
Selection.animMode(false);
if (typeof(callback) === 'function') {
callback.call(api);
}
}
};
}());
queueAnimator();
}
//}}}
function setSelect(rect) //{{{
{
setSelectRaw([rect[0] / xscale, rect[1] / yscale, rect[2] / xscale, rect[3] / yscale]);
options.onSelect.call(api, unscale(Coords.getFixed()));
Selection.enableHandles();
}
//}}}
function setSelectRaw(l) //{{{
{
Coords.setPressed([l[0], l[1]]);
Coords.setCurrent([l[2], l[3]]);
Selection.update();
}
//}}}
function tellSelect() //{{{
{
return unscale(Coords.getFixed());
}
//}}}
function tellScaled() //{{{
{
return Coords.getFixed();
}
//}}}
function setOptionsNew(opt) //{{{
{
setOptions(opt);
interfaceUpdate();
}
//}}}
function disableCrop() //{{{
{
options.disabled = true;
Selection.disableHandles();
Selection.setCursor('default');
Tracker.setCursor('default');
}
//}}}
function enableCrop() //{{{
{
options.disabled = false;
interfaceUpdate();
}
//}}}
function cancelCrop() //{{{
{
Selection.done();
Tracker.activateHandlers(null, null);
}
//}}}
function destroy() //{{{
{
$div.remove();
$origimg.show();
$origimg.css('visibility','visible');
$(obj).removeData('Jcrop');
}
//}}}
function setImage(src, callback) //{{{
{
Selection.release();
disableCrop();
var img = new Image();
img.onload = function () {
var iw = img.width;
var ih = img.height;
var bw = options.boxWidth;
var bh = options.boxHeight;
$img.width(iw).height(ih);
$img.attr('src', src);
$img2.attr('src', src);
presize($img, bw, bh);
boundx = $img.width();
boundy = $img.height();
$img2.width(boundx).height(boundy);
$trk.width(boundx + (bound * 2)).height(boundy + (bound * 2));
$div.width(boundx).height(boundy);
Shade.resize(boundx,boundy);
enableCrop();
if (typeof(callback) === 'function') {
callback.call(api);
}
};
img.src = src;
}
//}}}
function colorChangeMacro($obj,color,now) {
var mycolor = color || options.bgColor;
if (options.bgFade && supportsColorFade() && options.fadeTime && !now) {
$obj.animate({
backgroundColor: mycolor
}, {
queue: false,
duration: options.fadeTime
});
} else {
$obj.css('backgroundColor', mycolor);
}
}
function interfaceUpdate(alt) //{{{
// This method tweaks the interface based on options object.
// Called when options are changed and at end of initialization.
{
if (options.allowResize) {
if (alt) {
Selection.enableOnly();
} else {
Selection.enableHandles();
}
} else {
Selection.disableHandles();
}
Tracker.setCursor(options.allowSelect ? 'crosshair' : 'default');
Selection.setCursor(options.allowMove ? 'move' : 'default');
if (options.hasOwnProperty('trueSize')) {
xscale = options.trueSize[0] / boundx;
yscale = options.trueSize[1] / boundy;
}
if (options.hasOwnProperty('setSelect')) {
setSelect(options.setSelect);
Selection.done();
delete(options.setSelect);
}
Shade.refresh();
if (options.bgColor != bgcolor) {
colorChangeMacro(
options.shade? Shade.getShades(): $div,
options.shade?
(options.shadeColor || options.bgColor):
options.bgColor
);
bgcolor = options.bgColor;
}
if (bgopacity != options.bgOpacity) {
bgopacity = options.bgOpacity;
if (options.shade) Shade.refresh();
else Selection.setBgOpacity(bgopacity);
}
xlimit = options.maxSize[0] || 0;
ylimit = options.maxSize[1] || 0;
xmin = options.minSize[0] || 0;
ymin = options.minSize[1] || 0;
if (options.hasOwnProperty('outerImage')) {
$img.attr('src', options.outerImage);
delete(options.outerImage);
}
Selection.refresh();
}
//}}}
//}}}
if (Touch.support) $trk.bind('touchstart.jcrop', Touch.newSelection);
$hdl_holder.hide();
interfaceUpdate(true);
var api = {
setImage: setImage,
animateTo: animateTo,
setSelect: setSelect,
setOptions: setOptionsNew,
tellSelect: tellSelect,
tellScaled: tellScaled,
setClass: setClass,
disable: disableCrop,
enable: enableCrop,
cancel: cancelCrop,
release: Selection.release,
destroy: destroy,
focus: KeyManager.watchKeys,
getBounds: function () {
return [boundx * xscale, boundy * yscale];
},
getWidgetSize: function () {
return [boundx, boundy];
},
getScaleFactor: function () {
return [xscale, yscale];
},
getOptions: function() {
// careful: internal values are returned
return options;
},
ui: {
holder: $div,
selection: $sel
}
};
if (is_msie) $div.bind('selectstart', function () { return false; });
$origimg.data('Jcrop', api);
return api;
};
$.fn.Jcrop = function (options, callback) //{{{
{
var api;
// Iterate over each object, attach Jcrop
this.each(function () {
// If we've already attached to this object
if ($(this).data('Jcrop')) {
// The API can be requested this way (undocumented)
if (options === 'api') return $(this).data('Jcrop');
// Otherwise, we just reset the options...
else $(this).data('Jcrop').setOptions(options);
}
// If we haven't been attached, preload and attach
else {
if (this.tagName == 'IMG')
$.Jcrop.Loader(this,function(){
$(this).css({display:'block',visibility:'hidden'});
api = $.Jcrop(this, options);
if ($.isFunction(callback)) callback.call(api);
});
else {
$(this).css({display:'block',visibility:'hidden'});
api = $.Jcrop(this, options);
if ($.isFunction(callback)) callback.call(api);
}
}
});
// Return "this" so the object is chainable (jQuery-style)
return this;
};
//}}}
// $.Jcrop.Loader - basic image loader {{{
$.Jcrop.Loader = function(imgobj,success,error){
var $img = $(imgobj), img = $img[0];
function completeCheck(){
if (img.complete) {
$img.unbind('.jcloader');
if ($.isFunction(success)) success.call(img);
}
else window.setTimeout(completeCheck,50);
}
$img
.bind('load.jcloader',completeCheck)
.bind('error.jcloader',function(e){
$img.unbind('.jcloader');
if ($.isFunction(error)) error.call(img);
});
if (img.complete && $.isFunction(success)){
$img.unbind('.jcloader');
success.call(img);
}
};
//}}}
// Global Defaults {{{
$.Jcrop.defaults = {
// Basic Settings
allowSelect: true,
allowMove: true,
allowResize: true,
trackDocument: true,
// Styling Options
baseClass: 'jcrop',
addClass: null,
bgColor: 'black',
bgOpacity: 0.6,
bgFade: false,
borderOpacity: 0.4,
handleOpacity: 0.5,
handleSize: null,
aspectRatio: 0,
keySupport: true,
createHandles: ['n','s','e','w','nw','ne','se','sw'],
createDragbars: ['n','s','e','w'],
createBorders: ['n','s','e','w'],
drawBorders: true,
dragEdges: true,
fixedSupport: true,
touchSupport: null,
shade: null,
boxWidth: 0,
boxHeight: 0,
boundary: 2,
fadeTime: 400,
animationDelay: 20,
swingSpeed: 3,
minSelect: [0, 0],
maxSize: [0, 0],
minSize: [0, 0],
// Callbacks / Event Handlers
onChange: function () {},
onSelect: function () {},
onDblClick: function () {},
onRelease: function () {}
};
// }}}
}(jQuery));
| JavaScript |
/*!
* jQuery UI Widget 1.8.5
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Widget
*/
(function( $, undefined ) {
// jQuery 1.4+
if ( $.cleanData ) {
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
$( elem ).triggerHandler( "remove" );
}
_cleanData( elems );
};
} else {
var _remove = $.fn.remove;
$.fn.remove = function( selector, keepData ) {
return this.each(function() {
if ( !keepData ) {
if ( !selector || $.filter( selector, [ this ] ).length ) {
$( "*", this ).add( [ this ] ).each(function() {
$( this ).triggerHandler( "remove" );
});
}
}
return _remove.call( $(this), selector, keepData );
});
};
}
$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};
$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
// $.each( basePrototype, function( key, val ) {
// if ( $.isPlainObject(val) ) {
// basePrototype[ key ] = $.extend( {}, val );
// }
// });
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );
$.widget.bridge( name, $[ namespace ][ name ] );
};
$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = Array.prototype.slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.extend.apply( null, [ true, options ].concat(args) ) :
options;
// prevent calls to internal methods
if ( isMethodCall && options.substring( 0, 1 ) === "_" ) {
return returnValue;
}
if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name );
if ( !instance ) {
throw "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'";
}
if ( !$.isFunction( instance[options] ) ) {
throw "no such method '" + options + "' for " + name + " widget instance";
}
var methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, name, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
options: {
disabled: false
},
_createWidget: function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
$.metadata && $.metadata.get( element )[ this.widgetName ],
options );
var self = this;
this.element.bind( "remove." + this.widgetName, function() {
self.destroy();
});
this._create();
this._init();
},
_create: function() {},
_init: function() {},
destroy: function() {
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
},
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
self = this;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.extend( {}, self.options );
}
if (typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
options = {};
options[ key ] = value;
}
$.each( options, function( key, value ) {
self._setOption( key, value );
});
return self;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
[ value ? "addClass" : "removeClass"](
this.widgetBaseClass + "-disabled" + " " +
"ui-state-disabled" )
.attr( "aria-disabled", value );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_trigger: function( type, event, data ) {
var callback = this.options[ type ];
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
data = data || {};
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( event.originalEvent ) {
for ( var i = $.event.props.length, prop; i; ) {
prop = $.event.props[ --i ];
event[ prop ] = event.originalEvent[ prop ];
}
}
this.element.trigger( event, data );
return !( $.isFunction(callback) &&
callback.call( this.element[0], event, data ) === false ||
event.isDefaultPrevented() );
}
};
})( jQuery );
| JavaScript |
function setCheckboxes(the_form, id, do_check)
{
var elts = (typeof(document.forms[the_form].elements[id]) != 'undefined')
? document.forms[the_form].elements[id]
: 0;
var elts_cnt = (typeof(elts.length) != 'undefined')
? elts.length
: 0;
if (elts_cnt) {
for (var i = 0; i < elts_cnt; i++) {
elts[i].checked = do_check;
}
} else {
elts.checked = do_check;
}
return true;
}
function setCheckboxesRight(the_form, total_num, do_check)
{
var form = document.forms[the_form];
for(var i=0;i<total_num;i++){
form.elements['fc_'+i].checked=do_check;
for(x in arr_pm_code){
form.elements['arr_permission['+i+']['+arr_pm_code[x]+']'].checked=do_check;
}
/*form.elements['arr_right['+i+'][right_add]'].checked=do_check;
form.elements['arr_right['+i+'][right_modify]'].checked=do_check;
form.elements['arr_right['+i+'][right_delete]'].checked=do_check;
form.elements['arr_right['+i+'][right_remove]'].checked=do_check;
form.elements['arr_right['+i+'][right_restore]'].checked=do_check;
form.elements['arr_right['+i+'][right_search]'].checked=do_check;
form.elements['arr_right['+i+'][right_exp_pdf]'].checked=do_check;
form.elements['arr_right['+i+'][right_exp_exl]'].checked=do_check;*/
}
return true;
}
function setCheckboxesFunction(the_form,row,do_check)
{
var form = document.forms[the_form];
for(x in arr_pm_code){
form.elements['arr_permission['+row+']['+arr_pm_code[x]+']'].checked=do_check;
}
/*form.elements['arr_right['+row+'][right_read]'].checked=do_check;
form.elements['arr_right['+row+'][right_add]'].checked=do_check;
form.elements['arr_right['+row+'][right_modify]'].checked=do_check;
form.elements['arr_right['+row+'][right_delete]'].checked=do_check;
form.elements['arr_right['+row+'][right_remove]'].checked=do_check;
form.elements['arr_right['+row+'][right_restore]'].checked=do_check;
form.elements['arr_right['+row+'][right_search]'].checked=do_check;
form.elements['arr_right['+row+'][right_exp_pdf]'].checked=do_check;
form.elements['arr_right['+row+'][right_exp_exl]'].checked=do_check;*/
return true;
}
function check_chose(id, arid, the_form)
{
var n = $('#'+id+':checked').val();
if(n)
setCheckboxes(the_form, arid, true);
else
setCheckboxes(the_form, arid, false);
}
function get_check_chose(id,the_form){
var arr_value = new Array();
var elts = (typeof(document.forms[the_form].elements[id]) != 'undefined')
? document.forms[the_form].elements[id]
: 0;
var elts_cnt = (typeof(elts.length) != 'undefined')
? elts.length
: 0;
if (elts_cnt) {
for (var i = 0; i < elts_cnt; i++) {
if(elts[i].checked == true){
arr_value.push(elts[i].value);
}
}
}
return arr_value;
}
function check_chose_right(id,total_num,the_form){
var n = $('#'+id+':checked').val();
if(n)
{
setCheckboxesRight(the_form,total_num, true);
}
else{
setCheckboxesRight(the_form,total_num, false);
}
}
function check_chose_function(id,row,the_form){
var n = $('#'+id+':checked').val();
if(n)
{
setCheckboxesFunction(the_form,row, true);
}
else{
setCheckboxesFunction(the_form,row, false);
}
}
function verify_del()
{
return window.confirm("Bạn có muốn xóa các mục này không?\nVui lòng xác nhận.");
}
function verify_delpage()
{
return window.confirm("Bạn muốn xóa trang này?\nVui lòng xác nhận.");
}
function setCheckboxValue(id)
{
if(id.checked)
{
id.value = 1;
}else{
id.value = 0;
}
}
function set_action(form_name,action){
document.forms[form_name].action=action;
}
function verify_copy(str)
{
return window.confirm(str);
} | JavaScript |
/*
* jQuery Iframe Transport Plugin 1.7
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint unparam: true, nomen: true */
/*global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts three additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
$.ajaxTransport('iframe', function (options) {
if (options.async) {
var form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6.
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
'<iframe src="javascript:false;" name="iframe-transport-' +
counter + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="javascript:false;"></iframe>')
.appendTo(form);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
$(input).prop('name', clone.prop('name'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', 'javascript'.concat(':false;'));
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
$.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html());
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));
| JavaScript |
/*
* jQuery Iframe Transport Plugin 1.8.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Helper variable to create unique names for the transport iframes:
var counter = 0;
// The iframe transport accepts four additional options:
// options.fileInput: a jQuery collection of file input fields
// options.paramName: the parameter name for the file form data,
// overrides the name property of the file input field(s),
// can be a string or an array of strings.
// options.formData: an array of objects with name and value properties,
// equivalent to the return data of .serializeArray(), e.g.:
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
// options.initialIframeSrc: the URL of the initial iframe src,
// by default set to "javascript:false;"
$.ajaxTransport('iframe', function (options) {
if (options.async) {
// javascript:false as initial iframe src
// prevents warning popups on HTTPS in IE6:
/*jshint scripturl: true */
var initialIframeSrc = options.initialIframeSrc || 'javascript:false;',
/*jshint scripturl: false */
form,
iframe,
addParamChar;
return {
send: function (_, completeCallback) {
form = $('<form style="display:none;"></form>');
form.attr('accept-charset', options.formAcceptCharset);
addParamChar = /\?/.test(options.url) ? '&' : '?';
// XDomainRequest only supports GET and POST:
if (options.type === 'DELETE') {
options.url = options.url + addParamChar + '_method=DELETE';
options.type = 'POST';
} else if (options.type === 'PUT') {
options.url = options.url + addParamChar + '_method=PUT';
options.type = 'POST';
} else if (options.type === 'PATCH') {
options.url = options.url + addParamChar + '_method=PATCH';
options.type = 'POST';
}
// IE versions below IE8 cannot set the name property of
// elements that have already been added to the DOM,
// so we set the name along with the iframe HTML markup:
counter += 1;
iframe = $(
'<iframe src="' + initialIframeSrc +
'" name="iframe-transport-' + counter + '"></iframe>'
).bind('load', function () {
var fileInputClones,
paramNames = $.isArray(options.paramName) ?
options.paramName : [options.paramName];
iframe
.unbind('load')
.bind('load', function () {
var response;
// Wrap in a try/catch block to catch exceptions thrown
// when trying to access cross-domain iframe contents:
try {
response = iframe.contents();
// Google Chrome and Firefox do not throw an
// exception when calling iframe.contents() on
// cross-domain requests, so we unify the response:
if (!response.length || !response[0].firstChild) {
throw new Error();
}
} catch (e) {
response = undefined;
}
// The complete callback returns the
// iframe content document as response object:
completeCallback(
200,
'success',
{'iframe': response}
);
// Fix for IE endless progress bar activity bug
// (happens on form submits to iframe targets):
$('<iframe src="' + initialIframeSrc + '"></iframe>')
.appendTo(form);
window.setTimeout(function () {
// Removing the form in a setTimeout call
// allows Chrome's developer tools to display
// the response result
form.remove();
}, 0);
});
form
.prop('target', iframe.prop('name'))
.prop('action', options.url)
.prop('method', options.type);
if (options.formData) {
$.each(options.formData, function (index, field) {
$('<input type="hidden"/>')
.prop('name', field.name)
.val(field.value)
.appendTo(form);
});
}
if (options.fileInput && options.fileInput.length &&
options.type === 'POST') {
fileInputClones = options.fileInput.clone();
// Insert a clone for each file input field:
options.fileInput.after(function (index) {
return fileInputClones[index];
});
if (options.paramName) {
options.fileInput.each(function (index) {
$(this).prop(
'name',
paramNames[index] || options.paramName
);
});
}
// Appending the file input fields to the hidden form
// removes them from their original location:
form
.append(options.fileInput)
.prop('enctype', 'multipart/form-data')
// enctype must be set as encoding for IE:
.prop('encoding', 'multipart/form-data');
// Remove the HTML5 form attribute from the input(s):
options.fileInput.removeAttr('form');
}
form.submit();
// Insert the file input fields at their original location
// by replacing the clones with the originals:
if (fileInputClones && fileInputClones.length) {
options.fileInput.each(function (index, input) {
var clone = $(fileInputClones[index]);
// Restore the original name and form properties:
$(input)
.prop('name', clone.prop('name'))
.attr('form', clone.attr('form'));
clone.replaceWith(input);
});
}
});
form.append(iframe).appendTo(document.body);
},
abort: function () {
if (iframe) {
// javascript:false as iframe src aborts the request
// and prevents warning popups on HTTPS in IE6.
// concat is used to avoid the "Script URL" JSLint error:
iframe
.unbind('load')
.prop('src', initialIframeSrc);
}
if (form) {
form.remove();
}
}
};
}
});
// The iframe transport returns the iframe content document as response.
// The following adds converters from iframe to text, json, html, xml
// and script.
// Please note that the Content-Type for JSON responses has to be text/plain
// or text/html, if the browser doesn't include application/json in the
// Accept header, else IE will show a download dialog.
// The Content-Type for XML responses on the other hand has to be always
// application/xml or text/xml, so IE properly parses the XML response.
// See also
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation
$.ajaxSetup({
converters: {
'iframe text': function (iframe) {
return iframe && $(iframe[0].body).text();
},
'iframe json': function (iframe) {
return iframe && $.parseJSON($(iframe[0].body).text());
},
'iframe html': function (iframe) {
return iframe && $(iframe[0].body).html();
},
'iframe xml': function (iframe) {
var xmlDoc = iframe && iframe[0];
return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc :
$.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) ||
$(xmlDoc.body).html());
},
'iframe script': function (iframe) {
return iframe && $.globalEval($(iframe[0].body).text());
}
}
});
}));
| JavaScript |
/*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
| JavaScript |
/*
* jQuery File Upload Plugin Angular JS Example 1.2.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global window, angular */
(function () {
'use strict';
var isOnGitHub = window.location.hostname === 'blueimp.github.io',
url = isOnGitHub ? '//jquery-file-upload.appspot.com/' : 'server/php/';
angular.module('demo', [
'blueimp.fileupload'
])
.config([
'$httpProvider', 'fileUploadProvider',
function ($httpProvider, fileUploadProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
fileUploadProvider.defaults.redirect = window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
);
if (isOnGitHub) {
// Demo settings:
angular.extend(fileUploadProvider.defaults, {
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
}
}
])
.controller('DemoFileUploadController', [
'$scope', '$http', '$filter', '$window',
function ($scope, $http) {
$scope.options = {
url: url
};
if (!isOnGitHub) {
$scope.loadingFiles = true;
$http.get(url)
.then(
function (response) {
$scope.loadingFiles = false;
$scope.queue = response.data.files || [];
},
function () {
$scope.loadingFiles = false;
}
);
}
}
])
.controller('FileDestroyController', [
'$scope', '$http',
function ($scope, $http) {
var file = $scope.file,
state;
if (file.url) {
file.$state = function () {
return state;
};
file.$destroy = function () {
state = 'pending';
return $http({
url: file.deleteUrl,
method: file.deleteType
}).then(
function () {
state = 'resolved';
$scope.clear(file);
},
function () {
state = 'rejected';
}
);
};
} else if (!file.$cancel && !file._index) {
file.$cancel = function () {
$scope.clear(file);
};
}
}
]);
}());
| JavaScript |
/*
* jQuery File Upload jQuery UI Plugin 8.7.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery', './jquery.fileupload-ui'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
processdone: function (e, data) {
data.context.find('.start').button('enable');
},
progress: function (e, data) {
if (data.context) {
data.context.find('.progress').progressbar(
'option',
'value',
parseInt(data.loaded / data.total * 100, 10)
);
}
},
progressall: function (e, data) {
var $this = $(this);
$this.find('.fileupload-progress')
.find('.progress').progressbar(
'option',
'value',
parseInt(data.loaded / data.total * 100, 10)
).end()
.find('.progress-extended').each(function () {
$(this).html(
($this.data('blueimp-fileupload') ||
$this.data('fileupload'))
._renderExtendedProgress(data)
);
});
}
},
_renderUpload: function (func, files) {
var node = this._super(func, files),
showIconText = $(window).width() > 480;
node.find('.progress').empty().progressbar();
node.find('.start').button({
icons: {primary: 'ui-icon-circle-arrow-e'},
text: showIconText
});
node.find('.cancel').button({
icons: {primary: 'ui-icon-cancel'},
text: showIconText
});
if (node.hasClass('fade')) {
node.hide();
}
return node;
},
_renderDownload: function (func, files) {
var node = this._super(func, files),
showIconText = $(window).width() > 480;
node.find('.delete').button({
icons: {primary: 'ui-icon-trash'},
text: showIconText
});
if (node.hasClass('fade')) {
node.hide();
}
return node;
},
_startHandler: function (e) {
$(e.currentTarget).button('disable');
this._super(e);
},
_transition: function (node) {
var deferred = $.Deferred();
if (node.hasClass('fade')) {
node.fadeToggle(
this.options.transitionDuration,
this.options.transitionEasing,
function () {
deferred.resolveWith(node);
}
);
} else {
deferred.resolveWith(node);
}
return deferred;
},
_create: function () {
this._super();
this.element
.find('.fileupload-buttonbar')
.find('.fileinput-button').each(function () {
var input = $(this).find('input:file').detach();
$(this)
.button({icons: {primary: 'ui-icon-plusthick'}})
.append(input);
})
.end().find('.start')
.button({icons: {primary: 'ui-icon-circle-arrow-e'}})
.end().find('.cancel')
.button({icons: {primary: 'ui-icon-cancel'}})
.end().find('.delete')
.button({icons: {primary: 'ui-icon-trash'}})
.end().find('.progress').progressbar();
},
_destroy: function () {
this.element
.find('.fileupload-buttonbar')
.find('.fileinput-button').each(function () {
var input = $(this).find('input:file').detach();
$(this)
.button('destroy')
.append(input);
})
.end().find('.start')
.button('destroy')
.end().find('.cancel')
.button('destroy')
.end().find('.delete')
.button('destroy')
.end().find('.progress').progressbar('destroy');
this._super();
}
});
}));
| JavaScript |
/*
* jQuery postMessage Transport Plugin 1.1.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global define, window, document */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
var counter = 0,
names = [
'accepts',
'cache',
'contents',
'contentType',
'crossDomain',
'data',
'dataType',
'headers',
'ifModified',
'mimeType',
'password',
'processData',
'timeout',
'traditional',
'type',
'url',
'username'
],
convert = function (p) {
return p;
};
$.ajaxSetup({
converters: {
'postmessage text': convert,
'postmessage json': convert,
'postmessage html': convert
}
});
$.ajaxTransport('postmessage', function (options) {
if (options.postMessage && window.postMessage) {
var iframe,
loc = $('<a>').prop('href', options.postMessage)[0],
target = loc.protocol + '//' + loc.host,
xhrUpload = options.xhr().upload;
return {
send: function (_, completeCallback) {
counter += 1;
var message = {
id: 'postmessage-transport-' + counter
},
eventName = 'message.' + message.id;
iframe = $(
'<iframe style="display:none;" src="' +
options.postMessage + '" name="' +
message.id + '"></iframe>'
).bind('load', function () {
$.each(names, function (i, name) {
message[name] = options[name];
});
message.dataType = message.dataType.replace('postmessage ', '');
$(window).bind(eventName, function (e) {
e = e.originalEvent;
var data = e.data,
ev;
if (e.origin === target && data.id === message.id) {
if (data.type === 'progress') {
ev = document.createEvent('Event');
ev.initEvent(data.type, false, true);
$.extend(ev, data);
xhrUpload.dispatchEvent(ev);
} else {
completeCallback(
data.status,
data.statusText,
{postmessage: data.result},
data.headers
);
iframe.remove();
$(window).unbind(eventName);
}
}
});
iframe[0].contentWindow.postMessage(
message,
target
);
}).appendTo(document.body);
},
abort: function () {
if (iframe) {
iframe.remove();
}
}
};
}
});
}));
| JavaScript |
/*
* jQuery XDomainRequest Transport Plugin 1.1.3
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*
* Based on Julian Aubourg's ajaxHooks xdr.js:
* https://github.com/jaubourg/ajaxHooks/
*/
/* global define, window, XDomainRequest */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define(['jquery'], factory);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
if (window.XDomainRequest && !$.support.cors) {
$.ajaxTransport(function (s) {
if (s.crossDomain && s.async) {
if (s.timeout) {
s.xdrTimeout = s.timeout;
delete s.timeout;
}
var xdr;
return {
send: function (headers, completeCallback) {
var addParamChar = /\?/.test(s.url) ? '&' : '?';
function callback(status, statusText, responses, responseHeaders) {
xdr.onload = xdr.onerror = xdr.ontimeout = $.noop;
xdr = null;
completeCallback(status, statusText, responses, responseHeaders);
}
xdr = new XDomainRequest();
// XDomainRequest only supports GET and POST:
if (s.type === 'DELETE') {
s.url = s.url + addParamChar + '_method=DELETE';
s.type = 'POST';
} else if (s.type === 'PUT') {
s.url = s.url + addParamChar + '_method=PUT';
s.type = 'POST';
} else if (s.type === 'PATCH') {
s.url = s.url + addParamChar + '_method=PATCH';
s.type = 'POST';
}
xdr.open(s.type, s.url);
xdr.onload = function () {
callback(
200,
'OK',
{text: xdr.responseText},
'Content-Type: ' + xdr.contentType
);
};
xdr.onerror = function () {
callback(404, 'Not Found');
};
if (s.xdrTimeout) {
xdr.ontimeout = function () {
callback(0, 'timeout');
};
xdr.timeout = s.xdrTimeout;
}
xdr.send((s.hasContent && s.data) || null);
},
abort: function () {
if (xdr) {
xdr.onerror = $.noop();
xdr.abort();
}
}
};
}
});
}
}));
| JavaScript |
var the_form = window.document.frmUser;
function check_All(status)
{
for (i = 0; i < the_form.length; i++) {
the_form.elements[i].checked = status;
}
}
function delConfrim()
{
return confirm("Ban co muon xoa ko")
}
function submit_list(flag)
{
if (selected_item()){
the_form.factive.value = flag;
the_form.submit();
}
}
function delete_list(the_url) {
if (selected_item()){
question = confirm("Ban co muon xoa khong ?")
if (question != "0"){
the_form.action = the_url;
the_form.submit();
}
}
}
function selected_item(){
var name_count = the_form.length;
for (i=0;i<name_count;i++){
if (the_form.elements[i].checked){
return true;
}
}
alert('Hay chon 1 user');
return false;
}
| JavaScript |
var imgLib = {
configdefault:{
url:url,
url_lib:url+'mod_file_manager/image_manager',
dir_img:'',
width: 0,
height:0,
method:'imglib',
action:'',
callback:'',
return_tag:''
},
config:{},
openLib :function (option)
{
this.config = $.extend({},this.configdefault,option);
this.config.url_lib = this.config.url_lib+'/index/'+this.config.return_tag+'/'+this.config.width+'/'+this.config.height ;
if(this.config.method=='imgcrop')
{
this.config.url_lib = url+'mod_file_manager/image_manager/cropimage';
}
$.colorbox({href:this.config.url_lib,iframe:true, innerWidth:"980px", innerHeight:"600px"});
},
insert:function(data)
{
if(this.config.callback!= '' )
{
this.config.callback(data);
}
else
{
if(this.config.action=='imgcrop')
{
var rt_data = data[0];
var file = rt_data.lb_dir+'/'+rt_data.lb_name;
var rt_html = "";
rt_html += '<input type="hidden" name="'+this.config.return_tag+'" value="images/'+file+'" id="'+this.config.return_tag+'"/>';
//rt_html += '<a href="'+url+'mod_file_manager/image_manager/cropimage/'+this.config.return_tag+'/'+this.config.width+'/'+this.config.height+'" class="cboxElement" title="Image Crop"><img src="'+urlsite+'uploads/images/'+file+'" width="100px"/></a>';
rt_html += '<a href="javascript:imgLib.openLib({dir_img:\'images/'+file+'\',width:\''+this.config.width+'\',height:\''+this.config.height+'\',method:\'imgcrop\',return_tag:\''+this.config.return_tag+'\',action:\'imgcrop\'});"> <img src="'+urlsite+'uploads/images/'+file+'" width="100px"/></a>';
$("."+this.config.return_tag).html(rt_html);
$(".cboxElement").colorbox({width:"985px", height:"600px",iframe:true});
}
else if(this.config.action=='editor')
{
}
}
},
crop:function(data)
{
if(this.config.callback!= '' ){
this.config.callback(data);
}else{
if(this.config.action=='imgcrop'){
var rt_html = "";
rt_html += '<input type="hidden" name="'+this.config.return_tag+'" value="temp/'+data.file_name+'" id="'+this.config.return_tag+'"/>';
rt_html += '<a onclick="imgLib.openLib({dir_img:\'temp/'+data.file_name+'\',width:\''+this.config.width+'\',height:\''+this.config.height+'\',method:\'imgcrop\',return_tag:\''+this.config.return_tag+'\',action:\'imgcrop\'});" href="javascript:void(0);"> <img src="'+urlsite+'uploads/temp/'+data.file_name+'" width="100px"/></a>';
$("."+this.config.return_tag).html(rt_html);
$(".cboxElement").colorbox({width:"950", height:"650",iframe:true});
}
}
}
}; | JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "Vui lòng nhập đầy đủ thông tin",
"alertTextCheckboxMultiple": "Vui lòng chọn",
"alertTextCheckboxe": "* This checkbox is required"
},
"select-product-cat": {
"regex": /^[\-\+]?\d+$/,
"alertText": "Chọn danh mục sản phẩm"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters allowed"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Checks allowed Exceeded"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"email": {
// Simplified, was not working in the Iphone browser
"regex": /^([A-Za-z0-9_\-\.\'])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "Thông tin nhập vào phải là số"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/,
"alertText": "Thông tin nhập vào phải là số"
},
"date": {
// Date in ISO format. Credit: bassistance
"regex": /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/,
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery); | JavaScript |
jQuery(function($) {
$(".cboxElement").colorbox({
width:"730", height:"600", iframe:true
});
$("#addimages_avatar").colorbox({
width:"730", height:"600", iframe:true
});
$(".btnloadgroup").colorbox({
width:"730", height:"600", iframe:true
});
$(".btnloadshow").colorbox({
width:"730", height:"500", iframe:true
});
$(".colorbox").colorbox({iframe:true, fixed:true, width:"900", height:"600"});
});
| JavaScript |
function mkselected(id, value)
{
var loca = document.getElementById(id).options ;
for(var i=0;i<loca.length;i++){
if(loca[i].value == value)
loca[i].selected = true ;
}
}
function changestatus(value,id)
{
$("#loadstatus"+id).html('<image src="'+url+'templates/images/loading1.gif">');
$.post(url+"order/changestatus",{'status':value,'id':id},function(data)
{
$("#loadstatus"+id).html('');
},'json');
}
function loadstatic()
{
$("#static").html('<image src="'+url+'templates/images/loading.gif">');
$.post(url+"ajax/thongke",{},function(data)
{
$("#static").html(data);
});
}
//Site config
function loadConfig()
{
$("#config").html('<image src="'+url+'templates/images/loading.gif">');
$.post(url+"siteconfig/config",{},function(data)
{
$("#config").html(data);
});
}
//Member
function updatemember(id){
$("#page").html('<image src="'+url+'templates/images/loading.gif">');
$.post(url+"member/update/",{'id':id},function(data)
{
$("#page").html(data);
});
}
//Publish
function publish(table,field,id,status)
{
$("#publish"+id).html('<image src="'+url+'templates/images/loading.gif">');
$.post(url+"ajax/publish",{'table':table,'field':field,'id':id,'status':status},function(data)
{
$("#publish"+id).html(data);
});
}
$(function(){
$("#title").keyup(function()
{
var word=$(this).val();
$.post(url+"ajax/getalias/",{'name':word},function(data)
{
$("#alias").val(data);
});
return false;
});
});
function kodau(str){
str= str.toLowerCase();
str= str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");
str= str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");
str= str.replace(/ì|í|ị|ỉ|ĩ/g,"i");
str= str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");
str= str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");
str= str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");
str= str.replace(/đ/g,"d");
str= str.replace(/!|@|\$|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\'| |\"|\&|\#|\[|\]|~/g,"-");
str= str.replace(/-+-/g,"-"); //thay thế 2- thành 1-
str= str.replace(/^\-+|\-+$/g,"");//cắt bỏ ký tự - ở đầu và cuối chuỗi
return str;
}
function trit(a){
console.log(a) ;
}
| JavaScript |
// This file is part of the jQuery formatCurrency Plugin.
//
// The jQuery formatCurrency Plugin is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The jQuery formatCurrency Plugin is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the jQuery formatCurrency Plugin. If not, see <http://www.gnu.org/licenses/>.
(function($) {
$.formatCurrency = {};
$.formatCurrency.regions = [];
// default Region is en
$.formatCurrency.regions[''] = {
symbol: '',
positiveFormat: '%s%n',
negativeFormat: '(%s%n)',
decimalSymbol: '.',
digitGroupSymbol: ',',
groupDigits: true
};
$.fn.formatCurrency = function(destination, settings) {
if (arguments.length == 1 && typeof destination !== "string") {
settings = destination;
destination = false;
}
// initialize defaults
var defaults = {
name: "formatCurrency",
colorize: false,
region: '',
global: true,
roundToDecimalPlace: 2, // roundToDecimalPlace: -1; for no rounding; 0 to round to the dollar; 1 for one digit cents; 2 for two digit cents; 3 for three digit cents; ...
eventOnDecimalsEntered: false
};
// initialize default region
defaults = $.extend(defaults, $.formatCurrency.regions['']);
// override defaults with settings passed in
settings = $.extend(defaults, settings);
// check for region setting
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function() {
$this = $(this);
// get number
var num = '0';
num = $this[$this.is('input, select, textarea') ? 'val' : 'html']();
//identify '(123)' as a negative number
if (num.search('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
num = num.replace(settings.regex, '');
if (num === '' || (num === '-' && settings.roundToDecimalPlace === -1)) {
return;
}
if (settings.decimalSymbol != '.') {
num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arithmetic
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (settings.roundToDecimalPlace >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(settings.roundToDecimalPlace); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
if (settings.groupDigits) {
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
}
}
if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
num += settings.decimalSymbol + decimals;
}
// format symbol/negative
var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
var money = format.replace(/%s/g, settings.symbol);
money = money.replace(/%n/g, num);
// setup destination
var $destination = $([]);
if (!destination) {
$destination = $this;
} else {
$destination = $(destination);
}
// set destination
$destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money);
if (
hasDecimals &&
settings.eventOnDecimalsEntered &&
originalDecimals.length > settings.roundToDecimalPlace
) {
$destination.trigger('decimalsEntered', originalDecimals);
}
// colorize
if (settings.colorize) {
$destination.css('color', isPositive ? 'black' : 'red');
}
});
};
// Remove all non numbers from text
$.fn.toNumber = function(settings) {
var defaults = $.extend({
name: "toNumber",
region: '',
global: true
}, $.formatCurrency.regions['']);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
return this.each(function() {
var method = $(this).is('input, select, textarea') ? 'val' : 'html';
$(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, ''));
});
};
// returns the value from the first element as a number
$.fn.asNumber = function(settings) {
var defaults = $.extend({
name: "asNumber",
region: '',
parse: true,
parseType: 'Float',
global: true
}, $.formatCurrency.regions['']);
settings = jQuery.extend(defaults, settings);
if (settings.region.length > 0) {
settings = $.extend(settings, getRegionOrCulture(settings.region));
}
settings.regex = generateRegex(settings);
settings.parseType = validateParseType(settings.parseType);
var method = $(this).is('input, select, textarea') ? 'val' : 'html';
var num = $(this)[method]();
num = num ? num : "";
num = num.replace('(', '(-');
num = num.replace(settings.regex, '');
if (!settings.parse) {
return num;
}
if (num.length == 0) {
num = '0';
}
if (settings.decimalSymbol != '.') {
num = num.replace(settings.decimalSymbol, '.'); // reset to US decimal for arthmetic
}
return window['parse' + settings.parseType](num);
};
function getRegionOrCulture(region) {
var regionInfo = $.formatCurrency.regions[region];
if (regionInfo) {
return regionInfo;
}
else {
if (/(\w+)-(\w+)/g.test(region)) {
var culture = region.replace(/(\w+)-(\w+)/g, "$1");
return $.formatCurrency.regions[culture];
}
}
// fallback to extend(null) (i.e. nothing)
return null;
}
function validateParseType(parseType) {
switch (parseType.toLowerCase()) {
case 'int':
return 'Int';
case 'float':
return 'Float';
default:
throw 'invalid parseType';
}
}
function generateRegex(settings) {
if (settings.symbol === '') {
return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
}
else {
var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.');
return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
}
}
})(jQuery); | JavaScript |
/*
jQuery Tags Input Plugin 1.3.3
Copyright (c) 2011 XOXCO, Inc
Documentation for this plugin lives here:
http://xoxco.com/clickable/jquery-tags-input
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
ben@xoxco.com
*/
;(function($) {
var delimiter = new Array();
var tags_callbacks = new Array();
$.fn.doAutosize = function(o){
var minWidth = $(this).data('minwidth'),
maxWidth = $(this).data('maxwidth'),
val = '',
input = $(this),
testSubject = $('#'+$(this).data('tester_id'));
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
$.fn.resetAutosize = function(options){
// alert(JSON.stringify(options));
var minWidth = $(this).data('minwidth') || options.minInputWidth || $(this).width(),
maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
testerId = $(this).attr('id')+'_autosize_tester';
if(! $('#'+testerId).length > 0){
testSubject.attr('id', testerId);
testSubject.appendTo('body');
}
input.data('minwidth', minWidth);
input.data('maxwidth', maxWidth);
input.data('tester_id', testerId);
input.css('width', minWidth);
};
$.fn.addTag = function(value,options) {
options = jQuery.extend({focus:false,callback:true},options);
this.each(function() {
var id = $(this).attr('id');
var tagslist = $(this).val().split(delimiter[id]);
if (tagslist[0] == '') {
tagslist = new Array();
}
value = jQuery.trim(value);
if (options.unique) {
var skipTag = $(this).tagExist(value);
if(skipTag == true) {
//Marks fake input as not_valid to let styling it
$('#'+id+'_tag').addClass('not_valid');
}
} else {
var skipTag = false;
}
if (value !='' && skipTag != true) {
$('<span>').addClass('tag').append(
$('<span>').text(value).append(' '),
$('<a>', {
href : '#',
title : 'Removing tag',
text : 'x'
}).click(function () {
return $('#' + id).removeTag(escape(value));
})
).insertBefore('#' + id + '_addTag');
tagslist.push(value);
$('#'+id+'_tag').val('');
if (options.focus) {
$('#'+id+'_tag').focus();
} else {
$('#'+id+'_tag').blur();
}
$.fn.tagsInput.updateTagsField(this,tagslist);
if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) {
var f = tags_callbacks[id]['onAddTag'];
f.call(this, value);
}
if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
{
var i = tagslist.length;
var f = tags_callbacks[id]['onChange'];
f.call(this, $(this), tagslist[i-1]);
}
}
});
return false;
};
$.fn.removeTag = function(value) {
value = unescape(value);
this.each(function() {
var id = $(this).attr('id');
var old = $(this).val().split(delimiter[id]);
$('#'+id+'_tagsinput .tag').remove();
str = '';
for (i=0; i< old.length; i++) {
if (old[i]!=value) {
str = str + delimiter[id] +old[i];
}
}
$.fn.tagsInput.importTags(this,str);
if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) {
var f = tags_callbacks[id]['onRemoveTag'];
f.call(this, value);
}
});
return false;
};
$.fn.tagExist = function(val) {
var id = $(this).attr('id');
var tagslist = $(this).val().split(delimiter[id]);
return (jQuery.inArray(val, tagslist) >= 0); //true when tag exists, false when not
};
// clear all existing tags and import new ones from a string
$.fn.importTags = function(str) {
id = $(this).attr('id');
$('#'+id+'_tagsinput .tag').remove();
$.fn.tagsInput.importTags(this,str);
}
$.fn.tagsInput = function(options) {
var settings = jQuery.extend({
interactive:true,
defaultText:'từ khóa',
minChars:0,
width:'300px',
height:'28px',
autocomplete: {selectFirst: false },
'hide':true,
'delimiter':',',
'unique':true,
removeWithBackspace:true,
placeholderColor:'#666666',
autosize: true,
comfortZone: 20,
inputPadding: 6*2
},options);
this.each(function() {
if (settings.hide) {
$(this).hide();
}
var id = $(this).attr('id');
if (!id || delimiter[$(this).attr('id')]) {
id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id');
}
var data = jQuery.extend({
pid:id,
real_input: '#'+id,
holder: '#'+id+'_tagsinput',
input_wrapper: '#'+id+'_addTag',
fake_input: '#'+id+'_tag'
},settings);
delimiter[id] = data.delimiter;
if (settings.onAddTag || settings.onRemoveTag || settings.onChange) {
tags_callbacks[id] = new Array();
tags_callbacks[id]['onAddTag'] = settings.onAddTag;
tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag;
tags_callbacks[id]['onChange'] = settings.onChange;
}
var markup = '<div id="'+id+'_tagsinput" class="tagsinput"><div id="'+id+'_addTag">';
if (settings.interactive) {
markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />';
}
markup = markup + '</div><div class="tags_clear"></div></div>';
$(markup).insertAfter(this);
$(data.holder).css('width',settings.width);
$(data.holder).css('min-height',settings.height);
$(data.holder).css('height',settings.height);
if ($(data.real_input).val()!='') {
$.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val());
}
if (settings.interactive) {
$(data.fake_input).val($(data.fake_input).attr('data-default'));
$(data.fake_input).css('color',settings.placeholderColor);
$(data.fake_input).resetAutosize(settings);
$(data.holder).bind('click',data,function(event) {
$(event.data.fake_input).focus();
});
$(data.fake_input).bind('focus',data,function(event) {
if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) {
$(event.data.fake_input).val('');
}
$(event.data.fake_input).css('color','#000000');
});
if (settings.autocomplete_url != undefined) {
autocomplete_options = {source: settings.autocomplete_url};
for (attrname in settings.autocomplete) {
autocomplete_options[attrname] = settings.autocomplete[attrname];
}
if (jQuery.Autocompleter !== undefined) {
$(data.fake_input).autocomplete(settings.autocomplete_url, settings.autocomplete);
$(data.fake_input).bind('result',data,function(event,data,formatted) {
if (data) {
$('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)});
}
});
} else if (jQuery.ui.autocomplete !== undefined) {
$(data.fake_input).autocomplete(autocomplete_options);
$(data.fake_input).bind('autocompleteselect',data,function(event,ui) {
$(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)});
return false;
});
}
} else {
// if a user tabs out of the field, create a new tag
// this is only available if autocomplete is not used.
$(data.fake_input).bind('blur',data,function(event) {
var d = $(this).attr('data-default');
if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) {
if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
} else {
$(event.data.fake_input).val($(event.data.fake_input).attr('data-default'));
$(event.data.fake_input).css('color',settings.placeholderColor);
}
return false;
});
}
// if user types a comma, create a new tag
$(data.fake_input).bind('keypress',data,function(event) {
if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) {
event.preventDefault();
if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
$(event.data.fake_input).resetAutosize(settings);
return false;
} else if (event.data.autosize) {
$(event.data.fake_input).doAutosize(settings);
}
});
//Delete last tag on backspace
data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event)
{
if(event.keyCode == 8 && $(this).val() == '')
{
event.preventDefault();
var last_tag = $(this).closest('.tagsinput').find('.tag:last').text();
var id = $(this).attr('id').replace(/_tag$/, '');
last_tag = last_tag.replace(/[\s]+x$/, '');
$('#' + id).removeTag(escape(last_tag));
$(this).trigger('focus');
}
});
$(data.fake_input).blur();
//Removes the not_valid class when user changes the value of the fake input
if(data.unique) {
$(data.fake_input).keydown(function(event){
if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) {
$(this).removeClass('not_valid');
}
});
}
} // if settings.interactive
});
return this;
};
$.fn.tagsInput.updateTagsField = function(obj,tagslist) {
var id = $(obj).attr('id');
$(obj).val(tagslist.join(delimiter[id]));
};
$.fn.tagsInput.importTags = function(obj,val) {
$(obj).val('');
var id = $(obj).attr('id');
var tags = val.split(delimiter[id]);
for (i=0; i<tags.length; i++) {
$(obj).addTag(tags[i],{focus:false,callback:false});
}
if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
{
var f = tags_callbacks[id]['onChange'];
f.call(obj, obj, tags[i]);
}
};
})(jQuery);
| JavaScript |
/// <reference path="Jssor.js" />
/*
* Jssor.Slider 18.0
* http://www.jssor.com/
*
* TERMS OF USE - Jssor.Slider
*
* Copyright 2014 Jssor
*
* 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.
*/
var $JssorSlider$;
var $JssorSlideshowFormations$ = window.$JssorSlideshowFormations$ = {};
var $JssorSlideshowRunner$;
new function () {
//Constants +++++++
var COLUMN_INCREASE = 0;
var COLUMN_DECREASE = 1;
var ROW_INCREASE = 2;
var ROW_DECREASE = 3;
var DIRECTION_HORIZONTAL = 0x0003;
var DIRECTION_VERTICAL = 0x000C;
var TO_LEFT = 0x0001;
var TO_RIGHT = 0x0002;
var TO_TOP = 0x0004;
var TO_BOTTOM = 0x0008;
var FROM_LEFT = 0x0100;
var FROM_TOP = 0x0200;
var FROM_RIGHT = 0x0400;
var FROM_BOTTOM = 0x0800;
var ASSEMBLY_BOTTOM_LEFT = FROM_BOTTOM + TO_LEFT;
var ASSEMBLY_BOTTOM_RIGHT = FROM_BOTTOM + TO_RIGHT;
var ASSEMBLY_TOP_LEFT = FROM_TOP + TO_LEFT;
var ASSEMBLY_TOP_RIGHT = FROM_TOP + TO_RIGHT;
var ASSEMBLY_LEFT_TOP = FROM_LEFT + TO_TOP;
var ASSEMBLY_LEFT_BOTTOM = FROM_LEFT + TO_BOTTOM;
var ASSEMBLY_RIGHT_TOP = FROM_RIGHT + TO_TOP;
var ASSEMBLY_RIGHT_BOTTOM = FROM_RIGHT + TO_BOTTOM;
//Constants -------
//Formation Definition +++++++
function isToLeft(roadValue) {
return (roadValue & TO_LEFT) == TO_LEFT;
}
function isToRight(roadValue) {
return (roadValue & TO_RIGHT) == TO_RIGHT;
}
function isToTop(roadValue) {
return (roadValue & TO_TOP) == TO_TOP;
}
function isToBottom(roadValue) {
return (roadValue & TO_BOTTOM) == TO_BOTTOM;
}
function PushFormationOrder(arr, order, formationItem) {
formationItem.push(order);
arr[order] = arr[order] || [];
arr[order].push(formationItem);
}
$JssorSlideshowFormations$.$FormationStraight = function (transition) {
var cols = transition.$Cols;
var rows = transition.$Rows;
var formationDirection = transition.$Assembly;
var count = transition.$Count;
var a = [];
var i = 0;
var col = 0;
var r = 0;
var cl = cols - 1;
var rl = rows - 1;
var il = count - 1;
var cr;
var order;
for (r = 0; r < rows; r++) {
for (col = 0; col < cols; col++) {
cr = r + ',' + col;
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
order = il - (col * rows + (rl - r));
break;
case ASSEMBLY_RIGHT_TOP:
order = il - (r * cols + (cl - col));
break;
case ASSEMBLY_TOP_LEFT:
order = il - (col * rows + r);
case ASSEMBLY_LEFT_TOP:
order = il - (r * cols + col);
break;
case ASSEMBLY_BOTTOM_RIGHT:
order = col * rows + r;
break;
case ASSEMBLY_LEFT_BOTTOM:
order = r * cols + (cl - col);
break;
case ASSEMBLY_TOP_RIGHT:
order = col * rows + (rl - r);
break;
default:
order = r * cols + col;
break; //ASSEMBLY_RIGHT_BOTTOM
}
PushFormationOrder(a, order, [r, col]);
}
}
return a;
};
$JssorSlideshowFormations$.$FormationSwirl = function (transition) {
var cols = transition.$Cols;
var rows = transition.$Rows;
var formationDirection = transition.$Assembly;
var count = transition.$Count;
var a = [];
var hit = [];
var i = 0;
var col = 0;
var r = 0;
var cl = cols - 1;
var rl = rows - 1;
var il = count - 1;
var cr;
var courses;
var course = 0;
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
col = cl;
r = 0;
courses = [ROW_INCREASE, COLUMN_DECREASE, ROW_DECREASE, COLUMN_INCREASE];
break;
case ASSEMBLY_RIGHT_TOP:
col = 0;
r = rl;
courses = [COLUMN_INCREASE, ROW_DECREASE, COLUMN_DECREASE, ROW_INCREASE];
break;
case ASSEMBLY_TOP_LEFT:
col = cl;
r = rl;
courses = [ROW_DECREASE, COLUMN_DECREASE, ROW_INCREASE, COLUMN_INCREASE];
break;
case ASSEMBLY_LEFT_TOP:
col = cl;
r = rl;
courses = [COLUMN_DECREASE, ROW_DECREASE, COLUMN_INCREASE, ROW_INCREASE];
break;
case ASSEMBLY_BOTTOM_RIGHT:
col = 0;
r = 0;
courses = [ROW_INCREASE, COLUMN_INCREASE, ROW_DECREASE, COLUMN_DECREASE];
break;
case ASSEMBLY_LEFT_BOTTOM:
col = cl;
r = 0;
courses = [COLUMN_DECREASE, ROW_INCREASE, COLUMN_INCREASE, ROW_DECREASE];
break;
case ASSEMBLY_TOP_RIGHT:
col = 0;
r = rl;
courses = [ROW_DECREASE, COLUMN_INCREASE, ROW_INCREASE, COLUMN_DECREASE];
break;
default:
col = 0;
r = 0;
courses = [COLUMN_INCREASE, ROW_INCREASE, COLUMN_DECREASE, ROW_DECREASE];
break; //ASSEMBLY_RIGHT_BOTTOM
}
i = 0;
while (i < count) {
cr = r + ',' + col;
if (col >= 0 && col < cols && r >= 0 && r < rows && !hit[cr]) {
//a[cr] = i++;
hit[cr] = true;
PushFormationOrder(a, i++, [r, col]);
}
else {
switch (courses[course++ % courses.length]) {
case COLUMN_INCREASE:
col--;
break;
case ROW_INCREASE:
r--;
break;
case COLUMN_DECREASE:
col++;
break;
case ROW_DECREASE:
r++;
break;
}
}
switch (courses[course % courses.length]) {
case COLUMN_INCREASE:
col++;
break;
case ROW_INCREASE:
r++;
break;
case COLUMN_DECREASE:
col--;
break;
case ROW_DECREASE:
r--;
break;
}
}
return a;
};
$JssorSlideshowFormations$.$FormationZigZag = function (transition) {
var cols = transition.$Cols;
var rows = transition.$Rows;
var formationDirection = transition.$Assembly;
var count = transition.$Count;
var a = [];
var i = 0;
var col = 0;
var r = 0;
var cl = cols - 1;
var rl = rows - 1;
var il = count - 1;
var cr;
var courses;
var course = 0;
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
col = cl;
r = 0;
courses = [ROW_INCREASE, COLUMN_DECREASE, ROW_DECREASE, COLUMN_DECREASE];
break;
case ASSEMBLY_RIGHT_TOP:
col = 0;
r = rl;
courses = [COLUMN_INCREASE, ROW_DECREASE, COLUMN_DECREASE, ROW_DECREASE];
break;
case ASSEMBLY_TOP_LEFT:
col = cl;
r = rl;
courses = [ROW_DECREASE, COLUMN_DECREASE, ROW_INCREASE, COLUMN_DECREASE];
break;
case ASSEMBLY_LEFT_TOP:
col = cl;
r = rl;
courses = [COLUMN_DECREASE, ROW_DECREASE, COLUMN_INCREASE, ROW_DECREASE];
break;
case ASSEMBLY_BOTTOM_RIGHT:
col = 0;
r = 0;
courses = [ROW_INCREASE, COLUMN_INCREASE, ROW_DECREASE, COLUMN_INCREASE];
break;
case ASSEMBLY_LEFT_BOTTOM:
col = cl;
r = 0;
courses = [COLUMN_DECREASE, ROW_INCREASE, COLUMN_INCREASE, ROW_INCREASE];
break;
case ASSEMBLY_TOP_RIGHT:
col = 0;
r = rl;
courses = [ROW_DECREASE, COLUMN_INCREASE, ROW_INCREASE, COLUMN_INCREASE];
break;
default:
col = 0;
r = 0;
courses = [COLUMN_INCREASE, ROW_INCREASE, COLUMN_DECREASE, ROW_INCREASE];
break; //ASSEMBLY_RIGHT_BOTTOM
}
i = 0;
while (i < count) {
cr = r + ',' + col;
if (col >= 0 && col < cols && r >= 0 && r < rows && typeof (a[cr]) == 'undefined') {
PushFormationOrder(a, i++, [r, col]);
//a[cr] = i++;
switch (courses[course % courses.length]) {
case COLUMN_INCREASE:
col++;
break;
case ROW_INCREASE:
r++;
break;
case COLUMN_DECREASE:
col--;
break;
case ROW_DECREASE:
r--;
break;
}
}
else {
switch (courses[course++ % courses.length]) {
case COLUMN_INCREASE:
col--;
break;
case ROW_INCREASE:
r--;
break;
case COLUMN_DECREASE:
col++;
break;
case ROW_DECREASE:
r++;
break;
}
switch (courses[course++ % courses.length]) {
case COLUMN_INCREASE:
col++;
break;
case ROW_INCREASE:
r++;
break;
case COLUMN_DECREASE:
col--;
break;
case ROW_DECREASE:
r--;
break;
}
}
}
return a;
};
$JssorSlideshowFormations$.$FormationStraightStairs = function (transition) {
var cols = transition.$Cols;
var rows = transition.$Rows;
var formationDirection = transition.$Assembly;
var count = transition.$Count;
var a = [];
var i = 0;
var col = 0;
var r = 0;
var cl = cols - 1;
var rl = rows - 1;
var il = count - 1;
var cr;
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
case ASSEMBLY_TOP_RIGHT:
case ASSEMBLY_TOP_LEFT:
case ASSEMBLY_BOTTOM_RIGHT:
var C = 0;
var R = 0;
break;
case ASSEMBLY_LEFT_BOTTOM:
case ASSEMBLY_RIGHT_TOP:
case ASSEMBLY_LEFT_TOP:
case ASSEMBLY_RIGHT_BOTTOM:
var C = cl;
var R = 0;
break;
default:
formationDirection = ASSEMBLY_RIGHT_BOTTOM;
var C = cl;
var R = 0;
break;
}
col = C;
r = R;
while (i < count) {
cr = r + ',' + col;
if (isToTop(formationDirection) || isToRight(formationDirection)) {
PushFormationOrder(a, il - i++, [r, col]);
//a[cr] = il - i++;
}
else {
PushFormationOrder(a, i++, [r, col]);
//a[cr] = i++;
}
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
case ASSEMBLY_TOP_RIGHT:
col--;
r++;
break;
case ASSEMBLY_TOP_LEFT:
case ASSEMBLY_BOTTOM_RIGHT:
col++;
r--;
break;
case ASSEMBLY_LEFT_BOTTOM:
case ASSEMBLY_RIGHT_TOP:
col--;
r--;
break;
case ASSEMBLY_RIGHT_BOTTOM:
case ASSEMBLY_LEFT_TOP:
default:
col++;
r++;
break;
}
if (col < 0 || r < 0 || col > cl || r > rl) {
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
case ASSEMBLY_TOP_RIGHT:
C++;
break;
case ASSEMBLY_LEFT_BOTTOM:
case ASSEMBLY_RIGHT_TOP:
case ASSEMBLY_TOP_LEFT:
case ASSEMBLY_BOTTOM_RIGHT:
R++;
break;
case ASSEMBLY_RIGHT_BOTTOM:
case ASSEMBLY_LEFT_TOP:
default:
C--;
break;
}
if (C < 0 || R < 0 || C > cl || R > rl) {
switch (formationDirection) {
case ASSEMBLY_BOTTOM_LEFT:
case ASSEMBLY_TOP_RIGHT:
C = cl;
R++;
break;
case ASSEMBLY_TOP_LEFT:
case ASSEMBLY_BOTTOM_RIGHT:
R = rl;
C++;
break;
case ASSEMBLY_LEFT_BOTTOM:
case ASSEMBLY_RIGHT_TOP: R = rl; C--;
break;
case ASSEMBLY_RIGHT_BOTTOM:
case ASSEMBLY_LEFT_TOP:
default:
C = 0;
R++;
break;
}
if (R > rl)
R = rl;
else if (R < 0)
R = 0;
else if (C > cl)
C = cl;
else if (C < 0)
C = 0;
}
r = R;
col = C;
}
}
return a;
};
$JssorSlideshowFormations$.$FormationSquare = function (transition) {
var cols = transition.$Cols || 1;
var rows = transition.$Rows || 1;
var arr = [];
var i = 0;
var col;
var r;
var dc;
var dr;
var cr;
dc = cols < rows ? (rows - cols) / 2 : 0;
dr = cols > rows ? (cols - rows) / 2 : 0;
cr = Math.round(Math.max(cols / 2, rows / 2)) + 1;
for (col = 0; col < cols; col++) {
for (r = 0; r < rows; r++)
PushFormationOrder(arr, cr - Math.min(col + 1 + dc, r + 1 + dr, cols - col + dc, rows - r + dr), [r, col]);
}
return arr;
};
$JssorSlideshowFormations$.$FormationRectangle = function (transition) {
var cols = transition.$Cols || 1;
var rows = transition.$Rows || 1;
var arr = [];
var i = 0;
var col;
var r;
var cr;
cr = Math.round(Math.min(cols / 2, rows / 2)) + 1;
for (col = 0; col < cols; col++) {
for (r = 0; r < rows; r++)
PushFormationOrder(arr, cr - Math.min(col + 1, r + 1, cols - col, rows - r), [r, col]);
}
return arr;
};
$JssorSlideshowFormations$.$FormationRandom = function (transition) {
var a = [];
var r, col, i;
for (r = 0; r < transition.$Rows; r++) {
for (col = 0; col < transition.$Cols; col++)
PushFormationOrder(a, Math.ceil(100000 * Math.random()) % 13, [r, col]);
}
return a;
};
$JssorSlideshowFormations$.$FormationCircle = function (transition) {
var cols = transition.$Cols || 1;
var rows = transition.$Rows || 1;
var arr = [];
var i = 0;
var col;
var r;
var hc = cols / 2 - 0.5;
var hr = rows / 2 - 0.5;
for (col = 0; col < cols; col++) {
for (r = 0; r < rows; r++)
PushFormationOrder(arr, Math.round(Math.sqrt(Math.pow(col - hc, 2) + Math.pow(r - hr, 2))), [r, col]);
}
return arr;
};
$JssorSlideshowFormations$.$FormationCross = function (transition) {
var cols = transition.$Cols || 1;
var rows = transition.$Rows || 1;
var arr = [];
var i = 0;
var col;
var r;
var hc = cols / 2 - 0.5;
var hr = rows / 2 - 0.5;
for (col = 0; col < cols; col++) {
for (r = 0; r < rows; r++)
PushFormationOrder(arr, Math.round(Math.min(Math.abs(col - hc), Math.abs(r - hr))), [r, col]);
}
return arr;
};
$JssorSlideshowFormations$.$FormationRectangleCross = function (transition) {
var cols = transition.$Cols || 1;
var rows = transition.$Rows || 1;
var arr = [];
var i = 0;
var col;
var r;
var hc = cols / 2 - 0.5;
var hr = rows / 2 - 0.5;
var cr = Math.max(hc, hr) + 1;
for (col = 0; col < cols; col++) {
for (r = 0; r < rows; r++)
PushFormationOrder(arr, Math.round(cr - Math.max(hc - Math.abs(col - hc), hr - Math.abs(r - hr))) - 1, [r, col]);
}
return arr;
};
function GetFormation(transition) {
var formationInstance = transition.$Formation(transition);
return transition.$Reverse ? formationInstance.reverse() : formationInstance;
} //GetFormation
//var _PrototypeTransitions = [];
function EnsureTransitionInstance(options, slideshowInterval) {
var _SlideshowTransition = {
$Interval: slideshowInterval, //Delay to play next frame
$Duration: 1, //Duration to finish the entire transition
$Delay: 0, //Delay to assembly blocks
$Cols: 1, //Number of columns
$Rows: 1, //Number of rows
$Opacity: 0, //Fade block or not
$Zoom: 0, //Zoom block or not
$Clip: 0, //Clip block or not
$Move: false, //Move block or not
$SlideOut: false, //Slide the previous slide out to display next slide instead
//$FlyDirection: 0, //Specify fly transform with direction
$Reverse: false, //Reverse the assembly or not
$Formation: $JssorSlideshowFormations$.$FormationRandom, //Shape that assembly blocks as
$Assembly: ASSEMBLY_RIGHT_BOTTOM, //The way to assembly blocks
$ChessMode: { $Column: 0, $Row: 0 }, //Chess move or fly direction
$Easing: $JssorEasing$.$EaseSwing, //Specify variation of speed during transition
$Round: {},
$Blocks: [],
$During: {}
};
$Jssor$.$Extend(_SlideshowTransition, options);
_SlideshowTransition.$Count = _SlideshowTransition.$Cols * _SlideshowTransition.$Rows;
if ($Jssor$.$IsFunction(_SlideshowTransition.$Easing))
_SlideshowTransition.$Easing = { $Default: _SlideshowTransition.$Easing };
_SlideshowTransition.$FramesCount = Math.ceil(_SlideshowTransition.$Duration / _SlideshowTransition.$Interval);
_SlideshowTransition.$EasingInstance = GetEasing(_SlideshowTransition);
_SlideshowTransition.$GetBlocks = function (width, height) {
width /= _SlideshowTransition.$Cols;
height /= _SlideshowTransition.$Rows;
var wh = width + 'x' + height;
if (!_SlideshowTransition.$Blocks[wh]) {
_SlideshowTransition.$Blocks[wh] = { $Width: width, $Height: height };
for (var col = 0; col < _SlideshowTransition.$Cols; col++) {
for (var r = 0; r < _SlideshowTransition.$Rows; r++)
_SlideshowTransition.$Blocks[wh][r + ',' + col] = { $Top: r * height, $Right: col * width + width, $Bottom: r * height + height, $Left: col * width };
}
}
return _SlideshowTransition.$Blocks[wh];
};
if (_SlideshowTransition.$Brother) {
_SlideshowTransition.$Brother = EnsureTransitionInstance(_SlideshowTransition.$Brother, slideshowInterval);
_SlideshowTransition.$SlideOut = true;
}
return _SlideshowTransition;
}
function GetEasing(transition) {
var easing = transition.$Easing;
if (!easing.$Default)
easing.$Default = $JssorEasing$.$EaseSwing;
var duration = transition.$FramesCount;
var cache = easing.$Cache;
if (!cache) {
var enumerator = $Jssor$.$Extend({}, transition.$Easing, transition.$Round);
cache = easing.$Cache = {};
$Jssor$.$Each(enumerator, function (v, easingName) {
var easingFunction = easing[easingName] || easing.$Default;
var round = transition.$Round[easingName] || 1;
if (!$Jssor$.$IsArray(easingFunction.$Cache))
easingFunction.$Cache = [];
var easingFunctionCache = easingFunction.$Cache[duration] = easingFunction.$Cache[duration] || [];
if (!easingFunctionCache[round]) {
easingFunctionCache[round] = [0];
for (var t = 1; t <= duration; t++) {
var tRound = t / duration * round;
var tRoundFloor = Math.floor(tRound);
if (tRound != tRoundFloor)
tRound -= tRoundFloor;
easingFunctionCache[round][t] = easingFunction(tRound);
}
}
cache[easingName] = easingFunctionCache;
});
}
return cache;
} //GetEasing
//Formation Definition -------
function JssorSlideshowPlayer(slideContainer, slideElement, slideTransition, beginTime, slideContainerWidth, slideContainerHeight) {
var _Self = this;
var _Block;
var _StartStylesArr = {};
var _AnimationStylesArrs = {};
var _AnimationBlockItems = [];
var _StyleStart;
var _StyleEnd;
var _StyleDif;
var _ChessModeColumn = slideTransition.$ChessMode.$Column || 0;
var _ChessModeRow = slideTransition.$ChessMode.$Row || 0;
var _Blocks = slideTransition.$GetBlocks(slideContainerWidth, slideContainerHeight);
var _FormationInstance = GetFormation(slideTransition);
var _MaxOrder = _FormationInstance.length - 1;
var _Period = slideTransition.$Duration + slideTransition.$Delay * _MaxOrder;
var _EndTime = beginTime + _Period;
var _SlideOut = slideTransition.$SlideOut;
var _IsIn;
_EndTime += $Jssor$.$IsBrowserChrome() ? 260 : 50;
_Self.$EndTime = _EndTime;
_Self.$ShowFrame = function (time) {
time -= beginTime;
var isIn = time < _Period;
if (isIn || _IsIn) {
_IsIn = isIn;
if (!_SlideOut)
time = _Period - time;
var frameIndex = Math.ceil(time / slideTransition.$Interval);
$Jssor$.$Each(_AnimationStylesArrs, function (value, index) {
var itemFrameIndex = Math.max(frameIndex, value.$Min);
itemFrameIndex = Math.min(itemFrameIndex, value.length - 1);
if (value.$LastFrameIndex != itemFrameIndex) {
if (!value.$LastFrameIndex && !_SlideOut) {
$Jssor$.$ShowElement(_AnimationBlockItems[index]);
}
else if (itemFrameIndex == value.$Max && _SlideOut) {
$Jssor$.$HideElement(_AnimationBlockItems[index]);
}
value.$LastFrameIndex = itemFrameIndex;
$Jssor$.$SetStylesEx(_AnimationBlockItems[index], value[itemFrameIndex]);
}
});
}
};
function DisableHWA(elmt) {
$Jssor$.$DisableHWA(elmt);
var children = $Jssor$.$Children(elmt);
$Jssor$.$Each(children, function (child) {
DisableHWA(child);
});
}
//constructor
{
slideElement = $Jssor$.$CloneNode(slideElement);
DisableHWA(slideElement);
if ($Jssor$.$IsBrowserIe9Earlier()) {
var hasImage = !slideElement["no-image"];
var slideChildElements = $Jssor$.$FindChildrenByTag(slideElement);
$Jssor$.$Each(slideChildElements, function (slideChildElement) {
if (hasImage || slideChildElement["jssor-slider"])
$Jssor$.$CssOpacity(slideChildElement, $Jssor$.$CssOpacity(slideChildElement), true);
});
}
$Jssor$.$Each(_FormationInstance, function (formationItems, order) {
$Jssor$.$Each(formationItems, function (formationItem) {
var row = formationItem[0];
var col = formationItem[1];
{
var columnRow = row + ',' + col;
var chessHorizontal = false;
var chessVertical = false;
var chessRotate = false;
if (_ChessModeColumn && col % 2) {
if ($JssorDirection$.$IsHorizontal(_ChessModeColumn)) {
chessHorizontal = !chessHorizontal;
}
if ($JssorDirection$.$IsVertical(_ChessModeColumn)) {
chessVertical = !chessVertical;
}
if (_ChessModeColumn & 16)
chessRotate = !chessRotate;
}
if (_ChessModeRow && row % 2) {
if ($JssorDirection$.$IsHorizontal(_ChessModeRow)) {
chessHorizontal = !chessHorizontal;
}
if ($JssorDirection$.$IsVertical(_ChessModeRow)) {
chessVertical = !chessVertical;
}
if (_ChessModeRow & 16)
chessRotate = !chessRotate;
}
slideTransition.$Top = slideTransition.$Top || (slideTransition.$Clip & 4);
slideTransition.$Bottom = slideTransition.$Bottom || (slideTransition.$Clip & 8);
slideTransition.$Left = slideTransition.$Left || (slideTransition.$Clip & 1);
slideTransition.$Right = slideTransition.$Right || (slideTransition.$Clip & 2);
var topBenchmark = chessVertical ? slideTransition.$Bottom : slideTransition.$Top;
var bottomBenchmark = chessVertical ? slideTransition.$Top : slideTransition.$Bottom;
var leftBenchmark = chessHorizontal ? slideTransition.$Right : slideTransition.$Left;
var rightBenchmark = chessHorizontal ? slideTransition.$Left : slideTransition.$Right;
//$JssorDebug$.$Execute(function () {
// topBenchmark = bottomBenchmark = leftBenchmark = rightBenchmark = false;
//});
slideTransition.$Clip = topBenchmark || bottomBenchmark || leftBenchmark || rightBenchmark;
_StyleDif = {};
_StyleEnd = { $Top: 0, $Left: 0, $Opacity: 1, $Width: slideContainerWidth, $Height: slideContainerHeight };
_StyleStart = $Jssor$.$Extend({}, _StyleEnd);
_Block = $Jssor$.$Extend({}, _Blocks[columnRow]);
if (slideTransition.$Opacity) {
_StyleEnd.$Opacity = 2 - slideTransition.$Opacity;
}
if (slideTransition.$ZIndex) {
_StyleEnd.$ZIndex = slideTransition.$ZIndex;
_StyleStart.$ZIndex = 0;
}
var allowClip = slideTransition.$Cols * slideTransition.$Rows > 1 || slideTransition.$Clip;
if (slideTransition.$Zoom || slideTransition.$Rotate) {
var allowRotate = true;
if ($Jssor$.$IsBrowserIE() && $Jssor$.$BrowserEngineVersion() < 9) {
if (slideTransition.$Cols * slideTransition.$Rows > 1)
allowRotate = false;
else
allowClip = false;
}
if (allowRotate) {
_StyleEnd.$Zoom = slideTransition.$Zoom ? slideTransition.$Zoom - 1 : 1;
_StyleStart.$Zoom = 1;
if ($Jssor$.$IsBrowserIe9Earlier() || $Jssor$.$IsBrowserOpera())
_StyleEnd.$Zoom = Math.min(_StyleEnd.$Zoom, 2);
var rotate = slideTransition.$Rotate;
_StyleEnd.$Rotate = rotate * 360 * ((chessRotate) ? -1 : 1);
_StyleStart.$Rotate = 0;
}
}
if (allowClip) {
if (slideTransition.$Clip) {
var clipScale = slideTransition.$ScaleClip || 1;
var blockOffset = _Block.$Offset = {};
if (topBenchmark && bottomBenchmark) {
blockOffset.$Top = _Blocks.$Height / 2 * clipScale;
blockOffset.$Bottom = -blockOffset.$Top;
}
else if (topBenchmark) {
blockOffset.$Bottom = -_Blocks.$Height * clipScale;
}
else if (bottomBenchmark) {
blockOffset.$Top = _Blocks.$Height * clipScale;
}
if (leftBenchmark && rightBenchmark) {
blockOffset.$Left = _Blocks.$Width / 2 * clipScale;
blockOffset.$Right = -blockOffset.$Left;
}
else if (leftBenchmark) {
blockOffset.$Right = -_Blocks.$Width * clipScale;
}
else if (rightBenchmark) {
blockOffset.$Left = _Blocks.$Width * clipScale;
}
}
_StyleDif.$Clip = _Block;
_StyleStart.$Clip = _Blocks[columnRow];
}
//fly
{
var chessHor = chessHorizontal ? 1 : -1;
var chessVer = chessVertical ? 1 : -1;
if (slideTransition.x)
_StyleEnd.$Left += slideContainerWidth * slideTransition.x * chessHor;
if (slideTransition.y)
_StyleEnd.$Top += slideContainerHeight * slideTransition.y * chessVer;
}
$Jssor$.$Each(_StyleEnd, function (propertyEnd, property) {
if ($Jssor$.$IsNumeric(propertyEnd)) {
if (propertyEnd != _StyleStart[property]) {
_StyleDif[property] = propertyEnd - _StyleStart[property];
}
}
});
_StartStylesArr[columnRow] = _SlideOut ? _StyleStart : _StyleEnd;
var animationStylesArr = [];
var virtualFrameCount = Math.round(order * slideTransition.$Delay / slideTransition.$Interval);
_AnimationStylesArrs[columnRow] = new Array(virtualFrameCount);
_AnimationStylesArrs[columnRow].$Min = virtualFrameCount;
var framesCount = slideTransition.$FramesCount;
for (var frameN = 0; frameN <= framesCount; frameN++) {
var styleFrameN = {};
$Jssor$.$Each(_StyleDif, function (propertyDiff, property) {
var propertyEasings = slideTransition.$EasingInstance[property] || slideTransition.$EasingInstance.$Default;
var propertyEasingArray = propertyEasings[slideTransition.$Round[property] || 1];
var propertyDuring = slideTransition.$During[property] || [0, 1];
var propertyFrameN = (frameN / framesCount - propertyDuring[0]) / propertyDuring[1] * framesCount;
propertyFrameN = Math.round(Math.min(framesCount, Math.max(propertyFrameN, 0)));
var propertyEasingValue = propertyEasingArray[propertyFrameN];
if ($Jssor$.$IsNumeric(propertyDiff)) {
styleFrameN[property] = _StyleStart[property] + propertyDiff * propertyEasingValue;
}
else {
var value = styleFrameN[property] = $Jssor$.$Extend({}, _StyleStart[property]);
value.$Offset = [];
$Jssor$.$Each(propertyDiff.$Offset, function (rectX, n) {
var offsetValue = rectX * propertyEasingValue;
value.$Offset[n] = offsetValue;
value[n] += offsetValue;
});
}
});
if (_StyleStart.$Zoom) {
styleFrameN.$Transform = { $Rotate: styleFrameN.$Rotate || 0, $Scale: styleFrameN.$Zoom, $OriginalWidth: slideContainerWidth, $OriginalHeight: slideContainerHeight };
}
if (styleFrameN.$Clip && slideTransition.$Move) {
var styleFrameNClipOffset = styleFrameN.$Clip.$Offset;
var offsetY = (styleFrameNClipOffset.$Top || 0) + (styleFrameNClipOffset.$Bottom || 0);
var offsetX = (styleFrameNClipOffset.$Left || 0) + (styleFrameNClipOffset.$Right || 0);
styleFrameN.$Left = (styleFrameN.$Left || 0) + offsetX;
styleFrameN.$Top = (styleFrameN.$Top || 0) + offsetY;
styleFrameN.$Clip.$Left -= offsetX;
styleFrameN.$Clip.$Right -= offsetX;
styleFrameN.$Clip.$Top -= offsetY;
styleFrameN.$Clip.$Bottom -= offsetY;
}
styleFrameN.$ZIndex = styleFrameN.$ZIndex || 1;
_AnimationStylesArrs[columnRow].push(styleFrameN);
}
} //for
});
});
_FormationInstance.reverse();
$Jssor$.$Each(_FormationInstance, function (formationItems) {
$Jssor$.$Each(formationItems, function (formationItem) {
var row = formationItem[0];
var col = formationItem[1];
var columnRow = row + ',' + col;
var image = slideElement;
if (col || row)
image = $Jssor$.$CloneNode(slideElement);
$Jssor$.$SetStyles(image, _StartStylesArr[columnRow]);
$Jssor$.$CssOverflow(image, "hidden");
$Jssor$.$CssPosition(image, "absolute");
slideContainer.$AddClipElement(image);
_AnimationBlockItems[columnRow] = image;
$Jssor$.$ShowElement(image, !_SlideOut);
});
});
}
}
//JssorSlideshowRunner++++++++
var _SlideshowRunnerCount = 1;
$JssorSlideshowRunner$ = window.$JssorSlideshowRunner$ = function (slideContainer, slideContainerWidth, slideContainerHeight, slideshowOptions, handleTouchEventOnly) {
var _SelfSlideshowRunner = this;
//var _State = 0; //-1 fullfill, 0 clean, 1 initializing, 2 stay, 3 playing
var _EndTime;
var _SliderFrameCount;
var _SlideshowPlayerBelow;
var _SlideshowPlayerAbove;
var _PrevItem;
var _SlideItem;
var _TransitionIndex = 0;
var _TransitionsOrder = slideshowOptions.$TransitionsOrder;
var _SlideshowTransition;
var _SlideshowPerformance = 8;
function SlideshowProcessor() {
var _SelfSlideshowProcessor = this;
var _CurrentTime = 0;
$JssorAnimator$.call(_SelfSlideshowProcessor, 0, _EndTime);
_SelfSlideshowProcessor.$OnPositionChange = function (oldPosition, newPosition) {
if ((newPosition - _CurrentTime) > _SlideshowPerformance) {
_CurrentTime = newPosition;
_SlideshowPlayerAbove && _SlideshowPlayerAbove.$ShowFrame(newPosition);
_SlideshowPlayerBelow && _SlideshowPlayerBelow.$ShowFrame(newPosition);
}
};
_SelfSlideshowProcessor.$Transition = _SlideshowTransition;
}
//member functions
_SelfSlideshowRunner.$GetTransition = function (slideCount) {
var n = 0;
var transitions = slideshowOptions.$Transitions;
var transitionCount = transitions.length;
if (_TransitionsOrder) { /*Sequence*/
//if (transitionCount > slideCount && ($Jssor$.$IsBrowserChrome() || $Jssor$.$IsBrowserSafari() || $Jssor$.$IsBrowserFireFox())) {
// transitionCount -= transitionCount % slideCount;
//}
n = _TransitionIndex++ % transitionCount;
}
else { /*Random*/
n = Math.floor(Math.random() * transitionCount);
}
transitions[n] && (transitions[n].$Index = n);
return transitions[n];
};
_SelfSlideshowRunner.$Initialize = function (slideIndex, prevIndex, slideItem, prevItem, slideshowTransition) {
$JssorDebug$.$Execute(function () {
if (_SlideshowPlayerBelow) {
$JssorDebug$.$Fail("slideshow runner has not been cleared.");
}
});
_SlideshowTransition = slideshowTransition;
slideshowTransition = EnsureTransitionInstance(slideshowTransition, _SlideshowPerformance);
_SlideItem = slideItem;
_PrevItem = prevItem;
var prevSlideElement = prevItem.$Item;
var currentSlideElement = slideItem.$Item;
prevSlideElement["no-image"] = !prevItem.$Image;
currentSlideElement["no-image"] = !slideItem.$Image;
var slideElementAbove = prevSlideElement;
var slideElementBelow = currentSlideElement;
var slideTransitionAbove = slideshowTransition;
var slideTransitionBelow = slideshowTransition.$Brother || EnsureTransitionInstance({}, _SlideshowPerformance);
if (!slideshowTransition.$SlideOut) {
slideElementAbove = currentSlideElement;
slideElementBelow = prevSlideElement;
}
var shift = slideTransitionBelow.$Shift || 0;
_SlideshowPlayerBelow = new JssorSlideshowPlayer(slideContainer, slideElementBelow, slideTransitionBelow, Math.max(shift - slideTransitionBelow.$Interval, 0), slideContainerWidth, slideContainerHeight);
_SlideshowPlayerAbove = new JssorSlideshowPlayer(slideContainer, slideElementAbove, slideTransitionAbove, Math.max(slideTransitionBelow.$Interval - shift, 0), slideContainerWidth, slideContainerHeight);
_SlideshowPlayerBelow.$ShowFrame(0);
_SlideshowPlayerAbove.$ShowFrame(0);
_EndTime = Math.max(_SlideshowPlayerBelow.$EndTime, _SlideshowPlayerAbove.$EndTime);
_SelfSlideshowRunner.$Index = slideIndex;
};
_SelfSlideshowRunner.$Clear = function () {
slideContainer.$Clear();
_SlideshowPlayerBelow = null;
_SlideshowPlayerAbove = null;
};
_SelfSlideshowRunner.$GetProcessor = function () {
var slideshowProcessor = null;
if (_SlideshowPlayerAbove)
slideshowProcessor = new SlideshowProcessor();
return slideshowProcessor;
};
//Constructor
{
if ($Jssor$.$IsBrowserIe9Earlier() || $Jssor$.$IsBrowserOpera() || (handleTouchEventOnly && $Jssor$.$WebKitVersion() < 537)) {
_SlideshowPerformance = 16;
}
$JssorObject$.call(_SelfSlideshowRunner);
$JssorAnimator$.call(_SelfSlideshowRunner, -10000000, 10000000);
$JssorDebug$.$LiveStamp(_SelfSlideshowRunner, "slideshow_runner_" + _SlideshowRunnerCount++);
}
};
//JssorSlideshowRunner--------
//JssorSlider
function JssorSlider(elmt, options) {
var _SelfSlider = this;
//private classes
function Conveyor() {
var _SelfConveyor = this;
$JssorAnimator$.call(_SelfConveyor, -100000000, 200000000);
_SelfConveyor.$GetCurrentSlideInfo = function () {
var positionDisplay = _SelfConveyor.$GetPosition_Display();
var virtualIndex = Math.floor(positionDisplay);
var slideIndex = GetRealIndex(virtualIndex);
var slidePosition = positionDisplay - Math.floor(positionDisplay);
return { $Index: slideIndex, $VirtualIndex: virtualIndex, $Position: slidePosition };
};
_SelfConveyor.$OnPositionChange = function (oldPosition, newPosition) {
var index = Math.floor(newPosition);
if (index != newPosition && newPosition > oldPosition)
index++;
ResetNavigator(index, true);
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_POSITION_CHANGE, GetRealIndex(newPosition), GetRealIndex(oldPosition), newPosition, oldPosition);
};
}
//Carousel
function Carousel() {
var _SelfCarousel = this;
$JssorAnimator$.call(_SelfCarousel, 0, 0, { $LoopLength: _SlideCount });
//Carousel Constructor
{
$Jssor$.$Each(_SlideItems, function (slideItem) {
(_Loop & 1) && slideItem.$SetLoopLength(_SlideCount);
_SelfCarousel.$Chain(slideItem);
slideItem.$Shift(_ParkingPosition / _StepLength);
});
}
}
//Carousel
//Slideshow
function Slideshow() {
var _SelfSlideshow = this;
var _Wrapper = _SlideContainer.$Elmt;
$JssorAnimator$.call(_SelfSlideshow, -1, 2, { $Easing: $JssorEasing$.$EaseLinear, $Setter: { $Position: SetPosition }, $LoopLength: _SlideCount }, _Wrapper, { $Position: 1 }, { $Position: -1 });
_SelfSlideshow.$Wrapper = _Wrapper;
//Slideshow Constructor
{
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_SlideContainer.$Elmt, "debug-id", "slide_container");
});
}
}
//Slideshow
//CarouselPlayer
function CarouselPlayer(carousel, slideshow) {
var _SelfCarouselPlayer = this;
var _FromPosition;
var _ToPosition;
var _Duration;
var _StandBy;
var _StandByPosition;
$JssorAnimator$.call(_SelfCarouselPlayer, -100000000, 200000000, { $IntervalMax: 100 });
_SelfCarouselPlayer.$OnStart = function () {
_IsSliding = true;
_LoadingTicket = null;
//EVT_SWIPE_START
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_SWIPE_START, GetRealIndex(_Conveyor.$GetPosition()), _Conveyor.$GetPosition());
};
_SelfCarouselPlayer.$OnStop = function () {
_IsSliding = false;
_StandBy = false;
var currentSlideInfo = _Conveyor.$GetCurrentSlideInfo();
//EVT_SWIPE_END
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_SWIPE_END, GetRealIndex(_Conveyor.$GetPosition()), _Conveyor.$GetPosition());
if (!currentSlideInfo.$Position) {
OnPark(currentSlideInfo.$VirtualIndex, _CurrentSlideIndex);
}
};
_SelfCarouselPlayer.$OnPositionChange = function (oldPosition, newPosition) {
var toPosition;
if (_StandBy)
toPosition = _StandByPosition;
else {
toPosition = _ToPosition;
if (_Duration) {
var interPosition = newPosition / _Duration;
//if ($Jssor$.$IsBrowserChrome() || $Jssor$.$IsBrowserFireFox()) {
// Math.round(interPosition * 8 / _Duration) / 8 * _Duration;
// if ($Jssor$.$BrowserVersion() < 38)
// interPosition = parseFloat(interPosition.toFixed(4));
//}
toPosition = _Options.$SlideEasing(interPosition) * (_ToPosition - _FromPosition) + _FromPosition;
}
}
_Conveyor.$GoToPosition(toPosition);
};
_SelfCarouselPlayer.$PlayCarousel = function (fromPosition, toPosition, duration, callback) {
$JssorDebug$.$Execute(function () {
if (_SelfCarouselPlayer.$IsPlaying())
$JssorDebug$.$Fail("The carousel is already playing.");
});
_FromPosition = fromPosition;
_ToPosition = toPosition;
_Duration = duration;
_Conveyor.$GoToPosition(fromPosition);
_SelfCarouselPlayer.$GoToPosition(0);
_SelfCarouselPlayer.$PlayToPosition(duration, callback);
};
_SelfCarouselPlayer.$StandBy = function (standByPosition) {
_StandBy = true;
_StandByPosition = standByPosition;
_SelfCarouselPlayer.$Play(standByPosition, null, true);
};
_SelfCarouselPlayer.$SetStandByPosition = function (standByPosition) {
_StandByPosition = standByPosition;
};
_SelfCarouselPlayer.$MoveCarouselTo = function (position) {
_Conveyor.$GoToPosition(position);
};
//CarouselPlayer Constructor
{
_Conveyor = new Conveyor();
_Conveyor.$Combine(carousel);
_Conveyor.$Combine(slideshow);
}
}
//CarouselPlayer
//SlideContainer
function SlideContainer() {
var _Self = this;
var elmt = CreatePanel();
$Jssor$.$CssZIndex(elmt, 0);
$Jssor$.$Css(elmt, "pointerEvents", "none");
_Self.$Elmt = elmt;
_Self.$AddClipElement = function (clipElement) {
$Jssor$.$AppendChild(elmt, clipElement);
$Jssor$.$ShowElement(elmt);
};
_Self.$Clear = function () {
$Jssor$.$HideElement(elmt);
$Jssor$.$ClearInnerHtml(elmt);
};
}
//SlideContainer
//SlideItem
function SlideItem(slideElmt, slideIndex) {
var _SelfSlideItem = this;
var _CaptionSliderIn;
var _CaptionSliderOut;
var _CaptionSliderCurrent;
var _IsCaptionSliderPlayingWhenDragStart;
var _Wrapper;
var _BaseElement = slideElmt;
var _LoadingScreen;
var _ImageItem;
var _ImageElmts = [];
var _LinkItemOrigin;
var _LinkItem;
var _ImageLoading;
var _ImageLoaded;
var _ImageLazyLoading;
var _ContentRefreshed;
var _Processor;
var _PlayerInstanceElement;
var _PlayerInstance;
var _SequenceNumber; //for debug only
$JssorAnimator$.call(_SelfSlideItem, -_DisplayPieces, _DisplayPieces + 1, { $SlideItemAnimator: true });
function ResetCaptionSlider(fresh) {
_CaptionSliderOut && _CaptionSliderOut.$Revert();
_CaptionSliderIn && _CaptionSliderIn.$Revert();
RefreshContent(slideElmt, fresh);
_ContentRefreshed = true;
_CaptionSliderIn = new _CaptionSliderOptions.$Class(slideElmt, _CaptionSliderOptions, 1);
$JssorDebug$.$LiveStamp(_CaptionSliderIn, "caption_slider_" + _CaptionSliderCount + "_in");
_CaptionSliderOut = new _CaptionSliderOptions.$Class(slideElmt, _CaptionSliderOptions);
$JssorDebug$.$LiveStamp(_CaptionSliderOut, "caption_slider_" + _CaptionSliderCount + "_out");
$JssorDebug$.$Execute(function () {
_CaptionSliderCount++;
});
_CaptionSliderOut.$GoToBegin();
_CaptionSliderIn.$GoToBegin();
}
function EnsureCaptionSliderVersion() {
if (_CaptionSliderIn.$Version < _CaptionSliderOptions.$Version) {
ResetCaptionSlider();
}
}
//event handling begin
function LoadImageCompleteEventHandler(completeCallback, loadingScreen, image) {
if (!_ImageLoaded) {
_ImageLoaded = true;
if (_ImageItem && image) {
var imageWidth = image.width;
var imageHeight = image.height;
var fillWidth = imageWidth;
var fillHeight = imageHeight;
if (imageWidth && imageHeight && _Options.$FillMode) {
//0 stretch, 1 contain (keep aspect ratio and put all inside slide), 2 cover (keep aspect ratio and cover whole slide), 4 actual size, 5 contain for large image, actual size for small image, default value is 0
if (_Options.$FillMode & 3 && (!(_Options.$FillMode & 4) || imageWidth > _SlideWidth || imageHeight > _SlideHeight)) {
var fitHeight = false;
var ratio = _SlideWidth / _SlideHeight * imageHeight / imageWidth;
if (_Options.$FillMode & 1) {
fitHeight = (ratio > 1);
}
else if (_Options.$FillMode & 2) {
fitHeight = (ratio < 1);
}
fillWidth = fitHeight ? imageWidth * _SlideHeight / imageHeight : _SlideWidth;
fillHeight = fitHeight ? _SlideHeight : imageHeight * _SlideWidth / imageWidth;
}
$Jssor$.$CssWidth(_ImageItem, fillWidth);
$Jssor$.$CssHeight(_ImageItem, fillHeight);
$Jssor$.$CssTop(_ImageItem, (_SlideHeight - fillHeight) / 2);
$Jssor$.$CssLeft(_ImageItem, (_SlideWidth - fillWidth) / 2);
}
$Jssor$.$CssPosition(_ImageItem, "absolute");
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_LOAD_END, slideItem);
}
}
$Jssor$.$HideElement(loadingScreen);
completeCallback && completeCallback(_SelfSlideItem);
}
function LoadSlideshowImageCompleteEventHandler(nextIndex, nextItem, slideshowTransition, loadingTicket) {
if (loadingTicket == _LoadingTicket && _CurrentSlideIndex == slideIndex && _AutoPlay) {
if (!_Frozen) {
var nextRealIndex = GetRealIndex(nextIndex);
_SlideshowRunner.$Initialize(nextRealIndex, slideIndex, nextItem, _SelfSlideItem, slideshowTransition);
nextItem.$HideContentForSlideshow();
_Slideshow.$Locate(nextRealIndex, 1);
_Slideshow.$GoToPosition(nextRealIndex);
_CarouselPlayer.$PlayCarousel(nextIndex, nextIndex, 0);
}
}
}
function SlideReadyEventHandler(loadingTicket) {
if (loadingTicket == _LoadingTicket && _CurrentSlideIndex == slideIndex) {
if (!_Processor) {
var slideshowProcessor = null;
if (_SlideshowRunner) {
if (_SlideshowRunner.$Index == slideIndex)
slideshowProcessor = _SlideshowRunner.$GetProcessor();
else
_SlideshowRunner.$Clear();
}
EnsureCaptionSliderVersion();
_Processor = new Processor(slideIndex, slideshowProcessor, _SelfSlideItem.$GetCaptionSliderIn(), _SelfSlideItem.$GetCaptionSliderOut());
_Processor.$SetPlayer(_PlayerInstance);
}
!_Processor.$IsPlaying() && _Processor.$Replay();
}
}
function ParkEventHandler(currentIndex, previousIndex) {
if (currentIndex == slideIndex) {
if (currentIndex != previousIndex)
_SlideItems[previousIndex] && _SlideItems[previousIndex].$ParkOut();
else
_Processor && _Processor.$AdjustIdleOnPark();
_PlayerInstance && _PlayerInstance.$Enable();
//park in
var loadingTicket = _LoadingTicket = $Jssor$.$GetNow();
_SelfSlideItem.$LoadImage($Jssor$.$CreateCallback(null, SlideReadyEventHandler, loadingTicket));
}
else {
var distance = Math.abs(slideIndex - currentIndex);
var loadRange = _DisplayPieces + _Options.$LazyLoading;
if (!_ImageLazyLoading || distance <= loadRange || _SlideCount - distance <= loadRange) {
_SelfSlideItem.$LoadImage();
}
}
}
function SwipeStartEventHandler() {
if (_CurrentSlideIndex == slideIndex && _Processor) {
_Processor.$Stop();
_PlayerInstance && _PlayerInstance.$Quit();
_PlayerInstance && _PlayerInstance.$Disable();
_Processor.$OpenSlideshowPanel();
}
}
function FreezeEventHandler() {
if (_CurrentSlideIndex == slideIndex && _Processor) {
_Processor.$Stop();
}
}
function LinkClickEventHandler(event) {
if (_LastDragSucceded) {
$Jssor$.$CancelEvent(event);
}
else {
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_CLICK, slideIndex, event);
}
}
function PlayerAvailableEventHandler() {
_PlayerInstance = _PlayerInstanceElement.pInstance;
_Processor && _Processor.$SetPlayer(_PlayerInstance);
}
_SelfSlideItem.$LoadImage = function (completeCallback, loadingScreen) {
loadingScreen = loadingScreen || _LoadingScreen;
if (_ImageElmts.length && !_ImageLoaded) {
$Jssor$.$ShowElement(loadingScreen);
if (!_ImageLoading) {
_ImageLoading = true;
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_LOAD_START);
$Jssor$.$Each(_ImageElmts, function (imageElmt) {
if (!imageElmt.src) {
imageElmt.src = $Jssor$.$AttributeEx(imageElmt, "src2");
$Jssor$.$CssDisplay(imageElmt, imageElmt["display-origin"]);
}
});
}
$Jssor$.$LoadImages(_ImageElmts, _ImageItem, $Jssor$.$CreateCallback(null, LoadImageCompleteEventHandler, completeCallback, loadingScreen));
}
else {
LoadImageCompleteEventHandler(completeCallback, loadingScreen);
}
};
_SelfSlideItem.$GoForNextSlide = function () {
if (_SlideshowRunner) {
var slideshowTransition = _SlideshowRunner.$GetTransition(_SlideCount);
if (slideshowTransition) {
var loadingTicket = _LoadingTicket = $Jssor$.$GetNow();
var nextIndex = slideIndex + _PlayReverse;
var nextItem = _SlideItems[GetRealIndex(nextIndex)];
return nextItem.$LoadImage($Jssor$.$CreateCallback(null, LoadSlideshowImageCompleteEventHandler, nextIndex, nextItem, slideshowTransition, loadingTicket), _LoadingScreen);
}
}
PlayTo(_CurrentSlideIndex + _Options.$AutoPlaySteps * _PlayReverse);
};
_SelfSlideItem.$TryActivate = function () {
ParkEventHandler(slideIndex, slideIndex);
};
_SelfSlideItem.$ParkOut = function () {
//park out
_PlayerInstance && _PlayerInstance.$Quit();
_PlayerInstance && _PlayerInstance.$Disable();
_SelfSlideItem.$UnhideContentForSlideshow();
_Processor && _Processor.$Abort();
_Processor = null;
ResetCaptionSlider();
};
//for debug only
_SelfSlideItem.$StampSlideItemElements = function (stamp) {
stamp = _SequenceNumber + "_" + stamp;
$JssorDebug$.$Execute(function () {
if (_ImageItem)
$Jssor$.$Attribute(_ImageItem, "debug-id", stamp + "_slide_item_image_id");
$Jssor$.$Attribute(slideElmt, "debug-id", stamp + "_slide_item_item_id");
});
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_Wrapper, "debug-id", stamp + "_slide_item_wrapper_id");
});
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_LoadingScreen, "debug-id", stamp + "_loading_container_id");
});
};
_SelfSlideItem.$HideContentForSlideshow = function () {
$Jssor$.$HideElement(slideElmt);
};
_SelfSlideItem.$UnhideContentForSlideshow = function () {
$Jssor$.$ShowElement(slideElmt);
};
_SelfSlideItem.$EnablePlayer = function () {
_PlayerInstance && _PlayerInstance.$Enable();
};
function RefreshContent(elmt, fresh, level) {
if (elmt["jssor-slider"])
return;
level = level || 0;
if (!_ContentRefreshed) {
if (elmt.tagName == "IMG") {
_ImageElmts.push(elmt);
if (!elmt.src) {
_ImageLazyLoading = true;
elmt["display-origin"] = $Jssor$.$CssDisplay(elmt);
$Jssor$.$HideElement(elmt);
}
}
if ($Jssor$.$IsBrowserIe9Earlier()) {
$Jssor$.$CssZIndex(elmt, ($Jssor$.$CssZIndex(elmt) || 0) + 1);
}
if (_Options.$HWA && $Jssor$.$WebKitVersion()) {
if (!_HandleTouchEventOnly || $Jssor$.$WebKitVersion() < 534 || (!_SlideshowEnabled && !$Jssor$.$IsBrowserChrome())) {
$Jssor$.$EnableHWA(elmt);
}
}
}
var childElements = $Jssor$.$Children(elmt);
$Jssor$.$Each(childElements, function (childElement, i) {
var uAttribute = $Jssor$.$AttributeEx(childElement, "u");
if (uAttribute == "player" && !_PlayerInstanceElement) {
_PlayerInstanceElement = childElement;
if (_PlayerInstanceElement.pInstance) {
PlayerAvailableEventHandler();
}
else {
$Jssor$.$AddEvent(_PlayerInstanceElement, "dataavailable", PlayerAvailableEventHandler);
}
}
if (uAttribute == "caption") {
if (!$Jssor$.$IsBrowserIE() && !fresh) {
var captionElement = $Jssor$.$CloneNode(childElement);
$Jssor$.$InsertBefore(elmt, captionElement, childElement);
$Jssor$.$RemoveChild(elmt, childElement);
childElement = captionElement;
fresh = true;
}
}
else if (!_ContentRefreshed && !level && !_ImageItem && $Jssor$.$AttributeEx(childElement, "u") == "image") {
_ImageItem = childElement;
if (_ImageItem) {
if (_ImageItem.tagName == "A") {
_LinkItemOrigin = _ImageItem;
$Jssor$.$SetStyles(_LinkItemOrigin, _StyleDef);
_LinkItem = $Jssor$.$CloneNode(_ImageItem, true);
//cancel click event on <A> element when a drag of slide succeeded
$Jssor$.$AddEvent(_LinkItem, "click", LinkClickEventHandler);
$Jssor$.$SetStyles(_LinkItem, _StyleDef);
$Jssor$.$CssDisplay(_LinkItem, "block");
$Jssor$.$CssOpacity(_LinkItem, 0);
$Jssor$.$Css(_LinkItem, "backgroundColor", "#000");
_ImageItem = $Jssor$.$FindChildByTag(_ImageItem, "IMG");
$JssorDebug$.$Execute(function () {
if (!_ImageItem) {
$JssorDebug$.$Error("slide html code definition error, no 'IMG' found in a 'image with link' slide.\r\n" + elmt.outerHTML);
}
});
}
_ImageItem.border = 0;
$Jssor$.$SetStyles(_ImageItem, _StyleDef);
}
}
RefreshContent(childElement, fresh, level + 1);
});
}
_SelfSlideItem.$OnInnerOffsetChange = function (oldOffset, newOffset) {
var slidePosition = _DisplayPieces - newOffset;
SetPosition(_Wrapper, slidePosition);
//following lines are for future usage, not ready yet
//if (!_IsDragging || !_IsCaptionSliderPlayingWhenDragStart) {
// var _DealWithParallax;
// if (IsCurrentSlideIndex(slideIndex)) {
// if (_CaptionSliderOptions.$PlayOutMode == 2)
// _DealWithParallax = true;
// }
// else {
// if (!_CaptionSliderOptions.$PlayInMode) {
// //PlayInMode: 0 none
// _CaptionSliderIn.$GoToEnd();
// }
// //else if (_CaptionSliderOptions.$PlayInMode == 1) {
// // //PlayInMode: 1 chain
// // _CaptionSliderIn.$GoToBegin();
// //}
// else if (_CaptionSliderOptions.$PlayInMode == 2) {
// //PlayInMode: 2 parallel
// _DealWithParallax = true;
// }
// }
// if (_DealWithParallax) {
// _CaptionSliderIn.$GoToPosition((_CaptionSliderIn.$GetPosition_OuterEnd() - _CaptionSliderIn.$GetPosition_OuterBegin()) * Math.abs(newOffset - 1) * .8 + _CaptionSliderIn.$GetPosition_OuterBegin());
// }
//}
};
_SelfSlideItem.$GetCaptionSliderIn = function () {
return _CaptionSliderIn;
};
_SelfSlideItem.$GetCaptionSliderOut = function () {
return _CaptionSliderOut;
};
_SelfSlideItem.$Index = slideIndex;
$JssorObject$.call(_SelfSlideItem);
//SlideItem Constructor
{
var thumb = $Jssor$.$FindChild(slideElmt, "thumb", true);
if (thumb) {
_SelfSlideItem.$Thumb = $Jssor$.$CloneNode(thumb);
$Jssor$.$RemoveAttribute(thumb, "id");
$Jssor$.$HideElement(thumb);
}
$Jssor$.$ShowElement(slideElmt);
_LoadingScreen = $Jssor$.$CloneNode(_LoadingContainer);
$Jssor$.$CssZIndex(_LoadingScreen, 1000);
//cancel click event on <A> element when a drag of slide succeeded
$Jssor$.$AddEvent(slideElmt, "click", LinkClickEventHandler);
ResetCaptionSlider(true);
_SelfSlideItem.$Image = _ImageItem;
_SelfSlideItem.$Link = _LinkItem;
_SelfSlideItem.$Item = slideElmt;
_SelfSlideItem.$Wrapper = _Wrapper = slideElmt;
$Jssor$.$AppendChild(_Wrapper, _LoadingScreen);
_SelfSlider.$On(203, ParkEventHandler);
_SelfSlider.$On(28, FreezeEventHandler);
_SelfSlider.$On(24, SwipeStartEventHandler);
$JssorDebug$.$Execute(function () {
_SequenceNumber = _SlideItemCreatedCount++;
});
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_Wrapper, "debug-id", "slide-" + slideIndex);
});
}
}
//SlideItem
//Processor
function Processor(slideIndex, slideshowProcessor, captionSliderIn, captionSliderOut) {
var _SelfProcessor = this;
var _ProgressBegin = 0;
var _SlideshowBegin = 0;
var _SlideshowEnd;
var _CaptionInBegin;
var _IdleBegin;
var _IdleEnd;
var _ProgressEnd;
var _IsSlideshowRunning;
var _IsRollingBack;
var _PlayerInstance;
var _IsPlayerOnService;
var slideItem = _SlideItems[slideIndex];
$JssorAnimator$.call(_SelfProcessor, 0, 0);
function UpdateLink() {
$Jssor$.$ClearChildren(_LinkContainer);
if (_ShowLink && _IsSlideshowRunning && slideItem.$Link) {
$Jssor$.$AppendChild(_LinkContainer, slideItem.$Link);
}
$Jssor$.$ShowElement(_LinkContainer, !_IsSlideshowRunning && slideItem.$Image);
}
function ProcessCompleteEventHandler() {
if (_IsRollingBack) {
_IsRollingBack = false;
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_ROLLBACK_END, slideIndex, _IdleEnd, _ProgressBegin, _IdleBegin, _IdleEnd, _ProgressEnd);
_SelfProcessor.$GoToPosition(_IdleBegin);
}
_SelfProcessor.$Replay();
}
function PlayerSwitchEventHandler(isOnService) {
_IsPlayerOnService = isOnService;
_SelfProcessor.$Stop();
_SelfProcessor.$Replay();
}
_SelfProcessor.$Replay = function () {
var currentPosition = _SelfProcessor.$GetPosition_Display();
if (!_IsDragging && !_IsSliding && !_IsPlayerOnService && _CurrentSlideIndex == slideIndex) {
if (!currentPosition) {
if (_SlideshowEnd && !_IsSlideshowRunning) {
_IsSlideshowRunning = true;
_SelfProcessor.$OpenSlideshowPanel(true);
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_SLIDESHOW_START, slideIndex, _ProgressBegin, _SlideshowBegin, _SlideshowEnd, _ProgressEnd);
}
UpdateLink();
}
var toPosition;
var stateEvent = JssorSlider.$EVT_STATE_CHANGE;
if (currentPosition != _ProgressEnd) {
if (currentPosition == _IdleEnd) {
toPosition = _ProgressEnd;
}
else if (currentPosition == _IdleBegin) {
toPosition = _IdleEnd;
}
else if (!currentPosition) {
toPosition = _IdleBegin;
}
else if (currentPosition > _IdleEnd) {
_IsRollingBack = true;
toPosition = _IdleEnd;
stateEvent = JssorSlider.$EVT_ROLLBACK_START;
}
else {
//continue from break (by drag or lock)
toPosition = _SelfProcessor.$GetPlayToPosition();
}
}
_SelfSlider.$TriggerEvent(stateEvent, slideIndex, currentPosition, _ProgressBegin, _IdleBegin, _IdleEnd, _ProgressEnd);
var allowAutoPlay = _AutoPlay && (!_HoverToPause || _HoverStatus);
if (currentPosition == _ProgressEnd) {
allowAutoPlay && slideItem.$GoForNextSlide();
}
else if (allowAutoPlay || currentPosition != _IdleEnd) {
_SelfProcessor.$PlayToPosition(toPosition, ProcessCompleteEventHandler);
}
}
};
_SelfProcessor.$AdjustIdleOnPark = function () {
if (_IdleEnd == _ProgressEnd && _IdleEnd == _SelfProcessor.$GetPosition_Display())
_SelfProcessor.$GoToPosition(_IdleBegin);
};
_SelfProcessor.$Abort = function () {
_SlideshowRunner && _SlideshowRunner.$Index == slideIndex && _SlideshowRunner.$Clear();
var currentPosition = _SelfProcessor.$GetPosition_Display();
if (currentPosition < _ProgressEnd) {
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_STATE_CHANGE, slideIndex, -currentPosition -1, _ProgressBegin, _IdleBegin, _IdleEnd, _ProgressEnd);
}
};
_SelfProcessor.$OpenSlideshowPanel = function (open) {
if (slideshowProcessor) {
$Jssor$.$CssOverflow(_SlideshowPanel, open && slideshowProcessor.$Transition.$Outside ? "" : "hidden");
}
};
_SelfProcessor.$OnInnerOffsetChange = function (oldPosition, newPosition) {
if (_IsSlideshowRunning && newPosition >= _SlideshowEnd) {
_IsSlideshowRunning = false;
UpdateLink();
slideItem.$UnhideContentForSlideshow();
_SlideshowRunner.$Clear();
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_SLIDESHOW_END, slideIndex, _ProgressBegin, _SlideshowBegin, _SlideshowEnd, _ProgressEnd);
}
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_PROGRESS_CHANGE, slideIndex, newPosition, _ProgressBegin, _IdleBegin, _IdleEnd, _ProgressEnd);
};
_SelfProcessor.$SetPlayer = function (playerInstance) {
if (playerInstance && !_PlayerInstance) {
_PlayerInstance = playerInstance;
playerInstance.$On($JssorPlayer$.$EVT_SWITCH, PlayerSwitchEventHandler);
}
};
//Processor Constructor
{
if (slideshowProcessor) {
_SelfProcessor.$Chain(slideshowProcessor);
}
_SlideshowEnd = _SelfProcessor.$GetPosition_OuterEnd();
_CaptionInBegin = _SelfProcessor.$GetPosition_OuterEnd();
_SelfProcessor.$Chain(captionSliderIn);
_IdleBegin = captionSliderIn.$GetPosition_OuterEnd();
_IdleEnd = _IdleBegin + _Options.$AutoPlayInterval;
captionSliderOut.$Shift(_IdleEnd);
_SelfProcessor.$Combine(captionSliderOut);
_ProgressEnd = _SelfProcessor.$GetPosition_OuterEnd();
}
}
//Processor
//private classes
function SetPosition(elmt, position) {
var orientation = _DragOrientation > 0 ? _DragOrientation : _PlayOrientation;
var x = _StepLengthX * position * (orientation & 1);
var y = _StepLengthY * position * ((orientation >> 1) & 1);
if ($Jssor$.$IsBrowserChrome() && $Jssor$.$BrowserVersion() < 38) {
x = x.toFixed(3);
y = y.toFixed(3);
}
else {
x = Math.round(x);
y = Math.round(y);
}
if ($Jssor$.$IsBrowserIE() && $Jssor$.$BrowserVersion() >= 10 && $Jssor$.$BrowserVersion() < 11) {
elmt.style.msTransform = "translate(" + x + "px, " + y + "px)";
}
else if ($Jssor$.$IsBrowserChrome() && $Jssor$.$BrowserVersion() >= 30 && $Jssor$.$BrowserVersion() < 34) {
elmt.style.WebkitTransition = "transform 0s";
elmt.style.WebkitTransform = "translate3d(" + x + "px, " + y + "px, 0px) perspective(2000px)";
}
else {
$Jssor$.$CssLeft(elmt, x);
$Jssor$.$CssTop(elmt, y);
}
}
//Event handling begin
function OnMouseDown(event) {
var tagName = $Jssor$.$EventSrc(event).tagName;
if (!_DragOrientationRegistered && tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT" && RegisterDrag()) {
OnDragStart(event);
}
}
function Freeze() {
_CarouselPlaying_OnFreeze = _IsSliding;
_PlayToPosition_OnFreeze = _CarouselPlayer.$GetPlayToPosition();
_Position_OnFreeze = _Conveyor.$GetPosition();
if (_IsDragging || !_HoverStatus && (_HoverToPause & 12)) {
_CarouselPlayer.$Stop();
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_FREEZE);
}
}
function Unfreeze(byDrag) {
if (!_IsDragging && (_HoverStatus || !(_HoverToPause & 12)) && !_CarouselPlayer.$IsPlaying()) {
var currentPosition = _Conveyor.$GetPosition();
var toPosition = Math.ceil(_Position_OnFreeze);
if (byDrag && Math.abs(_DragOffsetTotal) >= _Options.$MinDragOffsetToSlide) {
toPosition = Math.ceil(currentPosition);
toPosition += _DragIndexAdjust;
}
if (!(_Loop & 1)) {
toPosition = Math.min(_SlideCount - _DisplayPieces, Math.max(toPosition, 0));
}
var t = Math.abs(toPosition - currentPosition);
t = 1 - Math.pow(1 - t, 5);
if (!_LastDragSucceded && _CarouselPlaying_OnFreeze) {
_CarouselPlayer.$Continue(_PlayToPosition_OnFreeze);
}
else if (currentPosition == toPosition) {
_CurrentSlideItem.$EnablePlayer();
_CurrentSlideItem.$TryActivate();
}
else {
_CarouselPlayer.$PlayCarousel(currentPosition, toPosition, t * _SlideDuration);
}
}
}
function OnDragStart(event) {
_IsDragging = true;
_DragInvalid = false;
_LoadingTicket = null;
$Jssor$.$AddEvent(document, _MoveEvent, OnDragMove);
_LastTimeMoveByDrag = $Jssor$.$GetNow() - 50;
_LastDragSucceded = 0;
Freeze();
if (!_CarouselPlaying_OnFreeze)
_DragOrientation = 0;
if (_HandleTouchEventOnly) {
var touchPoint = event.touches[0];
_DragStartMouseX = touchPoint.clientX;
_DragStartMouseY = touchPoint.clientY;
}
else {
var mousePoint = $Jssor$.$MousePosition(event);
_DragStartMouseX = mousePoint.x;
_DragStartMouseY = mousePoint.y;
$Jssor$.$CancelEvent(event);
}
_DragOffsetTotal = 0;
_DragOffsetLastTime = 0;
_DragIndexAdjust = 0;
//Trigger EVT_DRAGSTART
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_DRAG_START, GetRealIndex(_Position_OnFreeze), _Position_OnFreeze, event);
}
function OnDragMove(event) {
if (_IsDragging && (!$Jssor$.$IsBrowserIe9Earlier() || event.button)) {
var actionPoint;
if (_HandleTouchEventOnly) {
var touches = event.touches;
if (touches && touches.length > 0) {
actionPoint = { x: touches[0].clientX, y: touches[0].clientY };
}
}
else {
actionPoint = $Jssor$.$MousePosition(event);
}
if (actionPoint) {
var distanceX = actionPoint.x - _DragStartMouseX;
var distanceY = actionPoint.y - _DragStartMouseY;
if (Math.floor(_Position_OnFreeze) != _Position_OnFreeze)
_DragOrientation = _DragOrientation || (_PlayOrientation & _DragOrientationRegistered);
if ((distanceX || distanceY) && !_DragOrientation) {
if (_DragOrientationRegistered == 3) {
if (Math.abs(distanceY) > Math.abs(distanceX)) {
_DragOrientation = 2;
}
else
_DragOrientation = 1;
}
else {
_DragOrientation = _DragOrientationRegistered;
}
if (_HandleTouchEventOnly && _DragOrientation == 1 && Math.abs(distanceY) - Math.abs(distanceX) > 3) {
_DragInvalid = true;
}
}
if (_DragOrientation) {
var distance = distanceY;
var stepLength = _StepLengthY;
if (_DragOrientation == 1) {
distance = distanceX;
stepLength = _StepLengthX;
}
if (!(_Loop & 1)) {
if (distance > 0) {
var normalDistance = stepLength * _CurrentSlideIndex;
var sqrtDistance = distance - normalDistance;
if (sqrtDistance > 0) {
distance = normalDistance + Math.sqrt(sqrtDistance) * 5;
}
}
if (distance < 0) {
var normalDistance = stepLength * (_SlideCount - _DisplayPieces - _CurrentSlideIndex);
var sqrtDistance = -distance - normalDistance;
if (sqrtDistance > 0) {
distance = -normalDistance - Math.sqrt(sqrtDistance) * 5;
}
}
}
if (_DragOffsetTotal - _DragOffsetLastTime < -2) {
_DragIndexAdjust = 0;
}
else if (_DragOffsetTotal - _DragOffsetLastTime > 2) {
_DragIndexAdjust = -1;
}
_DragOffsetLastTime = _DragOffsetTotal;
_DragOffsetTotal = distance;
_PositionToGoByDrag = _Position_OnFreeze - _DragOffsetTotal / stepLength / (_ScaleRatio || 1);
if (_DragOffsetTotal && _DragOrientation && !_DragInvalid) {
$Jssor$.$CancelEvent(event);
if (!_IsSliding) {
_CarouselPlayer.$StandBy(_PositionToGoByDrag);
}
else
_CarouselPlayer.$SetStandByPosition(_PositionToGoByDrag);
}
else if ($Jssor$.$IsBrowserIe9Earlier()) {
$Jssor$.$CancelEvent(event);
}
}
}
}
else {
OnDragEnd(event);
}
}
function OnDragEnd(event) {
UnregisterDrag();
if (_IsDragging) {
_IsDragging = false;
_LastTimeMoveByDrag = $Jssor$.$GetNow();
$Jssor$.$RemoveEvent(document, _MoveEvent, OnDragMove);
_LastDragSucceded = _DragOffsetTotal;
_LastDragSucceded && $Jssor$.$CancelEvent(event);
_CarouselPlayer.$Stop();
var currentPosition = _Conveyor.$GetPosition();
//Trigger EVT_DRAG_END
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_DRAG_END, GetRealIndex(currentPosition), currentPosition, GetRealIndex(_Position_OnFreeze), _Position_OnFreeze, event);
Unfreeze(true);
Freeze();
}
}
//Event handling end
function SetCurrentSlideIndex(index) {
_PrevSlideItem = _SlideItems[_CurrentSlideIndex];
_PreviousSlideIndex = _CurrentSlideIndex;
_CurrentSlideIndex = GetRealIndex(index);
_CurrentSlideItem = _SlideItems[_CurrentSlideIndex];
ResetNavigator(index);
return _CurrentSlideIndex;
}
function OnPark(slideIndex, prevIndex) {
_DragOrientation = 0;
SetCurrentSlideIndex(slideIndex);
//Trigger EVT_PARK
_SelfSlider.$TriggerEvent(JssorSlider.$EVT_PARK, GetRealIndex(slideIndex), prevIndex);
}
function ResetNavigator(index, temp) {
_TempSlideIndex = index;
$Jssor$.$Each(_Navigators, function (navigator) {
navigator.$SetCurrentIndex(GetRealIndex(index), index, temp);
});
}
function RegisterDrag() {
var dragRegistry = JssorSlider.$DragRegistry || 0;
var dragOrientation = _DragEnabled;
if (_HandleTouchEventOnly)
(dragOrientation & 1) && (dragOrientation &= 1);
JssorSlider.$DragRegistry |= dragOrientation;
return (_DragOrientationRegistered = dragOrientation & ~dragRegistry);
}
function UnregisterDrag() {
if (_DragOrientationRegistered) {
JssorSlider.$DragRegistry &= ~_DragEnabled;
_DragOrientationRegistered = 0;
}
}
function CreatePanel() {
var div = $Jssor$.$CreateDiv();
$Jssor$.$SetStyles(div, _StyleDef);
$Jssor$.$CssPosition(div, "absolute");
return div;
}
function GetRealIndex(index) {
return (index % _SlideCount + _SlideCount) % _SlideCount;
}
function IsCurrentSlideIndex(index) {
return GetRealIndex(index) == _CurrentSlideIndex;
}
function IsPreviousSlideIndex(index) {
return GetRealIndex(index) == _PreviousSlideIndex;
}
//Navigation Request Handler
function NavigationClickHandler(index, relative) {
if (relative) {
if (!_Loop) {
//Stop at threshold
index = Math.min(Math.max(index + _TempSlideIndex, 0), _SlideCount - _DisplayPieces);
relative = false;
}
else if (_Loop & 2) {
//Rewind
index = GetRealIndex(index + _TempSlideIndex);
relative = false;
}
}
PlayTo(index, _Options.$SlideDuration, relative);
}
function ShowNavigators() {
$Jssor$.$Each(_Navigators, function (navigator) {
navigator.$Show(navigator.$Options.$ChanceToShow <= _HoverStatus);
});
}
function MainContainerMouseLeaveEventHandler() {
if (!_HoverStatus) {
//$JssorDebug$.$Log("mouseleave");
_HoverStatus = 1;
ShowNavigators();
if (!_IsDragging) {
(_HoverToPause & 12) && Unfreeze();
(_HoverToPause & 3) && _SlideItems[_CurrentSlideIndex].$TryActivate();
}
}
}
function MainContainerMouseEnterEventHandler() {
if (_HoverStatus) {
//$JssorDebug$.$Log("mouseenter");
_HoverStatus = 0;
ShowNavigators();
_IsDragging || !(_HoverToPause & 12) || Freeze();
}
}
function AdjustSlidesContainerSize() {
_StyleDef = { $Width: _SlideWidth, $Height: _SlideHeight, $Top: 0, $Left: 0 };
$Jssor$.$Each(_SlideElmts, function (slideElmt, i) {
$Jssor$.$SetStyles(slideElmt, _StyleDef);
$Jssor$.$CssPosition(slideElmt, "absolute");
$Jssor$.$CssOverflow(slideElmt, "hidden");
$Jssor$.$HideElement(slideElmt);
});
$Jssor$.$SetStyles(_LoadingContainer, _StyleDef);
}
function PlayToOffset(offset, slideDuration) {
PlayTo(offset, slideDuration, true);
}
function PlayTo(slideIndex, slideDuration, relative) {
/// <summary>
/// PlayTo( slideIndex [, slideDuration] ); //Play slider to position 'slideIndex' within a period calculated base on 'slideDuration'.
/// </summary>
/// <param name="slideIndex" type="Number">
/// slide slideIndex or position will be playing to
/// </param>
/// <param name="slideDuration" type="Number" optional="true">
/// base slide duration in milliseconds to calculate the whole duration to complete this play request.
/// default value is '$SlideDuration' value which is specified when initialize the slider.
/// </param>
/// http://msdn.microsoft.com/en-us/library/vstudio/bb385682.aspx
/// http://msdn.microsoft.com/en-us/library/vstudio/hh542720.aspx
if (_CarouselEnabled && (!_IsDragging || _Options.$NaviQuitDrag)) {
_IsSliding = true;
_IsDragging = false;
_CarouselPlayer.$Stop();
{
//Slide Duration
if (slideDuration == undefined)
slideDuration = _SlideDuration;
var positionDisplay = _Carousel.$GetPosition_Display();
var positionTo = slideIndex;
if (relative) {
positionTo = positionDisplay + slideIndex;
if (slideIndex > 0)
positionTo = Math.ceil(positionTo);
else
positionTo = Math.floor(positionTo);
}
if (!(_Loop & 1)) {
positionTo = GetRealIndex(positionTo);
positionTo = Math.max(0, Math.min(positionTo, _SlideCount - _DisplayPieces));
}
var positionOffset = (positionTo - positionDisplay) % _SlideCount;
positionTo = positionDisplay + positionOffset;
var duration = positionDisplay == positionTo ? 0 : slideDuration * Math.abs(positionOffset);
duration = Math.min(duration, slideDuration * _DisplayPieces * 1.5);
_CarouselPlayer.$PlayCarousel(positionDisplay, positionTo, duration || 1);
}
}
}
//private functions
//member functions
_SelfSlider.$PlayTo = PlayTo;
_SelfSlider.$GoTo = function (slideIndex) {
/// <summary>
/// instance.$GoTo( slideIndex ); //Go to the specifed slide immediately with no play.
/// </summary>
PlayTo(slideIndex, 1);
};
_SelfSlider.$Next = function () {
/// <summary>
/// instance.$Next(); //Play the slider to next slide.
/// </summary>
PlayToOffset(1);
};
_SelfSlider.$Prev = function () {
/// <summary>
/// instance.$Prev(); //Play the slider to previous slide.
/// </summary>
PlayToOffset(-1);
};
_SelfSlider.$Pause = function () {
/// <summary>
/// instance.$Pause(); //Pause the slider, prevent it from auto playing.
/// </summary>
_AutoPlay = false;
};
_SelfSlider.$Play = function () {
/// <summary>
/// instance.$Play(); //Start auto play if the slider is currently paused.
/// </summary>
if (!_AutoPlay) {
_AutoPlay = true;
_SlideItems[_CurrentSlideIndex] && _SlideItems[_CurrentSlideIndex].$TryActivate();
}
};
_SelfSlider.$SetSlideshowTransitions = function (transitions) {
/// <summary>
/// instance.$SetSlideshowTransitions( transitions ); //Reset slideshow transitions for the slider.
/// </summary>
$JssorDebug$.$Execute(function () {
if (!transitions || !transitions.length) {
$JssorDebug$.$Error("Can not set slideshow transitions, no transitions specified.");
}
});
$Jssor$.$TranslateTransitions(transitions); //for old transition compatibility
_Options.$SlideshowOptions.$Transitions = transitions;
};
_SelfSlider.$SetCaptionTransitions = function (transitions) {
/// <summary>
/// instance.$SetCaptionTransitions( transitions ); //Reset caption transitions for the slider.
/// </summary>
$JssorDebug$.$Execute(function () {
if (!transitions || !transitions.length) {
$JssorDebug$.$Error("Can not set caption transitions, no transitions specified");
}
});
$Jssor$.$TranslateTransitions(transitions); //for old transition compatibility
_CaptionSliderOptions.$CaptionTransitions = transitions;
_CaptionSliderOptions.$Version = $Jssor$.$GetNow();
};
_SelfSlider.$SlidesCount = function () {
/// <summary>
/// instance.$SlidesCount(); //Retrieve slides count of the slider.
/// </summary>
return _SlideElmts.length;
};
_SelfSlider.$CurrentIndex = function () {
/// <summary>
/// instance.$CurrentIndex(); //Retrieve current slide index of the slider.
/// </summary>
return _CurrentSlideIndex;
};
_SelfSlider.$IsAutoPlaying = function () {
/// <summary>
/// instance.$IsAutoPlaying(); //Retrieve auto play status of the slider.
/// </summary>
return _AutoPlay;
};
_SelfSlider.$IsDragging = function () {
/// <summary>
/// instance.$IsDragging(); //Retrieve drag status of the slider.
/// </summary>
return _IsDragging;
};
_SelfSlider.$IsSliding = function () {
/// <summary>
/// instance.$IsSliding(); //Retrieve right<-->left sliding status of the slider.
/// </summary>
return _IsSliding;
};
_SelfSlider.$IsMouseOver = function () {
/// <summary>
/// instance.$IsMouseOver(); //Retrieve mouse over status of the slider.
/// </summary>
return !_HoverStatus;
};
_SelfSlider.$LastDragSucceded = function () {
/// <summary>
/// instance.$IsLastDragSucceded(); //Retrieve last drag succeded status, returns 0 if failed, returns drag offset if succeded
/// </summary>
return _LastDragSucceded;
};
function OriginalWidth() {
/// <summary>
/// instance.$OriginalWidth(); //Retrieve original width of the slider.
/// </summary>
return $Jssor$.$CssWidth(_ScaleWrapper || elmt);
}
function OriginalHeight() {
/// <summary>
/// instance.$OriginalHeight(); //Retrieve original height of the slider.
/// </summary>
return $Jssor$.$CssHeight(_ScaleWrapper || elmt);
}
_SelfSlider.$OriginalWidth = _SelfSlider.$GetOriginalWidth = OriginalWidth;
_SelfSlider.$OriginalHeight = _SelfSlider.$GetOriginalHeight = OriginalHeight;
function Scale(dimension, isHeight) {
/// <summary>
/// instance.$ScaleWidth(); //Retrieve scaled dimension the slider currently displays.
/// instance.$ScaleWidth( dimension ); //Scale the slider to new width and keep aspect ratio.
/// </summary>
if (dimension == undefined)
return $Jssor$.$CssWidth(elmt);
$JssorDebug$.$Execute(function () {
if (!dimension || dimension < 0) {
$JssorDebug$.$Fail("'$ScaleWidth' error, 'dimension' should be positive value.");
}
});
if (!_ScaleWrapper) {
$JssorDebug$.$Execute(function () {
var originalWidthStr = $Jssor$.$Css(elmt, "width");
var originalHeightStr = $Jssor$.$Css(elmt, "height");
var originalWidth = $Jssor$.$CssP(elmt, "width");
var originalHeight = $Jssor$.$CssP(elmt, "height");
if (!originalWidthStr) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'dimension' of 'outer container' not specified. Please specify 'dimension' in pixel. e.g. 'dimension: 600px;'");
}
if (!originalHeightStr) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'height' of 'outer container' not specified. Please specify 'height' in pixel. e.g. 'height: 300px;'");
}
if (originalWidthStr.indexOf('%') != -1) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'dimension' of 'outer container' not valid. Please specify 'dimension' in pixel. e.g. 'dimension: 600px;'");
}
if (originalHeightStr.indexOf('%') != -1) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'height' of 'outer container' not valid. Please specify 'height' in pixel. e.g. 'height: 300px;'");
}
if (!originalWidth) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'dimension' of 'outer container' not valid. 'dimension' of 'outer container' should be positive number. e.g. 'dimension: 600px;'");
}
if (!originalHeight) {
$JssorDebug$.$Fail("Cannot scale jssor slider, 'height' of 'outer container' not valid. 'height' of 'outer container' should be positive number. e.g. 'height: 300px;'");
}
});
var innerWrapper = $Jssor$.$CreateDiv(document);
$Jssor$.$CssCssText(innerWrapper, $Jssor$.$CssCssText(elmt));
$Jssor$.$ClassName(innerWrapper, $Jssor$.$ClassName(elmt));
$Jssor$.$CssPosition(innerWrapper, "relative");
$Jssor$.$CssTop(innerWrapper, 0);
$Jssor$.$CssLeft(innerWrapper, 0);
$Jssor$.$CssOverflow(innerWrapper, "visible");
_ScaleWrapper = $Jssor$.$CreateDiv(document);
$Jssor$.$CssPosition(_ScaleWrapper, "absolute");
$Jssor$.$CssTop(_ScaleWrapper, 0);
$Jssor$.$CssLeft(_ScaleWrapper, 0);
$Jssor$.$CssWidth(_ScaleWrapper, $Jssor$.$CssWidth(elmt));
$Jssor$.$CssHeight(_ScaleWrapper, $Jssor$.$CssHeight(elmt));
$Jssor$.$SetStyleTransformOrigin(_ScaleWrapper, "0 0");
$Jssor$.$AppendChild(_ScaleWrapper, innerWrapper);
var children = $Jssor$.$Children(elmt);
$Jssor$.$AppendChild(elmt, _ScaleWrapper);
$Jssor$.$Css(elmt, "backgroundImage", "");
var noMoveElmts = {
"navigator": _BulletNavigatorOptions && _BulletNavigatorOptions.$Scale == false,
"arrowleft": _ArrowNavigatorOptions && _ArrowNavigatorOptions.$Scale == false,
"arrowright": _ArrowNavigatorOptions && _ArrowNavigatorOptions.$Scale == false,
"thumbnavigator": _ThumbnailNavigatorOptions && _ThumbnailNavigatorOptions.$Scale == false,
"thumbwrapper": _ThumbnailNavigatorOptions && _ThumbnailNavigatorOptions.$Scale == false
};
$Jssor$.$Each(children, function (child) {
$Jssor$.$AppendChild(noMoveElmts[$Jssor$.$AttributeEx(child, "u")] ? elmt : innerWrapper, child);
});
$Jssor$.$ShowElement(innerWrapper);
$Jssor$.$ShowElement(_ScaleWrapper);
}
$JssorDebug$.$Execute(function () {
if (!_InitialScrollWidth) {
_InitialScrollWidth = _SelfSlider.$Elmt.scrollWidth;
}
});
_ScaleRatio = dimension / (isHeight? $Jssor$.$CssHeight : $Jssor$.$CssWidth)(_ScaleWrapper);
$Jssor$.$CssScale(_ScaleWrapper, _ScaleRatio);
$Jssor$.$CssWidth(elmt, isHeight ? (_ScaleRatio * OriginalWidth()) : dimension);
$Jssor$.$CssHeight(elmt, isHeight ? dimension : (_ScaleRatio * OriginalHeight()));
$Jssor$.$Each(_Navigators, function (navigator) {
navigator.$Relocate();
});
}
_SelfSlider.$ScaleHeight = _SelfSlider.$GetScaleHeight = function (height) {
/// <summary>
/// instance.$ScaleHeight(); //Retrieve scaled height the slider currently displays.
/// instance.$ScaleHeight( dimension ); //Scale the slider to new height and keep aspect ratio.
/// </summary>
if (height == undefined)
return $Jssor$.$CssHeight(elmt);
Scale(height, true);
};
_SelfSlider.$ScaleWidth = _SelfSlider.$SetScaleWidth = _SelfSlider.$GetScaleWidth = Scale;
_SelfSlider.$GetVirtualIndex = function (index) {
var parkingIndex = Math.ceil(GetRealIndex(_ParkingPosition / _StepLength));
var displayIndex = GetRealIndex(index - _CurrentSlideIndex + parkingIndex);
if (displayIndex > _DisplayPieces) {
if (index - _CurrentSlideIndex > _SlideCount / 2)
index -= _SlideCount;
else if (index - _CurrentSlideIndex <= -_SlideCount / 2)
index += _SlideCount;
}
else {
index = _CurrentSlideIndex + displayIndex - parkingIndex;
}
return index;
};
//member functions
$JssorObject$.call(_SelfSlider);
$JssorDebug$.$Execute(function () {
var outerContainerElmt = $Jssor$.$GetElement(elmt);
if (!outerContainerElmt)
$JssorDebug$.$Fail("Outer container '" + elmt + "' not found.");
});
//initialize member variables
_SelfSlider.$Elmt = elmt = $Jssor$.$GetElement(elmt);
//initialize member variables
var _InitialScrollWidth; //for debug only
var _CaptionSliderCount = 1; //for debug only
var _Options = $Jssor$.$Extend({
$FillMode: 0, //[Optional] The way to fill image in slide, 0 stretch, 1 contain (keep aspect ratio and put all inside slide), 2 cover (keep aspect ratio and cover whole slide), 4 actual size, 5 contain for large image, actual size for small image, default value is 0
$LazyLoading: 1, //[Optional] For image with lazy loading format (<IMG src2="url" .../>), by default it will be loaded only when the slide comes.
//But an integer value (maybe 0, 1, 2 or 3) indicates that how far of nearby slides should be loaded immediately as well, default value is 1.
$StartIndex: 0, //[Optional] Index of slide to display when initialize, default value is 0
$AutoPlay: false, //[Optional] Whether to auto play, default value is false
$Loop: 1, //[Optional] Enable loop(circular) of carousel or not, 0: stop, 1: loop, 2 rewind, default value is 1
$HWA: true, //[Optional] Enable hardware acceleration or not, default value is true
$NaviQuitDrag: true,
$AutoPlaySteps: 1, //[Optional] Steps to go of every play (this options applys only when slideshow disabled), default value is 1
$AutoPlayInterval: 3000, //[Optional] Interval to play next slide since the previous stopped if a slideshow is auto playing, default value is 3000
$PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1
$SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 400
$SlideEasing: $JssorEasing$.$EaseOutQuad, //[Optional] Specifies easing for right to left animation, default value is $JssorEasing$.$EaseOutQuad
$MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset that trigger slide, default value is 20
$SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is recursive) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc.
$PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1
$DragOrientation: 1 //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 both, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
}, options);
//Sodo statement for development time intellisence only
$JssorDebug$.$Execute(function () {
_Options = $Jssor$.$Extend({
$ArrowKeyNavigation: undefined,
$SlideWidth: undefined,
$SlideHeight: undefined,
$SlideshowOptions: undefined,
$CaptionSliderOptions: undefined,
$BulletNavigatorOptions: undefined,
$ArrowNavigatorOptions: undefined,
$ThumbnailNavigatorOptions: undefined
},
_Options);
});
var _PlayOrientation = _Options.$PlayOrientation & 3;
var _PlayReverse = (_Options.$PlayOrientation & 4) / -4 || 1;
var _SlideshowOptions = _Options.$SlideshowOptions;
var _CaptionSliderOptions = $Jssor$.$Extend({ $Class: $JssorCaptionSliderBase$, $PlayInMode: 1, $PlayOutMode: 1 }, _Options.$CaptionSliderOptions);
$Jssor$.$TranslateTransitions(_CaptionSliderOptions.$CaptionTransitions); //for old transition compatibility
var _BulletNavigatorOptions = _Options.$BulletNavigatorOptions;
var _ArrowNavigatorOptions = _Options.$ArrowNavigatorOptions;
var _ThumbnailNavigatorOptions = _Options.$ThumbnailNavigatorOptions;
$JssorDebug$.$Execute(function () {
if (_SlideshowOptions && !_SlideshowOptions.$Class) {
$JssorDebug$.$Fail("Option $SlideshowOptions error, class not specified.");
}
});
$JssorDebug$.$Execute(function () {
if (_Options.$CaptionSliderOptions && !_Options.$CaptionSliderOptions.$Class) {
$JssorDebug$.$Fail("Option $CaptionSliderOptions error, class not specified.");
}
});
$JssorDebug$.$Execute(function () {
if (_BulletNavigatorOptions && !_BulletNavigatorOptions.$Class) {
$JssorDebug$.$Fail("Option $BulletNavigatorOptions error, class not specified.");
}
});
$JssorDebug$.$Execute(function () {
if (_ArrowNavigatorOptions && !_ArrowNavigatorOptions.$Class) {
$JssorDebug$.$Fail("Option $ArrowNavigatorOptions error, class not specified.");
}
});
$JssorDebug$.$Execute(function () {
if (_ThumbnailNavigatorOptions && !_ThumbnailNavigatorOptions.$Class) {
$JssorDebug$.$Fail("Option $ThumbnailNavigatorOptions error, class not specified.");
}
});
var _UISearchNoDeep = !_Options.$UISearchMode;
var _ScaleWrapper;
var _SlidesContainer = $Jssor$.$FindChild(elmt, "slides", _UISearchNoDeep);
var _LoadingContainer = $Jssor$.$FindChild(elmt, "loading", _UISearchNoDeep) || $Jssor$.$CreateDiv(document);
var _BulletNavigatorContainer = $Jssor$.$FindChild(elmt, "navigator", _UISearchNoDeep);
var _ArrowLeft = $Jssor$.$FindChild(elmt, "arrowleft", _UISearchNoDeep);
var _ArrowRight = $Jssor$.$FindChild(elmt, "arrowright", _UISearchNoDeep);
var _ThumbnailNavigatorContainer = $Jssor$.$FindChild(elmt, "thumbnavigator", _UISearchNoDeep);
$JssorDebug$.$Execute(function () {
//if (_BulletNavigatorOptions && !_BulletNavigatorContainer) {
// throw new Error("$BulletNavigatorOptions specified but bullet navigator container (<div u=\"navigator\" ...) not defined.");
//}
if (_BulletNavigatorContainer && !_BulletNavigatorOptions) {
throw new Error("Bullet navigator container defined but $BulletNavigatorOptions not specified.");
}
//if (_ArrowNavigatorOptions) {
// if (!_ArrowLeft) {
// throw new Error("$ArrowNavigatorOptions specified, but arrowleft (<span u=\"arrowleft\" ...) not defined.");
// }
// if (!_ArrowRight) {
// throw new Error("$ArrowNavigatorOptions specified, but arrowright (<span u=\"arrowright\" ...) not defined.");
// }
//}
if ((_ArrowLeft || _ArrowRight) && !_ArrowNavigatorOptions) {
throw new Error("arrowleft or arrowright defined, but $ArrowNavigatorOptions not specified.");
}
//if (_ThumbnailNavigatorOptions && !_ThumbnailNavigatorContainer) {
// throw new Error("$ThumbnailNavigatorOptions specified, but thumbnail navigator container (<div u=\"thumbnavigator\" ...) not defined.");
//}
if (_ThumbnailNavigatorContainer && !_ThumbnailNavigatorOptions) {
throw new Error("Thumbnail navigator container defined, but $ThumbnailNavigatorOptions not specified.");
}
});
var _SlidesContainerWidth = $Jssor$.$CssWidth(_SlidesContainer);
var _SlidesContainerHeight = $Jssor$.$CssHeight(_SlidesContainer);
$JssorDebug$.$Execute(function () {
if (isNaN(_SlidesContainerWidth))
$JssorDebug$.$Fail("Width of slides container wrong specification, it should be specified in pixel (like style='width: 600px;').");
if (_SlidesContainerWidth == undefined)
$JssorDebug$.$Fail("Width of slides container not specified, it should be specified in pixel (like style='width: 600px;').");
if (isNaN(_SlidesContainerHeight))
$JssorDebug$.$Fail("Height of slides container wrong specification, it should be specified in pixel (like style='height: 300px;').");
if (_SlidesContainerHeight == undefined)
$JssorDebug$.$Fail("Height of slides container not specified, it should be specified in pixel (like style='height: 300px;').");
var slidesContainerOverflow = $Jssor$.$CssOverflow(_SlidesContainer);
var slidesContainerOverflowX = $Jssor$.$Css(_SlidesContainer, "overflowX");
var slidesContainerOverflowY = $Jssor$.$Css(_SlidesContainer, "overflowY");
if (slidesContainerOverflow != "hidden" && (slidesContainerOverflowX != "hidden" || slidesContainerOverflowY != "hidden"))
$JssorDebug$.$Fail("Overflow of slides container wrong specification, it should be specified as 'hidden' (style='overflow:hidden;').");
//var slidesContainerTop = $Jssor$.$CssTop(_SlidesContainer);
//var slidesContainerLeft = $Jssor$.$CssLeft(_SlidesContainer);
//if (isNaN(slidesContainerTop))
// $JssorDebug$.$Fail("Top of slides container wrong specification, it should be specified in pixel (like style='top: 0px;').");
//if (slidesContainerTop == undefined)
// $JssorDebug$.$Fail("Top of slides container not specified, it should be specified in pixel (like style='top: 0px;').");
//if (isNaN(slidesContainerLeft))
// $JssorDebug$.$Fail("Left of slides container wrong specification, it should be specified in pixel (like style='left: 0px;').");
//if (slidesContainerLeft == undefined)
// $JssorDebug$.$Fail("Left of slides container not specified, it should be specified in pixel (like style='left: 0px;').");
});
$JssorDebug$.$Execute(function () {
if (!$Jssor$.$IsNumeric(_Options.$DisplayPieces))
$JssorDebug$.$Fail("Option $DisplayPieces error, it should be a numeric value and greater than or equal to 1.");
if (_Options.$DisplayPieces < 1)
$JssorDebug$.$Fail("Option $DisplayPieces error, it should be greater than or equal to 1.");
if (_Options.$DisplayPieces > 1 && _Options.$DragOrientation && _Options.$DragOrientation != _PlayOrientation)
$JssorDebug$.$Fail("Option $DragOrientation error, it should be 0 or the same of $PlayOrientation when $DisplayPieces is greater than 1.");
if (!$Jssor$.$IsNumeric(_Options.$ParkingPosition))
$JssorDebug$.$Fail("Option $ParkingPosition error, it should be a numeric value.");
if (_Options.$ParkingPosition && _Options.$DragOrientation && _Options.$DragOrientation != _PlayOrientation)
$JssorDebug$.$Fail("Option $DragOrientation error, it should be 0 or the same of $PlayOrientation when $ParkingPosition is not equal to 0.");
});
var _StyleDef;
var _SlideElmts = [];
{
var slideElmts = $Jssor$.$Children(_SlidesContainer);
$Jssor$.$Each(slideElmts, function (slideElmt) {
if (slideElmt.tagName == "DIV" && !$Jssor$.$AttributeEx(slideElmt, "u")) {
_SlideElmts.push(slideElmt);
}
});
}
$JssorDebug$.$Execute(function () {
if (_SlideElmts.length < 1) {
$JssorDebug$.$Error("Slides html code definition error, there must be at least 1 slide to initialize a slider.");
}
});
var _SlideItemCreatedCount = 0; //for debug only
var _SlideItemReleasedCount = 0; //for debug only
var _PreviousSlideIndex;
var _CurrentSlideIndex = -1;
var _TempSlideIndex;
var _PrevSlideItem;
var _CurrentSlideItem;
var _SlideCount = _SlideElmts.length;
var _SlideWidth = _Options.$SlideWidth || _SlidesContainerWidth;
var _SlideHeight = _Options.$SlideHeight || _SlidesContainerHeight;
var _SlideSpacing = _Options.$SlideSpacing;
var _StepLengthX = _SlideWidth + _SlideSpacing;
var _StepLengthY = _SlideHeight + _SlideSpacing;
var _StepLength = (_PlayOrientation & 1) ? _StepLengthX : _StepLengthY;
var _DisplayPieces = Math.min(_Options.$DisplayPieces, _SlideCount);
var _SlideshowPanel;
var _CurrentBoardIndex = 0;
var _DragOrientation;
var _DragOrientationRegistered;
var _DragInvalid;
var _HandleTouchEventOnly;
var _Navigators = [];
var _BulletNavigator;
var _ArrowNavigator;
var _ThumbnailNavigator;
var _ShowLink;
var _Frozen;
var _AutoPlay;
var _AutoPlaySteps = _Options.$AutoPlaySteps;
var _HoverToPause = _Options.$PauseOnHover;
var _AutoPlayInterval = _Options.$AutoPlayInterval;
var _SlideDuration = _Options.$SlideDuration;
var _SlideshowRunnerClass;
var _TransitionsOrder;
var _SlideshowEnabled;
var _ParkingPosition;
var _CarouselEnabled = _DisplayPieces < _SlideCount;
var _Loop = _CarouselEnabled ? _Options.$Loop : 0;
var _DragEnabled;
var _LastDragSucceded;
var _HoverStatus = 1; //0 Hovering, 1 Not hovering
//Variable Definition
var _IsSliding;
var _IsDragging;
var _LoadingTicket;
//The X position of mouse/touch when a drag start
var _DragStartMouseX = 0;
//The Y position of mouse/touch when a drag start
var _DragStartMouseY = 0;
var _DragOffsetTotal;
var _DragOffsetLastTime;
var _DragIndexAdjust;
var _Carousel;
var _Conveyor;
var _Slideshow;
var _CarouselPlayer;
var _SlideContainer = new SlideContainer();
var _ScaleRatio;
//$JssorSlider$ Constructor
{
_AutoPlay = _Options.$AutoPlay;
_SelfSlider.$Options = options;
AdjustSlidesContainerSize();
elmt["jssor-slider"] = true;
//_SlideshowPanel = CreatePanel();
//$Jssor$.$CssZIndex(elmt, $Jssor$.$CssZIndex(elmt));
//$Jssor$.$CssLeft(_SlideshowPanel, $Jssor$.$CssLeft(_SlidesContainer));
//$Jssor$.$CssZIndex(_SlidesContainer, $Jssor$.$CssZIndex(_SlidesContainer));
//$Jssor$.$CssTop(_SlideshowPanel, $Jssor$.$CssTop(_SlidesContainer));
$Jssor$.$CssZIndex(_SlidesContainer, $Jssor$.$CssZIndex(_SlidesContainer) || 0);
$Jssor$.$CssPosition(_SlidesContainer, "absolute");
_SlideshowPanel = $Jssor$.$CloneNode(_SlidesContainer);
$Jssor$.$InsertBefore($Jssor$.$ParentNode(_SlidesContainer), _SlideshowPanel, _SlidesContainer);
if (_SlideshowOptions) {
_ShowLink = _SlideshowOptions.$ShowLink;
_SlideshowRunnerClass = _SlideshowOptions.$Class;
$JssorDebug$.$Execute(function () {
if (!_SlideshowOptions.$Transitions || !_SlideshowOptions.$Transitions.length) {
$JssorDebug$.$Error("Invalid '$SlideshowOptions', no '$Transitions' specified.");
}
});
$Jssor$.$TranslateTransitions(_SlideshowOptions.$Transitions); //for old transition compatibility
_SlideshowEnabled = _DisplayPieces == 1 && _SlideCount > 1 && _SlideshowRunnerClass && (!$Jssor$.$IsBrowserIE() || $Jssor$.$BrowserVersion() >= 8);
}
_ParkingPosition = (_SlideshowEnabled || _DisplayPieces >= _SlideCount || !(_Loop & 1)) ? 0 : _Options.$ParkingPosition;
_DragEnabled = ((_DisplayPieces > 1 || _ParkingPosition) ? _PlayOrientation : -1) & _Options.$DragOrientation;
//SlideBoard
var _SlideboardElmt = _SlidesContainer;
var _SlideItems = [];
var _SlideshowRunner;
var _LinkContainer;
var _DownEvent = "mousedown";
var _MoveEvent = "mousemove";
var _UpEvent = "mouseup";
var _CancelEvent;
var _LastTimeMoveByDrag;
var _Position_OnFreeze;
var _CarouselPlaying_OnFreeze;
var _PlayToPosition_OnFreeze;
var _PositionToGoByDrag;
//SlideBoard Constructor
{
var msPrefix;
if (window.navigator.pointerEnabled || (msPrefix = window.navigator.msPointerEnabled)) {
_DownEvent = msPrefix ? "MSPointerDown" : "pointerdown";
_MoveEvent = msPrefix ? "MSPointerMove" : "pointermove";
_UpEvent = msPrefix ? "MSPointerUp" : "pointerup";
_CancelEvent = msPrefix ? "MSPointerCancel" : "pointercancel";
if (_DragEnabled) {
var touchAction = "none";
if (_DragEnabled == 1) {
touchAction = "pan-y";
}
else if (_DragEnabled == 2) {
touchAction = "pan-x";
}
$Jssor$.$Css(_SlideboardElmt, msPrefix ? "msTouchAction" : "touchAction", touchAction);
}
}
else if ("ontouchstart" in window || "createTouch" in document) {
_HandleTouchEventOnly = true;
_DownEvent = "touchstart";
_MoveEvent = "touchmove";
_UpEvent = "touchend";
_CancelEvent = "touchcancel";
}
_Slideshow = new Slideshow();
if (_SlideshowEnabled)
_SlideshowRunner = new _SlideshowRunnerClass(_SlideContainer, _SlideWidth, _SlideHeight, _SlideshowOptions, _HandleTouchEventOnly);
$Jssor$.$AppendChild(_SlideshowPanel, _Slideshow.$Wrapper);
$Jssor$.$CssOverflow(_SlidesContainer, "hidden");
//link container
{
_LinkContainer = CreatePanel();
$Jssor$.$Css(_LinkContainer, "backgroundColor", "#000");
$Jssor$.$CssOpacity(_LinkContainer, 0);
$Jssor$.$InsertBefore(_SlideboardElmt, _LinkContainer, _SlideboardElmt.firstChild);
}
for (var i = 0; i < _SlideElmts.length; i++) {
var slideElmt = _SlideElmts[i];
var slideItem = new SlideItem(slideElmt, i);
_SlideItems.push(slideItem);
}
$Jssor$.$HideElement(_LoadingContainer);
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_LoadingContainer, "debug-id", "loading-container");
});
_Carousel = new Carousel()
_CarouselPlayer = new CarouselPlayer(_Carousel, _Slideshow);
$JssorDebug$.$Execute(function () {
$Jssor$.$Attribute(_SlideboardElmt, "debug-id", "slide-board");
});
if (_DragEnabled) {
$Jssor$.$AddEvent(_SlidesContainer, _DownEvent, OnMouseDown);
$Jssor$.$AddEvent(document, _UpEvent, OnDragEnd);
_CancelEvent && $Jssor$.$AddEvent(document, _CancelEvent, OnDragEnd);
}
}
//SlideBoard
_HoverToPause &= (_HandleTouchEventOnly ? 10 : 5);
//Bullet Navigator
if (_BulletNavigatorContainer && _BulletNavigatorOptions) {
_BulletNavigator = new _BulletNavigatorOptions.$Class(_BulletNavigatorContainer, _BulletNavigatorOptions, OriginalWidth(), OriginalHeight());
_Navigators.push(_BulletNavigator);
}
//Arrow Navigator
if (_ArrowNavigatorOptions && _ArrowLeft && _ArrowRight) {
_ArrowNavigator = new _ArrowNavigatorOptions.$Class(_ArrowLeft, _ArrowRight, _ArrowNavigatorOptions, OriginalWidth(), OriginalHeight());
_Navigators.push(_ArrowNavigator);
}
//Thumbnail Navigator
if (_ThumbnailNavigatorContainer && _ThumbnailNavigatorOptions) {
_ThumbnailNavigatorOptions.$StartIndex = _Options.$StartIndex;
_ThumbnailNavigator = new _ThumbnailNavigatorOptions.$Class(_ThumbnailNavigatorContainer, _ThumbnailNavigatorOptions);
_Navigators.push(_ThumbnailNavigator);
}
$Jssor$.$Each(_Navigators, function (navigator) {
navigator.$Reset(_SlideCount, _SlideItems, _LoadingContainer);
navigator.$On($JssorNavigatorEvents$.$NAVIGATIONREQUEST, NavigationClickHandler);
});
Scale(OriginalWidth());
$Jssor$.$AddEvent(elmt, "mouseout", $Jssor$.$MouseOverOutFilter(MainContainerMouseLeaveEventHandler, elmt));
$Jssor$.$AddEvent(elmt, "mouseover", $Jssor$.$MouseOverOutFilter(MainContainerMouseEnterEventHandler, elmt));
ShowNavigators();
//Keyboard Navigation
if (_Options.$ArrowKeyNavigation) {
$Jssor$.$AddEvent(document, "keydown", function (e) {
if (e.keyCode == $JssorKeyCode$.$LEFT) {
//Arrow Left
PlayToOffset(-1);
}
else if (e.keyCode == $JssorKeyCode$.$RIGHT) {
//Arrow Right
PlayToOffset(1);
}
});
}
var startPosition = _Options.$StartIndex;
if (!(_Loop & 1)) {
startPosition = Math.max(0, Math.min(startPosition, _SlideCount - _DisplayPieces));
}
_CarouselPlayer.$PlayCarousel(startPosition, startPosition, 0);
}
}
//Jssor Slider
//JssorSlider.$ASSEMBLY_BOTTOM_LEFT = ASSEMBLY_BOTTOM_LEFT;
//JssorSlider.$ASSEMBLY_BOTTOM_RIGHT = ASSEMBLY_BOTTOM_RIGHT;
//JssorSlider.$ASSEMBLY_TOP_LEFT = ASSEMBLY_TOP_LEFT;
//JssorSlider.$ASSEMBLY_TOP_RIGHT = ASSEMBLY_TOP_RIGHT;
//JssorSlider.$ASSEMBLY_LEFT_TOP = ASSEMBLY_LEFT_TOP;
//JssorSlider.$ASSEMBLY_LEFT_BOTTOM = ASSEMBLY_LEFT_BOTTOM;
//JssorSlider.$ASSEMBLY_RIGHT_TOP = ASSEMBLY_RIGHT_TOP;
//JssorSlider.$ASSEMBLY_RIGHT_BOTTOM = ASSEMBLY_RIGHT_BOTTOM;
JssorSlider.$EVT_CLICK = 21;
JssorSlider.$EVT_DRAG_START = 22;
JssorSlider.$EVT_DRAG_END = 23;
JssorSlider.$EVT_SWIPE_START = 24;
JssorSlider.$EVT_SWIPE_END = 25;
JssorSlider.$EVT_LOAD_START = 26;
JssorSlider.$EVT_LOAD_END = 27;
JssorSlider.$EVT_FREEZE = 28;
JssorSlider.$EVT_POSITION_CHANGE = 202;
JssorSlider.$EVT_PARK = 203;
JssorSlider.$EVT_SLIDESHOW_START = 206;
JssorSlider.$EVT_SLIDESHOW_END = 207;
JssorSlider.$EVT_PROGRESS_CHANGE = 208;
JssorSlider.$EVT_STATE_CHANGE = 209;
JssorSlider.$EVT_ROLLBACK_START = 210;
JssorSlider.$EVT_ROLLBACK_END = 211;
window.$JssorSlider$ = $JssorSlider$ = JssorSlider;
//(function ($) {
// jQuery.fn.jssorSlider = function (options) {
// return this.each(function () {
// return $(this).data('jssorSlider') || $(this).data('jssorSlider', new JssorSlider(this, options));
// });
// };
//})(jQuery);
//window.jQuery && (jQuery.fn.jssorSlider = function (options) {
// return this.each(function () {
// return jQuery(this).data('jssorSlider') || jQuery(this).data('jssorSlider', new JssorSlider(this, options));
// });
//});
};
//$JssorBulletNavigator$
var $JssorNavigatorEvents$ = {
$NAVIGATIONREQUEST: 1,
$INDEXCHANGE: 2,
$RESET: 3
};
var $JssorBulletNavigator$ = window.$JssorBulletNavigator$ = function (elmt, options, containerWidth, containerHeight) {
var self = this;
$JssorObject$.call(self);
elmt = $Jssor$.$GetElement(elmt);
var _Count;
var _Length;
var _Width;
var _Height;
var _CurrentIndex;
var _CurrentInnerIndex = 0;
var _Options;
var _Steps;
var _Lanes;
var _SpacingX;
var _SpacingY;
var _Orientation;
var _ItemPrototype;
var _PrototypeWidth;
var _PrototypeHeight;
var _ButtonElements = [];
var _Buttons = [];
function Highlight(index) {
if (index != -1)
_Buttons[index].$Activate(index == _CurrentInnerIndex);
}
function OnNavigationRequest(index) {
self.$TriggerEvent($JssorNavigatorEvents$.$NAVIGATIONREQUEST, index * _Steps);
}
self.$Elmt = elmt;
self.$GetCurrentIndex = function () {
return _CurrentIndex;
};
self.$SetCurrentIndex = function (index) {
if (index != _CurrentIndex) {
var lastInnerIndex = _CurrentInnerIndex;
var innerIndex = Math.floor(index / _Steps);
_CurrentInnerIndex = innerIndex;
_CurrentIndex = index;
Highlight(lastInnerIndex);
Highlight(innerIndex);
//self.$TriggerEvent($JssorNavigatorEvents$.$INDEXCHANGE, index);
}
};
self.$Show = function (hide) {
$Jssor$.$ShowElement(elmt, hide);
};
var _Located;
self.$Relocate = function (force) {
if (!_Located || _Options.$Scale == false) {
if (_Options.$AutoCenter & 1) {
$Jssor$.$CssLeft(elmt, (containerWidth - _Width) / 2);
}
if (_Options.$AutoCenter & 2) {
$Jssor$.$CssTop(elmt, (containerHeight - _Height) / 2);
}
_Located = true;
}
};
var _Initialized;
self.$Reset = function (length) {
if (!_Initialized) {
_Length = length;
_Count = Math.ceil(length / _Steps);
_CurrentInnerIndex = 0;
var itemOffsetX = _PrototypeWidth + _SpacingX;
var itemOffsetY = _PrototypeHeight + _SpacingY;
var maxIndex = Math.ceil(_Count / _Lanes) - 1;
_Width = _PrototypeWidth + itemOffsetX * (!_Orientation ? maxIndex : _Lanes - 1);
_Height = _PrototypeHeight + itemOffsetY * (_Orientation ? maxIndex : _Lanes - 1);
$Jssor$.$CssWidth(elmt, _Width);
$Jssor$.$CssHeight(elmt, _Height);
//self.$Relocate(true);
for (var buttonIndex = 0; buttonIndex < _Count; buttonIndex++) {
var numberDiv = $Jssor$.$CreateSpan();
$Jssor$.$InnerText(numberDiv, buttonIndex + 1);
var div = $Jssor$.$BuildElement(_ItemPrototype, "NumberTemplate", numberDiv, true);
$Jssor$.$CssPosition(div, "absolute");
var columnIndex = buttonIndex % (maxIndex + 1);
$Jssor$.$CssLeft(div, !_Orientation ? itemOffsetX * columnIndex : buttonIndex % _Lanes * itemOffsetX);
$Jssor$.$CssTop(div, _Orientation ? itemOffsetY * columnIndex : Math.floor(buttonIndex / (maxIndex + 1)) * itemOffsetY);
$Jssor$.$AppendChild(elmt, div);
_ButtonElements[buttonIndex] = div;
if (_Options.$ActionMode & 1)
$Jssor$.$AddEvent(div, "click", $Jssor$.$CreateCallback(null, OnNavigationRequest, buttonIndex));
if (_Options.$ActionMode & 2)
$Jssor$.$AddEvent(div, "mouseover", $Jssor$.$MouseOverOutFilter($Jssor$.$CreateCallback(null, OnNavigationRequest, buttonIndex), div));
_Buttons[buttonIndex] = $Jssor$.$Buttonize(div);
}
//self.$TriggerEvent($JssorNavigatorEvents$.$RESET);
_Initialized = true;
}
};
//JssorBulletNavigator Constructor
{
self.$Options = _Options = $Jssor$.$Extend({
$SpacingX: 0,
$SpacingY: 0,
$Orientation: 1,
$ActionMode: 1
}, options);
//Sodo statement for development time intellisence only
$JssorDebug$.$Execute(function () {
_Options = $Jssor$.$Extend({
$Steps: undefined,
$Lanes: undefined
}, _Options);
});
_ItemPrototype = $Jssor$.$FindChild(elmt, "prototype");
$JssorDebug$.$Execute(function () {
if (!_ItemPrototype)
$JssorDebug$.$Fail("Navigator item prototype not defined.");
if (isNaN($Jssor$.$CssWidth(_ItemPrototype))) {
$JssorDebug$.$Fail("Width of 'navigator item prototype' not specified.");
}
if (isNaN($Jssor$.$CssHeight(_ItemPrototype))) {
$JssorDebug$.$Fail("Height of 'navigator item prototype' not specified.");
}
});
_PrototypeWidth = $Jssor$.$CssWidth(_ItemPrototype);
_PrototypeHeight = $Jssor$.$CssHeight(_ItemPrototype);
$Jssor$.$RemoveChild(elmt, _ItemPrototype);
_Steps = _Options.$Steps || 1;
_Lanes = _Options.$Lanes || 1;
_SpacingX = _Options.$SpacingX;
_SpacingY = _Options.$SpacingY;
_Orientation = _Options.$Orientation - 1;
}
};
var $JssorArrowNavigator$ = window.$JssorArrowNavigator$ = function (arrowLeft, arrowRight, options, containerWidth, containerHeight) {
var self = this;
$JssorObject$.call(self);
$JssorDebug$.$Execute(function () {
if (!arrowLeft)
$JssorDebug$.$Fail("Option '$ArrowNavigatorOptions' spepcified, but UI 'arrowleft' not defined. Define 'arrowleft' to enable direct navigation, or remove option '$ArrowNavigatorOptions' to disable direct navigation.");
if (!arrowRight)
$JssorDebug$.$Fail("Option '$ArrowNavigatorOptions' spepcified, but UI 'arrowright' not defined. Define 'arrowright' to enable direct navigation, or remove option '$ArrowNavigatorOptions' to disable direct navigation.");
if (isNaN($Jssor$.$CssWidth(arrowLeft))) {
$JssorDebug$.$Fail("Width of 'arrow left' not specified.");
}
if (isNaN($Jssor$.$CssWidth(arrowRight))) {
$JssorDebug$.$Fail("Width of 'arrow right' not specified.");
}
if (isNaN($Jssor$.$CssHeight(arrowLeft))) {
$JssorDebug$.$Fail("Height of 'arrow left' not specified.");
}
if (isNaN($Jssor$.$CssHeight(arrowRight))) {
$JssorDebug$.$Fail("Height of 'arrow right' not specified.");
}
});
var _Length;
var _CurrentIndex;
var _Options;
var _Steps;
var _ArrowWidth = $Jssor$.$CssWidth(arrowLeft);
var _ArrowHeight = $Jssor$.$CssHeight(arrowLeft);
function OnNavigationRequest(steps) {
self.$TriggerEvent($JssorNavigatorEvents$.$NAVIGATIONREQUEST, steps, true);
}
self.$GetCurrentIndex = function () {
return _CurrentIndex;
};
self.$SetCurrentIndex = function (index, virtualIndex, temp) {
if (temp) {
_CurrentIndex = virtualIndex;
}
else {
_CurrentIndex = index;
}
//self.$TriggerEvent($JssorNavigatorEvents$.$INDEXCHANGE, index);
};
self.$Show = function (hide) {
$Jssor$.$ShowElement(arrowLeft, hide);
$Jssor$.$ShowElement(arrowRight, hide);
};
var _Located;
self.$Relocate = function (force) {
if (!_Located || _Options.$Scale == false) {
if (_Options.$AutoCenter & 1) {
$Jssor$.$CssLeft(arrowLeft, (containerWidth - _ArrowWidth) / 2);
$Jssor$.$CssLeft(arrowRight, (containerWidth - _ArrowWidth) / 2);
}
if (_Options.$AutoCenter & 2) {
$Jssor$.$CssTop(arrowLeft, (containerHeight - _ArrowHeight) / 2);
$Jssor$.$CssTop(arrowRight, (containerHeight - _ArrowHeight) / 2);
}
_Located = true;
}
};
var _Initialized;
self.$Reset = function (length) {
_Length = length;
_CurrentIndex = 0;
if (!_Initialized) {
//self.$Relocate(true);
$Jssor$.$AddEvent(arrowLeft, "click", $Jssor$.$CreateCallback(null, OnNavigationRequest, -_Steps));
$Jssor$.$AddEvent(arrowRight, "click", $Jssor$.$CreateCallback(null, OnNavigationRequest, _Steps));
$Jssor$.$Buttonize(arrowLeft);
$Jssor$.$Buttonize(arrowRight);
_Initialized = true;
}
//self.$TriggerEvent($JssorNavigatorEvents$.$RESET);
};
//JssorArrowNavigator Constructor
{
self.$Options = _Options = $Jssor$.$Extend({
$Steps: 1
}, options);
_Steps = _Options.$Steps;
}
};
//$JssorThumbnailNavigator$
var $JssorThumbnailNavigator$ = window.$JssorThumbnailNavigator$ = function (elmt, options) {
var _Self = this;
var _Length;
var _Count;
var _CurrentIndex;
var _Options;
var _NavigationItems = [];
var _Width;
var _Height;
var _Lanes;
var _SpacingX;
var _SpacingY;
var _PrototypeWidth;
var _PrototypeHeight;
var _DisplayPieces;
var _Slider;
var _CurrentMouseOverIndex = -1;
var _SlidesContainer;
var _ThumbnailPrototype;
$JssorObject$.call(_Self);
elmt = $Jssor$.$GetElement(elmt);
function NavigationItem(item, index) {
var self = this;
var _Wrapper;
var _Button;
var _Thumbnail;
function Highlight(mouseStatus) {
_Button.$Activate(_CurrentIndex == index);
}
function OnNavigationRequest(event) {
if (!_Slider.$LastDragSucceded()) {
var tail = _Lanes - index % _Lanes;
var slideVirtualIndex = _Slider.$GetVirtualIndex((index + tail) / _Lanes - 1);
var itemVirtualIndex = slideVirtualIndex * _Lanes + _Lanes - tail;
_Self.$TriggerEvent($JssorNavigatorEvents$.$NAVIGATIONREQUEST, itemVirtualIndex);
}
//$JssorDebug$.$Log("navigation request");
}
$JssorDebug$.$Execute(function () {
self.$Wrapper = undefined;
});
self.$Index = index;
self.$Highlight = Highlight;
//NavigationItem Constructor
{
_Thumbnail = item.$Thumb || item.$Image || $Jssor$.$CreateDiv();
self.$Wrapper = _Wrapper = $Jssor$.$BuildElement(_ThumbnailPrototype, "ThumbnailTemplate", _Thumbnail, true);
_Button = $Jssor$.$Buttonize(_Wrapper);
if (_Options.$ActionMode & 1)
$Jssor$.$AddEvent(_Wrapper, "click", OnNavigationRequest);
if (_Options.$ActionMode & 2)
$Jssor$.$AddEvent(_Wrapper, "mouseover", $Jssor$.$MouseOverOutFilter(OnNavigationRequest, _Wrapper));
}
}
_Self.$GetCurrentIndex = function () {
return _CurrentIndex;
};
_Self.$SetCurrentIndex = function (index, virtualIndex, temp) {
var oldIndex = _CurrentIndex;
_CurrentIndex = index;
if (oldIndex != -1)
_NavigationItems[oldIndex].$Highlight();
_NavigationItems[index].$Highlight();
if (!temp) {
_Slider.$PlayTo(_Slider.$GetVirtualIndex(Math.floor(virtualIndex / _Lanes)));
}
};
_Self.$Show = function (hide) {
$Jssor$.$ShowElement(elmt, hide);
};
_Self.$Relocate = $Jssor$.$EmptyFunction;
var _Initialized;
_Self.$Reset = function (length, items, loadingContainer) {
if (!_Initialized) {
_Length = length;
_Count = Math.ceil(_Length / _Lanes);
_CurrentIndex = -1;
_DisplayPieces = Math.min(_DisplayPieces, items.length);
var horizontal = _Options.$Orientation & 1;
var slideWidth = _PrototypeWidth + (_PrototypeWidth + _SpacingX) * (_Lanes - 1) * (1 - horizontal);
var slideHeight = _PrototypeHeight + (_PrototypeHeight + _SpacingY) * (_Lanes - 1) * horizontal;
var slidesContainerWidth = slideWidth + (slideWidth + _SpacingX) * (_DisplayPieces - 1) * horizontal;
var slidesContainerHeight = slideHeight + (slideHeight + _SpacingY) * (_DisplayPieces - 1) * (1 - horizontal);
$Jssor$.$CssPosition(_SlidesContainer, "absolute");
$Jssor$.$CssOverflow(_SlidesContainer, "hidden");
if (_Options.$AutoCenter & 1) {
$Jssor$.$CssLeft(_SlidesContainer, (_Width - slidesContainerWidth) / 2);
}
if (_Options.$AutoCenter & 2) {
$Jssor$.$CssTop(_SlidesContainer, (_Height - slidesContainerHeight) / 2);
}
//$JssorDebug$.$Execute(function () {
// if (!_Options.$AutoCenter) {
// var slidesContainerTop = $Jssor$.$CssTop(_SlidesContainer);
// var slidesContainerLeft = $Jssor$.$CssLeft(_SlidesContainer);
// if (isNaN(slidesContainerTop)) {
// $JssorDebug$.$Fail("Position 'top' wrong specification of thumbnail navigator slides container (<div u=\"thumbnavigator\">...<div u=\"slides\">), \r\nwhen option $ThumbnailNavigatorOptions.$AutoCenter set to 0, it should be specified in pixel (like <div u=\"slides\" style=\"top: 0px;\">)");
// }
// if (isNaN(slidesContainerLeft)) {
// $JssorDebug$.$Fail("Position 'left' wrong specification of thumbnail navigator slides container (<div u=\"thumbnavigator\">...<div u=\"slides\">), \r\nwhen option $ThumbnailNavigatorOptions.$AutoCenter set to 0, it should be specified in pixel (like <div u=\"slides\" style=\"left: 0px;\">)");
// }
// }
//});
$Jssor$.$CssWidth(_SlidesContainer, slidesContainerWidth);
$Jssor$.$CssHeight(_SlidesContainer, slidesContainerHeight);
var slideItemElmts = [];
$Jssor$.$Each(items, function (item, index) {
var navigationItem = new NavigationItem(item, index);
var navigationItemWrapper = navigationItem.$Wrapper;
var columnIndex = Math.floor(index / _Lanes);
var laneIndex = index % _Lanes;
$Jssor$.$CssLeft(navigationItemWrapper, (_PrototypeWidth + _SpacingX) * laneIndex * (1 - horizontal));
$Jssor$.$CssTop(navigationItemWrapper, (_PrototypeHeight + _SpacingY) * laneIndex * horizontal);
if (!slideItemElmts[columnIndex]) {
slideItemElmts[columnIndex] = $Jssor$.$CreateDiv();
$Jssor$.$AppendChild(_SlidesContainer, slideItemElmts[columnIndex]);
}
$Jssor$.$AppendChild(slideItemElmts[columnIndex], navigationItemWrapper);
_NavigationItems.push(navigationItem);
});
var thumbnailSliderOptions = $Jssor$.$Extend({
$AutoPlay: false,
$NaviQuitDrag: false,
$SlideWidth: slideWidth,
$SlideHeight: slideHeight,
$SlideSpacing: _SpacingX * horizontal + _SpacingY * (1 - horizontal),
$MinDragOffsetToSlide: 12,
$SlideDuration: 200,
$PauseOnHover: 1,
$PlayOrientation: _Options.$Orientation,
$DragOrientation: _Options.$DisableDrag ? 0 : _Options.$Orientation
}, _Options);
_Slider = new $JssorSlider$(elmt, thumbnailSliderOptions);
_Initialized = true;
}
//_Self.$TriggerEvent($JssorNavigatorEvents$.$RESET);
};
//JssorThumbnailNavigator Constructor
{
_Self.$Options = _Options = $Jssor$.$Extend({
$SpacingX: 3,
$SpacingY: 3,
$DisplayPieces: 1,
$Orientation: 1,
$AutoCenter: 3,
$ActionMode: 1
}, options);
//Sodo statement for development time intellisence only
$JssorDebug$.$Execute(function () {
_Options = $Jssor$.$Extend({
$Lanes: undefined,
$Width: undefined,
$Height: undefined
}, _Options);
});
_Width = $Jssor$.$CssWidth(elmt);
_Height = $Jssor$.$CssHeight(elmt);
$JssorDebug$.$Execute(function () {
if (!_Width)
$JssorDebug$.$Fail("width of 'thumbnavigator' container not specified.");
if (!_Height)
$JssorDebug$.$Fail("height of 'thumbnavigator' container not specified.");
});
_SlidesContainer = $Jssor$.$FindChild(elmt, "slides", true);
_ThumbnailPrototype = $Jssor$.$FindChild(_SlidesContainer, "prototype");
$JssorDebug$.$Execute(function () {
if (!_ThumbnailPrototype)
$JssorDebug$.$Fail("prototype of 'thumbnavigator' not defined.");
});
_PrototypeWidth = $Jssor$.$CssWidth(_ThumbnailPrototype);
_PrototypeHeight = $Jssor$.$CssHeight(_ThumbnailPrototype);
$Jssor$.$RemoveChild(_SlidesContainer, _ThumbnailPrototype);
_Lanes = _Options.$Lanes || 1;
_SpacingX = _Options.$SpacingX;
_SpacingY = _Options.$SpacingY;
_DisplayPieces = _Options.$DisplayPieces;
}
};
//$JssorCaptionSliderBase$
function $JssorCaptionSliderBase$() {
$JssorAnimator$.call(this, 0, 0);
this.$Revert = $Jssor$.$EmptyFunction;
}
var $JssorCaptionSlider$ = window.$JssorCaptionSlider$ = function (container, captionSlideOptions, playIn) {
$JssorDebug$.$Execute(function () {
if (!captionSlideOptions.$CaptionTransitions) {
$JssorDebug$.$Error("'$CaptionSliderOptions' option error, '$CaptionSliderOptions.$CaptionTransitions' not specified.");
}
//else if (!$Jssor$.$IsArray(captionSlideOptions.$CaptionTransitions)) {
// $JssorDebug$.$Error("'$CaptionSliderOptions' option error, '$CaptionSliderOptions.$CaptionTransitions' is not an array.");
//}
});
var _Self = this;
var _ImmediateOutCaptionHanger;
var _PlayMode = playIn ? captionSlideOptions.$PlayInMode : captionSlideOptions.$PlayOutMode;
var _CaptionTransitions = captionSlideOptions.$CaptionTransitions;
var _CaptionTuningFetcher = { $Transition: "t", $Delay: "d", $Duration: "du", x: "x", y: "y", $Rotate: "r", $Zoom: "z", $Opacity: "f", $BeginTime: "b" };
var _CaptionTuningTransfer = {
$Default: function (value, tuningValue) {
if (!isNaN(tuningValue.$Value))
value = tuningValue.$Value;
else
value *= tuningValue.$Percent;
return value;
},
$Opacity: function (value, tuningValue) {
return this.$Default(value - 1, tuningValue);
}
};
_CaptionTuningTransfer.$Zoom = _CaptionTuningTransfer.$Opacity;
$JssorAnimator$.call(_Self, 0, 0);
function GetCaptionItems(element, level) {
var itemsToPlay = [];
var lastTransitionName;
var namedTransitions = [];
var namedTransitionOrders = [];
//$JssorDebug$.$Execute(function () {
// var debugInfoElement = $Jssor$.$GetElement("debugInfo");
// if (debugInfoElement && playIn) {
// var text = $Jssor.$InnerHtml(debugInfoElement) + "<br>";
// $Jssor$.$InnerHtml(debugInfoElement, text);
// }
//});
function FetchRawTransition(captionElmt, index) {
var rawTransition = {};
$Jssor$.$Each(_CaptionTuningFetcher, function (fetchAttribute, fetchProperty) {
var attributeValue = $Jssor$.$AttributeEx(captionElmt, fetchAttribute + (index || ""));
if (attributeValue) {
var propertyValue = {};
if (fetchAttribute == "t") {
//if (($Jssor$.$IsBrowserChrome() || $Jssor$.$IsBrowserSafari() || $Jssor$.$IsBrowserFireFox()) && attributeValue == "*") {
// attributeValue = Math.floor(Math.random() * captionSlideOptions.$CaptionTransitions.length);
// $Jssor$.$Attribute(captionElmt, fetchAttribute + (index || ""), attributeValue);
//}
propertyValue.$Value = attributeValue;
}
else if (attributeValue.indexOf("%") + 1)
propertyValue.$Percent = $Jssor$.$ParseFloat(attributeValue) / 100;
else
propertyValue.$Value = $Jssor$.$ParseFloat(attributeValue);
rawTransition[fetchProperty] = propertyValue;
}
});
return rawTransition;
}
function GetRandomTransition() {
return _CaptionTransitions[Math.floor(Math.random() * _CaptionTransitions.length)];
}
function EvaluateCaptionTransition(transitionName) {
var transition;
if (transitionName == "*") {
transition = GetRandomTransition();
}
else if (transitionName) {
//indexed transition allowed, just the same as named transition
var tempTransition = _CaptionTransitions[$Jssor$.$ParseInt(transitionName)] || _CaptionTransitions[transitionName];
if ($Jssor$.$IsArray(tempTransition)) {
if (transitionName != lastTransitionName) {
lastTransitionName = transitionName;
namedTransitionOrders[transitionName] = 0;
namedTransitions[transitionName] = tempTransition[Math.floor(Math.random() * tempTransition.length)];
}
else {
namedTransitionOrders[transitionName]++;
}
tempTransition = namedTransitions[transitionName];
if ($Jssor$.$IsArray(tempTransition)) {
tempTransition = tempTransition.length && tempTransition[namedTransitionOrders[transitionName] % tempTransition.length];
if ($Jssor$.$IsArray(tempTransition)) {
//got transition from array level 3, random for all captions
tempTransition = tempTransition[Math.floor(Math.random() * tempTransition.length)];
}
//else {
// //got transition from array level 2, in sequence for all adjacent captions with same name specified
// transition = tempTransition;
//}
}
//else {
// //got transition from array level 1, random but same for all adjacent captions with same name specified
// transition = tempTransition;
//}
}
//else {
// //got transition directly from a simple transition object
// transition = tempTransition;
//}
transition = tempTransition;
if ($Jssor$.$IsString(transition))
transition = EvaluateCaptionTransition(transition);
}
return transition;
}
var captionElmts = $Jssor$.$Children(element);
$Jssor$.$Each(captionElmts, function (captionElmt, i) {
var transitionsWithTuning = [];
transitionsWithTuning.$Elmt = captionElmt;
var isCaption = $Jssor$.$AttributeEx(captionElmt, "u") == "caption";
$Jssor$.$Each(playIn ? [0, 3] : [2], function (j, k) {
if (isCaption) {
var transition;
var rawTransition;
if (j != 2 || !$Jssor$.$AttributeEx(captionElmt, "t3")) {
rawTransition = FetchRawTransition(captionElmt, j);
if (j == 2 && !rawTransition.$Transition) {
rawTransition.$Delay = rawTransition.$Delay || { $Value: 0 };
rawTransition = $Jssor$.$Extend(FetchRawTransition(captionElmt, 0), rawTransition);
}
}
if (rawTransition && rawTransition.$Transition) {
transition = EvaluateCaptionTransition(rawTransition.$Transition.$Value);
if (transition) {
//var transitionWithTuning = $Jssor$.$Extend({ $Delay: 0, $ScaleHorizontal: 1, $ScaleVertical: 1 }, transition);
var transitionWithTuning = $Jssor$.$Extend({ $Delay: 0 }, transition);
$Jssor$.$Each(rawTransition, function (rawPropertyValue, propertyName) {
var tuningPropertyValue = (_CaptionTuningTransfer[propertyName] || _CaptionTuningTransfer.$Default).apply(_CaptionTuningTransfer, [transitionWithTuning[propertyName], rawTransition[propertyName]]);
if (!isNaN(tuningPropertyValue))
transitionWithTuning[propertyName] = tuningPropertyValue;
});
if (!k) {
if (rawTransition.$BeginTime)
transitionWithTuning.$BeginTime = rawTransition.$BeginTime.$Value || 0;
else if ((_PlayMode) & 2)
transitionWithTuning.$BeginTime = 0;
}
}
}
transitionsWithTuning.push(transitionWithTuning);
}
if ((level % 2) && !k) {
//transitionsWithTuning.$Children = GetCaptionItems(captionElmt, lastTransitionName, [].concat(namedTransitions), [].concat(namedTransitionOrders), level + 1);
transitionsWithTuning.$Children = GetCaptionItems(captionElmt, level + 1);
}
});
itemsToPlay.push(transitionsWithTuning);
});
return itemsToPlay;
}
function CreateAnimator(item, transition, immediateOut) {
var animatorOptions = {
$Easing: transition.$Easing,
$Round: transition.$Round,
$During: transition.$During,
$Reverse: playIn && !immediateOut,
$Optimize: true
};
$JssorDebug$.$Execute(function () {
animatorOptions.$CaptionAnimator = true;
});
var captionItem = item;
var captionParent = $Jssor$.$ParentNode(item);
var captionItemWidth = $Jssor$.$CssWidth(captionItem);
var captionItemHeight = $Jssor$.$CssHeight(captionItem);
var captionParentWidth = $Jssor$.$CssWidth(captionParent);
var captionParentHeight = $Jssor$.$CssHeight(captionParent);
var toStyles = {};
var fromStyles = {};
var scaleClip = transition.$ScaleClip || 1;
//Opacity
if (transition.$Opacity) {
toStyles.$Opacity = 2 - transition.$Opacity;
}
animatorOptions.$OriginalWidth = captionItemWidth;
animatorOptions.$OriginalHeight = captionItemHeight;
//Transform
if (transition.$Zoom || transition.$Rotate) {
toStyles.$Zoom = transition.$Zoom ? transition.$Zoom - 1 : 1;
if ($Jssor$.$IsBrowserIe9Earlier() || $Jssor$.$IsBrowserOpera())
toStyles.$Zoom = Math.min(toStyles.$Zoom, 2);
fromStyles.$Zoom = 1;
var rotate = transition.$Rotate || 0;
toStyles.$Rotate = rotate * 360;
fromStyles.$Rotate = 0;
}
//Clip
else if (transition.$Clip) {
var fromStyleClip = { $Top: 0, $Right: captionItemWidth, $Bottom: captionItemHeight, $Left: 0 };
var toStyleClip = $Jssor$.$Extend({}, fromStyleClip);
var blockOffset = toStyleClip.$Offset = {};
var topBenchmark = transition.$Clip & 4;
var bottomBenchmark = transition.$Clip & 8;
var leftBenchmark = transition.$Clip & 1;
var rightBenchmark = transition.$Clip & 2;
if (topBenchmark && bottomBenchmark) {
blockOffset.$Top = captionItemHeight / 2 * scaleClip;
blockOffset.$Bottom = -blockOffset.$Top;
}
else if (topBenchmark)
blockOffset.$Bottom = -captionItemHeight * scaleClip;
else if (bottomBenchmark)
blockOffset.$Top = captionItemHeight * scaleClip;
if (leftBenchmark && rightBenchmark) {
blockOffset.$Left = captionItemWidth / 2 * scaleClip;
blockOffset.$Right = -blockOffset.$Left;
}
else if (leftBenchmark)
blockOffset.$Right = -captionItemWidth * scaleClip;
else if (rightBenchmark)
blockOffset.$Left = captionItemWidth * scaleClip;
animatorOptions.$Move = transition.$Move;
toStyles.$Clip = toStyleClip;
fromStyles.$Clip = fromStyleClip;
}
//Fly
{
var toLeft = 0;
var toTop = 0;
if (transition.x)
toLeft -= captionParentWidth * transition.x;
if (transition.y)
toTop -= captionParentHeight * transition.y;
if (toLeft || toTop || animatorOptions.$Move) {
toStyles.$Left = toLeft + $Jssor$.$CssLeft(captionItem);
toStyles.$Top = toTop + $Jssor$.$CssTop(captionItem);
}
}
//duration
var duration = transition.$Duration;
fromStyles = $Jssor$.$Extend(fromStyles, $Jssor$.$GetStyles(captionItem, toStyles));
animatorOptions.$Setter = $Jssor$.$StyleSetterEx();
return new $JssorAnimator$(transition.$Delay, duration, animatorOptions, captionItem, fromStyles, toStyles);
}
function CreateAnimators(streamLineLength, captionItems) {
$Jssor$.$Each(captionItems, function (captionItem, i) {
$JssorDebug$.$Execute(function () {
if (captionItem.length) {
var top = $Jssor$.$CssTop(captionItem.$Elmt);
var left = $Jssor$.$CssLeft(captionItem.$Elmt);
var width = $Jssor$.$CssWidth(captionItem.$Elmt);
var height = $Jssor$.$CssHeight(captionItem.$Elmt);
var error = null;
if (isNaN(top))
error = "Style 'top' for caption not specified. Please always specify caption like 'position: absolute; top: ...px; left: ...px; width: ...px; height: ...px;'.";
else if (isNaN(left))
error = "Style 'left' not specified. Please always specify caption like 'position: absolute; top: ...px; left: ...px; width: ...px; height: ...px;'.";
else if (isNaN(width))
error = "Style 'width' not specified. Please always specify caption like 'position: absolute; top: ...px; left: ...px; width: ...px; height: ...px;'.";
else if (isNaN(height))
error = "Style 'height' not specified. Please always specify caption like 'position: absolute; top: ...px; left: ...px; width: ...px; height: ...px;'.";
if (error)
$JssorDebug$.$Error("Caption " + (i + 1) + " definition error, \r\n" + error + "\r\n" + captionItem.$Elmt.outerHTML);
}
});
var animator;
var captionElmt = captionItem.$Elmt;
var transition = captionItem[0];
var transition3 = captionItem[1];
if (transition) {
animator = CreateAnimator(captionElmt, transition);
streamLineLength = animator.$Locate(transition.$BeginTime == undefined ? streamLineLength : transition.$BeginTime, 1);
}
streamLineLength = CreateAnimators(streamLineLength, captionItem.$Children);
if (transition3) {
var animator3 = CreateAnimator(captionElmt, transition3, 1);
animator3.$Locate(streamLineLength, 1);
_Self.$Combine(animator3);
_ImmediateOutCaptionHanger.$Combine(animator3);
}
if (animator)
_Self.$Combine(animator);
});
return streamLineLength;
}
_Self.$Revert = function () {
_Self.$GoToPosition(_Self.$GetPosition_OuterEnd() * (playIn || 0));
_ImmediateOutCaptionHanger.$GoToBegin();
};
//Constructor
{
_ImmediateOutCaptionHanger = new $JssorAnimator$(0, 0);
//var streamLineLength = 0;
//var captionItems = GetCaptionItems(container, null, [], [], 1);
CreateAnimators(0, _PlayMode ? GetCaptionItems(container, 1) : []);
}
};
//Event Table
//$EVT_CLICK = 21; function(slideIndex[, event])
//$EVT_DRAG_START = 22; function(position[, virtualPosition, event])
//$EVT_DRAG_END = 23; function(position, startPosition[, virtualPosition, virtualStartPosition, event])
//$EVT_SWIPE_START = 24; function(position[, virtualPosition])
//$EVT_SWIPE_END = 25; function(position[, virtualPosition])
//$EVT_LOAD_START = 26; function(slideIndex)
//$EVT_LOAD_END = 27; function(slideIndex)
//$EVT_POSITION_CHANGE = 202; function(position, fromPosition[, virtualPosition, virtualFromPosition])
//$EVT_PARK = 203; function(slideIndex, fromIndex)
//$EVT_PROGRESS_CHANGE = 208; function(slideIndex, progress[, progressBegin, idleBegin, idleEnd, progressEnd])
//$EVT_STATE_CHANGE = 209; function(slideIndex, progress[, progressBegin, idleBegin, idleEnd, progressEnd])
//$EVT_ROLLBACK_START = 210; function(slideIndex, progress[, progressBegin, idleBegin, idleEnd, progressEnd])
//$EVT_ROLLBACK_END = 211; function(slideIndex, progress[, progressBegin, idleBegin, idleEnd, progressEnd])
//$EVT_SLIDESHOW_START = 206; function(slideIndex[, progressBegin, slideshowBegin, slideshowEnd, progressEnd])
//$EVT_SLIDESHOW_END = 207; function(slideIndex[, progressBegin, slideshowBegin, slideshowEnd, progressEnd])
//http://www.jssor.com/development/reference-api.html
| JavaScript |
Calendar.LANG("ro", "Română", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Astăzi",
today: "Astăzi", // appears in bottom bar
wk: "săp.",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Ianuarie",
"Februarie",
"Martie",
"Aprilie",
"Mai",
"Iunie",
"Iulie",
"August",
"Septembrie",
"Octombrie",
"Noiembrie",
"Decembrie" ],
smn : [ "Ian",
"Feb",
"Mar",
"Apr",
"Mai",
"Iun",
"Iul",
"Aug",
"Sep",
"Oct",
"Noi",
"Dec" ],
dn : [ "Duminică",
"Luni",
"Marţi",
"Miercuri",
"Joi",
"Vineri",
"Sâmbătă",
"Duminică" ],
sdn : [ "Du",
"Lu",
"Ma",
"Mi",
"Jo",
"Vi",
"Sâ",
"Du" ]
});
| JavaScript |
Calendar.LANG("cn", "中文", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "今天",
today: "今天", // appears in bottom bar
wk: "周",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "AM",
PM: "PM",
mn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
smn : [ "一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月"],
dn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ],
sdn : [ "日",
"一",
"二",
"三",
"四",
"五",
"六",
"日" ]
});
| JavaScript |
Calendar.LANG("ru", "русский", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Сегодня",
today: "Сегодня", // appears in bottom bar
wk: "нед",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "январь",
"февраль",
"март",
"апрель",
"май",
"июнь",
"июль",
"август",
"сентябрь",
"октябрь",
"ноябрь",
"декабрь" ],
smn : [ "янв",
"фев",
"мар",
"апр",
"май",
"июн",
"июл",
"авг",
"сен",
"окт",
"ноя",
"дек" ],
dn : [ "воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота",
"воскресенье" ],
sdn : [ "вск",
"пон",
"втр",
"срд",
"чет",
"пят",
"суб",
"вск" ]
});
| JavaScript |
Calendar.LANG("fr", "Français", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday : "Aujourd'hui",
today: "Aujourd'hui", // appears in bottom bar
wk: "sm.",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Janvier",
"Février",
"Mars",
"Avril",
"Mai",
"Juin",
"Juillet",
"Août",
"Septembre",
"Octobre",
"Novembre",
"Décembre" ],
smn : [ "Jan",
"Fév",
"Mar",
"Avr",
"Mai",
"Juin",
"Juil",
"Aou",
"Sep",
"Oct",
"Nov",
"Déc" ],
dn : [ "Dimanche",
"Lundi",
"Mardi",
"Mercredi",
"Jeudi",
"Vendredi",
"Samedi",
"Dimanche" ],
sdn : [ "Di",
"Lu",
"Ma",
"Me",
"Je",
"Ve",
"Sa",
"Di" ]
});
| JavaScript |
Calendar.LANG("pt", "Portuguese", {
fdow: 1, // primeiro dia da semana para esse local; 0 = Domingo, 1 = Segunda, etc.
goToday: "Dia de Hoje",
today: "Hoje",
wk: "sm",
weekend: "0,6", // 0 = Domingo, 1 = Segunda, etc.
AM: "am",
PM: "pm",
mn : [ "Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro" ],
smn : [ "Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez" ],
dn : [ "Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sábado",
"Domingo" ],
sdn : [ "Dom",
"Seg",
"Ter",
"Qua",
"Qui",
"Sex",
"Sab",
"Dom" ]
});
| JavaScript |
Calendar.LANG("cz", "Czech", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Ukaž dnešek",
today: "Dnes", // appears in bottom bar
wk: "týd",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Leden",
"Únor",
"Březen",
"Duben",
"Květen",
"Červen",
"Červenec",
"Srpen",
"Září",
"Říjen",
"Listopad",
"Prosinec" ],
smn : [ "Led",
"Úno",
"Bře",
"Dub",
"Kvě",
"Črn",
"Črc",
"Srp",
"Zář",
"Říj",
"Lis",
"Pro" ],
dn : [ "Neděle",
"Pondělí",
"Úterý",
"Středa",
"Čtvrtek",
"Pátek",
"Sobota",
"Neděle" ],
sdn : [ "Ne",
"Po",
"Út",
"St",
"Čt",
"Pá",
"So",
"Ne" ]
});
| JavaScript |
Calendar.LANG("de", "Deutsch", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday : "Heute ausw\u00e4hlen",
today: "Heute", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember" ],
smn : [ "Jan",
"Feb",
"M\u00e4r",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez" ],
dn : [ "Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag",
"Sonntag" ],
sdn : [ "So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa",
"So" ]
});
| JavaScript |
Calendar.LANG("jp", "Japanese", {
fdow: 1, // 地元の週の初めの日; 0 = 日曜日, 1 = 月曜日, 等.
goToday: "本日へ",
today: "本日", // ボットンバーに表示
wk: "週",
weekend: "0,6", // 0 = 日曜日, 1 = 月曜日, 等.
AM: "am",
PM: "pm",
mn : [ "1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月" ],
smn : [ "1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月" ],
dn : [ "日曜日",
"月曜日",
"火曜日",
"水曜日",
"木曜日",
"金曜日",
"土曜日",
"日曜日" ],
sdn : [ "日",
"月",
"火",
"水",
"木",
"金",
"土",
"日" ]
});
| JavaScript |
Calendar.LANG("it", "Italiano", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Vai a oggi",
today: "Oggi", // appears in bottom bar
wk: "set",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Gennaio",
"Febbraio",
"Marzo",
"Aprile",
"Maggio",
"Giugno",
"Luglio",
"Agosto",
"Settembre",
"Ottobre",
"Novembre",
"Dicembre" ],
smn : [ "Gen",
"Feb",
"Mar",
"Apr",
"Mag",
"Giu",
"Lug",
"Ago",
"Set",
"Ott",
"Nov",
"Dic" ],
dn : [ "Domenica",
"Lunedì",
"Martedì",
"Mercoledì",
"Giovedi",
"Venerdì",
"Sabato",
"Domenica" ],
sdn : [ "Do",
"Lu",
"Ma",
"Me",
"Gi",
"Ve",
"Sa",
"Do" ]
});
| JavaScript |
Calendar.LANG("es", "Español", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Ir a Hoy",
today: "Hoy", // appears in bottom bar
wk: "sem",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre" ],
smn : [ "Ene",
"Feb",
"Mar",
"Abr",
"May",
"Jun",
"Jul",
"Ago",
"Sep",
"Oct",
"Nov",
"Dic" ],
dn : [ "Domingo",
"Lunes",
"Martes",
"Miercoles",
"Jueves",
"Viernes",
"Sabado",
"Domingo" ],
sdn : [ "Do",
"Lu",
"Ma",
"Mi",
"Ju",
"Vi",
"Sa",
"Do" ]
});
| JavaScript |
// autor: Piotr kwiatkowski
// www: http://pasjonata.net
Calendar.LANG("pl", "Polish", {
fdow: 1, // pierwszy dzień tygodnia; 0 = Niedziela, 1 = Poniedziałek, itd.
goToday: "Idzie Dzisiaj",
today: "Dziś",
wk: "wk",
weekend: "0,6", // 0 = Niedziela, 1 = Poniedziałek, itd.
AM: "am",
PM: "pm",
mn : [ "Styczeń",
"Luty",
"Marzec",
"Kwiecień",
"Maj",
"Czerwiec",
"Lipiec",
"Sierpień",
"Wrzesień",
"Październik",
"Listopad",
"Grudzień" ],
smn : [ "Sty",
"Lut",
"Mar",
"Kwi",
"Maj",
"Cze",
"Lip",
"Sie",
"Wrz",
"Paź",
"Lis",
"Gru" ],
dn : [ "Niedziela",
"Poniedziałek",
"Wtorek",
"Środa",
"Czwartek",
"Piątek",
"Sobota",
"Niedziela" ],
sdn : [ "Ni",
"Po",
"Wt",
"Śr",
"Cz",
"Pi",
"So",
"Ni" ]
});
| JavaScript |
Calendar.LANG("en", "English", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Go Today",
today: "Today", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December" ],
smn : [ "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec" ],
dn : [ "Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" ],
sdn : [ "Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su" ]
});
| JavaScript |
/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
var MD5 = function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
/***/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
| JavaScript |
jQuery(document).ready(function ($) {
var options = {
$AutoPlay: false, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$AutoPlaySteps: 4, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
$AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
$PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1
$ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false
$SlideDuration: 160, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20
$SlideWidth: 170, //[Optional] Width of every slide in pixels, default value is width of 'slides' container
//$SlideHeight: 150, //[Optional] Height of every slide in pixels, default value is height of 'slides' container
$SlideSpacing: 60, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 4, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc).
$PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1
$DragOrientation: 1, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
$BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
$Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1
$SpacingX:0, //[Optional] Horizontal space between each item in pixel, default value is 0
$SpacingY:0, //[Optional] Vertical space between each item in pixel, default value is 0
$Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
},
$ArrowNavigatorOptions: {
$Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 4 //[Optional] Steps to go for each navigation request, default value is 1
}
};
function runSlider(id){
var jssor_slider1 = new $JssorSlider$(id, options);
var bodyWidth = document.body.clientWidth;
if (bodyWidth)
jssor_slider1.$ScaleWidth(Math.min(bodyWidth, 860));
else
window.setTimeout(runSlider, 30);
}
runSlider('slider1_container');
runSlider('slider2_container');
runSlider('slider3_container');
runSlider('slider4_container');
if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
$(window).bind('resize', runSlider);
}
//if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
// $(window).bind("orientationchange", ScaleSlider);
//}
//responsive code end
});
| JavaScript |
/*
* Jssor 18.0
* http://www.jssor.com/
*
* TERMS OF USE - Jssor
*
* Copyright 2014 Jssor
*
* 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.
*/
/*! Jssor */
//$JssorDebug$
var $JssorDebug$ = new function () {
this.$DebugMode = true;
// Methods
this.$Log = function (msg, important) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.log) {
console.log(msg);
} else if (debug && important) {
alert(msg);
}
};
this.$Error = function (msg, e) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.error) {
console.error(msg);
} else if (debug) {
alert(msg);
}
if (debug) {
// since we're debugging, fail fast by crashing
throw e || new Error(msg);
}
};
this.$Fail = function (msg) {
throw new Error(msg);
};
this.$Assert = function (value, msg) {
var debug = this.$DebugMode;
if (debug) {
if (!value)
throw new Error("Assert failed " + msg || "");
}
};
this.$Trace = function (msg) {
var console = window.console || {};
var debug = this.$DebugMode;
if (debug && console.log) {
console.log(msg);
}
};
this.$Execute = function (func) {
var debug = this.$DebugMode;
if (debug)
func();
};
this.$LiveStamp = function (obj, id) {
var debug = this.$DebugMode;
if (debug) {
var stamp = document.createElement("DIV");
stamp.setAttribute("id", id);
obj.$Live = stamp;
}
};
this.$C_AbstractMethod = function () {
/// <summary>
/// Tells compiler the method is abstract, it should be implemented by subclass.
/// </summary>
throw new Error("The method is abstract, it should be implemented by subclass.");
};
function C_AbstractClass (instance) {
/// <summary>
/// Tells compiler the class is abstract, it should be implemented by subclass.
/// </summary>
if(instance.constructor === C_AbstractClass.caller)
throw new Error("Cannot create instance of an abstract class.");
}
this.$C_AbstractClass = C_AbstractClass;
};
//$JssorEasing$
var $JssorEasing$ = window.$JssorEasing$ = {
$EaseLinear: function (t) {
return t;
},
$EaseGoBack: function (t) {
return 1 - Math.abs((t *= 2) - 1);
},
$EaseSwing: function (t) {
return -Math.cos(t * Math.PI) / 2 + .5;
},
$EaseInQuad: function (t) {
return t * t;
},
$EaseOutQuad: function (t) {
return -t * (t - 2);
},
$EaseInOutQuad: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t : -1 / 2 * (--t * (t - 2) - 1);
},
$EaseInCubic: function (t) {
return t * t * t;
},
$EaseOutCubic: function (t) {
return (t -= 1) * t * t + 1;
},
$EaseInOutCubic: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t : 1 / 2 * ((t -= 2) * t * t + 2);
},
$EaseInQuart: function (t) {
return t * t * t * t;
},
$EaseOutQuart: function (t) {
return -((t -= 1) * t * t * t - 1);
},
$EaseInOutQuart: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t * t : -1 / 2 * ((t -= 2) * t * t * t - 2);
},
$EaseInQuint: function (t) {
return t * t * t * t * t;
},
$EaseOutQuint: function (t) {
return (t -= 1) * t * t * t * t + 1;
},
$EaseInOutQuint: function (t) {
return (t *= 2) < 1 ? 1 / 2 * t * t * t * t * t : 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
$EaseInSine: function (t) {
return 1 - Math.cos(t * Math.PI / 2);
},
$EaseOutSine: function (t) {
return Math.sin(t * Math.PI / 2);
},
$EaseInOutSine: function (t) {
return -1 / 2 * (Math.cos(Math.PI * t) - 1);
},
$EaseInExpo: function (t) {
return t == 0 ? 0 : Math.pow(2, 10 * (t - 1));
},
$EaseOutExpo: function (t) {
return t == 1 ? 1 : -Math.pow(2, -10 * t) + 1;
},
$EaseInOutExpo: function (t) {
return t == 0 || t == 1 ? t : (t *= 2) < 1 ? 1 / 2 * Math.pow(2, 10 * (t - 1)) : 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
$EaseInCirc: function (t) {
return -(Math.sqrt(1 - t * t) - 1);
},
$EaseOutCirc: function (t) {
return Math.sqrt(1 - (t -= 1) * t);
},
$EaseInOutCirc: function (t) {
return (t *= 2) < 1 ? -1 / 2 * (Math.sqrt(1 - t * t) - 1) : 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
$EaseInElastic: function (t) {
if (!t || t == 1)
return t;
var p = .3, s = .075;
return -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p));
},
$EaseOutElastic: function (t) {
if (!t || t == 1)
return t;
var p = .3, s = .075;
return Math.pow(2, -10 * t) * Math.sin((t - s) * 2 * Math.PI / p) + 1;
},
$EaseInOutElastic: function (t) {
if (!t || t == 1)
return t;
var p = .45, s = .1125;
return (t *= 2) < 1 ? -.5 * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p) : Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * 2 * Math.PI / p) * .5 + 1;
},
$EaseInBack: function (t) {
var s = 1.70158;
return t * t * ((s + 1) * t - s);
},
$EaseOutBack: function (t) {
var s = 1.70158;
return (t -= 1) * t * ((s + 1) * t + s) + 1;
},
$EaseInOutBack: function (t) {
var s = 1.70158;
return (t *= 2) < 1 ? 1 / 2 * t * t * (((s *= 1.525) + 1) * t - s) : 1 / 2 * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2);
},
$EaseInBounce: function (t) {
return 1 - $JssorEasing$.$EaseOutBounce(1 - t)
},
$EaseOutBounce: function (t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
},
$EaseInOutBounce: function (t) {
return t < 1 / 2 ? $JssorEasing$.$EaseInBounce(t * 2) * .5 : $JssorEasing$.$EaseOutBounce(t * 2 - 1) * .5 + .5;
},
$EaseInWave: function (t) {
return 1 - Math.cos(t * Math.PI * 2)
},
$EaseOutWave: function (t) {
return Math.sin(t * Math.PI * 2);
},
$EaseOutJump: function (t) {
return 1 - (((t *= 2) < 1) ? (t = 1 - t) * t * t : (t -= 1) * t * t);
},
$EaseInJump: function (t) {
return ((t *= 2) < 1) ? t * t * t : (t = 2 - t) * t * t;
}
};
var $JssorDirection$ = window.$JssorDirection$ = {
$TO_LEFT: 0x0001,
$TO_RIGHT: 0x0002,
$TO_TOP: 0x0004,
$TO_BOTTOM: 0x0008,
$HORIZONTAL: 0x0003,
$VERTICAL: 0x000C,
$LEFTRIGHT: 0x0003,
$TOPBOTOM: 0x000C,
$TOPLEFT: 0x0005,
$TOPRIGHT: 0x0006,
$BOTTOMLEFT: 0x0009,
$BOTTOMRIGHT: 0x000A,
$AROUND: 0x000F,
$GetDirectionHorizontal: function (direction) {
return direction & 0x0003;
},
$GetDirectionVertical: function (direction) {
return direction & 0x000C;
},
$ChessHorizontal: function (direction) {
return (~direction & 0x0003) + (direction & 0x000C);
},
$ChessVertical: function (direction) {
return (~direction & 0x000C) + (direction & 0x0003);
},
$IsToLeft: function (direction) {
return (direction & 0x0003) == 0x0001;
},
$IsToRight: function (direction) {
return (direction & 0x0003) == 0x0002;
},
$IsToTop: function (direction) {
return (direction & 0x000C) == 0x0004;
},
$IsToBottom: function (direction) {
return (direction & 0x000C) == 0x0008;
},
$IsHorizontal: function (direction) {
return (direction & 0x0003) > 0;
},
$IsVertical: function (direction) {
return (direction & 0x000C) > 0;
}
};
var $JssorKeyCode$ = {
$BACKSPACE: 8,
$COMMA: 188,
$DELETE: 46,
$DOWN: 40,
$END: 35,
$ENTER: 13,
$ESCAPE: 27,
$HOME: 36,
$LEFT: 37,
$NUMPAD_ADD: 107,
$NUMPAD_DECIMAL: 110,
$NUMPAD_DIVIDE: 111,
$NUMPAD_ENTER: 108,
$NUMPAD_MULTIPLY: 106,
$NUMPAD_SUBTRACT: 109,
$PAGE_DOWN: 34,
$PAGE_UP: 33,
$PERIOD: 190,
$RIGHT: 39,
$SPACE: 32,
$TAB: 9,
$UP: 38
};
var $JssorAlignment$ = {
$TopLeft: 0x11,
$TopCenter: 0x12,
$TopRight: 0x14,
$MiddleLeft: 0x21,
$MiddleCenter: 0x22,
$MiddleRight: 0x24,
$BottomLeft: 0x41,
$BottomCenter: 0x42,
$BottomRight: 0x44,
$IsTop: function (aligment) {
return aligment & 0x10 > 0;
},
$IsMiddle: function (alignment) {
return alignment & 0x20 > 0;
},
$IsBottom: function (alignment) {
return alignment & 0x40 > 0;
},
$IsLeft: function (alignment) {
return alignment & 0x01 > 0;
},
$IsCenter: function (alignment) {
return alignment & 0x02 > 0;
},
$IsRight: function (alignment) {
return alignment & 0x04 > 0;
}
};
var $JssorMatrix$;
var $JssorAnimator$;
// $Jssor$ is a static class, so make it singleton instance
var $Jssor$ = window.$Jssor$ = new function () {
// Fields
var _This = this;
var REGEX_WHITESPACE_GLOBAL = /\S+/g;
var ROWSER_UNKNOWN = 0;
var BROWSER_IE = 1;
var BROWSER_FIREFOX = 2;
var BROWSER_FIREFOX = 3;
var BROWSER_CHROME = 4;
var BROWSER_OPERA = 5;
//var arrActiveX = ["Msxml2.XMLHTTP", "Msxml3.XMLHTTP", "Microsoft.XMLHTTP"];
var browser = 0;
var browserRuntimeVersion = 0;
var browserEngineVersion = 0;
var browserJavascriptVersion = 0;
var webkitVersion = 0;
var app = navigator.appName;
var ver = navigator.appVersion;
var ua = navigator.userAgent;
var _DocElmt = document.documentElement;
var _TransformProperty;
function DetectBrowser() {
if (!browser) {
if (app == "Microsoft Internet Explorer" &&
!!window.attachEvent && !!window.ActiveXObject) {
var ieOffset = ua.indexOf("MSIE");
browser = BROWSER_IE;
browserEngineVersion = ParseFloat(ua.substring(ieOffset + 5, ua.indexOf(";", ieOffset)));
//check IE javascript version
/*@cc_on
browserJavascriptVersion = @_jscript_version;
@*/
// update: for intranet sites and compat view list sites, IE sends
// an IE7 User-Agent to the server to be interoperable, and even if
// the page requests a later IE version, IE will still report the
// IE7 UA to JS. we should be robust to self
//var docMode = document.documentMode;
//if (typeof docMode !== "undefined") {
// browserRuntimeVersion = docMode;
//}
browserRuntimeVersion = document.documentMode || browserEngineVersion;
}
else if (app == "Netscape" && !!window.addEventListener) {
var ffOffset = ua.indexOf("Firefox");
var saOffset = ua.indexOf("Safari");
var chOffset = ua.indexOf("Chrome");
var webkitOffset = ua.indexOf("AppleWebKit");
if (ffOffset >= 0) {
browser = BROWSER_FIREFOX;
browserRuntimeVersion = ParseFloat(ua.substring(ffOffset + 8));
}
else if (saOffset >= 0) {
var slash = ua.substring(0, saOffset).lastIndexOf("/");
browser = (chOffset >= 0) ? BROWSER_CHROME : BROWSER_FIREFOX;
browserRuntimeVersion = ParseFloat(ua.substring(slash + 1, saOffset));
}
if (webkitOffset >= 0)
webkitVersion = ParseFloat(ua.substring(webkitOffset + 12));
}
else {
var match = /(opera)(?:.*version|)[ \/]([\w.]+)/i.exec(ua);
if (match) {
browser = BROWSER_OPERA;
browserRuntimeVersion = ParseFloat(match[2]);
}
}
}
}
function IsBrowserIE() {
DetectBrowser();
return browser == BROWSER_IE;
}
function IsBrowserIeQuirks() {
return IsBrowserIE() && (browserRuntimeVersion < 6 || document.compatMode == "BackCompat"); //Composite to "CSS1Compat"
}
function IsBrowserFireFox() {
DetectBrowser();
return browser == BROWSER_FIREFOX;
}
function IsBrowserSafari() {
DetectBrowser();
return browser == BROWSER_FIREFOX;
}
function IsBrowserChrome() {
DetectBrowser();
return browser == BROWSER_CHROME;
}
function IsBrowserOpera() {
DetectBrowser();
return browser == BROWSER_OPERA;
}
function IsBrowserBadTransform() {
return IsBrowserSafari() && (webkitVersion > 534) && (webkitVersion < 535);
}
function IsBrowserIe9Earlier() {
return IsBrowserIE() && browserRuntimeVersion < 9;
}
function GetTransformProperty(elmt) {
if (!_TransformProperty) {
// Note that in some versions of IE9 it is critical that
// msTransform appear in this list before MozTransform
each(['transform', 'WebkitTransform', 'msTransform', 'MozTransform', 'OTransform'], function (property) {
if (elmt.style[property] != undefined) {
_TransformProperty = property;
return true;
}
});
_TransformProperty = _TransformProperty || "transform";
}
return _TransformProperty;
}
// Helpers
function getOffsetParent(elmt, isFixed) {
// IE and Opera "fixed" position elements don't have offset parents.
// regardless, if it's fixed, its offset parent is the body.
if (isFixed && elmt != document.body) {
return document.body;
} else {
return elmt.offsetParent;
}
}
function toString(obj) {
return Object.prototype.toString.call(obj);
}
// [[Class]] -> type pairs
var class2type;
function each(object, callback) {
if (toString(object) == "[object Array]") {
for (var i = 0; i < object.length; i++) {
if (callback(object[i], i, object)) {
return true;
}
}
}
else {
for (var name in object) {
if (callback(object[name], name, object)) {
return true;
}
}
}
}
function GetClass2Type() {
if (!class2type) {
class2type = {};
each(["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object"], function (name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
}
return class2type;
}
function type(obj) {
return obj == null ? String(obj) : GetClass2Type()[toString(obj)] || "object";
}
function isPlainObject(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || type(obj) !== "object" || obj.nodeType || _This.$IsWindow(obj)) {
return false;
}
var hasOwn = Object.prototype.hasOwnProperty;
try {
// Not own constructor property must be Object
if (obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) { }
return key === undefined || hasOwn.call(obj, key);
}
function Point(x, y) {
return { x: x, y: y };
}
function Delay(code, delay) {
setTimeout(code, delay || 0);
}
function RemoveByReg(str, reg) {
var m = reg.exec(str);
if (m) {
var header = str.substr(0, m.index);
var tailer = str.substr(m.lastIndex + 1, str.length - (m.lastIndex + 1));
str = header + tailer;
}
return str;
}
function BuildNewCss(oldCss, removeRegs, replaceValue) {
var css = (!oldCss || oldCss == "inherit") ? "" : oldCss;
each(removeRegs, function (removeReg) {
var m = removeReg.exec(css);
if (m) {
var header = css.substr(0, m.index);
var tailer = css.substr(m.lastIndex + 1, css.length - (m.lastIndex + 1));
css = header + tailer;
}
});
css = replaceValue + (css.indexOf(" ") != 0 ? " " : "") + css;
return css;
}
function SetStyleFilterIE(elmt, value) {
if (browserRuntimeVersion < 9) {
elmt.style.filter = value;
}
}
function SetStyleMatrixIE(elmt, matrix, offset) {
//matrix is not for ie9+ running in ie8- mode
if (browserJavascriptVersion < 9) {
var oldFilterValue = elmt.style.filter;
var matrixReg = new RegExp(/[\s]*progid:DXImageTransform\.Microsoft\.Matrix\([^\)]*\)/g);
var matrixValue = matrix ? "progid:DXImageTransform.Microsoft.Matrix(" + "M11=" + matrix[0][0] + ", M12=" + matrix[0][1] + ", M21=" + matrix[1][0] + ", M22=" + matrix[1][1] + ", SizingMethod='auto expand')" : "";
var newFilterValue = BuildNewCss(oldFilterValue, [matrixReg], matrixValue);
SetStyleFilterIE(elmt, newFilterValue);
_This.$CssMarginTop(elmt, offset.y);
_This.$CssMarginLeft(elmt, offset.x);
}
}
// Methods
_This.$IsBrowserIE = IsBrowserIE;
_This.$IsBrowserIeQuirks = IsBrowserIeQuirks;
_This.$IsBrowserFireFox = IsBrowserFireFox;
_This.$IsBrowserSafari = IsBrowserSafari;
_This.$IsBrowserChrome = IsBrowserChrome;
_This.$IsBrowserOpera = IsBrowserOpera;
_This.$IsBrowserBadTransform = IsBrowserBadTransform;
_This.$IsBrowserIe9Earlier = IsBrowserIe9Earlier;
_This.$BrowserVersion = function () {
return browserRuntimeVersion;
};
_This.$BrowserEngineVersion = function () {
return browserEngineVersion || browserRuntimeVersion;
};
_This.$WebKitVersion = function () {
DetectBrowser();
return webkitVersion;
};
_This.$Delay = Delay;
_This.$Inherit = function (instance, baseClass) {
baseClass.apply(instance, [].slice.call(arguments, 2));
return Extend({}, instance);
};
function Construct(instance, constructor) {
instance.constructor === Construct.caller && instance.$Construct && instance.$Construct();
}
_This.$Construct = Construct;
_This.$GetElement = function (elmt) {
if (_This.$IsString(elmt)) {
elmt = document.getElementById(elmt);
}
return elmt;
};
function GetEvent(event) {
return event || window.event;
}
GetEvent = GetEvent;
_This.$EventSrc = function (event) {
event = GetEvent(event);
return event.target || event.srcElement || document;
};
_This.$EventDst = function (event) {
event = GetEvent(event);
return event.relatedTarget || event.toElement;
};
_This.$MousePosition = function (event) {
event = GetEvent(event);
var body = document.body;
return {
x: event.pageX || event.clientX + (_DocElmt.scrollLeft || body.scrollLeft || 0) - (_DocElmt.clientLeft || body.clientLeft || 0) || 0,
y: event.pageY || event.clientY + (_DocElmt.scrollTop || body.scrollTop || 0) - (_DocElmt.clientTop || body.clientTop || 0) || 0
};
};
_This.$PageScroll = function () {
var body = document.body;
return {
x: (window.pageXOffset || _DocElmt.scrollLeft || body.scrollLeft || 0) - (_DocElmt.clientLeft || body.clientLeft || 0),
y: (window.pageYOffset || _DocElmt.scrollTop || body.scrollTop || 0) - (_DocElmt.clientTop || body.clientTop || 0)
};
};
_This.$WindowSize = function () {
var body = document.body;
return {
x: body.clientWidth || _DocElmt.clientWidth,
y: body.clientHeight || _DocElmt.clientHeight
};
};
//_This.$GetElementPosition = function (elmt) {
// elmt = _This.$GetElement(elmt);
// var result = Point();
// // technique from:
// // http://www.quirksmode.org/js/findpos.html
// // with special check for "fixed" elements.
// while (elmt) {
// result.x += elmt.offsetLeft;
// result.y += elmt.offsetTop;
// var isFixed = _This.$GetElementStyle(elmt).position == "fixed";
// if (isFixed) {
// result = result.$Plus(_This.$PageScroll(window));
// }
// elmt = getOffsetParent(elmt, isFixed);
// }
// return result;
//};
//_This.$GetMouseScroll = function (event) {
// event = GetEvent(event);
// var delta = 0; // default value
// // technique from:
// // http://blog.paranoidferret.com/index.php/2007/10/31/javascript-tutorial-the-scroll-wheel/
// if (typeof (event.wheelDelta) == "number") {
// delta = event.wheelDelta;
// } else if (typeof (event.detail) == "number") {
// delta = event.detail * -1;
// } else {
// $JssorDebug$.$Fail("Unknown event mouse scroll, no known technique.");
// }
// // normalize value to [-1, 1]
// return delta ? delta / Math.abs(delta) : 0;
//};
//_This.$MakeAjaxRequest = function (url, callback) {
// var async = typeof (callback) == "function";
// var req = null;
// if (async) {
// var actual = callback;
// var callback = function () {
// Delay($Jssor$.$CreateCallback(null, actual, req), 1);
// };
// }
// if (window.ActiveXObject) {
// for (var i = 0; i < arrActiveX.length; i++) {
// try {
// req = new ActiveXObject(arrActiveX[i]);
// break;
// } catch (e) {
// continue;
// }
// }
// } else if (window.XMLHttpRequest) {
// req = new XMLHttpRequest();
// }
// if (!req) {
// $JssorDebug$.$Fail("Browser doesn't support XMLHttpRequest.");
// }
// if (async) {
// req.onreadystatechange = function () {
// if (req.readyState == 4) {
// // prevent memory leaks by breaking circular reference now
// req.onreadystatechange = new Function();
// callback();
// }
// };
// }
// try {
// req.open("GET", url, async);
// req.send(null);
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while making AJAX request: " + e.message);
// req.onreadystatechange = null;
// req = null;
// if (async) {
// callback();
// }
// }
// return async ? null : req;
//};
//_This.$ParseXml = function (string) {
// var xmlDoc = null;
// if (window.ActiveXObject) {
// try {
// xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// xmlDoc.async = false;
// xmlDoc.loadXML(string);
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while parsing XML (ActiveX): " + e.message);
// }
// } else if (window.DOMParser) {
// try {
// var parser = new DOMParser();
// xmlDoc = parser.parseFromString(string, "text/xml");
// } catch (e) {
// $JssorDebug$.$Log(e.name + " while parsing XML (DOMParser): " + e.message);
// }
// } else {
// $JssorDebug$.$Fail("Browser doesn't support XML DOM.");
// }
// return xmlDoc;
//};
function Css(elmt, name, value) {
/// <summary>
/// access css
/// $Jssor$.$Css(elmt, name); //get css value
/// $Jssor$.$Css(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" optional="true">
/// the value to set
/// </param>
if (value != undefined) {
elmt.style[name] = value;
}
else {
var style = elmt.currentStyle || elmt.style;
value = style[name];
if (value == "" && window.getComputedStyle) {
style = elmt.ownerDocument.defaultView.getComputedStyle(elmt, null);
style && (value = style.getPropertyValue(name) || style[name]);
}
return value;
}
}
function CssN(elmt, name, value, isDimensional) {
/// <summary>
/// access css as numeric
/// $Jssor$.$CssN(elmt, name); //get css value
/// $Jssor$.$CssN(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" type="Number" optional="true">
/// the value to set
/// </param>
if (value != undefined) {
isDimensional && (value += "px");
Css(elmt, name, value);
}
else {
return ParseFloat(Css(elmt, name));
}
}
function CssP(elmt, name, value) {
/// <summary>
/// access css in pixel as numeric, like 'top', 'left', 'width', 'height'
/// $Jssor$.$CssP(elmt, name); //get css value
/// $Jssor$.$CssP(elmt, name, value); //set css value
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="name" type="String">
/// the name of css property
/// </param>
/// <param name="value" type="Number" optional="true">
/// the value to set
/// </param>
return CssN(elmt, name, value, true);
}
function CssProxy(name, numericOrDimension) {
/// <summary>
/// create proxy to access css, CssProxy(name[, numericOrDimension]);
/// </summary>
/// <param name="elmt" type="HTMLElement">
/// the element to access css
/// </param>
/// <param name="numericOrDimension" type="Number" optional="true">
/// not set: access original css, 1: access css as numeric, 2: access css in pixel as numeric
/// </param>
var isDimensional = numericOrDimension & 2;
var cssAccessor = numericOrDimension ? CssN : Css;
return function (elmt, value) {
return cssAccessor(elmt, name, value, isDimensional);
};
}
function GetStyleOpacity(elmt) {
if (IsBrowserIE() && browserEngineVersion < 9) {
var match = /opacity=([^)]*)/.exec(elmt.style.filter || "");
return match ? (ParseFloat(match[1]) / 100) : 1;
}
else
return ParseFloat(elmt.style.opacity || "1");
}
function SetStyleOpacity(elmt, opacity, ie9EarlierForce) {
if (IsBrowserIE() && browserEngineVersion < 9) {
//var filterName = "filter"; // browserEngineVersion < 8 ? "filter" : "-ms-filter";
var finalFilter = elmt.style.filter || "";
// for CSS filter browsers (IE), remove alpha filter if it's unnecessary.
// update: doing _This always since IE9 beta seems to have broken the
// behavior if we rely on the programmatic filters collection.
var alphaReg = new RegExp(/[\s]*alpha\([^\)]*\)/g);
// important: note the lazy star! _This protects against
// multiple filters; we don't want to delete the other ones.
// update: also trimming extra whitespace around filter.
var ieOpacity = Math.round(100 * opacity);
var alphaFilter = "";
if (ieOpacity < 100 || ie9EarlierForce) {
alphaFilter = "alpha(opacity=" + ieOpacity + ") ";
//elmt.style["-ms-filter"] = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + ieOpacity + ") ";
}
var newFilterValue = BuildNewCss(finalFilter, [alphaReg], alphaFilter);
SetStyleFilterIE(elmt, newFilterValue);
}
//if (!IsBrowserIE() || browserEngineVersion >= 9)
else {
elmt.style.opacity = opacity == 1 ? "" : Math.round(opacity * 100) / 100;
}
}
function SetStyleTransformInternal(elmt, transform) {
var rotate = transform.$Rotate || 0;
var scale = transform.$Scale == undefined ? 1 : transform.$Scale;
if (IsBrowserIe9Earlier()) {
var matrix = _This.$CreateMatrix(rotate / 180 * Math.PI, scale, scale);
SetStyleMatrixIE(elmt, (!rotate && scale == 1) ? null : matrix, _This.$GetMatrixOffset(matrix, transform.$OriginalWidth, transform.$OriginalHeight));
}
else {
//rotate(15deg) scale(.5) translateZ(0)
var transformProperty = GetTransformProperty(elmt);
if (transformProperty) {
var transformValue = "rotate(" + rotate % 360 + "deg) scale(" + scale + ")";
if (IsBrowserChrome() && webkitVersion > 535)
transformValue += " perspective(2000px)";
elmt.style[transformProperty] = transformValue;
}
}
}
_This.$SetStyleTransform = function (elmt, transform) {
if (IsBrowserBadTransform()) {
Delay(_This.$CreateCallback(null, SetStyleTransformInternal, elmt, transform));
}
else {
SetStyleTransformInternal(elmt, transform);
}
};
_This.$SetStyleTransformOrigin = function (elmt, transformOrigin) {
var transformProperty = GetTransformProperty(elmt);
if (transformProperty)
elmt.style[transformProperty + "Origin"] = transformOrigin;
};
_This.$CssScale = function (elmt, scale) {
if (IsBrowserIE() && browserEngineVersion < 9 || (browserEngineVersion < 10 && IsBrowserIeQuirks())) {
elmt.style.zoom = (scale == 1) ? "" : scale;
}
else {
var transformProperty = GetTransformProperty(elmt);
if (transformProperty) {
//rotate(15deg) scale(.5)
var transformValue = "scale(" + scale + ")";
var oldTransformValue = elmt.style[transformProperty];
var scaleReg = new RegExp(/[\s]*scale\(.*?\)/g);
var newTransformValue = BuildNewCss(oldTransformValue, [scaleReg], transformValue);
elmt.style[transformProperty] = newTransformValue;
}
}
};
_This.$EnableHWA = function (elmt) {
if (!elmt.style[GetTransformProperty(elmt)] || elmt.style[GetTransformProperty(elmt)] == "none")
elmt.style[GetTransformProperty(elmt)] = "perspective(2000px)";
};
_This.$DisableHWA = function (elmt) {
//if (force || elmt.style[GetTransformProperty(elmt)] == "perspective(2000px)")
elmt.style[GetTransformProperty(elmt)] = "none";
};
var ie8OffsetWidth = 0;
var ie8OffsetHeight = 0;
//var ie8WindowResizeCallbackHandlers;
//var ie8LastVerticalScrollbar;
//var toggleInfo = "";
//function Ie8WindowResizeFilter(window, handler) {
// var trigger = true;
// var checkElement = (IsBrowserIeQuirks() ? window.document.body : window.document.documentElement);
// if (checkElement) {
// //check vertical bar
// //var hasVerticalBar = checkElement.scrollHeight > checkElement.clientHeight;
// //var verticalBarToggle = hasVerticalBar != ie8LastVerticalScrollbar;
// //ie8LastVerticalScrollbar = hasVerticalBar;
// var widthChange = checkElement.offsetWidth - ie8OffsetWidth;
// var heightChange = checkElement.offsetHeight - ie8OffsetHeight;
// if (widthChange || heightChange) {
// ie8OffsetWidth += widthChange;
// ie8OffsetHeight += heightChange;
// }
// else
// trigger = false;
// }
// trigger && handler();
//}
//_This.$OnWindowResize = function (window, handler) {
// if (IsBrowserIE() && browserEngineVersion < 9) {
// if (!ie8WindowResizeCallbackHandlers) {
// ie8WindowResizeCallbackHandlers = [handler];
// handler = _This.$CreateCallback(null, Ie8WindowResizeFilter, window);
// }
// else {
// ie8WindowResizeCallbackHandlers.push(handler);
// return;
// }
// }
// _This.$AddEvent(window, "resize", handler);
//};
_This.$WindowResizeFilter = function (window, handler) {
return IsBrowserIe9Earlier() ? function () {
var trigger = true;
var checkElement = (IsBrowserIeQuirks() ? window.document.body : window.document.documentElement);
if (checkElement) {
//check vertical bar
//var hasVerticalBar = checkElement.scrollHeight > checkElement.clientHeight;
//var verticalBarToggle = hasVerticalBar != ie8LastVerticalScrollbar;
//ie8LastVerticalScrollbar = hasVerticalBar;
var widthChange = checkElement.offsetWidth - ie8OffsetWidth;
var heightChange = checkElement.offsetHeight - ie8OffsetHeight;
if (widthChange || heightChange) {
ie8OffsetWidth += widthChange;
ie8OffsetHeight += heightChange;
}
else
trigger = false;
}
trigger && handler();
} : handler;
};
_This.$MouseOverOutFilter = function (handler, target) {
/// <param name="target" type="HTMLDomElement">
/// The target element to detect mouse over/out events. (for ie < 9 compatibility)
/// </param>
$JssorDebug$.$Execute(function () {
if (!target) {
throw new Error("Null reference, parameter \"target\".");
}
});
return function (event) {
event = GetEvent(event);
var eventName = event.type;
var related = event.relatedTarget || (eventName == "mouseout" ? event.toElement : event.fromElement);
if (!related || (related !== target && !_This.$IsChild(target, related))) {
handler(event);
}
};
};
_This.$AddEvent = function (elmt, eventName, handler, useCapture) {
elmt = _This.$GetElement(elmt);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (elmt.addEventListener) {
if (eventName == "mousewheel") {
elmt.addEventListener("DOMMouseScroll", handler, useCapture);
}
// we are still going to add the mousewheel -- not a mistake!
// _This is for opera, since it uses onmousewheel but needs addEventListener.
elmt.addEventListener(eventName, handler, useCapture);
}
else if (elmt.attachEvent) {
elmt.attachEvent("on" + eventName, handler);
if (useCapture && elmt.setCapture) {
elmt.setCapture();
}
}
$JssorDebug$.$Execute(function () {
if (!elmt.addEventListener && !elmt.attachEvent) {
$JssorDebug$.$Fail("Unable to attach event handler, no known technique.");
}
});
};
_This.$RemoveEvent = function (elmt, eventName, handler, useCapture) {
elmt = _This.$GetElement(elmt);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (elmt.removeEventListener) {
if (eventName == "mousewheel") {
elmt.removeEventListener("DOMMouseScroll", handler, useCapture);
}
// we are still going to remove the mousewheel -- not a mistake!
// _This is for opera, since it uses onmousewheel but needs removeEventListener.
elmt.removeEventListener(eventName, handler, useCapture);
}
else if (elmt.detachEvent) {
elmt.detachEvent("on" + eventName, handler);
if (useCapture && elmt.releaseCapture) {
elmt.releaseCapture();
}
}
};
_This.$FireEvent = function (elmt, eventName) {
//var document = elmt.document;
$JssorDebug$.$Execute(function () {
if (!document.createEvent && !document.createEventObject) {
$JssorDebug$.$Fail("Unable to fire event, no known technique.");
}
if (!elmt.dispatchEvent && !elmt.fireEvent) {
$JssorDebug$.$Fail("Unable to fire event, no known technique.");
}
});
var evento;
if (document.createEvent) {
evento = document.createEvent("HTMLEvents");
evento.initEvent(eventName, false, false);
elmt.dispatchEvent(evento);
}
else {
var ieEventName = "on" + eventName;
evento = document.createEventObject();
//event.eventType = ieEventName;
//event.eventName = ieEventName;
elmt.fireEvent(ieEventName, evento);
}
};
_This.$AddEventBrowserMouseUp = function (handler, userCapture) {
_This.$AddEvent((IsBrowserIe9Earlier()) ? document : window, "mouseup", handler, userCapture);
};
_This.$RemoveEventBrowserMouseUp = function (handler, userCapture) {
_This.$RemoveEvent((IsBrowserIe9Earlier()) ? document : window, "mouseup", handler, userCapture);
};
//_This.$AddEventBrowserMouseDown = function (handler, userCapture) {
// _This.$AddEvent((IsBrowserIe9Earlier()) ? document : window, "mousedown", handler, userCapture);
//};
//_This.$RemoveEventBrowserMouseDown = function (handler, userCapture) {
// _This.$RemoveEvent((IsBrowserIe9Earlier()) ? document : window, "mousedown", handler, userCapture);
//};
_This.$CancelEvent = function (event) {
event = GetEvent(event);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (event.preventDefault) {
event.preventDefault(); // W3C for preventing default
}
event.cancel = true; // legacy for preventing default
event.returnValue = false; // IE for preventing default
};
_This.$StopEvent = function (event) {
event = GetEvent(event);
// technique from:
// http://blog.paranoidferret.com/index.php/2007/08/10/javascript-working-with-events/
if (event.stopPropagation) {
event.stopPropagation(); // W3C for stopping propagation
}
event.cancelBubble = true; // IE for stopping propagation
};
_This.$CreateCallback = function (object, method) {
// create callback args
var initialArgs = [].slice.call(arguments, 2);
// create closure to apply method
var callback = function () {
// concatenate new args, but make a copy of initialArgs first
var args = initialArgs.concat([].slice.call(arguments, 0));
return method.apply(object, args);
};
//$JssorDebug$.$LiveStamp(callback, "callback_" + ($Jssor$.$GetNow() & 0xFFFFFF));
return callback;
};
var _Freeer;
_This.$FreeElement = function (elmt) {
if (!_Freeer)
_Freeer = _This.$CreateDiv();
if (elmt) {
$Jssor$.$AppendChild(_Freeer, elmt);
$Jssor$.$ClearInnerHtml(_Freeer);
}
};
_This.$InnerText = function (elmt, text) {
if (text == undefined)
return elmt.textContent || elmt.innerText;
var textNode = document.createTextNode(text);
_This.$ClearInnerHtml(elmt);
elmt.appendChild(textNode);
};
_This.$InnerHtml = function (elmt, html) {
if (html == undefined)
return elmt.innerHTML;
elmt.innerHTML = html;
};
_This.$GetClientRect = function (elmt) {
var rect = elmt.getBoundingClientRect();
return { x: rect.left, y: rect.top, w: rect.right - rect.left, h: rect.bottom - rect.top };
};
_This.$ClearInnerHtml = function (elmt) {
elmt.innerHTML = "";
};
_This.$EncodeHtml = function (text) {
var div = _This.$CreateDiv();
_This.$InnerText(div, text);
return _This.$InnerHtml(div);
};
_This.$DecodeHtml = function (html) {
var div = _This.$CreateDiv();
_This.$InnerHtml(div, html);
return _This.$InnerText(div);
};
_This.$SelectElement = function (elmt) {
var userSelection;
if (window.getSelection) {
//W3C default
userSelection = window.getSelection();
}
var theRange = null;
if (document.createRange) {
theRange = document.createRange();
theRange.selectNode(elmt);
}
else {
theRange = document.body.createTextRange();
theRange.moveToElementText(elmt);
theRange.select();
}
//set user selection
if (userSelection)
userSelection.addRange(theRange);
};
_This.$DeselectElements = function () {
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
};
_This.$Children = function (elmt) {
var children = [];
for (var tmpEl = elmt.firstChild; tmpEl; tmpEl = tmpEl.nextSibling) {
if (tmpEl.nodeType == 1) {
children.push(tmpEl);
}
}
return children;
};
function FindChild(elmt, attrValue, noDeep, attrName) {
attrName = attrName || "u";
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (AttributeEx(elmt, attrName) == attrValue)
return elmt;
if (!noDeep) {
var childRet = FindChild(elmt, attrValue, noDeep, attrName);
if (childRet)
return childRet;
}
}
}
}
_This.$FindChild = FindChild;
function FindChildren(elmt, attrValue, noDeep, attrName) {
attrName = attrName || "u";
var ret = [];
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (AttributeEx(elmt, attrName) == attrValue)
ret.push(elmt);
if (!noDeep) {
var childRet = FindChildren(elmt, attrValue, noDeep, attrName);
if (childRet.length)
ret = ret.concat(childRet);
}
}
}
return ret;
}
_This.$FindChildren = FindChildren;
function FindChildByTag(elmt, tagName, noDeep) {
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (elmt.tagName == tagName)
return elmt;
if (!noDeep) {
var childRet = FindChildByTag(elmt, tagName, noDeep);
if (childRet)
return childRet;
}
}
}
}
_This.$FindChildByTag = FindChildByTag;
function FindChildrenByTag(elmt, tagName, noDeep) {
var ret = [];
for (elmt = elmt ? elmt.firstChild : null; elmt; elmt = elmt.nextSibling) {
if (elmt.nodeType == 1) {
if (!tagName || elmt.tagName == tagName)
ret.push(elmt);
if (!noDeep) {
var childRet = FindChildrenByTag(elmt, tagName, noDeep);
if (childRet.length)
ret = ret.concat(childRet);
}
}
}
return ret;
}
_This.$FindChildrenByTag = FindChildrenByTag;
_This.$GetElementsByTag = function (elmt, tagName) {
return elmt.getElementsByTagName(tagName);
};
function Extend(target) {
for (var i = 1; i < arguments.length; i++) {
var options = arguments[i];
// Only deal with non-null/undefined values
if (options) {
// Extend the base object
for (var name in options) {
target[name] = options[name];
}
}
}
// Return the modified object
return target;
}
_This.$Extend = Extend;
function Unextend(target, options) {
$JssorDebug$.$Assert(options);
var unextended = {};
// Extend the base object
for (var name in target) {
if (target[name] != options[name]) {
unextended[name] = target[name];
}
}
// Return the modified object
return unextended;
}
_This.$Unextend = Unextend;
_This.$IsUndefined = function (obj) {
return type(obj) == "undefined";
};
_This.$IsFunction = function (obj) {
return type(obj) == "function";
};
_This.$IsArray = function (obj) {
return type(obj) == "array";
};
_This.$IsString = function (obj) {
return type(obj) == "string";
};
_This.$IsNumeric = function (obj) {
return !isNaN(ParseFloat(obj)) && isFinite(obj);
};
_This.$IsWindow = function (obj) {
return obj && obj == obj.window;
};
_This.$Type = type;
// args is for internal usage only
_This.$Each = each;
_This.$IsPlainObject = isPlainObject;
function CreateElement(tagName) {
return document.createElement(tagName);
}
_This.$CreateElement = CreateElement;
_This.$CreateDiv = function () {
return CreateElement("DIV", document);
};
_This.$CreateSpan = function () {
return CreateElement("SPAN", document);
};
_This.$EmptyFunction = function () { };
function Attribute(elmt, name, value) {
if (value == undefined)
return elmt.getAttribute(name);
elmt.setAttribute(name, value);
}
function AttributeEx(elmt, name) {
return Attribute(elmt, name) || Attribute(elmt, "data-" + name);
}
_This.$Attribute = Attribute;
_This.$AttributeEx = AttributeEx;
function ClassName(elmt, className) {
if (className == undefined)
return elmt.className;
elmt.className = className;
}
_This.$ClassName = ClassName;
function ToHash(array) {
var hash = {};
each(array, function (item) {
hash[item] = item;
});
return hash;
}
_This.$ToHash = ToHash;
function Join(separator, strings) {
/// <param name="separator" type="String">
/// The element to show the dialog around
/// </param>
/// <param name="strings" type="Array" value="['1']">
/// The element to show the dialog around
/// </param>
var joined = "";
each(strings, function (str) {
joined && (joined += separator);
joined += str;
});
return joined;
}
_This.$Join = Join;
_This.$AddClass = function (elmt, className) {
var newClassName = ClassName(elmt) + " " + className;
ClassName(elmt, Join(" ", ToHash(newClassName.match(REGEX_WHITESPACE_GLOBAL))));
};
_This.$RemoveClass = function (elmt, className) {
ClassName(elmt, Join(" ", _This.$Unextend(ToHash(ClassName(elmt).match(REGEX_WHITESPACE_GLOBAL)), ToHash(className.match(REGEX_WHITESPACE_GLOBAL)))));
};
_This.$ParentNode = function (elmt) {
return elmt.parentNode;
};
_This.$HideElement = function (elmt) {
_This.$CssDisplay(elmt, "none");
};
_This.$HideElements = function (elmts) {
for (var i = 0; i < elmts.length; i++) {
_This.$HideElement(elmts[i]);
}
};
_This.$ShowElement = function (elmt, hide) {
_This.$CssDisplay(elmt, hide ? "none" : "");
};
_This.$ShowElements = function (elmts, hide) {
for (var i = 0; i < elmts.length; i++) {
_This.$ShowElement(elmts[i], hide);
}
};
_This.$RemoveAttribute = function (elmt, attrbuteName) {
elmt.removeAttribute(attrbuteName);
};
_This.$CanClearClip = function () {
return IsBrowserIE() && browserRuntimeVersion < 10;
};
_This.$SetStyleClip = function (elmt, clip) {
if (clip) {
elmt.style.clip = "rect(" + Math.round(clip.$Top) + "px " + Math.round(clip.$Right) + "px " + Math.round(clip.$Bottom) + "px " + Math.round(clip.$Left) + "px)";
}
else {
var cssText = elmt.style.cssText;
var clipRegs = [
new RegExp(/[\s]*clip: rect\(.*?\)[;]?/i),
new RegExp(/[\s]*cliptop: .*?[;]?/i),
new RegExp(/[\s]*clipright: .*?[;]?/i),
new RegExp(/[\s]*clipbottom: .*?[;]?/i),
new RegExp(/[\s]*clipleft: .*?[;]?/i)
];
var newCssText = BuildNewCss(cssText, clipRegs, "");
$Jssor$.$CssCssText(elmt, newCssText);
}
};
_This.$GetNow = function () {
return new Date().getTime();
};
_This.$AppendChild = function (elmt, child) {
elmt.appendChild(child);
};
_This.$AppendChildren = function (elmt, children) {
each(children, function (child) {
_This.$AppendChild(elmt, child);
});
};
_This.$InsertBefore = function (elmt, child, refObject) {
elmt.insertBefore(child, refObject);
};
_This.$InsertAdjacentHtml = function (elmt, where, text) {
elmt.insertAdjacentHTML(where, text);
};
_This.$RemoveChild = function (elmt, child) {
elmt.removeChild(child);
};
_This.$RemoveChildren = function (elmt, children) {
each(children, function (child) {
_This.$RemoveChild(elmt, child);
});
};
_This.$ClearChildren = function (elmt) {
_This.$RemoveChildren(elmt, _This.$Children(elmt));
};
_This.$ParseInt = function (str, radix) {
return parseInt(str, radix || 10);
};
function ParseFloat(str) {
return parseFloat(str);
}
_This.$ParseFloat = ParseFloat;
_This.$IsChild = function (elmtA, elmtB) {
var body = document.body;
while (elmtB && elmtA != elmtB && body != elmtB) {
try {
elmtB = elmtB.parentNode;
} catch (e) {
// Firefox sometimes fires events for XUL elements, which throws
// a "permission denied" error. so this is not a child.
return false;
}
}
return elmtA == elmtB;
};
function CloneNode(elmt, noDeep) {
return elmt.cloneNode(!noDeep);
}
_This.$CloneNode = CloneNode;
function TranslateTransition(transition) {
if (transition) {
var flyDirection = transition.$FlyDirection;
if (flyDirection & 1) {
transition.x = transition.$ScaleHorizontal || 1;
}
if (flyDirection & 2) {
transition.x = -transition.$ScaleHorizontal || -1;
}
if (flyDirection & 4) {
transition.y = transition.$ScaleVertical || 1;
}
if (flyDirection & 8) {
transition.y = -transition.$ScaleVertical || -1;
}
if (transition.$Rotate == true)
transition.$Rotate = 1;
TranslateTransition(transition.$Brother);
}
}
_This.$TranslateTransitions = function (transitions) {
/// <summary>
/// For backward compatibility only.
/// </summary>
if (transitions) {
for (var i = 0; i < transitions.length; i++) {
TranslateTransition(transitions[i]);
}
for (var name in transitions) {
TranslateTransition(transitions[name]);
}
}
};
//function ImageLoader() {
// var _ThisImageLoader = this;
// var _BaseImageLoader = _This.$Inherit(_ThisImageLoader, $JssorObject$);
// var _ImageLoading = 1;
// var _MainImageSrc;
// var _MainImage;
// var _CompleteCallback;
// var _MainImageAbort;
// function LoadCompleteCallback(image, abort) {
// _ImageLoading--;
// if (image) {
// _This.$RemoveEvent(image, "load");
// _This.$RemoveEvent(image, "abort");
// _This.$RemoveEvent(image, "error");
// if (_MainImageSrc == image.src) {
// _MainImage = image;
// _MainImageAbort = abort;
// }
// }
// _CompleteCallback && _CompleteCallback(_MainImage, _MainImageAbort);
// }
// function LoadImage(src) {
// _ImageLoading++;
// if (IsBrowserOpera() && browserRuntimeVersion < 11.6 || !src) {
// LoadImageCallback(callback, null, !src);
// }
// else {
// var image = new Image();
// _This.$AddEvent(image, "load", _This.$CreateCallback(null, LoadImageCallback, image, false));
// var abortHandler = _This.$CreateCallback(null, LoadImageCallback, image, true);
// _This.$AddEvent(image, "abort", abortHandler);
// _This.$AddEvent(image, "error", abortHandler);
// image.src = src;
// }
// }
// _ThisImageLoader.$LoadImage = function (src, callback) {
// _MainImageSrc = src;
// _CompleteCallback = callback;
// LoadImage(src);
// LoadComplete();
// };
// _ThisImageLoader.$LoadImages = function (imageElmts, mainImageElmt, callback) {
// mainImageElmt && (_MainImageSrc = mainImageElmt.src);
// _CompleteCallback = callback;
// each(imageElmts, function (imageElmt) {
// LoadImage(imageElmt.src);
// });
// LoadComplete();
// };
//}
_This.$LoadImage = function (src, callback) {
var image = new Image();
function LoadImageCompleteHandler(abort) {
_This.$RemoveEvent(image, "load", LoadImageCompleteHandler);
_This.$RemoveEvent(image, "abort", ErrorOrAbortHandler);
_This.$RemoveEvent(image, "error", ErrorOrAbortHandler);
if (callback)
callback(image, abort);
}
function ErrorOrAbortHandler() {
LoadImageCompleteHandler(true);
}
if (IsBrowserOpera() && browserRuntimeVersion < 11.6 || !src) {
LoadImageCompleteHandler(!src);
}
else {
_This.$AddEvent(image, "load", LoadImageCompleteHandler);
_This.$AddEvent(image, "abort", ErrorOrAbortHandler);
_This.$AddEvent(image, "error", ErrorOrAbortHandler);
image.src = src;
}
};
_This.$LoadImages = function (imageElmts, mainImageElmt, callback) {
var _ImageLoading = imageElmts.length + 1;
function LoadImageCompleteEventHandler(image, abort) {
_ImageLoading--;
if (mainImageElmt && image && image.src == mainImageElmt.src)
mainImageElmt = image;
!_ImageLoading && callback && callback(mainImageElmt);
}
each(imageElmts, function (imageElmt) {
_This.$LoadImage(imageElmt.src, LoadImageCompleteEventHandler);
});
LoadImageCompleteEventHandler();
};
_This.$BuildElement = function (template, tagName, replacer, createCopy) {
if (createCopy)
template = CloneNode(template);
var templateHolders = $Jssor$.$GetElementsByTag(template, tagName);
for (var j = templateHolders.length -1; j > -1; j--) {
var templateHolder = templateHolders[j];
var replaceItem = CloneNode(replacer);
ClassName(replaceItem, ClassName(templateHolder));
$Jssor$.$CssCssText(replaceItem, templateHolder.style.cssText);
var thumbnailPlaceHolderParent = $Jssor$.$ParentNode(templateHolder);
$Jssor$.$InsertBefore(thumbnailPlaceHolderParent, replaceItem, templateHolder);
$Jssor$.$RemoveChild(thumbnailPlaceHolderParent, templateHolder);
}
return template;
};
var _MouseDownButtons;
function JssorButtonEx(elmt) {
var _Self = this;
var _OriginClassName;
var _IsMouseDown; //class name 'dn'
var _IsActive; //class name 'av'
var _IsDisabled; //class name 'ds'
function Highlight() {
var className = _OriginClassName;
if (_IsDisabled) {
className += 'ds';
}
else if (_IsMouseDown) {
className += 'dn';
}
else if (_IsActive) {
className += "av";
}
ClassName(elmt, className);
}
function OnMouseDown(event) {
if (_IsDisabled) {
_This.$CancelEvent(event);
}
else {
_MouseDownButtons.push(_Self);
_IsMouseDown = true;
Highlight();
}
}
_Self.$MouseUp = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
_IsMouseDown = false;
Highlight();
};
_Self.$Activate = function (activate) {
if (activate != undefined) {
_IsActive = activate;
Highlight();
}
else {
return _IsActive;
}
};
_Self.$Enable = function (enable) {
if (enable != undefined) {
_IsDisabled = !enable;
Highlight();
}
else {
return !_IsDisabled;
}
};
//JssorButtonEx Constructor
{
elmt = _This.$GetElement(elmt);
if (!_MouseDownButtons) {
_This.$AddEventBrowserMouseUp(function () {
var oldMouseDownButtons = _MouseDownButtons;
_MouseDownButtons = [];
each(oldMouseDownButtons, function (button) {
button.$MouseUp();
});
});
_MouseDownButtons = [];
}
_OriginClassName = ClassName(elmt);
$Jssor$.$AddEvent(elmt, "mousedown", OnMouseDown);
}
}
_This.$Buttonize = function (elmt) {
return new JssorButtonEx(elmt);
};
_This.$Css = Css;
_This.$CssN = CssN;
_This.$CssP = CssP;
_This.$CssOverflow = CssProxy("overflow");
_This.$CssTop = CssProxy("top", 2);
_This.$CssLeft = CssProxy("left", 2);
_This.$CssWidth = CssProxy("width", 2);
_This.$CssHeight = CssProxy("height", 2);
_This.$CssMarginLeft = CssProxy("marginLeft", 2);
_This.$CssMarginTop = CssProxy("marginTop", 2);
_This.$CssPosition = CssProxy("position");
_This.$CssDisplay = CssProxy("display");
_This.$CssZIndex = CssProxy("zIndex", 1);
_This.$CssFloat = function (elmt, float) {
return Css(elmt, IsBrowserIE() ? "styleFloat" : "cssFloat", float);
};
_This.$CssOpacity = function (elmt, opacity, ie9EarlierForce) {
if (opacity != undefined) {
SetStyleOpacity(elmt, opacity, ie9EarlierForce);
}
else {
return GetStyleOpacity(elmt);
}
};
_This.$CssCssText = function (elmt, text) {
if (text != undefined) {
elmt.style.cssText = text;
}
else {
return elmt.style.cssText;
}
};
var _StyleGetter = {
$Opacity: _This.$CssOpacity,
$Top: _This.$CssTop,
$Left: _This.$CssLeft,
$Width: _This.$CssWidth,
$Height: _This.$CssHeight,
$Position: _This.$CssPosition,
$Display: _This.$CssDisplay,
$ZIndex: _This.$CssZIndex
};
var _StyleSetterReserved;
function StyleSetter() {
if (!_StyleSetterReserved) {
_StyleSetterReserved = Extend({
$MarginTop: _This.$CssMarginTop,
$MarginLeft: _This.$CssMarginLeft,
$Clip: _This.$SetStyleClip,
$Transform: _This.$SetStyleTransform
}, _StyleGetter);
}
return _StyleSetterReserved;
}
function StyleSetterEx() {
StyleSetter();
//For Compression Only
_StyleSetterReserved.$Transform = _StyleSetterReserved.$Transform;
return _StyleSetterReserved;
}
_This.$StyleSetter = StyleSetter;
_This.$StyleSetterEx = StyleSetterEx;
_This.$GetStyles = function (elmt, originStyles) {
StyleSetter();
var styles = {};
each(originStyles, function (value, key) {
if (_StyleGetter[key]) {
styles[key] = _StyleGetter[key](elmt);
}
});
return styles;
};
_This.$SetStyles = function (elmt, styles) {
var styleSetter = StyleSetter();
each(styles, function (value, key) {
styleSetter[key] && styleSetter[key](elmt, value);
});
};
_This.$SetStylesEx = function (elmt, styles) {
StyleSetterEx();
_This.$SetStyles(elmt, styles);
};
$JssorMatrix$ = new function () {
var _ThisMatrix = this;
function Multiply(ma, mb) {
var acs = ma[0].length;
var rows = ma.length;
var cols = mb[0].length;
var matrix = [];
for (var r = 0; r < rows; r++) {
var row = matrix[r] = [];
for (var c = 0; c < cols; c++) {
var unitValue = 0;
for (var ac = 0; ac < acs; ac++) {
unitValue += ma[r][ac] * mb[ac][c];
}
row[c] = unitValue;
}
}
return matrix;
}
_ThisMatrix.$ScaleX = function (matrix, sx) {
return _ThisMatrix.$ScaleXY(matrix, sx, 0);
};
_ThisMatrix.$ScaleY = function (matrix, sy) {
return _ThisMatrix.$ScaleXY(matrix, 0, sy);
};
_ThisMatrix.$ScaleXY = function (matrix, sx, sy) {
return Multiply(matrix, [[sx, 0], [0, sy]]);
};
_ThisMatrix.$TransformPoint = function (matrix, p) {
var pMatrix = Multiply(matrix, [[p.x], [p.y]]);
return Point(pMatrix[0][0], pMatrix[1][0]);
};
};
_This.$CreateMatrix = function (alpha, scaleX, scaleY) {
var cos = Math.cos(alpha);
var sin = Math.sin(alpha);
//var r11 = cos;
//var r21 = sin;
//var r12 = -sin;
//var r22 = cos;
//var m11 = cos * scaleX;
//var m12 = -sin * scaleY;
//var m21 = sin * scaleX;
//var m22 = cos * scaleY;
return [[cos * scaleX, -sin * scaleY], [sin * scaleX, cos * scaleY]];
};
_This.$GetMatrixOffset = function (matrix, width, height) {
var p1 = $JssorMatrix$.$TransformPoint(matrix, Point(-width / 2, -height / 2));
var p2 = $JssorMatrix$.$TransformPoint(matrix, Point(width / 2, -height / 2));
var p3 = $JssorMatrix$.$TransformPoint(matrix, Point(width / 2, height / 2));
var p4 = $JssorMatrix$.$TransformPoint(matrix, Point(-width / 2, height / 2));
return Point(Math.min(p1.x, p2.x, p3.x, p4.x) + width / 2, Math.min(p1.y, p2.y, p3.y, p4.y) + height / 2);
};
_This.$Transform = function (fromStyles, toStyles, interPosition, easings, durings, rounds, options) {
var currentStyles = toStyles;
if (fromStyles) {
currentStyles = {};
for (var key in toStyles) {
var round = rounds[key] || 1;
var during = durings[key] || [0, 1];
var propertyInterPosition = (interPosition - during[0]) / during[1];
propertyInterPosition = Math.min(Math.max(propertyInterPosition, 0), 1);
propertyInterPosition = propertyInterPosition * round;
var floorPosition = Math.floor(propertyInterPosition);
if (propertyInterPosition != floorPosition)
propertyInterPosition -= floorPosition;
var easing = easings[key] || easings.$Default;
var easingValue = easing(propertyInterPosition);
var currentPropertyValue;
var value = fromStyles[key];
var toValue = toStyles[key];
if ($Jssor$.$IsNumeric(toValue)) {
currentPropertyValue = value + (toValue - value) * easingValue;
}
else {
currentPropertyValue = $Jssor$.$Extend({ $Offset: {} }, fromStyles[key]);
$Jssor$.$Each(toValue.$Offset, function (rectX, n) {
var offsetValue = rectX * easingValue;
currentPropertyValue.$Offset[n] = offsetValue;
currentPropertyValue[n] += offsetValue;
});
}
currentStyles[key] = currentPropertyValue;
}
if (fromStyles.$Zoom) {
currentStyles.$Transform = { $Rotate: currentStyles.$Rotate || 0, $Scale: currentStyles.$Zoom, $OriginalWidth: options.$OriginalWidth, $OriginalHeight: options.$OriginalHeight };
}
}
if (toStyles.$Clip && options.$Move) {
var styleFrameNClipOffset = currentStyles.$Clip.$Offset;
var offsetY = (styleFrameNClipOffset.$Top || 0) + (styleFrameNClipOffset.$Bottom || 0);
var offsetX = (styleFrameNClipOffset.$Left || 0) + (styleFrameNClipOffset.$Right || 0);
currentStyles.$Left = (currentStyles.$Left || 0) + offsetX;
currentStyles.$Top = (currentStyles.$Top || 0) + offsetY;
currentStyles.$Clip.$Left -= offsetX;
currentStyles.$Clip.$Right -= offsetX;
currentStyles.$Clip.$Top -= offsetY;
currentStyles.$Clip.$Bottom -= offsetY;
}
if (currentStyles.$Clip && $Jssor$.$CanClearClip() && !currentStyles.$Clip.$Top && !currentStyles.$Clip.$Left && (currentStyles.$Clip.$Right == options.$OriginalWidth) && (currentStyles.$Clip.$Bottom == options.$OriginalHeight))
currentStyles.$Clip = null;
return currentStyles;
};
};
//$JssorObject$
var $JssorObject$ = window.$JssorObject$ = function () {
var _ThisObject = this;
// Fields
var _Listeners = []; // dictionary of eventName --> array of handlers
var _Listenees = [];
// Private Methods
function AddListener(eventName, handler) {
$JssorDebug$.$Execute(function () {
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
$Jssor$.$Each(_Listeners, function (listener) {
if (listener.$EventName == eventName && listener.$Handler === handler) {
throw new Error("The handler listened to the event already, cannot listen to the same event of the same object with the same handler twice.");
}
});
});
_Listeners.push({ $EventName: eventName, $Handler: handler });
}
function RemoveListener(eventName, handler) {
$JssorDebug$.$Execute(function () {
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
});
$Jssor$.$Each(_Listeners, function (listener, index) {
if (listener.$EventName == eventName && listener.$Handler === handler) {
_Listeners.splice(index, 1);
}
});
}
function ClearListeners() {
_Listeners = [];
}
function ClearListenees() {
$Jssor$.$Each(_Listenees, function (listenee) {
$Jssor$.$RemoveEvent(listenee.$Obj, listenee.$EventName, listenee.$Handler);
});
_Listenees = [];
}
//Protected Methods
_ThisObject.$Listen = function (obj, eventName, handler, useCapture) {
$JssorDebug$.$Execute(function () {
if (!obj)
throw new Error("param 'obj' is null or empty.");
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
$Jssor$.$Each(_Listenees, function (listenee) {
if (listenee.$Obj === obj && listenee.$EventName == eventName && listenee.$Handler === handler) {
throw new Error("The handler listened to the event already, cannot listen to the same event of the same object with the same handler twice.");
}
});
});
$Jssor$.$AddEvent(obj, eventName, handler, useCapture);
_Listenees.push({ $Obj: obj, $EventName: eventName, $Handler: handler });
};
_ThisObject.$Unlisten = function (obj, eventName, handler) {
$JssorDebug$.$Execute(function () {
if (!obj)
throw new Error("param 'obj' is null or empty.");
if (eventName == undefined || eventName == null)
throw new Error("param 'eventName' is null or empty.");
if (typeof (handler) != "function") {
throw "param 'handler' must be a function.";
}
});
$Jssor$.$Each(_Listenees, function (listenee, index) {
if (listenee.$Obj === obj && listenee.$EventName == eventName && listenee.$Handler === handler) {
$Jssor$.$RemoveEvent(obj, eventName, handler);
_Listenees.splice(index, 1);
}
});
};
_ThisObject.$UnlistenAll = ClearListenees;
// Public Methods
_ThisObject.$On = _ThisObject.addEventListener = AddListener;
_ThisObject.$Off = _ThisObject.removeEventListener = RemoveListener;
_ThisObject.$TriggerEvent = function (eventName) {
var args = [].slice.call(arguments, 1);
$Jssor$.$Each(_Listeners, function (listener) {
try {
listener.$EventName == eventName && listener.$Handler.apply(window, args);
} catch (e) {
// handler threw an error, ignore, go on to next one
$JssorDebug$.$Error(e.name + " while executing " + eventName +
" handler: " + e.message, e);
}
});
};
_ThisObject.$Destroy = function () {
ClearListenees();
ClearListeners();
for (var name in _ThisObject)
delete _ThisObject[name];
};
$JssorDebug$.$C_AbstractClass(_ThisObject);
};
$JssorAnimator$ = function (delay, duration, options, elmt, fromStyles, toStyles) {
delay = delay || 0;
var _ThisAnimator = this;
var _AutoPlay;
var _Hiden;
var _CombineMode;
var _PlayToPosition;
var _PlayDirection;
var _NoStop;
var _TimeStampLastFrame = 0;
var _SubEasings;
var _SubRounds;
var _SubDurings;
var _Callback;
var _Position_Current = 0;
var _Position_Display = 0;
var _Hooked;
var _Position_InnerBegin = delay;
var _Position_InnerEnd = delay + duration;
var _Position_OuterBegin;
var _Position_OuterEnd;
var _LoopLength;
var _NestedAnimators = [];
var _StyleSetter;
function GetPositionRange(position, begin, end) {
var range = 0;
if (position < begin)
range = -1;
else if (position > end)
range = 1;
return range;
}
function GetInnerPositionRange(position) {
return GetPositionRange(position, _Position_InnerBegin, _Position_InnerEnd);
}
function GetOuterPositionRange(position) {
return GetPositionRange(position, _Position_OuterBegin, _Position_OuterEnd);
}
function Shift(offset) {
_Position_OuterBegin += offset;
_Position_OuterEnd += offset;
_Position_InnerBegin += offset;
_Position_InnerEnd += offset;
_Position_Current += offset;
_Position_Display += offset;
$Jssor$.$Each(_NestedAnimators, function (animator) {
animator, animator.$Shift(offset);
});
}
function Locate(position, relative) {
var offset = position - _Position_OuterBegin + delay * relative;
Shift(offset);
//$JssorDebug$.$Execute(function () {
// _ThisAnimator.$Position_InnerBegin = _Position_InnerBegin;
// _ThisAnimator.$Position_InnerEnd = _Position_InnerEnd;
// _ThisAnimator.$Position_OuterBegin = _Position_OuterBegin;
// _ThisAnimator.$Position_OuterEnd = _Position_OuterEnd;
//});
return _Position_OuterEnd;
}
function GoToPosition(positionOuter, force) {
var trimedPositionOuter = positionOuter;
if (_LoopLength && (trimedPositionOuter >= _Position_OuterEnd || trimedPositionOuter <= _Position_OuterBegin)) {
trimedPositionOuter = ((trimedPositionOuter - _Position_OuterBegin) % _LoopLength + _LoopLength) % _LoopLength + _Position_OuterBegin;
}
if (!_Hooked || _NoStop || force || _Position_Current != trimedPositionOuter) {
var positionToDisplay = Math.min(trimedPositionOuter, _Position_OuterEnd);
positionToDisplay = Math.max(positionToDisplay, _Position_OuterBegin);
if (!_Hooked || _NoStop || force || positionToDisplay != _Position_Display) {
if (toStyles) {
var interPosition = (positionToDisplay - _Position_InnerBegin) / (duration || 1);
//if (options.$Optimize && $Jssor$.$IsBrowserChrome() && duration) {
// interPosition = Math.round(interPosition / 8 * duration) * 8 / duration;
//}
if (options.$Reverse)
interPosition = 1 - interPosition;
var currentStyles = $Jssor$.$Transform(fromStyles, toStyles, interPosition, _SubEasings, _SubDurings, _SubRounds, options);
$Jssor$.$Each(currentStyles, function (value, key) {
_StyleSetter[key] && _StyleSetter[key](elmt, value);
});
}
_ThisAnimator.$OnInnerOffsetChange(_Position_Display - _Position_InnerBegin, positionToDisplay - _Position_InnerBegin);
}
_Position_Display = positionToDisplay;
$Jssor$.$Each(_NestedAnimators, function (animator, i) {
var nestedAnimator = positionOuter < _Position_Current ? _NestedAnimators[_NestedAnimators.length - i - 1] : animator;
nestedAnimator.$GoToPosition(positionOuter, force);
});
var positionOld = _Position_Current;
var positionNew = positionOuter;
_Position_Current = trimedPositionOuter;
_Hooked = true;
_ThisAnimator.$OnPositionChange(positionOld, positionNew);
}
}
function Join(animator, combineMode) {
/// <summary>
/// Combine another animator as nested animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
/// <param name="combineMode" type="int">
/// 0: parallel - place the animator parallel to this animator.
/// 1: chain - chain the animator at the _Position_InnerEnd of this animator.
/// </param>
$JssorDebug$.$Execute(function () {
if (combineMode !== 0 && combineMode !== 1)
$JssorDebug$.$Fail("Argument out of range, the value of 'combineMode' should be either 0 or 1.");
});
if (combineMode)
animator.$Locate(_Position_OuterEnd, 1);
_Position_OuterEnd = Math.max(_Position_OuterEnd, animator.$GetPosition_OuterEnd());
_NestedAnimators.push(animator);
}
var RequestAnimationFrame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.msRequestAnimationFrame;
if ($Jssor$.$IsBrowserSafari() && $Jssor$.$BrowserVersion() < 7) {
RequestAnimationFrame = null;
$JssorDebug$.$Log("Custom animation frame for safari before 7.");
}
RequestAnimationFrame = RequestAnimationFrame || function (callback) {
$Jssor$.$Delay(callback, options.$Interval);
};
function ShowFrame() {
if (_AutoPlay) {
var now = $Jssor$.$GetNow();
var timeOffset = Math.min(now - _TimeStampLastFrame, options.$IntervalMax);
var timePosition = _Position_Current + timeOffset * _PlayDirection;
_TimeStampLastFrame = now;
if (timePosition * _PlayDirection >= _PlayToPosition * _PlayDirection)
timePosition = _PlayToPosition;
GoToPosition(timePosition);
if (!_NoStop && timePosition * _PlayDirection >= _PlayToPosition * _PlayDirection) {
Stop(_Callback);
}
else {
RequestAnimationFrame(ShowFrame);
}
}
}
function PlayToPosition(toPosition, callback, noStop) {
if (!_AutoPlay) {
_AutoPlay = true;
_NoStop = noStop
_Callback = callback;
toPosition = Math.max(toPosition, _Position_OuterBegin);
toPosition = Math.min(toPosition, _Position_OuterEnd);
_PlayToPosition = toPosition;
_PlayDirection = _PlayToPosition < _Position_Current ? -1 : 1;
_ThisAnimator.$OnStart();
_TimeStampLastFrame = $Jssor$.$GetNow();
RequestAnimationFrame(ShowFrame);
}
}
function Stop(callback) {
if (_AutoPlay) {
_NoStop = _AutoPlay = _Callback = false;
_ThisAnimator.$OnStop();
if (callback)
callback();
}
}
_ThisAnimator.$Play = function (positionLength, callback, noStop) {
PlayToPosition(positionLength ? _Position_Current + positionLength : _Position_OuterEnd, callback, noStop);
};
_ThisAnimator.$PlayToPosition = PlayToPosition;
_ThisAnimator.$PlayToBegin = function (callback, noStop) {
PlayToPosition(_Position_OuterBegin, callback, noStop);
};
_ThisAnimator.$PlayToEnd = function (callback, noStop) {
PlayToPosition(_Position_OuterEnd, callback, noStop);
};
_ThisAnimator.$Stop = Stop;
_ThisAnimator.$Continue = function (toPosition) {
PlayToPosition(toPosition);
};
_ThisAnimator.$GetPosition = function () {
return _Position_Current;
};
_ThisAnimator.$GetPlayToPosition = function () {
return _PlayToPosition;
};
_ThisAnimator.$GetPosition_Display = function () {
return _Position_Display;
};
_ThisAnimator.$GoToPosition = GoToPosition;
_ThisAnimator.$GoToBegin = function () {
GoToPosition(_Position_OuterBegin, true);
};
_ThisAnimator.$GoToEnd = function () {
GoToPosition(_Position_OuterEnd, true);
};
_ThisAnimator.$Move = function (offset) {
GoToPosition(_Position_Current + offset);
};
_ThisAnimator.$CombineMode = function () {
return _CombineMode;
};
_ThisAnimator.$GetDuration = function () {
return duration;
};
_ThisAnimator.$IsPlaying = function () {
return _AutoPlay;
};
_ThisAnimator.$IsOnTheWay = function () {
return _Position_Current > _Position_InnerBegin && _Position_Current <= _Position_InnerEnd;
};
_ThisAnimator.$SetLoopLength = function (length) {
_LoopLength = length;
};
_ThisAnimator.$Locate = Locate;
_ThisAnimator.$Shift = Shift;
_ThisAnimator.$Join = Join;
_ThisAnimator.$Combine = function (animator) {
/// <summary>
/// Combine another animator parallel to this animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
Join(animator, 0);
};
_ThisAnimator.$Chain = function (animator) {
/// <summary>
/// Chain another animator at the _Position_InnerEnd of this animator
/// </summary>
/// <param name="animator" type="$JssorAnimator$">
/// An instance of $JssorAnimator$
/// </param>
Join(animator, 1);
};
_ThisAnimator.$GetPosition_InnerBegin = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_InnerBegin;
};
_ThisAnimator.$GetPosition_InnerEnd = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_InnerEnd;
};
_ThisAnimator.$GetPosition_OuterBegin = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_OuterBegin;
};
_ThisAnimator.$GetPosition_OuterEnd = function () {
/// <summary>
/// Internal member function, do not use it.
/// </summary>
/// <private />
/// <returns type="int" />
return _Position_OuterEnd;
};
_ThisAnimator.$OnPositionChange = _ThisAnimator.$OnStart = _ThisAnimator.$OnStop = _ThisAnimator.$OnInnerOffsetChange = $Jssor$.$EmptyFunction;
_ThisAnimator.$Version = $Jssor$.$GetNow();
//Constructor 1
{
options = $Jssor$.$Extend({
$Interval: 16,
$IntervalMax: 50
}, options);
//Sodo statement, for development time intellisence only
$JssorDebug$.$Execute(function () {
options = $Jssor$.$Extend({
$LoopLength: undefined,
$Setter: undefined,
$Easing: undefined
}, options);
});
_LoopLength = options.$LoopLength;
_StyleSetter = $Jssor$.$Extend({}, $Jssor$.$StyleSetter(), options.$Setter);
_Position_OuterBegin = _Position_InnerBegin = delay;
_Position_OuterEnd = _Position_InnerEnd = delay + duration;
_SubRounds = options.$Round || {};
_SubDurings = options.$During || {};
_SubEasings = $Jssor$.$Extend({ $Default: $Jssor$.$IsFunction(options.$Easing) && options.$Easing || $JssorEasing$.$EaseSwing }, options.$Easing);
}
};
function $JssorPlayerClass$() {
var _ThisPlayer = this;
var _PlayerControllers = [];
function PlayerController(playerElement) {
var _SelfPlayerController = this;
var _PlayerInstance;
var _PlayerInstantces = [];
function OnPlayerInstanceDataAvailable(event) {
var srcElement = $Jssor$.$EventSrc(event);
_PlayerInstance = srcElement.pInstance;
$Jssor$.$RemoveEvent(srcElement, "dataavailable", OnPlayerInstanceDataAvailable);
$Jssor$.$Each(_PlayerInstantces, function (playerInstance) {
if (playerInstance != _PlayerInstance) {
playerInstance.$Remove();
}
});
playerElement.pTagName = _PlayerInstance.tagName;
_PlayerInstantces = null;
}
function HandlePlayerInstance(playerInstanceElement) {
var playerHandler;
if (!playerInstanceElement.pInstance) {
var playerHandlerAttribute = $Jssor$.$AttributeEx(playerInstanceElement, "pHandler");
if ($JssorPlayer$[playerHandlerAttribute]) {
$Jssor$.$AddEvent(playerInstanceElement, "dataavailable", OnPlayerInstanceDataAvailable);
playerHandler = new $JssorPlayer$[playerHandlerAttribute](playerElement, playerInstanceElement);
_PlayerInstantces.push(playerHandler);
$JssorDebug$.$Execute(function () {
if ($Jssor$.$Type(playerHandler.$Remove) != "function") {
$JssorDebug$.$Fail("'pRemove' interface not implemented for player handler '" + playerHandlerAttribute + "'.");
}
});
}
}
return playerHandler;
}
_SelfPlayerController.$InitPlayerController = function () {
if (!playerElement.pInstance && !HandlePlayerInstance(playerElement)) {
var playerInstanceElements = $Jssor$.$Children(playerElement);
$Jssor$.$Each(playerInstanceElements, function (playerInstanceElement) {
HandlePlayerInstance(playerInstanceElement);
});
}
};
}
_ThisPlayer.$EVT_SWITCH = 21;
_ThisPlayer.$FetchPlayers = function (elmt) {
elmt = elmt || document.body;
var playerElements = $Jssor$.$FindChildren(elmt, "player");
$Jssor$.$Each(playerElements, function (playerElement) {
if (!_PlayerControllers[playerElement.pId]) {
playerElement.pId = _PlayerControllers.length;
_PlayerControllers.push(new PlayerController(playerElement));
}
var playerController = _PlayerControllers[playerElement.pId];
playerController.$InitPlayerController();
});
};
} | JavaScript |
this.screenshotPreview = function(){
/* CONFIG */
xOffset = 10;
yOffset = 30;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.screenshot").hover(function(e){
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
$("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");
$("#screenshot")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px")
.fadeIn("fast");
},
function(){
this.title = this.t;
$("#screenshot").remove();
});
$("a.screenshot").mousemove(function(e){
$("#screenshot")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px");
});
};
$(document).ready(function() {
// --- Hide Image ---
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
// --- Calendar Function ---
$( ".datepicker" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange:"1995:y"
});
$( ".birthdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange:"-100y:y",
defaultDate:"y-m-d"
});
$( ".datepicker2" ).datepicker({
changeMonth: true,
changeYear: true,
minDate: "-15y",
maxDate: "y"
});
$( ".datepicker_books" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: "-40:+0"
});
$( ".datepicker-payment" ).datepicker({
changeMonth: true
});
$( ".datepicker3" ).datepicker({
changeMonth: true,
changeYear: true,
});
// --- Accordion Function ---
$('.accordion h3.head').click(function() {
$(this).next().slideToggle('slow');
return false;
});
$('.accordion h3.head2').click(function(){
$('ul.head2 li').slideToggle('slow')
return false;
});
// --- Student Stat ---
$( '.studentStat' ).click(function(){
var a = $('input[name=student_status]:checked').val();
if(a=='new')
{
$('input[name=student_id]').val('');
$('#studentId').css({ "display" : "none" });
}
else
{
$('#studentId').css({ "display" : "block" });
}
});
// --- Modal ---
$( '#msgDialog' ).dialog({
draggable:false,
autoOpen: false,
resizable: false,
height:400,
modal: true,
buttons: {
'Ok': function() {
$( this ).dialog( 'close' );
}
}
});
// --- Tab ---
// Tabs
$('#tabs').tabs();
// --- Get The Base URL ---
var baseurl = $('#baseurl').val();
// --- Confirm Deletion ---
$( 'a.confirm' ).click(function(e){
e.preventDefault();
var theHREF = $(this).attr("href");
var title = $(this).attr("title");
if(!title ){
$( '#msgDialog > p' ).html( 'Are You Sure?' );
}else{
$( '#msgDialog > p' ).html( title );
}
$( '#msgDialog' ).dialog( 'option', 'title', 'Confirm' );
$("#msgDialog").dialog('option', 'buttons', {
"Confirm" : function() {
window.location.href = theHREF;
},
"Cancel" : function() {
$(this).dialog("close");
}
});
$("#msgDialog").dialog("open");
$('.ui-dialog-buttonpane').find('button').addClass('btn btn-mini btn-primary');
});
$( 'a.confirm_blank' ).click(function(e){
//$( '#msgDialog > p' ).html( 'Are You Sure?' );
//$( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
//alert('here');
e.preventDefault();
var theHREF = $(this).attr("href");
var title = $(this).attr("title");
if(!title ){
$( '#msgDialog > p' ).html( 'Are You Sure?' );
}else{
$( '#msgDialog > p' ).html( title );
}
$( '#msgDialog' ).dialog( 'option', 'title', 'Confirm' );
$("#msgDialog").dialog('option', 'buttons', {
"Confirm" : function() {
window.location = theHREF;
},
"Cancel" : function() {
$(this).dialog("close");
}
});
$("#msgDialog").dialog("open");
});
// --- Create Subject To Curriculum Record ---
$( '.subject_to_curriculum' ).click(function(){
$( '#ajaxLoadAni' ).fadeIn( 'slow' );
var target = $(this).attr("id");
$.ajax({
dataType : 'json',
url: baseurl + 'admin/create_subject_to_curriculum',
type: 'POST',
data: $( '#myform' + target ).serialize(),
success: function( response ) {
$( '#msgDialog > p' ).html( 'inserted' );
$( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' );
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
}
});
return false;
});
// CHECK ALL CHECKBOXES
$('.check_all').click(function(){
var id = $(this).attr('id');
if($(this).is(':checked')){
$('.'+id).attr('checked', 'checked');
}
else if($(this).not(':checked')){
$('.'+id).removeAttr('checked');
}
});
$('.time').timepicker({
hourGrid: 4,
minuteGrid: 10,
timeFormat: 'hh:mm tt'
});
//function confirm-auto start
$( 'a.confirm-auto' ).click(function(e){
e.preventDefault();
$('body').addClass('disable_scroll');
$(this).addClass('current_pick');
var theHREF = $(this).attr("href");
var title = $(this).attr("title");
if(!title ){
$( '#msgDialog > p' ).html( 'Are You Sure?' );
}else{
$( '#msgDialog > p' ).html( title );
}
$('#msgDialog' ).dialog( 'option', 'title', 'Confirm Action' );
$('#msgDialog' ).dialog( {
resizable: false,
height:140,
modal: true
});
$("#msgDialog").dialog('option', 'buttons', {
"Confirm" : function() {
$('body').removeClass('disable_scroll');
$(this).dialog("close");
$.ajax({
type: 'POST',
url: theHREF,
data:{
'jquery' : true
},
beforeSend: function() {
$('body').addClass('disable_scroll');
$('#loader').show();
},
complete: function(){
$('body').removeClass('disable_scroll');
$('#loader').hide('slow');
},
success: function(msg){
if(msg == 'true')
{
alert("Process was successfully Done");
$('a.current_pick').parents('tr.profile_box').hide(2000);
}else{
alert("Process encountered an error");
}
},
error: function (msg){
alert("An error has occured");
}
});
},
"Cancel" : function() {
$('body').removeClass('disable_scroll');
$(this).dialog("close");
}
});
$("#msgDialog").dialog("open");
});
$('#fee').change(function(){
var url = $(this).attr('url');
var opt = $(this).val();
if(opt == 'is_registration_fee' || opt == 'is_tuition_fee')
{
$.get(url, function(data) {
$('.dynamic-dropdown').html(data).show(50);
});
}else{
$('.dynamic-dropdown').hide(50);
}
});
screenshotPreview();
});// --- end document ready ---
| JavaScript |
$(document).ready(function(){
$('input#payment_input').focus(function(){
var amount = $(this).attr('original_fee_value');
var number = $(this).attr('fee_number');
$(this).keyup(function(){
var value = $(this).val();
$('input#amount_balance_'+number).val(numberWithCommas((+amount - +value).toFixed(2)));
$('input#amount_balance_hidden'+number).val(+amount - +value);
});
});
$('input.breakdown_sum').blur(function(){
var sum = 0;
var remaining;
var max = $('input#payment_recieved').attr('rate');
$('input.breakdown_sum').each(function() {
sum += Number($(this).val());
remaining = +max - +sum;
$('input#breakdown_total').val(numberWithCommas(sum.toFixed(2)));
$('input#breakdown_remaining').val(numberWithCommas(remaining.toFixed(2)));
if(sum > max)
{
$('div#message').html('<div class="error">Warning total Payment Breakdown is greater than recieved Payment</div>');
}else{
$('div#message').html('');
}
});
});
});
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
} | JavaScript |
$(document).ready(function(){
//higlight a selected cell in a calendar
$(".this_day").click(function(){
$(".this_day").removeClass("selected");
$(this).addClass("selected");
});
//adds data in database.
$("#button").click(function()
{
var selected = $(".selected .day_num").text(); // gets the numerical "day" in the calendar.
var event = $("#new_event").val(); // gets the event. input by user
if((selected == '') || (event == '')){ //checks if "day" or event is empty and performs proper window alert.
if(selected == ''){
alert("Choose proper day.");
$(".this_day").removeClass("selected");
exit;
}
if(event == ''){
alert("Enter event.");
}
}else{
$.ajax({ // if data is OK, ajax is performed.
url: window.location, // data passed to same page.
type: "POST",
data:{
day : selected,
event : event
},
success: function(msg){
alert(selected + " " + event);
location.reload(); // if successful, page is reloaded
}
});
}
});
//deletes data from database.
$("#delete").click(function()
{
var selected = $(".selected .day_num").text(); // gets the numerical "day" in the calendar.
if(selected == ''){
alert("No date selected.");
}else{
var f = confirm("Are you sure?");
if(f == true){
$.ajax({
url:window.location, // data passed to same page.
type:"POST",
data:{
flag : f,
a_day : selected
},
success: function(msg){
location.reload(); // if successful, page is reloaded
}
});
}
}
});
$('#birthdate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
onSelect: function(dateText, inst)
{
$(this).val(dateText);
alert($(this).val());
}
});
// datepicker for attendance
$('#datepicker').datepicker({
dateFormat: 'MM dd, yy',
changeMonth: true,
showButtonPanel: true,
onSelect: function(dateText, inst)
{
$(this).val(dateText);
}
});
// function for deleting attendance in m.k12/teacher/attendance
$(".confirm_btns").on("click", function(e){
var link = this;
e.preventDefault();
$("<div title='Delete'>Are you sure you want to continue?</div>").dialog({
buttons: {
"OK" : function(){
window.location = link.href;
},
"Cancel" : function(){
$(this).dialog("close");
}
}
});
});
//for viewing subjects of teachers
$(function(){
$("#subj_accordion").accordion({
collapsible: true,
icons: false,
heightStyle: "content"
});
});
//for submitting remarks in report card
$("input.remarks_in").blur(function(){
$("form.remarks_form").submit();
});
//for username generation in hrd or admin (employee_settings/change_settings)
var charArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$('#gen_uname').click(function(){
var rand_uname = "";
while(rand_uname.length != 10)
{
rand_uname += charArray.charAt(Math.floor(Math.random()*62)+1);
}
$("<div title='Generated Username'>Use " + rand_uname + " as username?</div>").dialog({
resizable: false,
buttons: {
"OK" : function(){
$('#username').val(rand_uname);
$(this).dialog("close");
},
"Cancel" : function(){
$(this).dialog("close");
}
}
});
});
//for password generation in hrd or admin (employee_settings/change_settings)
$('#gen_pword').click(function(){
var rand_pword = "";
while(rand_pword.length != 7)
{
rand_pword += charArray.charAt(Math.floor(Math.random()*62)+1);
}
$("<div title='Generated Password'>Use " + rand_pword + " as password?</div>").dialog({
resizable: false,
buttons: {
"OK" : function(){
$('#password').val(rand_pword);
$(this).dialog("close");
},
"Cancel" : function(){
$(this).dialog("close");
}
}
});
});
$('#submit_changes').click(function(){
if($('#username').val() == '' && $('#password').val() == ''){
$("<div title='No entry found'>Please enter at least one entry</div>").dialog({
resizable: false,
modal: true,
buttons: {
"OK" : function(){
$(this).dialog("close");
}
}
});
}else
{
$("<div title='Settings Changed'><p>Are you sure?</p><br /><p>Note: Please give changes to employee concerned IMMEDIATELY.</p></div>").dialog({
resizable: false,
modal: true,
buttons: {
"Yes" : function(){
$('#settings_form').submit();
$(this).dialog("close");
},
"Cancel" : function(){
$(this).dialog("close");
}
}
});
}
});
$('.submit_btns').click(function(){
$("<div title='Submit'>Are you sure?</div>").dialog({
resizable: false,
modal: true,
buttons: {
"Yes" : function(){
$(".submit_forms").submit();
$(this).dialog("close");
},
"Cancel" : function(){
$(this).dialog("close");
}
}
});
});
});
| JavaScript |
$(function(){
var currentForm;
$( '#msgDialog' ).dialog({
draggable:false,
autoOpen: false,
resizable: false,
maxWidth:600,
maxHeight: 500,
width: 400,
height: 360,
modal: true,
buttons: {
'No, I want to change something.' : function()
{
$(this).dialog('close');
},
'Yes. Everything is correct, proceed.': function() {
$(window).unbind('beforeunload');
currentForm.submit();
//console.log(currentForm);
}
}
});
$( '#msgDialog2' ).dialog({
draggable:false,
autoOpen: false,
resizable: false,
maxWidth:600,
maxHeight: 500,
width: 400,
height: 360,
modal: true,
buttons: {
'Close.' : function()
{
$(this).dialog('close');
}
}
});
// check grade level form
$('#check-level-form').submit(function (event) {
event.preventDefault();
currentForm = this;
$(this).on('valid', function (event) {
var grade = $('#level-section option:selected').text();
var block = $('input[name=section]:checked', '#check-level-form').attr('title');
var thehtml ='';
var block_f;
if(typeof block == 'undefined')
{
block_f = 'No Block Set for '+ grade +'. Please Proceed.';
}else{
block_f = block;
}
thehtml += '<p>Selected grade level is: <strong>'+ grade +'</strong></p>';
thehtml += '<p>Selected Block is: <strong>'+ block_f +'</strong></p>';
$( '.ui-dialog-title' ).html('Grade Level and Block.');
$( '#msgDialog > div.content' ).html(thehtml);
$( '#msgDialog' ).dialog('open');
});
});
$('#check-form-submit').submit(function (event) {
event.preventDefault();
currentForm = this;
//console.log(currentForm);
});
$('#check-form-submit').on('invalid', function (event) {
$( '.ui-dialog-title' ).html('Error.');
$( '#msgDialog2 > div.content' ).html('<p><strong>Please fix the fields marked with red.</strong></p>');
$( '#msgDialog2' ).dialog('open');
});
$('#check-form-submit').on('valid', function (event) {
$( '.ui-dialog-title' ).html('Verify Registration Form.');
$( '#msgDialog > div.content' ).html('<p><strong>Please confirm that all data is true and correct.</strong></p>');
$( '#msgDialog' ).dialog('open');
});
}); | JavaScript |
/**
* editable_selects.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
TinyMCE_EditableSelects.onBlurEditableSelectInput();
}
};
| JavaScript |
/**
* mctabs.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
function MCTabs() {
this.settings = [];
this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher');
};
MCTabs.prototype.init = function(settings) {
this.settings = settings;
};
MCTabs.prototype.getParam = function(name, default_value) {
var value = null;
value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
// Fix bool values
if (value == "true" || value == "false")
return (value == "true");
return value;
};
MCTabs.prototype.showTab =function(tab){
tab.className = 'current';
tab.setAttribute("aria-selected", true);
tab.setAttribute("aria-expanded", true);
tab.tabIndex = 0;
};
MCTabs.prototype.hideTab =function(tab){
var t=this;
tab.className = '';
tab.setAttribute("aria-selected", false);
tab.setAttribute("aria-expanded", false);
tab.tabIndex = -1;
};
MCTabs.prototype.showPanel = function(panel) {
panel.className = 'current';
panel.setAttribute("aria-hidden", false);
};
MCTabs.prototype.hidePanel = function(panel) {
panel.className = 'panel';
panel.setAttribute("aria-hidden", true);
};
MCTabs.prototype.getPanelForTab = function(tabElm) {
return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls");
};
MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) {
var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this;
tabElm = document.getElementById(tab_id);
if (panel_id === undefined) {
panel_id = t.getPanelForTab(tabElm);
}
panelElm= document.getElementById(panel_id);
panelContainerElm = panelElm ? panelElm.parentNode : null;
tabContainerElm = tabElm ? tabElm.parentNode : null;
selectionClass = t.getParam('selection_class', 'current');
if (tabElm && tabContainerElm) {
nodes = tabContainerElm.childNodes;
// Hide all other tabs
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "LI") {
t.hideTab(nodes[i]);
}
}
// Show selected tab
t.showTab(tabElm);
}
if (panelElm && panelContainerElm) {
nodes = panelContainerElm.childNodes;
// Hide all other panels
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "DIV")
t.hidePanel(nodes[i]);
}
if (!avoid_focus) {
tabElm.focus();
}
// Show selected panel
t.showPanel(panelElm);
}
};
MCTabs.prototype.getAnchor = function() {
var pos, url = document.location.href;
if ((pos = url.lastIndexOf('#')) != -1)
return url.substring(pos + 1);
return "";
};
//Global instance
var mcTabs = new MCTabs();
tinyMCEPopup.onInit.add(function() {
var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each;
each(dom.select('div.tabs'), function(tabContainerElm) {
var keyNav;
dom.setAttrib(tabContainerElm, "role", "tablist");
var items = tinyMCEPopup.dom.select('li', tabContainerElm);
var action = function(id) {
mcTabs.displayTab(id, mcTabs.getPanelForTab(id));
mcTabs.onChange.dispatch(id);
};
each(items, function(item) {
dom.setAttrib(item, 'role', 'tab');
dom.bind(item, 'click', function(evt) {
action(item.id);
});
});
dom.bind(dom.getRoot(), 'keydown', function(evt) {
if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab
keyNav.moveFocus(evt.shiftKey ? -1 : 1);
tinymce.dom.Event.cancel(evt);
}
});
each(dom.select('a', tabContainerElm), function(a) {
dom.setAttrib(a, 'tabindex', '-1');
});
keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', {
root: tabContainerElm,
items: items,
onAction: action,
actOnFocus: true,
enableLeftRight: true,
enableUpDown: true
}, tinyMCEPopup.dom);
});
}); | JavaScript |
/**
* validate.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
// String validation:
if (!Validator.isEmail('myemail'))
alert('Invalid email.');
// Form validation:
var f = document.forms['myform'];
if (!Validator.isEmail(f.myemail))
alert('Invalid email.');
*/
var Validator = {
isEmail : function(s) {
return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
},
isAbsUrl : function(s) {
return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
},
isSize : function(s) {
return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
},
isId : function(s) {
return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
},
isEmpty : function(s) {
var nl, i;
if (s.nodeName == 'SELECT' && s.selectedIndex < 1)
return true;
if (s.type == 'checkbox' && !s.checked)
return true;
if (s.type == 'radio') {
for (i=0, nl = s.form.elements; i<nl.length; i++) {
if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
return false;
}
return true;
}
return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
},
isNumber : function(s, d) {
return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$'));
},
test : function(s, p) {
s = s.nodeType == 1 ? s.value : s;
return s == '' || new RegExp(p).test(s);
}
};
var AutoValidator = {
settings : {
id_cls : 'id',
int_cls : 'int',
url_cls : 'url',
number_cls : 'number',
email_cls : 'email',
size_cls : 'size',
required_cls : 'required',
invalid_cls : 'invalid',
min_cls : 'min',
max_cls : 'max'
},
init : function(s) {
var n;
for (n in s)
this.settings[n] = s[n];
},
validate : function(f) {
var i, nl, s = this.settings, c = 0;
nl = this.tags(f, 'label');
for (i=0; i<nl.length; i++) {
this.removeClass(nl[i], s.invalid_cls);
nl[i].setAttribute('aria-invalid', false);
}
c += this.validateElms(f, 'input');
c += this.validateElms(f, 'select');
c += this.validateElms(f, 'textarea');
return c == 3;
},
invalidate : function(n) {
this.mark(n.form, n);
},
getErrorMessages : function(f) {
var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (this.hasClass(nl[i], s.invalid_cls)) {
field = document.getElementById(nl[i].getAttribute("for"));
values = { field: nl[i].textContent };
if (this.hasClass(field, s.min_cls, true)) {
message = ed.getLang('invalid_data_min');
values.min = this.getNum(field, s.min_cls);
} else if (this.hasClass(field, s.number_cls)) {
message = ed.getLang('invalid_data_number');
} else if (this.hasClass(field, s.size_cls)) {
message = ed.getLang('invalid_data_size');
} else {
message = ed.getLang('invalid_data');
}
message = message.replace(/{\#([^}]+)\}/g, function(a, b) {
return values[b] || '{#' + b + '}';
});
messages.push(message);
}
}
return messages;
},
reset : function(e) {
var t = ['label', 'input', 'select', 'textarea'];
var i, j, nl, s = this.settings;
if (e == null)
return;
for (i=0; i<t.length; i++) {
nl = this.tags(e.form ? e.form : e, t[i]);
for (j=0; j<nl.length; j++) {
this.removeClass(nl[j], s.invalid_cls);
nl[j].setAttribute('aria-invalid', false);
}
}
},
validateElms : function(f, e) {
var nl, i, n, s = this.settings, st = true, va = Validator, v;
nl = this.tags(f, e);
for (i=0; i<nl.length; i++) {
n = nl[i];
this.removeClass(n, s.invalid_cls);
if (this.hasClass(n, s.required_cls) && va.isEmpty(n))
st = this.mark(f, n);
if (this.hasClass(n, s.number_cls) && !va.isNumber(n))
st = this.mark(f, n);
if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true))
st = this.mark(f, n);
if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n))
st = this.mark(f, n);
if (this.hasClass(n, s.email_cls) && !va.isEmail(n))
st = this.mark(f, n);
if (this.hasClass(n, s.size_cls) && !va.isSize(n))
st = this.mark(f, n);
if (this.hasClass(n, s.id_cls) && !va.isId(n))
st = this.mark(f, n);
if (this.hasClass(n, s.min_cls, true)) {
v = this.getNum(n, s.min_cls);
if (isNaN(v) || parseInt(n.value) < parseInt(v))
st = this.mark(f, n);
}
if (this.hasClass(n, s.max_cls, true)) {
v = this.getNum(n, s.max_cls);
if (isNaN(v) || parseInt(n.value) > parseInt(v))
st = this.mark(f, n);
}
}
return st;
},
hasClass : function(n, c, d) {
return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className);
},
getNum : function(n, c) {
c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0];
c = c.replace(/[^0-9]/g, '');
return c;
},
addClass : function(n, c, b) {
var o = this.removeClass(n, c);
n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c;
},
removeClass : function(n, c) {
c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' ');
return n.className = c != ' ' ? c : '';
},
tags : function(f, s) {
return f.getElementsByTagName(s);
},
mark : function(f, n) {
var s = this.settings;
this.addClass(n, s.invalid_cls);
n.setAttribute('aria-invalid', 'true');
this.markLabels(f, n, s.invalid_cls);
return false;
},
markLabels : function(f, n, ic) {
var nl, i;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id)
this.addClass(nl[i], ic);
}
return null;
}
};
| JavaScript |
/**
* form_utils.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme"));
function getColorPickerHTML(id, target_form_element) {
var h = "", dom = tinyMCEPopup.dom;
if (label = dom.select('label[for=' + target_form_element + ']')[0]) {
label.id = label.id || dom.uniqueId();
}
h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">';
h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> <span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>';
return h;
}
function updateColor(img_id, form_element_id) {
document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value;
}
function setBrowserDisabled(id, state) {
var img = document.getElementById(id);
var lnk = document.getElementById(id + "_link");
if (lnk) {
if (state) {
lnk.setAttribute("realhref", lnk.getAttribute("href"));
lnk.removeAttribute("href");
tinyMCEPopup.dom.addClass(img, 'disabled');
} else {
if (lnk.getAttribute("realhref"))
lnk.setAttribute("href", lnk.getAttribute("realhref"));
tinyMCEPopup.dom.removeClass(img, 'disabled');
}
}
}
function getBrowserHTML(id, target_form_element, type, prefix) {
var option = prefix + "_" + type + "_browser_callback", cb, html;
cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback"));
if (!cb)
return "";
html = "";
html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">';
html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> </span></a>';
return html;
}
function openBrowser(img_id, target_form_element, type, option) {
var img = document.getElementById(img_id);
if (img.className != "mceButtonDisabled")
tinyMCEPopup.openBrowser(target_form_element, type, option);
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
if (!value)
value = "";
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option(value, value);
option.selected = true;
sel.options[sel.options.length] = option;
sel.selectedIndex = sel.options.length - 1;
}
return found;
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null || elm.selectedIndex === -1)
return "";
return elm.options[elm.selectedIndex].value;
}
function addSelectValue(form_obj, field_name, name, value) {
var s = form_obj.elements[field_name];
var o = new Option(name, value);
s.options[s.options.length] = o;
}
function addClassesToList(list_id, specific_option) {
// Setup class droplist
var styleSelectElm = document.getElementById(list_id);
var styles = tinyMCEPopup.getParam('theme_advanced_styles', false);
styles = tinyMCEPopup.getParam(specific_option, styles);
if (styles) {
var stylesAr = styles.split(';');
for (var i=0; i<stylesAr.length; i++) {
if (stylesAr != "") {
var key, value;
key = stylesAr[i].split('=')[0];
value = stylesAr[i].split('=')[1];
styleSelectElm.options[styleSelectElm.length] = new Option(key, value);
}
}
} else {
tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) {
styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']);
});
}
}
function isVisible(element_id) {
var elm = document.getElementById(element_id);
return elm && elm.style.display != "none";
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return "rgb(" + r + "," + g + "," + b + ")";
}
return col;
}
function trimSize(size) {
return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2');
}
function getCSSSize(size) {
size = trimSize(size);
if (size == "")
return "";
// Add px
if (/^[0-9]+$/.test(size))
size += 'px';
// Sanity check, IE doesn't like broken values
else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size)))
return "";
return size;
}
function getStyle(elm, attrib, style) {
var val = tinyMCEPopup.dom.getAttrib(elm, attrib);
if (val != '')
return '' + val;
if (typeof(style) == 'undefined')
style = attrib;
return tinyMCEPopup.dom.getStyle(elm, style);
}
| JavaScript |
/*
12306 Auto Login => A javascript snippet to help you auto login 12306.com.
Copyright (C) 2011 w000.cn
Includes jQuery
Copyright 2011, John Resig
Dual licensed under the MIT or GPL Version 2 licenses.
http://jquery.org/license
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// ==UserScript==
// @name 12306 Auto refresh
// @author w000.cn@gmail.com
// @namespace https://plus.google.com/107416899831145722597
// @description A javascript snippet to help you auto login 12306.com
// @include *://dynamic.12306.cn/otsweb/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
function withjQuery(callback, safe){
if(typeof(jQuery) == "undefined") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
if(safe) {
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery);";
script.addEventListener('load', function() {
document.head.appendChild(cb);
});
}
else {
var dollar = undefined;
if(typeof($) != "undefined") dollar = $;
script.addEventListener('load', function() {
jQuery.noConflict();
$ = dollar;
callback(jQuery);
});
}
document.head.appendChild(script);
} else {
callback(jQuery);
}
}
withjQuery(function($){
//alert(document.body.innerHTML);
if (document.body.innerHTML.indexOf("Access Denied") > -1)
{
setTimeout(location.reload(),2000);
}
//notify('网页刷新成功!');
}, true);
| JavaScript |
//Script by Aneesh of www.bloggerplugins.org
//Released on August 19th August 2009
var relatedTitles = new Array();
var relatedTitlesNum = 0;
var relatedUrls = new Array();
var thumburl = new Array();
function related_results_labels_thumbs(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
var entry = json.feed.entry[i];
relatedTitles[relatedTitlesNum] = entry.title.$t;
try
{thumburl[relatedTitlesNum]=entry.media$thumbnail.url;}
catch (error){
s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){
thumburl[relatedTitlesNum]=d;} else thumburl[relatedTitlesNum]='http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png';
}
if(relatedTitles[relatedTitlesNum].length>200) relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0, 100)+"...";
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
relatedUrls[relatedTitlesNum] = entry.link[k].href;
relatedTitlesNum++;
}
}
}
}
function removeRelatedDuplicates_thumbs() {
var tmp = new Array(0);
var tmp2 = new Array(0);
var tmp3 = new Array(0);
for(var i = 0; i < relatedUrls.length; i++) {
if(!contains_thumbs(tmp, relatedUrls[i]))
{
tmp.length += 1;
tmp[tmp.length - 1] = relatedUrls[i];
tmp2.length += 1;
tmp3.length += 1;
tmp2[tmp2.length - 1] = relatedTitles[i];
tmp3[tmp3.length - 1] = thumburl[i];
}
}
relatedTitles = tmp2;
relatedUrls = tmp;
thumburl=tmp3;
}
function contains_thumbs(a, e) {
for(var j = 0; j < a.length; j++) if (a[j]==e) return true;
return false;
}
function printRelatedLabels_thumbs() {
for(var i = 0; i < relatedUrls.length; i++)
{
if((relatedUrls[i]==currentposturl)||(!(relatedTitles[i])))
{
relatedUrls.splice(i,1);
relatedTitles.splice(i,1);
thumburl.splice(i,1);
}
}
var r = Math.floor((relatedTitles.length - 1) * Math.random());
var i = 0;
if(relatedTitles.length>0) document.write('');
document.write('<div style="clear: both;"/>');
while (i < relatedTitles.length && i < 20 && i<maxresults) {
document.write('<div style="background-color:#F2F2F2;padding:3px;border:1px solid silver;width:97px;height:125px;margin:0 11px 10px 0;float:left;">');
document.write('<a style="text-decoration:none;float:left;');
if(i!=0) document.write('border-left:solid 0px #d4eaf2;"');
else document.write('"');
document.write(' href="' + relatedUrls[r] + '"><img alt="Free Ebook Download" title="'+relatedTitles[r]+'" style="width:97px;height:125px;border:0px;" src="'+thumburl[r]+'"/></a></div>');
if (r < relatedTitles.length - 1) {
r++;
} else {
r = 0;
}
i++;
}
document.write('</div>');
} | JavaScript |
//<![CDATA[
$(document).ready(function() {
// change the dimension variable below to be the pixel size you want
var dimension = 199;
// this identifies the PopularPosts2 div element, finds each image in it, and resizes it
$('#Blog1,#related-posts').find('img').each(function(n, image){
var image = $(image);
image.attr({src : image.attr('src').replace(/s\B\d{2,4}-c/,'s' + dimension)});
image.attr('width','auto');
image.attr('height','auto');
});
});
$(document).ready(function() {
// change the dimension variable below to be the pixel size you want
var dimension = 105;
// this identifies the PopularPosts2 div element, finds each image in it, and resizes it
$('#PopularPosts2').find('img').each(function(n, image){
var image = $(image);
image.attr({src : image.attr('src').replace(/s\B\d{2,4}-c/,'s' + dimension)});
image.attr('width','auto');
image.attr('height','auto');
});
});
//]]> | JavaScript |
//<![CDATA[
jQuery(document).ready(function() {
//Set Default State of each portfolio piece
$(".paging").show();
$(".paging a:first").addClass("active");
//Get size of images, how many there are, then determin the size of the image reel.
var imageWidth = $(".sompret").width();
var imageSum = $(".image_reel img").size();
var imageReelWidth = imageWidth * imageSum;
//Adjust the image reel to its new size
$(".image_reel").css({'width' : imageReelWidth});
//Paging + Slider Function
rotate = function(){
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
$(".paging a").removeClass('active'); //Remove all active class
$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
$(".crott").stop(true,true).slideUp('slow');
$(".crott").eq( $('.paging a.active').attr("rel") - 1 ).slideDown("slow");
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500 );
};
//Rotation + Timing Event
rotateSwitch = function(){
$(".crott").eq( $('.paging a.active').attr("rel") - 1 ).slideDown("slow");
play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
$active = $('.paging a.active').next();
if ( $active.length === 0) { //If paging reaches the end...
$active = $('.paging a:first'); //go back to first
}
rotate(); //Trigger the paging and slider function
}, 10000); //Timer speed in milliseconds (3 seconds)
};
rotateSwitch(); //Run function on launch
//On Click
$(".paging a").click(function() {
$active = $(this); //Activate the clicked paging
//Reset Timer
clearInterval(play); //Stop the rotation
rotate(); //Trigger rotation immediately
rotateSwitch(); // Resume rotation
return false; //Prevent browser jump to link anchor
});
});
//]]> | JavaScript |
var tabbedTOC_defaults = {
blogUrl: "http://www.dte.web.id", // Blog URL
containerId: "tabbed-toc", // Container ID
activeTab: 1, // The default active tab index (default: the first tab)
showDates: false, // true to show the post date
showSummaries: false, // true to show the posts summaries
numChars: 200, // Number of summary chars
showThumbnails: false, // true to show the posts thumbnails (Not recommended)
thumbSize: 40, // Thumbnail size
noThumb: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC", // No thumbnail URL
monthNames: [ // Array of month names
"Januari",
"Februari",
"Maret",
"April",
"Mei",
"Juni",
"Juli",
"Agustus",
"September",
"Oktober",
"November",
"Desember"
],
newTabLink: true, // Open link in new window?
maxResults: 99999, // Maximum posts result
preload: 0, // Load the feed after 0 seconds (option => time in milliseconds || "onload")
sortAlphabetically: true, // `false` to sort posts by date
showNew: false, // `false` to hide the "New!" mark in most recent posts, or define how many recent posts are to be marked
newText: " - <em style='color:red;'>Baru!</em>" // HTML for the "New!" text
};
for (var i in tabbedTOC_defaults) {
tabbedTOC_defaults[i] = (typeof(tabbedTOC[i]) !== undefined && typeof(tabbedTOC[i]) !== 'undefined') ? tabbedTOC[i] : tabbedTOC_defaults[i];
}
function clickTab(pos) {
var a = document.getElementById(tabbedTOC_defaults.containerId),
b = a.getElementsByTagName('ol'),
c = a.getElementsByTagName('ul')[0],
d = c.getElementsByTagName('a');
for (var t = 0; t < b.length; t++) {
b[t].style.display = "none";
b[parseInt(pos, 10)].style.display = "block";
}
for (var u = 0; u < d.length; u++) {
d[u].className = "";
d[parseInt(pos, 10)].className = "active-tab";
}
}
function showTabs(json) {
var total = parseInt(json.feed.openSearch$totalResults.$t,10),
c = tabbedTOC_defaults,
entry = json.feed.entry,
category = json.feed.category,
skeleton = "",
newPosts = [];
for (var g = 0; g < (c.showNew === true ? 5 : c.showNew); g++) {
if (g == entry.length) break;
entry[g].title.$t = entry[g].title.$t + (c.showNew !== false ? c.newText : '');
}
entry = c.sortAlphabetically ? entry.sort(function(a,b) {
return (a.title.$t.localeCompare(b.title.$t));
}) : entry;
category = c.sortAlphabetically ? category.sort(function(a,b) {
return (a.term.localeCompare(b.term));
}) : category;
// Build the tabs skeleton
skeleton = '<span class="divider-layer"></span><ul class="toc-tabs">';
for (var h = 0, cen = category.length; h < cen; h++) {
skeleton += '<li class="toc-tab-item-' + h + '"><a href="javascript:clickTab(' + h + ');">' + category[h].term + '</a></li>';
}
skeleton += '</ul>';
// Bulid the tabs contents skeleton
skeleton += '<div class="toc-content">';
for (var i = 0, cnt = category.length; i < cnt; i++) {
skeleton += '<ol class="panel" data-category="' + category[i].term + '"';
skeleton += (i != (c.activeTab-1)) ? ' style="display:none;"' : '';
skeleton += '>';
for (var j = 0; j < total; j++) {
if (j == entry.length) break;
var link, entries = entry[j],
pub = entries.published.$t, // Get the post date
month = c.monthNames, // Month array from the configuration
title = entries.title.$t, // Get the post title
summary = ("summary" in entries && c.showSummaries === true) ? entries.summary.$t.replace(/<br ?\/?>/g," ").replace(/<.*?>/g,"").replace(/[<>]/g,"").substring(0,c.numChars) + '…' : '', // Get the post summary
img = ("media$thumbnail" in entries && c.showThumbnails === true) ? '<img class="thumbnail" style="width:'+c.thumbSize+'px;height:'+c.thumbSize+'px;" alt="" src="' + entries.media$thumbnail.url.replace(/\/s72(\-c)?\//,"/s"+c.thumbSize+"-c/") + '"/>' : '<img class="thumbnail" style="width:'+c.thumbSize+'px;height:'+c.thumbSize+'px;" alt="" src="' + c.noThumb.replace(/\/s72(\-c)?\//,"/s"+c.thumbSize+"-c/") + '"/>', // Get the post thumbnail
cat = (entries.category) ? entries.category : [], // Post categories
date = (c.showDates) ? '<time datetime="' + pub + '" title="' + pub + '">' + pub.substring(8,10) + ' ' + month[parseInt(pub.substring(5,7),10)-1] + ' ' + pub.substring(0,4) + '</time>' : ''; // Formated published date
for (var k = 0; k < entries.link.length; k++) {
if (entries.link[k].rel == 'alternate') {
link = entries.link[k].href; // Get the post URL
break;
}
}
for (var l = 0, check = cat.length; l < check; l++) {
var target = (c.newTabLink) ? ' target="_blank"' : ''; // Open link in new window?
// Write the list skeleton only if at least one of the post...
// ... has the same category term with one of the current categories term list
if (cat[l].term == category[i].term) {
skeleton += '<li title="' + cat[l].term + '"';
skeleton += (c.showSummaries) ? ' class="bold"' : '';
skeleton += '><a href="' + link + '"' + target + '>' + title + date + '</a>';
skeleton += (c.showSummaries) ? '<span class="summary">' + img + summary + '<span style="display:block;clear:both;"></span></span>' : '';
skeleton += '</li>';
}
}
}
skeleton += '</ol>';
}
skeleton += '</div>';
skeleton += '<div style="clear:both;"></div>';
document.getElementById(c.containerId).innerHTML = skeleton;
clickTab(c.activeTab-1);
}
(function() {
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.src = tabbedTOC_defaults.blogUrl + '/feeds/posts/summary?alt=json-in-script&max-results=' + tabbedTOC_defaults.maxResults + '&orderby=published&callback=showTabs';
if (tabbedTOC_defaults.preload !== "onload") {
setTimeout(function() {
h.appendChild(s);
}, tabbedTOC_defaults.preload);
} else {
window.onload = function() {
h.appendChild(s);
};
}
})(); | JavaScript |
var bcLoadingImage = "http://1.bp.blogspot.com/-vPivuucfViM/UN8jzBwcZKI/AAAAAAAAHbY/at-JwuUBk_4/s1600/horizontal-loading.gif";
var bcLoadingMessage = "";
var bcArchiveNavText = "View Archive";
var bcArchiveNavPrev = '◄';
var bcArchiveNavNext = '►';
var headDays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var headInitial = ["Su","Mo","Tu","We","Th","Fr","Sa"];
// Nothing to configure past this point ----------------------------------
var timeOffset;
var bcBlogID;
var calMonth;
var calDay = 1;
var calYear;
var startIndex;
var callmth;
var bcNav = new Array ();
var bcList = new Array ();
//Initialize Fill Array
var fill = ["","31","28","31","30","31","30","31","31","30","31","30","31"];
function openStatus(){
document.getElementById('calLoadingStatus').style.display = 'block';
document.getElementById('calendarDisplay').innerHTML = '';
}
function closeStatus(){
document.getElementById('calLoadingStatus').style.display = 'none';
}
function bcLoadStatus(){
cls = document.getElementById('calLoadingStatus');
img = document.createElement('img');
img.src = bcLoadingImage;
img.style.verticalAlign = 'middle';
cls.appendChild(img);
txt = document.createTextNode(bcLoadingMessage);
cls.appendChild(txt);
}
function callArchive(mth,yr,nav){
// Check for Leap Years
if (((yr % 4 == 0) && (yr % 100 != 0)) || (yr % 400 == 0)) {
fill[2] = '29';
}
else {
fill[2] = '28';
}
calMonth = mth;
calYear = yr;
if(mth.charAt(0) == 0){
calMonth = mth.substring(1);
}
callmth = mth;
bcNavAll = document.getElementById('bcFootAll');
bcNavPrev = document.getElementById('bcFootPrev');
bcNavNext = document.getElementById('bcFootNext');
bcSelect = document.getElementById('bcSelection');
a = document.createElement('a');
at = document.createTextNode(bcArchiveNavText);
a.href = bcNav[nav];
a.appendChild(at);
bcNavAll.innerHTML = '';
bcNavAll.appendChild(a);
bcNavPrev.innerHTML = '';
bcNavNext.innerHTML = '';
if(nav < bcNav.length -1){
a = document.createElement('a');
a.innerHTML = bcArchiveNavPrev;
bcp = parseInt(nav,10) + 1;
a.href = bcNav[bcp];
a.title = 'Previous Archive';
prevSplit = bcList[bcp].split(',');
a.onclick = function(){bcSelect.options[bcp].selected = true;openStatus();callArchive(prevSplit[0],prevSplit[1],prevSplit[2]);return false;};
bcNavPrev.appendChild(a);
}
if(nav > 0){
a = document.createElement('a');
a.innerHTML = bcArchiveNavNext;
bcn = parseInt(nav,10) - 1;
a.href = bcNav[bcn];
a.title = 'Next Archive';
nextSplit = bcList[bcn].split(',');
a.onclick = function(){bcSelect.options[bcn].selected = true;openStatus();callArchive(nextSplit[0],nextSplit[1],nextSplit[2]);return false;};
bcNavNext.appendChild(a);
}
script = document.createElement('script');
script.src = 'http://www.blogger.com/feeds/'+bcBlogId+'/posts/summary?published-max='+calYear+'-'+callmth+'-'+fill[calMonth]+'T23%3A59%3A59'+timeOffset+'&published-min='+calYear+'-'+callmth+'-01T00%3A00%3A00'+timeOffset+'&max-results=100&orderby=published&alt=json-in-script&callback=cReadArchive';
document.getElementsByTagName('head')[0].appendChild(script);
}
function cReadArchive(root){
// Check for Leap Years
if (((calYear % 4 == 0) && (calYear % 100 != 0)) || (calYear % 400 == 0)) {
fill[2] = '29';
}
else {
fill[2] = '28';
}
closeStatus();
document.getElementById('lastRow').style.display = 'none';
calDis = document.getElementById('calendarDisplay');
var feed = root.feed;
var total = feed.openSearch$totalResults.$t;
var entries = feed.entry || [];
var fillDate = new Array();
var fillTitles = new Array();
fillTitles.length = 32;
var ul = document.createElement('ul');
ul.id = 'calendarUl';
for (var i = 0; i < feed.entry.length; ++i) {
var entry = feed.entry[i];
for (var j = 0; j < entry.link.length; ++j) {
if (entry.link[j].rel == "alternate") {
var link = entry.link[j].href;
}
}
var title = entry.title.$t;
var author = entry.author[0].name.$t;
var date = entry.published.$t;
var summary = entry.summary.$t;
isPublished = date.split('T')[0].split('-')[2];
if(isPublished.charAt(0) == '0'){
isPublished = isPublished.substring(1);
}
fillDate.push(isPublished);
if (fillTitles[isPublished]){
fillTitles[isPublished] = fillTitles[isPublished] + ' | ' + title;
}
else {
fillTitles[isPublished] = title;
}
li = document.createElement('li');
li.style.listType = 'none';
li.innerHTML = '<a href="'+link+'">'+title+'</a>';
ul.appendChild(li);
}
calDis.appendChild(ul);
var val1 = parseInt(calDay, 10)
var valxx = parseInt(calMonth, 10);
var val2 = valxx - 1;
var val3 = parseInt(calYear, 10);
var firstCalDay = new Date(val3,val2,1);
var val0 = firstCalDay.getDay();
startIndex = val0 + 1;
var dayCount = 1;
for (x =1; x < 38; x++){
var cell = document.getElementById('cell'+x);
if( x < startIndex){
cell.innerHTML = ' ';
cell.className = 'firstCell';
}
if( x >= startIndex){
cell.innerHTML = dayCount;
cell.className = 'filledCell';
for(p = 0; p < fillDate.length; p++){
if(dayCount == fillDate[p]){
if(fillDate[p].length == 1){
fillURL = '0'+fillDate[p];
}
else {
fillURL = fillDate[p];
}
cell.className = 'highlightCell';
cell.innerHTML = '<a href="/search?updated-max='+calYear+'-'+callmth+'-'+fillURL+'T23%3A59%3A59'+timeOffset+'&updated-min='+calYear+'-'+callmth+'-'+fillURL+'T00%3A00%3A00'+timeOffset+'" title="'+fillTitles[fillDate[p]].replace(/"/g,'\'')+'">'+dayCount+'</a>';
}
}
if( dayCount > fill[valxx]){
cell.innerHTML = ' ';
cell.className = 'emptyCell';
}
dayCount++;
}
}
visTotal = parseInt(startIndex) + parseInt(fill[valxx]) -1;
if(visTotal >35){
document.getElementById('lastRow').style.display = '';
}
}
function initCal(){
document.getElementById('blogger_calendar').style.display = 'block';
var bcInit = document.getElementById('bloggerCalendarList').getElementsByTagName('a');
var bcCount = document.getElementById('bloggerCalendarList').getElementsByTagName('li');
document.getElementById('bloggerCalendarList').style.display = 'none';
calHead = document.getElementById('bcHead');
tr = document.createElement('tr');
for(t = 0; t < 7; t++){
th = document.createElement('th');
th.abbr = headDays[t];
scope = 'col';
th.title = headDays[t];
th.innerHTML = headInitial[t];
tr.appendChild(th);
}
calHead.appendChild(tr);
for (x = 0; x <bcInit.length;x++){
var stripYear= bcInit[x].href.split('_')[0].split('/')[3];
var stripMonth = bcInit[x].href.split('_')[1];
bcList.push(stripMonth + ','+ stripYear + ',' + x);
bcNav.push(bcInit[x].href);
}
var sel = document.createElement('select');
sel.id = 'bcSelection';
sel.onchange = function(){var cSend = this.options[this.selectedIndex].value.split(',');openStatus();callArchive(cSend[0],cSend[1],cSend[2]);};
q = 0;
for (r = 0; r <bcList.length; r++){
var selText = bcInit[r].innerHTML;
var selCount = bcCount[r].innerHTML.split('> (')[1];
var selValue = bcList[r];
sel.options[q] = new Option(selText + ' ('+selCount,selValue);
q++
}
document.getElementById('bcaption').appendChild(sel);
var m = bcList[0].split(',')[0];
var y = bcList[0].split(',')[1];
callArchive(m,y,'0');
}
function timezoneSet(root){
var feed = root.feed;
var updated = feed.updated.$t;
var id = feed.id.$t;
bcBlogId = id.split('blog-')[1];
upLength = updated.length;
if(updated.charAt(upLength-1) == "Z"){timeOffset = "+07:00";}
else {timeOffset = updated.substring(upLength-6,upLength);}
timeOffset = encodeURIComponent(timeOffset);
} | JavaScript |
//<![CDATA[
imgr = new Array();
imgr[0] = "http://2.bp.blogspot.com/-uitX7ROPtTU/Tyv-G4NA_uI/AAAAAAAAFBY/NcWLPVnYEnU/s1600/no+image.jpg";
showRandomImg = true;
aBold = true;
summaryPost1 = 80;
summaryTitle = 20;
numposts1 = 10;
function removeHtmlTag(strx,chop){
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
s = s.join("");
s = s.substring(0,chop-1);
return s;
}
function showrecentposts1(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
for (var i = 0; i < numposts1; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = m+ ' ' + day + ' ' + y ;
var trtd = '<div class="crott"><a href="'+posturl+'">'+posttitle+'</a><p>'+removeHtmlTag(postcontent,summaryPost1)+'... </p></div>';
document.write(trtd);
j++;
}
}
function showrecentposts2(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
for (var i = 0; i < numposts1 ; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = day+ ' ' + m + ' ' + y ;
var trtd = '<a href="'+posturl+'"><img src="'+img[i]+'"/></a>';
document.write(trtd);
j++;
}
}
//]]> | JavaScript |
/*
* Copyright (C) 2013 rdrrlabs gmail com,
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* grid control */
var timeriGCMTable;
var timeriGCMTableSelection;
$(document).ready(function() {
timeriGCMTable = $("#timeriGCMTable").dataTable( {
"sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
// http://www.datatables.net/usage/server-side
"bServerSide": true,
"bFilter ": false,
"bSort ": false,
"bSortClasses": false,
"sAjaxSource": "/timer_gcm/get",
"sPaginationType": "bootstrap",
"aoColumns": [
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
]
})
// Row selection: http://www.datatables.net/examples/api/select_single_row.html
$("#timeriGCMTable tbody").click(function(event) {
$(timeriGCMTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass("row_selected")
})
var tr = event.target.parentNode
$(tr).addClass("row_selected")
timeriGCMOnRowSelected(timeriGCMTable.fnGetData(tr))
})
timeriGCMUnselectAll()
} )
// -----------------------------------------------------------
// No Add Dialog
// -----------------------------------------------------------
function timeriGCMRefresh() {
timeriGCMUnselectAll()
timeriGCMTable.fnDraw()
}
// -----------------------------------------------------------
function timeriGCMUnselectAll() {
timeriGCMTableSelection = undefined;
$(timeriGCMTable.fnSettings().aoData).each(function () {
$(this.nTr).removeClass("row_selected")
})
var b = $("#timeriGCMDeleteButton")
b.attr("disabled", "disabled");
b.attr("title", "Select a row to delete it.")
//--b = $("#timeriGCMAddButton")
//--b.html("Add new user...")
}
function timeriGCMOnRowSelected(trGetData) {
if (trGetData != undefined && trGetData.length == 2) {
timeriGCMTableSelection = trGetData
var b = $("#timeriGCMDeleteButton").removeAttr("disabled");
b.attr("title", "Delete entry for email [" + timeriGCMTableSelection[0] + "]")
//--b = $("#timeriGCMAddButton")
//--b.html("Add/Edit user...")
}
}
function timeriGCMDelete() {
if (timeriGCMTableSelection == undefined) {
alert("Error. Nothing to delete.")
return
}
if (!confirm("Do you want to delete [" + timeriGCMTableSelection[0] + "] ?")) {
return
}
var q = $.ajax({
type: "DELETE",
url: "/timer_gcm/del/" + encodeURI(timeriGCMTableSelection[0]),
error: function(xhr, status, error) {
var str = $.trim(error + ": " + xhr.responseText.replace(/[^A-Za-z0-9]+/gi, " "));
alert(str)
},
success: function(data, status, xhr) {
timeriGCMRefresh()
},
})
}
| JavaScript |
/* grid control */
/* Source: http://www.datatables.net/blog/Twitter_Bootstrap_2
and at the bottom, all the JS to make datatable compatible with bootstrap's look:
http://www.datatables.net/media/blog/bootstrap_2/DT_bootstrap.js
*/
$.extend( $.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline"
} );
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": oSettings._iDisplayLength === -1 ?
0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
};
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).addClass('pagination').append(
'<ul>'+
'<li class="prev disabled"><a href="#">← '+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+' → </a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, ien=an.length ; i<ien ; i++ ) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
} );
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ( $.fn.DataTable.TableTools ) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend( true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
} );
// Have the collection use a bootstrap compatible dropdown
$.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
} );
}
// -----------------------------------------------------------
| JavaScript |
$(function(){
var aBackgrounds = $( 'section > .bg' )
, $content = $( '#content' )
;
function measureBackgrounds(){
var i, l, oData, $item, $section, fRW, fRH;
for( i=0, l=aBackgrounds.length; i<l; i++ ){
$item = aBackgrounds.eq(i);
oData = $item.data();
$section = $item.parent();
$section.appendTo( $content );
if( !oData.width ){
oData.width = $item.width();
oData.height = $item.height();
}
fRW = $section.width() / oData.width;
fRH = $section.height() / oData.height;
$item.css( { width: 'auto', height: 'auto' } ).css( fRW > fRH ? 'width' : 'height', '100%' );
$section.detach();
}
}
$( window ).bind( 'post-resize-anim', measureBackgrounds );
}); | JavaScript |
$(function() {
//LANGUAGE BUTTONS EFFECTS
$('#lang > ul > li > a').mouseover(function() {
$(this).css({'color': '#E8E595'});
}).mouseout(function() {
$(this).css({'color': ''});
});
//SLIDES - WORK SHOW/HIDE BUTTONS
$('.how_we_work_nav').find('li').click(function(){
var i = $('.how_we_work_nav > ul > li').index(this);
//if visibility check, else no action
if( $(".slides_work:eq(" + i + "):visible").length !== 1 ) {
//animate buttons
$(".how_we_work_buttons").removeClass('b_active');
$(".how_we_work_buttons:eq(" + i + ")").addClass(' b_active');
//calculate left margin
var $div = $(".slides_work:eq(" + i + ")");
var $lm = ($div.parent().width() / 2 - $div.width() / 2) / $div.parent().width() * 100 + "%";
$(".slides_work").hide();
$div.css({'marginLeft' : '-100%' , 'opacity' : '0'})
.show()
.animate({'marginLeft' : $lm
, 'opacity' : '1'}, 1200, "easeInOutQuint");
}
});
//CONTACT FORM SHOW/HIDE BUTTONS
$('.contact_us_nav').find('li').click(function(){
var i = $('.contact_us_nav > ul > li').index(this);
//if visibility check, else no action
if( $(".contact_forms:eq(" + i + "):visible").length !== 1 ) {
//animate buttons
$(".project_form_buttons").css('background', 'transparent');
$(".project_form_buttons:eq(" + i + ")").css('background', '#D0A825');
$(".contact_forms").stop().hide();
$(".contact_forms:eq(" + i + ")")
.effect('bounce', {"direction" : "down", "mode" : "show", "distance" : "6", "times" : 2}, 800);
$('input, textarea').placeholder();
}
});
//ROTATING BILLBOARD
var Banner = setInterval( "slideSwitch(direction, easing)", 9000 );
//Banner;
//STOP BILLBOARD ROTATION clearInterval(Banner);
var playback = true;
$('#playback').click(function() {
if(playback === true) {
$(this).find('img').attr("src", "http://forafreeworld.com/img/playback_play.png").effect('highlight', 1000);
clearInterval(Banner);
playback = false;
} else {
$(this).find('img').attr("src", "http://forafreeworld.com/img/playback_pause.png").effect('highlight', 1000);
Banner = setInterval( "slideSwitch(direction, easing)", 9000 );
playback = true;
}
});
//BE FREE BUTTON HOVER
$('#be_free_button').mouseover(function() {
$(this).stop().animate({ "borderColor" : "#3F617B", "backgroundColor" : "#FFF", "color" : "#3F617B"}, 500);
})
.mouseout(function() {
$(this).stop().animate({ "borderColor" : "#FFF", "backgroundColor" : "transparent", "color" : "#fff"}, 500);
})
.click(function() {
$(this).stop().animate({ "borderColor" : "#FFF", "backgroundColor" : "transparent", "color" : "#fff"}, 500);
});
//TEXTAREA AUTO-RESIZE
$('body').on('keyup','textarea', function (){
$(this).css({'minHeight' : '40px', 'maxHeight' : '100px', 'height' : 'auto' });
$(this).height( this.scrollHeight );
});
$('body').find( 'textarea' ).keyup();
//form support for browsers not supporting placeholder
$('input, textarea').placeholder();
});
//define animation options - our work
var direction = new Array();
direction[0] = {
"left" : "-150%",
"top" : "-150%"
};
direction[1] = {
"top" : "150%"
};
direction[2] = {
"left" : "150%"
};
direction[3] = {
"top" : "-150%"
};
var easing = new Array('easeInQuint', 'easeInOutElastic', 'easeOutBack', 'easeOutCirc');
function slideSwitch(dir, ease) {
var $active = $('#slider_work > div.active');
if ( $active.length == 0 ) $active = $('#slider_work > div:last');
var $next = $active.next('div').length ? $active.next('div') : $('#slider_work > div:first');
$active.addClass('last-active');
//random direction generator
var i = Math.floor(Math.random()*4);
var j = Math.floor(Math.random()*4);
var option = dir[i];
var easing = ease[j];
$next.css(option)
.addClass('active')
.animate({ "left" : "" , "top" : ""}, {duration: 2000, easing: easing, start: function() {
$active.removeClass('active last-active');
}
});
} | JavaScript |
/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input');
var isTextareaSupported = 'placeholder' in document.createElement('textarea');
var prototype = $.fn;
var valHooks = $.valHooks;
var propHooks = $.propHooks;
var hooks;
var placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
var $passwordInput = $element.data('placeholder-password');
if ($passwordInput) {
return $passwordInput[0].value;
}
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
var $passwordInput = $element.data('placeholder-password');
if ($passwordInput) {
return $passwordInput[0].value = value;
}
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != safeActiveElement()) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
if (!isInputSupported) {
valHooks.input = hooks;
propHooks.value = hooks;
}
if (!isTextareaSupported) {
valHooks.textarea = hooks;
propHooks.value = hooks;
}
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {};
var rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
}
function setPlaceholder() {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) {}
}
}(this, document, jQuery)); | JavaScript |
$(function(){
var $nav = $('#nav'), aRules = [];
//create the ul
$('section').each(function(){
var $this = $(this)
, sTitle = $this.attr('data-nav') || $this.find('h2:first').text()
, sId = $this.attr('id').split('-').pop(); //story-header -> header
aRules.push('body.section-' + sId + ' #nav li.' + sId + ' a');
$nav.append('<li class="' + sId + '"><h1><span>' + sTitle +
'</span></h1><a href="#' + sId + '">' + sId + '</a></li>');
});
//add blog link to menu manually
var $url = $(location).attr('href');
var $lang = 'en';
var $blog = 'Blog';
if ($url.toLowerCase().indexOf('/bg/') >= 0) { $lang = 'bg'; $blog = 'Блог'; }
$nav.append('<li class="Blog"><h1><span>' + $blog + '</span></h1>' +
'<a href="http://blog.forafreeworld.com" target="_blank">' + $blog + '</a></li>');
$nav.on('click', 'a', function(){
scrollToSection($(this).attr('href').substr(1)); //to remove #
});
//scrollToSection for all a's in document
$('body').on('click', 'a', function(ev){
var href = this.getAttribute('href') || '';
if( href.indexOf('#') === 0){
ev.preventDefault();
scrollToSection(href.substr(1));
}
} );
}); | JavaScript |
$(function(){
var $window = $( window )
, $body = $( 'body' )
, $bodyAndHTML = $body.add( 'html' )
, $content = $( '#content' )
, $sections = $content.find( 'section' )
, $scroller = $( '#mock-scroller' )
, fScrPercent = 0
, aAnimProps = [ 'opacity', 'left', 'top', 'width', 'height', 'background-position' ]
, sHash = location.hash
, bAllowAnims = !~location.href.indexOf( 'noanims' )
, aAnimations = []
, webkitCSS = document.body.style[ 'webkitTransform' ] !== undefined
, mozCSS = document.body.style[ 'MozTransform' ] !== undefined
, msCSS = document.body.style[ 'msTransform' ] !== undefined
, iAnimTimeout, iWindowHeight, sLastHash, iMaxHeight, iWinScrTop, iLastScrTime, iScrTimeout, sWinSize, kinetics
;
// find all animatable nodes and store properties
$sections.each( function( ix ){
var $sec = $sections.eq( ix );
$sec.data( '$pNodes' , $sec.find( '.animate' ) );
$sec.data( 'bSection', true );
$sec.add( $sec.data( '$pNodes' ) ).each( function(){
var $this = $( this )
, oData = $this.data()
;
oData.iPause = 0 | $this.attr( 'anim-pause' );
oData.bDetached = !!~'1 true'.indexOf( $this.attr( 'anim-detached' ) );
oData.fSpeed = parseFloat( $this.attr( 'anim-speed' ) ) || 1;
oData.onFocus = $this.attr( 'anim-focus-handler' );
oData.onBlur = $this.attr( 'anim-blur-handler' );
} );
// remove the section from the DOM
$sec.detach();
} );
// converts a unit string to px
function parseUnit( vVal, $node, sValFn ){
var aVal = /(-?\d+)(.*)/.exec( vVal )
, fUnit = parseFloat( aVal[ 1 ] )
, sUnit = aVal[ 2 ]
;
switch( sUnit ){
case '':
case 'px':
return fUnit;
case '%':
return $node[ sValFn ]() * fUnit / 100;
default:
throw new Error( 'Unexpected unit type: ' + sUnit );
return;
}
}
// reads all listed css properties from $node with sClass applied
function readCSSProps( $node, sClass ){
var oObj = {}
, i, l, vPropVal, sProp
;
$node.addClass( sClass ).removeAttr( 'style' );
for( i=0, l=aAnimProps.length; i<l; i++ ){
sProp = aAnimProps[i];
switch( sProp ){
// numeric css
case 'opacity':
vPropVal = 0 | $node.css( sProp );
break;
// numeric position
case 'left':
case 'top':
vPropVal = $node.position()[ sProp ];
break;
// numeric size
case 'width':
case 'height':
vPropVal = $node[ 'outer' + sProp.substr( 0, 1 ).toUpperCase() + sProp.substr( 1 ) ]();
break;
// split numeric properties
case 'background-position':
vPropVal = ( $node.css( sProp ) || '0 0' ).split( ' ' );
vPropVal[0] = parseUnit( vPropVal[0], $node, 'outerWidth' );
vPropVal[1] = parseUnit( vPropVal[1], $node, 'outerHeight' );
break;
}
oObj[ sProp ] = vPropVal;
}
$node.removeClass( 'start focus to end' );
return oObj;
}
// determines if two values are equal if they are basic types or arrays
function eq( vVal1, vVal2 ){
var i, l;
if( vVal1 === vVal2 ){ return true; }
if( typeof vVal1 !== typeof vVal2 ){ return false; }
if( vVal1.length && vVal1.splice && vVal2.length && vVal2.splice ){
if( vVal1.length != vVal2.length ){ return false; }
for( i=0, l=vVal1.length; i<l; i++ ){
if( !eq( vVal1[i], vVal2[i] ) ){
return false;
}
}
return true;
}
return false;
}
// returns properties that differ between two objects
function propDiff( oProps1, oProps2 ){
var oDiff = {}
, n, bProp;
for( n in oProps2 ){
if( !eq( oProps1[n], oProps2[n] ) ){
oDiff[n] = bProp = [ oProps1[n], oProps2[n] ];
}
}
return bProp && oDiff;
}
// given a node, top & stage, stores an animation for the node
function addDiffAnimation( $node, iTop, iStage, iAnimLength ){
var stages = [ 'start', 'focus', 'to', 'end' ]
, iStartStage = iStage - 1
, sEndStage = stages[ iStage ]
, oPropsEnd = readCSSProps( $node, sEndStage )
, oData = $node.data()
, bPreDefLen = !!iAnimLength
, oPropDiff, n, iDiff
;
if( !iAnimLength ){ iAnimLength = 0; }
// get the diff between this stage and the prior one
oPropDiff = propDiff( readCSSProps( $node, stages[ iStartStage ] ), oPropsEnd );
if( !oPropDiff ){ return 0; }
for( n in oPropDiff ){
iDiff = Math.abs( oPropDiff[n][1] - oPropDiff[n][0] );
if( !bPreDefLen && ( iDiff > iAnimLength ) ){ iAnimLength = iDiff; }
}
aAnimations.push( {
$node : $node
, oProps : oPropDiff
, iTop : iTop
, iBottom : iTop + iAnimLength
, bSection : oData.bSection
} );
return oData.bDetached ? 0 : iAnimLength;
}
// window loaded or re-sized, re-calculate all dimensions
function measureAnimations(){
var iTop = 0
, iStartTimer = +new Date()
, iLastSection = $sections.length - 1
, iPageHeight = 0
, oAnim, oData
;
aAnimations = window.aAnimations = [];
$scroller.css( 'height', 10000 );
// add animations for each section & .animate tag in each section
$sections.each( function( ix ){
var $sec = $( this )
, oData = $sec.data()
, $pNodes = oData.$pNodes
, iSecHeight = 0
, iMaxPause = oData.iPause
, i, l, iAnimSize, $pNode
;
oData.startsAt = iTop;
// append section to content and reset position
$sec
.css({ top : '', visibility: 'hidden' })
.appendTo( $content );
if( ix ){
iSecHeight = addDiffAnimation( $sec, iTop, 1 );
}
for( i=0, l=$pNodes.length; i<l; i++ ){
$pNode = $pNodes.eq( i );
if( bAllowAnims ){
iMaxPause = Math.max(
iMaxPause
, addDiffAnimation( $pNode, iTop , 1, iSecHeight )
, iAnimSize = addDiffAnimation( $pNode, iTop + iSecHeight + iMaxPause , 2, iSecHeight )
, addDiffAnimation( $pNode, iTop + iSecHeight + iMaxPause + iAnimSize, 3, iSecHeight )
);
}
}
if( ix ){
iTop += iMaxPause; // Math.max( iSecHeight, iMaxPause, $sec.outerHeight() );
}
addDiffAnimation( $sec, iTop + iSecHeight, 2 );
if( ix < iLastSection ){
addDiffAnimation( $sec, iTop + iSecHeight, 3 );
}
$sec.detach().css({ visibility: 'visible' });
oData.endsAt = iTop += iSecHeight;
oData.bVisible = false;
} );
// wipe start/end positions on sections
for( i=0, l=$sections.length; i<l; i++ ){
$sections.eq(i).data().iTop = Infinity;
$sections.eq(i).data().iBottom = -Infinity;
}
// post-process animations
for( i=0, l=aAnimations.length; i<l; i++ ){
oAnim = aAnimations[i];
if( oAnim.iBottom > iPageHeight ){
iPageHeight = oAnim.iBottom;
}
if( oAnim.bSection ){
oData = oAnim.$node.data();
if( oAnim.iTop < oData.iTop ){
oData.iTop = oAnim.iTop;
}
if( oAnim.iBottom > oData.iBottom ){
oData.iBottom = oAnim.iBottom;
}
}
}
iPageHeight = Math.max( iPageHeight, ++$sections.last().data().iBottom );
$scroller.css( 'height', ( iMaxHeight = iPageHeight ) + iWindowHeight );
$window.trigger( 'animations-added', { animations: aAnimations } );
}
function onResize(){
var pTop = ( iWinScrTop / iMaxHeight ) || 0;
measureAnimations();
$window.trigger( 'post-resize-anim' );
$window.scrollTop( pTop * iMaxHeight );
onScroll();
kinetics
.adjustRange( iMaxHeight )
.setPosition( pTop * iMaxHeight );
}
function singlePartialCSSProp( iScrTop, oAnim, oProp ){
return ( iScrTop - oAnim.iTop ) / ( oAnim.iBottom - oAnim.iTop ) * ( oProp[1] - oProp[0] ) + oProp[0];
}
function partialCSSProp( iScrTop, oAnim, oProp ){
if( oProp[0].splice ){
return $.map( oProp[0], function( nul, ix ){
return ( 0|singlePartialCSSProp( iScrTop, oAnim, [ oProp[0][ix], oProp[1][ix] ] ) ) + 'px';
} ).join( ' ' );
}else{
return singlePartialCSSProp( iScrTop, oAnim, oProp );
}
}
function onScrollHandler(){
var cDate = +new Date()
, iScrTop = $window.scrollTop()
, iDiff = cDate - iLastScrTime
;
iLastScrTime = cDate;
if( iScrTimeout ){
clearTimeout( iScrTimeout );
iScrTimeout = 0;
}
// last tick was either recent enough or a while ago. pass through
if( ( iDiff > 200 ) || ( iDiff < 50 ) ){
onScroll( iScrTop );
}else{
// stupid browser scrolling is too slow, fix it
var iLastTop = iWinScrTop
, iScrDiff = iScrTop - iLastTop
;
function nextScrollTick(){
var now = +new Date()
, iStep = ( now + 30 - cDate ) / iDiff;
if( iStep > 1 ){ iStep = 1; }
onScroll( iLastTop + iScrDiff * iStep )
if( iStep < 1 ){
iScrTimeout = setTimeout( nextScrollTick, 30 );
}
}
nextScrollTick();
}
}
function onScroll( iScrTop ){
var bChangedLoc = false
, i, l, oAnim, $sec, oData
, $node, sSecId, n, oCssProps, oProps, iCurScr, sState
;
iScrTop || ( iScrTop = $window.scrollTop() );
iWinScrTop = iScrTop;
if( iScrTop < 0 ){ iScrTop = 0; }
if( iScrTop > iMaxHeight ){ iScrTop = iMaxHeight; }
// hide/show sections
for( i=0, l=$sections.length; i<l; i++ ){
$sec = $sections.eq(i);
oData = $sec.data();
if( ( oData.iTop <= iScrTop ) && ( oData.iBottom >= ( iScrTop ) ) ){
if( !oData.bVisible ){
$sec.appendTo( $content );
oData.bVisible = true;
}
if( !bChangedLoc ){
if( sLastHash != ( sSecId = $sec.attr( 'id' ).split( '-' ).pop() ) ){
location.replace( '#' + ( sLastHash = sSecId ) );
$body.prop( 'class', $body.prop( 'class' ).replace( /(?: |^)section-[^ ]+/g, '' ) ).addClass( 'section-' + sSecId );
}
bChangedLoc = true;
}
}else{
if( oData.bVisible ){
$sec.detach();
oData.bVisible = false;
}
}
}
for( i=0, l=aAnimations.length; i<l; i++ ){
oAnim = aAnimations[i];
$node = oAnim.$node;
iCurScr = iScrTop;
if( ( oAnim.iTop > iCurScr ) || ( oAnim.iBottom < iCurScr ) ){
sState = oAnim.lastState;
oAnim.lastState = 'disabled';
// animation is newly disabled
if( sState === 'enabled' ){
iCurScr = ( oAnim.iTop > iCurScr ) ? oAnim.iTop : oAnim.iBottom;
}else{
continue;
}
}else{
oAnim.lastState = 'enabled';
}
// in the middle of an animation
oCssProps = {};
oProps = oAnim.oProps;
for( n in oProps ){
oCssProps[ n ] = partialCSSProp( iCurScr, oAnim, oProps[n] );
//oCssProps[n] = 0|-( ( iScrTop - oProps[n][0] ) / ( oProps[n][1] - oProps[n][0] ) * ( oProps[n][1] - oProps[n][0] ) + oProps[n][0] );
}
$node.css( hardwareCSSTransform( oCssProps ) );
}
}
function hardwareCSSTransform( props ){
if( props.top!=null || props.left!=null ){
if( webkitCSS ){
props.webkitTransform = 'translate3d(' + ( props.left || 0 ) + 'px, ' + ( props.top || 0 ) + 'px, 0)';
if( null != props.top ){ props.top = 0; }
if( null != props.left ){ props.left = 0; }
}
if( mozCSS || msCSS ){
props[ mozCSS ? 'MozTransform' : 'msTransform' ] = ( props.top ? 'translateY(' + props.top + 'px)' : '' ) + ( props.left ? 'translateX(' + props.left + 'px)' : '' );
if( null != props.top ){ props.top = 0; }
if( null != props.left ){ props.left = 0; }
}
}
return props;
}
window.getAnimationController = function( sSelector ){
var oAnim, i, l;
for( i=0, l=aAnimations.length; i<l; i++ ){
if( aAnimations[i].$node.is( sSelector ) ){
oAnim = aAnimations[i];
break;
}
}
if( !oAnim ){
throw new Error( 'no animation matches selector ' + sSelector );
}
return {
scrollTo: function( iTop ){
iTop += oAnim.iTop;
iTop = Math.max( oAnim.iTop, Math.min( oAnim.iBottom, iTop ) );
$bodyAndHTML.scrollTop( iTop );
}
, scrollBy : function( iTop ){
iTop = iWinScrTop + iTop;
iTop = Math.max( oAnim.iTop, Math.min( oAnim.iBottom, iTop ) );
$bodyAndHTML.scrollTop( iTop );
}
}
}
window.scrollToSection = function( sSec, immediate ){
var $sect = $sections.filter( '#section-' + sSec )
, oData = $sect.data()
, top = oData.iTop + ( $sections[0] === $sect[0] ? 0 : iWindowHeight + 1 );
if( immediate ){
$bodyAndHTML.scrollTop( top );
}else{
$bodyAndHTML.animate({ scrollTop: top }, 1000);
}
}
if( sHash ){
setTimeout( function(){
scrollToSection( sHash.substr( 1 ), true );
}, 100 );
}
/* touch move kinetics */
kinetics = new Kinetics( window );
window.kinetics = kinetics;
kinetics.bind( 'move', function( ev, y ){
onScroll( y );
} );
$window
/**
* On resize:
*
* - save window height for onscroll calculations
* - re-calculate the height of all the <section> elements
* - adjust top position so that it's at the same %, not same px
**/
.bind( 'resize', function(){
// patch IE which keeps triggering resize events when elements are resized
var sCurWinSize = $window.width() + 'x' + $window.height();
if( sCurWinSize === sWinSize ){ return; }
sWinSize = sCurWinSize;
if( iAnimTimeout ){ clearTimeout( iAnimTimeout ); }
iAnimTimeout = setTimeout( onResize, 50 );
iWindowHeight = $window.height();
})
.trigger( 'resize' )
.bind( 'scroll', onScrollHandler );
}); | JavaScript |
~function(){
function KineticModel() {
var min = 0
, max = 1000
, lastPosition = 0
, velocity = 0
, timestamp = Date.now()
, timeConstant, ticker
;
function clamped(pos) {
return (pos > max) ? max : (pos < min) ? min : pos;
}
function nop() {}
this.duration = 1950;
this.position = 0;
this.updateInterval = 1000 / 60;
this.onPositionChanged = nop;
this.onScrollStarted = nop;
this.onScrollStopped = nop;
this.setRange = function (start, end) {
min = start;
max = end;
};
this.getRange = function () {
return {
minimum : min
, maximum : max
};
};
this.setPosition = function (pos) {
var self = this;
this.position = clamped(pos);
this.onPositionChanged(this.position);
if (!ticker) {
// Track down the movement to compute the initial
// scrolling velocity.
ticker = window.setInterval(function () {
var now = Date.now(),
elapsed = now - timestamp,
v = (self.position - lastPosition) * 1000 / elapsed;
// Moving average to filter the speed.
if (ticker && elapsed >= self.updateInterval) {
timestamp = now;
if (v > 1 || v < -1) {
velocity = 0.2 * (velocity) + 0.8 * v;
lastPosition = self.position;
}
}
}, this.updateInterval);
}
};
this.resetSpeed = function () {
velocity = 0;
lastPosition = this.position;
window.clearInterval(ticker);
ticker = null;
};
this.release = function () {
var self = this
, amplitude = velocity
, targetPosition = this.position + amplitude
, timeConstant = 1 + this.duration / 6
, timestamp = Date.now()
;
window.clearInterval(ticker);
ticker = null;
if (velocity > 1 || velocity < -1) {
this.onScrollStarted(self.position);
window.clearInterval(ticker);
ticker = window.setInterval(function () {
var elapsed = Date.now() - timestamp;
if (ticker) {
self.position = targetPosition - amplitude * Math.exp(-elapsed / timeConstant);
self.position = clamped(self.position);
self.onPositionChanged(self.position);
if (elapsed > self.duration) {
self.resetSpeed();
self.onScrollStopped(self.position);
}
}
}, this.updateInterval);
}
};
}
function Kinetics( el ){
var scroller = new KineticModel()
, pressed = false
, refPos = 0
, $watcher = $( '<div></div>' );
scroller.onPositionChanged = function( y ){
$watcher.trigger( 'move', y );
};
$watcher.adjustRange = function( max ){
scroller.setRange( 0, max );
return $watcher
}
$watcher.setPosition = function( y ){
scroller.position = y;
return $watcher;
}
function tap( e ){
pressed = true;
if (e.targetTouches && (e.targetTouches.length >= 1)) {
refPos = e.targetTouches[0].clientY;
} else {
refPos = e.clientY;
}
scroller.resetSpeed();
e.preventDefault();
e.stopPropagation();
return false;
}
function untap( e ){
pressed = false;
scroller.release();
e.preventDefault();
e.stopPropagation();
return false;
}
function drag( e ){
var pos, delta;
if (!pressed) {
return;
}
if (e.targetTouches && (e.targetTouches.length >= 1)) {
pos = e.targetTouches[0].clientY;
} else {
pos = e.clientY;
}
delta = refPos - pos;
if (delta > 2 || delta < -2) {
scroller.setPosition( scroller.position += delta );
refPos = pos;
}
e.preventDefault();
e.stopPropagation();
return false;
}
if( el.addEventListener ){
el.addEventListener( 'touchstart', tap );
el.addEventListener( 'touchmove' , drag );
el.addEventListener( 'touchend' , untap );
}
return $watcher;
}
window.Kinetics = Kinetics;
}(); | JavaScript |
/**
* @preserve HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
/** version */
var version = '3.6.2';
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
// assign a false positive if detection fails => unable to shiv
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/\w+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}' +
// hides non-rendered elements
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video',
/**
* current version of html5shiv
*/
'version': version,
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
/*------------------------------- Print Shiv -------------------------------*/
/** Used to filter media types */
var reMedia = /^$|\b(?:all|print)\b/;
/** Used to namespace printable elements */
var shivNamespace = 'html5shiv';
/** Detect whether the browser supports shivable style sheets */
var supportsShivableSheets = !supportsUnknownElements && (function() {
// assign a false negative if unable to shiv
var docEl = document.documentElement;
return !(
typeof document.namespaces == 'undefined' ||
typeof document.parentWindow == 'undefined' ||
typeof docEl.applyElement == 'undefined' ||
typeof docEl.removeNode == 'undefined' ||
typeof window.attachEvent == 'undefined'
);
}());
/*--------------------------------------------------------------------------*/
/**
* Wraps all HTML5 elements in the given document with printable elements.
* (eg. the "header" element is wrapped with the "html5shiv:header" element)
* @private
* @param {Document} ownerDocument The document.
* @returns {Array} An array wrappers added.
*/
function addWrappers(ownerDocument) {
var node,
nodes = ownerDocument.getElementsByTagName('*'),
index = nodes.length,
reElements = RegExp('^(?:' + getElements().join('|') + ')$', 'i'),
result = [];
while (index--) {
node = nodes[index];
if (reElements.test(node.nodeName)) {
result.push(node.applyElement(createWrapper(node)));
}
}
return result;
}
/**
* Creates a printable wrapper for the given element.
* @private
* @param {Element} element The element.
* @returns {Element} The wrapper.
*/
function createWrapper(element) {
var node,
nodes = element.attributes,
index = nodes.length,
wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName);
// copy element attributes to the wrapper
while (index--) {
node = nodes[index];
node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue);
}
// copy element styles to the wrapper
wrapper.style.cssText = element.style.cssText;
return wrapper;
}
/**
* Shivs the given CSS text.
* (eg. header{} becomes html5shiv\:header{})
* @private
* @param {String} cssText The CSS text to shiv.
* @returns {String} The shived CSS text.
*/
function shivCssText(cssText) {
var pair,
parts = cssText.split('{'),
index = parts.length,
reElements = RegExp('(^|[\\s,>+~])(' + getElements().join('|') + ')(?=[[\\s,>+~#.:]|$)', 'gi'),
replacement = '$1' + shivNamespace + '\\:$2';
while (index--) {
pair = parts[index] = parts[index].split('}');
pair[pair.length - 1] = pair[pair.length - 1].replace(reElements, replacement);
parts[index] = pair.join('}');
}
return parts.join('{');
}
/**
* Removes the given wrappers, leaving the original elements.
* @private
* @params {Array} wrappers An array of printable wrappers.
*/
function removeWrappers(wrappers) {
var index = wrappers.length;
while (index--) {
wrappers[index].removeNode();
}
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document for print.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivPrint(ownerDocument) {
var shivedSheet,
wrappers,
data = getExpandoData(ownerDocument),
namespaces = ownerDocument.namespaces,
ownerWindow = ownerDocument.parentWindow;
if (!supportsShivableSheets || ownerDocument.printShived) {
return ownerDocument;
}
if (typeof namespaces[shivNamespace] == 'undefined') {
namespaces.add(shivNamespace);
}
function removeSheet() {
clearTimeout(data._removeSheetTimer);
if (shivedSheet) {
shivedSheet.removeNode(true);
}
shivedSheet= null;
}
ownerWindow.attachEvent('onbeforeprint', function() {
removeSheet();
var imports,
length,
sheet,
collection = ownerDocument.styleSheets,
cssText = [],
index = collection.length,
sheets = Array(index);
// convert styleSheets collection to an array
while (index--) {
sheets[index] = collection[index];
}
// concat all style sheet CSS text
while ((sheet = sheets.pop())) {
// IE does not enforce a same origin policy for external style sheets...
// but has trouble with some dynamically created stylesheets
if (!sheet.disabled && reMedia.test(sheet.media)) {
try {
imports = sheet.imports;
length = imports.length;
} catch(er){
length = 0;
}
for (index = 0; index < length; index++) {
sheets.push(imports[index]);
}
try {
cssText.push(sheet.cssText);
} catch(er){}
}
}
// wrap all HTML5 elements with printable elements and add the shived style sheet
cssText = shivCssText(cssText.reverse().join(''));
wrappers = addWrappers(ownerDocument);
shivedSheet = addStyleSheet(ownerDocument, cssText);
});
ownerWindow.attachEvent('onafterprint', function() {
// remove wrappers, leaving the original elements, and remove the shived style sheet
removeWrappers(wrappers);
clearTimeout(data._removeSheetTimer);
data._removeSheetTimer = setTimeout(removeSheet, 500);
});
ownerDocument.printShived = true;
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
// expose API
html5.type += ' print';
html5.shivPrint = shivPrint;
// shiv for print
shivPrint(document);
}(this, document));
| JavaScript |
Calendar.LANG("en", "English", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Go Today",
today: "Today", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December" ],
smn : [ "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec" ],
dn : [ "Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" ],
sdn : [ "Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su" ]
});
| JavaScript |
/*
* AVIM JavaScript Vietnamese Input Method Source File dated 28-07-2008
*
* Copyright (C) 2004-2008 Hieu Tran Dang <lt2hieu2004 (at) users (dot) sf (dot) net
* Website: http://noname00.com/hieu
*
* You are allowed to use this software in any way you want providing:
* 1. You must retain this copyright notice at all time
* 2. You must not claim that you or any other third party is the author
* of this software in any way.
*/
var AVIMGlobalConfig = {
method: 0, //Default input method: 0=AUTO, 1=TELEX, 2=VNI, 3=VIQR, 4=VIQR*
onOff: 1, //Starting status: 0=Off, 1=On
ckSpell: 1, //Spell Check: 0=Off, 1=On
oldAccent: 1, //0: New way (oa`, oe`, uy`), 1: The good old day (o`a, o`e, u`y)
useCookie: 1, //Cookies: 0=Off, 1=On
exclude: ["email"], //IDs of the fields you DON'T want to let users type Vietnamese in
showControl: 1, //Show control panel: 0=Off, 1=On. If you turn this off, you must write your own control panel.
controlCSS: "../../../Resource/StyleSheet/Guest/avim.css" //Path to avim.css
};
//Set to true the methods which you want to be included in the AUTO method
var AVIMAutoConfig = {
telex: true,
vni: true,
viqr: false,
viqrStar: false
};
function AVIM() {
this.radioID = "avim_auto,avim_telex,avim_vni,avim_viqr,avim_viqr2,avim_off,avim_ckspell,avim_daucu".split(",");
this.attached = [];
this.changed = false;
this.agt = navigator.userAgent.toLowerCase();
this.alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM\ ";
this.support = true;
this.ver = 0;
this.specialChange = false;
this.is_ie = ((this.agt.indexOf("msie") != -1) && (this.agt.indexOf("opera") == -1));
this.is_opera = false;
this.isKHTML = false;
this.kl = 0;
this.skey = [97,226,259,101,234,105,111,244,417,117,432,121,65,194,258,69,202,73,79,212,416,85,431,89];
this.fID = document.getElementsByTagName("iframe");
this.range = null;
this.whit = false;
this.db1 = [273,272];
this.ds1 = ['d','D'];
this.os1 = "o,O,ơ,Ơ,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(",");
this.ob1 = "ô,Ô,ô,Ô,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",");
this.mocs1 = "o,O,ô,Ô,u,U,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ú,Ú,ù,Ù,ụ,Ụ,ủ,Ủ,ũ,Ũ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",");
this.mocb1 = "ơ,Ơ,ơ,Ơ,ư,Ư,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ,ứ,Ứ,ừ,Ừ,ự,Ự,ử,Ử,ữ,Ữ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(",");
this.trangs1 = "a,A,â,Â,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ".split(",");
this.trangb1 = "ă,Ă,ă,Ă,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ".split(",");
this.as1 = "a,A,ă,Ă,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",");
this.ab1 = "â,Â,â,Â,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",");
this.es1 = "e,E,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",");
this.eb1 = "ê,Ê,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",");
this.english = "ĐÂĂƠƯÊÔ";
this.lowen = "đâăơưêô";
this.arA = "á,à,ả,ã,ạ,a,Á,À,Ả,Ã,Ạ,A".split(',');
this.mocrA = "ó,ò,ỏ,õ,ọ,o,ú,ù,ủ,ũ,ụ,u,Ó,Ò,Ỏ,Õ,Ọ,O,Ú,Ù,Ủ,Ũ,Ụ,U".split(',');
this.erA = "é,è,ẻ,ẽ,ẹ,e,É,È,Ẻ,Ẽ,Ẹ,E".split(',');
this.orA = "ó,ò,ỏ,õ,ọ,o,Ó,Ò,Ỏ,Õ,Ọ,O".split(',');
this.aA = "ấ,ầ,ẩ,ẫ,ậ,â,Ấ,Ầ,Ẩ,Ẫ,Ậ,Â".split(',');
this.oA = "ố,ồ,ổ,ỗ,ộ,ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ô".split(',');
this.mocA = "ớ,ờ,ở,ỡ,ợ,ơ,ứ,ừ,ử,ữ,ự,ư,Ớ,Ờ,Ở,Ỡ,Ợ,Ơ,Ứ,Ừ,Ử,Ữ,Ự,Ư".split(',');
this.trangA = "ắ,ằ,ẳ,ẵ,ặ,ă,Ắ,Ằ,Ẳ,Ẵ,Ặ,Ă".split(',');
this.eA = "ế,ề,ể,ễ,ệ,ê,Ế,Ề,Ể,Ễ,Ệ,Ê".split(',');
this.oA = "ố,ồ,ổ,ỗ,ộ,ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ô".split(',');
this.skey2 = "a,a,a,e,e,i,o,o,o,u,u,y,A,A,A,E,E,I,O,O,O,U,U,Y".split(',');
this.fcc = function(x) {
return String.fromCharCode(x);
}
this.getEL = function(id) {
return document.getElementById(id);
}
this.getSF = function() {
var sf = [], x;
for(x = 0; x < this.skey.length; x++) {
sf[sf.length] = this.fcc(this.skey[x]);
}
return sf;
}
if(AVIMGlobalConfig.showControl) {
this.css = document.createElement('link');
this.css.rel = 'stylesheet';
this.css.type = 'text/css';
this.css.href = AVIMGlobalConfig.controlCSS;
document.getElementsByTagName('head')[0].appendChild(this.css);
document.write('<span id="AVIMControl">');
document.write('<p class="AVIMControl"><input id="avim_auto" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(0);" />Tự động');
document.write('<input id="avim_telex" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(1);" />TELEX');
document.write('<input id="avim_vni" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(2);" />VNI');
document.write('<input id="avim_viqr" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(3);" />VIQR');
document.write('<input id="avim_viqr2" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(4);" />VIQR*');
document.write('<input id="avim_off" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(-1);" />Tắt<br />');
document.write('<a class="AVIMControl" style="float: right; position: relative; top: 3px;" onclick="document.getElementById(' + "'AVIMControl').style.display='none';" + '">[Ẩn AVIM - F12]</a>');
document.write('<input type="checkbox" id="avim_ckspell" onclick="AVIMObj.setSpell(this);" />Chính tả');
document.write('<input type="checkbox" id="avim_daucu" onclick="AVIMObj.setDauCu(this);" />Kiểu cũ</p>');
document.write('</span>');
}
if(!this.is_ie) {
if(this.agt.indexOf("opera") >= 0) {
this.operaV = this.agt.split(" ");
this.operaVersion = parseInt(this.operaV[this.operaV.length - 1]);
if(this.operaVersion >= 8) {
this.is_opera = true;
} else {
this.operaV = this.operaV[0].split("/");
this.operaVersion = parseInt(this.operaV[1]);
if(this.operaVersion >= 8) this.is_opera = true;
}
} else if(this.agt.indexOf("khtml") >= 0) {
this.isKHTML = true;
} else {
this.ver = this.agt.substr(this.agt.indexOf("rv:") + 3);
this.ver = parseFloat(this.ver.substr(0, this.ver.indexOf(" ")));
if(this.agt.indexOf("mozilla") < 0) this.ver = 0;
}
}
this.nospell = function(w, k) {
return false;
}
this.ckspell = function(w, k) {
w = this.unV(w);
var exc = "UOU,IEU".split(','), z, next = true, noE = "UU,UOU,UOI,IEU,AO,IA,AI,AY,AU,AO".split(','), noBE = "YEU";
var check = true, noM = "UE,UYE,IU,EU,UY".split(','), noMT = "AY,AU".split(','), noT = "UA", t = -1, notV2 = "IAO";
var uw = this.up(w), tw = uw, update = false, gi = "IO", noAOEW = "OE,OO,AO,EO,IA,AI".split(','), noAOE = "OA", test, a, b;
var notViet = "AA,AE,EE,OU,YY,YI,IY,EY,EA,EI,II,IO,YO,YA,OOO".split(','), uk = this.up(k), twE, uw2 = this.unV2(uw);
var vSConsonant = "B,C,D,G,H,K,L,M,N,P,Q,R,S,T,V,X".split(','), vDConsonant = "CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',');
var vDConsonantE = "CH,NG,NH".split(','),sConsonant = "C,P,T,CH".split(','),vSConsonantE = "C,M,N,P,T".split(',');
var noNHE = "O,U,IE,Ô,Ơ,Ư,IÊ,Ă,Â,UYE,UYÊ,UO,ƯƠ,ƯO,UƠ,UA,ƯA,OĂ,OE,OÊ".split(','),oMoc = "UU,UOU".split(',');
if(this.FRX.indexOf(uk) >= 0) {
for(a = 0; a < sConsonant.length; a++) {
if(uw.substr(uw.length - sConsonant[a].length, sConsonant[a].length) == sConsonant[a]) {
return true;
}
}
}
for(a = 0; a < uw.length; a++) {
if("FJZW1234567890".indexOf(uw.substr(a, 1)) >= 0) {
return true;
}
for(b = 0; b < notViet.length; b++) {
if(uw2.substr(a, notViet[b].length) == notViet[b]) {
for(z = 0; z < exc.length; z++) {
if(uw2.indexOf(exc[z]) >= 0) {
next=false;
}
}
if(next && ((gi.indexOf(notViet[b]) < 0) || (a <= 0) || (uw2.substr(a - 1, 1) != 'G'))) {
return true;
}
}
}
}
for(b = 0; b < vDConsonant.length; b++) {
if(tw.indexOf(vDConsonant[b]) == 0) {
tw = tw.substr(vDConsonant[b].length);
update = true;
t = b;
break;
}
}
if(!update) {
for(b = 0; b < vSConsonant.length; b++) {
if(tw.indexOf(vSConsonant[b]) == 0) {
tw=tw.substr(1);
break;
}
}
}
update=false;
twE=tw;
for(b = 0; b < vDConsonantE.length; b++) {
if(tw.substr(tw.length - vDConsonantE[b].length) == vDConsonantE[b]) {
tw = tw.substr(0, tw.length - vDConsonantE[b].length);
if(b == 2){
for(z = 0; z < noNHE.length; z++) {
if(tw == noNHE[z]) {
return true;
}
}
if((uk == this.trang) && ((tw == "OA") || (tw == "A"))) {
return true;
}
}
update = true;
break;
}
}
if(!update) {
for(b = 0; b < vSConsonantE.length; b++) {
if(tw.substr(tw.length - 1) == vSConsonantE[b]) {
tw = tw.substr(0, tw.length - 1);
break;
}
}
}
if(tw) {
for(a = 0; a < vDConsonant.length; a++) {
for(b = 0; b < tw.length; b++) {
if(tw.substr(b, vDConsonant[a].length) == vDConsonant[a]) {
return true;
}
}
}
for(a = 0; a < vSConsonant.length; a++) {
if(tw.indexOf(vSConsonant[a]) >= 0) {
return true;
}
}
}
test = tw.substr(0, 1);
if((t == 3) && ((test == "A") || (test == "O") || (test == "U") || (test == "Y"))) {
return true;
}
if((t == 5) && ((test == "E") || (test == "I") || (test == "Y"))) {
return true;
}
uw2 = this.unV2(tw);
if(uw2 == notV2) {
return true;
}
if(tw != twE) {
for(z = 0; z < noE.length; z++) {
if(uw2 == noE[z]) {
return true;
}
}
}
if((tw != uw) && (uw2 == noBE)) {
return true;
}
if(uk != this.moc) {
for(z = 0; z < oMoc.length; z++) {
if(tw == oMoc[z]) return true;
}
}
if((uw2.indexOf('UYE')>0) && (uk == 'E')) {
check=false;
}
if((this.them.indexOf(uk) >= 0) && check) {
for(a = 0; a < noAOEW.length; a++) {
if(uw2.indexOf(noAOEW[a]) >= 0) {
return true;
}
}
if(uk != this.trang) {
if(uw2 == noAOE) {
return true;
}
}
if((uk == this.trang) && (this.trang != 'W')) {
if(uw2 == noT) {
return true;
}
}
if(uk == this.moc) {
for(a = 0; a < noM.length; a++) {
if(uw2 == noM[a]) {
return true;
}
}
}
if((uk == this.moc) || (uk == this.trang)) {
for(a = 0; a < noMT.length; a++) {
if(uw2 == noMT[a]) {
return true;
}
}
}
}
this.tw5 = tw;
if((uw2.charCodeAt(0) == 272) || (uw2.charCodeAt(0) == 273)) {
if(uw2.length > 4) {
return true;
}
} else if(uw2.length > 3) {
return true;
}
return false;
}
this.noCookie = function() {}
this.doSetCookie = function() {
var exp = new Date(11245711156480).toGMTString();
document.cookie = 'AVIM_on_off=' + AVIMGlobalConfig.onOff + ';expires=' + exp;
document.cookie = 'AVIM_method=' + AVIMGlobalConfig.method + ';expires=' + exp;
document.cookie = 'AVIM_ckspell=' + AVIMGlobalConfig.ckSpell + ';expires=' + exp;
document.cookie = 'AVIM_daucu=' + AVIMGlobalConfig.oldAccent + ';expires=' + exp;
}
this.doGetCookie = function() {
var ck = document.cookie, res = /AVIM_method/.test(ck), p, i, ckA = ck.split(';');
if(!res || (ck.indexOf('AVIM_ckspell') < 0)) {
this.setCookie();
return;
}
for(i = 0; i < ckA.length; i++) {
p = ckA[i].split('=');
p[0] = p[0].replace(/^\s+/g, "");
p[1] = parseInt(p[1]);
if(p[0] == 'AVIM_on_off') {
AVIMGlobalConfig.onOff = p[1];
}
else if(p[0] == 'AVIM_method') {
AVIMGlobalConfig.method = p[1];
}
else if(p[0] == 'AVIM_ckspell') {
if(p[1] == 0) {
AVIMGlobalConfig.ckSpell=0;
this.spellerr=this.nospell;
} else {
AVIMGlobalConfig.ckSpell=1;
this.spellerr=this.ckspell;
}
} else if(p[0] == 'AVIM_daucu') {
AVIMGlobalConfig.oldAccent = parseInt(p[1]);
}
}
}
if(AVIMGlobalConfig.useCookie == 1) {
this.setCookie = this.doSetCookie;
this.getCookie = this.doGetCookie;
} else {
this.setCookie = this.noCookie;
this.getCookie = this.noCookie;
}
this.setMethod = function(m) {
if(m == -1) {
AVIMGlobalConfig.onOff = 0;
if(this.getEL(this.radioID[5])) {
this.getEL(this.radioID[5]).checked = true;
}
} else {
AVIMGlobalConfig.onOff = 1;
AVIMGlobalConfig.method = m;
if(this.getEL(this.radioID[m])) {
this.getEL(this.radioID[m]).checked = true;
}
}
this.setSpell(AVIMGlobalConfig.ckSpell);
this.setDauCu(AVIMGlobalConfig.oldAccent);
this.setCookie();
}
this.setDauCu = function(box) {
if(typeof(box) == "number") {
AVIMGlobalConfig.oldAccent = box;
if(this.getEL(this.radioID[7])) {
this.getEL(this.radioID[7]).checked = box;
}
} else {
AVIMGlobalConfig.oldAccent = (box.checked) ? 1 : 0;
}
this.setCookie();
}
this.setSpell = function(box) {
if(typeof(box) == "number") {
this.spellerr = (box == 1) ? this.ckspell : this.nospell;
if(this.getEL(this.radioID[6])) {
this.getEL(this.radioID[6]).checked = box;
}
} else {
if(box.checked) {
this.spellerr = this.ckspell;
AVIMGlobalConfig.ckSpell = 1;
} else {
this.spellerr = this.nospell;
AVIMGlobalConfig.ckSpell = 0;
}
}
this.setCookie();
}
if(this.is_ie || (this.ver >= 1.3) || this.is_opera || this.isKHTML) {
this.getCookie();
if(AVIMGlobalConfig.onOff == 0) this.setMethod(-1);
else this.setMethod(AVIMGlobalConfig.method);
this.setSpell(AVIMGlobalConfig.ckSpell);
this.setDauCu(AVIMGlobalConfig.oldAccent);
} else {
this.support = false;
}
this.mozGetText = function(obj) {
var v, pos, w = "", g = 1;
v = (obj.data) ? obj.data : obj.value;
if(v.length <= 0) {
return false;
}
if(!obj.data) {
if(!obj.setSelectionRange) {
return false;
}
pos = obj.selectionStart;
} else {
pos = obj.pos;
}
if(obj.selectionStart != obj.selectionEnd) {
return ["", pos];
}
while(1) {
if(pos - g < 0) {
break;
} else if(this.notWord(v.substr(pos - g, 1))) {
if(v.substr(pos - g, 1) == "\\") {
w = v.substr(pos - g, 1) + w;
}
break;
} else {
w = v.substr(pos - g, 1) + w;
}
g++;
}
return [w, pos];
}
this.ieGetText = function(obj) {
var caret = obj.document.selection.createRange(), w="";
if(caret.text) {
caret.text = "";
} else {
while(1) {
caret.moveStart("character", -1);
if(w.length == caret.text.length) {
break;
}
w = caret.text;
if(this.notWord(w.charAt(0))) {
if(w.charCodeAt(0) == 13) {
w=w.substr(2);
} else if(w.charAt(0) != "\\") {
w=w.substr(1);
}
break;
}
}
}
if(w.length) {
caret.collapse(false);
caret.moveStart("character", -w.length);
obj.cW = caret.duplicate();
return obj;
} else {
return false;
}
}
this.start = function(obj, key) {
var w = "", method = AVIMGlobalConfig.method, dockspell = AVIMGlobalConfig.ckSpell, uni, uni2 = false, uni3 = false, uni4 = false;
this.oc=obj;
var telex = "D,A,E,O,W,W".split(','), vni = "9,6,6,6,7,8".split(','), viqr = "D,^,^,^,+,(".split(','), viqr2 = "D,^,^,^,*,(".split(','), a, noNormC;
if(method == 0) {
var arr = [], check = [AVIMAutoConfig.telex, AVIMAutoConfig.vni, AVIMAutoConfig.viqr, AVIMAutoConfig.viqrStar];
var value1 = [telex, vni, viqr, viqr2], uniA = [uni, uni2, uni3, uni4], D2A = ["DAWEO", "6789", "D^+(", "D^*("];
for(a = 0; a < check.length; a++) {
if(check[a]) {
arr[arr.length] = value1[a];
} else {
D2A[a] = "";
}
}
for(a = 0; a < arr.length; a++) {
uniA[a] = arr[a];
}
uni = uniA[0];
uni2 = uniA[1];
uni3 = uniA[2];
uni4 = uniA[3];
this.D2 = D2A.join();
if(!uni) {
return;
}
} else if(method == 1) {
uni = telex;
this.D2 = "DAWEO";
}
else if(method == 2) {
uni = vni;
this.D2 = "6789";
}
else if(method == 3) {
uni = viqr;
this.D2 = "D^+(";
}
else if(method == 4) {
uni = viqr2;
this.D2 = "D^*(";
}
if(!this.is_ie) {
key = this.fcc(key.which);
w = this.mozGetText(obj);
if(!w || obj.sel) {
return;
}
if(this.D2.indexOf(this.up(key)) >= 0) {
noNormC = true;
} else {
noNormC = false;
}
this.main(w[0], key, w[1], uni, noNormC);
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni2 && !this.changed) {
this.main(w[0], key, w[1], uni2, noNormC);
}
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni3 && !this.changed) {
this.main(w[0], key, w[1], uni3, noNormC);
}
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni4 && !this.changed) {
this.main(w[0], key, w[1], uni4, noNormC);
}
} else {
obj = this.ieGetText(obj);
if(obj) {
var sT = obj.cW.text;
w = this.main(sT, key, 0, uni, false);
if(uni2 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni2, false);
}
if(uni3 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni3, false);
}
if(uni4 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni4, false);
}
if(w) {
obj.cW.text = w;
}
}
}
if(this.D2.indexOf(this.up(key)) >= 0) {
if(!this.is_ie) {
w = this.mozGetText(obj);
if(!w) {
return;
}
this.normC(w[0], key, w[1]);
} else if(typeof(obj) == "object") {
obj = this.ieGetText(obj);
if(obj) {
w = obj.cW.text;
if(!this.changed) {
w += key;
this.changed = true;
}
obj.cW.text = w;
w = this.normC(w, key, 0);
if(w) {
obj = this.ieGetText(obj);
obj.cW.text = w;
}
}
}
}
}
this.findC = function(w, k, sf) {
var method = AVIMGlobalConfig.method;
if(((method == 3) || (method == 4)) && (w.substr(w.length - 1, 1) == "\\")) {
return [1, k.charCodeAt(0)];
}
var str = "", res, cc = "", pc = "", tE = "", vowA = [], s = "ÂĂÊÔƠƯêâăơôư", c = 0, dn = false, uw = this.up(w), tv, g;
var DAWEOFA = this.up(this.aA.join() + this.eA.join() + this.mocA.join() + this.trangA.join() + this.oA.join() + this.english), h, uc;
for(g = 0; g < sf.length; g++) {
if(this.nan(sf[g])) {
str += sf[g];
} else {
str += this.fcc(sf[g]);
}
}
var uk = this.up(k), uni_array = this.repSign(k), w2 = this.up(this.unV2(this.unV(w))), dont = "ƯA,ƯU".split(',');
if (this.DAWEO.indexOf(uk) >= 0) {
if(uk == this.moc) {
if((w2.indexOf("UU") >= 0) && (this.tw5 != dont[1])) {
if(w2.indexOf("UU") == (w.length - 2)) {
res=2;
} else {
return false;
}
} else if(w2.indexOf("UOU") >= 0) {
if(w2.indexOf("UOU") == (w.length-3)) {
res=2;
} else {
return false;
}
}
}
if(!res) {
for(g = 1; g <= w.length; g++) {
cc = w.substr(w.length - g, 1);
pc = this.up(w.substr(w.length - g - 1, 1));
uc = this.up(cc);
for(h = 0; h < dont.length; h++) {
if((this.tw5 == dont[h]) && (this.tw5 == this.unV(pc + uc))) {
dn = true;
}
}
if(dn) {
dn = false;
continue;
}
if(str.indexOf(uc) >= 0) {
if(((uk == this.moc) && (this.unV(uc) == "U") && (this.up(this.unV(w.substr(w.length - g + 1, 1))) == "A")) || ((uk == this.trang) && (this.unV(uc) == 'A') && (this.unV(pc) == 'U'))) {
if(this.unV(uc) == "U") {
tv=1;
} else {
tv=2;
}
var ccc = this.up(w.substr(w.length - g - tv, 1));
if(ccc != "Q") {
res = g + tv - 1;
} else if(uk == this.trang) {
res = g;
} else if(this.moc != this.trang) {
return false;
}
} else {
res = g;
}
if(!this.whit || (uw.indexOf("Ư") < 0) || (uw.indexOf("W") < 0)) {
break;
}
} else if(DAWEOFA.indexOf(uc) >= 0) {
if(uk == this.D) {
if(cc == "đ") {
res = [g, 'd'];
} else if(cc == "Đ") {
res = [g, 'D'];
}
} else {
res = this.DAWEOF(cc, uk, g);
}
if(res) break;
}
}
}
}
if((uk != this.Z) && (this.DAWEO.indexOf(uk) < 0)) {
var tEC = this.retKC(uk);
for(g = 0;g < tEC.length; g++) {
tE += this.fcc(tEC[g]);
}
}
for(g = 1; g <= w.length; g++) {
if(this.DAWEO.indexOf(uk) < 0) {
cc = this.up(w.substr(w.length - g, 1));
pc = this.up(w.substr(w.length - g - 1, 1));
if(str.indexOf(cc) >= 0) {
if(cc == 'U') {
if(pc != 'Q') {
c++;
vowA[vowA.length] = g;
}
} else if(cc == 'I') {
if((pc != 'G') || (c <= 0)) {
c++;
vowA[vowA.length] = g;
}
} else {
c++;
vowA[vowA.length] = g;
}
} else if(uk != this.Z) {
for(h = 0; h < uni_array.length; h++) if(uni_array[h] == w.charCodeAt(w.length - g)) {
if(this.spellerr(w, k)) {
return false;
}
return [g, tEC[h % 24]];
}
for(h = 0; h < tEC.length; h++) {
if(tEC[h] == w.charCodeAt(w.length - g)) {
return [g, this.fcc(this.skey[h])];
}
}
}
}
}
if((uk != this.Z) && (typeof(res) != 'object')) {
if(this.spellerr(w, k)) {
return false;
}
}
if(this.DAWEO.indexOf(uk) < 0) {
for(g = 1; g <= w.length; g++) {
if((uk != this.Z) && (s.indexOf(w.substr(w.length - g, 1)) >= 0)) {
return g;
} else if(tE.indexOf(w.substr(w.length - g, 1)) >= 0) {
for(h = 0; h < tEC.length; h++) {
if(w.substr(w.length - g, 1).charCodeAt(0) == tEC[h]) {
return [g, this.fcc(this.skey[h])];
}
}
}
}
}
if(res) {
return res;
}
if((c == 1) || (uk == this.Z)) {
return vowA[0];
} else if(c == 2) {
var v = 2;
if(w.substr(w.length - 1) == " ") {
v = 3;
}
var ttt = this.up(w.substr(w.length - v, 2));
if((AVIMGlobalConfig.oldAccent == 0) && ((ttt == "UY") || (ttt == "OA") || (ttt == "OE"))) {
return vowA[0];
}
var c2 = 0, fdconsonant, sc = "BCD" + this.fcc(272) + "GHKLMNPQRSTVX", dc = "CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',');
for(h = 1; h <= w.length; h++) {
fdconsonant=false;
for(g = 0; g < dc.length; g++) {
if(this.up(w.substr(w.length - h - dc[g].length + 1, dc[g].length)).indexOf(dc[g])>=0) {
c2++;
fdconsonant = true;
if(dc[g] != 'NGH') {
h++;
} else {
h+=2;
}
}
}
if(!fdconsonant) {
if(sc.indexOf(this.up(w.substr(w.length - h, 1))) >= 0) {
c2++;
} else {
break;
}
}
}
if((c2 == 1) || (c2 == 2)) {
return vowA[0];
} else {
return vowA[1];
}
} else if(c == 3) {
return vowA[1];
} else return false;
}
this.ie_replaceChar = function(w, pos, c) {
var r = "", uc = 0;
if(isNaN(c)) uc = this.up(c);
if(this.whit && (this.up(w.substr(w.length - pos - 1, 1)) == 'U') && (pos != 1) && (this.up(w.substr(w.length - pos - 2, 1)) != 'Q')) {
this.whit = false;
if((this.up(this.unV(this.fcc(c))) == "Ơ") || (uc == "O")) {
if(w.substr(w.length - pos - 1, 1) == 'u') r = this.fcc(432);
else r = this.fcc(431);
}
if(uc == "O") {
if(c == "o") {
c = 417;
} else {
c = 416;
}
}
}
if(!isNaN(c)) {
this.changed = true;
r += this.fcc(c);
return w.substr(0, w.length - pos - r.length + 1) + r + w.substr(w.length - pos + 1);
} else {
return w.substr(0, w.length - pos) + c + w.substr(w.length - pos + 1);
}
}
this.replaceChar = function(o, pos, c) {
var bb = false;
if(!this.nan(c)) {
var replaceBy = this.fcc(c), wfix = this.up(this.unV(this.fcc(c)));
this.changed = true;
} else {
var replaceBy = c;
if((this.up(c) == "O") && this.whit) {
bb=true;
}
}
if(!o.data) {
var savePos = o.selectionStart, sst = o.scrollTop;
if ((this.up(o.value.substr(pos - 1, 1)) == 'U') && (pos < savePos - 1) && (this.up(o.value.substr(pos - 2, 1)) != 'Q')) {
if((wfix == "Ơ") || bb) {
if (o.value.substr(pos-1,1) == 'u') {
var r = this.fcc(432);
} else {
var r = this.fcc(431);
}
}
if(bb) {
this.changed = true;
if(c == "o") {
replaceBy = "ơ";
} else {
replaceBy = "Ơ";
}
}
}
o.value = o.value.substr(0, pos) + replaceBy + o.value.substr(pos + 1);
if(r) o.value = o.value.substr(0, pos - 1) + r + o.value.substr(pos);
o.setSelectionRange(savePos, savePos);
o.scrollTop = sst;
} else {
if ((this.up(o.data.substr(pos - 1, 1)) == 'U') && (pos < o.pos - 1)) {
if((wfix == "Ơ") || bb) {
if (o.data.substr(pos - 1, 1) == 'u') {
var r = this.fcc(432);
} else {
var r = this.fcc(431);
}
}
if(bb) {
this.changed = true;
if(c == "o") {
replaceBy = "ơ";
} else {
replaceBy = "Ơ";
}
}
}
o.deleteData(pos, 1);
o.insertData(pos, replaceBy);
if(r) {
o.deleteData(pos - 1, 1);
o.insertData(pos - 1, r);
}
}
if(this.whit) {
this.whit=false;
}
}
this.tr = function(k, w, by, sf, i) {
var r, pos = this.findC(w, k, sf), g;
if(pos) {
if(pos[1]) {
if(this.is_ie) {
return this.ie_replaceChar(w, pos[0], pos[1]);
} else {
return this.replaceChar(this.oc, i-pos[0], pos[1]);
}
} else {
var c, pC = w.substr(w.length - pos, 1), cmp;
r = sf;
for(g = 0; g < r.length; g++) {
if(this.nan(r[g]) || (r[g] == "e")) {
cmp = pC;
} else {
cmp = pC.charCodeAt(0);
}
if(cmp == r[g]) {
if(!this.nan(by[g])) {
c = by[g];
} else {
c = by[g].charCodeAt(0);
}
if(this.is_ie) {
return this.ie_replaceChar(w, pos, c);
} else {
return this.replaceChar(this.oc, i - pos, c);
}
}
}
}
}
return false;
}
this.main = function(w, k, i, a, noNormC) {
var uk = this.up(k), bya = [this.db1, this.ab1, this.eb1, this.ob1, this.mocb1, this.trangb1], got = false, t = "d,D,a,A,a,A,o,O,u,U,e,E,o,O".split(",");
var sfa = [this.ds1, this.as1, this.es1, this.os1, this.mocs1, this.trangs1], by = [], sf = [], method = AVIMGlobalConfig.method, h, g;
if((method == 2) || ((method == 0) && (a[0] == "9"))) {
this.DAWEO = "6789";
this.SFJRX = "12534";
this.S = "1";
this.F = "2";
this.J = "5";
this.R = "3";
this.X = "4";
this.Z = "0";
this.D = "9";
this.FRX = "234";
this.AEO = "6";
this.moc = "7";
this.trang = "8";
this.them = "678";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 3) || ((method == 0) && (a[4] == "+"))) {
this.DAWEO = "^+(D";
this.SFJRX = "'`.?~";
this.S = "'";
this.F = "`";
this.J = ".";
this.R = "?";
this.X = "~";
this.Z = "-";
this.D = "D";
this.FRX = "`?~";
this.AEO = "^";
this.moc = "+";
this.trang = "(";
this.them = "^+(";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 4) || ((method == 0) && (a[4] == "*"))) {
this.DAWEO = "^*(D";
this.SFJRX = "'`.?~";
this.S = "'";
this.F = "`";
this.J = ".";
this.R = "?";
this.X = "~";
this.Z = "-";
this.D = "D";
this.FRX = "`?~";
this.AEO = "^";
this.moc = "*";
this.trang = "(";
this.them = "^*(";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 1) || ((method == 0) && (a[0] == "D"))) {
this.SFJRX = "SFJRX";
this.DAWEO = "DAWEO";
this.D = 'D';
this.S = 'S';
this.F = 'F';
this.J = 'J';
this.R = 'R';
this.X = 'X';
this.Z = 'Z';
this.FRX = "FRX";
this.them = "AOEW";
this.trang = "W";
this.moc = "W";
this.A = "A";
this.E = "E";
this.O = "O";
}
if(this.SFJRX.indexOf(uk) >= 0) {
var ret = this.sr(w,k,i);
got=true;
if(ret) {
return ret;
}
} else if(uk == this.Z) {
sf = this.repSign(null);
for(h = 0; h < this.english.length; h++) {
sf[sf.length] = this.lowen.charCodeAt(h);
sf[sf.length] = this.english.charCodeAt(h);
}
for(h = 0; h < 5; h++) {
for(g = 0; g < this.skey.length; g++) {
by[by.length] = this.skey[g];
}
}
for(h = 0; h < t.length; h++) {
by[by.length] = t[h];
}
got = true;
} else {
for(h = 0; h < a.length; h++) {
if(a[h] == uk) {
got = true;
by = by.concat(bya[h]);
sf = sf.concat(sfa[h]);
}
}
}
if(uk == this.moc) {
this.whit = true;
}
if(!got) {
if(noNormC) {
return;
} else {
return this.normC(w, k, i);
}
}
return this.DAWEOZ(k, w, by, sf, i, uk);
}
this.DAWEOZ = function(k, w, by, sf, i, uk) {
if((this.DAWEO.indexOf(uk) >= 0) || (this.Z.indexOf(uk) >= 0)) {
return this.tr(k, w, by, sf, i);
}
}
this.normC = function(w, k, i) {
var uk = this.up(k), u = this.repSign(null), fS, c, j, h, space = (k.charCodeAt(0) == 32) ? true : false;
if(!this.is_ie && space) {
return;
}
for(j = 1; j <= w.length; j++) {
for(h = 0; h < u.length; h++) {
if(u[h] == w.charCodeAt(w.length - j)) {
if(h <= 23) {
fS = this.S;
} else if(h <= 47) {
fS = this.F;
} else if(h <= 71) {
fS = this.J;
} else if(h <= 95) {
fS = this.R;
} else {
fS = this.X;
}
c = this.skey[h % 24];
if((this.alphabet.indexOf(uk) < 0) && (this.D2.indexOf(uk) < 0)) {
return w;
}
w = this.unV(w);
if(!space && !this.changed) {
w += k;
}
if(!this.is_ie) {
var sp = this.oc.selectionStart, pos = sp;
if(!this.changed) {
var sst = this.oc.scrollTop;
pos += k.length;
if(!this.oc.data) {
this.oc.value = this.oc.value.substr(0, sp) + k + this.oc.value.substr(this.oc.selectionEnd);
this.changed = true;
this.oc.scrollTop = sst;
} else {
this.oc.insertData(this.oc.pos, k);
this.oc.pos++;
this.range.setEnd(this.oc, this.oc.pos);
this.specialChange = true;
}
}
if(!this.oc.data) {
this.oc.setSelectionRange(pos, pos);
}
if(!this.ckspell(w, fS)) {
this.replaceChar(this.oc, i - j, c);
if(!this.oc.data) {
var a = [this.D];
this.main(w, fS, pos, a, false);
} else {
var ww = this.mozGetText(this.oc), a = [this.D];
this.main(ww[0], fS, ww[1], a, false);
}
}
} else {
var ret = this.sr(w, fS, 0);
if(space && ret) {
ret += this.fcc(32);
}
if(ret) {
return ret;
}
}
}
}
}
}
this.DAWEOF = function(cc, k, g) {
var ret = [g], kA = [this.A, this.moc, this.trang, this.E, this.O], z, a;
var ccA = [this.aA, this.mocA, this.trangA, this.eA, this.oA], ccrA = [this.arA, this.mocrA, this.arA, this.erA, this.orA];
for(a = 0; a < kA.length; a++) {
if(k == kA[a]) {
for(z = 0; z < ccA[a].length; z++) {
if(cc == ccA[a][z]) {
ret[1] = ccrA[a][z];
}
}
}
}
if(ret[1]) {
return ret;
} else {
return false;
}
}
this.retKC = function(k) {
if(k == this.S) {
return [225,7845,7855,233,7871,237,243,7889,7899,250,7913,253,193,7844,7854,201,7870,205,211,7888,7898,218,7912,221];
}
if(k == this.F) {
return [224,7847,7857,232,7873,236,242,7891,7901,249,7915,7923,192,7846,7856,200,7872,204,210,7890,7900,217,7914,7922];
}
if(k == this.J) {
return [7841,7853,7863,7865,7879,7883,7885,7897,7907,7909,7921,7925,7840,7852,7862,7864,7878,7882,7884,7896,7906,7908,7920,7924];
}
if(k == this.R) {
return [7843,7849,7859,7867,7875,7881,7887,7893,7903,7911,7917,7927,7842,7848,7858,7866,7874,7880,7886,7892,7902,7910,7916,7926];
}
if(k == this.X) {
return [227,7851,7861,7869,7877,297,245,7895,7905,361,7919,7929,195,7850,7860,7868,7876,296,213,7894,7904,360,7918,7928];
}
}
this.unV = function(w) {
var u = this.repSign(null), b, a;
for(a = 1; a <= w.length; a++) {
for(b = 0; b < u.length; b++) {
if(u[b] == w.charCodeAt(w.length - a)) {
w = w.substr(0, w.length - a) + this.fcc(this.skey[b % 24]) + w.substr(w.length - a + 1);
}
}
}
return w;
}
this.unV2 = function(w) {
var a, b;
for(a = 1; a <= w.length; a++) {
for(b = 0; b < this.skey.length; b++) {
if(this.skey[b] == w.charCodeAt(w.length - a)) {
w = w.substr(0, w.length - a) + this.skey2[b] + w.substr(w.length - a + 1);
}
}
}
return w;
}
this.repSign = function(k) {
var t = [], u = [], a, b;
for(a = 0; a < 5; a++) {
if((k == null)||(this.SFJRX.substr(a, 1) != this.up(k))) {
t = this.retKC(this.SFJRX.substr(a, 1));
for(b = 0; b < t.length; b++) u[u.length] = t[b];
}
}
return u;
}
this.sr = function(w, k, i) {
var sf = this.getSF(), pos = this.findC(w, k, sf);
if(pos) {
if(pos[1]) {
if(!this.is_ie) {
this.replaceChar(this.oc, i-pos[0], pos[1]);
} else {
return this.ie_replaceChar(w, pos[0], pos[1]);
}
} else {
var c = this.retUni(w, k, pos);
if (!this.is_ie) {
this.replaceChar(this.oc, i-pos, c);
} else {
return this.ie_replaceChar(w, pos, c);
}
}
}
return false;
}
this.retUni = function(w, k, pos) {
var u = this.retKC(this.up(k)), uC, lC, c = w.charCodeAt(w.length - pos), a, t = this.fcc(c);
for(a = 0; a < this.skey.length; a++) {
if(this.skey[a] == c) {
if(a < 12) {
lC=a;
uC=a+12;
} else {
lC = a - 12;
uC=a;
}
if(t != this.up(t)) {
return u[lC];
}
return u[uC];
}
}
}
this.ifInit = function(w) {
var sel = w.getSelection();
this.range = sel ? sel.getRangeAt(0) : document.createRange();
}
this.ifMoz = function(e) {
var code = e.which, avim = this.AVIM, cwi = e.target.parentNode.wi;
if(typeof(cwi) == "undefined") cwi = e.target.parentNode.parentNode.wi;
if(e.ctrlKey || (e.altKey && (code != 92) && (code != 126))) return;
avim.ifInit(cwi);
var node = avim.range.endContainer, newPos;
avim.sk = avim.fcc(code);
avim.saveStr = "";
if(avim.checkCode(code) || !avim.range.startOffset || (typeof(node.data) == 'undefined')) return;
node.sel = false;
if(node.data) {
avim.saveStr = node.data.substr(avim.range.endOffset);
if(avim.range.startOffset != avim.range.endOffset) {
node.sel=true;
}
node.deleteData(avim.range.startOffset, node.data.length);
}
avim.range.setEnd(node, avim.range.endOffset);
avim.range.setStart(node, 0);
if(!node.data) {
return;
}
node.value = node.data;
node.pos = node.data.length;
node.which=code;
avim.start(node, e);
node.insertData(node.data.length, avim.saveStr);
newPos = node.data.length - avim.saveStr.length + avim.kl;
avim.range.setEnd(node, newPos);
avim.range.setStart(node, newPos);
avim.kl = 0;
if(avim.specialChange) {
avim.specialChange = false;
avim.changed = false;
node.deleteData(node.pos - 1, 1);
}
if(avim.changed) {
avim.changed = false;
e.preventDefault();
}
}
this.FKeyPress = function() {
var obj = this.findF();
this.sk = this.fcc(obj.event.keyCode);
if(this.checkCode(obj.event.keyCode) || (obj.event.ctrlKey && (obj.event.keyCode != 92) && (obj.event.keyCode != 126))) {
return;
}
this.start(obj, this.sk);
}
this.checkCode = function(code) {
if(((AVIMGlobalConfig.onOff == 0) || ((code < 45) && (code != 42) && (code != 32) && (code != 39) && (code != 40) && (code != 43)) || (code == 145) || (code == 255))) {
return true;
}
}
this.notWord = function(w) {
var str = "\ \r\n#,\\;.:-_()<>+-*/=?!\"$%{}[]\'~|^\@\&\t" + this.fcc(160);
return (str.indexOf(w) >= 0);
}
this.nan = function(w) {
if (isNaN(w) || (w == 'e')) {
return true;
} else {
return false;
}
}
this.up = function(w) {
w = w.toUpperCase();
if(this.isKHTML) {
var str = "êôơâăưếốớấắứềồờầằừễỗỡẫẵữệộợậặự", rep="ÊÔƠÂĂƯẾỐỚẤẮỨỀỒỜẦẰỪỄỖỠẪẴỮỆỘỢẶỰ", z, io;
for(z = 0; z < w.length; z++) {
io = str.indexOf(w.substr(z, 1));
if(io >= 0) {
w = w.substr(0, z) + rep.substr(io, 1) + w.substr(z + 1);
}
}
}
return w;
}
this.findIgnore = function(el) {
var va = AVIMGlobalConfig.exclude, i;
for(i = 0; i < va.length; i++) {
if((el.id == va[i]) && (va[i].length > 0)) {
return true;
}
}
}
this.findF = function() {
var g;
for(g = 0; g < this.fID.length; g++) {
if(this.findIgnore(this.fID[g])) return;
this.frame = this.fID[g];
if(typeof(this.frame) != "undefined") {
try {
if (this.frame.contentWindow.document && this.frame.contentWindow.event) {
return this.frame.contentWindow;
}
} catch(e) {
if (this.frame.document && this.frame.event) {
return this.frame;
}
}
}
}
}
this.keyPressHandler = function(e) {
if(!this.support) {
return;
}
if(!this.is_ie) {
var el = e.target, code = e.which;
if(e.ctrlKey) {
return;
}
if(e.altKey && (code != 92) && (code != 126)) {
return;
}
} else {
var el = window.event.srcElement, code = window.event.keyCode;
if(window.event.ctrlKey && (code != 92) && (code != 126)) {
return;
}
}
if(((el.type != 'textarea') && (el.type != 'text')) || this.checkCode(code)) {
return;
}
this.sk = this.fcc(code);
if(this.findIgnore(el)) {
return;
}
if(!this.is_ie) {
this.start(el, e);
} else {
this.start(el, this.sk);
}
if(this.changed) {
this.changed = false;
return false;
}
return true;
}
this.attachEvt = function(obj, evt, handle, capture) {
if(this.is_ie) {
obj.attachEvent("on" + evt, handle);
} else {
obj.addEventListener(evt, handle, capture);
}
}
this.keyDownHandler = function(e) {
if(e == "iframe") {
this.frame = this.findF();
var key = this.frame.event.keyCode;
} else {
var key = (!this.is_ie) ? e.which : window.event.keyCode;
}
if (key == 123) {
document.getElementById('AVIMControl').style.display = (document.getElementById('AVIMControl').style.display == 'none') ? 'block' : 'none';
}
}
}
function AVIMInit(AVIM) {
var kkk = false;
if(AVIM.support && !AVIM.isKHTML) {
if(AVIM.is_opera) {
if(AVIM.operaVersion < 9) {
return;
}
}
for(AVIM.g = 0; AVIM.g < AVIM.fID.length; AVIM.g++) {
if(AVIM.findIgnore(AVIM.fID[AVIM.g])) {
continue;
}
if(AVIM.is_ie) {
var doc;
try {
AVIM.frame = AVIM.fID[AVIM.g];
if(typeof(AVIM.frame) != "undefined") {
if(AVIM.frame.contentWindow.document) {
doc = AVIM.frame.contentWindow.document;
} else if(AVIM.frame.document) {
doc = AVIM.frame.document;
}
}
} catch(e) {}
if(doc && ((AVIM.up(doc.designMode) == "ON") || doc.body.contentEditable)) {
for (var l = 0; l < AVIM.attached.length; l++) {
if (doc == AVIM.attached[l]) {
kkk = true;
break;
}
}
if (!kkk) {
AVIM.attached[AVIM.attached.length] = doc;
AVIM.attachEvt(doc, "keydown", function() {
AVIM.keyDownHandler("iframe");
}, false);
AVIM.attachEvt(doc, "keypress", function() {
AVIM.FKeyPress();
if(AVIM.changed) {
AVIM.changed = false;
return false;
}
}, false);
}
}
} else {
var iframedit;
try {
AVIM.wi = AVIM.fID[AVIM.g].contentWindow;
iframedit = AVIM.wi.document;
iframedit.wi = AVIM.wi;
if(iframedit && (AVIM.up(iframedit.designMode) == "ON")) {
iframedit.AVIM = AVIM;
AVIM.attachEvt(iframedit, "keypress", AVIM.ifMoz, false);
AVIM.attachEvt(iframedit, "keydown", AVIM.keyDownHandler, false);
}
} catch(e) {}
}
}
}
}
AVIMObj = new AVIM();
function AVIMAJAXFix() {
var a = 50;
while(a < 5000) {
setTimeout("AVIMInit(AVIMObj)", a);
a += 50;
}
}
AVIMAJAXFix();
AVIMObj.attachEvt(document, "mousedown", AVIMAJAXFix, false);
AVIMObj.attachEvt(document, "keydown", AVIMObj.keyDownHandler, true);
AVIMObj.attachEvt(document, "keypress", function(e) {
var a = AVIMObj.keyPressHandler(e);
if (a == false) {
if (AVIMObj.is_ie) window.event.returnValue = false;
else e.preventDefault();
}
}, true);
| JavaScript |
/*
* jFlip plugin for jQuery v0.4 (28/2/2009)
*
* A plugin to make a page flipping gallery
*
* Copyright (c) 2008-2009 Renato Formato (rformato@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
*/
;(function($){
var Flip = function(canvas,width,height,images,opts) {
//private vars
opts = $.extend({background:"green",cornersTop:true,scale:"noresize"},opts);
var obj = this,
el = canvas.prev(),
index = 0,
init = false,
background = opts.background,
cornersTop = opts.cornersTop,
gradientColors = opts.gradientColors || ['#4F2727','#FF8F8F','#F00'],
curlSize = opts.curlSize || 0.1,
scale = opts.scale,
patterns = [],
canvas2 = canvas.clone(),
ctx2 = $.browser.msie?null:canvas2[0].getContext("2d"),
canvas = $.browser.msie?$(G_vmlCanvasManager.initElement(canvas[0])):canvas,
ctx = canvas[0].getContext("2d"),
loaded = 0;
var images = images.each(function(i){
if(patterns[i]) return;
var img = this;
img.onload = function() {
var r = 1;
if(scale!="noresize") {
var rx = width/this.width,
ry = height/this.height;
if(scale=="fit")
r = (rx<1 || ry<1)?Math.min(rx,ry):1;
if(scale=="fill") {
r = Math.min(rx,ry);
}
};
$(img).data("flip.scale",r);
patterns[i] = ctx.createPattern(img,"no-repeat");
loaded++;
if(loaded==images.length && !init) {
init = true;
draw();
}
};
if(img.complete)
window.setTimeout(function(){img.onload()},10);
}).get();
var
width = width,height = height,mX = width,mY = height,
basemX = mX*(1-curlSize), basemY = mY*curlSize,sideLeft = false,
off = $.browser.msie?canvas.offset():null,
onCorner = false,
curlDuration=400,curling = false,
animationTimer,startDate,
flipDuration=700,flipping = false,baseFlipX,baseFlipY,
lastmX,lastmY,
inCanvas = false,
mousedown = false,
dragging = false;
$(window).scroll(function(){
//off = canvas.offset(); //update offset on scroll
});
//IE can't handle correctly mouseenter and mouseleave on VML
var c = $.browser.msie?(function(){
var div = $("<div>").width(width).height(height).css({position:"absolute",cursor:"default",zIndex:1}).appendTo("body");
//second hack for IE7 that can't handle correctly mouseenter and mouseleave if the div has no background color
if(parseInt($.browser.version)==7)
div.css({opacity:0.000001,background:"#FFF"});
var positionDiv = function() {
off = canvas.offset();
return div.css({left:off.left+'px',top:off.top+'px'});
}
$(window).resize(positionDiv);
return positionDiv();
})():canvas;
c.mousemove(function(e){
//track the mouse
/*
if(!off) off = canvas.offset(); //safari can't calculate correctly offset at DOM ready
mX = e.clientX-off.left;
mY = e.clientY-off.top;
window.setTimeout(draw,0);
return;
*/
if(!off)
off = canvas.offset(); //safari can't calculate correctly offset at DOM ready
if(mousedown && onCorner) {
if(!dragging) {
dragging = true;
window.clearInterval(animationTimer);
}
mX = !sideLeft?e.pageX-off.left:width-(e.pageX-off.left);
mY = cornersTop?e.pageY-off.top:height-(e.pageY-off.top);
window.setTimeout(draw,0);
return false;
}
lastmX = e.pageX||lastmX, lastmY = e.pageY||lastmY;
if(!flipping) {
sideLeft = (lastmX-off.left)<width/2;
//cornersTop = (lastmY-off.top)<height/2;
}
if(!flipping &&
((lastmX-off.left)>basemX || (lastmX-off.left)<(width-basemX)) &&
((cornersTop && (lastmY-off.top)<basemY) || (!cornersTop && (lastmY-off.top)>(height-basemY)))) {
if(!onCorner) {
onCorner= true;
c.css("cursor","pointer");
}
} else {
if(onCorner) {
onCorner= false;
c.css("cursor","default");
}
};
return false;
}).bind("mouseenter",function(e){
inCanvas = true;
if(flipping) return;
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlIn,10);
return false;
}).bind("mouseleave",function(e){
inCanvas = false;
dragging = false;
mousedown = false;
if(flipping) return;
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlOut,10);
return false;
}).click(function(){
if(onCorner && !flipping) {
flipping = true;
c.triggerHandler("mousemove");
window.clearInterval(animationTimer);
startDate = new Date().getTime();
baseFlipX = mX;
baseFlipY = mY;
animationTimer = window.setInterval(flip,10);
index += sideLeft?-1:1;
if(index<0) index = images.length-1;
if(index==images.length) index = 0;
el.trigger("flip.jflip",[index,images.length]);
}
return false;
}).mousedown(function(){
dragging = false;
mousedown = true;
return false;
}).mouseup(function(){
mousedown = false;
return false;
});
var flip = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=flipDuration) {
window.clearInterval(animationTimer);
if(sideLeft) {
images.unshift(images.pop());
patterns.unshift(patterns.pop());
} else {
images.push(images.shift());
patterns.push(patterns.shift());
}
mX = width;
mY = height;
draw();
flipping = false;
//init corner move if still in Canvas
if(inCanvas) {
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlIn,10);
c.triggerHandler("mousemove");
}
return;
}
//da mX a -width (mX+width) in duration millisecondi
mX = baseFlipX-2*(width)*delta/flipDuration;
mY = baseFlipY+2*(height)*delta/flipDuration;
draw();
},
cornerMove = function() {
var date = new Date(),delta = date.getTime()-startDate;
mX = basemX+Math.sin(Math.PI*2*delta/1000);
mY = basemY+Math.cos(Math.PI*2*delta/1000);
drawing = true;
window.setTimeout(draw,0);
},
cornerCurlIn = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=curlDuration) {
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerMove,10);
}
mX = width-(width-basemX)*delta/curlDuration;
mY = basemY*delta/curlDuration;
draw();
},
cornerCurlOut = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=curlDuration) {
window.clearInterval(animationTimer);
}
mX = basemX+(width-basemX)*delta/curlDuration;
mY = basemY-basemY*delta/curlDuration;
draw();
},
curlShape = function(m,q) {
//cannot draw outside the viewport because of IE blurring the pattern
var intyW = m*width+q,intx0 = -q/m;
if($.browser.msie) {
intyW = Math.round(intyW);
intx0 = Math.round(intx0);
};
ctx.beginPath();
ctx.moveTo(width,Math.min(intyW,height));
ctx.lineTo(width,0);
ctx.lineTo(Math.max(intx0,0),0);
if(intx0<0) {
ctx.lineTo(0,Math.min(q,height));
if(q<height) {
ctx.lineTo((height-q)/m,height);
}
ctx.lineTo(width,height);
} else {
if(intyW<height)
ctx.lineTo(width,intyW);
else {
ctx.lineTo((height-q)/m,height);
ctx.lineTo(width,height);
}
}
},
draw = function() {
if(!init) return;
if($.browser.msie)
ctx.clearRect(0,0,width,height);
ctx.fillStyle = background;
ctx.fillRect(0,0,width,height);
var img = images[0], r = $(img).data("flip.scale");
if($.browser.msie) {
ctx.fillStyle = patterns[0];
ctx.fillStyle.width2 = ctx.fillStyle.width*r;
ctx.fillStyle.height2 = ctx.fillStyle.height*r;
ctx.fillRect(0,0,width,height);
} else {
ctx.drawImage(img,(width-img.width*r)/2,(height-img.height*r)/2,img.width*r,img.height*r);
}
if(mY && mX!=width) {
var m = 2,
q = (mY-m*(mX+width))/2;
m2 = mY/(width-mX),
q2 = mX*m2;
if(m==m2) return;
var sx=1,sy=1,tx=0,ty=0;
ctx.save();
if(sideLeft) {
tx = width;
sx = -1;
}
if(!cornersTop) {
ty = height;
sy = -1;
}
ctx.translate(tx,ty);
ctx.scale(sx,sy);
//draw page flip
//intx,inty is the intersection between the line of the curl and the line
//from the canvas corner to the curl point
var intx = (q2-q)/(m-m2);
var inty = m*intx+q;
//y=m*x+mY-m*mX line per (mX,mY) parallel to the curl line
//y=-x/m+inty+intx/m line perpendicular to the curl line
//intersection x between the 2 lines = int2x
//y of perpendicular for the intersection x = int2y
//opera do not fill a shape if gradient is finished
var int2x = (2*inty+intx+2*m*mX-2*mY)/(2*m+1);
var int2y = -int2x/m+inty+intx/m;
var d = Math.sqrt(Math.pow(intx-int2x,2)+Math.pow(inty-int2y,2));
var stopHighlight = Math.min(d*0.5,30);
var c;
if(!($.browser.mozilla && parseFloat($.browser.version)<1.9)) {
c = ctx;
} else {
c = ctx2;
c.clearRect(0,0,width,height);
c.save();
c.translate(1,0); //the curl shapes do not overlap perfeclty
}
var gradient = c.createLinearGradient(intx,inty,int2x,int2y);
gradient.addColorStop(0, gradientColors[0]);
gradient.addColorStop(stopHighlight/d, gradientColors[1]);
gradient.addColorStop(1, gradientColors[2]);
c.fillStyle = gradient;
c.beginPath();
c.moveTo(-q/m,0);
c.quadraticCurveTo((-q/m+mX)/2+0.02*mX,mY/2,mX,mY);
c.quadraticCurveTo((width+mX)/2,(m*width+q+mY)/2-0.02*(height-mY),width,m*width+q);
if(!($.browser.mozilla && parseFloat($.browser.version)<1.9)) {
c.fill();
} else {
//for ff 2.0 use a clip region on a second canvas and copy all its content (much faster)
c.save();
c.clip();
c.fillRect(0,0,width,height);
c.restore();
ctx.drawImage(canvas2[0],0,0);
c.restore();
}
//can't understand why this doesn't work on ff 2, fill is slow
/*
ctx.save();
ctx.clip();
ctx.fillRect(0,0,width,height);
ctx.restore();
*/
gradient = null;
//draw solid color background
ctx.fillStyle = background;
curlShape(m,q);
ctx.fill();
//draw back image
curlShape(m,q);
//safari and opera delete the path when doing restore
if(!$.browser.safari && !$.browser.opera)
ctx.restore();
var img = sideLeft?images[images.length-1]:images[1];
r = $(img).data("flip.scale");
if($.browser.msie) {
//excanvas does not support clip
ctx.fillStyle = sideLeft?patterns[patterns.length-1]:patterns[1];
//hack to scale the pattern on IE (modified excanvas)
ctx.fillStyle.width2 = ctx.fillStyle.width*r;
ctx.fillStyle.height2 = ctx.fillStyle.height*r;
ctx.fill();
} else {
ctx.save();
ctx.clip();
//safari and opera delete the path when doing restore
//at this point we have not reverted the trasform
if($.browser.safari || $.browser.opera) {
//revert transform
ctx.scale(1/sx,1/sy);
ctx.translate(-tx,-ty);
}
ctx.drawImage(img,(width-img.width*r)/2,(height-img.height*r)/2,img.width*r,img.height*r);
//ctx.drawImage(img,(width-img.width)/2,(height-img.height)/2);
ctx.restore();
if($.browser.safari || $.browser.opera)
ctx.restore()
}
}
}
}
$.fn.jFlip = function(width,height,opts){
return this.each(function() {
$(this).wrap("<div class='flip_gallery'>");
var images = $(this).find("img");
//cannot hide because explorer does not give the image dimensions if hidden
var canvas = $(document.createElement("canvas")).attr({width:width,height:height}).css({margin:0,width:width+"px",height:height+"px"})
$(this).css({position:"absolute",left:"-9000px",top:"-9000px"}).after(canvas);
new Flip($(this).next(),width || 300,height || 300,images,opts);
});
};
})(jQuery);
| JavaScript |
$(document).ready(function() {
//Sidebar Accordion Menu:
$("#main-nav li ul").hide(); //Hide all sub menus
$("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
$("#main-nav li a.nav-top-item").click( // When a top menu item is clicked...
function() {
$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
if ($(this).attr("href") == null || $(this).attr("href") == "" || $(this).attr("href") == "#") {
return false;
}
}
);
// Sidebar Accordion Menu Hover Effect:
$("#main-nav li .nav-top-item").hover(
function() {
$(this).stop();
$(this).animate({ paddingRight: "25px" }, 200);
},
function() {
$(this).stop();
$(this).animate({ paddingRight: "15px" });
}
);
//Minimize Content Box
$(".content-box-header h3").css({ "cursor": "s-resize" }); // Give the h3 in Content Box Header a different cursor
$(".content-box-header-toggled").next().hide(); // Hide the content of the header if it has the class "content-box-header-toggled"
$(".content-box-header h3").click( // When the h3 is clicked...
function() {
$(this).parent().parent().find(".content-box-content").toggle(); // Toggle the Content Box
$(this).parent().toggleClass("content-box-header-toggled"); // Give the Content Box Header a special class for styling and hiding
$(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
}
);
// Content box tabs:
$('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs
$('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
$('ul.content-box-tabs li a.default-tab').addClass('current'); // Set the class of the default tab link to "current"
$('.content-box ul.content-box-tabs li a').click( //When a tab is clicked...
function() {
$(this).parent().siblings().find("a").removeClass('current'); // Remove "current" class from all tabs
$(this).addClass('current'); // Add class "current" to clicked tab
var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab
$(currentTab).siblings().hide(); // Hide all content divs
$(currentTab).show(); // Show the content div with the id equal to the id of clicked tab
return false;
}
);
// Check all checkboxes when the one in a table head is checked:
$('.check-all').click(
function() {
$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));
}
)
});
| JavaScript |
Calendar.LANG("en", "English", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Go Today",
today: "Today", // appears in bottom bar
wk: "wk",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December" ],
smn : [ "Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec" ],
dn : [ "Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" ],
sdn : [ "Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa",
"Su" ]
});
| JavaScript |
/*
* AVIM JavaScript Vietnamese Input Method Source File dated 28-07-2008
*
* Copyright (C) 2004-2008 Hieu Tran Dang <lt2hieu2004 (at) users (dot) sf (dot) net
* Website: http://noname00.com/hieu
*
* You are allowed to use this software in any way you want providing:
* 1. You must retain this copyright notice at all time
* 2. You must not claim that you or any other third party is the author
* of this software in any way.
*/
var AVIMGlobalConfig = {
method: 0, //Default input method: 0=AUTO, 1=TELEX, 2=VNI, 3=VIQR, 4=VIQR*
onOff: 1, //Starting status: 0=Off, 1=On
ckSpell: 1, //Spell Check: 0=Off, 1=On
oldAccent: 1, //0: New way (oa`, oe`, uy`), 1: The good old day (o`a, o`e, u`y)
useCookie: 1, //Cookies: 0=Off, 1=On
exclude: ["email"], //IDs of the fields you DON'T want to let users type Vietnamese in
showControl: 1, //Show control panel: 0=Off, 1=On. If you turn this off, you must write your own control panel.
controlCSS: "../../../Resource/StyleSheet/Guest/avim.css" //Path to avim.css
};
//Set to true the methods which you want to be included in the AUTO method
var AVIMAutoConfig = {
telex: true,
vni: true,
viqr: false,
viqrStar: false
};
function AVIM() {
this.radioID = "avim_auto,avim_telex,avim_vni,avim_viqr,avim_viqr2,avim_off,avim_ckspell,avim_daucu".split(",");
this.attached = [];
this.changed = false;
this.agt = navigator.userAgent.toLowerCase();
this.alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM\ ";
this.support = true;
this.ver = 0;
this.specialChange = false;
this.is_ie = ((this.agt.indexOf("msie") != -1) && (this.agt.indexOf("opera") == -1));
this.is_opera = false;
this.isKHTML = false;
this.kl = 0;
this.skey = [97,226,259,101,234,105,111,244,417,117,432,121,65,194,258,69,202,73,79,212,416,85,431,89];
this.fID = document.getElementsByTagName("iframe");
this.range = null;
this.whit = false;
this.db1 = [273,272];
this.ds1 = ['d','D'];
this.os1 = "o,O,ơ,Ơ,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(",");
this.ob1 = "ô,Ô,ô,Ô,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",");
this.mocs1 = "o,O,ô,Ô,u,U,ó,Ó,ò,Ò,ọ,Ọ,ỏ,Ỏ,õ,Õ,ú,Ú,ù,Ù,ụ,Ụ,ủ,Ủ,ũ,Ũ,ố,Ố,ồ,Ồ,ộ,Ộ,ổ,Ổ,ỗ,Ỗ".split(",");
this.mocb1 = "ơ,Ơ,ơ,Ơ,ư,Ư,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ,ứ,Ứ,ừ,Ừ,ự,Ự,ử,Ử,ữ,Ữ,ớ,Ớ,ờ,Ờ,ợ,Ợ,ở,Ở,ỡ,Ỡ".split(",");
this.trangs1 = "a,A,â,Â,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ".split(",");
this.trangb1 = "ă,Ă,ă,Ă,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ".split(",");
this.as1 = "a,A,ă,Ă,á,Á,à,À,ạ,Ạ,ả,Ả,ã,Ã,ắ,Ắ,ằ,Ằ,ặ,Ặ,ẳ,Ẳ,ẵ,Ẵ,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",");
this.ab1 = "â,Â,â,Â,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,ấ,Ấ,ầ,Ầ,ậ,Ậ,ẩ,Ẩ,ẫ,Ẫ,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",");
this.es1 = "e,E,é,É,è,È,ẹ,Ẹ,ẻ,Ẻ,ẽ,Ẽ".split(",");
this.eb1 = "ê,Ê,ế,Ế,ề,Ề,ệ,Ệ,ể,Ể,ễ,Ễ".split(",");
this.english = "ĐÂĂƠƯÊÔ";
this.lowen = "đâăơưêô";
this.arA = "á,à,ả,ã,ạ,a,Á,À,Ả,Ã,Ạ,A".split(',');
this.mocrA = "ó,ò,ỏ,õ,ọ,o,ú,ù,ủ,ũ,ụ,u,Ó,Ò,Ỏ,Õ,Ọ,O,Ú,Ù,Ủ,Ũ,Ụ,U".split(',');
this.erA = "é,è,ẻ,ẽ,ẹ,e,É,È,Ẻ,Ẽ,Ẹ,E".split(',');
this.orA = "ó,ò,ỏ,õ,ọ,o,Ó,Ò,Ỏ,Õ,Ọ,O".split(',');
this.aA = "ấ,ầ,ẩ,ẫ,ậ,â,Ấ,Ầ,Ẩ,Ẫ,Ậ,Â".split(',');
this.oA = "ố,ồ,ổ,ỗ,ộ,ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ô".split(',');
this.mocA = "ớ,ờ,ở,ỡ,ợ,ơ,ứ,ừ,ử,ữ,ự,ư,Ớ,Ờ,Ở,Ỡ,Ợ,Ơ,Ứ,Ừ,Ử,Ữ,Ự,Ư".split(',');
this.trangA = "ắ,ằ,ẳ,ẵ,ặ,ă,Ắ,Ằ,Ẳ,Ẵ,Ặ,Ă".split(',');
this.eA = "ế,ề,ể,ễ,ệ,ê,Ế,Ề,Ể,Ễ,Ệ,Ê".split(',');
this.oA = "ố,ồ,ổ,ỗ,ộ,ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ô".split(',');
this.skey2 = "a,a,a,e,e,i,o,o,o,u,u,y,A,A,A,E,E,I,O,O,O,U,U,Y".split(',');
this.fcc = function(x) {
return String.fromCharCode(x);
}
this.getEL = function(id) {
return document.getElementById(id);
}
this.getSF = function() {
var sf = [], x;
for(x = 0; x < this.skey.length; x++) {
sf[sf.length] = this.fcc(this.skey[x]);
}
return sf;
}
if(AVIMGlobalConfig.showControl) {
this.css = document.createElement('link');
this.css.rel = 'stylesheet';
this.css.type = 'text/css';
this.css.href = AVIMGlobalConfig.controlCSS;
document.getElementsByTagName('head')[0].appendChild(this.css);
document.write('<span id="AVIMControl">');
document.write('<p class="AVIMControl"><input id="avim_auto" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(0);" />Tự động');
document.write('<input id="avim_telex" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(1);" />TELEX');
document.write('<input id="avim_vni" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(2);" />VNI');
document.write('<input id="avim_viqr" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(3);" />VIQR');
document.write('<input id="avim_viqr2" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(4);" />VIQR*');
document.write('<input id="avim_off" type="radio" name="AVIMMethod" onclick="AVIMObj.setMethod(-1);" />Tắt<br />');
document.write('<a class="AVIMControl" style="float: right; position: relative; top: 3px;" onclick="document.getElementById(' + "'AVIMControl').style.display='none';" + '">[Ẩn AVIM - F12]</a>');
document.write('<input type="checkbox" id="avim_ckspell" onclick="AVIMObj.setSpell(this);" />Chính tả');
document.write('<input type="checkbox" id="avim_daucu" onclick="AVIMObj.setDauCu(this);" />Kiểu cũ</p>');
document.write('</span>');
}
if(!this.is_ie) {
if(this.agt.indexOf("opera") >= 0) {
this.operaV = this.agt.split(" ");
this.operaVersion = parseInt(this.operaV[this.operaV.length - 1]);
if(this.operaVersion >= 8) {
this.is_opera = true;
} else {
this.operaV = this.operaV[0].split("/");
this.operaVersion = parseInt(this.operaV[1]);
if(this.operaVersion >= 8) this.is_opera = true;
}
} else if(this.agt.indexOf("khtml") >= 0) {
this.isKHTML = true;
} else {
this.ver = this.agt.substr(this.agt.indexOf("rv:") + 3);
this.ver = parseFloat(this.ver.substr(0, this.ver.indexOf(" ")));
if(this.agt.indexOf("mozilla") < 0) this.ver = 0;
}
}
this.nospell = function(w, k) {
return false;
}
this.ckspell = function(w, k) {
w = this.unV(w);
var exc = "UOU,IEU".split(','), z, next = true, noE = "UU,UOU,UOI,IEU,AO,IA,AI,AY,AU,AO".split(','), noBE = "YEU";
var check = true, noM = "UE,UYE,IU,EU,UY".split(','), noMT = "AY,AU".split(','), noT = "UA", t = -1, notV2 = "IAO";
var uw = this.up(w), tw = uw, update = false, gi = "IO", noAOEW = "OE,OO,AO,EO,IA,AI".split(','), noAOE = "OA", test, a, b;
var notViet = "AA,AE,EE,OU,YY,YI,IY,EY,EA,EI,II,IO,YO,YA,OOO".split(','), uk = this.up(k), twE, uw2 = this.unV2(uw);
var vSConsonant = "B,C,D,G,H,K,L,M,N,P,Q,R,S,T,V,X".split(','), vDConsonant = "CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',');
var vDConsonantE = "CH,NG,NH".split(','),sConsonant = "C,P,T,CH".split(','),vSConsonantE = "C,M,N,P,T".split(',');
var noNHE = "O,U,IE,Ô,Ơ,Ư,IÊ,Ă,Â,UYE,UYÊ,UO,ƯƠ,ƯO,UƠ,UA,ƯA,OĂ,OE,OÊ".split(','),oMoc = "UU,UOU".split(',');
if(this.FRX.indexOf(uk) >= 0) {
for(a = 0; a < sConsonant.length; a++) {
if(uw.substr(uw.length - sConsonant[a].length, sConsonant[a].length) == sConsonant[a]) {
return true;
}
}
}
for(a = 0; a < uw.length; a++) {
if("FJZW1234567890".indexOf(uw.substr(a, 1)) >= 0) {
return true;
}
for(b = 0; b < notViet.length; b++) {
if(uw2.substr(a, notViet[b].length) == notViet[b]) {
for(z = 0; z < exc.length; z++) {
if(uw2.indexOf(exc[z]) >= 0) {
next=false;
}
}
if(next && ((gi.indexOf(notViet[b]) < 0) || (a <= 0) || (uw2.substr(a - 1, 1) != 'G'))) {
return true;
}
}
}
}
for(b = 0; b < vDConsonant.length; b++) {
if(tw.indexOf(vDConsonant[b]) == 0) {
tw = tw.substr(vDConsonant[b].length);
update = true;
t = b;
break;
}
}
if(!update) {
for(b = 0; b < vSConsonant.length; b++) {
if(tw.indexOf(vSConsonant[b]) == 0) {
tw=tw.substr(1);
break;
}
}
}
update=false;
twE=tw;
for(b = 0; b < vDConsonantE.length; b++) {
if(tw.substr(tw.length - vDConsonantE[b].length) == vDConsonantE[b]) {
tw = tw.substr(0, tw.length - vDConsonantE[b].length);
if(b == 2){
for(z = 0; z < noNHE.length; z++) {
if(tw == noNHE[z]) {
return true;
}
}
if((uk == this.trang) && ((tw == "OA") || (tw == "A"))) {
return true;
}
}
update = true;
break;
}
}
if(!update) {
for(b = 0; b < vSConsonantE.length; b++) {
if(tw.substr(tw.length - 1) == vSConsonantE[b]) {
tw = tw.substr(0, tw.length - 1);
break;
}
}
}
if(tw) {
for(a = 0; a < vDConsonant.length; a++) {
for(b = 0; b < tw.length; b++) {
if(tw.substr(b, vDConsonant[a].length) == vDConsonant[a]) {
return true;
}
}
}
for(a = 0; a < vSConsonant.length; a++) {
if(tw.indexOf(vSConsonant[a]) >= 0) {
return true;
}
}
}
test = tw.substr(0, 1);
if((t == 3) && ((test == "A") || (test == "O") || (test == "U") || (test == "Y"))) {
return true;
}
if((t == 5) && ((test == "E") || (test == "I") || (test == "Y"))) {
return true;
}
uw2 = this.unV2(tw);
if(uw2 == notV2) {
return true;
}
if(tw != twE) {
for(z = 0; z < noE.length; z++) {
if(uw2 == noE[z]) {
return true;
}
}
}
if((tw != uw) && (uw2 == noBE)) {
return true;
}
if(uk != this.moc) {
for(z = 0; z < oMoc.length; z++) {
if(tw == oMoc[z]) return true;
}
}
if((uw2.indexOf('UYE')>0) && (uk == 'E')) {
check=false;
}
if((this.them.indexOf(uk) >= 0) && check) {
for(a = 0; a < noAOEW.length; a++) {
if(uw2.indexOf(noAOEW[a]) >= 0) {
return true;
}
}
if(uk != this.trang) {
if(uw2 == noAOE) {
return true;
}
}
if((uk == this.trang) && (this.trang != 'W')) {
if(uw2 == noT) {
return true;
}
}
if(uk == this.moc) {
for(a = 0; a < noM.length; a++) {
if(uw2 == noM[a]) {
return true;
}
}
}
if((uk == this.moc) || (uk == this.trang)) {
for(a = 0; a < noMT.length; a++) {
if(uw2 == noMT[a]) {
return true;
}
}
}
}
this.tw5 = tw;
if((uw2.charCodeAt(0) == 272) || (uw2.charCodeAt(0) == 273)) {
if(uw2.length > 4) {
return true;
}
} else if(uw2.length > 3) {
return true;
}
return false;
}
this.noCookie = function() {}
this.doSetCookie = function() {
var exp = new Date(11245711156480).toGMTString();
document.cookie = 'AVIM_on_off=' + AVIMGlobalConfig.onOff + ';expires=' + exp;
document.cookie = 'AVIM_method=' + AVIMGlobalConfig.method + ';expires=' + exp;
document.cookie = 'AVIM_ckspell=' + AVIMGlobalConfig.ckSpell + ';expires=' + exp;
document.cookie = 'AVIM_daucu=' + AVIMGlobalConfig.oldAccent + ';expires=' + exp;
}
this.doGetCookie = function() {
var ck = document.cookie, res = /AVIM_method/.test(ck), p, i, ckA = ck.split(';');
if(!res || (ck.indexOf('AVIM_ckspell') < 0)) {
this.setCookie();
return;
}
for(i = 0; i < ckA.length; i++) {
p = ckA[i].split('=');
p[0] = p[0].replace(/^\s+/g, "");
p[1] = parseInt(p[1]);
if(p[0] == 'AVIM_on_off') {
AVIMGlobalConfig.onOff = p[1];
}
else if(p[0] == 'AVIM_method') {
AVIMGlobalConfig.method = p[1];
}
else if(p[0] == 'AVIM_ckspell') {
if(p[1] == 0) {
AVIMGlobalConfig.ckSpell=0;
this.spellerr=this.nospell;
} else {
AVIMGlobalConfig.ckSpell=1;
this.spellerr=this.ckspell;
}
} else if(p[0] == 'AVIM_daucu') {
AVIMGlobalConfig.oldAccent = parseInt(p[1]);
}
}
}
if(AVIMGlobalConfig.useCookie == 1) {
this.setCookie = this.doSetCookie;
this.getCookie = this.doGetCookie;
} else {
this.setCookie = this.noCookie;
this.getCookie = this.noCookie;
}
this.setMethod = function(m) {
if(m == -1) {
AVIMGlobalConfig.onOff = 0;
if(this.getEL(this.radioID[5])) {
this.getEL(this.radioID[5]).checked = true;
}
} else {
AVIMGlobalConfig.onOff = 1;
AVIMGlobalConfig.method = m;
if(this.getEL(this.radioID[m])) {
this.getEL(this.radioID[m]).checked = true;
}
}
this.setSpell(AVIMGlobalConfig.ckSpell);
this.setDauCu(AVIMGlobalConfig.oldAccent);
this.setCookie();
}
this.setDauCu = function(box) {
if(typeof(box) == "number") {
AVIMGlobalConfig.oldAccent = box;
if(this.getEL(this.radioID[7])) {
this.getEL(this.radioID[7]).checked = box;
}
} else {
AVIMGlobalConfig.oldAccent = (box.checked) ? 1 : 0;
}
this.setCookie();
}
this.setSpell = function(box) {
if(typeof(box) == "number") {
this.spellerr = (box == 1) ? this.ckspell : this.nospell;
if(this.getEL(this.radioID[6])) {
this.getEL(this.radioID[6]).checked = box;
}
} else {
if(box.checked) {
this.spellerr = this.ckspell;
AVIMGlobalConfig.ckSpell = 1;
} else {
this.spellerr = this.nospell;
AVIMGlobalConfig.ckSpell = 0;
}
}
this.setCookie();
}
if(this.is_ie || (this.ver >= 1.3) || this.is_opera || this.isKHTML) {
this.getCookie();
if(AVIMGlobalConfig.onOff == 0) this.setMethod(-1);
else this.setMethod(AVIMGlobalConfig.method);
this.setSpell(AVIMGlobalConfig.ckSpell);
this.setDauCu(AVIMGlobalConfig.oldAccent);
} else {
this.support = false;
}
this.mozGetText = function(obj) {
var v, pos, w = "", g = 1;
v = (obj.data) ? obj.data : obj.value;
if(v.length <= 0) {
return false;
}
if(!obj.data) {
if(!obj.setSelectionRange) {
return false;
}
pos = obj.selectionStart;
} else {
pos = obj.pos;
}
if(obj.selectionStart != obj.selectionEnd) {
return ["", pos];
}
while(1) {
if(pos - g < 0) {
break;
} else if(this.notWord(v.substr(pos - g, 1))) {
if(v.substr(pos - g, 1) == "\\") {
w = v.substr(pos - g, 1) + w;
}
break;
} else {
w = v.substr(pos - g, 1) + w;
}
g++;
}
return [w, pos];
}
this.ieGetText = function(obj) {
var caret = obj.document.selection.createRange(), w="";
if(caret.text) {
caret.text = "";
} else {
while(1) {
caret.moveStart("character", -1);
if(w.length == caret.text.length) {
break;
}
w = caret.text;
if(this.notWord(w.charAt(0))) {
if(w.charCodeAt(0) == 13) {
w=w.substr(2);
} else if(w.charAt(0) != "\\") {
w=w.substr(1);
}
break;
}
}
}
if(w.length) {
caret.collapse(false);
caret.moveStart("character", -w.length);
obj.cW = caret.duplicate();
return obj;
} else {
return false;
}
}
this.start = function(obj, key) {
var w = "", method = AVIMGlobalConfig.method, dockspell = AVIMGlobalConfig.ckSpell, uni, uni2 = false, uni3 = false, uni4 = false;
this.oc=obj;
var telex = "D,A,E,O,W,W".split(','), vni = "9,6,6,6,7,8".split(','), viqr = "D,^,^,^,+,(".split(','), viqr2 = "D,^,^,^,*,(".split(','), a, noNormC;
if(method == 0) {
var arr = [], check = [AVIMAutoConfig.telex, AVIMAutoConfig.vni, AVIMAutoConfig.viqr, AVIMAutoConfig.viqrStar];
var value1 = [telex, vni, viqr, viqr2], uniA = [uni, uni2, uni3, uni4], D2A = ["DAWEO", "6789", "D^+(", "D^*("];
for(a = 0; a < check.length; a++) {
if(check[a]) {
arr[arr.length] = value1[a];
} else {
D2A[a] = "";
}
}
for(a = 0; a < arr.length; a++) {
uniA[a] = arr[a];
}
uni = uniA[0];
uni2 = uniA[1];
uni3 = uniA[2];
uni4 = uniA[3];
this.D2 = D2A.join();
if(!uni) {
return;
}
} else if(method == 1) {
uni = telex;
this.D2 = "DAWEO";
}
else if(method == 2) {
uni = vni;
this.D2 = "6789";
}
else if(method == 3) {
uni = viqr;
this.D2 = "D^+(";
}
else if(method == 4) {
uni = viqr2;
this.D2 = "D^*(";
}
if(!this.is_ie) {
key = this.fcc(key.which);
w = this.mozGetText(obj);
if(!w || obj.sel) {
return;
}
if(this.D2.indexOf(this.up(key)) >= 0) {
noNormC = true;
} else {
noNormC = false;
}
this.main(w[0], key, w[1], uni, noNormC);
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni2 && !this.changed) {
this.main(w[0], key, w[1], uni2, noNormC);
}
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni3 && !this.changed) {
this.main(w[0], key, w[1], uni3, noNormC);
}
if(!dockspell) {
w = this.mozGetText(obj);
}
if(w && uni4 && !this.changed) {
this.main(w[0], key, w[1], uni4, noNormC);
}
} else {
obj = this.ieGetText(obj);
if(obj) {
var sT = obj.cW.text;
w = this.main(sT, key, 0, uni, false);
if(uni2 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni2, false);
}
if(uni3 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni3, false);
}
if(uni4 && ((w == sT) || (typeof(w) == 'undefined'))) {
w = this.main(sT, key, 0, uni4, false);
}
if(w) {
obj.cW.text = w;
}
}
}
if(this.D2.indexOf(this.up(key)) >= 0) {
if(!this.is_ie) {
w = this.mozGetText(obj);
if(!w) {
return;
}
this.normC(w[0], key, w[1]);
} else if(typeof(obj) == "object") {
obj = this.ieGetText(obj);
if(obj) {
w = obj.cW.text;
if(!this.changed) {
w += key;
this.changed = true;
}
obj.cW.text = w;
w = this.normC(w, key, 0);
if(w) {
obj = this.ieGetText(obj);
obj.cW.text = w;
}
}
}
}
}
this.findC = function(w, k, sf) {
var method = AVIMGlobalConfig.method;
if(((method == 3) || (method == 4)) && (w.substr(w.length - 1, 1) == "\\")) {
return [1, k.charCodeAt(0)];
}
var str = "", res, cc = "", pc = "", tE = "", vowA = [], s = "ÂĂÊÔƠƯêâăơôư", c = 0, dn = false, uw = this.up(w), tv, g;
var DAWEOFA = this.up(this.aA.join() + this.eA.join() + this.mocA.join() + this.trangA.join() + this.oA.join() + this.english), h, uc;
for(g = 0; g < sf.length; g++) {
if(this.nan(sf[g])) {
str += sf[g];
} else {
str += this.fcc(sf[g]);
}
}
var uk = this.up(k), uni_array = this.repSign(k), w2 = this.up(this.unV2(this.unV(w))), dont = "ƯA,ƯU".split(',');
if (this.DAWEO.indexOf(uk) >= 0) {
if(uk == this.moc) {
if((w2.indexOf("UU") >= 0) && (this.tw5 != dont[1])) {
if(w2.indexOf("UU") == (w.length - 2)) {
res=2;
} else {
return false;
}
} else if(w2.indexOf("UOU") >= 0) {
if(w2.indexOf("UOU") == (w.length-3)) {
res=2;
} else {
return false;
}
}
}
if(!res) {
for(g = 1; g <= w.length; g++) {
cc = w.substr(w.length - g, 1);
pc = this.up(w.substr(w.length - g - 1, 1));
uc = this.up(cc);
for(h = 0; h < dont.length; h++) {
if((this.tw5 == dont[h]) && (this.tw5 == this.unV(pc + uc))) {
dn = true;
}
}
if(dn) {
dn = false;
continue;
}
if(str.indexOf(uc) >= 0) {
if(((uk == this.moc) && (this.unV(uc) == "U") && (this.up(this.unV(w.substr(w.length - g + 1, 1))) == "A")) || ((uk == this.trang) && (this.unV(uc) == 'A') && (this.unV(pc) == 'U'))) {
if(this.unV(uc) == "U") {
tv=1;
} else {
tv=2;
}
var ccc = this.up(w.substr(w.length - g - tv, 1));
if(ccc != "Q") {
res = g + tv - 1;
} else if(uk == this.trang) {
res = g;
} else if(this.moc != this.trang) {
return false;
}
} else {
res = g;
}
if(!this.whit || (uw.indexOf("Ư") < 0) || (uw.indexOf("W") < 0)) {
break;
}
} else if(DAWEOFA.indexOf(uc) >= 0) {
if(uk == this.D) {
if(cc == "đ") {
res = [g, 'd'];
} else if(cc == "Đ") {
res = [g, 'D'];
}
} else {
res = this.DAWEOF(cc, uk, g);
}
if(res) break;
}
}
}
}
if((uk != this.Z) && (this.DAWEO.indexOf(uk) < 0)) {
var tEC = this.retKC(uk);
for(g = 0;g < tEC.length; g++) {
tE += this.fcc(tEC[g]);
}
}
for(g = 1; g <= w.length; g++) {
if(this.DAWEO.indexOf(uk) < 0) {
cc = this.up(w.substr(w.length - g, 1));
pc = this.up(w.substr(w.length - g - 1, 1));
if(str.indexOf(cc) >= 0) {
if(cc == 'U') {
if(pc != 'Q') {
c++;
vowA[vowA.length] = g;
}
} else if(cc == 'I') {
if((pc != 'G') || (c <= 0)) {
c++;
vowA[vowA.length] = g;
}
} else {
c++;
vowA[vowA.length] = g;
}
} else if(uk != this.Z) {
for(h = 0; h < uni_array.length; h++) if(uni_array[h] == w.charCodeAt(w.length - g)) {
if(this.spellerr(w, k)) {
return false;
}
return [g, tEC[h % 24]];
}
for(h = 0; h < tEC.length; h++) {
if(tEC[h] == w.charCodeAt(w.length - g)) {
return [g, this.fcc(this.skey[h])];
}
}
}
}
}
if((uk != this.Z) && (typeof(res) != 'object')) {
if(this.spellerr(w, k)) {
return false;
}
}
if(this.DAWEO.indexOf(uk) < 0) {
for(g = 1; g <= w.length; g++) {
if((uk != this.Z) && (s.indexOf(w.substr(w.length - g, 1)) >= 0)) {
return g;
} else if(tE.indexOf(w.substr(w.length - g, 1)) >= 0) {
for(h = 0; h < tEC.length; h++) {
if(w.substr(w.length - g, 1).charCodeAt(0) == tEC[h]) {
return [g, this.fcc(this.skey[h])];
}
}
}
}
}
if(res) {
return res;
}
if((c == 1) || (uk == this.Z)) {
return vowA[0];
} else if(c == 2) {
var v = 2;
if(w.substr(w.length - 1) == " ") {
v = 3;
}
var ttt = this.up(w.substr(w.length - v, 2));
if((AVIMGlobalConfig.oldAccent == 0) && ((ttt == "UY") || (ttt == "OA") || (ttt == "OE"))) {
return vowA[0];
}
var c2 = 0, fdconsonant, sc = "BCD" + this.fcc(272) + "GHKLMNPQRSTVX", dc = "CH,GI,KH,NGH,GH,NG,NH,PH,QU,TH,TR".split(',');
for(h = 1; h <= w.length; h++) {
fdconsonant=false;
for(g = 0; g < dc.length; g++) {
if(this.up(w.substr(w.length - h - dc[g].length + 1, dc[g].length)).indexOf(dc[g])>=0) {
c2++;
fdconsonant = true;
if(dc[g] != 'NGH') {
h++;
} else {
h+=2;
}
}
}
if(!fdconsonant) {
if(sc.indexOf(this.up(w.substr(w.length - h, 1))) >= 0) {
c2++;
} else {
break;
}
}
}
if((c2 == 1) || (c2 == 2)) {
return vowA[0];
} else {
return vowA[1];
}
} else if(c == 3) {
return vowA[1];
} else return false;
}
this.ie_replaceChar = function(w, pos, c) {
var r = "", uc = 0;
if(isNaN(c)) uc = this.up(c);
if(this.whit && (this.up(w.substr(w.length - pos - 1, 1)) == 'U') && (pos != 1) && (this.up(w.substr(w.length - pos - 2, 1)) != 'Q')) {
this.whit = false;
if((this.up(this.unV(this.fcc(c))) == "Ơ") || (uc == "O")) {
if(w.substr(w.length - pos - 1, 1) == 'u') r = this.fcc(432);
else r = this.fcc(431);
}
if(uc == "O") {
if(c == "o") {
c = 417;
} else {
c = 416;
}
}
}
if(!isNaN(c)) {
this.changed = true;
r += this.fcc(c);
return w.substr(0, w.length - pos - r.length + 1) + r + w.substr(w.length - pos + 1);
} else {
return w.substr(0, w.length - pos) + c + w.substr(w.length - pos + 1);
}
}
this.replaceChar = function(o, pos, c) {
var bb = false;
if(!this.nan(c)) {
var replaceBy = this.fcc(c), wfix = this.up(this.unV(this.fcc(c)));
this.changed = true;
} else {
var replaceBy = c;
if((this.up(c) == "O") && this.whit) {
bb=true;
}
}
if(!o.data) {
var savePos = o.selectionStart, sst = o.scrollTop;
if ((this.up(o.value.substr(pos - 1, 1)) == 'U') && (pos < savePos - 1) && (this.up(o.value.substr(pos - 2, 1)) != 'Q')) {
if((wfix == "Ơ") || bb) {
if (o.value.substr(pos-1,1) == 'u') {
var r = this.fcc(432);
} else {
var r = this.fcc(431);
}
}
if(bb) {
this.changed = true;
if(c == "o") {
replaceBy = "ơ";
} else {
replaceBy = "Ơ";
}
}
}
o.value = o.value.substr(0, pos) + replaceBy + o.value.substr(pos + 1);
if(r) o.value = o.value.substr(0, pos - 1) + r + o.value.substr(pos);
o.setSelectionRange(savePos, savePos);
o.scrollTop = sst;
} else {
if ((this.up(o.data.substr(pos - 1, 1)) == 'U') && (pos < o.pos - 1)) {
if((wfix == "Ơ") || bb) {
if (o.data.substr(pos - 1, 1) == 'u') {
var r = this.fcc(432);
} else {
var r = this.fcc(431);
}
}
if(bb) {
this.changed = true;
if(c == "o") {
replaceBy = "ơ";
} else {
replaceBy = "Ơ";
}
}
}
o.deleteData(pos, 1);
o.insertData(pos, replaceBy);
if(r) {
o.deleteData(pos - 1, 1);
o.insertData(pos - 1, r);
}
}
if(this.whit) {
this.whit=false;
}
}
this.tr = function(k, w, by, sf, i) {
var r, pos = this.findC(w, k, sf), g;
if(pos) {
if(pos[1]) {
if(this.is_ie) {
return this.ie_replaceChar(w, pos[0], pos[1]);
} else {
return this.replaceChar(this.oc, i-pos[0], pos[1]);
}
} else {
var c, pC = w.substr(w.length - pos, 1), cmp;
r = sf;
for(g = 0; g < r.length; g++) {
if(this.nan(r[g]) || (r[g] == "e")) {
cmp = pC;
} else {
cmp = pC.charCodeAt(0);
}
if(cmp == r[g]) {
if(!this.nan(by[g])) {
c = by[g];
} else {
c = by[g].charCodeAt(0);
}
if(this.is_ie) {
return this.ie_replaceChar(w, pos, c);
} else {
return this.replaceChar(this.oc, i - pos, c);
}
}
}
}
}
return false;
}
this.main = function(w, k, i, a, noNormC) {
var uk = this.up(k), bya = [this.db1, this.ab1, this.eb1, this.ob1, this.mocb1, this.trangb1], got = false, t = "d,D,a,A,a,A,o,O,u,U,e,E,o,O".split(",");
var sfa = [this.ds1, this.as1, this.es1, this.os1, this.mocs1, this.trangs1], by = [], sf = [], method = AVIMGlobalConfig.method, h, g;
if((method == 2) || ((method == 0) && (a[0] == "9"))) {
this.DAWEO = "6789";
this.SFJRX = "12534";
this.S = "1";
this.F = "2";
this.J = "5";
this.R = "3";
this.X = "4";
this.Z = "0";
this.D = "9";
this.FRX = "234";
this.AEO = "6";
this.moc = "7";
this.trang = "8";
this.them = "678";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 3) || ((method == 0) && (a[4] == "+"))) {
this.DAWEO = "^+(D";
this.SFJRX = "'`.?~";
this.S = "'";
this.F = "`";
this.J = ".";
this.R = "?";
this.X = "~";
this.Z = "-";
this.D = "D";
this.FRX = "`?~";
this.AEO = "^";
this.moc = "+";
this.trang = "(";
this.them = "^+(";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 4) || ((method == 0) && (a[4] == "*"))) {
this.DAWEO = "^*(D";
this.SFJRX = "'`.?~";
this.S = "'";
this.F = "`";
this.J = ".";
this.R = "?";
this.X = "~";
this.Z = "-";
this.D = "D";
this.FRX = "`?~";
this.AEO = "^";
this.moc = "*";
this.trang = "(";
this.them = "^*(";
this.A = "^";
this.E = "^";
this.O = "^";
} else if((method == 1) || ((method == 0) && (a[0] == "D"))) {
this.SFJRX = "SFJRX";
this.DAWEO = "DAWEO";
this.D = 'D';
this.S = 'S';
this.F = 'F';
this.J = 'J';
this.R = 'R';
this.X = 'X';
this.Z = 'Z';
this.FRX = "FRX";
this.them = "AOEW";
this.trang = "W";
this.moc = "W";
this.A = "A";
this.E = "E";
this.O = "O";
}
if(this.SFJRX.indexOf(uk) >= 0) {
var ret = this.sr(w,k,i);
got=true;
if(ret) {
return ret;
}
} else if(uk == this.Z) {
sf = this.repSign(null);
for(h = 0; h < this.english.length; h++) {
sf[sf.length] = this.lowen.charCodeAt(h);
sf[sf.length] = this.english.charCodeAt(h);
}
for(h = 0; h < 5; h++) {
for(g = 0; g < this.skey.length; g++) {
by[by.length] = this.skey[g];
}
}
for(h = 0; h < t.length; h++) {
by[by.length] = t[h];
}
got = true;
} else {
for(h = 0; h < a.length; h++) {
if(a[h] == uk) {
got = true;
by = by.concat(bya[h]);
sf = sf.concat(sfa[h]);
}
}
}
if(uk == this.moc) {
this.whit = true;
}
if(!got) {
if(noNormC) {
return;
} else {
return this.normC(w, k, i);
}
}
return this.DAWEOZ(k, w, by, sf, i, uk);
}
this.DAWEOZ = function(k, w, by, sf, i, uk) {
if((this.DAWEO.indexOf(uk) >= 0) || (this.Z.indexOf(uk) >= 0)) {
return this.tr(k, w, by, sf, i);
}
}
this.normC = function(w, k, i) {
var uk = this.up(k), u = this.repSign(null), fS, c, j, h, space = (k.charCodeAt(0) == 32) ? true : false;
if(!this.is_ie && space) {
return;
}
for(j = 1; j <= w.length; j++) {
for(h = 0; h < u.length; h++) {
if(u[h] == w.charCodeAt(w.length - j)) {
if(h <= 23) {
fS = this.S;
} else if(h <= 47) {
fS = this.F;
} else if(h <= 71) {
fS = this.J;
} else if(h <= 95) {
fS = this.R;
} else {
fS = this.X;
}
c = this.skey[h % 24];
if((this.alphabet.indexOf(uk) < 0) && (this.D2.indexOf(uk) < 0)) {
return w;
}
w = this.unV(w);
if(!space && !this.changed) {
w += k;
}
if(!this.is_ie) {
var sp = this.oc.selectionStart, pos = sp;
if(!this.changed) {
var sst = this.oc.scrollTop;
pos += k.length;
if(!this.oc.data) {
this.oc.value = this.oc.value.substr(0, sp) + k + this.oc.value.substr(this.oc.selectionEnd);
this.changed = true;
this.oc.scrollTop = sst;
} else {
this.oc.insertData(this.oc.pos, k);
this.oc.pos++;
this.range.setEnd(this.oc, this.oc.pos);
this.specialChange = true;
}
}
if(!this.oc.data) {
this.oc.setSelectionRange(pos, pos);
}
if(!this.ckspell(w, fS)) {
this.replaceChar(this.oc, i - j, c);
if(!this.oc.data) {
var a = [this.D];
this.main(w, fS, pos, a, false);
} else {
var ww = this.mozGetText(this.oc), a = [this.D];
this.main(ww[0], fS, ww[1], a, false);
}
}
} else {
var ret = this.sr(w, fS, 0);
if(space && ret) {
ret += this.fcc(32);
}
if(ret) {
return ret;
}
}
}
}
}
}
this.DAWEOF = function(cc, k, g) {
var ret = [g], kA = [this.A, this.moc, this.trang, this.E, this.O], z, a;
var ccA = [this.aA, this.mocA, this.trangA, this.eA, this.oA], ccrA = [this.arA, this.mocrA, this.arA, this.erA, this.orA];
for(a = 0; a < kA.length; a++) {
if(k == kA[a]) {
for(z = 0; z < ccA[a].length; z++) {
if(cc == ccA[a][z]) {
ret[1] = ccrA[a][z];
}
}
}
}
if(ret[1]) {
return ret;
} else {
return false;
}
}
this.retKC = function(k) {
if(k == this.S) {
return [225,7845,7855,233,7871,237,243,7889,7899,250,7913,253,193,7844,7854,201,7870,205,211,7888,7898,218,7912,221];
}
if(k == this.F) {
return [224,7847,7857,232,7873,236,242,7891,7901,249,7915,7923,192,7846,7856,200,7872,204,210,7890,7900,217,7914,7922];
}
if(k == this.J) {
return [7841,7853,7863,7865,7879,7883,7885,7897,7907,7909,7921,7925,7840,7852,7862,7864,7878,7882,7884,7896,7906,7908,7920,7924];
}
if(k == this.R) {
return [7843,7849,7859,7867,7875,7881,7887,7893,7903,7911,7917,7927,7842,7848,7858,7866,7874,7880,7886,7892,7902,7910,7916,7926];
}
if(k == this.X) {
return [227,7851,7861,7869,7877,297,245,7895,7905,361,7919,7929,195,7850,7860,7868,7876,296,213,7894,7904,360,7918,7928];
}
}
this.unV = function(w) {
var u = this.repSign(null), b, a;
for(a = 1; a <= w.length; a++) {
for(b = 0; b < u.length; b++) {
if(u[b] == w.charCodeAt(w.length - a)) {
w = w.substr(0, w.length - a) + this.fcc(this.skey[b % 24]) + w.substr(w.length - a + 1);
}
}
}
return w;
}
this.unV2 = function(w) {
var a, b;
for(a = 1; a <= w.length; a++) {
for(b = 0; b < this.skey.length; b++) {
if(this.skey[b] == w.charCodeAt(w.length - a)) {
w = w.substr(0, w.length - a) + this.skey2[b] + w.substr(w.length - a + 1);
}
}
}
return w;
}
this.repSign = function(k) {
var t = [], u = [], a, b;
for(a = 0; a < 5; a++) {
if((k == null)||(this.SFJRX.substr(a, 1) != this.up(k))) {
t = this.retKC(this.SFJRX.substr(a, 1));
for(b = 0; b < t.length; b++) u[u.length] = t[b];
}
}
return u;
}
this.sr = function(w, k, i) {
var sf = this.getSF(), pos = this.findC(w, k, sf);
if(pos) {
if(pos[1]) {
if(!this.is_ie) {
this.replaceChar(this.oc, i-pos[0], pos[1]);
} else {
return this.ie_replaceChar(w, pos[0], pos[1]);
}
} else {
var c = this.retUni(w, k, pos);
if (!this.is_ie) {
this.replaceChar(this.oc, i-pos, c);
} else {
return this.ie_replaceChar(w, pos, c);
}
}
}
return false;
}
this.retUni = function(w, k, pos) {
var u = this.retKC(this.up(k)), uC, lC, c = w.charCodeAt(w.length - pos), a, t = this.fcc(c);
for(a = 0; a < this.skey.length; a++) {
if(this.skey[a] == c) {
if(a < 12) {
lC=a;
uC=a+12;
} else {
lC = a - 12;
uC=a;
}
if(t != this.up(t)) {
return u[lC];
}
return u[uC];
}
}
}
this.ifInit = function(w) {
var sel = w.getSelection();
this.range = sel ? sel.getRangeAt(0) : document.createRange();
}
this.ifMoz = function(e) {
var code = e.which, avim = this.AVIM, cwi = e.target.parentNode.wi;
if(typeof(cwi) == "undefined") cwi = e.target.parentNode.parentNode.wi;
if(e.ctrlKey || (e.altKey && (code != 92) && (code != 126))) return;
avim.ifInit(cwi);
var node = avim.range.endContainer, newPos;
avim.sk = avim.fcc(code);
avim.saveStr = "";
if(avim.checkCode(code) || !avim.range.startOffset || (typeof(node.data) == 'undefined')) return;
node.sel = false;
if(node.data) {
avim.saveStr = node.data.substr(avim.range.endOffset);
if(avim.range.startOffset != avim.range.endOffset) {
node.sel=true;
}
node.deleteData(avim.range.startOffset, node.data.length);
}
avim.range.setEnd(node, avim.range.endOffset);
avim.range.setStart(node, 0);
if(!node.data) {
return;
}
node.value = node.data;
node.pos = node.data.length;
node.which=code;
avim.start(node, e);
node.insertData(node.data.length, avim.saveStr);
newPos = node.data.length - avim.saveStr.length + avim.kl;
avim.range.setEnd(node, newPos);
avim.range.setStart(node, newPos);
avim.kl = 0;
if(avim.specialChange) {
avim.specialChange = false;
avim.changed = false;
node.deleteData(node.pos - 1, 1);
}
if(avim.changed) {
avim.changed = false;
e.preventDefault();
}
}
this.FKeyPress = function() {
var obj = this.findF();
this.sk = this.fcc(obj.event.keyCode);
if(this.checkCode(obj.event.keyCode) || (obj.event.ctrlKey && (obj.event.keyCode != 92) && (obj.event.keyCode != 126))) {
return;
}
this.start(obj, this.sk);
}
this.checkCode = function(code) {
if(((AVIMGlobalConfig.onOff == 0) || ((code < 45) && (code != 42) && (code != 32) && (code != 39) && (code != 40) && (code != 43)) || (code == 145) || (code == 255))) {
return true;
}
}
this.notWord = function(w) {
var str = "\ \r\n#,\\;.:-_()<>+-*/=?!\"$%{}[]\'~|^\@\&\t" + this.fcc(160);
return (str.indexOf(w) >= 0);
}
this.nan = function(w) {
if (isNaN(w) || (w == 'e')) {
return true;
} else {
return false;
}
}
this.up = function(w) {
w = w.toUpperCase();
if(this.isKHTML) {
var str = "êôơâăưếốớấắứềồờầằừễỗỡẫẵữệộợậặự", rep="ÊÔƠÂĂƯẾỐỚẤẮỨỀỒỜẦẰỪỄỖỠẪẴỮỆỘỢẶỰ", z, io;
for(z = 0; z < w.length; z++) {
io = str.indexOf(w.substr(z, 1));
if(io >= 0) {
w = w.substr(0, z) + rep.substr(io, 1) + w.substr(z + 1);
}
}
}
return w;
}
this.findIgnore = function(el) {
var va = AVIMGlobalConfig.exclude, i;
for(i = 0; i < va.length; i++) {
if((el.id == va[i]) && (va[i].length > 0)) {
return true;
}
}
}
this.findF = function() {
var g;
for(g = 0; g < this.fID.length; g++) {
if(this.findIgnore(this.fID[g])) return;
this.frame = this.fID[g];
if(typeof(this.frame) != "undefined") {
try {
if (this.frame.contentWindow.document && this.frame.contentWindow.event) {
return this.frame.contentWindow;
}
} catch(e) {
if (this.frame.document && this.frame.event) {
return this.frame;
}
}
}
}
}
this.keyPressHandler = function(e) {
if(!this.support) {
return;
}
if(!this.is_ie) {
var el = e.target, code = e.which;
if(e.ctrlKey) {
return;
}
if(e.altKey && (code != 92) && (code != 126)) {
return;
}
} else {
var el = window.event.srcElement, code = window.event.keyCode;
if(window.event.ctrlKey && (code != 92) && (code != 126)) {
return;
}
}
if(((el.type != 'textarea') && (el.type != 'text')) || this.checkCode(code)) {
return;
}
this.sk = this.fcc(code);
if(this.findIgnore(el)) {
return;
}
if(!this.is_ie) {
this.start(el, e);
} else {
this.start(el, this.sk);
}
if(this.changed) {
this.changed = false;
return false;
}
return true;
}
this.attachEvt = function(obj, evt, handle, capture) {
if(this.is_ie) {
obj.attachEvent("on" + evt, handle);
} else {
obj.addEventListener(evt, handle, capture);
}
}
this.keyDownHandler = function(e) {
if(e == "iframe") {
this.frame = this.findF();
var key = this.frame.event.keyCode;
} else {
var key = (!this.is_ie) ? e.which : window.event.keyCode;
}
if (key == 123) {
document.getElementById('AVIMControl').style.display = (document.getElementById('AVIMControl').style.display == 'none') ? 'block' : 'none';
}
}
}
function AVIMInit(AVIM) {
var kkk = false;
if(AVIM.support && !AVIM.isKHTML) {
if(AVIM.is_opera) {
if(AVIM.operaVersion < 9) {
return;
}
}
for(AVIM.g = 0; AVIM.g < AVIM.fID.length; AVIM.g++) {
if(AVIM.findIgnore(AVIM.fID[AVIM.g])) {
continue;
}
if(AVIM.is_ie) {
var doc;
try {
AVIM.frame = AVIM.fID[AVIM.g];
if(typeof(AVIM.frame) != "undefined") {
if(AVIM.frame.contentWindow.document) {
doc = AVIM.frame.contentWindow.document;
} else if(AVIM.frame.document) {
doc = AVIM.frame.document;
}
}
} catch(e) {}
if(doc && ((AVIM.up(doc.designMode) == "ON") || doc.body.contentEditable)) {
for (var l = 0; l < AVIM.attached.length; l++) {
if (doc == AVIM.attached[l]) {
kkk = true;
break;
}
}
if (!kkk) {
AVIM.attached[AVIM.attached.length] = doc;
AVIM.attachEvt(doc, "keydown", function() {
AVIM.keyDownHandler("iframe");
}, false);
AVIM.attachEvt(doc, "keypress", function() {
AVIM.FKeyPress();
if(AVIM.changed) {
AVIM.changed = false;
return false;
}
}, false);
}
}
} else {
var iframedit;
try {
AVIM.wi = AVIM.fID[AVIM.g].contentWindow;
iframedit = AVIM.wi.document;
iframedit.wi = AVIM.wi;
if(iframedit && (AVIM.up(iframedit.designMode) == "ON")) {
iframedit.AVIM = AVIM;
AVIM.attachEvt(iframedit, "keypress", AVIM.ifMoz, false);
AVIM.attachEvt(iframedit, "keydown", AVIM.keyDownHandler, false);
}
} catch(e) {}
}
}
}
}
AVIMObj = new AVIM();
function AVIMAJAXFix() {
var a = 50;
while(a < 5000) {
setTimeout("AVIMInit(AVIMObj)", a);
a += 50;
}
}
AVIMAJAXFix();
AVIMObj.attachEvt(document, "mousedown", AVIMAJAXFix, false);
AVIMObj.attachEvt(document, "keydown", AVIMObj.keyDownHandler, true);
AVIMObj.attachEvt(document, "keypress", function(e) {
var a = AVIMObj.keyPressHandler(e);
if (a == false) {
if (AVIMObj.is_ie) window.event.returnValue = false;
else e.preventDefault();
}
}, true);
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.