code
stringlengths
1
2.08M
language
stringclasses
1 value
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["en-US"] = $.extend(true, {}, en, { }, cultures["en-US"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["ru-RU"] = $.extend(true, {}, en, { name: "ru-RU", englishName: "Russian (Russia)", nativeName: "русский (Россия)", language: "ru", numberFormat: { ',': " ", '.': ",", percent: { pattern: ["-n%","n%"], ',': " ", '.': "," }, currency: { pattern: ["-n$","n$"], ',': " ", '.': ",", symbol: "р." } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"], namesAbbr: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"], namesShort: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"] }, months: { names: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь",""], namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""] }, monthsGenitive: { names: ["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря",""], namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "d MMMM yyyy 'г.'", t: "H:mm", T: "H:mm:ss", f: "d MMMM yyyy 'г.' H:mm", F: "d MMMM yyyy 'г.' H:mm:ss", Y: "MMMM yyyy" } }) } }, cultures["ru-RU"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["fr-FR"] = $.extend(true, {}, en, { name: "fr-FR", englishName: "French (France)", nativeName: "français (France)", language: "fr", numberFormat: { ',': " ", '.': ",", percent: { ',': " ", '.': "," }, currency: { pattern: ["-n $","n $"], ',': " ", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { firstDay: 1, days: { names: ["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"], namesAbbr: ["dim.","lun.","mar.","mer.","jeu.","ven.","sam."], namesShort: ["di","lu","ma","me","je","ve","sa"] }, months: { names: ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre",""], namesAbbr: ["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc.",""] }, AM: null, PM: null, eras: [{"name":"ap. J.-C.","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", F: "dddd d MMMM yyyy HH:mm:ss", M: "d MMMM", Y: "MMMM yyyy" } }) } }, cultures["fr-FR"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["de-DE"] = $.extend(true, {}, en, { name: "de-DE", englishName: "German (Germany)", nativeName: "Deutsch (Deutschland)", language: "de", numberFormat: { ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"], namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"], namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"] }, months: { names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""], namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""] }, AM: null, PM: null, eras: [{"name":"n. Chr.","start":null,"offset":0}], patterns: { d: "dd.MM.yyyy", D: "dddd, d. MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd, d. MMMM yyyy HH:mm", F: "dddd, d. MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["de-DE"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["cs-CZ"] = $.extend(true, {}, en, { name: "cs-CZ", englishName: "Czech (Czech Republic)", nativeName: "čeština (Česká republika)", language: "cs", numberFormat: { ',': " ", '.': ",", percent: { pattern: ["-n%","n%"], ',': " ", '.': "," }, currency: { pattern: ["-n $","n $"], ',': " ", '.': ",", symbol: "Kč" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["neděle","pondělí","úterý","středa","čtvrtek","pátek","sobota"], namesAbbr: ["ne","po","út","st","čt","pá","so"], namesShort: ["ne","po","út","st","čt","pá","so"] }, months: { names: ["leden","únor","březen","duben","květen","červen","červenec","srpen","září","říjen","listopad","prosinec",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, monthsGenitive: { names: ["ledna","února","března","dubna","května","června","července","srpna","září","října","listopadu","prosince",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["dop.","dop.","DOP."], PM: ["odp.","odp.","ODP."], eras: [{"name":"n. l.","start":null,"offset":0}], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy H:mm", F: "d. MMMM yyyy H:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["cs-CZ"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["ja-JP"] = $.extend(true, {}, en, { name: "ja-JP", englishName: "Japanese (Japan)", nativeName: "日本語 (日本)", language: "ja", numberFormat: { percent: { pattern: ["-n%","n%"] }, currency: { pattern: ["-$n","$n"], decimals: 0, symbol: "¥" } }, calendars: { standard: $.extend(true, {}, standard, { days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"西暦","start":null,"offset":0}], patterns: { d: "yyyy/MM/dd", D: "yyyy'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "yyyy'年'M'月'd'日' H:mm", F: "yyyy'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "yyyy'年'M'月'" } }), Japanese: $.extend(true, {}, standard, { name: "Japanese", days: { names: ["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日"], namesAbbr: ["日","月","火","水","木","金","土"], namesShort: ["日","月","火","水","木","金","土"] }, months: { names: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: ["午前","午前","午前"], PM: ["午後","午後","午後"], eras: [{"name":"平成","start":null,"offset":1867},{"name":"昭和","start":-1812153600000,"offset":1911},{"name":"大正","start":-1357603200000,"offset":1925},{"name":"明治","start":60022080000,"offset":1988}], twoDigitYearMax: 99, patterns: { d: "gg y/M/d", D: "gg y'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "gg y'年'M'月'd'日' H:mm", F: "gg y'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "gg y'年'M'月'" } }) } }, cultures["ja-JP"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
/*! * jQuery globalization Plugin v1.0.0pre * http://github.com/jquery/jquery-global * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function() { var globalization = {}, localized = { en: {} }; localized["default"] = localized.en; globalization.extend = function( deep ) { var target = arguments[ 1 ] || {}; for ( var i = 2, l = arguments.length; i < l; i++ ) { var source = arguments[ i ]; if ( source ) { for ( var field in source ) { var sourceVal = source[ field ]; if ( typeof sourceVal !== "undefined" ) { if ( deep && (isObject( sourceVal ) || isArray( sourceVal )) ) { var targetVal = target[ field ]; // extend onto the existing value, or create a new one targetVal = targetVal && (isObject( targetVal ) || isArray( targetVal )) ? targetVal : (isArray( sourceVal ) ? [] : {}); target[ field ] = this.extend( true, targetVal, sourceVal ); } else { target[ field ] = sourceVal; } } } } } return target; } globalization.findClosestCulture = function(name) { var match; if ( !name ) { return this.culture || this.cultures["default"]; } if ( isString( name ) ) { name = name.split( ',' ); } if ( isArray( name ) ) { var lang, cultures = this.cultures, list = name, i, l = list.length, prioritized = []; for ( i = 0; i < l; i++ ) { name = trim( list[ i ] ); var pri, parts = name.split( ';' ); lang = trim( parts[ 0 ] ); if ( parts.length === 1 ) { pri = 1; } else { name = trim( parts[ 1 ] ); if ( name.indexOf("q=") === 0 ) { name = name.substr( 2 ); pri = parseFloat( name, 10 ); pri = isNaN( pri ) ? 0 : pri; } else { pri = 1; } } prioritized.push( { lang: lang, pri: pri } ); } prioritized.sort(function(a, b) { return a.pri < b.pri ? 1 : -1; }); // exact match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; match = cultures[ lang ]; if ( match ) { return match; } } // neutral language match for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; do { var index = lang.lastIndexOf( "-" ); if ( index === -1 ) { break; } // strip off the last part. e.g. en-US => en lang = lang.substr( 0, index ); match = cultures[ lang ]; if ( match ) { return match; } } while ( 1 ); } // last resort: match first culture using that language for ( i = 0; i < l; i++ ) { lang = prioritized[ i ].lang; for ( var cultureKey in cultures ) { var culture = cultures[ cultureKey ]; if ( culture.language == lang ) { return culture; } } } } else if ( typeof name === 'object' ) { return name; } return match || null; } globalization.preferCulture = function(name) { this.culture = this.findClosestCulture( name ) || this.cultures["default"]; } globalization.localize = function(key, culture, value) { // usign default culture in case culture is not provided if (typeof culture !== 'string') { culture = this.culture.name || this.culture || "default"; } culture = this.cultures[ culture ] || { name: culture }; var local = localized[ culture.name ]; if ( arguments.length === 3 ) { if ( !local) { local = localized[ culture.name ] = {}; } local[ key ] = value; } else { if ( local ) { value = local[ key ]; } if ( typeof value === 'undefined' ) { var language = localized[ culture.language ]; if ( language ) { value = language[ key ]; } if ( typeof value === 'undefined' ) { value = localized["default"][ key ]; } } } return typeof value === "undefined" ? null : value; } globalization.format = function(value, format, culture) { culture = this.findClosestCulture( culture ); if ( typeof value === "number" ) { value = formatNumber( value, format, culture ); } else if ( value instanceof Date ) { value = formatDate( value, format, culture ); } return value; } globalization.parseInt = function(value, radix, culture) { return Math.floor( this.parseFloat( value, radix, culture ) ); } globalization.parseFloat = function(value, radix, culture) { // make radix optional if (typeof radix === "string") { culture = radix; radix = 10; } culture = this.findClosestCulture( culture ); var ret = NaN, nf = culture.numberFormat; if (value.indexOf(culture.numberFormat.currency.symbol) > -1) { // remove currency symbol value = value.replace(culture.numberFormat.currency.symbol, ""); // replace decimal seperator value = value.replace(culture.numberFormat.currency["."], culture.numberFormat["."]); } // trim leading and trailing whitespace value = trim( value ); // allow infinity or hexidecimal if (regexInfinity.test(value)) { ret = parseFloat(value, radix); } else if (!radix && regexHex.test(value)) { ret = parseInt(value, 16); } else { var signInfo = parseNegativePattern( value, nf, nf.pattern[0] ), sign = signInfo[0], num = signInfo[1]; // determine sign and number if ( sign === "" && nf.pattern[0] !== "-n" ) { signInfo = parseNegativePattern( value, nf, "-n" ); sign = signInfo[0]; num = signInfo[1]; } sign = sign || "+"; // determine exponent and number var exponent, intAndFraction, exponentPos = num.indexOf( 'e' ); if ( exponentPos < 0 ) exponentPos = num.indexOf( 'E' ); if ( exponentPos < 0 ) { intAndFraction = num; exponent = null; } else { intAndFraction = num.substr( 0, exponentPos ); exponent = num.substr( exponentPos + 1 ); } // determine decimal position var integer, fraction, decSep = nf['.'], decimalPos = intAndFraction.indexOf( decSep ); if ( decimalPos < 0 ) { integer = intAndFraction; fraction = null; } else { integer = intAndFraction.substr( 0, decimalPos ); fraction = intAndFraction.substr( decimalPos + decSep.length ); } // handle groups (e.g. 1,000,000) var groupSep = nf[","]; integer = integer.split(groupSep).join(''); var altGroupSep = groupSep.replace(/\u00A0/g, " "); if ( groupSep !== altGroupSep ) { integer = integer.split(altGroupSep).join(''); } // build a natively parsable number string var p = sign + integer; if ( fraction !== null ) { p += '.' + fraction; } if ( exponent !== null ) { // exponent itself may have a number patternd var expSignInfo = parseNegativePattern( exponent, nf, "-n" ); p += 'e' + (expSignInfo[0] || "+") + expSignInfo[1]; } if ( regexParseFloat.test( p ) ) { ret = parseFloat( p ); } } return ret; } globalization.parseDate = function(value, formats, culture) { culture = this.findClosestCulture( culture ); var date, prop, patterns; if ( formats ) { if ( typeof formats === "string" ) { formats = [ formats ]; } if ( formats.length ) { for ( var i = 0, l = formats.length; i < l; i++ ) { var format = formats[ i ]; if ( format ) { date = parseExact( value, format, culture ); if ( date ) { break; } } } } } else { patterns = culture.calendar.patterns; for ( prop in patterns ) { date = parseExact( value, patterns[prop], culture ); if ( date ) { break; } } } return date || null; } // 1. When defining a culture, all fields are required except the ones stated as optional. // 2. You can use globalization.extend to copy an existing culture and provide only the differing values, // a good practice since most cultures do not differ too much from the 'default' culture. // DO use the 'default' culture if you do this, as it is the only one that definitely // exists. // 3. Other plugins may add to the culture information provided by extending it. However, // that plugin may extend it prior to the culture being defined, or after. Therefore, // do not overwrite values that already exist when defining the baseline for a culture, // by extending your culture object with the existing one. // 4. Each culture should have a ".calendars" object with at least one calendar named "standard" // which serves as the default calendar in use by that culture. // 5. Each culture should have a ".calendar" object which is the current calendar being used, // it may be dynamically changed at any time to one of the calendars in ".calendars". // To define a culture, use the following pattern, which handles defining the culture based // on the 'default culture, extending it with the existing culture if it exists, and defining // it if it does not exist. // globalization.cultures.foo = globalization.extend(true, globalization.extend(true, {}, globalization.cultures['default'], fooCulture), globalization.cultures.foo) var cultures = globalization.cultures = globalization.cultures || {}; var en = cultures["default"] = cultures.en = globalization.extend(true, { // A unique name for the culture in the form <language code>-<country/region code> name: "en", // the name of the culture in the english language englishName: "English", // the name of the culture in its own language nativeName: "English", // whether the culture uses right-to-left text isRTL: false, // 'language' is used for so-called "specific" cultures. // For example, the culture "es-CL" means "Spanish, in Chili". // It represents the Spanish-speaking culture as it is in Chili, // which might have different formatting rules or even translations // than Spanish in Spain. A "neutral" culture is one that is not // specific to a region. For example, the culture "es" is the generic // Spanish culture, which may be a more generalized version of the language // that may or may not be what a specific culture expects. // For a specific culture like "es-CL", the 'language' field refers to the // neutral, generic culture information for the language it is using. // This is not always a simple matter of the string before the dash. // For example, the "zh-Hans" culture is netural (Simplified Chinese). // And the 'zh-SG' culture is Simplified Chinese in Singapore, whose lanugage // field is "zh-CHS", not "zh". // This field should be used to navigate from a specific culture to it's // more general, neutral culture. If a culture is already as general as it // can get, the language may refer to itself. language: "en", // numberFormat defines general number formatting rules, like the digits in // each grouping, the group separator, and how negative numbers are displayed. numberFormat: { // [negativePattern] // Note, numberFormat.pattern has no 'positivePattern' unlike percent and currency, // but is still defined as an array for consistency with them. // negativePattern: one of "(n)|-n|- n|n-|n -" pattern: ["-n"], // number of decimal places normally shown decimals: 2, // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // symbol used for positive numbers '+': "+", // symbol used for negative numbers '-': "-", percent: { // [negativePattern, positivePattern] // negativePattern: one of "-n %|-n%|-%n|%-n|%n-|n-%|n%-|-% n|n %-|% n-|% -n|n- %" // positivePattern: one of "n %|n%|%n|% n" pattern: ["-n %","n %"], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // symbol used to represent a percentage symbol: "%" }, currency: { // [negativePattern, positivePattern] // negativePattern: one of "($n)|-$n|$-n|$n-|(n$)|-n$|n-$|n$-|-n $|-$ n|n $-|$ n-|$ -n|n- $|($ n)|(n $)" // positivePattern: one of "$n|n$|$ n|n $" pattern: ["($n)","$n"], // number of decimal places normally shown decimals: 2, // array of numbers indicating the size of each number group. // TODO: more detailed description and example groupSizes: [3], // string that separates number groups, as in 1,000,000 ',': ",", // string that separates a number from the fractional portion, as in 1.99 '.': ".", // symbol used to represent currency symbol: "$" } }, // calendars defines all the possible calendars used by this culture. // There should be at least one defined with name 'standard', and is the default // calendar used by the culture. // A calendar contains information about how dates are formatted, information about // the calendar's eras, a standard set of the date formats, // translations for day and month names, and if the calendar is not based on the Gregorian // calendar, conversion functions to and from the Gregorian calendar. calendars: { standard: { // name that identifies the type of calendar this is name: "Gregorian_USEnglish", // separator of parts of a date (e.g. '/' in 11/05/1955) '/': "/", // separator of parts of a time (e.g. ':' in 05:44 PM) ':': ":", // the first day of the week (0 = Sunday, 1 = Monday, etc) firstDay: 0, days: { // full day names names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], // abbreviated day names namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"], // shortest day names namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"] }, months: { // full month names (13 months for lunar calendards -- 13th month should be "" if not lunar) names: ["January","February","March","April","May","June","July","August","September","October","November","December",""], // abbreviated month names namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""] }, // AM and PM designators in one of these forms: // The usual view, and the upper and lower case versions // [standard,lowercase,uppercase] // The culture does not use AM or PM (likely all standard date formats use 24 hour time) // null AM: ["AM", "am", "AM"], PM: ["PM", "pm", "PM"], eras: [ // eras in reverse chronological order. // name: the name of the era in this culture (e.g. A.D., C.E.) // start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era. // offset: offset in years from gregorian calendar { "name": "A.D.", "start": null, "offset": 0 } ], // when a two digit year is given, it will never be parsed as a four digit // year greater than this year (in the appropriate era for the culture) // Set it as a full year (e.g. 2029) or use an offset format starting from // the current year: "+19" would correspond to 2029 if the current year 2010. twoDigitYearMax: 2029, // set of predefined date and time patterns used by the culture // these represent the format someone in this culture would expect // to see given the portions of the date that are shown. patterns: { // short date pattern d: "M/d/yyyy", // long date pattern D: "dddd, MMMM dd, yyyy", // short time pattern t: "h:mm tt", // long time pattern T: "h:mm:ss tt", // long date, short time pattern f: "dddd, MMMM dd, yyyy h:mm tt", // long date, long time pattern F: "dddd, MMMM dd, yyyy h:mm:ss tt", // month/day pattern M: "MMMM dd", // month/year pattern Y: "yyyy MMMM", // S is a sortable format that does not vary by culture S: "yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss" } // optional fields for each calendar: /* monthsGenitive: Same as months but used when the day preceeds the month. Omit if the culture has no genitive distinction in month names. For an explaination of genitive months, see http://blogs.msdn.com/michkap/archive/2004/12/25/332259.aspx convert: Allows for the support of non-gregorian based calendars. This convert object is used to to convert a date to and from a gregorian calendar date to handle parsing and formatting. The two functions: fromGregorian(date) Given the date as a parameter, return an array with parts [year, month, day] corresponding to the non-gregorian based year, month, and day for the calendar. toGregorian(year, month, day) Given the non-gregorian year, month, and day, return a new Date() object set to the corresponding date in the gregorian calendar. */ } } }, cultures.en); en.calendar = en.calendar || en.calendars.standard; var regexTrim = /^\s+|\s+$/g, regexInfinity = /^[+-]?infinity$/i, regexHex = /^0x[a-f0-9]+$/i, regexParseFloat = /^[+-]?\d*\.?\d*(e[+-]?\d+)?$/, toString = Object.prototype.toString; function startsWith(value, pattern) { return value.indexOf( pattern ) === 0; } function endsWith(value, pattern) { return value.substr( value.length - pattern.length ) === pattern; } function trim(value) { return (value+"").replace( regexTrim, "" ); } function zeroPad(str, count, left) { for (var l=str.length; l < count; l++) { str = (left ? ('0' + str) : (str + '0')); } return str; } function isArray(obj) { return toString.call(obj) === "[object Array]"; } function isString(obj) { return toString.call(obj) === "[object String]"; } function isObject(obj) { return toString.call(obj) === "[object Object]"; } function arrayIndexOf( array, item ) { if ( array.indexOf ) { return array.indexOf( item ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === item ) { return i; } } return -1; } // *************************************** Numbers *************************************** function expandNumber(number, precision, formatInfo) { var groupSizes = formatInfo.groupSizes, curSize = groupSizes[ 0 ], curGroupIndex = 1, factor = Math.pow( 10, precision ), rounded = Math.round( number * factor ) / factor; if ( !isFinite(rounded) ) { rounded = number; } number = rounded; var numberString = number+"", right = "", split = numberString.split(/e/i), exponent = split.length > 1 ? parseInt( split[ 1 ], 10 ) : 0; numberString = split[ 0 ]; split = numberString.split( "." ); numberString = split[ 0 ]; right = split.length > 1 ? split[ 1 ] : ""; var l; if ( exponent > 0 ) { right = zeroPad( right, exponent, false ); numberString += right.slice( 0, exponent ); right = right.substr( exponent ); } else if ( exponent < 0 ) { exponent = -exponent; numberString = zeroPad( numberString, exponent + 1 ); right = numberString.slice( -exponent, numberString.length ) + right; numberString = numberString.slice( 0, -exponent ); } if ( precision > 0 ) { right = formatInfo['.'] + ((right.length > precision) ? right.slice( 0, precision ) : zeroPad( right, precision )); } else { right = ""; } var stringIndex = numberString.length - 1, sep = formatInfo[","], ret = ""; while ( stringIndex >= 0 ) { if ( curSize === 0 || curSize > stringIndex ) { return numberString.slice( 0, stringIndex + 1 ) + ( ret.length ? ( sep + ret + right ) : right ); } ret = numberString.slice( stringIndex - curSize + 1, stringIndex + 1 ) + ( ret.length ? ( sep + ret ) : "" ); stringIndex -= curSize; if ( curGroupIndex < groupSizes.length ) { curSize = groupSizes[ curGroupIndex ]; curGroupIndex++; } } return numberString.slice( 0, stringIndex + 1 ) + sep + ret + right; } function parseNegativePattern(value, nf, negativePattern) { var neg = nf["-"], pos = nf["+"], ret; switch (negativePattern) { case "n -": neg = ' ' + neg; pos = ' ' + pos; // fall through case "n-": if ( endsWith( value, neg ) ) { ret = [ '-', value.substr( 0, value.length - neg.length ) ]; } else if ( endsWith( value, pos ) ) { ret = [ '+', value.substr( 0, value.length - pos.length ) ]; } break; case "- n": neg += ' '; pos += ' '; // fall through case "-n": if ( startsWith( value, neg ) ) { ret = [ '-', value.substr( neg.length ) ]; } else if ( startsWith(value, pos) ) { ret = [ '+', value.substr( pos.length ) ]; } break; case "(n)": if ( startsWith( value, '(' ) && endsWith( value, ')' ) ) { ret = [ '-', value.substr( 1, value.length - 2 ) ]; } break; } return ret || [ '', value ]; } function formatNumber(value, format, culture) { if ( !format || format === 'i' ) { return culture.name.length ? value.toLocaleString() : value.toString(); } format = format || "D"; var nf = culture.numberFormat, number = Math.abs(value), precision = -1, pattern; if (format.length > 1) precision = parseInt( format.slice( 1 ), 10 ); var current = format.charAt( 0 ).toUpperCase(), formatInfo; switch (current) { case "D": pattern = 'n'; if (precision !== -1) { number = zeroPad( ""+number, precision, true ); } if (value < 0) number = -number; break; case "N": formatInfo = nf; // fall through case "C": formatInfo = formatInfo || nf.currency; // fall through case "P": formatInfo = formatInfo || nf.percent; pattern = value < 0 ? formatInfo.pattern[0] : (formatInfo.pattern[1] || "n"); if (precision === -1) precision = formatInfo.decimals; number = expandNumber( number * (current === "P" ? 100 : 1), precision, formatInfo ); break; default: throw "Bad number format specifier: " + current; } var patternParts = /n|\$|-|%/g, ret = ""; for (;;) { var index = patternParts.lastIndex, ar = patternParts.exec(pattern); ret += pattern.slice( index, ar ? ar.index : pattern.length ); if (!ar) { break; } switch (ar[0]) { case "n": ret += number; break; case "$": ret += nf.currency.symbol; break; case "-": // don't make 0 negative if ( /[1-9]/.test( number ) ) { ret += nf["-"]; } break; case "%": ret += nf.percent.symbol; break; } } return ret; } // *************************************** Dates *************************************** function outOfRange(value, low, high) { return value < low || value > high; } function expandYear(cal, year) { // expands 2-digit year into 4 digits. var now = new Date(), era = getEra(now); if ( year < 100 ) { var twoDigitYearMax = cal.twoDigitYearMax; twoDigitYearMax = typeof twoDigitYearMax === 'string' ? new Date().getFullYear() % 100 + parseInt( twoDigitYearMax, 10 ) : twoDigitYearMax; var curr = getEraYear( now, cal, era ); year += curr - ( curr % 100 ); if ( year > twoDigitYearMax ) { year -= 100; } } return year; } function getEra(date, eras) { if ( !eras ) return 0; var start, ticks = date.getTime(); for ( var i = 0, l = eras.length; i < l; i++ ) { start = eras[ i ].start; if ( start === null || ticks >= start ) { return i; } } return 0; } function toUpper(value) { // 'he-IL' has non-breaking space in weekday names. return value.split( "\u00A0" ).join(' ').toUpperCase(); } function toUpperArray(arr) { var results = []; for ( var i = 0, l = arr.length; i < l; i++ ) { results[i] = toUpper(arr[i]); } return results; } function getEraYear(date, cal, era, sortable) { var year = date.getFullYear(); if ( !sortable && cal.eras ) { // convert normal gregorian year to era-shifted gregorian // year by subtracting the era offset year -= cal.eras[ era ].offset; } return year; } function getDayIndex(cal, value, abbr) { var ret, days = cal.days, upperDays = cal._upperDays; if ( !upperDays ) { cal._upperDays = upperDays = [ toUpperArray( days.names ), toUpperArray( days.namesAbbr ), toUpperArray( days.namesShort ) ]; } value = toUpper( value ); if ( abbr ) { ret = arrayIndexOf( upperDays[ 1 ], value ); if ( ret === -1 ) { ret = arrayIndexOf( upperDays[ 2 ], value ); } } else { ret = arrayIndexOf( upperDays[ 0 ], value ); } return ret; } function getMonthIndex(cal, value, abbr) { var months = cal.months, monthsGen = cal.monthsGenitive || cal.months, upperMonths = cal._upperMonths, upperMonthsGen = cal._upperMonthsGen; if ( !upperMonths ) { cal._upperMonths = upperMonths = [ toUpperArray( months.names ), toUpperArray( months.namesAbbr ) ]; cal._upperMonthsGen = upperMonthsGen = [ toUpperArray( monthsGen.names ), toUpperArray( monthsGen.namesAbbr ) ]; } value = toUpper( value ); var i = arrayIndexOf( abbr ? upperMonths[ 1 ] : upperMonths[ 0 ], value ); if ( i < 0 ) { i = arrayIndexOf( abbr ? upperMonthsGen[ 1 ] : upperMonthsGen[ 0 ], value ); } return i; } function appendPreOrPostMatch(preMatch, strings) { // appends pre- and post- token match strings while removing escaped characters. // Returns a single quote count which is used to determine if the token occurs // in a string literal. var quoteCount = 0, escaped = false; for ( var i = 0, il = preMatch.length; i < il; i++ ) { var c = preMatch.charAt( i ); switch ( c ) { case '\'': if ( escaped ) { strings.push( "'" ); } else { quoteCount++; } escaped = false; break; case '\\': if ( escaped ) { strings.push( "\\" ); } escaped = !escaped; break; default: strings.push( c ); escaped = false; break; } } return quoteCount; } function expandFormat(cal, format) { // expands unspecified or single character date formats into the full pattern. format = format || "F"; var pattern, patterns = cal.patterns, len = format.length; if ( len === 1 ) { pattern = patterns[ format ]; if ( !pattern ) { throw "Invalid date format string '" + format + "'."; } format = pattern; } else if ( len === 2 && format.charAt(0) === "%" ) { // %X escape format -- intended as a custom format string that is only one character, not a built-in format. format = format.charAt( 1 ); } return format; } function getParseRegExp(cal, format) { // converts a format string into a regular expression with groups that // can be used to extract date fields from a date string. // check for a cached parse regex. var re = cal._parseRegExp; if ( !re ) { cal._parseRegExp = re = {}; } else { var reFormat = re[ format ]; if ( reFormat ) { return reFormat; } } // expand single digit formats, then escape regular expression characters. var expFormat = expandFormat( cal, format ).replace( /([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1" ), regexp = ["^"], groups = [], index = 0, quoteCount = 0, tokenRegExp = getTokenRegExp(), match; // iterate through each date token found. while ( (match = tokenRegExp.exec( expFormat )) !== null ) { var preMatch = expFormat.slice( index, match.index ); index = tokenRegExp.lastIndex; // don't replace any matches that occur inside a string literal. quoteCount += appendPreOrPostMatch( preMatch, regexp ); if ( quoteCount % 2 ) { regexp.push( match[ 0 ] ); continue; } // add a regex group for the token. var m = match[ 0 ], len = m.length, add; switch ( m ) { case 'dddd': case 'ddd': case 'MMMM': case 'MMM': case 'gg': case 'g': add = "(\\D+)"; break; case 'tt': case 't': add = "(\\D*)"; break; case 'yyyy': case 'fff': case 'ff': case 'f': add = "(\\d{" + len + "})"; break; case 'dd': case 'd': case 'MM': case 'M': case 'yy': case 'y': case 'HH': case 'H': case 'hh': case 'h': case 'mm': case 'm': case 'ss': case 's': add = "(\\d\\d?)"; break; case 'zzz': add = "([+-]?\\d\\d?:\\d{2})"; break; case 'zz': case 'z': add = "([+-]?\\d\\d?)"; break; case '/': add = "(\\" + cal["/"] + ")"; break; default: throw "Invalid date format pattern '" + m + "'."; break; } if ( add ) { regexp.push( add ); } groups.push( match[ 0 ] ); } appendPreOrPostMatch( expFormat.slice( index ), regexp ); regexp.push( "$" ); // allow whitespace to differ when matching formats. var regexpStr = regexp.join( '' ).replace( /\s+/g, "\\s+" ), parseRegExp = {'regExp': regexpStr, 'groups': groups}; // cache the regex for this format. return re[ format ] = parseRegExp; } function getTokenRegExp() { // regular expression for matching date and time tokens in format strings. return /\/|dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z|gg|g/g; } function parseExact(value, format, culture) { // try to parse the date string by matching against the format string // while using the specified culture for date field names. value = trim( value ); var cal = culture.calendar, // convert date formats into regular expressions with groupings. // use the regexp to determine the input format and extract the date fields. parseInfo = getParseRegExp(cal, format), match = new RegExp(parseInfo.regExp).exec(value); if (match === null) { return null; } // found a date format that matches the input. var groups = parseInfo.groups, era = null, year = null, month = null, date = null, weekDay = null, hour = 0, hourOffset, min = 0, sec = 0, msec = 0, tzMinOffset = null, pmHour = false; // iterate the format groups to extract and set the date fields. for ( var j = 0, jl = groups.length; j < jl; j++ ) { var matchGroup = match[ j + 1 ]; if ( matchGroup ) { var current = groups[ j ], clength = current.length, matchInt = parseInt( matchGroup, 10 ); switch ( current ) { case 'dd': case 'd': // Day of month. date = matchInt; // check that date is generally in valid range, also checking overflow below. if ( outOfRange( date, 1, 31 ) ) return null; break; case 'MMM': case 'MMMM': month = getMonthIndex( cal, matchGroup, clength === 3 ); if ( outOfRange( month, 0, 11 ) ) return null; break; case 'M': case 'MM': // Month. month = matchInt - 1; if ( outOfRange( month, 0, 11 ) ) return null; break; case 'y': case 'yy': case 'yyyy': year = clength < 4 ? expandYear( cal, matchInt ) : matchInt; if ( outOfRange( year, 0, 9999 ) ) return null; break; case 'h': case 'hh': // Hours (12-hour clock). hour = matchInt; if ( hour === 12 ) hour = 0; if ( outOfRange( hour, 0, 11 ) ) return null; break; case 'H': case 'HH': // Hours (24-hour clock). hour = matchInt; if ( outOfRange( hour, 0, 23 ) ) return null; break; case 'm': case 'mm': // Minutes. min = matchInt; if ( outOfRange( min, 0, 59 ) ) return null; break; case 's': case 'ss': // Seconds. sec = matchInt; if ( outOfRange( sec, 0, 59 ) ) return null; break; case 'tt': case 't': // AM/PM designator. // see if it is standard, upper, or lower case PM. If not, ensure it is at least one of // the AM tokens. If not, fail the parse for this format. pmHour = cal.PM && ( matchGroup === cal.PM[0] || matchGroup === cal.PM[1] || matchGroup === cal.PM[2] ); if ( !pmHour && ( !cal.AM || (matchGroup !== cal.AM[0] && matchGroup !== cal.AM[1] && matchGroup !== cal.AM[2]) ) ) return null; break; case 'f': // Deciseconds. case 'ff': // Centiseconds. case 'fff': // Milliseconds. msec = matchInt * Math.pow( 10, 3-clength ); if ( outOfRange( msec, 0, 999 ) ) return null; break; case 'ddd': // Day of week. case 'dddd': // Day of week. weekDay = getDayIndex( cal, matchGroup, clength === 3 ); if ( outOfRange( weekDay, 0, 6 ) ) return null; break; case 'zzz': // Time zone offset in +/- hours:min. var offsets = matchGroup.split( /:/ ); if ( offsets.length !== 2 ) return null; hourOffset = parseInt( offsets[ 0 ], 10 ); if ( outOfRange( hourOffset, -12, 13 ) ) return null; var minOffset = parseInt( offsets[ 1 ], 10 ); if ( outOfRange( minOffset, 0, 59 ) ) return null; tzMinOffset = (hourOffset * 60) + (startsWith( matchGroup, '-' ) ? -minOffset : minOffset); break; case 'z': case 'zz': // Time zone offset in +/- hours. hourOffset = matchInt; if ( outOfRange( hourOffset, -12, 13 ) ) return null; tzMinOffset = hourOffset * 60; break; case 'g': case 'gg': var eraName = matchGroup; if ( !eraName || !cal.eras ) return null; eraName = trim( eraName.toLowerCase() ); for ( var i = 0, l = cal.eras.length; i < l; i++ ) { if ( eraName === cal.eras[ i ].name.toLowerCase() ) { era = i; break; } } // could not find an era with that name if ( era === null ) return null; break; } } } var result = new Date(), defaultYear, convert = cal.convert; defaultYear = convert ? convert.fromGregorian( result )[ 0 ] : result.getFullYear(); if ( year === null ) { year = defaultYear; } else if ( cal.eras ) { // year must be shifted to normal gregorian year // but not if year was not specified, its already normal gregorian // per the main if clause above. year += cal.eras[ (era || 0) ].offset; } // set default day and month to 1 and January, so if unspecified, these are the defaults // instead of the current day/month. if ( month === null ) { month = 0; } if ( date === null ) { date = 1; } // now have year, month, and date, but in the culture's calendar. // convert to gregorian if necessary if ( convert ) { result = convert.toGregorian( year, month, date ); // conversion failed, must be an invalid match if ( result === null ) return null; } else { // have to set year, month and date together to avoid overflow based on current date. result.setFullYear( year, month, date ); // check to see if date overflowed for specified month (only checked 1-31 above). if ( result.getDate() !== date ) return null; // invalid day of week. if ( weekDay !== null && result.getDay() !== weekDay ) { return null; } } // if pm designator token was found make sure the hours fit the 24-hour clock. if ( pmHour && hour < 12 ) { hour += 12; } result.setHours( hour, min, sec, msec ); if ( tzMinOffset !== null ) { // adjust timezone to utc before applying local offset. var adjustedMin = result.getMinutes() - ( tzMinOffset + result.getTimezoneOffset() ); // Safari limits hours and minutes to the range of -127 to 127. We need to use setHours // to ensure both these fields will not exceed this range. adjustedMin will range // somewhere between -1440 and 1500, so we only need to split this into hours. result.setHours( result.getHours() + parseInt( adjustedMin / 60, 10 ), adjustedMin % 60 ); } return result; } function formatDate(value, format, culture) { var cal = culture.calendar, convert = cal.convert; if ( !format || !format.length || format === 'i' ) { var ret; if ( culture && culture.name.length ) { if ( convert ) { // non-gregorian calendar, so we cannot use built-in toLocaleString() ret = formatDate( value, cal.patterns.F, culture ); } else { var eraDate = new Date( value.getTime() ), era = getEra( value, cal.eras ); eraDate.setFullYear( getEraYear( value, cal, era ) ); ret = eraDate.toLocaleString(); } } else { ret = value.toString(); } return ret; } var eras = cal.eras, sortable = format === "s"; format = expandFormat( cal, format ); // Start with an empty string ret = []; var hour, zeros = ['0','00','000'], foundDay, checkedDay, dayPartRegExp = /([^d]|^)(d|dd)([^d]|$)/g, quoteCount = 0, tokenRegExp = getTokenRegExp(), converted; function padZeros(num, c) { var r, s = num+''; if ( c > 1 && s.length < c ) { r = ( zeros[ c - 2 ] + s); return r.substr( r.length - c, c ); } else { r = s; } return r; } function hasDay() { if ( foundDay || checkedDay ) { return foundDay; } foundDay = dayPartRegExp.test( format ); checkedDay = true; return foundDay; } function getPart( date, part ) { if ( converted ) { return converted[ part ]; } switch ( part ) { case 0: return date.getFullYear(); case 1: return date.getMonth(); case 2: return date.getDate(); } } if ( !sortable && convert ) { converted = convert.fromGregorian( value ); } for (;;) { // Save the current index var index = tokenRegExp.lastIndex, // Look for the next pattern ar = tokenRegExp.exec( format ); // Append the text before the pattern (or the end of the string if not found) var preMatch = format.slice( index, ar ? ar.index : format.length ); quoteCount += appendPreOrPostMatch( preMatch, ret ); if ( !ar ) { break; } // do not replace any matches that occur inside a string literal. if ( quoteCount % 2 ) { ret.push( ar[ 0 ] ); continue; } var current = ar[ 0 ], clength = current.length; switch ( current ) { case "ddd": //Day of the week, as a three-letter abbreviation case "dddd": // Day of the week, using the full name var names = (clength === 3) ? cal.days.namesAbbr : cal.days.names; ret.push( names[ value.getDay() ] ); break; case "d": // Day of month, without leading zero for single-digit days case "dd": // Day of month, with leading zero for single-digit days foundDay = true; ret.push( padZeros( getPart( value, 2 ), clength ) ); break; case "MMM": // Month, as a three-letter abbreviation case "MMMM": // Month, using the full name var part = getPart( value, 1 ); ret.push( (cal.monthsGenitive && hasDay()) ? cal.monthsGenitive[ clength === 3 ? "namesAbbr" : "names" ][ part ] : cal.months[ clength === 3 ? "namesAbbr" : "names" ][ part ] ); break; case "M": // Month, as digits, with no leading zero for single-digit months case "MM": // Month, as digits, with leading zero for single-digit months ret.push( padZeros( getPart( value, 1 ) + 1, clength ) ); break; case "y": // Year, as two digits, but with no leading zero for years less than 10 case "yy": // Year, as two digits, with leading zero for years less than 10 case "yyyy": // Year represented by four full digits part = converted ? converted[ 0 ] : getEraYear( value, cal, getEra( value, eras ), sortable ); if ( clength < 4 ) { part = part % 100; } ret.push( padZeros( part, clength ) ); break; case "h": // Hours with no leading zero for single-digit hours, using 12-hour clock case "hh": // Hours with leading zero for single-digit hours, using 12-hour clock hour = value.getHours() % 12; if ( hour === 0 ) hour = 12; ret.push( padZeros( hour, clength ) ); break; case "H": // Hours with no leading zero for single-digit hours, using 24-hour clock case "HH": // Hours with leading zero for single-digit hours, using 24-hour clock ret.push( padZeros( value.getHours(), clength ) ); break; case "m": // Minutes with no leading zero for single-digit minutes case "mm": // Minutes with leading zero for single-digit minutes ret.push( padZeros( value.getMinutes(), clength ) ); break; case "s": // Seconds with no leading zero for single-digit seconds case "ss": // Seconds with leading zero for single-digit seconds ret.push( padZeros(value .getSeconds(), clength ) ); break; case "t": // One character am/pm indicator ("a" or "p") case "tt": // Multicharacter am/pm indicator part = value.getHours() < 12 ? (cal.AM ? cal.AM[0] : " ") : (cal.PM ? cal.PM[0] : " "); ret.push( clength === 1 ? part.charAt( 0 ) : part ); break; case "f": // Deciseconds case "ff": // Centiseconds case "fff": // Milliseconds ret.push( padZeros( value.getMilliseconds(), 3 ).substr( 0, clength ) ); break; case "z": // Time zone offset, no leading zero case "zz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( (hour <= 0 ? '+' : '-') + padZeros( Math.floor( Math.abs( hour ) ), clength ) ); break; case "zzz": // Time zone offset with leading zero hour = value.getTimezoneOffset() / 60; ret.push( (hour <= 0 ? '+' : '-') + padZeros( Math.floor( Math.abs( hour ) ), 2 ) + // Hard coded ":" separator, rather than using cal.TimeSeparator // Repeated here for consistency, plus ":" was already assumed in date parsing. ":" + padZeros( Math.abs( value.getTimezoneOffset() % 60 ), 2 ) ); break; case "g": case "gg": if ( cal.eras ) { ret.push( cal.eras[ getEra(value, eras) ].name ); } break; case "/": ret.push( cal["/"] ); break; default: throw "Invalid date format pattern '" + current + "'."; break; } } return ret.join( '' ); } // EXPORTS jQuery.global = globalization; })();
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["it-IT"] = $.extend(true, {}, en, { name: "it-IT", englishName: "Italian (Italy)", nativeName: "italiano (Italia)", language: "it", numberFormat: { ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-$ n","$ n"], ',': ".", '.': ",", symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { firstDay: 1, days: { names: ["domenica","lunedì","martedì","mercoledì","giovedì","venerdì","sabato"], namesAbbr: ["dom","lun","mar","mer","gio","ven","sab"], namesShort: ["do","lu","ma","me","gi","ve","sa"] }, months: { names: ["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre",""], namesAbbr: ["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic",""] }, AM: null, PM: null, eras: [{"name":"d.C.","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", F: "dddd d MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["it-IT"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["he-IL"] = $.extend(true, {}, en, { name: "he-IL", englishName: "Hebrew (Israel)", nativeName: "עברית (ישראל)", language: "he", isRTL: true, numberFormat: { percent: { pattern: ["-n%","n%"] }, currency: { pattern: ["$-n","$ n"], symbol: "₪" } }, calendars: { standard: $.extend(true, {}, standard, { days: { names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"], namesAbbr: ["יום א","יום ב","יום ג","יום ד","יום ה","יום ו","שבת"], namesShort: ["א","ב","ג","ד","ה","ו","ש"] }, months: { names: ["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר",""], namesAbbr: ["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ",""] }, eras: [{"name":"לספירה","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd dd MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd dd MMMM yyyy HH:mm", F: "dddd dd MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }), Hebrew: $.extend(true, {}, standard, { name: "Hebrew", '/': " ", days: { names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"], namesAbbr: ["א","ב","ג","ד","ה","ו","ש"], namesShort: ["א","ב","ג","ד","ה","ו","ש"] }, months: { names: ["תשרי","חשון","כסלו","טבת","שבט","אדר","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"], namesAbbr: ["תשרי","חשון","כסלו","טבת","שבט","אדר","אדר ב","ניסן","אייר","סיון","תמוז","אב","אלול"] }, eras: [{"name":"C.E.","start":null,"offset":0}], twoDigitYearMax: 5790, patterns: { d: "dd MMMM yyyy", D: "dddd dd MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd dd MMMM yyyy HH:mm", F: "dddd dd MMMM yyyy HH:mm:ss", M: "dd MMMM", Y: "MMMM yyyy" } }) } }, cultures["he-IL"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["sa-IN"] = $.extend(true, {}, en, { name: "sa-IN", englishName: "Sanskrit (India)", nativeName: "संस्कृत (भारतम्)", language: "sa", numberFormat: { groupSizes: [3,2], percent: { groupSizes: [3,2] }, currency: { pattern: ["$ -n","$ n"], groupSizes: [3,2], symbol: "रु" } }, calendars: { standard: $.extend(true, {}, standard, { '/': "-", days: { names: ["रविवासरः","सोमवासरः","मङ्गलवासरः","बुधवासरः","गुरुवासरः","शुक्रवासरः","शनिवासरः"], namesAbbr: ["रविवासरः","सोमवासरः","मङ्गलवासरः","बुधवासरः","गुरुवासरः","शुक्रवासरः","शनिवासरः"], namesShort: ["र","स","म","ब","ग","श","श"] }, months: { names: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""], namesAbbr: ["जनवरी","फरवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्तूबर","नवम्बर","दिसम्बर",""] }, AM: ["पूर्वाह्न","पूर्वाह्न","पूर्वाह्न"], PM: ["अपराह्न","अपराह्न","अपराह्न"], patterns: { d: "dd-MM-yyyy", D: "dd MMMM yyyy dddd", t: "HH:mm", T: "HH:mm:ss", f: "dd MMMM yyyy dddd HH:mm", F: "dd MMMM yyyy dddd HH:mm:ss", M: "dd MMMM" } }) } }, cultures["sa-IN"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["hr"] = $.extend(true, {}, en, { name: "hr", englishName: "Croatian", nativeName: "hrvatski", language: "hr", numberFormat: { pattern: ["- n"], ',': ".", '.': ",", percent: { pattern: ["-n%","n%"], ',': ".", '.': "," }, currency: { pattern: ["-n $","n $"], ',': ".", '.': ",", symbol: "kn" } }, calendars: { standard: $.extend(true, {}, standard, { '/': ".", firstDay: 1, days: { names: ["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"], namesAbbr: ["ned","pon","uto","sri","čet","pet","sub"], namesShort: ["ne","po","ut","sr","če","pe","su"] }, months: { names: ["siječanj","veljača","ožujak","travanj","svibanj","lipanj","srpanj","kolovoz","rujan","listopad","studeni","prosinac",""], namesAbbr: ["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro",""] }, monthsGenitive: { names: ["siječnja","veljače","ožujka","travnja","svibnja","lipnja","srpnja","kolovoza","rujna","listopada","studenog","prosinca",""], namesAbbr: ["sij","vlj","ožu","tra","svi","lip","srp","kol","ruj","lis","stu","pro",""] }, AM: null, PM: null, patterns: { d: "d.M.yyyy.", D: "d. MMMM yyyy.", t: "H:mm", T: "H:mm:ss", f: "d. MMMM yyyy. H:mm", F: "d. MMMM yyyy. H:mm:ss", M: "d. MMMM" } }) } }, cultures["hr"]); culture.calendar = culture.calendars.standard; })(jQuery);
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.fullscreen = { init: function() { this.fullscreen = false; this.addBtn('fullscreen', 'Fullscreen', function(obj) { obj.toggleFullscreen(); }); this.setBtnRight('fullscreen'); }, toggleFullscreen: function() { var html; if (this.fullscreen === false) { this.changeBtnIcon('fullscreen', 'normalscreen'); this.setBtnActive('fullscreen'); this.fullscreen = true; this.fsheight = this.$editor.height(); this.tmpspan = $('<span></span>'); this.$box.addClass('redactor_box_fullscreen').after(this.tmpspan); $('body, html').css('overflow', 'hidden'); $('body').prepend(this.$box); this.fullScreenResize(); $(window).resize($.proxy(this.fullScreenResize, this)); $(document).scrollTop(0,0); this.$editor.focus(); } else { this.removeBtnIcon('fullscreen', 'normalscreen'); this.setBtnInactive('fullscreen'); this.fullscreen = false; $(window).unbind('resize', $.proxy(this.fullScreenResize, this)); $('body, html').css('overflow', ''); this.$box.removeClass('redactor_box_fullscreen').css({ width: 'auto', height: 'auto' }); this.tmpspan.after(this.$box).remove(); this.syncCode(); if (this.opts.autoresize) { this.$el.css('height', 'auto'); this.$editor.css('height', 'auto') } else { this.$el.css('height', this.fsheight); this.$editor.css('height', this.fsheight) } this.$editor.focus(); } }, fullScreenResize: function() { if (this.fullscreen === false) { return false; } var pad = this.$editor.css('padding-top').replace('px', ''); var height = $(window).height() - 34; this.$box.width($(window).width() - 2).height(height+34); this.$editor.height(height-(pad*2)); this.$el.height(height); }, }
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.advanced = { init: function() { var Redactor=this; this.addBtnBefore('video', 'plugin_img', 'Insert Image', function(obj) { Redactor.saveSelection(); if($("#redactor_advanced_img").length==0){ $('body').append( '<div id="redactor_advanced_img">\ <div class="grid_9">\ <div class="pr20">\ <table class="w100pc">\ <tr>\ <td>Image Url</td>\ <td class="pr"><form name="frmredactor_advanced_img">\ <div class="pr">\ <input type="text" id="redactor_advanced_img_src" class="classic-input w100pc mb8" />\ <div class="pa hover50 icon16 chooseimage chooseimage_icon"\ onclick="redactorBrowse()"\ title="Choose image from my host"\ ></div>\ </div>\ </form>\ </td>\ </tr>\ <tr>\ <td>Width</td>\ <td><input type="number" id="redactor_advanced_img_w" class="classic-input w100pc mb8" /></td>\ </tr>\ <tr>\ <td>Height</td>\ <td><input type="number" id="redactor_advanced_img_h" class="classic-input w100pc mb8" /></td>\ </tr>\ <tr>\ <td>&nbsp;</td>\ <td><input type="checkbox" checked=1 id="redactor_advanced_img_c"/><label for="">Classic Image</label></td>\ </tr>\ </table>\ </div>\ </div>\ </div>'); } $("#redactor_advanced_img_src").val(""); $("#redactor_advanced_img_w").val(""); $("#redactor_advanced_img_w").val(""); ShowConfirmDialogMessage($("#redactor_advanced_img"), "Insert Image ",function(){ try{ var src=$("#redactor_advanced_img_src").val(),str=""; var w=parseInt($("#redactor_advanced_img_w").val()); var h=parseInt($("#redactor_advanced_img_h").val()); if (w>0){ if(w>500) w=500; str+= ' width:'+w+'px;'; } if (h>0){ if(h>500) h=500; str+= ' height:'+h+'px;'; } if ($('#redactor_advanced_img_c').is(':checked')) { str+= ' margin:0 auto;display:block;border:1px solid #ccc;padding:4px;background:#fff'; } Redactor.restoreSelection(); if(src!=""){ obj.insertHtml('<img src="'+src+'" style="max-with:500px;'+str+'"/>'); CloseConfirmDialogMessage($("#redactor_advanced_img")); } }catch(e){} }); $("#redactor_advanced_img_src").focus(); }); //this.addBtnSeparatorBefore('advanced'); }, insertClip: function(html) { this.restoreSelection(); this.execCommand('inserthtml', html); this.modalClose(); } } function redactorBrowse(){ BrowseServer('redactor_advanced_img_src' ); }
JavaScript
if (typeof RedactorPlugins === 'undefined') var RedactorPlugins = {}; RedactorPlugins.advanced = { init: function() { this.addBtnAfter('link', 'advanced', 'Advanced', function(obj) { obj.insertHtml('<b>It\'s awesome!</b> '); }); this.addBtnSeparatorBefore('advanced'); } }
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget 1.14pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery 1.4.2+ * - jQuery UI 1.8 widget factory * * Optional: * - jQuery UI effects * - jQuery UI position utility * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($, undefined) { var multiselectID = 0; var $doc = $(document); $.widget("ech.multiselect", { // default options options: { header: true, height: 175, minWidth: 225, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: 'Select options', selectedText: '# selected', selectedList: 0, show: null, hide: null, autoOpen: false, multiple: true, position: {} }, _create: function() { var el = this.element.hide(); var o = this.options; this.speed = $.fx.speeds._default; // default speed for effects this._isOpen = false; // assume no // create a unique namespace for events that the widget // factory cannot unbind automatically. Use eventNamespace if on // jQuery UI 1.9+, and otherwise fallback to a custom string. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID); var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>')) .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all') .addClass(o.classes) .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') }) .insertAfter(el), buttonlabel = (this.buttonlabel = $('<span />')) .html(o.noneSelectedText) .appendTo(button), menu = (this.menu = $('<div />')) .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all') .addClass(o.classes) .appendTo(document.body), header = (this.header = $('<div />')) .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix') .appendTo(menu), headerLinkContainer = (this.headerLinkContainer = $('<ul />')) .addClass('ui-helper-reset') .html(function() { if(o.header === true) { return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>'; } else if(typeof o.header === "string") { return '<li>' + o.header + '</li>'; } else { return ''; } }) .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>') .appendTo(header), checkboxContainer = (this.checkboxContainer = $('<ul />')) .addClass('ui-multiselect-checkboxes ui-helper-reset') .appendTo(menu); // perform event bindings this._bindEvents(); // build menu this.refresh(true); // some addl. logic for single selects if(!o.multiple) { menu.addClass('ui-multiselect-single'); } // bump unique ID multiselectID++; }, _init: function() { if(this.options.header === false) { this.header.hide(); } if(!this.options.multiple) { this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide(); } if(this.options.autoOpen) { this.open(); } if(this.element.is(':disabled')) { this.disable(); } }, refresh: function(init) { var el = this.element; var o = this.options; var menu = this.menu; var checkboxContainer = this.checkboxContainer; var optgroups = []; var html = ""; var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags // build items el.find('option').each(function(i) { var $this = $(this); var parent = this.parentNode; var title = this.innerHTML; var description = this.title; var value = this.value; var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i); var isDisabled = this.disabled; var isSelected = this.selected; var labelClasses = [ 'ui-corner-all' ]; var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className; var optLabel; // is this an optgroup? if(parent.tagName === 'OPTGROUP') { optLabel = parent.getAttribute('label'); // has this optgroup been added already? if($.inArray(optLabel, optgroups) === -1) { html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>'; optgroups.push(optLabel); } } if(isDisabled) { labelClasses.push('ui-state-disabled'); } // browsers automatically select the first option // by default with single selects if(isSelected && !o.multiple) { labelClasses.push('ui-state-active'); } html += '<li class="' + liClasses + '">'; // create the label html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">'; html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"'; // pre-selected? if(isSelected) { html += ' checked="checked"'; html += ' aria-selected="true"'; } // disabled? if(isDisabled) { html += ' disabled="disabled"'; html += ' aria-disabled="true"'; } // add the title and close everything off html += ' /><span>' + title + '</span></label></li>'; }); // insert into the DOM checkboxContainer.html(html); // cache some moar useful elements this.labels = menu.find('label'); this.inputs = this.labels.children('input'); // set widths this._setButtonWidth(); this._setMenuWidth(); // remember default value this.button[0].defaultValue = this.update(); // broadcast refresh event; useful for widgets if(!init) { this._trigger('refresh'); } }, // updates the button text. call refresh() to rebuild update: function() { var o = this.options; var $inputs = this.inputs; var $checked = $inputs.filter(':checked'); var numChecked = $checked.length; var value; if(numChecked === 0) { value = o.noneSelectedText; } else { if($.isFunction(o.selectedText)) { value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get()); } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) { value = $checked.map(function() { return $(this).next().html(); }).get().join(', '); } else { value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length); } } this._setButtonValue(value); return value; }, // this exists as a separate method so that the developer // can easily override it. _setButtonValue: function(value) { this.buttonlabel.text(value); }, // binds events _bindEvents: function() { var self = this; var button = this.button; function clickHandler() { self[ self._isOpen ? 'close' : 'open' ](); return false; } // webkit doesn't like it when you click on the span :( button .find('span') .bind('click.multiselect', clickHandler); // button events button.bind({ click: clickHandler, keypress: function(e) { switch(e.which) { case 27: // esc case 38: // up case 37: // left self.close(); break; case 39: // right case 40: // down self.open(); break; } }, mouseenter: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, mouseleave: function() { $(this).removeClass('ui-state-hover'); }, focus: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-focus'); } }, blur: function() { $(this).removeClass('ui-state-focus'); } }); // header links this.header.delegate('a', 'click.multiselect', function(e) { // close link if($(this).hasClass('ui-multiselect-close')) { self.close(); // check all / uncheck all } else { self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll'](); } e.preventDefault(); }); // optgroup label toggle support this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) { e.preventDefault(); var $this = $(this); var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'); var nodes = $inputs.get(); var label = $this.parent().text(); // trigger event and bail if the return is false if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) { return; } // toggle inputs self._toggleChecked( $inputs.filter(':checked').length !== $inputs.length, $inputs ); self._trigger('optgrouptoggle', e, { inputs: nodes, label: label, checked: nodes[0].checked }); }) .delegate('label', 'mouseenter.multiselect', function() { if(!$(this).hasClass('ui-state-disabled')) { self.labels.removeClass('ui-state-hover'); $(this).addClass('ui-state-hover').find('input').focus(); } }) .delegate('label', 'keydown.multiselect', function(e) { e.preventDefault(); switch(e.which) { case 9: // tab case 27: // esc self.close(); break; case 38: // up case 40: // down case 37: // left case 39: // right self._traverse(e.which, this); break; case 13: // enter $(this).find('input')[0].click(); break; } }) .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) { var $this = $(this); var val = this.value; var checked = this.checked; var tags = self.element.find('option'); // bail if this input is disabled or the event is cancelled if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) { e.preventDefault(); return; } // make sure the input has focus. otherwise, the esc key // won't close the menu after clicking an item. $this.focus(); // toggle aria state $this.attr('aria-selected', checked); // change state on the original option tags tags.each(function() { if(this.value === val) { this.selected = checked; } else if(!self.options.multiple) { this.selected = false; } }); // some additional single select-specific logic if(!self.options.multiple) { self.labels.removeClass('ui-state-active'); $this.closest('label').toggleClass('ui-state-active', checked); // close menu self.close(); } // fire change on the select box self.element.trigger("change"); // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827 // http://bugs.jquery.com/ticket/3827 setTimeout($.proxy(self.update, self), 10); }); // close each widget when clicking on any other element/anywhere else on the page $doc.bind('mousedown.' + this._namespaceID, function(event) { var target = event.target; if(self._isOpen && !$.contains(self.menu[0], target) && !$.contains(self.button[0], target) && target !== self.button[0] && target !== self.menu[0]) { self.close(); } }); // deal with form resets. the problem here is that buttons aren't // restored to their defaultValue prop on form reset, and the reset // handler fires before the form is actually reset. delaying it a bit // gives the form inputs time to clear. $(this.element[0].form).bind('reset.multiselect', function() { setTimeout($.proxy(self.refresh, self), 10); }); }, // set button width _setButtonWidth: function() { var width = this.element.outerWidth(); var o = this.options; if(/\d/.test(o.minWidth) && width < o.minWidth) { width = o.minWidth; } // set widths this.button.outerWidth(width); }, // set menu width _setMenuWidth: function() { var m = this.menu; m.outerWidth(this.button.outerWidth()); }, // move up or down within the menu _traverse: function(which, start) { var $start = $(start); var moveToLast = which === 38 || which === 37; // select the first li that isn't an optgroup label / disabled $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first'](); // if at the first/last element if(!$next.length) { var $container = this.menu.find('ul').last(); // move to the first/last this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover'); // set scroll position $container.scrollTop(moveToLast ? $container.height() : 0); } else { $next.find('label').trigger('mouseover'); } }, // This is an internal function to toggle the checked property and // other related attributes of a checkbox. // // The context of this function should be a checkbox; do not proxy it. _toggleState: function(prop, flag) { return function() { if(!this.disabled) { this[ prop ] = flag; } if(flag) { this.setAttribute('aria-selected', true); } else { this.removeAttribute('aria-selected'); } }; }, _toggleChecked: function(flag, group) { var $inputs = (group && group.length) ? group : this.inputs; var self = this; // toggle state on inputs $inputs.each(this._toggleState('checked', flag)); // give the first input focus $inputs.eq(0).focus(); // update button text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // toggle state on original option tags this.element .find('option') .each(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger("change"); } }, _toggleDisabled: function(flag) { this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); var inputs = this.menu.find('input'); var key = "ech-multiselect-disabled"; if(flag) { // remember which elements this widget disabled (not pre-disabled) // elements, so that they can be restored if the widget is re-enabled. inputs = inputs.filter(':enabled').data(key, true) } else { inputs = inputs.filter(function() { return $.data(this, key) === true; }).removeData(key); } inputs .attr({ 'disabled':flag, 'arial-disabled':flag }) .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); this.element.attr({ 'disabled':flag, 'aria-disabled':flag }); }, // open the menu open: function(e) { var self = this; var button = this.button; var menu = this.menu; var speed = this.speed; var o = this.options; var args = []; // bail if the multiselectopen event returns false, this widget is disabled, or is already open if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) { return; } var $container = menu.find('ul').last(); var effect = o.show; // figure out opening effects/speeds if($.isArray(o.show)) { effect = o.show[0]; speed = o.show[1] || self.speed; } // if there's an effect, assume jQuery UI is in use // build the arguments to pass to show() if(effect) { args = [ effect, speed ]; } // set the scroll of the checkbox container $container.scrollTop(0).height(o.height); // positon this.position(); // show the menu, maybe with a speed/effect combo $.fn.show.apply(menu, args); // select the first not disabled option // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus'); button.addClass('ui-state-active'); this._isOpen = true; this._trigger('open'); }, // close the menu close: function() { if(this._trigger('beforeclose') === false) { return; } var o = this.options; var effect = o.hide; var speed = this.speed; var args = []; // figure out opening effects/speeds if($.isArray(o.hide)) { effect = o.hide[0]; speed = o.hide[1] || this.speed; } if(effect) { args = [ effect, speed ]; } $.fn.hide.apply(this.menu, args); this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave'); this._isOpen = false; this._trigger('close'); }, enable: function() { this._toggleDisabled(false); }, disable: function() { this._toggleDisabled(true); }, checkAll: function(e) { this._toggleChecked(true); this._trigger('checkAll'); }, uncheckAll: function() { this._toggleChecked(false); this._trigger('uncheckAll'); }, getChecked: function() { return this.menu.find('input').filter(':checked'); }, destroy: function() { // remove classes + data $.Widget.prototype.destroy.call(this); // unbind events $doc.unbind(this._namespaceID); this.button.remove(); this.menu.remove(); this.element.show(); return this; }, isOpen: function() { return this._isOpen; }, widget: function() { return this.menu; }, getButton: function() { return this.button; }, position: function() { var o = this.options; // use the position utility if it exists and options are specifified if($.ui.position && !$.isEmptyObject(o.position)) { o.position.of = o.position.of || this.button; this.menu .show() .position(o.position) .hide(); // otherwise fallback to custom positioning } else { var pos = this.button.offset(); this.menu.css({ top: pos.top + this.button.outerHeight(), left: pos.left }); } }, // react to option changes after initialization _setOption: function(key, value) { var menu = this.menu; switch(key) { case 'header': menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide'](); break; case 'checkAllText': menu.find('a.ui-multiselect-all span').eq(-1).text(value); break; case 'uncheckAllText': menu.find('a.ui-multiselect-none span').eq(-1).text(value); break; case 'height': menu.find('ul').last().height(parseInt(value, 10)); break; case 'minWidth': this.options[key] = parseInt(value, 10); this._setButtonWidth(); this._setMenuWidth(); break; case 'selectedText': case 'selectedList': case 'noneSelectedText': this.options[key] = value; // these all needs to update immediately for the update() call this.update(); break; case 'classes': menu.add(this.button).removeClass(this.options.classes).addClass(value); break; case 'multiple': menu.toggleClass('ui-multiselect-single', !value); this.options.multiple = value; this.element[0].multiple = value; this.refresh(); break; case 'position': this.position(); } $.Widget.prototype._setOption.apply(this, arguments); } }); })(jQuery);
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget Filtering Plugin 1.5pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery UI MultiSelect widget * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($) { var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g; $.widget('ech.multiselectfilter', { options: { label: 'Filter:', width: null, /* override default width set in css file (px). null will inherit */ placeholder: 'Enter keywords', autoReset: false }, _create: function() { var opts = this.options; var elem = $(this.element); // get the multiselect instance var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect"))); // store header; add filter class so the close/check all/uncheck all links can be positioned correctly var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter')); // wrapper elem var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header)); // reference to the actual inputs this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]'); // build the input box this.input = wrapper.find('input').bind({ keydown: function(e) { // prevent the enter key from submitting the form / closing the widget if(e.which === 13) { e.preventDefault(); } }, keyup: $.proxy(this._handler, this), click: $.proxy(this._handler, this) }); // cache input values for searching this.updateCache(); // rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired, // only the currently filtered elements are checked instance._toggleChecked = function(flag, group) { var $inputs = (group && group.length) ? group : this.labels.find('input'); var _self = this; // do not include hidden elems if the menu isn't open. var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled'; $inputs = $inputs .not(selector) .each(this._toggleState('checked', flag)); // update text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // select option tags this.element.find('option').filter(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { _self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger('change'); } }; // rebuild cache when multiselect is updated var doc = $(document).bind('multiselectrefresh', $.proxy(function() { this.updateCache(); this._handler(); }, this)); // automatically reset the widget on close? if(this.options.autoReset) { doc.bind('multiselectclose', $.proxy(this._reset, this)); } }, // thx for the logic here ben alman _handler: function(e) { var term = $.trim(this.input[0].value.toLowerCase()), // speed up lookups rows = this.rows, inputs = this.inputs, cache = this.cache; if(!term) { rows.show(); } else { rows.hide(); var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi'); this._trigger("filter", e, $.map(cache, function(v, i) { if(v.search(regex) !== -1) { rows.eq(i).show(); return inputs.get(i); } return null; })); } // show/hide optgroups this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() { var $this = $(this); var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() { return $.css(this, "display") !== 'none'; }).length; $this[isVisible ? 'show' : 'hide'](); }); }, _reset: function() { this.input.val('').trigger('keyup'); }, updateCache: function() { // each list item this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)"); // cache this.cache = this.element.children().map(function() { var elem = $(this); // account for optgroups if(this.tagName.toLowerCase() === "optgroup") { elem = elem.children(); } return elem.map(function() { return this.innerHTML.toLowerCase(); }).get(); }).get(); }, widget: function() { return this.wrapper; }, destroy: function() { $.Widget.prototype.destroy.call(this); this.input.val('').trigger("keyup"); this.wrapper.remove(); } }); })(jQuery);
JavaScript
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * <p> * * For a fairly comprehensive set of languages see the * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a> * file that came with this source. At a minimum, the lexer should work on a * number of languages including C and friends, Java, Python, Bash, SQL, HTML, * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk * and a subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. * <p> * Usage: <ol> * <li> include this source file in an html page via * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>} * <li> define style rules. See the example page for examples. * <li> mark the {@code <pre>} and {@code <code>} tags in your source with * {@code class=prettyprint.} * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty * printer needs to do more substantial DOM manipulations to support that, so * some css styles may not be preserved. * </ol> * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in, but if you wish, you can add * another class to the {@code <pre>} or {@code <code>} element to specify the * language, as in {@code <pre class="prettyprint lang-java">}. Any class that * starts with "lang-" followed by a file extension, specifies the file type. * See the "lang-*.js" files in this directory for code that implements * per-language file handlers. * <p> * Change log:<br> * cbeust, 2006/08/22 * <blockquote> * Java annotations (start with "@") are now captured as literals ("lit") * </blockquote> * @requires console * @overrides window */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ window['PR_SHOULD_USE_CONTINUATION'] = true; /** the number of characters between tab columns */ window['PR_TAB_WIDTH'] = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ window['PR_normalizedHtml'] /** Contains functions for creating and registering new language handlers. * @type {Object} */ = window['PR'] /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ = window['prettyPrintOne'] /** Find all the {@code <pre>} and {@code <code>} tags in the DOM with * {@code class=prettyprint} and prettify them. * @param {Function?} opt_whenDone if specified, called when the last entry * has been finished. */ = window['prettyPrint'] = void 0; /** browser detection. @extern @returns false if not IE, otherwise the major version. */ window['_pr_isIE6'] = function () { var ieVersion = navigator && navigator.userAgent && navigator.userAgent.match(/\bMSIE ([678])\./); ieVersion = ieVersion ? +ieVersion[1] : false; window['_pr_isIE6'] = function () { return ieVersion; }; return ieVersion; }; (function () { // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try typeof "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "abstract boolean byte extends final finally implements import " + "instanceof null native package strictfp super synchronized throws " + "transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params partial readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * * <p>The link a above does not accurately describe EcmaScript rules since * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works * very well in practice. * * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:^^|[+-]'; for (var i = 0; i < preceders.length; ++i) { pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1'); } pattern += ')\\s*'; // matches at end, and matches empty string return pattern; // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_nbspEnt, ' ') .replace(pr_ampEnt, '&'); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } var newlineRe = /[\r\n]/g; /** * Are newlines and adjacent spaces significant in the given node's innerHTML? */ function isPreformatted(node, content) { // PRE means preformatted, and is a very common case, so don't create // unnecessary computed style objects. if ('PRE' === node.tagName) { return true; } if (!newlineRe.test(content)) { return true; } // Don't care var whitespace = ''; // For disconnected nodes, IE has no currentStyle. if (node.currentStyle) { whitespace = node.currentStyle.whiteSpace; } else if (window.getComputedStyle) { // Firefox makes a best guess if node is disconnected whereas Safari // returns the empty string. whitespace = window.getComputedStyle(node, null).whiteSpace; } return !whitespace || whitespace === 'pre'; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } /** * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally * matches the union o the sets o strings matched d by the input RegExp. * Since it matches globally, if the input strings have a start-of-input * anchor (/^.../), it is ignored for the purposes of unioning. * @param {Array.<RegExp>} regexs non multiline, non-global regexs. * @return {RegExp} a global regex. */ function combinePrefixPatterns(regexs) { var capturedGroupIndex = 0; var needToFoldCase = false; var ignoreCase = false; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.ignoreCase) { ignoreCase = true; } else if (/[a-z]/i.test(regex.source.replace( /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) { needToFoldCase = true; ignoreCase = false; break; } } function decodeEscape(charsetPart) { if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); } switch (charsetPart.charAt(1)) { case 'b': return 8; case 't': return 9; case 'n': return 0xa; case 'v': return 0xb; case 'f': return 0xc; case 'r': return 0xd; case 'u': case 'x': return parseInt(charsetPart.substring(2), 16) || charsetPart.charCodeAt(1); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': return parseInt(charsetPart.substring(1), 8); default: return charsetPart.charCodeAt(1); } } function encodeEscape(charCode) { if (charCode < 0x20) { return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16); } var ch = String.fromCharCode(charCode); if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') { ch = '\\' + ch; } return ch; } function caseFoldCharset(charSet) { var charsetParts = charSet.substring(1, charSet.length - 1).match( new RegExp( '\\\\u[0-9A-Fa-f]{4}' + '|\\\\x[0-9A-Fa-f]{2}' + '|\\\\[0-3][0-7]{0,2}' + '|\\\\[0-7]{1,2}' + '|\\\\[\\s\\S]' + '|-' + '|[^-\\\\]', 'g')); var groups = []; var ranges = []; var inverse = charsetParts[0] === '^'; for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) { var p = charsetParts[i]; switch (p) { case '\\B': case '\\b': case '\\D': case '\\d': case '\\S': case '\\s': case '\\W': case '\\w': groups.push(p); continue; } var start = decodeEscape(p); var end; if (i + 2 < n && '-' === charsetParts[i + 1]) { end = decodeEscape(charsetParts[i + 2]); i += 2; } else { end = start; } ranges.push([start, end]); // If the range might intersect letters, then expand it. if (!(end < 65 || start > 122)) { if (!(end < 65 || start > 90)) { ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]); } if (!(end < 97 || start > 122)) { ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]); } } } // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]] // -> [[1, 12], [14, 14], [16, 17]] ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); }); var consolidatedRanges = []; var lastRange = [NaN, NaN]; for (var i = 0; i < ranges.length; ++i) { var range = ranges[i]; if (range[0] <= lastRange[1] + 1) { lastRange[1] = Math.max(lastRange[1], range[1]); } else { consolidatedRanges.push(lastRange = range); } } var out = ['[']; if (inverse) { out.push('^'); } out.push.apply(out, groups); for (var i = 0; i < consolidatedRanges.length; ++i) { var range = consolidatedRanges[i]; out.push(encodeEscape(range[0])); if (range[1] > range[0]) { if (range[1] + 1 > range[0]) { out.push('-'); } out.push(encodeEscape(range[1])); } } out.push(']'); return out.join(''); } function allowAnywhereFoldCaseAndRenumberGroups(regex) { // Split into character sets, escape sequences, punctuation strings // like ('(', '(?:', ')', '^'), and runs of characters that do not // include any of the above. var parts = regex.source.match( new RegExp( '(?:' + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape + '|\\\\[0-9]+' // a back-reference or octal escape + '|\\\\[^ux0-9]' // other escape sequence + '|\\(\\?[:!=]' // start of a non-capturing group + '|[\\(\\)\\^]' // start/emd of a group, or line start + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters + ')', 'g')); var n = parts.length; // Maps captured group numbers to the number they will occupy in // the output or to -1 if that has not been determined, or to // undefined if they need not be capturing in the output. var capturedGroups = []; // Walk over and identify back references to build the capturedGroups // mapping. for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { // groups are 1-indexed, so max group index is count of '(' ++groupIndex; } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { capturedGroups[decimalValue] = -1; } } } // Renumber groups and reduce capturing groups to non-capturing groups // where possible. for (var i = 1; i < capturedGroups.length; ++i) { if (-1 === capturedGroups[i]) { capturedGroups[i] = ++capturedGroupIndex; } } for (var i = 0, groupIndex = 0; i < n; ++i) { var p = parts[i]; if (p === '(') { ++groupIndex; if (capturedGroups[groupIndex] === undefined) { parts[i] = '(?:'; } } else if ('\\' === p.charAt(0)) { var decimalValue = +p.substring(1); if (decimalValue && decimalValue <= groupIndex) { parts[i] = '\\' + capturedGroups[groupIndex]; } } } // Remove any prefix anchors so that the output will match anywhere. // ^^ really does mean an anchored match though. for (var i = 0, groupIndex = 0; i < n; ++i) { if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; } } // Expand letters to groupts to handle mixing of case-sensitive and // case-insensitive patterns if necessary. if (regex.ignoreCase && needToFoldCase) { for (var i = 0; i < n; ++i) { var p = parts[i]; var ch0 = p.charAt(0); if (p.length >= 2 && ch0 === '[') { parts[i] = caseFoldCharset(p); } else if (ch0 !== '\\') { // TODO: handle letters in numeric escapes. parts[i] = p.replace( /[a-zA-Z]/g, function (ch) { var cc = ch.charCodeAt(0); return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']'; }); } } } return parts.join(''); } var rewritten = []; for (var i = 0, n = regexs.length; i < n; ++i) { var regex = regexs[i]; if (regex.global || regex.multiline) { throw new Error('' + regex); } rewritten.push( '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')'); } return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g'); } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } else if (!isPreformatted(node, content)) { content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1') .replace(/(?:[\r\n]+[ \t]*)+/g, ' '); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } var pr_chunkPattern = new RegExp( '[^<]+' // A run of characters other than '<' + '|<\!--[\\s\\S]*?--\>' // an HTML comment + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>' // a CDATA section // a probable tag that should not be highlighted + '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>' + '|<', // A '<' that does not begin a larger chunk 'g'); var pr_commentPrefix = /^<\!--/; var pr_cdataPrefix = /^<!\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; var j; end_tag_loop: for (j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** * Apply the given language handler to sourceCode and add the resulting * decorations to out. * @param {number} basePos the index of sourceCode within the chunk of source * whose decorations are already present on out. */ function appendDecorations(basePos, sourceCode, langHandler, out) { if (!sourceCode) { return; } var job = { source: sourceCode, basePos: basePos }; langHandler(job); out.push.apply(out, job.decorations); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, DEPRECATED, shortcut : string]. * * Style is a style constant like PR_PLAIN, or can be a string of the * form 'lang-FOO', where FOO is a language extension describing the * language of the portion of the token in $1 after pattern executes. * E.g., if style is 'lang-lisp', and group 1 contains the text * '(hello (world))', then that portion of the token will be passed to the * registered lisp handler for formatting. * The text before and after group 1 will be restyled using this decorator * so decorators should take care that this doesn't result in infinite * recursion. For example, the HTML lexer rule for SCRIPT elements looks * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match * '<script>foo()<\/script>', which would cause the current decorator to * be called with '<script>' which would not match the same rule since * group 1 must not be empty, so it would be instead styled as PR_TAG by * the generic tag rule. The handler registered for the 'js' extension would * then be called with 'foo()', and finally, the current decorator would * be called with '<\/script>' which would not match the original rule and * so the generic tag rule would identify it as a tag. * * Pattern must only match prefixes, and if it matches a prefix, then that * match is considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (Object)} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; var tokenizer; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); var allRegexs = []; var regexKeys = {}; for (var i = 0, n = allPatterns.length; i < n; ++i) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } var regex = patternParts[1]; var k = '' + regex; if (!regexKeys.hasOwnProperty(k)) { allRegexs.push(regex); regexKeys[k] = null; } } allRegexs.push(/[\0-\uffff]/); tokenizer = combinePrefixPatterns(allRegexs); })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; /** * Lexes job.source and produces an output array job.decorations of style * classes preceded by the position at which they start in job.source in * order. * * @param {Object} job an object like {@code * source: {string} sourceText plain text, * basePos: {int} position of job.source in the larger chunk of * sourceCode. * } */ var decorate = function (job) { var sourceCode = job.source, basePos = job.basePos; /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = [basePos, PR_PLAIN]; var pos = 0; // index into sourceCode var tokens = sourceCode.match(tokenizer) || []; var styleCache = {}; for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) { var token = tokens[ti]; var style = styleCache[token]; var match = void 0; var isEmbedded; if (typeof style === 'string') { isEmbedded = false; } else { var patternParts = shortcuts[token.charAt(0)]; if (patternParts) { match = token.match(patternParts[1]); style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; match = token.match(patternParts[1]); if (match) { style = patternParts[0]; break; } } if (!match) { // make sure that we make progress style = PR_PLAIN; } } isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5); if (isEmbedded && !(match && typeof match[1] === 'string')) { isEmbedded = false; style = PR_SOURCE; } if (!isEmbedded) { styleCache[token] = style; } } var tokenStart = pos; pos += token.length; if (!isEmbedded) { decorations.push(basePos + tokenStart, style); } else { // Treat group 1 as an embedded block of source code. var embeddedSource = match[1]; var embeddedSourceStart = token.indexOf(embeddedSource); var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length; if (match[2]) { // If embeddedSource can be blank, then it would match at the // beginning which would cause us to infinitely recurse on the // entire token, so we catch the right context in match[2]. embeddedSourceEnd = token.length - match[2].length; embeddedSourceStart = embeddedSourceEnd - embeddedSource.length; } var lang = style.substring(5); // Decorate the left of the embedded source appendDecorations( basePos + tokenStart, token.substring(0, embeddedSourceStart), decorate, decorations); // Decorate the embedded source appendDecorations( basePos + tokenStart + embeddedSourceStart, embeddedSource, langHandlerForExtension(lang, embeddedSource), decorations); // Decorate the right of the embedded section appendDecorations( basePos + tokenStart + embeddedSourceEnd, token.substring(embeddedSourceEnd), decorate, decorations); } } job.decorations = decorations; }; return decorate; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (Object)} a function that examines the source code * in the input job and builds the decoration list. */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options['tripleQuotedStrings']) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options['multiLineStrings']) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } if (options['verbatimStrings']) { // verbatim-string-literal production from the C# grammar. See issue 93. fallthroughStylePatterns.push( [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); } if (options['hashComments']) { if (options['cStyleComments']) { // Stop C preprocessor declarations at an unclosed open comment shortcutStylePatterns.push( [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#']); fallthroughStylePatterns.push( [PR_STRING, /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null]); } else { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } } if (options['cStyleComments']) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options['regexLiterals']) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '/'); fallthroughStylePatterns.push( ['lang-regex', new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')') ]); } var keywords = options['keywords'].replace(/^\s+|\s+$/g, ''); if (keywords.length) { fallthroughStylePatterns.push( [PR_KEYWORD, new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]); } shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']); fallthroughStylePatterns.push( // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null], [PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null], [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null], [PR_LITERAL, new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]); return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); } var decorateSource = sourceDecorator({ 'keywords': ALL_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'multiLineStrings': true, 'regexLiterals': true }); /** Breaks {@code job.source} around style boundaries in * {@code job.decorations} while re-interleaving {@code job.extractedTags}, * and leaves the result in {@code job.prettyPrintedHtml}. * @param {Object} job like { * source: {string} source as plain text, * extractedTags: {Array.<number|string>} extractedTags chunks of raw * html preceded by their position in {@code job.source} * in order * decorations: {Array.<number|string} an array of style classes preceded * by the position at which they start in job.source in order * } * @private */ function recombineTagsAndDecorations(job) { var sourceText = job.source; var extractedTags = job.extractedTags; var decorations = job.decorations; var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); // IE collapses multiple adjacient <br>s into 1 line break. // Prefix every <br> with '&nbsp;' can prevent such IE's behavior. var lineBreakHtml = window['_pr_isIE6']() ? '&nbsp;<br />' : '<br />'; html.push(htmlChunk.replace(newlineRe, lineBreakHtml)); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } job.prettyPrintedHtml = html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (Object)} handler a function from source code to a list * of decorations. Takes a single argument job which describes the * state of the computation. The single parameter has the form * {@code { * source: {string} as plain text. * decorations: {Array.<number|string>} an array of style classes * preceded by the position at which they start in * job.source in order. * The language handler should assigned this field. * basePos: {int} the position of source in the larger source chunk. * All positions in the output decorations array are relative * to the larger source chunk. * } } * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.warn('cannot override language handler %s', ext); } } } function langHandlerForExtension(extension, source) { if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. extension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } return langHandlerRegistry[extension]; } registerLangHandler(decorateSource, ['default-code']); registerLangHandler( createSimpleLexer( [], [ [PR_PLAIN, /^[^<?]+/], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/], [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], // Unescaped content in an unknown language ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/], ['lang-', /^<%([\s\S]+?)(?:%>|$)/], [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i], // Unescaped content in javascript. (Or possibly vbscript). ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i], // Contains unescaped stylesheet content ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i], ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] ]), ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']); registerLangHandler( createSimpleLexer( [ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'], [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\''] ], [ [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i], [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], [PR_PUNCTUATION, /^[=<>\/]+/], ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i], ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i], ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i], ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i], ['lang-css', /^style\s*=\s*\'([^\']+)\'/i], ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i] ]), ['in.tag']); registerLangHandler( createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']); registerLangHandler(sourceDecorator({ 'keywords': CPP_KEYWORDS, 'hashComments': true, 'cStyleComments': true }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']); registerLangHandler(sourceDecorator({ 'keywords': 'null true false' }), ['json']); registerLangHandler(sourceDecorator({ 'keywords': CSHARP_KEYWORDS, 'hashComments': true, 'cStyleComments': true, 'verbatimStrings': true }), ['cs']); registerLangHandler(sourceDecorator({ 'keywords': JAVA_KEYWORDS, 'cStyleComments': true }), ['java']); registerLangHandler(sourceDecorator({ 'keywords': SH_KEYWORDS, 'hashComments': true, 'multiLineStrings': true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ 'keywords': PYTHON_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'tripleQuotedStrings': true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ 'keywords': PERL_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ 'keywords': RUBY_KEYWORDS, 'hashComments': true, 'multiLineStrings': true, 'regexLiterals': true }), ['rb']); registerLangHandler(sourceDecorator({ 'keywords': JSCRIPT_KEYWORDS, 'cStyleComments': true, 'regexLiterals': true }), ['js']); registerLangHandler( createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']); function applyDecorator(job) { var sourceCodeHtml = job.sourceCodeHtml; var opt_langExtension = job.langExtension; // Prepopulate output in case processing fails with an exception. job.prettyPrintedHtml = sourceCodeHtml; try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; job.source = source; job.basePos = 0; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ job.extractedTags = sourceAndExtractedTags.tags; // Apply the appropriate language handler langHandlerForExtension(opt_langExtension, source)(job); // Integrate the decorations and tags back into the source code to produce // a decorated html string which is left in job.prettyPrintedHtml. recombineTagsAndDecorations(job); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } } } function prettyPrintOne(sourceCodeHtml, opt_langExtension) { var job = { sourceCodeHtml: sourceCodeHtml, langExtension: opt_langExtension }; applyDecorator(job); return job.prettyPrintedHtml; } function prettyPrint(opt_whenDone) { var isIE678 = window['_pr_isIE6'](); var ieNewline = isIE678 === 6 ? '\r\n' : '\r'; // See bug 71 and http://stackoverflow.com/questions/136443/why-doesnt-ie7- // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0, n = codeSegments[i].length; j < n; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var clock = Date; if (!clock['now']) { clock = { 'now': function () { return (new Date).getTime(); } }; } // The loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; var prettyPrintingJob; function doWork() { var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ? clock.now() + 250 /* ms */ : Infinity); for (; k < elements.length && clock.now() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing prettyPrintingJob = { sourceCodeHtml: content, langExtension: langExtension, sourceNode: cs }; applyDecorator(prettyPrintingJob); replaceWithPrettyPrintedHtml(); } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } function replaceWithPrettyPrintedHtml() { var newContent = prettyPrintingJob.prettyPrintedHtml; if (!newContent) { return; } var cs = prettyPrintingJob.sourceNode; // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE678 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode(ieNewline), lineBreak); } } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'combinePrefixPatterns': combinePrefixPatterns, 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget 1.14pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery 1.4.2+ * - jQuery UI 1.8 widget factory * * Optional: * - jQuery UI effects * - jQuery UI position utility * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($, undefined) { var multiselectID = 0; var $doc = $(document); $.widget("ech.multiselect", { // default options options: { header: true, height: 175, minWidth: 225, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: 'Select options', selectedText: '# selected', selectedList: 0, show: null, hide: null, autoOpen: false, multiple: true, position: {} }, _create: function() { var el = this.element.hide(); var o = this.options; this.speed = $.fx.speeds._default; // default speed for effects this._isOpen = false; // assume no // create a unique namespace for events that the widget // factory cannot unbind automatically. Use eventNamespace if on // jQuery UI 1.9+, and otherwise fallback to a custom string. this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID); var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>')) .addClass('ui-multiselect ui-widget ui-state-default ui-corner-all') .addClass(o.classes) .attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') }) .insertAfter(el), buttonlabel = (this.buttonlabel = $('<span />')) .html(o.noneSelectedText) .appendTo(button), menu = (this.menu = $('<div />')) .addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all') .addClass(o.classes) .appendTo(document.body), header = (this.header = $('<div />')) .addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix') .appendTo(menu), headerLinkContainer = (this.headerLinkContainer = $('<ul />')) .addClass('ui-helper-reset') .html(function() { if(o.header === true) { return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>'; } else if(typeof o.header === "string") { return '<li>' + o.header + '</li>'; } else { return ''; } }) .append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>') .appendTo(header), checkboxContainer = (this.checkboxContainer = $('<ul />')) .addClass('ui-multiselect-checkboxes ui-helper-reset') .appendTo(menu); // perform event bindings this._bindEvents(); // build menu this.refresh(true); // some addl. logic for single selects if(!o.multiple) { menu.addClass('ui-multiselect-single'); } // bump unique ID multiselectID++; }, _init: function() { if(this.options.header === false) { this.header.hide(); } if(!this.options.multiple) { this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide(); } if(this.options.autoOpen) { this.open(); } if(this.element.is(':disabled')) { this.disable(); } }, refresh: function(init) { var el = this.element; var o = this.options; var menu = this.menu; var checkboxContainer = this.checkboxContainer; var optgroups = []; var html = ""; var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags // build items el.find('option').each(function(i) { var $this = $(this); var parent = this.parentNode; var title = this.innerHTML; var description = this.title; var value = this.value; var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i); var isDisabled = this.disabled; var isSelected = this.selected; var labelClasses = [ 'ui-corner-all' ]; var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className; var optLabel; // is this an optgroup? if(parent.tagName === 'OPTGROUP') { optLabel = parent.getAttribute('label'); // has this optgroup been added already? if($.inArray(optLabel, optgroups) === -1) { html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '"><a href="#">' + optLabel + '</a></li>'; optgroups.push(optLabel); } } if(isDisabled) { labelClasses.push('ui-state-disabled'); } // browsers automatically select the first option // by default with single selects if(isSelected && !o.multiple) { labelClasses.push('ui-state-active'); } html += '<li class="' + liClasses + '">'; // create the label html += '<label for="' + inputID + '" title="' + description + '" class="' + labelClasses.join(' ') + '">'; html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"'; // pre-selected? if(isSelected) { html += ' checked="checked"'; html += ' aria-selected="true"'; } // disabled? if(isDisabled) { html += ' disabled="disabled"'; html += ' aria-disabled="true"'; } // add the title and close everything off html += ' /><span>' + title + '</span></label></li>'; }); // insert into the DOM checkboxContainer.html(html); // cache some moar useful elements this.labels = menu.find('label'); this.inputs = this.labels.children('input'); // set widths this._setButtonWidth(); this._setMenuWidth(); // remember default value this.button[0].defaultValue = this.update(); // broadcast refresh event; useful for widgets if(!init) { this._trigger('refresh'); } }, // updates the button text. call refresh() to rebuild update: function() { var o = this.options; var $inputs = this.inputs; var $checked = $inputs.filter(':checked'); var numChecked = $checked.length; var value; if(numChecked === 0) { value = o.noneSelectedText; } else { if($.isFunction(o.selectedText)) { value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get()); } else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) { value = $checked.map(function() { return $(this).next().html(); }).get().join(', '); } else { value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length); } } this._setButtonValue(value); return value; }, // this exists as a separate method so that the developer // can easily override it. _setButtonValue: function(value) { this.buttonlabel.text(value); }, // binds events _bindEvents: function() { var self = this; var button = this.button; function clickHandler() { self[ self._isOpen ? 'close' : 'open' ](); return false; } // webkit doesn't like it when you click on the span :( button .find('span') .bind('click.multiselect', clickHandler); // button events button.bind({ click: clickHandler, keypress: function(e) { switch(e.which) { case 27: // esc case 38: // up case 37: // left self.close(); break; case 39: // right case 40: // down self.open(); break; } }, mouseenter: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, mouseleave: function() { $(this).removeClass('ui-state-hover'); }, focus: function() { if(!button.hasClass('ui-state-disabled')) { $(this).addClass('ui-state-focus'); } }, blur: function() { $(this).removeClass('ui-state-focus'); } }); // header links this.header.delegate('a', 'click.multiselect', function(e) { // close link if($(this).hasClass('ui-multiselect-close')) { self.close(); // check all / uncheck all } else { self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll'](); } e.preventDefault(); }); // optgroup label toggle support this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) { e.preventDefault(); var $this = $(this); var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)'); var nodes = $inputs.get(); var label = $this.parent().text(); // trigger event and bail if the return is false if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) { return; } // toggle inputs self._toggleChecked( $inputs.filter(':checked').length !== $inputs.length, $inputs ); self._trigger('optgrouptoggle', e, { inputs: nodes, label: label, checked: nodes[0].checked }); }) .delegate('label', 'mouseenter.multiselect', function() { if(!$(this).hasClass('ui-state-disabled')) { self.labels.removeClass('ui-state-hover'); $(this).addClass('ui-state-hover').find('input').focus(); } }) .delegate('label', 'keydown.multiselect', function(e) { e.preventDefault(); switch(e.which) { case 9: // tab case 27: // esc self.close(); break; case 38: // up case 40: // down case 37: // left case 39: // right self._traverse(e.which, this); break; case 13: // enter $(this).find('input')[0].click(); break; } }) .delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) { var $this = $(this); var val = this.value; var checked = this.checked; var tags = self.element.find('option'); // bail if this input is disabled or the event is cancelled if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) { e.preventDefault(); return; } // make sure the input has focus. otherwise, the esc key // won't close the menu after clicking an item. $this.focus(); // toggle aria state $this.attr('aria-selected', checked); // change state on the original option tags tags.each(function() { if(this.value === val) { this.selected = checked; } else if(!self.options.multiple) { this.selected = false; } }); // some additional single select-specific logic if(!self.options.multiple) { self.labels.removeClass('ui-state-active'); $this.closest('label').toggleClass('ui-state-active', checked); // close menu self.close(); } // fire change on the select box self.element.trigger("change"); // setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827 // http://bugs.jquery.com/ticket/3827 setTimeout($.proxy(self.update, self), 10); }); // close each widget when clicking on any other element/anywhere else on the page $doc.bind('mousedown.' + this._namespaceID, function(event) { var target = event.target; if(self._isOpen && !$.contains(self.menu[0], target) && !$.contains(self.button[0], target) && target !== self.button[0] && target !== self.menu[0]) { self.close(); } }); // deal with form resets. the problem here is that buttons aren't // restored to their defaultValue prop on form reset, and the reset // handler fires before the form is actually reset. delaying it a bit // gives the form inputs time to clear. $(this.element[0].form).bind('reset.multiselect', function() { setTimeout($.proxy(self.refresh, self), 10); }); }, // set button width _setButtonWidth: function() { var width = this.element.outerWidth(); var o = this.options; if(/\d/.test(o.minWidth) && width < o.minWidth) { width = o.minWidth; } // set widths this.button.outerWidth(width); }, // set menu width _setMenuWidth: function() { var m = this.menu; m.outerWidth(this.button.outerWidth()); }, // move up or down within the menu _traverse: function(which, start) { var $start = $(start); var moveToLast = which === 38 || which === 37; // select the first li that isn't an optgroup label / disabled $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)')[ moveToLast ? 'last' : 'first'](); // if at the first/last element if(!$next.length) { var $container = this.menu.find('ul').last(); // move to the first/last this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover'); // set scroll position $container.scrollTop(moveToLast ? $container.height() : 0); } else { $next.find('label').trigger('mouseover'); } }, // This is an internal function to toggle the checked property and // other related attributes of a checkbox. // // The context of this function should be a checkbox; do not proxy it. _toggleState: function(prop, flag) { return function() { if(!this.disabled) { this[ prop ] = flag; } if(flag) { this.setAttribute('aria-selected', true); } else { this.removeAttribute('aria-selected'); } }; }, _toggleChecked: function(flag, group) { var $inputs = (group && group.length) ? group : this.inputs; var self = this; // toggle state on inputs $inputs.each(this._toggleState('checked', flag)); // give the first input focus $inputs.eq(0).focus(); // update button text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // toggle state on original option tags this.element .find('option') .each(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger("change"); } }, _toggleDisabled: function(flag) { this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); var inputs = this.menu.find('input'); var key = "ech-multiselect-disabled"; if(flag) { // remember which elements this widget disabled (not pre-disabled) // elements, so that they can be restored if the widget is re-enabled. inputs = inputs.filter(':enabled').data(key, true) } else { inputs = inputs.filter(function() { return $.data(this, key) === true; }).removeData(key); } inputs .attr({ 'disabled':flag, 'arial-disabled':flag }) .parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled'); this.element.attr({ 'disabled':flag, 'aria-disabled':flag }); }, // open the menu open: function(e) { var self = this; var button = this.button; var menu = this.menu; var speed = this.speed; var o = this.options; var args = []; // bail if the multiselectopen event returns false, this widget is disabled, or is already open if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) { return; } var $container = menu.find('ul').last(); var effect = o.show; // figure out opening effects/speeds if($.isArray(o.show)) { effect = o.show[0]; speed = o.show[1] || self.speed; } // if there's an effect, assume jQuery UI is in use // build the arguments to pass to show() if(effect) { args = [ effect, speed ]; } // set the scroll of the checkbox container $container.scrollTop(0).height(o.height); // positon this.position(); // show the menu, maybe with a speed/effect combo $.fn.show.apply(menu, args); // select the first not disabled option // triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover // will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus'); button.addClass('ui-state-active'); this._isOpen = true; this._trigger('open'); }, // close the menu close: function() { if(this._trigger('beforeclose') === false) { return; } var o = this.options; var effect = o.hide; var speed = this.speed; var args = []; // figure out opening effects/speeds if($.isArray(o.hide)) { effect = o.hide[0]; speed = o.hide[1] || this.speed; } if(effect) { args = [ effect, speed ]; } $.fn.hide.apply(this.menu, args); this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave'); this._isOpen = false; this._trigger('close'); }, enable: function() { this._toggleDisabled(false); }, disable: function() { this._toggleDisabled(true); }, checkAll: function(e) { this._toggleChecked(true); this._trigger('checkAll'); }, uncheckAll: function() { this._toggleChecked(false); this._trigger('uncheckAll'); }, getChecked: function() { return this.menu.find('input').filter(':checked'); }, destroy: function() { // remove classes + data $.Widget.prototype.destroy.call(this); // unbind events $doc.unbind(this._namespaceID); this.button.remove(); this.menu.remove(); this.element.show(); return this; }, isOpen: function() { return this._isOpen; }, widget: function() { return this.menu; }, getButton: function() { return this.button; }, position: function() { var o = this.options; // use the position utility if it exists and options are specifified if($.ui.position && !$.isEmptyObject(o.position)) { o.position.of = o.position.of || this.button; this.menu .show() .position(o.position) .hide(); // otherwise fallback to custom positioning } else { var pos = this.button.offset(); this.menu.css({ top: pos.top + this.button.outerHeight(), left: pos.left }); } }, // react to option changes after initialization _setOption: function(key, value) { var menu = this.menu; switch(key) { case 'header': menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide'](); break; case 'checkAllText': menu.find('a.ui-multiselect-all span').eq(-1).text(value); break; case 'uncheckAllText': menu.find('a.ui-multiselect-none span').eq(-1).text(value); break; case 'height': menu.find('ul').last().height(parseInt(value, 10)); break; case 'minWidth': this.options[key] = parseInt(value, 10); this._setButtonWidth(); this._setMenuWidth(); break; case 'selectedText': case 'selectedList': case 'noneSelectedText': this.options[key] = value; // these all needs to update immediately for the update() call this.update(); break; case 'classes': menu.add(this.button).removeClass(this.options.classes).addClass(value); break; case 'multiple': menu.toggleClass('ui-multiselect-single', !value); this.options.multiple = value; this.element[0].multiple = value; this.refresh(); break; case 'position': this.position(); } $.Widget.prototype._setOption.apply(this, arguments); } }); })(jQuery);
JavaScript
/* jshint forin:true, noarg:true, noempty:true, eqeqeq:true, boss:true, undef:true, curly:true, browser:true, jquery:true */ /* * jQuery MultiSelect UI Widget Filtering Plugin 1.5pre * Copyright (c) 2012 Eric Hynds * * http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ * * Depends: * - jQuery UI MultiSelect widget * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ (function($) { var rEscape = /[\-\[\]{}()*+?.,\\\^$|#\s]/g; $.widget('ech.multiselectfilter', { options: { label: 'Filter:', width: null, /* override default width set in css file (px). null will inherit */ placeholder: 'Enter keywords', autoReset: false }, _create: function() { var opts = this.options; var elem = $(this.element); // get the multiselect instance var instance = (this.instance = (elem.data('echMultiselect') || elem.data("multiselect"))); // store header; add filter class so the close/check all/uncheck all links can be positioned correctly var header = (this.header = instance.menu.find('.ui-multiselect-header').addClass('ui-multiselect-hasfilter')); // wrapper elem var wrapper = (this.wrapper = $('<div class="ui-multiselect-filter">' + (opts.label.length ? opts.label : '') + '<input placeholder="'+opts.placeholder+'" type="search"' + (/\d/.test(opts.width) ? 'style="width:'+opts.width+'px"' : '') + ' /></div>').prependTo(this.header)); // reference to the actual inputs this.inputs = instance.menu.find('input[type="checkbox"], input[type="radio"]'); // build the input box this.input = wrapper.find('input').bind({ keydown: function(e) { // prevent the enter key from submitting the form / closing the widget if(e.which === 13) { e.preventDefault(); } }, keyup: $.proxy(this._handler, this), click: $.proxy(this._handler, this) }); // cache input values for searching this.updateCache(); // rewrite internal _toggleChecked fn so that when checkAll/uncheckAll is fired, // only the currently filtered elements are checked instance._toggleChecked = function(flag, group) { var $inputs = (group && group.length) ? group : this.labels.find('input'); var _self = this; // do not include hidden elems if the menu isn't open. var selector = instance._isOpen ? ':disabled, :hidden' : ':disabled'; $inputs = $inputs .not(selector) .each(this._toggleState('checked', flag)); // update text this.update(); // gather an array of the values that actually changed var values = $inputs.map(function() { return this.value; }).get(); // select option tags this.element.find('option').filter(function() { if(!this.disabled && $.inArray(this.value, values) > -1) { _self._toggleState('selected', flag).call(this); } }); // trigger the change event on the select if($inputs.length) { this.element.trigger('change'); } }; // rebuild cache when multiselect is updated var doc = $(document).bind('multiselectrefresh', $.proxy(function() { this.updateCache(); this._handler(); }, this)); // automatically reset the widget on close? if(this.options.autoReset) { doc.bind('multiselectclose', $.proxy(this._reset, this)); } }, // thx for the logic here ben alman _handler: function(e) { var term = $.trim(this.input[0].value.toLowerCase()), // speed up lookups rows = this.rows, inputs = this.inputs, cache = this.cache; if(!term) { rows.show(); } else { rows.hide(); var regex = new RegExp(term.replace(rEscape, "\\$&"), 'gi'); this._trigger("filter", e, $.map(cache, function(v, i) { if(v.search(regex) !== -1) { rows.eq(i).show(); return inputs.get(i); } return null; })); } // show/hide optgroups this.instance.menu.find(".ui-multiselect-optgroup-label").each(function() { var $this = $(this); var isVisible = $this.nextUntil('.ui-multiselect-optgroup-label').filter(function() { return $.css(this, "display") !== 'none'; }).length; $this[isVisible ? 'show' : 'hide'](); }); }, _reset: function() { this.input.val('').trigger('keyup'); }, updateCache: function() { // each list item this.rows = this.instance.menu.find(".ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label)"); // cache this.cache = this.element.children().map(function() { var elem = $(this); // account for optgroups if(this.tagName.toLowerCase() === "optgroup") { elem = elem.children(); } return elem.map(function() { return this.innerHTML.toLowerCase(); }).get(); }).get(); }, widget: function() { return this.wrapper; }, destroy: function() { $.Widget.prototype.destroy.call(this); this.input.val('').trigger("keyup"); this.wrapper.remove(); } }); })(jQuery);
JavaScript
(function($){ var el, widget, button, input; function getVisible() { return widget.find(".ui-multiselect-checkboxes input:visible"); } function getChecked() { return el.multiselect("getChecked"); } function getSelected() { return el.children(":selected"); } function searchFor(term) { input.val(term).trigger("keyup"); } function triggerClick() { this.click(); } function searchTest( term, expected, message ) { message || (message = "searching for '#'"); message = message.replace("#", term); searchFor(term); equals( getVisible().length, expected, message ); } module("filter widget - multiple select", { setup: function() { el = $('<select multiple>' + '<option></option>' + '<option value="foo">testffoooo</option>' + '<option value="bar">testbbaarr</option>' + '<option value=" baz ">testbbaazz</option>' + '<option value="qux">testquxtest</option>' + '<option value="10">ten</option>' + '<option value="100">one hundred</option>' + '<option value="5">five</option>' + '<option>a test with word boundaries</option>' + '<option>special regex !^$()//-|{}/: characters</option>' + '</option>'); el.appendTo(document.body); el.multiselect(); el.multiselectfilter(); el.multiselect("open"); widget = el.multiselect("widget"); input = widget.find(".ui-multiselect-filter input"); button = el.next(); }, teardown: function() { el.multiselectfilter("destroy"); el.multiselect("destroy"); el.remove(); } }); test("defaults", function(){ expect(1); ok( input.is(":visible"), "Filter input box is visible" ); }); test("filtering by node text", function(){ searchTest( "bbaa", 2); searchTest( "bbaarr", 1); searchTest( " bbaa ", 2, "searching for '#' with whitespace"); searchTest( " ", el.children().length, "searching for an empty string"); searchTest( "test", 5); searchTest( "one hundred", 1); searchTest( "with wor", 1); searchTest( " with wor ", 1); $.each("$ ^ / : // { } | -".split(" "), function( i, char ){ searchTest( char, 1 ); }); }); test("filtering by node value", function(){ // searchTest( "100", 1); // searchTest( "baz", 1); }); test("filtering & checking", function(){ searchFor("ba"); getVisible().each(triggerClick); equals(getChecked().length, 2, "Two checkboxes are selected"); equals(getSelected().length, 2, "Two option tags are selected"); getVisible().each(triggerClick); equals(getChecked().length, 0, "After clicking again, no checkboxes are selected"); equals(getSelected().length, 0, "After clicking again, no tags are selected"); }); test("checkAll / uncheckAll", function(){ searchFor("ba"); el.multiselect("checkAll"); equals(getChecked().length, 2, "checkAll: two checkboxes are selected"); equals(getSelected().length, 2, "checkAll: two option tags are selected"); el.multiselect("uncheckAll"); equals(getChecked().length, 0, "uncheckAll: no checkboxes are selected"); equals(getSelected().length, 0, "uncheckAll: no option tags are selected"); }); test("combination of filtering/methods/click events", function(){ searchFor("ba"); getVisible().first().each(triggerClick); equals(getChecked().length, 1, "selecting 1 of multiple results (checked)"); equals(getSelected().length, 1, "selecting 1 of multiple results (selected)"); searchFor(" "); equals(getChecked().length, 1, "clearing search, only 1 is still selected"); el.multiselect("uncheckAll"); equals(getChecked().length, 0, "uncheckAll, nothing is selected (checked)"); equals(getSelected().length, 0, "uncheckedAll, nothing is selected (selected)"); searchFor("one hundred") el.multiselect("checkAll"); equals(getChecked().length, 1, "checkAll on one matching result (checked)"); equals(getSelected().length, 1, "checkAll on one matching result (selected)"); searchFor("foo"); el.multiselect("checkAll"); equals(getChecked().length, 2, "checkAll on one matching result (checked)"); equals(getSelected().length, 2, "checkAll on one matching result (selected)"); }); })(jQuery);
JavaScript
(function($){ module("methods"); test("open", function(){ expect(2); el = $("select").multiselect().multiselect("open"); ok( el.multiselect("isOpen"), "isOpen parameter true" ); equals( menu().css("display"), "block", "Test display CSS property" ); el.multiselect("destroy"); }); test("close", function(){ expect(2); el = $("select").multiselect().multiselect("open").multiselect("close"); ok( !el.multiselect("isOpen"), "isOpen parameter false" ); equals( menu().css("display"), "none", "Test display CSS property" ); el.multiselect("destroy"); }); test("enable", function(){ expect(2); el = $("select").multiselect().multiselect("disable").multiselect("enable"); ok( button().is(":disabled") === false, "Button is enabled" ); ok( el.is(":disabled") === false, "Original select is enabled" ); el.multiselect("destroy"); }); test("disable", function(){ expect(2); // clone this one so the original is not affected el = $("select").clone(true).appendTo(body).multiselect().multiselect("disable"); ok( button().is(":disabled"), 'Button is disabled'); ok( el.is(":disabled"), 'Original select is disabled'); el.multiselect("destroy").remove(); }); test("enabling w/ pre-disabled tags (#216)", function(){ expect(5); el = $('<select><option disabled value="foo">foo</option><option value="bar">bar</option>') .appendTo(document.body) .multiselect(); var boxes = menu().find("input") var disabled = boxes.first(); var enabled = boxes.last(); var key = "ech-multiselect-disabled"; equals(disabled.is(":disabled"), true, "The first option is disabled"); el.multiselect("disable"); equals(disabled.data(key), undefined, "After disabling the widget, the pre-disabled option is not flagged to re-enable"); equals(enabled.data(key), true, "and the enabled option is flagged to be re-enable"); el.multiselect("enable"); equals(disabled.is(":disabled"), true, "After enabling, the first option is still disabled"); equals(disabled.data(key), undefined, "and the option no longer has the stored data flag"); el.multiselect("destroy").remove(); }); test("widget", function(){ expect(1); el = $("select").multiselect(); ok( menu().is("div.ui-multiselect-menu"), 'Widget is the menu element'); el.multiselect("destroy"); }); test("getButton", function(){ expect(1); el = $("select").multiselect(); var button = el.multiselect("getButton"); ok( button.is("button.ui-multiselect"), 'Button is the button element'); el.multiselect("destroy"); }); test("checkAll", function(){ expect(1); el = $("select").multiselect().multiselect("checkAll"); var inputs = menu().find("input"); ok( inputs.filter(":checked").length === inputs.length, 'All inputs selected on the widget?'); el.multiselect("destroy"); }); test("uncheckAll", function(){ expect(1); el = $("select").multiselect().multiselect("checkAll").multiselect("uncheckAll"); ok( menu().find("input:checked").length === 0, 'All inputs unchecked on the widget?'); el.multiselect("destroy"); }); test("isOpen", function(){ expect(2); el = $("select").multiselect().multiselect("open"); ok( el.multiselect("isOpen"), 'Testing isOpen method after calling open method'); el = $("select").multiselect("close"); ok( !el.multiselect("isOpen"), 'Testing isOpen method after calling close method'); el.multiselect("destroy"); }); test("destroy", function(){ expect(2); el = $("select").multiselect().multiselect("destroy"); ok( !$(".ui-multiselect").length , 'button.ui-multiselect removed from the DOM'); ok( !el.data("multiselect") , 'no more multiselect obj attached to elem'); }); test("getChecked", function(){ expect(2); el = $("select").multiselect().multiselect("checkAll"); equals( el.multiselect("getChecked").length, 9, 'number of checkboxes returned after checking all and calling getChecked'); el.multiselect("uncheckAll"); equals( el.multiselect("getChecked").length, 0, 'number of checkboxes returned after unchecking all and calling getChecked'); el.multiselect("destroy"); }); test("refresh", function(){ expect(4); el = $("select").clone().appendTo(body).multiselect(); el.empty().html('<option value="foo">foo</option><option value="bar">bar</option>'); el.multiselect('refresh'); var checkboxes, getCheckboxes = (function hai(){ checkboxes = menu().find('input[type="checkbox"]'); return hai; })(); equals( checkboxes.length, 2, "After clearing the select, adding 2 options, and refresh(), only 2 checkboxes exist"); equals( checkboxes.eq(0).val(), 'foo', 'first is foo' ); equals( checkboxes.eq(1).val(), 'bar', 'second is foo' ); // add one more w/ append, just for safety's sake el.append('<option value="baz">baz</option>'); el.multiselect('refresh'); getCheckboxes(); equals( checkboxes.eq(2).val(), 'baz', 'after an append() call, the third option is now' ); el.multiselect("destroy").remove(); }); test("position", function() { expect(2); var left = "500px"; el = $("select").clone().appendTo(body).multiselect(); // move the button button().css({ position: "absolute", left: left }); // sanity check the fact that the menu and button are out of sync notEqual(menu().css("left"), left, "After moving the button, the menu remains in its old position"); // update the menu position el.multiselect("position"); // make sure the new position is accurate equals(menu().css("left"), left, "After calling position(), the menu has updated to the same left value as the button"); el.multiselect("destroy").remove(); }); })(jQuery);
JavaScript
(function($){ var el, widget, elems; module("html", { setup: function() { el = $("select").multiselect(); widget = el.multiselect("widget"); } }); test("pull in optgroup's class", function(){ expect(5); elems = widget.find('.ui-multiselect-optgroup-label'); equals( elems.length, 3, 'There are three labels' ); elems.filter(":not(:last)").each( function() { equals($(this).hasClass('ui-multiselect-optgroup-label'),true,'Default class is present when no extra class is defined'); }); elems.filter(":last").each( function() { equals($(this).hasClass('ui-multiselect-optgroup-label'),true,'Default class is present when extra class is defined'); equals($(this).hasClass('optgroupClass'),true,'Extra class is present'); }); }); test("pull in options's class", function(){ expect(1); equals(widget.find('input[value="9"]').parents('li:first').hasClass('optionClass'),true,'Extra class is present'); }); })(jQuery);
JavaScript
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e){ return false; } })() } var testId = 0; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( this.previousModule ) { QUnit.moduleDone( this.module, config.moduleStats.bad, config.moduleStats.all ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( this.module, this.moduleTestEnvironment ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } QUnit.testStart( this.testName, this.testEnvironment ); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Setup failed on " + this.name + ": " + e.message ); } }, run: function() { if ( this.async ) { QUnit.stop(); } try { this.callback.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? fail("Test " + this.name + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }, teardown: function() { try { checkPollution(); this.testEnvironment.teardown.call(this.testEnvironment); } catch(e) { // TODO use testName instead of name for no-markup message? QUnit.ok( false, "Teardown failed on " + this.name + ": " + e.message ); } }, finish: function() { if ( this.expected && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible defined.sessionStorage && sessionStorage.setItem("qunit-" + this.testName, bad); if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location.search = "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, "")); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.style.display = resultDisplayStyle(!bad); li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( ol ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; } } } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { // TODO use testName instead of name for no-markup message? fail("reset() failed, following Test " + this.name + ", exception and reset fn follows", e, QUnit.reset); } QUnit.testDone( this.testName, bad, this.assertions.length ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.testName); if (bad) { run(); } else { synchronize(run); }; } } var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.previousModule = config.currentModule; config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.previousModule = config.previousModule; test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeHtml(msg); QUnit.log(a, msg, details); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(fn, message) { try { fn(); QUnit.ok( false, message ); } catch (e) { QUnit.ok( true, message ); } }, start: function() { // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.blocking = true; if ( timeout && defined.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } } }; // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } else if ( GETParams[i].search('=') > -1 ) { GETParams.splice( i, 1 ); i--; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filters: [], queue: [] }); var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#main, #qunit-fixture" ).html( config.fixture ); } else { var main = id( 'main' ) || id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = Object.prototype.toString.call( obj ) .match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeHtml(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeHtml(QUnit.jsDump.parse(expected)); actual = escapeHtml(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + source +'</pre></td></tr>'; } } output += "</table>"; QUnit.log(result, message, details); config.current.assertions.push({ result: !!result, message: output }); }, // Logging callbacks begin: function() {}, done: function(failures, total) {}, log: function(result, message) {}, testStart: function(name, testEnvironment) {}, testDone: function(name, failures, total) {}, moduleStart: function(name, testEnvironment) {}, moduleDone: function(name, failures, total) {} }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } addEvent(window, "load", function() { QUnit.begin(); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { var paramsIndex = location.href.lastIndexOf(location.search); if ( paramsIndex > -1 ) { var mainPageLocation = location.href.slice(0, paramsIndex); if ( mainPageLocation == location.href ) { banner.innerHTML = '<a href=""> ' + banner.innerHTML + '</a> '; } else { var testName = decodeURIComponent(location.search.slice(1)); banner.innerHTML = '<a href="' + mainPageLocation + '">' + banner.innerHTML + '</a> &#8250; <a href="">' + testName + '</a>'; } } } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : ""; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('main') || id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }); function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all ); } function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } } } function resultDisplayStyle(passed) { return passed && id("qunit-filter-pass") && id("qunit-filter-pass").checked ? 'none' : ''; } function escapeHtml(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&"<>\\]/g, function(s) { switch(s) { case "&": return "&amp;"; case "\\": return "\\\\"; case '"': return '\"'; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); } } function process() { var start = (new Date()).getTime(); while ( config.queue.length && !config.blocking ) { if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) { config.queue.shift()(); } else { window.setTimeout( process, 13 ); break; } } if (!config.blocking && !config.queue.length) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.current.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.current.expected++; } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i, j, loop; var len; // b could be an object literal here if ( ! (QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } //track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]){ loop = true;//dont rewalk array } } if (!loop && ! innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object": function (b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); //track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep loop = false; for(j=0;j<parents.length;j++){ if(parents[j] === a[i]) loop = true; //don't go down the same path twice } aProperties.push(i); // collect a's properties if (!loop && ! innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) ); QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n){ var ns = new Object(); var os = new Object(); for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: new Array(), o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: new Array(), n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n){ o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
JavaScript
(function($){ module("events"); test("multiselectopen", function(){ expect(27); // inject widget el = $("<select multiple><option value='foo'>foo</option></select>").appendTo(body); el.multiselect({ open: function(e,ui){ ok( true, 'option: multiselect("open") fires open callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectopen', 'option: event type in callback'); equals(menu().css("display"), 'block', 'menu display css property equals block'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectopen", function(e,ui){ ok(true, 'event: multiselect("open") fires multiselectopen event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }); // now try to open it.. el.multiselect("open") // make sure the width of the menu and button are equivalent equals( button().outerWidth(), menu().outerWidth(), 'button and menu widths are equivalent'); // close el.multiselect("close"); // make sure a click event on the button opens the menu as well. button().trigger("click"); el.multiselect("close"); // make sure a click event on a span inside the button opens the menu as well. button().find("span:first").trigger("click"); // reset for next test el.multiselect("destroy").remove(); // now try returning false prevent opening el = $("<select></select>") .appendTo(body) .multiselect() .bind("multiselectbeforeopen", function(){ ok( true, "event: binding multiselectbeforeopen to return false (prevent from opening)" ); return false; }) .multiselect("open"); ok( !el.multiselect("isOpen"), "multiselect is not open after multiselect('open')" ); el.multiselect("destroy").remove(); }); test("multiselectclose", function(){ expect(25); // inject widget el = $("<select multiple><option>foo</option></select>").appendTo(body); el.multiselect({ close: function(e,ui){ ok( true, 'option: multiselect("close") fires close callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectclose', 'option: event type in callback'); equals(menu().css("display"), 'none', 'menu display css property equals none'); same(ui, {}, 'option: ui hash'); } }) .bind("multiselectclose", function(e,ui){ ok(true, 'multiselect("close") fires multiselectclose event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .multiselect("open") .multiselect("close") .multiselect("open"); // make sure a click event on the button closes the menu as well. button().click(); el.multiselect("open"); // make sure a click event on a span inside the button closes the menu as well. button().find("span:first").click(); // make sure that the menu is actually closed. see issue #68 ok( el.multiselect('isOpen') === false, 'menu is indeed closed' ); el.multiselect("destroy").remove(); }); test("multiselectbeforeclose", function(){ expect(8); // inject widget el = $("<select multiple></select>").appendTo(body); el.multiselect({ beforeclose: function(e,ui){ ok( true, 'option: multiselect("beforeclose") fires close callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectbeforeclose', 'option: event type in callback'); same(ui, {}, 'option: ui hash'); } }) .bind("multiselectbeforeclose", function(e,ui){ ok(true, 'multiselect("beforeclose") fires multiselectclose event'); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .multiselect("open") .multiselect("close"); el.multiselect("destroy").remove(); // test 'return false' functionality el = $("<select multiple></select>").appendTo(body); el.multiselect({ beforeclose: function(){ return false; } }); el.multiselect('open').multiselect('close'); ok( menu().is(':visible') && el.multiselect("isOpen"), "returning false inside callback prevents menu from closing" ); el.multiselect("destroy").remove(); }); test("multiselectclick", function(){ expect(28); var times = 0; // inject widget el = $("<select multiple><option value='1'>Option 1</option><option value='2'>Option 2</option></select>") .appendTo(body); el.multiselect({ click: function(e,ui){ ok(true, 'option: triggering the click event on the second checkbox fires the click callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectclick', 'option: event type in callback'); equals(ui.value, "2", "option: ui.value equals"); equals(ui.text, "Option 2", "option: ui.title equals"); if(times === 0) { equals(ui.checked, true, "option: ui.checked equals"); } else if(times === 1) { equals(ui.checked, false, "option: ui.checked equals"); } } }) .bind("multiselectclick", function(e,ui){ ok(true, 'event: triggering the click event on the second checkbox triggers multiselectclick'); equals(this, el[0], 'event: context of event'); equals(ui.value, "2", "event: ui.value equals"); equals(ui.text, "Option 2", "event: ui.title equals"); if(times === 0) { equals(ui.checked, true, "option: ui.checked equals"); } else if(times === 1) { equals(ui.checked, false, "option: ui.checked equals"); } }) .bind("change", function(e){ if(++times === 1){ equals(el.val().join(), "2", "event: select element val() within the change event is correct" ); } else { equals(el.val(), null, "event: select element val() within the change event is correct" ); } ok(true, "event: the select's change event fires"); }) .multiselect("open"); // trigger a click event on the input var lastInput = menu().find("input").last(); lastInput[0].click(); // trigger once more. lastInput[0].click(); // make sure it has focus equals(true, lastInput.is(":focus"), "The input has focus"); // make sure menu isn't closed automatically equals( true, el.multiselect('isOpen'), 'menu stays open' ); el.multiselect("destroy").remove(); }); test("multiselectcheckall", function(){ expect(10); // inject widget el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body); el.multiselect({ checkAll: function(e,ui){ ok( true, 'option: multiselect("checkAll") fires checkall callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectcheckall', 'option: event type in callback'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectcheckall", function(e,ui){ ok( true, 'event: multiselect("checkall") fires multiselectcheckall event' ); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .bind("change", function(){ ok(true, "event: the select's change event fires"); equals( el.val().join(), "1,2", "event: select element val() within the change event is correct" ); }) .multiselect("open") .multiselect("checkAll"); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); test("multiselectuncheckall", function(){ expect(10); // inject widget el = $('<select multiple><option value="1">Option 1</option><option value="2">Option 2</option></select>').appendTo(body); el.multiselect({ uncheckAll: function(e,ui){ ok( true, 'option: multiselect("uncheckAll") fires uncheckall callback' ); equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectuncheckall', 'option: event type in callback'); same(ui, {}, 'option: ui hash in callback'); } }) .bind("multiselectuncheckall", function(e,ui){ ok( true, 'event: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); same(ui, {}, 'event: ui hash'); }) .bind("change", function(){ ok(true, "event: the select's change event fires"); equals( el.val(), null, "event: select element val() within the change event is correct" ); }) .multiselect("open") .multiselect("uncheckAll"); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); test("multiselectbeforeoptgrouptoggle", function(){ expect(10); // inject widget el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>') .appendTo(body); el.bind("change", function(){ ok(true, "the select's change event fires"); }) .multiselect({ beforeoptgrouptoggle: function(e,ui){ equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectbeforeoptgrouptoggle', 'option: event type in callback'); equals(ui.label, "Set One", 'option: ui.label equals'); equals(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key'); } }) .bind("multiselectbeforeoptgrouptoggle", function(e,ui){ ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); equals(ui.label, "Set One", 'event: ui.label equals'); equals(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key'); }) .multiselect("open"); menu().find("li.ui-multiselect-optgroup-label a").click(); el.multiselect("destroy").remove(); el = el.clone(); // test return false preventing checkboxes from activating el.bind("change", function(){ ok( true ); // should not fire }).multiselect({ beforeoptgrouptoggle: function(){ return false; }, // if this fires the expected count will be off. just a redundant way of checking that return false worked optgrouptoggle: function(){ ok( true ); } }).appendTo( body ); var label = menu().find("li.ui-multiselect-optgroup-label a").click(); equals( menu().find(":input:checked").length, 0, "when returning false inside the optgrouptoggle handler, no checkboxes are checked" ); el.multiselect("destroy").remove(); }); test("multiselectoptgrouptoggle", function(){ expect(12); // inject widget el = $('<select multiple><optgroup label="Set One"><option value="1">Option 1</option><option value="2">Option 2</option></optgroup></select>').appendTo(body); el.multiselect({ optgrouptoggle: function(e,ui){ equals(this, el[0], "option: context of callback"); equals(e.type, 'multiselectoptgrouptoggle', 'option: event type in callback'); equals(ui.label, "Set One", 'option: ui.label equals'); equals(ui.inputs.length, 2, 'option: number of inputs in the ui.inputs key'); equals(ui.checked, true, 'option: ui.checked equals true'); } }) .bind("multiselectoptgrouptoggle", function(e,ui){ ok( true, 'option: multiselect("uncheckall") fires multiselectuncheckall event' ); equals(this, el[0], 'event: context of event'); equals(ui.label, "Set One", 'event: ui.label equals'); equals(ui.inputs.length, 2, 'event: number of inputs in the ui.inputs key'); equals(ui.checked, true, 'event: ui.checked equals true'); }) .multiselect("open"); // trigger native click event on optgroup menu().find("li.ui-multiselect-optgroup-label a").click(); equals(menu().find(":input:checked").length, 2, "both checkboxes are actually checked" ); equals(menu().find("input").first().is(":focus"), true, "The first input has focus"); el.multiselect("destroy").remove(); }); })(jQuery);
JavaScript
var el; var body = document.body; function button(){ return el.next(); } function menu(){ return el.multiselect("widget"); } function header(){ return menu().find('.ui-multiselect-header'); } QUnit.done = function(){ $("select").hide(); }; (function($){ module("core"); test("init", function(){ expect(6); el = $("select").multiselect(), $header = header(); ok( $header.find('a.ui-multiselect-all').css('display') !== 'none', 'select all is visible' ); ok( $header.find('a.ui-multiselect-none').css('display') !== 'none', 'select none is visible' ); ok( $header.find('a.ui-multiselect-close').css('display') !== 'none', 'close link is visible' ); ok( menu().is(':hidden'), 'menu is hidden'); ok( el.is(":hidden"), 'the original select is hidden'); ok( el.attr('tabIndex') == 2, 'button inherited the correct tab index'); el.multiselect("destroy"); }); test("form submission", function(){ expect(3); var form = $('<form></form>').appendTo(body), data; el = $('<select id="test" name="test" multiple="multiple"><option value="foo" selected="selected">foo</option><option value="bar">bar</option></select>') .appendTo(form) .multiselect() .multiselect("checkAll"); data = form.serialize(); equals( data, 'test=foo&test=bar', 'after checking all and serializing the form, the correct keys were serialized'); el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'after unchecking all and serializing the form, nothing was serialized'); // re-check all and destroy, exposing original select el.multiselect("checkAll").multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar', 'after checking all, destroying the widget, and serializing the form, the correct keys were serialized'); form.remove(); }); test("form submission, optgroups", function(){ expect(4); var form = $('<form></form>').appendTo(body), data; el = $('<select id="test" name="test" multiple="multiple"><optgroup label="foo"><option value="foo">foo</option><option value="bar">bar</option></optgroup><optgroup label="bar"><option value="baz">baz</option><option value="bax">bax</option></optgroup></select>') .appendTo(form) .multiselect() .multiselect("checkAll"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz&test=bax', 'after checking all and serializing the form, the correct keys were serialized'); el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'after unchecking all and serializing the form, nothing was serialized'); // re-check all and destroy, exposing original select el.multiselect("checkAll").multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz&test=bax', 'after checking all, destroying the widget, and serializing the form, the correct keys were serialized'); // reset option tags el.find("option").each(function(){ this.selected = false; }); // test checking one option in both optgroups el.multiselect(); // finds the first input in each optgroup (assumes 2 options per optgroup) el.multiselect("widget").find('.ui-multiselect-checkboxes li:not(.ui-multiselect-optgroup-label) input:even').each(function( i ){ this.click(); }); data = form.serialize(); equals( data, 'test=foo&test=baz', 'after manually checking one input in each group, the correct two are serialized'); el.multiselect('destroy'); form.remove(); }); test("form submission, single select", function(){ expect(7); var form = $('<form></form>').appendTo("body"), radios, data; el = $('<select id="test" name="test" multiple="multiple"><option value="foo">foo</option><option value="bar">bar</option><option value="baz">baz</option></select>') .appendTo(form) .multiselect({ multiple: false }); // select multiple radios to ensure that, in the underlying select, only one // will remain selected radios = menu().find(":radio"); radios[0].click(); radios[2].click(); radios[1].click(); data = form.serialize(); equals( data, 'test=bar', 'the form serializes correctly after clicking on multiple radio buttons'); equals( radios.filter(":checked").length, 1, 'Only one radio button is selected'); // uncheckAll method el.multiselect("uncheckAll"); data = form.serialize(); equals( data.length, 0, 'After unchecking all, nothing was serialized'); equals( radios.filter(":checked").length, 0, 'No radio buttons are selected'); // checkAll method el.multiselect("checkAll"); data = form.serialize(); equals( el.multiselect("getChecked").length, 1, 'After checkAll, only one radio is selected'); equals( radios.filter(":checked").length, 1, 'One radio is selected'); // expose original el.multiselect("destroy"); data = form.serialize(); equals( data, 'test=foo&test=bar&test=baz', 'after destroying the widget and serializing the form, the correct key was serialized: ' + data); form.remove(); }); asyncTest("form reset, nothing pre-selected", function(){ expect(2); var form = $('<form></form>').appendTo(body), noneSelected = 'Please check something'; el = $('<select name="test" multiple="multiple"><option value="foo">foo</option><option value="bar">bar</option></select>') .appendTo(form) .multiselect({ noneSelectedText: noneSelected }) .multiselect("checkAll"); // trigger reset form.trigger("reset"); setTimeout(function(){ equals( menu().find(":checked").length, 0, "no checked checkboxes" ); equals( button().text(), noneSelected, "none selected text"); el.multiselect('destroy'); form.remove(); start(); }, 10); }); asyncTest("form reset, pre-selected options", function(){ expect(2); var form = $('<form></form>').appendTo(body); el = $('<select name="test" multiple="multiple"><option value="foo" selected="selected">foo</option><option value="bar" selected="selected">bar</option></select>') .appendTo(form) .multiselect({ selectedText: '# of # selected' }) .multiselect("uncheckAll"); // trigger reset form.trigger("reset"); setTimeout(function(){ equals( menu().find(":checked").length, 2, "two checked checkboxes" ); equals( button().text(), "2 of 2 selected", "selected text" ); el.multiselect('destroy'); form.remove(); start(); }, 10); }); })(jQuery);
JavaScript
(function($){ module("options"); test("noneSelectedText", function(){ expect(7); var text; el = $("select").multiselect({ noneSelectedText: 'None Selected' }); // read from widget text = el.multiselect("option", "noneSelectedText"); equals( button().text(), text, 'on init, button reads "None Selected"'); el.multiselect("checkAll"); ok( button().text() !== text, 'after checkAll, button no longer reads "None Selected"'); el.multiselect("uncheckAll"); equals( button().text(), text, 'after uncheckAll, button text restored to "None Selected"'); // change the option value el.multiselect("option", "noneSelectedText", "No Checkboxes Checked"); equals( el.multiselect("option", "noneSelectedText"), "No Checkboxes Checked", "new noneSelectedText value set correctly"); // read updated value from widget text = el.multiselect("option", "noneSelectedText"); // test against the new value equals( button().text(), text, 'after changing the option value, button now reads "No Checkboxes Checked"'); el.multiselect("checkAll"); ok( button().text() !== text, 'after checkAll, button no longer reads "No Checkboxes Checked"'); el.multiselect("uncheckAll"); equals( button().text(), text, 'after uncheckAll, button text restored to "No Checkboxes Checked"'); el.multiselect("destroy"); }); test("selectedText", function(){ expect(3); var numOptions = $("select option").length; el = $("select").multiselect({ selectedText: '# of # selected' }); el.multiselect("checkAll"); equals( button().text(), numOptions+' of '+numOptions+' selected', 'after checkAll, button reflects the total number of checked boxes'); // change option value el.multiselect("option", "selectedText", function( numChecked ){ return numChecked + ' options selected'; }); equals( button().text(), numOptions+' options selected', 'after changing the option to a function value, button reflects the new text'); // uncheck all el.multiselect("uncheckAll"); equals( button().text(), el.multiselect("option","noneSelectedText"), 'after unchecking all, button text now reflects noneSelectedText option value'); el.multiselect("destroy"); }); test("selectedList", function(){ expect(2); var html = '<select multiple><option value="foo">foo &quot;with quotes&quot;</option><option value="bar">bar</option><option value="baz">baz</option></select>'; el = $(html).appendTo("body").multiselect({ selectedList: 3 }); el.multiselect("checkAll"); equals( button().text(), 'foo "with quotes", bar, baz', 'after checkAll, button text is a list of all options in the select'); el.multiselect("destroy").remove(); el = $(html).appendTo("body").multiselect({ selectedList: 2 }); el.multiselect("checkAll"); equals( button().text(), '3 selected', 'after checkAll with a limited selectedList value, button value displays number of checked'); el.multiselect("destroy").remove(); }); function asyncSelectedList( useTrigger, message ){ expect(1); stop(); var html = '<select multiple><option value="foo">foo</option><option value="bar">bar</option><option value="baz">baz</option></select>', checkboxes; el = $(html).appendTo(body).multiselect({ selectedList: 2 }); checkboxes = el.multiselect("widget").find(":checkbox"); if( useTrigger ){ checkboxes.eq(0).trigger('click'); checkboxes.eq(1).trigger('click'); } else { checkboxes.eq(0)[0].click(); checkboxes.eq(1)[0].click(); } setTimeout(function(){ equals( button().text(), 'foo, bar', message); el.multiselect("destroy").remove(); start(); }, 10); } test("selectedList - manual trigger - jQuery", function(){ asyncSelectedList( true, 'manually checking items with trigger()' ); }); test("selectedList - manual trigger - native", function(){ asyncSelectedList( false, 'manually checking items with element.click()' ); }); test("selectedList - encoding", function() { expect(1); el = $('<select><option value="A&amp;E">A&amp;E</option></select>') .appendTo("body") .multiselect({ selectedList: 1 }); equals(button().text(), 'A&amp;E'); el.multiselect("destroy").remove(); }); test("height", function(){ expect(2); var height = 234; el = $("select").multiselect({ height: height }).multiselect("open"); equals( height, menu().find("ul.ui-multiselect-checkboxes").height(), 'height after opening propertly set to '+height ); // change height and re-test height = 333; el.multiselect("option", "height", height); equals( height, menu().find("ul.ui-multiselect-checkboxes").height(), 'changing value through api to '+height ); el.multiselect("destroy"); }); test("minWidth", function(){ expect(3); var minWidth = 321; el = $("select").multiselect({ minWidth:minWidth }).multiselect("open"); equals( minWidth, button().outerWidth(), 'outerWidth of button is ' + minWidth ); // change height and re-test minWidth = 351; el.multiselect("option", "minWidth", minWidth); equals( minWidth, button().outerWidth(), 'changing value through api to '+minWidth); // change height to something that should fail. minWidth = 10; el.multiselect("option", "minWidth", minWidth); var outerWidth = button().outerWidth(); ok( minWidth !== outerWidth, 'changing value through api to '+minWidth+' (too small), outerWidth is actually ' + outerWidth); el.multiselect("destroy"); }); test("checkAllText", function(){ expect(2); var text = "foo"; el = $("select").multiselect({ checkAllText:text }); equals( text, menu().find(".ui-multiselect-all").text(), 'check all link reads '+text ); // set through option text = "bar"; el.multiselect("option","checkAllText","bar"); equals( text, menu().find(".ui-multiselect-all").text(), 'check all link reads '+text ); el.multiselect("destroy"); }); test("uncheckAllText", function(){ expect(2); var text = "foo"; el = $("select").multiselect({ uncheckAllText:text }); equals( text, menu().find(".ui-multiselect-none").text(), 'check all link reads '+text ); // set through option text = "bar"; el.multiselect("option","uncheckAllText","bar"); equals( text, menu().find(".ui-multiselect-none").text(), 'changing value through api to '+text ); el.multiselect("destroy"); }); test("autoOpen", function(){ expect(2); el = $("select").multiselect({ autoOpen:false }); ok( menu().is(":hidden"), 'menu is hidden with autoOpen off'); el.multiselect("destroy"); el = $("select").multiselect({ autoOpen:true }); ok( menu().is(":visible"), 'menu is visible with autoOpen on'); el.multiselect("destroy"); // no built in support for change on the fly; not testing it. }); test("multiple (false - single select)", function(){ expect(10); el = $("select").multiselect({ multiple:false }); // get some references var $menu = menu(), $header = header(); ok( $header.find('a.ui-multiselect-all').is(':hidden'), 'select all link is hidden' ); ok( $header.find('a.ui-multiselect-none').is(':hidden'), 'select none link is hidden' ); ok( $header.find('a.ui-multiselect-close').css('display') !== 'hidden', 'close link is visible' ); ok( !$menu.find(":checkbox").length, 'no checkboxes are present'); ok( $menu.find(":radio").length > 0, 'but radio boxes are'); // simulate click on ALL radios var radios = $menu.find(":radio").trigger("click"); // at the end of that, only one radio should be checked and the menu closed equals( radios.filter(":checked").length, 1, 'After checking all radios, only one is actually checked'); equals( false, el.multiselect('isOpen'), 'Menu is closed' ); // uncheck boxes... should only be one radios.filter(":checked").trigger("click"); // method calls el.multiselect("checkAll"); equals( $menu.find("input:radio:checked").length, 1, 'After checkAll method call only one is actually checked'); el.multiselect("uncheckAll"); equals( $menu.find("input:radio:checked").length, 0, 'After uncheckAll method nothing is checked'); // check/uncheck all links equals( $menu.find(".ui-multiselect-all, ui-multiselect-none").filter(":visible").length, 0, "Check/uncheck all links don't exist"); el.multiselect("destroy"); }); test("multiple (changing dynamically)", function(){ expect(6); el = $('<select multiple><option value="foo">foo</option></select>') .appendTo("body") .multiselect(); el.multiselect("option", "multiple", false); equals(el[0].multiple, false, "When changing a multiple select to a single select, the select element no longer has the multiple property"); equals(menu().hasClass("ui-multiselect-single"), true, "...and the menu now has the single select class"); equals(menu().find('input[type="radio"]').length, 1, "...and the checkbox is now a radio button"); el.multiselect("option", "multiple", true); equals(el[0].multiple, true, "When changing a single select to a multiple select, the select element has the multiple property"); equals(menu().hasClass("ui-multiselect-single"), false, "...and the menu doesn't have the single select class"); equals(menu().find('input[type="checkbox"]').length, 1, "...and the radio button is now a checkbox"); el.multiselect("destroy").remove(); }); test("classes", function(){ expect(6); var classname = 'foo'; el = $("select").multiselect({ classes:classname }); var $button = button(), $widget = menu(); equals( $widget.hasClass(classname), true, 'menu has the class ' + classname); equals( $button.hasClass(classname), true, 'button has the class ' + classname); // change it up var newclass = 'bar'; el.multiselect("option", "classes", newclass); equals( $widget.hasClass(newclass), true, 'menu has the new class ' + newclass); equals( $button.hasClass(newclass), true, 'button has the new class ' + newclass); equals( $button.hasClass(classname), false, 'menu no longer has the class ' + classname); equals( $button.hasClass(classname), false, 'button no longer has the class ' + classname); el.multiselect("destroy"); }); test("header", function(){ expect(7); function countLinks(){ return header().find("a").length; } // default el = $("select").multiselect({ autoOpen:true }); ok(header().is(':visible'), "default config: header is visible" ); el.multiselect("option", "header", false); ok(header().is(':hidden'), "after changing header option on default config: header is no longer visible" ); // test for all links within the default header equals(countLinks(), 3, "number of links in the default header config"); el.multiselect("destroy"); // create again, this time header false el = $("select").multiselect({ header:false, autoOpen:true }); ok(header().is(':hidden'), "init with header false: header is not visible" ); el.multiselect("option", "header", true); ok(header().is(':visible'), "after changing header option: header is visible" ); el.multiselect("destroy"); // create again, this time custom header el = $("select").multiselect({ header:"hai guyz", autoOpen:true }); equals(header().text(), "hai guyz", "header equals custom text"); equals(countLinks(), 1, "number of links in the custom header config (should be close button)"); el.multiselect("destroy"); }); })(jQuery);
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: '全選', uncheckAllText: '清空', noneSelectedText: '請選擇', selectedText: '# 已選擇' }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: '全选', uncheckAllText: '清空', noneSelectedText: '请选择', selectedText: '# 已选择' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Marcar todos', uncheckAllText: 'Desmarcar todos', noneSelectedText: 'Selecione as opções', selectedText: '# selecionado' }); })( jQuery );
JavaScript
/* Japanese initialisation for the jQuery UI multiselect plugin. */ /* Written by Daisuke (daisuketaniwaki@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'すべて選択', uncheckAllText: '選択解除', noneSelectedText: '選択してください', selectedText: '#つ選択中' }); })( jQuery );
JavaScript
/* Italian initialization for the jQuery UI multiselect plugin. */ /* Written by Vincenzo Farruggia(mastropinguino@networky.net). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Seleziona tutto', uncheckAllText: 'Deseleziona tutto', noneSelectedText: 'Seleziona le opzioni', selectedText: '# selezionati' }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Introduzca una palabra" }); })( jQuery );
JavaScript
/* Japanese initialisation for the jQuery UI multiselect plugin. */ /* Written by Daisuke (daisuketaniwaki@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '絞込み:', placeholder: 'キーワードを入力してください' }); })( jQuery );
JavaScript
/* Polish initialisation for the jQuery UI multiselect plugin. */ /* Written by Tomasz Mazur (contact@tomaszmazur.eu). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtruj:", placeholder: "Wprowadź słowa kluczowe" }); })( jQuery );
JavaScript
/* French initialisation for the jQuery UI multiselect plugin. */ /* Written by Charles SANQUER (charles.sanquer@spyrit.net). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Tout cocher', uncheckAllText: 'Tout décocher', noneSelectedText: 'Selectionner les options', selectedText: '# selectionnés' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Yusuf Özer (realsby@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtre:", placeholder: "Bir kelime yazın" }); })( jQuery );
JavaScript
/* Italian initialization for the jQuery UI multiselect plugin. */ /* Written by Vincenzo Farruggia(mastropinguino@networky.net). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Digita una parola chiave" }); })( jQuery );
JavaScript
/* Czech initialisation for the jQuery UI multiselect plugin. */ /* Written by Michi (michi.m@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtrovat:", placeholder: "Napište výraz" }); })( jQuery );
JavaScript
/* Russian initialisation for the jQuery UI multiselect plugin. */ /* Written by Artem Packhomov (gorblnu4@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Отметить все', uncheckAllText: 'Снять отметку со всех', noneSelectedText: 'Выберите из списка', selectedText: 'Выбрано #' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinícius Fontoura Corrêa (vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtro:", placeholder: "Entre com a palavra" }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Vinius Fontoura Correa(vinusfc@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Marca todas', uncheckAllText: 'Desmarque todas', noneSelectedText: 'Seleccione las opciones', selectedText: '# seleccionado' }); })( jQuery );
JavaScript
/* German initialisation for the jQuery UI multiselect plugin. */ /* Written by Sven Tatter (sven.tatter@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Suchen:", placeholder: "Stichwort eingeben" }); })( jQuery );
JavaScript
/* Spanish initialisation for the jQuery UI multiselect plugin. */ /* Written by Tomasz Mazur (contact@tomaszmazur.eu). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Zaznacz wszystkie', uncheckAllText: 'Odznacz wszystkie', noneSelectedText: 'Wybierz opcje', selectedText: 'Zaznaczono #' }); })( jQuery );
JavaScript
/* Russian initialisation for the jQuery UI multiselect plugin. */ /* Written by Artem Packhomov (gorblnu4@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Фильтр:", placeholder: "Введите запрос" }); })( jQuery );
JavaScript
/* German initialisation for the jQuery UI multiselect plugin. */ /* Written by Sven Tatter (sven.tatter@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Alle auswählen', uncheckAllText: 'Alle abwählen', noneSelectedText: 'Nichts ausgewählt', selectedText: '# ausgewählt' }); })( jQuery );
JavaScript
/* Brazilian initialisation for the jQuery UI multiselect plugin. */ /* Written by Yusuf Özer (realsby@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Tümünü seç', uncheckAllText: 'Tümünü sil', noneSelectedText: 'Seçenekleri belirleyin', selectedText: '# adet seçildi' }); })( jQuery );
JavaScript
/* French initialisation for the jQuery UI multiselect plugin. */ /* Written by Charles SANQUER (charles.sanquer@spyrit.net). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: "Filtre:", placeholder: "Entrer un mot clé" }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '过滤:', placeholder: '输入关键字过滤' }); })( jQuery );
JavaScript
/* Simplified Chinese initialisation for the jQuery UI multiselect plugin. */ /* Written by Ben (ben@zfben.com). */ (function ( $ ) { $.extend($.ech.multiselectfilter.prototype.options, { label: '過濾:', placeholder: '輸入關鍵字過濾' }); })( jQuery );
JavaScript
/* Czech initialisation for the jQuery UI multiselect plugin. */ /* Written by Michi (michi.m@gmail.com). */ (function ( $ ) { $.extend($.ech.multiselect.prototype.options, { checkAllText: 'Vybrat vše', uncheckAllText: 'Zrušit výběr', noneSelectedText: 'Nic není vybráno', selectedText: '# vybráno' }); })( jQuery );
JavaScript
//<![CDATA[ // Recent Post widget for Blogger with Preloader // Author: Taufik Nurrohman // https://plus.google.com/108949996304093815163/about // Licence: Free for change, keep the original attribution, non commercial function showRecentPosts(json) { for (var i = 0; i < rp_numPosts; i++) { if (i == json.feed.entry.length) break; var entry = json.feed.entry[i], postTitle = entry.title.$t, postAuthor = entry.author[0].name.$t, postDate = entry.published.$t.substring(0, 10), postUrl, linkTarget, postContent, postImage, skeleton = ""; var dy = postDate.substring(0, 4), dm = postDate.substring(5, 7), dd = postDate.substring(8, 10); for (var j = 0; j < entry.link.length; j++) { if (entry.link[j].rel == 'alternate') { postUrl = entry.link[j].href; break; } } for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') { commentNum = entry.link[k].title.split(" ")[0]; commentLabel = entry.link[k].title.split(" ")[1]; break; } } if ("content" in entry) { postContent = entry.content.$t; } else if ("summary" in entry) { postContent = entry.summary.$t; } else { postContent = ''; } if (rp_thumbWidth !== 0) { if ("media$thumbnail" in entry) { postImage = '<img style="width:' + rp_thumbWidth + 'px;height:' + rp_thumbWidth + 'px;" src="' + entry.media$thumbnail.url.replace(/\/s[0-9]+\-c/g, "\/s" + rp_thumbWidth + "-c") + '" alt="Loading..." />'; } else { postImage = '<img style="width:' + rp_thumbWidth + 'px;height:' + rp_thumbWidth + 'px;" src="' + rp_noImage + '" alt="Loading..."/>'; } } else { postImage = ""; } postContent = postContent.replace(/<br ?\/?>/ig, " "); postContent = postContent.replace(/<\S[^>]*>/g, ""); if (postContent.length > rp_numChars) { if (rp_numChars !== 0) { postContent = postContent.substring(0, rp_numChars) + '&hellip;'; } else { postContent = ''; } } linkTarget = (rp_newTabLink) ? ' target="_blank"' : ''; skeleton = '<li>'; skeleton += '<a href="' + postUrl + '"' + linkTarget + '>' + postImage + '</a>'; skeleton += '<div class="recent-right">'; skeleton += '<a class="title" href="' + postUrl + '"' + linkTarget + '>' + postTitle + '</a>'; skeleton += postContent; skeleton += '</div>'; skeleton += '<br style="clear:both;"/><span class="foot"><span class="recent-date">' + dd + ' ' + rp_monthNames[parseInt(dm, 10) - 1] + ' ' + dy + '</span></span>'; skeleton += '</li>'; document.getElementById('recent-post').innerHTML += skeleton; } } var labelName = (rp_sortByLabel !== false) ? '-/' + rp_sortByLabel : ""; var rp_script = document.createElement('script'); rp_script.src = rp_homePage + '/feeds/posts/default/' + labelName + '?alt=json-in-script&callback=showRecentPosts'; // Preloading... if (rp_loadTimer === "onload") { window.onload = function() { document.getElementsByTagName('head')[0].appendChild(rp_script); }; } else { setTimeout(function() { document.getElementsByTagName('head')[0].appendChild(rp_script); }, rp_loadTimer); } //]]>
JavaScript
//<![CDATA[ var thumbnail_mode = "float" ; summary_noimg = 250; summary_img = 210; img_thumb_size = 95; var numm_rand_post=3; function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1){ 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); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createTumbnail(thumbUrl,img_size) { var thumbnail = thumbUrl ; var patt0 = /s72-c/g; var patt1 = /s200/g; var patt2 = /s320/g; var patt3 = /s400/g; var patt4 = /s640/g; var patt5 = /s1600/g; if ( patt1.test(thumbnail) == true) { thumbnail = thumbnail.replace("s200","s"+img_size+"-c"); return thumbnail; } else if (patt2.test(thumbnail) == true) { thumbnail = thumbnail.replace("s320","s"+img_size+"-c"); return thumbnail; } else if (patt3.test(thumbnail) == true) { thumbnail = thumbnail.replace("s400","s"+img_size+"-c"); return thumbnail; } else if (patt4.test(thumbnail) == true) { thumbnail = thumbnail.replace("s640","s"+img_size+"-c"); return thumbnail; } else if (patt5.test(thumbnail) == true) { thumbnail = thumbnail.replace("s1600","s"+img_size+"-c"); return thumbnail; } else if (patt0.test(thumbnail) == true) { thumbnail = thumbnail.replace("s72-c","s"+img_size+"-c"); return thumbnail; } } function popTumbnail(Turl,Tsize) { return ('<img src="'+createTumbnail(Turl,Tsize)+'" />'); } function createSummaryAndThumb(ID,pURL,pTitle){ var pID = 'summary' + ID; var pThumb = 'thumbnail-' + ID; var div = document.getElementById(pID); var thumb = document.getElementById(pThumb); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<span style="padding:0px;"><a href="'+ pURL +'" alt="tumbnail" title="'+ pTitle +'"><img src="' + img[0].src + '" alt="thumbnails"/></a></span>'; summ = summary_img; } else { imgtag = ''; summ = summary_img; } thumb.innerHTML = imgtag ; div.innerHTML = '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>'; } //]]>
JavaScript
var JudNav = {}; //Pengambilan judul artikel melalui feed function ambilJudNav(json) { for (var i = 0; i < json.feed.entry.length; i++) { var judul = json.feed.entry[i]; var data = ""; for (var k = 0; k < judul.link.length; k++) { if (judul.link[k].rel == 'alternate') { data = judul.link[k].href; break } } if (data != "") JudNav[data] = judul.title.$t } } //Penulisan sekumpulan judul feed dengan mengambilnya dari fungsi sebelumnya 'ambilJudNav' document.write('<script type="text/javascript" src="http://' + window.location.hostname + '/feeds/posts/summary?redirect=false&max-results=500&alt=json-in-script&callback=ambilJudNav"></' + 'script>'); //Pengambilan Anchor, Pengecekan URL dan Penggantian beberapa simbol function JudulURL(anchor) { var linkurl = anchor.match(/\/([^\/_]+)(_.*)?\.html/); if (linkurl) { linkurl = linkurl[1].replace(/-/g, " "); linkurl = linkurl[0].toUpperCase() + linkurl.slice(1); if (linkurl.length > 28) linkurl = linkurl.replace(/ [^ ]+$/, "...") } return linkurl } //Mengganti 'Posting Lama' dan 'Posting Lebih Baru' $(window).load(function () { window.setTimeout(function () { var anchor = $("a.blog-pager-newer-link").attr("href"); if (anchor) { var judul = JudNav[anchor]; if (!judul) judul = JudulURL(anchor); if (judul) $("a.blog-pager-newer-link").html(judul) } anchor = $("a.blog-pager-older-link").attr("href"); if (anchor) { var judul = JudNav[anchor]; if (!judul) judul = JudulURL(anchor); if (judul) $("a.blog-pager-older-link").html(judul) } }, 500) });
JavaScript
$(document).ready(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace(/\/$/,''); } var locationPath = filterPath(location.pathname); var scrollElem = scrollableElement('html', 'body'); $('a[href*=#]').each(function() { var thisPath = filterPath(this.pathname) || locationPath; if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) { var $target = $(this.hash), target = this.hash; if (target) { var targetOffset = $target.offset().top; $(this).click(function(event) { event.preventDefault(); $(scrollElem).animate({scrollTop: targetOffset}, 400, function() { location.hash = target; }); }); } } }); // use the first element that is "scrollable" function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; } });
JavaScript
//<![CDATA[ $(document).ready(function() { function getTargetTop(elem){ var id = elem.attr("href"); var offset = 60; return $(id).offset().top - offset; } $('a[href^="#"]').click(function(event) { var target = getTargetTop($(this)); $('html, body').animate({scrollTop:target}, 1200); event.preventDefault(); }); var sections = $('a[href^="#"]'); function checkSectionSelected(scrolledTo){ var threshold = 200; var i; for (i = 0; i < sections.length; i++) { var section = $(sections[i]); var target = getTargetTop(section); if (scrolledTo > target - threshold && scrolledTo < target + threshold) { sections.removeClass("active"); section.addClass("active"); } } ;} checkSectionSelected($(window).scrollTop()); $(window).scroll(function(e){ checkSectionSelected($(window).scrollTop()) }); }); //]]>
JavaScript
/** * An object of type SimpleRotator can be used to implement a trackball-like mouse rotation * of a WebGL scene about the origin. Only the first parameter to the constructor is required. * When an object is created, mouse event handlers are set up on the canvas to respond to rotation. * The class defines the following methods for an object rotator of type SimpleRotator: * rotator.setView(viewDirectionVector, viewUpVector, viewDistance) set up the view, where the * parameters are optional and are used in the same way as the corresponding parameters in the constructor; * rotator.setViewDistance(viewDistance) sets the distance of the viewer from the origin without * changing the direction of view; * rotator.getViewDistance() returns the viewDistance; * rotator.getViewMatrix() returns a Float32Array representing the viewing transformation matrix * for the current view, suitable for use with gl.uniformMatrix4fv or for further transformation with * the glmatrix library mat4 class; * rotator.getViewMatrixArray() returns the view transformation matrix as a regular JavaScript * array, but still represents as a 1D array of 16 elements, in column-major order. * * @param canvas the HTML canvas element used for WebGL drawing. The user will rotate the * scene by dragging the mouse on this canvas. This parameter is required. * @param callback if present must be a function, which is called whenever the rotation changes. * It is typically the function that draws the scene * @param viewDirectionVector if present must be an array of three numbers, not all zero. The * view is from the direction of this vector towards the origin (0,0,0). If not present, * the value [0,0,10] is used. * @param viewUpVector if present must be an array of three numbers. Gives a vector that will * be seen as pointing upwards in the view. If not present, the value is [0,1,0]. * @param viewDistance if present must be a positive number. Gives the distance of the viewer * from the origin. If not present, the length of viewDirectionVector is used. */ function SimpleRotator(canvas, callback, viewDirectionVector, viewUpVector, viewDistance) { var unitx = new Array(3); var unity = new Array(3); var unitz = new Array(3); var viewZ; this.setView = function( viewDirectionVector, viewUpVector, viewDistance ) { var viewpoint = viewDirectionVector || [0,0,10]; var viewup = viewUpVector || [0,1,0]; if (viewDistance && typeof viewDistance == "number") viewZ = viewDistance; else viewZ = length(viewpoint); copy(unitz,viewpoint); normalize(unitz, unitz); copy(unity,unitz); scale(unity, unity, dot(unitz,viewup)); subtract(unity,viewup,unity); normalize(unity,unity); cross(unitx,unity,unitz); } this.getViewMatrix = function (){ return new Float32Array( this.getViewMatrixArray() ); } this.getViewMatrixArray = function() { return [ unitx[0], unity[0], unitz[0], 0, unitx[1], unity[1], unitz[1], 0, unitx[2], unity[2], unitz[2], 0, 0, 0, -viewZ, 1 ]; } this.getViewDistance = function() { return viewZ; } this.setViewDistance = function(viewDistance) { viewZ = viewDistance; } function applyTransvection(e1, e2) { // rotate vector e1 onto e2 function reflectInAxis(axis, source, destination) { var s = 2 * (axis[0] * source[0] + axis[1] * source[1] + axis[2] * source[2]); destination[0] = s*axis[0] - source[0]; destination[1] = s*axis[1] - source[1]; destination[2] = s*axis[2] - source[2]; } normalize(e1,e1); normalize(e2,e2); var e = [0,0,0]; add(e,e1,e2); normalize(e,e); var temp = [0,0,0]; reflectInAxis(e,unitz,temp); reflectInAxis(e1,temp,unitz); reflectInAxis(e,unitx,temp); reflectInAxis(e1,temp,unitx); reflectInAxis(e,unity,temp); reflectInAxis(e1,temp,unity); } var centerX = canvas.width/2; var centerY = canvas.height/2; var radius = Math.min(centerX,centerY); var radius2 = radius*radius; var prevx,prevy; var prevRay = [0,0,0]; var dragging = false; function doMouseDown(evt) { if (dragging) return; dragging = true; document.addEventListener("mousemove", doMouseDrag, false); document.addEventListener("mouseup", doMouseUp, false); var box = canvas.getBoundingClientRect(); prevx = window.pageXOffset + evt.clientX - box.left; prevy = window.pageYOffset + evt.clientY - box.top; } function doMouseDrag(evt) { if (!dragging) return; var box = canvas.getBoundingClientRect(); console.log(">>> DEBUG >>> Mouse X:" + evt.clientX + ", Y:" + evt.clientY); var x = window.pageXOffset + evt.clientX - box.left; var y = window.pageYOffset + evt.clientY - box.top; var ray1 = toRay(prevx,prevy); var ray2 = toRay(x,y); applyTransvection(ray1,ray2); prevx = x; prevy = y; if (callback) { callback(); } } function doMouseUp(evt) { if (dragging) { document.removeEventListener("mousemove", doMouseDrag, false); document.removeEventListener("mouseup", doMouseUp, false); dragging = false; } } function toRay(x,y) { var dx = x - centerX; var dy = centerY - y; var vx = dx * unitx[0] + dy * unity[0]; // The mouse point as a vector in the image plane. var vy = dx * unitx[1] + dy * unity[1]; var vz = dx * unitx[2] + dy * unity[2]; var dist2 = vx*vx + vy*vy + vz*vz; if (dist2 > radius2) { return [vx,vy,vz]; } else { var z = Math.sqrt(radius2 - dist2); return [vx+z*unitz[0], vy+z*unitz[1], vz+z*unitz[2]]; } } function dot(v,w) { return v[0]*w[0] + v[1]*w[1] + v[2]*w[2]; } function length(v) { return Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } function normalize(v,w) { var d = length(w); v[0] = w[0]/d; v[1] = w[1]/d; v[2] = w[2]/d; } function copy(v,w) { v[0] = w[0]; v[1] = w[1]; v[2] = w[2]; } function add(sum,v,w) { sum[0] = v[0] + w[0]; sum[1] = v[1] + w[1]; sum[2] = v[2] + w[2]; } function subtract(dif,v,w) { dif[0] = v[0] - w[0]; dif[1] = v[1] - w[1]; dif[2] = v[2] - w[2]; } function scale(ans,v,num) { ans[0] = v[0] * num; ans[1] = v[1] * num; ans[2] = v[2] * num; } function cross(c,v,w) { var x = v[1]*w[2] - v[2]*w[1]; var y = v[2]*w[0] - v[0]*w[2]; var z = v[0]*w[1] - v[1]*w[0]; c[0] = x; c[1] = y; c[2] = z; } this.setView(viewDirectionVector, viewUpVector, viewDistance); canvas.addEventListener("mousedown", doMouseDown, false); }
JavaScript
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
JavaScript
/** * To debug: * Prompt> set HTTP_PROXY=http://www-proxy.us.oracle.com:80 * Prompt> npm install -g node-inspector * Prompt> node-inspector * * From another console: * Prompt> node --debug server.js */ "use strict"; process.title = 'node-leap-motion'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) { // Static resource var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) { console.log("Read resource content:\n---------------\n" + data + "\n--------------"); } var contentType = "text/html"; if (resource.endsWith(".css")) { contentType = "text/css"; } else if (resource.endsWith(".html")) { contentType = "text/html"; } else if (resource.endsWith(".xml")) { contentType = "text/xml"; } else if (resource.endsWith(".js")) { contentType = "text/javascript"; } else if (resource.endsWith(".jpg")) { contentType = "image/jpg"; } else if (resource.endsWith(".gif")) { contentType = "image/gif"; } else if (resource.endsWith(".png")) { contentType = "image/png"; } res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else { res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. } }); } else if (req.url.startsWith("/verbose=")) { if (req.method === "GET") { verbose = (req.url.substring("/verbose=".length) === 'on'); res.end(JSON.stringify({verbose: verbose?'on':'off'})); } } else if (req.url == "/") { if (req.method === "POST") { var data = ""; if (verbose) { console.log("---- Headers ----"); for (var item in req.headers) { console.log(item + ": " + req.headers[item]); } console.log("-----------------"); } req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = []; /** * Helper function for escaping input strings */ var htmlEntities = function(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }; /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text // console.log((new Date()) + ' Received Message: ' + message.utf8Data); try { var mess = JSON.parse(message.utf8Data); console.log('P:' + mess.pitch + ', R:' + mess.roll + ', Y:' + mess.yaw); } catch (err) { console.log(">>> ERR >>> " + err + ' in ' + message.utf8Data); } //text: htmlEntities(message.utf8Data) var obj = { time: (new Date()).getTime(), text: message.utf8Data }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type: 'message', data: obj }); for (var i=0; i<clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(code) { // Close var nb = clients.length; for (var i=0; i<clients.length; i++) { if (clients[i] === connection) { clients.splice(i, 1); break; } } if (verbose) { console.log("We have (" + nb + "->) " + clients.length + " client(s) connected."); } }); });
JavaScript
// App specific code var nbMessReceived = 0; var init = function() { ws.onopen = function() { try { var text; try { text = 'Message:'; } catch (err) { text = '<small>Connected</small>'; } promptFld.innerHTML = text; if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='blue'>" + ' Connection opened.' + "</font>"); statusFld.scrollTop = statusFld.scrollHeight; nbMessReceived++; } catch (err) {} }; ws.onerror = function(error) { if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='red'>" + error.err + "</font>"); statusFld.scrollTop = statusFld.scrollHeight; nbMessReceived++; }; ws.onmessage = function(message) // message/event { var json = {}; if (typeof(message.data) === 'string') { try { json = JSON.parse(message.data); } catch (e) { console.log(e); console.log('This doesn\'t look like a valid JSON: ' + message.data); } } //console.log("Split: type=" + json.type + ", data=" + json.data); if (json.type !== undefined && json.type === 'message' && typeof(json.data.text) === 'string') // it's a single message, text { var dt = new Date(); /** * Add message to the chat window */ var existing = contentFld.innerHTML; // Content already there var toDisplay = ""; try { toDisplay = json.data.text; } catch (err) {} contentFld.innerHTML = existing + ('At ' + + (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':' + (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) + ': ' + toDisplay + '<br>'); contentFld.scrollTop = contentFld.scrollHeight; } else // Unexpected { var payload = {}; } }; ws.onclose = function() { if (nbMessReceived === 0) statusFld.innerHTML = ""; statusFld.innerHTML += ((nbMessReceived === 0?"":"<br>") + "<small>" + (new Date()).format("d-M-Y H:i:s._ Z") + "</small>:<font color='blue'>" + ' Connection closed' + "</font>"); promptFld.innerHTML = 'Connection closed'; }; }; var send = function(mess) { ws.send(mess); }; var getClass = function(obj) { if (obj && typeof obj === 'object' && Object.prototype.toString.call(obj) !== '[object Array]' && obj.constructor) { var arr = obj.constructor.toString().match(/function\s*(\w+)/); if (arr && arr.length === 2) { return arr[1]; } } return false; }; // Date formatting // Provide month names Date.prototype.getMonthName = function() { var month_names = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; return month_names[this.getMonth()]; }; // Provide month abbreviation Date.prototype.getMonthAbbr = function() { var month_abbrs = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; return month_abbrs[this.getMonth()]; }; // Provide full day of week name Date.prototype.getDayFull = function() { var days_full = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; return days_full[this.getDay()]; }; // Provide full day of week name Date.prototype.getDayAbbr = function() { var days_abbr = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat' ]; return days_abbr[this.getDay()]; }; // Provide the day of year 1-365 Date.prototype.getDayOfYear = function() { var onejan = new Date(this.getFullYear(),0,1); return Math.ceil((this - onejan) / 86400000); }; // Provide the day suffix (st,nd,rd,th) Date.prototype.getDaySuffix = function() { var d = this.getDate(); var sfx = ["th", "st", "nd", "rd"]; var val = d % 100; return (sfx[(val-20)%10] || sfx[val] || sfx[0]); }; // Provide Week of Year Date.prototype.getWeekOfYear = function() { var onejan = new Date(this.getFullYear(),0,1); return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7); }; // Provide if it is a leap year or not Date.prototype.isLeapYear = function() { var yr = this.getFullYear(); if ((parseInt(yr) % 4) === 0) { if (parseInt(yr) % 100 === 0) { if (parseInt(yr) % 400 !== 0) return false; if (parseInt(yr) % 400 === 0) return true; } if (parseInt(yr) % 100 !== 0) return true; } if ((parseInt(yr) % 4) !== 0) return false; }; // Provide Number of Days in a given month Date.prototype.getMonthDayCount = function() { var month_day_counts = [ 31, this.isLeapYear() ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; return month_day_counts[this.getMonth()]; }; // format provided date into this.format format Date.prototype.format = function(dateFormat) { // break apart format string into array of characters dateFormat = dateFormat.split(""); var date = this.getDate(), month = this.getMonth(), hours = this.getHours(), minutes = this.getMinutes(), seconds = this.getSeconds(), milli = this.getTime() % 1000, tzOffset = - (this.getTimezoneOffset() / 60); var lpad = function(s, w, len) { var str = s; while (str.length < len) str = w + str; return str; }; // get all date properties ( based on PHP date object functionality ) var date_props = { d: date < 10 ? '0'+date : date, D: this.getDayAbbr(), j: this.getDate(), l: this.getDayFull(), S: this.getDaySuffix(), w: this.getDay(), z: this.getDayOfYear(), W: this.getWeekOfYear(), F: this.getMonthName(), m: month < 10 ? '0'+(month+1) : month+1, M: this.getMonthAbbr(), n: month+1, t: this.getMonthDayCount(), L: this.isLeapYear() ? '1' : '0', Y: this.getFullYear(), y: this.getFullYear()+''.substring(2,4), a: hours > 12 ? 'pm' : 'am', A: hours > 12 ? 'PM' : 'AM', g: hours % 12 > 0 ? hours % 12 : 12, G: hours > 0 ? hours : "12", h: hours % 12 > 0 ? hours % 12 : 12, H: hours < 10 ? '0' + hours : hours, i: minutes < 10 ? '0' + minutes : minutes, s: seconds < 10 ? '0' + seconds : seconds, Z: "UTC" + (tzOffset > 0 ?"+":"") + tzOffset, _: lpad(milli, '0', 3) }; // loop through format array of characters and add matching data else add the format character (:,/, etc.) var date_string = ""; for (var i=0; i<dateFormat.length; i++) { var f = dateFormat[i]; if (f.match(/[a-zA-Z|_]/g)) date_string += date_props[f] ? date_props[f] : ''; else date_string += f; } return date_string; };
JavaScript
"use strict"; var connection; (function () { var ws = window.WebSocket || window.MozWebSocket; if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function() { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; var valuePitch = leapmotion.pitch; var valueYaw = leapmotion.yaw; angularSpeedAroundZ = valueYaw * 0.01; // yaw angularSpeedAroundY = valueRoll * 0.01; // roll angularSpeedAroundX = valuePitch * 0.01; // pitch } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping every 3 sec })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess){ var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
"use strict"; var connection; (function () { var ws = window.WebSocket || window.MozWebSocket; if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function() { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; var valuePitch = leapmotion.pitch; var valueYaw = leapmotion.yaw; displayRoll.setValue(valueRoll); displayPitch.setValue(valuePitch); displayYaw.setValue(valueYaw); } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping every 3 sec })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess){ var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
"use strict"; var connection; (function () { var ws = window.WebSocket || window.MozWebSocket; if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function() { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') { try { var leapmotion = JSON.parse(json.data.text); var valueRoll = leapmotion.roll; // var valuePitch = leapmotion.pitch; var valueYaw = -leapmotion.yaw; displayPitch.setValue(valueRoll); displayYaw.setValue(valueYaw); } catch (err) { console.log("Err:" + err + " for " + json.data.text); } } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping every 3 sec })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess){ var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
# Joystick # #!/bin/bash PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../AdafruitI2C/classes CP=$CP:../ADC/classes #CP=$CP:../SevenSegDisplay/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar # sudo java -cp $CP -Dverbose=true raspisamples.PanTiltJoyStick
JavaScript
"use strict"; var connection; (function () { // if user is running mozilla then use it's built-in WebSocket // window.WebSocket = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back var ws = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back // if browser doesn't support WebSocket, just show some notification and exit // if (!window.WebSocket) if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); // TODO Fallback return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function () { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; connection.onmessage = function (message) { console.log('onmessage:' + JSON.stringify(message.data)); var data = JSON.parse(message.data); var value = data.data.text.replace(/&quot;/g, '"'); var val = JSON.parse(value); displayValue.setValue(val.value); }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { console.log("Sending:" + msg); if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess) { try { var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; } catch (err) { console.log(mess); } }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
JavaScript
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ "use strict"; /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. * * Static requests must be prefixed with /data/, like in http://machine:9876/data/chat.html */ // Optional. You will see this name in eg. 'ps' or 'top' command process.title = 'node-pwm'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) == 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) // Static resource { var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) console.log("Read resource content:\n---------------\n" + data + "\n--------------"); var contentType = "text/html"; if (resource.endsWith(".css")) contentType = "text/css"; else if (resource.endsWith(".html")) contentType = "text/html"; else if (resource.endsWith(".xml")) contentType = "text/xml"; else if (resource.endsWith(".js")) contentType = "text/javascript"; else if (resource.endsWith(".jpg")) contentType = "image/jpg"; else if (resource.endsWith(".gif")) contentType = "image/gif"; else if (resource.endsWith(".png")) contentType = "image/png"; res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. }); } else if (req.url == "/") { if (req.method === "POST") { var data = ""; console.log("---- Headers ----"); for(var item in req.headers) console.log(item + ": " + req.headers[item]); console.log("-----------------"); req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); if (req.headers["tyrus-ws-attempt"] !== "undefined" && req.headers["tyrus-ws-attempt"] === "Hand-Shake") // List of the supoprted protocols { console.log(" ... writing headers..."); res.writeHead(200, {'Content-Type': 'application/json', 'tyrus-fallback-transports': 'WebSocket,MozWebSocket,XMLHttpRequest,FedEx,UPS', 'tyrus-connection-id': guid() }); } else res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); console.log("Connect to [http://localhost:9876/data/display.html]"); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type:'message', data: obj }); console.log("Rebroadcasting: " + json); for (var i=0; i < clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(connection) { // Close }); }); function s4() { return (Math.floor((1 + Math.random()) * 0x10000) & 0xffff) .toString(16); // .substring(1); }; function guid() { return s4() + "." + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + "." + s4() + "." + s4(); }
JavaScript
"use strict"; var connection; (function () { // if user is running mozilla then use it's built-in WebSocket // window.WebSocket = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back var ws = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back // if browser doesn't support WebSocket, just show some notification and exit // if (!window.WebSocket) if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); // TODO Fallback return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function () { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') // TODO Get rid of the other types above { // it's a single message var value = parseInt(json.data.text); // console.log('Setting value to ' + value); displayValue.setValue(value); } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess) { var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
JavaScript
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ "use strict"; /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. * * Static requests must be prefixed with /data/, like in http://machine:9876/data/chat.html */ // Optional. You will see this name in eg. 'ps' or 'top' command process.title = 'node-chat'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) == 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) // Static resource { var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) console.log("Read resource content:\n---------------\n" + data + "\n--------------"); var contentType = "text/html"; if (resource.endsWith(".css")) contentType = "text/css"; else if (resource.endsWith(".html")) contentType = "text/html"; else if (resource.endsWith(".xml")) contentType = "text/xml"; else if (resource.endsWith(".js")) contentType = "text/javascript"; else if (resource.endsWith(".jpg")) contentType = "image/jpg"; else if (resource.endsWith(".gif")) contentType = "image/gif"; else if (resource.endsWith(".png")) contentType = "image/png"; res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. }); } else if (req.url == "/") { if (req.method === "POST") { var data = ""; console.log("---- Headers ----"); for(var item in req.headers) console.log(item + ": " + req.headers[item]); console.log("-----------------"); req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); if (req.headers["tyrus-ws-attempt"] !== "undefined" && req.headers["tyrus-ws-attempt"] === "Hand-Shake") // List of the supoprted protocols { console.log(" ... writing headers..."); res.writeHead(200, {'Content-Type': 'application/json', 'tyrus-fallback-transports': 'WebSocket,MozWebSocket,XMLHttpRequest,FedEx,UPS', 'tyrus-connection-id': guid() }); } else res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type:'message', data: obj }); for (var i=0; i < clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(connection) { // Close }); }); function s4() { return (Math.floor((1 + Math.random()) * 0x10000) & 0xffff) .toString(16); // .substring(1); }; function guid() { return s4() + "." + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + "." + s4() + "." + s4(); }
JavaScript
var set = function(device, state) { request(device, state); }; var SERVICE_ROOT = "/relay-access"; var request = function(pin, status) { var restRequest = SERVICE_ROOT + "?dev=" + pin + "&status=" + status; var ajax = new XMLHttpRequest(); ajax.open("GET", restRequest, false); ajax.send(null); };
JavaScript
"use strict"; var connection; (function () { var ws = window.WebSocket || window.MozWebSocket; if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function() { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; // most important part - incoming messages connection.onmessage = function (message) { // console.log('onmessage:' + message); // try to parse JSON message. try { var json = JSON.parse(message.data); } catch (e) { displayMessage('This doesn\'t look like a valid JSON: ' + message.data); return; } // NOTE: if you're not sure about the JSON structure // check the server source code above if (json.type === 'message') { // it's a single message var value = parseInt(json.data.text); // console.log('Setting value to ' + value); displayValue.setValue(value); } else { displayMessage('Hmm..., I\'ve never seen JSON like this: ' + json); } }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess){ var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; }; var resetStatus = function() { statusFld.innerHTML = ""; };
JavaScript
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
JavaScript
/** * To debug: * Prompt> set HTTP_PROXY=http://www-proxy.us.oracle.com:80 * Prompt> npm install -g node-inspector * Prompt> node-inspector * * From another console: * Prompt> node --debug server.js */ "use strict"; process.title = 'node-oil-detector'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) { // Static resource var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) { console.log("Read resource content:\n---------------\n" + data + "\n--------------"); } var contentType = "text/html"; if (resource.endsWith(".css")) { contentType = "text/css"; } else if (resource.endsWith(".html")) { contentType = "text/html"; } else if (resource.endsWith(".xml")) { contentType = "text/xml"; } else if (resource.endsWith(".js")) { contentType = "text/javascript"; } else if (resource.endsWith(".jpg")) { contentType = "image/jpg"; } else if (resource.endsWith(".gif")) { contentType = "image/gif"; } else if (resource.endsWith(".png")) { contentType = "image/png"; } res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else { res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. } }); } else if (req.url.startsWith("/verbose=")) { if (req.method === "GET") { verbose = (req.url.substring("/verbose=".length) === 'on'); res.end(JSON.stringify({verbose: verbose?'on':'off'})); } } else if (req.url == "/") { if (req.method === "POST") { var data = ""; if (verbose) { console.log("---- Headers ----"); for (var item in req.headers) { console.log(item + ": " + req.headers[item]); } console.log("-----------------"); } req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ var htmlEntities = function(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }; /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type: 'message', data: obj }); for (var i=0; i<clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(code) { // Close var nb = clients.length; for (var i=0; i<clients.length; i++) { if (clients[i] === connection) { clients.splice(i, 1); break; } } if (verbose) { console.log("We have (" + nb + "->) " + clients.length + " client(s) connected."); } }); });
JavaScript
/* ScriptName: channeltab.js Author: Akai Website: http://nhacuato.com/ */ $(document).ready(function() { function ncttabs(rel) { $channelcontent.hide(); $channeltab.removeClass("selected"); var id = rel.attr("rel"); $("#" + id).show(); rel.addClass("selected"); } $channeltab = $(".container #main .channel .tabs a"); $channelcontent = $(".container #main .channel .main .tab-content"); $(".container #main .channel .main .tab-content:not(:first)").hide(); $channeltab.click(function() { ncttabs($(this)); }); $channelcontent.first().show(); });
JavaScript
$(document).ready(function() { $channelr = $(".container #channelr"); $channelm = $(".container #channelr #channel"); $channelb = $(".container #channelr #channelb"); $channelg = $(".container #channelg"); $channelv = 0; function channelh() { if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $channelm.css({zIndex: 1}).fadeOut(); else { setTimeout(function() { $channelr.css({zIndex: -1}); }, 100); setTimeout(function() { $channelm.css({zIndex: -1}); }, 200); setTimeout(function() { $channelr.css({zIndex: ""}); }, 300); } $channelr.animate({marginTop: -$channelm.height() + 2}, 500); $channelb.css({backgroundImage: "url(http://123tivi.googlecode.com/svn/123tv/images/channelu.png)"}); $channelv = 0; } function channels() { if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") { setTimeout(function() { $channelm.css({zIndex: -1}).fadeIn(); }, 200); setTimeout(function() { $channelm.css({zIndex: 1}); }, 500); } else { setTimeout(function() { $channelr.css({zIndex: -1}); }, 100); setTimeout(function() { $channelm.css({zIndex: 0}); }, 200); setTimeout(function() { $channelr.css({zIndex: 0}); }, 300); } $channelr.animate({marginTop: -$channelr.height() * 2}, 500); $channelb.css({backgroundImage: "url(http://123tivi.googlecode.com/svn/123tv/images/channeld.png)"}); $channelv = 1; } function nctchanneli(rel) { if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $(".container #channelg:not(:first)").hide(); $channelg.hide(); $(".container #channelr #channel a").removeClass("selected"); var id = rel.attr("rel"); $("." + id).show(); rel.addClass("selected"); } $channelb.click(function() { if ($channelv == 1) channelh(); else channels(); }); $channelr.css({width: $channelg.width()}); if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $channelm.before("<div style=\"height: 1px; background: #ff4e00; width:960px;\"></div>").hide(); else $channelm.css({zIndex: -1}).before("<div style=\"height: 1px; background: #ff4e00; width:960px;\"></div>"); $(".container #channelg:not(:first)").hide(); $(".container #channelr #channel a").click(function() { nctchanneli($(this)); }); $channelg.first().show(); });
JavaScript
/************************************************************************/ /* Rainbow Links Version 1.03 (2003.9.20) */ /* Script updated by Dynamicdrive.com for IE6 */ /* Copyright (C) 1999-2001 TAKANASHI Mizuki */ /* takanasi@hamal.freemail.ne.jp */ /*----------------------------------------------------------------------*/ /* Read it somehow even if my English text is a little wrong! ;-) */ /* */ /* Usage: */ /* Insert '<script src="rainbow.js"></script>' into the BODY section, */ /* right after the BODY tag itself, before anything else. */ /* You don't need to add "onMouseover" and "onMouseout" attributes!! */ /* */ /* If you'd like to add effect to other texts(not link texts), then */ /* add 'onmouseover="doRainbow(this);"' and */ /* 'onmouseout="stopRainbow();"' to the target tags. */ /* */ /* This Script works with IE4,Netscape6,Mozilla browser and above only, */ /* but no error occurs on other browsers. */ /************************************************************************/ //////////////////////////////////////////////////////////////////// // Setting var rate = 20; // Increase amount(The degree of the transmutation) //////////////////////////////////////////////////////////////////// // Main routine if (document.getElementById) window.onerror=new Function("return true") var objActive; // The object which event occured in var act = 0; // Flag during the action var elmH = 0; // Hue var elmS = 128; // Saturation var elmV = 255; // Value var clrOrg; // A color before the change var TimerID; // Timer ID if (document.all) { document.onmouseover = doRainbowAnchor; document.onmouseout = stopRainbowAnchor; } else if (document.getElementById) { document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT); document.onmouseover = Mozilla_doRainbowAnchor; document.onmouseout = Mozilla_stopRainbowAnchor; } //============================================================================= // doRainbow // This function begins to change a color. //============================================================================= function doRainbow(obj) { if (act == 0) { act = 1; if (obj) objActive = obj; else objActive = event.srcElement; clrOrg = objActive.style.color; TimerID = setInterval("ChangeColor()",100); } } //============================================================================= // stopRainbow // This function stops to change a color. //============================================================================= function stopRainbow() { if (act) { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } //============================================================================= // doRainbowAnchor // This function begins to change a color. (of a anchor, automatically) //============================================================================= function doRainbowAnchor() { if (act == 0) { var obj = event.srcElement; while (obj.tagName != 'A' && obj.tagName != 'BODY') { obj = obj.parentElement; if (obj.tagName == 'A' || obj.tagName == 'BODY') break; } if (obj.tagName == 'A' && obj.href != '') { objActive = obj; act = 1; clrOrg = objActive.style.color; TimerID = setInterval("ChangeColor()",100); } } } //============================================================================= // stopRainbowAnchor // This function stops to change a color. (of a anchor, automatically) //============================================================================= function stopRainbowAnchor() { if (act) { if (objActive.tagName == 'A') { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } } //============================================================================= // Mozilla_doRainbowAnchor(for Netscape6 and Mozilla browser) // This function begins to change a color. (of a anchor, automatically) //============================================================================= function Mozilla_doRainbowAnchor(e) { if (act == 0) { obj = e.target; while (obj.nodeName != 'A' && obj.nodeName != 'BODY') { obj = obj.parentNode; if (obj.nodeName == 'A' || obj.nodeName == 'BODY') break; } if (obj.nodeName == 'A' && obj.href != '') { objActive = obj; act = 1; clrOrg = obj.style.color; TimerID = setInterval("ChangeColor()",100); } } } //============================================================================= // Mozilla_stopRainbowAnchor(for Netscape6 and Mozilla browser) // This function stops to change a color. (of a anchor, automatically) //============================================================================= function Mozilla_stopRainbowAnchor(e) { if (act) { if (objActive.nodeName == 'A') { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } } //============================================================================= // Change Color // This function changes a color actually. //============================================================================= function ChangeColor() { objActive.style.color = makeColor(); } //============================================================================= // makeColor // This function makes rainbow colors. //============================================================================= function makeColor() { // Don't you think Color Gamut to look like Rainbow? // HSVtoRGB if (elmS == 0) { elmR = elmV; elmG = elmV; elmB = elmV; } else { t1 = elmV; t2 = (255 - elmS) * elmV / 255; t3 = elmH % 30; t3 = (t1 - t2) * t3 / 30; if (elmH < 60) { elmR = t1; elmB = t2; elmG = t2 + t3; } else if (elmH < 120) { elmG = t1; elmB = t2; elmR = t1 - t3; } else if (elmH < 180) { elmG = t1; elmR = t2; elmB = t2 + t3; } else if (elmH < 240) { elmB = t1; elmR = t2; elmG = t1 - t3; } else if (elmH < 300) { elmB = t1; elmG = t2; elmR = t2 + t3; } else if (elmH < 360) { elmR = t1; elmG = t2; elmB = t1 - t3; } else { elmR = 0; elmG = 0; elmB = 0; } } elmR = Math.floor(elmR).toString(16); elmG = Math.floor(elmG).toString(16); elmB = Math.floor(elmB).toString(16); if (elmR.length == 1) elmR = "0" + elmR; if (elmG.length == 1) elmG = "0" + elmG; if (elmB.length == 1) elmB = "0" + elmB; elmH = elmH + rate; if (elmH >= 360) elmH = 0; return '#' + elmR + elmG + elmB; }
JavaScript
function hm_play(linkxem) { if (linkxem.indexOf('id="embed_tv"')!=-1) { var play = linkxem; } else if (linkxem.indexOf("http://")!=-1) { if (linkxem.indexOf("http://tv-msn.com")!=-1 || linkxem.indexOf("http://www2.k-tv.at")!=-1 || linkxem.indexOf("http://vtc.com.vn")!=-1 || linkxem.indexOf("http://tv24.vn")!=-1 || linkxem.indexOf("http://itv.vtc.vn/")!=-1 || linkxem.indexOf("http://megafun.vn/")!=-1 || linkxem.indexOf("http://farm.vtc.vn/")!=-1 || linkxem.indexOf("http://www.htvc.vn/")!=-1 || linkxem.indexOf("http://www.vpoptv.com")!=-1 ) { var play = '<iframe src="'+linkxem+'" scrolling="no" frameborder="0" width="100%" height="100%"></iframe>' } else if (linkxem.indexOf("http://static.livestream.com")!=-1) { var play = '<embed type="application/x-shockwave-flash" src="'+linkxem+'" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" width="100%" height="100%"/>'; } else if (linkxem.indexOf("http://tikilive.com/public/")!=-1) { var play = '<embed allowFullScreen="true" src="'+linkxem+'&advertisment=0&showChat=0&pwidth=100%&pheight=100%" type="application/x-shockwave-flash" width="100%" height="100%" allowScriptAccess="always"></embed>'; } else if (linkxem.indexOf("file=http://")!=-1) { var play = '<embed type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" allowfullscreen="true" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf?'+linkxem+'&provider=http%3A%2F%2Fmegafun.vn%2Fcommon%2Fplayer%2FadaptiveProvider.swf&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip" width="100%" height="100%"/>'; } else { var play = '<EMBED EnableContextMenu="0" type="application/x-mplayer2" showstatusbar="1" SRC="'+linkxem+'" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" width="100%" height="100%">'; } } else if (linkxem.indexOf("rtmp://")!=-1 || linkxem.indexOf("&file=")!=-1 || linkxem.indexOf("&amp;file=")!=-1) { var play = '<embed type="application/x-shockwave-flash" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" flashvars="streamer='+linkxem+'&type=rtmp&fullscreen=true&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip&image=images/logo.png" width="100%" height="100%"/>'; } else if (linkxem.indexOf("file=")!=-1) { var play = '<embed type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" allowfullscreen="true" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf?'+linkxem+'&provider=http%3A%2F%2Fmegafun.vn%2Fcommon%2Fplayer%2FadaptiveProvider.swf&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip" width="100%" height="100%"/>'; } else if (linkxem.indexOf("mms://")!=-1 || linkxem.indexOf("rtsp://")!=-1) { var play = '<EMBED EnableContextMenu="0" type="application/x-mplayer2" SRC="'+linkxem+'" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" showstatusbar="1" width="100%" height="100%"/>'; } else { var play='<div style="text-align:center;margin-top:30px;"><b>Rất tiếc, Server bạn chọn bị lỗi! Vui lòng chọn Server khác!</b><br><img src="https://123tivi.googlecode.com/svn/trunk/123tv/alert.png" width="300" height="250px"/></div>'; } document.getElementById("HMPlayers").innerHTML = '<div id="HMPlayer">'+play+'</div>'; } var a = document.getElementById("Blog1").innerHTML; var a=a.replace(/\[m\]/gi,"<span style='display:none;' id='linkxem'>"); var a=a.replace(/\[\/m\]/gi,"</span>"); var a=a.replace(/\[st\]/gi,"<span style='display:none;'>"); var a=a.replace(/\[\/st\]/gi,"</span>"); document.getElementById("Blog1").innerHTML =a; var b=document.getElementById('linkxem').innerHTML; var h = b.split("|"); var l = h.length; var link = location.href; if (link.indexOf("?p=")!=-1) { var ser = link.substring(link.indexOf("?p=")+3,link.indexOf("?p=")+4); if (ser=="") { hm_play(h[0]); } else { if (h[ser]===undefined || h[ser]==""){ document.getElementById("HMPlayers").innerHTML = '<div id="HMPlayer"><div style="text-align:center;margin-top:30px;"><b>Server không tồn tại! Xin vui lòng chọn server khác!</b><br><img src="https://123tivi.googlecode.com/svn/trunk/123tv/alert.png" width="300" height="250px"/></div></div>'; } else { hm_play(h[ser]); } } } else { hm_play(h[0]); } document.write ('<div id="list_ser" style="display:none;">'); for (i=0;i<l;i++) { var k= i+1; if (h[i]!="") { if (i==0) { var server = '<a id="ser_'+i+'" href="?p='+i+'" class="selected">'+k+'</a>'; } else { var server = '<a id="ser_'+i+'" href="?p='+i+'">'+k+'</a>'; } document.write (server); } } document.write ('</div>'); if (link.indexOf("?p=")!=-1) { if (ser!="" && ser!="0") { if (h[ser]===undefined) { $('#ser_0').removeClass('selected'); } else { $('#ser_0').removeClass('selected'); $('#ser_'+ser).addClass('selected'); } } } var list_server = document.getElementById("list_ser").innerHTML; document.getElementById("list_server").innerHTML = '<span style="float:left;margin-right:5px;font-size:14px;font-weight:bold;">Server: </span>'+list_server; if (link.indexOf("?p=")==-1) { $("#ser_0").removeAttr("href"); } else { if (ser=="" || ser=="0") { $("#ser_0").removeAttr("href"); } else { $('#ser_'+ser).removeAttr("href"); } }
JavaScript
var titles=new Array();var titlesNum=0;var urls=new Array();var time=new Array();var titleh=new Array(); function related_results_labels(c){ for(var b=0;b<c.feed.entry.length;b++){ var d=c.feed.entry[b]; titles[titlesNum]=d.title.$t; s=d.content.$t; titleh[titlesNum]=s.substring(s.indexOf("[st]")+4,s.indexOf("[/st]")); for(var a=0;a<d.link.length;a++){ if(d.link[a].rel=="alternate"){ urls[titlesNum]=d.link[a].href; time[titlesNum]=d.published.$t; titlesNum++;break}}}} function removeRelatedDuplicates(){ var b=new Array(0); var c=new Array(0); var m=new Array(0); e=new Array(0); for(var a=0;a<urls.length;a++){ if(!contains(b,urls[a])){ b.length+=1; b[b.length-1]=urls[a]; m.length+=1; m[m.length-1]=titleh[a]; c.length+=1; c[c.length-1]=titles[a]; e.length+=1; e[e.length-1]=time[a]; } } titles=c; urls=b;time=e;titleh=m; } function contains(b,d){ for(var c=0;c<b.length;c++){if(b[c]==d){return true}}return false} function printRelatedLabels(a){ var y=a.indexOf('?m=0'); if(y!=-1){a=a.replace(/\?m=0/g,'')} for(var b=0;b<urls.length;b++){ if(urls[b]==a){ urls.splice(b,1); titles.splice(b,1); titleh.splice(b,1); time.splice(b,1)}} var c=Math.floor((titles.length-1)*Math.random()); var b=0; if(titles.length==0){document.write("<li>Không có bài viết liên quan</li>")} else{ while(b<titles.length&&b<20&&b<maxresults){ if(y!=-1){ urls[c]=urls[c]+'?m=0' } document.write('<a href="'+urls[c]+'" title="'+titles[c]+'">'+titleh[c]+"</a>"); if(c<titles.length-1){c++} else{c=0}b++ } } urls.splice(0,urls.length);titles.splice(0,titles.length)};
JavaScript
imgr = new Array(); imgr[0] = "https://lh3.googleusercontent.com/-IBkOgk0LW6c/TqulPrgd6RI/AAAAAAAAAmg/VHnAiJCR4jc/s800/no_img.jpg"; showRandomImg = true; aBold = true; summaryPost = 70; summaryTitle = 25; numposts = 100; 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 gettv(json) { j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0; img = new Array(); if (numposts <= json.feed.entry.length) { maxpost = numposts; } else { maxpost=json.feed.entry.length; } for (var i = 0; i < maxpost; 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 ; if (i>=0 && i <=32) { var trtd = '<div class="gettv"><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;"><img alt="'+posttitle+'" style="border:1px solid #CBCBCB;width:116px;height:130px;padding: 5px;background: transparent;" src="'+img[i]+'"/></a><br/><span style="color: #06C;font-size: 12px;font-weight: bold;">'+s+'</span><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;">'+posttitle+'</a></div>'; document.write(trtd); } j++; } document.write('<div style="clear: both;"></div>'); }
JavaScript
imgr = new Array(); imgr[0] = "https://lh3.googleusercontent.com/-IBkOgk0LW6c/TqulPrgd6RI/AAAAAAAAAmg/VHnAiJCR4jc/s800/no_img.jpg"; showRandomImg = true; aBold = true; summaryPost = 70; summaryTitle = 25; numposts = 100; 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 gettv(json) { j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0; img = new Array(); if (numposts <= json.feed.entry.length) { maxpost = numposts; } else { maxpost=json.feed.entry.length; } for (var i = 0; i < maxpost; 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 ; if (i>=0 && i <=32) { var trtd = '<div class="gettv"><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;"><img alt="'+posttitle+'" style="border:1px solid #CBCBCB;width:116px;height:130px;padding: 5px;background: transparent;" src="'+img[i]+'"/></a><br/><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;">'+posttitle+'</a></div>'; document.write(trtd); } j++; } document.write('<div style="clear: both;"></div>'); }
JavaScript
function postlabel(json) { for (var i = 0; i < numposts; i++) { var entry = json.feed.entry[i]; var posttitle = entry.title.$t; var posturl;if (i == json.feed.entry.length) break; for (var k = 0; k < entry.link.length;k++){ if(entry.link[k].rel=='replies'&&entry.link[k].type=='text/html'){ var commenttext=entry.link[k].title; var commenturl=entry.link[k].href; } if (entry.link[k].rel == 'alternate') { posturl = entry.link[k].href;break; } } if("content"in entry){ var postcontent=entry.content.$t; } var vidid = postcontent.substring(postcontent.indexOf("http://www.youtube.com/watch?v=")+31,postcontent.indexOf("endofvid")); try {thumburl='http://i2.ytimg.com/vi/'+vidid+'/default.jpg';}catch (error){ thumburl='http://1.bp.blogspot.com/_u4gySN2ZgqE/SmWGbEU9sgI/AAAAAAAAAhc/1C_WxeHhfoA/s800/noimagethumb.png'; } var postdate = entry.published.$t; var cdyear = postdate.substring(0,4); var cdmonth = postdate.substring(5,7); var cdday = postdate.substring(8,10); var monthnames = new Array(); monthnames[1] = "Jan";monthnames[2] = "Feb";monthnames[3] = "Mar";monthnames[4] = "Apr";monthnames[5] = "May";monthnames[6] = "Jun";monthnames[7] = "Jul";monthnames[8] = "Aug";monthnames[9] = "Sep";monthnames[10] = "Oct";monthnames[11] = "Nov";monthnames[12] = "Dec"; document.write('<div class="content-item"><a href="'+ posturl + '" class="video-img" title="'+posttitle+'"><img width="128px" height="72px" src="'+thumburl+'"/></a><div class="meta"><a title="'+posttitle+'" href="'+posturl+'" target ="_top">'+posttitle+'</a></div></div>'); } }
JavaScript
 function GetListChiNhanh() { strData = "cmd=GetListChiNhanh"; //alert(strData); $.ajax({ url: 'ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Server quá tải - GetListChiNhanh'); GetListChiNhanh(); }, success: function (msg) { $('#sbLstChiNhanh2').html(msg); $('#sbLstChiNhanh1').html(msg); } // end success }); // end ajax } function isVaildDatVanChuyen() { if ($('#DiaChiLayHang').val() == '') { alert('Địa chỉ lấy hàng rỗng'); return false; } if ($('#DiaChiNguoiNhan').val() == '') { alert('Địa chỉ người nhận rỗng'); return false; } if ($('#CMND').val() == '') { alert('CMND rỗng'); return false; } if ($('#TenNguoiNhan').val() == '') { alert('Địa chỉ người nhận rỗng'); return false; } if ($('#DienThoaiNguoiNhan').val() == '') { alert('Diện thoại người nhận rỗng'); return false; } if ($('#ThongTinTaiKhoan').val() == '') { alert('Thông tin tài khoản rỗng'); return false; } if ($('#TenMonHang').val() == '') { alert('Tên món hàng rỗng'); return false; } if ($('#KichThuoc').val() == '') { alert('Kích thước rỗng'); return false; } if ($('#TrongLuong').val() == '') { alert('Trọng lượng rỗng'); return false; } else { if (isNaN($('#TrongLuong').val())) { alert('Trọng lượng phải là số'); return false; } } return true; } function DatVanChuyen() { if (isVaildDatVanChuyen()) { strData = "cmd=DatVanChuyen&"; $('#loadingRuler').css('display', 'block'); strData += $('form').serialize(); alert(strData); $.ajax({ url: 'ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error DatVanChuyen'); }, success: function (msg) { $('#loadingRuler').css('display', 'none'); $('#statusResult').css('display', 'block'); $('#tblResult').css('display', 'block'); $('#tblResult').slideUp('fast'); $('#tblResult').slideDown('slow'); $('#statusResult').html(msg); //alert(msg); } }); } } $(document).ready(function () { GetListChiNhanh(); $('#DatVanChuyen').click(function () { DatVanChuyen(); }); });
JavaScript
/* * Autocomplete - jQuery plugin 1.0.2 * * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, 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 5747 2008-06-25 18:30:55Z 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) { // 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; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v; } v += options.multipleSeparator; } $input.val(v); 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 [""]; } var words = value.split( options.multipleSeparator ); var result = []; $.each(words, function(i, value) { if ( $.trim(value) ) result[i] = $.trim(value); }); return result; } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); 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) $.Autocompleter.Selection(input, 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( "" ); } } ); } if (wasVisible) // position cursor at end of input field $.Autocompleter.Selection(input, input.value.length, input.value.length); }; 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, 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 (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 : '400px', //$(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(); } }; }; $.Autocompleter.Selection = function(field, start, end) { if( field.createTextRange ){ var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } else if( field.setSelectionRange ){ field.setSelectionRange(start, end); } else { if( field.selectionStart ){ field.selectionStart = start; field.selectionEnd = end; } } field.focus(); }; })(jQuery);
JavaScript
function formatCurrency(num){ num = num.toString().replace(/\$|\,/g,''); if(isNaN(num)) num = "0"; sign = (num == (num = Math.abs(num))); num = Math.floor(num*100+0.50000000001); num = Math.floor(num/100).toString(); for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3)); return (((sign)?'':'-') + num).replace(",","."); } var nDay; function datediff(d,m,y,nDay){ strData = 'cmd=datediff&y=' + y + '&m=' + m + '&d=' + d; $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ alert('Error at check date'); }, success: function(msg){ $('#nDay').val(msg); } }); } function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } function isValidDate(d,m,y,label_error){ //s = d + "-" + m + "-" + y; //alert(s); if(isNaN(y)){ $('#' + label_error).html('Năm phải là số'); $('#' + label_error).fadeIn("slow").show(); return false; } if((y=='') || (y>2100)){ $('#' + label_error).html('Năm không hợp lệ'); $('#' + label_error).fadeIn("slow").show(); return false; } if(d>31){ $('#' + label_error).html('Ngày quá 31'); $('#' + label_error).fadeIn("slow").show(); return false; } if((m==4) || (m==6) || (m==9) || (m==11)) if(d==31){ $('#' + label_error).html('Tháng ' + m + " không có ngày 31"); $('#' + label_error).fadeIn("slow").show(); return false; } if(m==2){ if((d==30) || (d==31)){ $('#' + label_error).html('Tháng ' + m + " không có ngày "+ d); $('#' + label_error).fadeIn("slow").show(); return false; } if(d==29) if((y%100)!=0 && (y%4!=0)){ $('#' + label_error).html('Tháng ' + m + " năm " + y + " không có ngày " + d); $('#' + label_error).fadeIn("slow").show(); return false; } } //datediff(d, m, y); //sleep(2000); /*t = setTimeout(function(){ flag = $('#nDay').val().split(','); alert(flag); if(parseInt(flag[0])!=1){ $('#' + label_error).html('Ngày nhận sai thực tế'); $('#' + label_error).fadeIn("slow").show(); return false; } }, 1500)*/ $('#' + label_error).html(''); $('#' + label_error).fadeIn("slow").hide(); return true; } // Đã tắt alert function isVaildNumber(value){ if(isNaN(value)){ alert('Số không hợp lệ'); return false; } if(value>99){ alert('Số lượng quá lớn'); return false; } if(value==''){ //alert('so luong rong'); return false; } return true; } function iShow(divShow,iType,msg){ // Định nghĩa từng loại show ở đây // 1. FadeIn 2.Show 3... switch(iType){ case 1:{ $('#' + divShow).html(msg); $('#' + divShow).slideDown("slow"); break; } case 2:{ $('#' + divShow).html(msg); $('#' + divShow).show('slow'); break; } } } function iHide(divShow,iType){ switch(iType){ case 1:{ $('#' + divShow).slideUp("fast"); break; } case 2:{ $('#' + divShow).hide('fast'); break; } } } function iHide2(divShow,iType){ switch(iType){ case 1:{ $('#' + divShow).slideUp("fast"); $('#' + divShow).html(''); break; } case 2:{ $('#' + divShow).hide('fast'); $('#' + divShow).html(''); break; } } } // Hàm này kích hoạt textbox để dùng chức năng autocomplete function isAutocomplete(selectbox, textbox, checkbox){ var isChecked=$('#' + checkbox).is(':checked'); if(isChecked==true){ $('#' + selectbox).css('display','none'); var width = $('#' + selectbox).width(); $('#' + textbox).css('width',width); $('#' + textbox).css('display','block'); } else{ $('#' + selectbox).css('display','block'); $('#' + textbox).css('display','none'); } } function splitNameAndId(textbox,hidden){ // Qui định 10 tag khoảng cách từ name đến ID, nhằm tạo sự thẩm mỷ cho người dùng hỏi bối rối // Gặp phức tạp là người dùng nhấn enter var val = $('#' + textbox).val(); listVal = val.split(' ,'); //alert(listVal); $('#'+ hidden).val(listVal[1]); // IS EASY FALSE $('#'+ textbox).val(listVal[0]); } // src : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes function enter(event,txt_nameFood, hidden,lblUnit,lblUnitPrice,txt_Quantity){ if (event.keyCode == 13){ // Cat ten va ma ra rieng, ma vo hiiden splitNameAndId(txt_nameFood,hidden); // khi hidden co value thi tien hanh lay don gia va donvi selectIFood(hidden,lblUnit,lblUnitPrice); // setfocus cho textbox nhap so luong - nho nhap xong reset lai moi thu $('#' + txt_Quantity).focus(); //$('#' + txt_nameFood).trigger($.Event("keydown", { keyCode: 36 })); //e = jQuery.Event("keydown"); //e.which = 36; //$('#' + txt_nameFood ).trigger(e) //$('#' + txt_nameFood).selectionStart; //var obj = document.getElementById(txt_nameFood); //doGetCaretPosition(obj); } } // Dep qua 1 bên function loadTypesFood(divView1,divView2,divJavascript){ strData = "cmd=loadTypesFood"; $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ ///iShow(divView1,2,msg); alert('Server quá tải vui lòng chờ trong giây lát(er250-load type food'); }, success: function(msg){ //alert(msg); var imsg = msg.split(" ----- "); iShow(divView1,2,imsg[0]); iShow(divView2,2,msg[1]); iShow(divJavascript,2,msg[2]); } }); } function checkITypeFood(divView,idTypeFood,inputCheck,optionView){ var isChecked=$('#' + inputCheck).is(':checked'); if(isChecked==true){ // Đoạn này chống DDOS = javascript từ Anomynous if(optionView=="1"){ strData = "cmd=checkITypeFood&idTypeFood=" + idTypeFood + "&optionView=" + optionView; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ //var msg1 = htmlViewTypeFood(); //iShow(divView,2,msg1); alert('Server quá tải vui lòng chờ trong giây lát và chọn lại lần nữa(err278-check foods'); }, success: function(msg){ //var msg1 = htmlViewTypeFood(); iShow(divView,1,msg); } }); } else if(optionView=="0"){ // Chỉ request thôi, không xử lý ajax //alert(optionView); window.onload = location.href='Foods.php?idTypeFood=' + idTypeFood; } } else iHide(divView,2); } function selectIFood(selectIdFood,elementUnit,elementUPrice,elementQuantity){ var idFood = $('#' + selectIdFood).val(); strData = "cmd=selectIFood&idFood=" + idFood; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ /* Chuỗi trả về : Unit,UnitPrice */ //var listmsg = msg.split(','); //$('#' + elementUnit).html(listmsg[0]); //$('#' + elementUPrice).html(listmsg[1]); alert('Server quá tải vui lòng chờ trong giây lát và chọn lại lần nữa (err310 - select foods'); }, success: function(msg){ var listmsg = msg.split(','); $('#' + elementUnit).html(listmsg[0]); $('#' + elementUPrice).html(formatCurrency(listmsg[1])); $('#' + elementQuantity).focus(); } }); } // Apply for textbox - at tim kiem tong hop function orderIFood1(event,inputQuantity,lblPrice,lblAmount,elementIdFood,txtNameFood,divView){ // Lấy số lượng Quantity = $('#' + inputQuantity).val(); // Lấy đơn giá Price = $('#' + lblPrice).text().replace(".",""); // Lay idFood idFood = $('#' + elementIdFood).val(); // Đảm báo đúng định dạng if(isVaildNumber(Quantity) && (idFood !=null || idFood!="")){ // Tính thành tiền Amount = eval(Quantity*Price); $('#' + lblAmount).html(formatCurrency(Amount)); // Khi nhấn enter if(event.keyCode==13){ //idFood; //idFood = $('#' + elementIdFood).val(); strData = "cmd=orderIFood&idFood=" + idFood + "&Quantity=" + Quantity; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ alert('Server quá tải vui lòng chờ trong giây lát hoặc làm lại lần nữa(err346 - order iFood1 editext'); }, success: function(msg){ //alert('Bạn đã đặt hàng thành công'); //alert(msg); iShow(divView,2,msg); $('#' + inputQuantity).val(''); $('#' + lblAmount).text(''); $('#' + lblPrice).text(''); $('#' + txtNameFood).val(''); $('#' + txtNameFood).focus(); resizeDivBasket(); } }); } // end keyup } // end Quantity i vaild } // Apply for button function orderIFood2(inputQuantity,lblPrice,lblAmount,elementIdFood,txtNameFood,divView){ var Quantity = $('#' + inputQuantity).val(); var idFood; idFood = $('#' + elementIdFood).val(); //alert(idFood); if(isVaildNumber(Quantity) && idFood!='' && idFood != "0"){ strData = "cmd=orderIFood&idFood=" + idFood + "&Quantity=" + Quantity; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ alert('Server quá tải vui lòng chờ trong giây lát hoặc làm lại lần nữa(err376 - at order button'); }, success: function(msg){ //alert(msg); $('#' + inputQuantity).val(''); $('#' + lblAmount).text(''); $('#' + lblPrice).text(''); $('#' + txtNameFood).val(''); iShow(divView,2,msg); $('#' + txtNameFood).focus(); resizeDivBasket(); } }); } } function resizeDivBasket(){ // se height khi qua khung var pBHeight = $('#Basket').height(); //alert(pBHeight); if(pBHeight>600){ $('#Basket').css('height','600px'); //alert(pBHeight); } else{// chi xe 1 chieu check, khi bo check no sai y nghia //alert('Giỏ hàng còn xem được tất cả mặt hàng\n Nên thanh cuộn không hiệu lực'); //$('#Basket').css('height',"auto"); //$('#isScroll').attr('checked', false); } } function orderFood(divView){ d = $('#day').val();m = $('#month').val();y = $('#year').val(); $('.error').hide(); strData = "cmd=orderFood&Ngay=" + d +"&Thang=" + m + "&Nam=" + y; // alert(strData); var answer = confirm("Quý khách đã kiểm tra đúng ngày giao ?"); // ẩn giỏ hàng if(answer){ $('#' + divView).hide('slow'); $('#hidepage').animate({opacity: 0.9},250); // Hien trang cho $('#hidepage').css('visibility','visible'); if(isValidDate(d,m,y,'lbl_date')){ $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 5000, error: function(){ alert('Server quá tải vui lòng chờ trong giây lát hoặc làm lại lần nữa (err417 - at order foods'); }, success: function(msg){ //setTimeout("$('#hidepage').hide('slow')",2500); $('#Basket').css('height',"auto"); $('#Basket').css('scroll',"none"); //$('#' + divView).hide('slow'); $('#' + divView).html(msg); setTimeout("$('#" + divView + "').show('slow')",200); //setTimeout("returnResult(" + divView + "," + msg + ")",2500); } }); } } //setTimeout("window.onload = window.location = 'BasketHistory.php'",4000); } function returnResult(divView,msg){ $('#hidepage').hide('slow'); $('#Basket').css('height',"auto"); $('#' + divView).html(msg); $('#' + divView).show('slow'); } //function orderIFood(idFood,Quantity,divView,divHide){ alert(idFood);} function deleteIFood(idFood,divView){ $('#Basket').css('height',"auto"); strData = "cmd=deleteIFood&idFood=" + $('#' + idFood).val(); //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ alert('Server quá tải, chờ một chút làm lại lần nữa(err447 at delete iFood )'); }, success: function(msg){ iShow(divView,2,msg); //resizeDivBasket(); } }); //resizeDivBasket(); return true; } // Dung cho gio hang khi nhan vao button function updateQuantity(BidFood,BQuantity,divView){ var Quantity = $('#' + BQuantity).val(); var idFood = $('#' + BidFood).val(); if(isVaildNumber(Quantity)){ strData = "cmd=updateQuantity&idFood=" + idFood + "&Quantity=" + Quantity; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(msg){ alert('Server quá tải, chờ một chút làm lại lần nữa(err470 at update quantity )'); }, success: function(msg){ iShow(divView,2,msg); } }); } } // Dung cho gio hang khi nhan vao texbox function updateQuantity2(event,inputQuantity,lblPrice,lblAmount,elementIdFood,divView){ // Lấy số lượng Quantity = $('#' + inputQuantity).val(); // Lấy đơn giá Price = $('#' + lblPrice).text().replace(".",""); // Lay idFood idFood = $('#' + elementIdFood).val(); // Đảm báo đúng định dạng if(isVaildNumber(Quantity) && (idFood !=null || idFood!="")){ // Tính thành tiền Amount = eval(Quantity*Price); $('#' + lblAmount).html(formatCurrency(Amount)); // Khi nhấn enter if(event.keyCode==13){ //idFood; //idFood = $('#' + elementIdFood).val(); strData = "cmd=updateQuantity&idFood=" + idFood + "&Quantity=" + Quantity; //alert(strData); $.ajax({ url: 'ajaxActions.php', type: 'GET', data: strData, timeout: 4000, error: function(){ alert('Server quá tải, chờ một chút hoặc làm lại lần nữa(err504 at update quantity2 )'); }, success: function(msg){ iShow(divView,2,msg); } }); } // end keyup } // end Quantity i vaild }
JavaScript
//v1.7 // Flash Player Version Detection // Detect Client Browser type // Copyright 2005-2007 Adobe Systems Incorporated. All rights reserved. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var version; var axo; var e; // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } return version; } // JavaScript helper required to detect Flash Player PlugIn version information function GetSwfVer(){ // NS/Opera version >= 3 check for Flash plugin in plugin array var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; else if ( isIE && isWin && !isOpera ) { flashVer = ControlVersion(); } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { versionStr = GetSwfVer(); if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { // Given "WIN 2,0,0,11" tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"] tempString = tempArray[1]; // "2,0,0,11" versionArray = tempString.split(","); // ['2', '0', '0', '11'] } else { versionArray = versionStr.split("."); } var versionMajor = versionArray[0]; var versionMinor = versionArray[1]; var versionRevision = versionArray[2]; // is the major.revision >= requested major.revision AND the minor version >= requested minor if (versionMajor > parseFloat(reqMajorVer)) { return true; } else if (versionMajor == parseFloat(reqMajorVer)) { if (versionMinor > parseFloat(reqMinorVer)) return true; else if (versionMinor == parseFloat(reqMinorVer)) { if (versionRevision >= parseFloat(reqRevision)) return true; } } return false; } } function AC_AddExtension(src, ext) { if (src.indexOf('?') != -1) return src.replace(/\?/, ext+'?'); else return src + ext; } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = ''; if (isIE && isWin && !isOpera) { str += '<object '; for (var i in objAttrs) { str += i + '="' + objAttrs[i] + '" '; } str += '>'; for (var i in params) { str += '<param name="' + i + '" value="' + params[i] + '" /> '; } str += '</object>'; } else { str += '<embed '; for (var i in embedAttrs) { str += i + '="' + embedAttrs[i] + '" '; } str += '> </embed>'; } document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_SW_RunContent(){ var ret = AC_GetArgs ( arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000" , null ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": case "id": ret.objAttrs[args[i]] = args[i+1]; break; case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; }
JavaScript
// JavaScript Document function iShow(divShow, divHide, iType,msg){ // Định nghĩa từng loại show ở đây // 1. FadeIn 2.Show 3... switch(iType){ case 1:{ $('#' + divHide).slideUp("fast"); //$('#' + divShow).html(msg); $('#' + divShow).slideDown("fast"); break; } case 2:{ $('#' + divHide).hide('fast'); //$('#' + divShow).html(msg); $('#' + divShow).show('fast'); break; } } } function isVaildLogin(username,pass){ if(username=='' || pass==''){ alert('Username, pass không được rỗng'); return false; } return true; } function Login(username,pass,divShow,divHide){ if(isVaildLogin(username,pass)){ //strData = "cmd=Login&username=" + username + "&pass=" + pass; //alert(strData); $.ajax({ url: 'ajaxActions.aspx', type: 'POST', data: { cmd: "Login", username: username, pass: pass }, //strData, timeout: 4000, error: function (msg) { Logout('Login', 'Logined'); }, success: function (msg) { if (!isNaN(msg)) { var number = parseInt(msg); switch (number) { case 0: { alert('Tài khoản chưa đăng ký hoặc sai thông tin'); Logout('Login', 'Logined'); break; } } } // Server tra ve username else { iShow(divShow, divHide, 2, msg); $('#lbl_username').text(msg); } } }); } } function Logout(divShow,divHide){ strData = "cmd=Logout"; //alert(strData); $.ajax({ url: 'ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function(msg){ alert('Error Login'); }, success: function(msg){ iShow(divShow,divHide,2,msg); $('#lbl_username').text(''); } }); } function checkLogin(){ strData = "cmd=CheckLogin"; //alert(strData); $.ajax({ url: 'ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { //alert('Error CheckLogined'); checkLogin(); }, success: function (msg) { if (!isNaN(msg)) { var number = parseInt(msg); switch (number) { case 0: { Logout('Login', 'Logined'); break; } } } // Server tra ve username else { iShow('Logined', 'Login', 1, msg); // msg bo k0 $('#lbl_username').html(msg); } } // end success }); // end ajax } $(document).ready(function () { checkLogin(); // Login $('#btLogin').click(function () { var username = $('#username').val(); var pass = MD5($('#password').val()); Login(username, pass, 'Logined', 'Login'); }); $("#password").keyup(function (event) { if (event.keyCode == 13) { //alert('a'); var username = $('#username').val(); var pass = MD5($('#password').val()); Login(username, pass, 'Logined', 'Login'); } }); // Logout $('#btLogout').click(function () { Logout('Login', 'Logined'); $('#left').hide('fast'); }); });
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(); }
JavaScript
$(document).ready(function() { $('.error').hide(); $('#txt_username').change(function(){ check(); }); $('#txt_password2').blur(function(){ if(!compare("txt_password", "txt_password2", "lbl_password2")); $('#lbl_password2').fadeIn("slow").hide(); }); $('#txt_password').blur(function(){ if(!check_null("txt_password", "lbl_password", 6, null, "lbl_password2")) $('#lbl_password').fadeIn("slow").hide(); }); $('#txt_email').change(function(){ if(!check_email("txt_email","lbl_email2")){ if(!check_null("txt_email", "lbl_email", null, 50, "lbl_email2")) $('#lbl_email').fadeIn("slow").hide(); $('#lbl_email2').fadeIn("slow").hide(); $('#lbl_email').fadeIn("slow").hide(); } }); }); function check_null(obj, error_message_id, length_min, length_max, error_message_check_length_id) { var temp = $("#" + obj); if (temp.val() == "") { $("#" + error_message_id).fadeIn("slow").show(); temp.focus(); return false; } else { if (length_min != null) { if (temp.val().length < length_min) { $("#" + error_message_check_length_id).fadeIn("slow").show(); temp.focus(); return false; } } if (length_max != null) { if (temp.val().length > length_max) { $("#" + error_message_check_length_id).fadeIn("slow").show(); temp.focus(); return false; } } return true; } } function compare(obj, obj_to_compare, error_message_id) { var temp = $("#" + obj); var temp_to_compare = $("#" + obj_to_compare); if (temp.val() != temp_to_compare.val()) { $("#" + error_message_id).fadeIn("slow").show(); temp_to_compare.focus(); return false; } return true; } function echeck(d) { return /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(d); } //check email //obj: object form to compare //error_message_id: message id function check_email(obj, error_message_id) { var temp = $("#" + obj); if (!echeck(temp.val())) { $("#" + error_message_id).fadeIn("slow").show(); temp.focus(); return false; } return true; } function gotosite(){ window.location="Home.aspx"; } function check(){ if(document.getElementById('txt_username').value==''){ $('#lbl_username').fadeIn("slow").show(); return false; } else{ $.ajax({ url: 'ajaxActions.aspx', type: 'GET', data: { username: $('#txt_username').val(), cmd: 'check' }, timeout: 2000, error: function(){ alert('co loi'); }, success: function(msg){ $('#lbl_username').fadeIn("slow").show(); document.getElementById('lbl_username').innerHTML = msg } }); // Ajax } } $(function () { $('.error').hide(); $('#lblMessage').hide(); $("#bt_reg").click(function () { $('.error').hide(); var $form = $("#frmRegister"); var username = $('#txt_username').val(); var password = $('#txt_password').val(); var password2 = $('#txt_password2').val(); var email = $('#txt_email').val(); var fullname = $('#txt_fullname').val(); var address = $('#txt_address').val(); var phone = $('#txt_phone').val(); var thongtintaikhoan = $('#thongtintaikhoan').val(); var cmnd = $('#cmnd').val(); //begin validate form if (!check_null("txt_password", "lbl_password", 6, null, "lbl_password2") || !compare("txt_password", "txt_password2", "lbl_password2") || !check_null("txt_email", "lbl_email", null, 50, "lbl_email2") || !check_email("txt_email", "lbl_email2")) { return false; } else { password = MD5(password); var strData = "cmd=reg&username=" + username + "&password=" + password + "&email=" + email + "&fullname=" + fullname + "&address=" + address + "&phone=" + phone; alert(strData); $.ajax({ type: "POST", url: "ajaxActions.aspx", data: { cmd: "Register", username: username, password: password, email: email, fullname: fullname, addr: address, phone: phone, cmnd: cmnd, thongtintaikhoan: thongtintaikhoan }, success: function (msg) { alert(msg); } }); return false; } // end else }); // end function click }); // end document
JavaScript
function GetListChiNhanh() { strData = "cmd=GetListChiNhanh"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListDiaChi'); }, success: function (msg) { $('#sbdiachidau').html(msg); $('#sbdiachicuoi').html(msg); } // end success }); // end ajax } function GetListTuyenDuong() { strData = "cmd=GetListTuyenDuong"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListTuyenDuong'); }, success: function (msg) { $('#DanhSachTuyenDuong').html(msg); } // end success }); // end ajax } function addTuyenDuong() { strData = "cmd=addTuyenDuong&"; strData += $('form').serialize(); //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error addTuyenDuong'); }, success: function (msg) { alert(msg); GetListTuyenDuong(); } }); } function ViewChiTietTuyenDuong(MaTuyen) { strData = "cmd=ViewChiTietTuyenDuong&MaTuyen=" + MaTuyen; // alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error ViewChiTietTuyenDuong'); }, success: function (msg) { $('#DetailTuyenDuong').html(msg); } }); return true; } $(document).ready(function () { GetListChiNhanh(); GetListTuyenDuong(); $('#bt_them').click(function () { addTuyenDuong(); }); });
JavaScript
function GetListLoaiNhanVien() { strData = "cmd=GetListLoaiNhanVien"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListLoaiNhanVien'); }, success: function (msg) { $('#sbLoaiNhanVien').html(msg); } // end success }); // end ajax } function GetListNhanVien() { strData = "cmd=GetListNhanVien"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListNhanVien'); }, success: function (msg) { $('#ListNV').html(msg); } // end success }); // end ajax } function addNhanVien() { strData = "cmd=addNhanVien&"; $('form').submit(function () { //alert($(this).serialize()); //return false; }); strData += $('form').serialize(); //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error addNhanVien'); }, success: function (msg) { alert(msg); GetListNhanVien(); } }); } function viewDetail(MaNV) { strData = "cmd=ViewDetailNV&MaNhanVien=" + MaNV; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error view Detasil'); }, success: function (msg) { $('#DetailNV').html(msg); } }); return true; } $(document).ready(function () { GetListLoaiNhanVien(); GetListNhanVien(); $('#bt_them').click(function () { addNhanVien(); }); });
JavaScript
function GetListChiNhanh() { strData = "cmd=GetListChiNhanh_1"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListChiNhanh_1'); }, success: function (msg) { $('#ListChiNhanh').html(msg); } // end success }); // end ajax } function addChiNhanh() { strData = "cmd=addChiNhanh&"; $('form').submit(function () { //alert($(this).serialize()); //return false; }); strData += $('form').serialize(); //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error addChiNhanh'); }, success: function (msg) { alert(msg); GetListChiNhanh(); } }); } $(document).ready(function () { GetListChiNhanh(); $('#bt_them').click(function () { addChiNhanh(); }); });
JavaScript
function enableAllMenu(){ // menu quan ly kho $('#TitleQLKho').css('display','block'); $('#mnQLKho').css('display','block'); // menu quan ly cong ty $('#TitleQLCongTy').css('display','block'); $('#mnQLCongTy').css('display','block'); // men ql chi nhanh $('#TitleQLChiNhanh').css('display','block'); $('#mnQLChiNhanh').css('display','block'); // menu tai xe $('#TitleQLTaiXe').css('display','block'); $('#mnQLTaiXe').css('display','block'); // he thong $('#TitleQLHeThong').css('display','block'); $('#mnQLHeThong').css('display','block'); } function disibleAllMenu(){ // menu quan ly kho $('#TitleQLKho').css('display','none'); $('#mnQLKho').css('display','none'); // menu quan ly cong ty $('#TitleQLCongTy').css('display','none'); $('#mnQLCongTy').css('display','none'); // men ql chi nhanh $('#TitleQLChiNhanh').css('display','none'); $('#mnQLChiNhanh').css('display','none'); // menu tai xe $('#TitleQLTaiXe').css('display','none'); $('#mnQLTaiXe').css('display','none'); $('#TitleQLHeThong').css('display','none'); $('#mnQLHeThong').css('display','none'); } function enableMenuCustomize(MaLoaiNV){ switch(MaLoaiNV){ case 1:{ // menu tai xe $('#TitleQLTaiXe').css('display','block'); $('#mnQLTaiXe').css('display','block'); break; } case 2:{ // menu quan ly cong ty $('#TitleQLCongTy').css('display','block'); $('#mnQLCongTy').css('display','block'); break; } case 3:{ // men ql chi nhanh $('#TitleQLChiNhanh').css('display','block'); $('#mnQLChiNhanh').css('display','block'); break; } case 4:{ // menu quan ly kho $('#TitleQLKho').css('display','block'); $('#mnQLKho').css('display','block'); break; } case 5:{ // menu tai xe $('#TitleQLTaiXe').css('display','block'); $('#mnQLTaiXe').css('display','block'); break; } case 6 :{ // he thong $('#TitleQLHeThong').css('display','block'); $('#mnQLHeThong').css('display','block'); break; } } // end switch } // JavaScript Document function iShow(divShow, divHide, iType,msg){ // Định nghĩa từng loại show ở đây // 1. FadeIn 2.Show 3... switch(iType){ case 1:{ $('#' + divHide).slideUp("fast"); //$('#' + divShow).html(msg); $('#' + divShow).slideDown("fast"); break; } case 2:{ $('#' + divHide).hide('fast'); //$('#' + divShow).html(msg); $('#' + divShow).show('fast'); break; } } } function isVaildLogin(username,pass){ if(username=='' || pass==''){ alert('Username, pass không hợp lệ'); return false; } return true; } function Login(username,pass,divShow,divHide){ if(isVaildLogin(username,pass)){ //strData = "cmd=Login&username=" + username + "&pass=" + pass; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'POST', data: { cmd: "LoginAdmin", username: username, pass: pass }, //strData, timeout: 4000, error: function (msg) { Logout(divShow, divHide); }, success: function (msg) { // msg format : 1,ndp1007->ok or 0,0 -> fail //alert(msg); msgNumber = msg.split(','); if(!isNaN(msgNumber[0])){ var number = parseInt(msgNumber[0]); switch(number){ case 0:{ Logout(divShow, divHide); break; } default:{ //1,ndp1007 //alert(msg); $('#main_container').slideUp('slow'); iShow(divShow,divHide,1,msgNumber[1]);// msg bo k0 $('#lbl_username').text(msgNumber[1]); // Hiện menu tương ứng với MaLoaiNV msgNumber[0] enableMenuCustomize(number); } } } } // end susscess }); // end ajax } } function Logout(divShow,divHide){ strData = "cmd=LogoutAdmin"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error Login'); }, success: function (msg) { disibleAllMenu(); iShow(divHide, divShow, 2, msg); $('#lbl_username').text(''); $('#main_container').slideDown('slow'); } }); } function checkLogin(divShow,divHide){ strData = "cmd=CheckLoginAdmin"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function(msg){ alert('Error CheckLogined'); }, success: function(msg){ // msg format : 1,ndp1007->ok or 0,0 -> fail msgNumber = msg.split(','); if(!isNaN(msgNumber[0])){ var number = parseInt(msgNumber[0]); switch(number){ case 0:{ Logout(divShow, divHide); $('#left').slideUp('fast'); break; } default:{ //1,ndp1007 $('#main_container').slideUp('slow'); iShow(divShow,divHide,1,msgNumber[1]);// msg bo k0 $('#lbl_username').text(msgNumber[1]); // Hiện menu tương ứng với MaLoaiNV msgNumber[0] enableMenuCustomize(number); } } } }// end success }); // end ajax } $(document).ready(function() { disibleAllMenu(); checkLogin('Logined','Login'); // Login $('#btLogin').click(function(){ var username = $('#username').val(); var pass = $('#password').val(); Login(username,pass,'Logined','Login'); }); $('#btnDangNhap').click(function(){ var username = $('#username2').val(); var pass = $('#password2').val(); Login(username,pass,'Logined','Login'); }); $("#password").keyup(function (event) { if (event.keyCode == 13) { var username = $('#username').val(); var pass = $('#password').val(); Login(username, pass, 'Logined', 'Login'); } }); $("#password2").keyup(function (event) { if (event.keyCode == 13) { var username = $('#username2').val(); var pass = $('#password2').val(); Login(username, pass, 'Logined', 'Login'); } }); // Logout $('#btLogout').click(function(){ Logout('Logined', 'Login'); $('#left').slideUp('fast'); }); });
JavaScript
function UpdateTinhTrang(e, MaKhachHang, lbl_status) { isChecked = $(e).is(':checked'); strData = isChecked == true ? "cmd=UpdateTinhTrang&MaKhachHang=" + MaKhachHang : "cmd=UpdateTinhTrang0&MaKhachHang=" + MaKhachHang; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error Update tinh trang'); }, success: function (msg) { if(parseInt(msg)==1) $('#' + lbl_status).css('background-color', 'green'); if(parseInt(msg)==0) $('#' + lbl_status).css('background-color', 'red'); } }); return true; } function GetListKhachHang() { strData = "cmd=GetListKhachHang"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListKhachHang'); }, success: function (msg) { $('#ListKH').html(msg); } // end success }); // end ajax } $(document).ready(function () { GetListKhachHang(); });
JavaScript
function GetListXe() { strData = "cmd=GetListXe"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListXe'); }, success: function (msg) { $('#QuanLyXe').html(msg); } // end success }); // end ajax } function ThayDoiTinhTrangXe(Maxe) { strData = "cmd=ThayDoiTinhTrangXe&MaXe=" + MaXe; alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error Thay Doi tinh Trang Xe'); }, success: function (msg) { $('#ThayDoiTinhTrangXe').html(msg); } }); return true; } $(document).ready(function () { GetListXe(); });
JavaScript
function GetListTuyenDuong() { strData = "cmd=GetListTuyenDuong_1"; //alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListTuyenDuong'); }, success: function (msg) { $('#sbTenTuyen').html(msg); } // end success }); // end ajax } function GetListChiNhanh() { strData = "cmd=GetListChiNhanh"; // alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error GetListDiaChi'); }, success: function (msg) { $('#sbChiNhanh2').html(msg); $('#sbChiNhanh1').html(msg); } // end success }); // end ajax } function ViewChiTietTuyenDuong() { //MaTuyen = $('#txt_MaTuyen').val(); strData = "cmd=ViewChiTietTuyenDuong"; strData += $('form').serialize(); alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error ViewChiTietTuyenDuong'); }, success: function (msg) { $('#DetailTuyenDuong').html(msg); } }); return true; } function addLoTrinhTuyen() { strData = "cmd=addLoTrinhTuyen&"; strData += $('form').serialize(); alert(strData); $.ajax({ url: '../ajaxActions.aspx', type: 'GET', data: strData, timeout: 4000, error: function (msg) { alert('Error adddoanDuong'); }, success: function (msg) { alert(msg); GetListChiNhanh(); } }); } //function GetMaTuyen_TenTuyen() { // matuyen = 1; //Request.QueryString["MaTuyen"]; // matuyen = $('#hidMaTuyen').val(); // strData = "cmd=GetMaTuyen_TenTuyen&MaTuyen1="+ matuyen; // alert(strData); // $.ajax({ // url: '../ajaxActions.aspx', // type: 'GET', // data: strData, // timeout: 4000, // error: function (msg) { // alert('Error GetMaTuyen_TenTuyen'); // }, // success: function (msg) { // $('#GetMaTuyen_TenTuyen').html(msg); // } // end success // }); // end ajax //} $(document).ready(function () { // GetListChiNhanh(); GetListChiNhanh(); //ViewChiTietTuyenDuong() //GetListTuyenDuong(); //GetMaTuyen_TenTuyen() $('#bt_them').click(function () { addLoTrinhTuyen(); ViewChiTietTuyenDuong(); }); });
JavaScript
(function($){ $.fn.extend({ valid8: function(options) { return this.each(function(){ $(this).data('valid', false); var defaultOptions = { reguglarExpressions: [], ajaxRequests: [], jsFunctions: [], onValid: defaultOnValid, onError: defaultOnError, validationEvents: ['keyup','blur'], validationFrequency: 500, values: null }; if(self.type == 'checkbox') defaultOptions.reguglarExpressions = [{expression: /^true$/, errormessage: 'Required'}]; else defaultOptions.reguglarExpressions = [{expression: /^.+$/, errormessage: 'Required'}]; $(this).data('settings', $.extend(defaultOptions, options)); initialize(this); }); }, isValid: function(){ var valid = true; this.each(function() { validate(this); if($(this).data('valid') == false) valid = false; }); return valid; } }); function initialize(el) { $(el).data('errors', new Array()); $(el).data('valids', new Array()); $(el).data('keypressTimer', null); if($(el).attr('value').length > 0) validate(el); activate(el); }; function activate(el) { var events = $(el).data('settings').validationEvents; if(typeof events == 'string') $(el)[events](function (e){ handleEvent(e, el); }); else { $.each(events, function(i, event){ $(el)[event](function (e){ handleEvent(e, el); }); }); } }; function validate(el) { // Dispose old errors and valids $(el).data('errors', new Array()); $(el).data('valids', new Array()); var value; // Handle checkbox if(el.type == 'checkbox') value = el.checked; else value = el.value; regexpValidation(value.replace(/^[ \t]+|[ \t]+$/,''),el); }; function regexpValidation(value, el){ $.each($(el).data('settings').reguglarExpressions, function(i, validator){ if(!validator.expression.test(value)) $(el).data('errors')[$(el).data('errors').length] = validator.errormessage; else if(validator.validmessage) $(el).data('valids')[$(el).data('valids').length] = validator.validmessage; }); if($(el).data('errors').length > 0) onError(el); else if($(el).data('settings').jsFunctions.length > 0) { functionValidation(value, el); } else if($(el).data('settings').ajaxRequests.length > 0){ fileValidation(value, el); } else { onValid(el); } }; function functionValidation(value, el){ $.each($(el).data('settings').jsFunctions, function(i, validator){ var v; if(validator.values){ if(typeof validator.values == 'function') v = validator.values(); } var values = v || value; if(validator['function'](values).valid) $(el).data('valids')[$(el).data('valids').length] = validator['function'](values).message; else $(el).data('errors')[$(el).data('errors').length] = validator['function'](values).message; }); if($(el).data('errors').length > 0) onError(el); else if($(el).data('settings').ajaxRequests.length > 0) { fileValidation(value, el); } else { onValid(el); } } function fileValidation(value, el){ $.each($(el).data('settings').ajaxRequests, function(i, validator){ var v; if(validator.values){ if(typeof validator.values == 'function') v = validator.values(); } var values = v || {value: value}; $.post(validator.url, values, function(data, textStatus){ if(data.valid) { $(el).data('valids')[$(el).data('valids').length] = data.message; } else { $(el).data('errors')[$(el).data('errors').length] = data.message; } if($(el).data('errors').length > 0) onError(el); else { onValid(el); } }, "json"); }); }; function handleEvent(e, el){ if(e.keyCode && $(el).attr('value').length > 0) { clearTimeout($(el).data('keypressTimer')); $(el).data('keypressTimer',setTimeout(function() { validate(el); }, $(el).data('settings').validationFrequency)); } else if(e.keyCode && $(el).attr('value').length <= 0) return false; else { validate(el); } }; function defaultOnValid(valids,el) { var parent = $(el).parent(); parent.removeClass('error'); parent.removeClass('loading'); parent.addClass('valid'); setMessage(valids,el); }; function defaultOnError(errors,el) { var parent = $(el).parent(); parent.removeClass('valid'); parent.removeClass('loading'); parent.addClass('error'); setMessage(errors,el); }; function onValid(el) { $(el).data('valid', true); $(el).data('settings').onValid($(el).data('valids'), el); } function onError(el) { $(el).data('valid', false); $(el).data('settings').onError($(el).data('errors'), el); } function setMessage(messages,el) { var parent = $(el).parent(); var elementId = el.id + "ValidationMessage"; if(!$('#'+elementId).length > 0){ parent.append($(document.createElement('span')).attr('id', elementId)); } $('#'+elementId).html(""); $('#'+elementId).text(messages[0]); }; })(jQuery);
JavaScript
//http://plugins.jquery.com/files/jquery.rpc.js_1.txt window.jQuery = window.jQuery || {}; jQuery.rpc = function(url, dataType, onLoadCallback, version) { return new (function(url, dataType, onLoadCallback, version) { version = version || "1.0"; dataType = dataType || "json"; if(dataType != "json" && dataType != "xml") { new Error("IllegalArgument: Unsupported data type"); } var _self = this; var serializeToXml = function(data) { switch (typeof data) { case 'boolean': return '<boolean>'+ ((data) ? '1' : '0') +'</boolean>'; case 'number': var parsed = parseInt(data); if(parsed == data) { return '<int>'+ data +'</int>'; } return '<double>'+ data +'</double>'; case 'string': return '<string>'+ data +'</string>'; case 'object': if(data instanceof Date) { return '<dateTime.iso8601>'+ data.getFullYear() + data.getMonth() + data.getDate() +'T'+ data.getHours() +':'+ data.getMinutes() +':'+ data.getSeconds() +'</dateTime.iso8601>'; } else if(data instanceof Array) { var ret = '<array><data>'+"\n"; for (var i=0; i < data.length; i++) { ret += ' <value>'+ serializeToXml(data[i]) +"</value>\n"; } ret += '</data></array>'; return ret; } else { var ret = '<struct>'+"\n"; jQuery.each(data, function(key, value) { ret += " <member><name>"+ key +"</name><value>"; ret += serializeToXml(value) +"</value></member>\n"; }); ret += '</struct>'; return ret; } } } var xmlRpc = function(method, params) { var ret = '<?xml version="'+version+'"?><methodCall><methodName>'+method+'</methodName><params>'; for(var i=0; i<params.length; i++) { ret += "<param><value>"+serializeToXml(params[i])+"</value></param>"; } ret += "</params></methodCall>"; return ret; } var parseXmlValue = function(node) { childs = jQuery(node).children(); for(var i=0; i < childs.length; i++) { switch(childs[i].tagName) { case 'boolean': return (jQuery(childs[i]).text() == 1); case 'int': return parseInt(jQuery(childs[i]).text()); case 'double': return parseFloat(jQuery(childs[i]).text()); case "string": return jQuery(childs[i]).text(); case "array": var ret = []; jQuery("> data > value", childs[i]).each( function() { ret.push(parseXmlValue(this)); } ); return ret; case "struct": var ret = {}; jQuery("> member", childs[i]).each( function() { ret[jQuery( "> name", this).text()] = parseXmlValue(jQuery("value", this)); } ); return ret; case "dateTime.iso8601": /* TODO: fill me :( */ return NULL; } } } var parseXmlResponse = function(data) { var ret = {}; ret.version = version; jQuery("methodResponse params param > value", data).each( function(index) { ret.result = parseXmlValue(this); } ); jQuery("methodResponse fault > value", data).each( function(index) { ret.error = parseXmlValue(this); } ); return ret; } var rpc_contents = { 'xml':'text/xml' ,'json':'application/json' }; var _rpc = function(method, callback) { var params = []; for (var i=2; i<arguments.length; i++) { params.push(arguments[i]); } // console.log(params); var data; if(dataType == 'json') { data = {"version":version, "method":method, "params":params}; } else { data = xmlRpc(method, params); } jQuery.ajax({ "url": url, "dataType": dataType, "type": "POST", "data": data, "success": function(inp) { var json = inp; if(dataType == "xml") { json = parseXmlResponse(inp); } // console.log("json response:", json); callback(json); }, "processData": false, "contentType": rpc_contents[dataType] }); }; _rpc("system.listMethods", function(json) { // console.log(json); /* get the functions */ if(!json.result) { return; } var proc = null; for(var i = 0; i<json.result.length; i++) { proc = json.result[i]; var obj = _self; var objStack = proc.split(/\./); for(var j = 0; j < (objStack.length - 1); j++){ obj[objStack[j]] = obj[objStack[j]] || {}; obj = obj[objStack[j]]; } /* add the new procedure */ obj[objStack[j]] = ( function(method, obj) { var _outer = {"method":method,"rpc":_rpc}; return function(callback) { var params = []; params.push(_outer.method); params.push(callback); for (var i=1; i<arguments.length; i++) { params.push(arguments[i]); } _rpc.apply(_self, params); } } )(proc, _rpc); } // console.log('Load was performed.'); if(onLoadCallback) { onLoadCallback(_self); } } ); })(url, dataType, onLoadCallback, version); };
JavaScript
//initiailzie stuff when document is ready $(document).ready(function() { // gets username var username = gup("id"); //alert(username); // testing field // a hash map to return the username $("#data").data("username", username); USER_ID = $("#data").data("username"); //get the buddy list getBuddyList(); sendStatus(1); //make the buddy list window draggable $("#buddyList").draggable({"handle" : ".buddyHandle"}); //event handler for the add buddy button $("#addBuddyBtn").click(function() { addBuddy(); }); //event handler for the remove buddy button $("#delBuddyBtn").click(function() { removeBuddy(); }); eventListener(); }); //This is the URL for the IM server we are sending and recieving from //Note that the page this script is loaded from must be on the same domain as the URL the data is being sent to, otherwse you will get an ajax permission denied error. var IM_URL = "/pimp/WebResponder"; //This is my user id - assume this eventually comes from a loin somehwere //var USER_ID = "james"; //var USER_ID = $("#data").data("username"); var USER_ID; //Initialize jquery ajax to wait for a server response instead of the default asyncronous send, and set the URL of the IM server $.ajaxSetup({ async: false, url : IM_URL }); var zindex = 1; var initOffset = 10; var initXY = 100; //An array that contains the current list of buddies. Each entry is a buddy object which consists of an object with an id and a status. var buddyList = []; /******************************************************************* * Put some dummy buddies in the list so I can test it, remove this later ********************************************************************/ /* buddyList.push( { id : "james", status : 1 }); buddyList.push( { id : "hi", status : 1 }); buddyList.push( { id : "hello", status : 0 }); buddyList.push( { id : "joe", status : 1 }); buddyList.push( { id : "abc", status : 1 }); buddyList.push( { id : "blahbla", status : 1 }); buddyList.push( { id : "qweqwe", status : 1 }); buddyList.push( { id : "xvcdcz", status : 1 }); buddyList.push( { id : "safddf", status : 1 }); */ // gets url parameters function gup( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if (results == null) return ""; else return results[1]; } //create a new chat window with the given id and title function showWindow(id, title) { //get the template HTML for a new IM window var newHtml = $("#buddyTemplate").html(); var newId = 'buddy_' + id; //if the window exists but was hidden, just show it and exit if ( $("#" + newId).length>0 ) { $("#" + newId).show(); return; } //set the new ID to something unique newHtml = newHtml.replace("budId", newId ); //add the new window to the page $("#container").append(newHtml); var sNewId = "#" + newId; //set the new window's title and make it draggable $(sNewId + " .buddyTitle").text(title); $(sNewId).draggable({"handle" : ".buddyHandle"}); //offset the new window's position and show it $(sNewId).css("left", initXY + "px"); $(sNewId).css("top", initXY + "px"); initXY += initOffset; $(sNewId).show(); $(sNewId + " .chatEntry").focus(); //Add event handler for enter key in the IM chat entry box //This will put the message entered in the IM buddy chat window and call sendMessage() to send message to server $(sNewId + " .chatEntry").keyup( function(e) { if (e.which == 13) { var budChat = $(this).siblings(".budChat"); var messageText = $(this).val(); var d = new Date(); //alert("message Text:"+ messageText); var div = $("<div class='chatLine'><em>"+d.toLocaleTimeString()+"</em> "+USER_ID+": <strong>"+messageText+"</strong></div>"); //append the entered text to the buddy chat box budChat.append(div); budChat.scrollTo(budChat.find(".chatLine:last").get(0)); //clear the IM chat entry box $(this).val(""); //construct the IM message to send var message = new Object(); message.userID = USER_ID; message.recipientID = title; message.message = messageText; message.type = 0; message.timestamp = new Date(); //send the message sendMessage(message, budChat); } }); //IM window mousedown event handler //Give chat entry box focus and move window to front when selected $(sNewId).mousedown(function() { $(this).css("zIndex", zindex++); $(sNewId + " .chatEntry").focus(); }); //Close button event handler //This will hide a window when its closeButton is clicked $(".closeButton").click( function() { $(this).closest(".closeable").hide(); }); //increment ID for next window to be created //id++; } //Sends a message to the server. //Waits for a response and returns 0 on failure or 1 on success (but it also alerts the error message). function sendMessage(message, budChat) { var userID = message.userID; var recipientID = message.recipientID; var message = message.message; var status = 0; try { //send the message to the remote URL, using the URL set above in ajaxSetup() $.ajax({ data : "&type=sendmessage&to="+recipientID+"&from="+USER_ID+"&message="+message, success : function(responseData, textStatus) { if (responseData != 1) { budChat.append("<span style='color: red; font-style: italic'>Error sending message: Code "+responseData+"</span>"); } }, error : function(x,t,r) { if (t !=null) throw(t); else if (r != null) throw(r); } }); } catch (e) { //catch permission denied error alert("Error sending message: " + e); } return status; } //Gets a buddy list from the remote URL, using the URL set above in ajaxSetup(), then updates the global buddy ist variable and the buddy list window function getBuddyList() { try { //send the userID to the remote URL, using the URL set above in ajaxSetup() //NOTE: the data being sent is just the userId currently. //The URL and/or the data will need changing so the server understands this is a buddy list request // alert("2"); testing field $.ajax({ //url: "http://tornado.ics.uci.edu:8080/pimp/WebResponder?&type=getbuddylist&clientID="+$("#data").data("username"), //url: "http://tornado.ics.uci.edu:8080/pimp/WebResponder?&type=getbuddylist&clientID="+USER_ID, //url: IM_URL + "?&type=getbuddylist&clientID=" + USER_ID, data: "type=getbuddylist&clientID="+USER_ID, dataType: "json", //assuming that the buddy list returned is in json format success : function(responseData, textStatus) { if (textStatus == "success") { //set the global buddyList to the returned data buddyList = responseData.buddylist; //assumes that the response data is an object that is an array of buddies as described above for the buddyList global //and update the displayed list from the buddyList updateBuddyList(); } else throw(textStatus); }, error : function(x,t,r) { if (t !=null) throw(t); else if (r != null) throw(r); } }); } catch (e) { //catch permission denied error alert("Error getting buddy list: " + e); } } //Adds a buddy to the buddy list window. //Prompts for the buddy id, then it sends a request to the server to get the buddy status. //If the server responds that the specified buddy exists, then it adds it to the list function addBuddy() { //Prompt for the buddy to add var buddyId = window.prompt("Enter the buddy id to add:"); if (buddyId == null || buddyId.length==0) return; /*********************************************************/ // Just for testing - remove this section when comm works // buddyList.push( {id : buddyId, status : 1} ); // updateBuddyList(); // return; /*********************************************************/ //send the message to the remote URL, using the URL set above in ajaxSetup() //NOTE: the data being sent is just the userId currently, //The URL and/or the data will need changing so the server understands this is an add buddy request, and to add the buddy info to the request /* $.ajax({ //data : USER_ID, //add something here to indicate this is an add buddy request and include the buddyId data: "&type=addbuddy&clientID="+USER_ID+"&buddy="+buddyId+"&group=default", success : function(responseData, textStatus) { //if server sends back any successful status, then assume this means that this buddy is valid, so go ahead and add its if (responseData == 1) { //This is where we add the new buddy to the global buddy list //The status for the newly added buddy should be set to whatever the server returns, but just setting to 1 for now buddyList.push( {id : buddyId, status : 0} ); //TODO: get status for this buddy //And then update the displayed list updateBuddyList(); } else throw(textStatus); }, error : function(x,t,r) { if (t !=null) throw(t); else if (r != null) throw(r); } }); */ $.get(IM_URL+"?&type=addbuddy&clientID="+USER_ID+"&buddy="+buddyId.toLowerCase()+"&group=default", function(data){ if (data ==1){ //success buddyList.push( {id : buddyId, status : 0} ); updateBuddyList(); getBuddyList(); } else { alert ("No User Exists\nerror code: "+data); } }); } //Removes the highlighted buddy from the buddy list window function removeBuddy() { var selectedBuddy = $("#buddies .selected"); //should only be 1 selected, if none, then do nothing if (selectedBuddy.length != 1) return; var buddyId = selectedBuddy.attr('id'); /**************************************************************************************************** // Just for testing - remove this section when comm works $.each(buddyList, function(i, val) { //if the selected id matches the current is in the list, remove it from the buddyList array and return if (buddyId == val.id) { buddyList.splice(i, 1); return false; } }); //update the visual list updateBuddyList(); //and hide any buddy window with this id (really should remove it entirely, but this is ok for now $("#buddy_" + buddyId).hide(); return; *****************************************************************************************************/ //send the message to the remote URL, using the URL set above in ajaxSetup() //NOTE: the data being sent is just the userId currently, //The URL and/or the data will need changing so the server understands this is a remove buddy request, and to add the buddy info to the request /* $.ajax({ data : "type=removebuddy&clientID="+USER_ID+"&buddy="+buddyId+"&group=default", success : function(responseData, textStatus) { //doesnt matter what the server sends back - we will go ahead and remove it from our list anyway if (responseData == 1) { $.each(buddyList, function(i, val) { //if the selected id matches the current is in the list, remove it from the buddyList array and return if (buddyId == val.id) { buddyList.splice(i, 1); return false; } }); //update the visual list updateBuddyList(); //and hide any buddy window with this id (really should remove it entirely, but this is ok for now $("#buddy_" + buddyId).hide(); } else { //throw(textStatus); } }, error : function(x,t,r) { if (t !=null) throw(t); else if (r != null) throw(r); } }); */ $.get(IM_URL+"?&type=removebuddy&clientID="+USER_ID+"&buddy="+buddyId.toLowerCase()+"&group=default", function(data){ if (data == 1){ //success $.each(buddyList, function(i, val) { //if the selected id matches the current is in the list, remove it from the buddyList array and return if (buddyId == val.id) { buddyList.splice(i, 1); return false; } }); //update the visual list updateBuddyList(); //and hide any buddy window with this id (really should remove it entirely, but this is ok for now $("#buddy_" + buddyId).hide(); } else { alert("error. code: "+data); } }); } //Send the status function sendStatus(status) { $.post(IM_URL+"?&type=status&status="+status+"&clientid="+USER_ID); } //Helper function to update the displayed buddy list from the global buddy list variable function updateBuddyList() { $("#buddies").html(""); var listHtml = ""; //for each buddy in the buddyList array, add it in a div tag to the html string $.each(buddyList, function(i, val) { //add a status class so the entrycould have different appearance depending on status var status = "status" + val.status; listHtml += "<div id=\"" + val.id + "\" class=\"buddyListId " + status + "\">" + val.id + "</div>"; }); //and refresh the buddy list window with the contents of this html string $("#buddies").html(listHtml); //add event handlers for the buddy list id when clicked $(".buddyListId").click(function() { //remove the selected class for all buddy id's $(".selected").css("background-color", "#eef"); $(".buddyListId").removeClass("selected"); //and add it to this one thay was just clicked $(this).addClass("selected"); }); //add event handlers for the buddy list id when double-clicked top open a chat window $(".buddyListId").dblclick(function() { //show the chat window, make the title and id both the same as the id ofthe buddy showWindow($(this).attr('id'), $(this).attr('id')) }); //scroll to the bottom of buddies window var buddiesElement = document.getElementById("buddies"); buddiesElement.scrollTop = buddiesElement.scrollHeight; buddyHover(); } function getHistory(){ $.get(IM_URL+"?&type=gethistory&clientID="+USER_ID, function(data){ }); } function buddyHover(){ $(".buddyListId").hover(function(){ if ($(this).hasClass("selected")){ $(this).css("background-color", "#7700bb"); } else { $(this).css("background-color", "#dae8ff"); } },function(){ if ($(this).hasClass("selected")){ $(this).css("background-color", "#7700bb"); } else { $(this).css("background-color", "#eef"); } }); } function eventListener(){ $.getJSON(IM_URL+"?&type=event&clientid="+USER_ID, function(data){ if (data == null){ } else { if (data.status == 0){ } else if (data.status == 1){ var messages = data.messages; updateMessages(messages); } else if (data.status == 2){ //data is just a buddylist buddyList = data.buddylist; updateBuddyList(); } else if (data.status == 3){ var messages = data.messages; buddyList = data.buddylist; updateMessages(messages); updateBuddyList(); } else { //else nothing... I dunno } } setTimeout('eventListener()', 1); }); } function updateMessages(messages){ //messages is an array $.each(messages, function(i, val) { var sender = val.sender; //var receiver = val.receiver; var message = val.text; var time = val.time; if ($("#buddy_"+sender).size() > 0){ //if the window is already open //make it appear if it isn't //$("#buddy_"+sender) $("#buddy_"+sender).css("display", "block"); addIncomingMessage(sender, message, time); } else { //make create the window template and add the message showWindow(sender, sender); addIncomingMessage(sender, message, time); } }); } function addIncomingMessage(sender, message, time){ var d = new Date(); var chatline = "<div class='chatLine'><em>"+d.toLocaleTimeString()+"</em> "+sender+": <strong>"+message+"</strong></div>"; $("#buddy_"+sender+" .budChat").append(chatline); $("#buddy_"+sender+" .budChat").scrollTo($("#buddy_"+sender+" .budChat").find(".chatLine:last").get(0)); }
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
// Copyright 2011 Google /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript