Special:Preferences: Use OOjs UI
[lhc/web/wiklou.git] / resources / src / mediawiki.special / mediawiki.special.preferences.timezone.js
1 /*!
2 * JavaScript for Special:Preferences: Timezone field enhancements.
3 */
4 ( function ( mw, $ ) {
5 $( function () {
6 var
7 timezoneWidget, $localtimeHolder, servertime;
8
9 // Timezone functions.
10 // Guesses Timezone from browser and updates fields onchange.
11
12 // This is identical to OO.ui.infuse( ... ), but it makes the class name of the result known.
13 try {
14 timezoneWidget = mw.widgets.SelectWithInputWidget.static.infuse( $( '#wpTimeCorrection' ) );
15 } catch ( err ) {
16 // This preference could theoretically be disabled ($wgHiddenPrefs)
17 timezoneWidget = null;
18 }
19
20 $localtimeHolder = $( '#wpLocalTime' );
21 servertime = parseInt( $( 'input[name="wpServerTime"]' ).val(), 10 );
22
23 function minutesToHours( min ) {
24 var tzHour = Math.floor( Math.abs( min ) / 60 ),
25 tzMin = Math.abs( min ) % 60,
26 tzString = ( ( min >= 0 ) ? '' : '-' ) + ( ( tzHour < 10 ) ? '0' : '' ) + tzHour +
27 ':' + ( ( tzMin < 10 ) ? '0' : '' ) + tzMin;
28 return tzString;
29 }
30
31 function hoursToMinutes( hour ) {
32 var minutes,
33 arr = hour.split( ':' );
34
35 arr[ 0 ] = parseInt( arr[ 0 ], 10 );
36
37 if ( arr.length === 1 ) {
38 // Specification is of the form [-]XX
39 minutes = arr[ 0 ] * 60;
40 } else {
41 // Specification is of the form [-]XX:XX
42 minutes = Math.abs( arr[ 0 ] ) * 60 + parseInt( arr[ 1 ], 10 );
43 if ( arr[ 0 ] < 0 ) {
44 minutes *= -1;
45 }
46 }
47 // Gracefully handle non-numbers.
48 if ( isNaN( minutes ) ) {
49 return 0;
50 } else {
51 return minutes;
52 }
53 }
54
55 function updateTimezoneSelection() {
56 var minuteDiff, localTime,
57 type = timezoneWidget.dropdowninput.getValue();
58
59 if ( type === 'other' ) {
60 // User specified time zone manually in <input>
61 // Grab data from the textbox, parse it.
62 minuteDiff = hoursToMinutes( timezoneWidget.textinput.getValue() );
63 } else {
64 // Time zone not manually specified by user
65 if ( type === 'guess' ) {
66 // Get browser timezone & fill it in
67 minuteDiff = -( new Date().getTimezoneOffset() );
68 timezoneWidget.textinput.setValue( minutesToHours( minuteDiff ) );
69 timezoneWidget.dropdowninput.setValue( 'other' );
70 } else {
71 // Grab data from the dropdown value
72 minuteDiff = parseInt( type.split( '|' )[ 1 ], 10 ) || 0;
73 }
74 }
75
76 // Determine local time from server time and minutes difference, for display.
77 localTime = servertime + minuteDiff;
78
79 // Bring time within the [0,1440) range.
80 localTime = ( ( localTime % 1440 ) + 1440 ) % 1440;
81
82 $localtimeHolder.text( mw.language.convertNumber( minutesToHours( localTime ) ) );
83 }
84
85 if ( timezoneWidget ) {
86 timezoneWidget.dropdowninput.on( 'change', updateTimezoneSelection );
87 timezoneWidget.textinput.on( 'change', updateTimezoneSelection );
88 updateTimezoneSelection();
89 }
90
91 } );
92 }( mediaWiki, jQuery ) );