code
stringlengths
1
2.08M
language
stringclasses
1 value
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sergi Mansilla <sergi AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/ocaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ocaml_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var OcamlHighlightRules = require("./ocaml_highlight_rules").OcamlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new OcamlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); var indenter = /(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/; (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(\*(.*)\*\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(*" + line + "*)"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') && state === 'start' && indenter.test(line)) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/ocaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var OcamlHighlightRules = function() { var keywords = lang.arrayToMap(( "and|as|assert|begin|class|constraint|do|done|downto|else|end|" + "exception|external|for|fun|function|functor|if|in|include|" + "inherit|initializer|lazy|let|match|method|module|mutable|new|" + "object|of|open|or|private|rec|sig|struct|then|to|try|type|val|" + "virtual|when|while|with").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false").split("|") ); var builtinFunctions = lang.arrayToMap(( "abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|" + "add_available_units|add_big_int|add_buffer|add_channel|add_char|" + "add_initializer|add_int_big_int|add_interfaces|add_num|add_string|" + "add_substitute|add_substring|alarm|allocated_bytes|allow_only|" + "allow_unsafe_modules|always|append|appname_get|appname_set|" + "approx_num_exp|approx_num_fix|arg|argv|arith_status|array|" + "array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|" + "assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|" + "beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|" + "bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|" + "bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|" + "bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|" + "cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|" + "chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|" + "chown|chr|chroot|classify_float|clear|clear_available_units|" + "clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|" + "close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|" + "close_out|close_out_noerr|close_process|close_process|" + "close_process_full|close_process_in|close_process_out|close_subwindow|" + "close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|" + "combine|combine|command|compact|compare|compare_big_int|compare_num|" + "complex32|complex64|concat|conj|connect|contains|contains_from|contents|" + "copy|cos|cosh|count|count|counters|create|create_alarm|create_image|" + "create_matrix|create_matrix|create_matrix|create_object|" + "create_object_and_run_initializers|create_object_opt|create_process|" + "create_process|create_process_env|create_process_env|create_table|" + "current|current_dir_name|current_point|current_x|current_y|curveto|" + "custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|" + "delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|" + "dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|" + "double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|" + "draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|" + "dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|" + "environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|" + "error_message|escaped|establish_server|executable_name|execv|execve|execvp|" + "execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|" + "file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|" + "filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|" + "float|float32|float64|float_of_big_int|float_of_bits|float_of_int|" + "float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|" + "flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|" + "for_all|for_all2|force|force_newline|force_val|foreground|fork|" + "format_of_string|formatter_of_buffer|formatter_of_out_channel|" + "fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|" + "from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|" + "full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|" + "genarray_of_array1|genarray_of_array2|genarray_of_array3|get|" + "get_all_formatter_output_functions|get_approx_printing|get_copy|" + "get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|" + "get_formatter_output_functions|get_formatter_tag_functions|get_image|" + "get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|" + "get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|" + "get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|" + "getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|" + "getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|" + "getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|" + "getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|" + "getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|" + "global_replace|global_substitute|gmtime|green|grid|group_beginning|" + "group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|" + "hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|" + "incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|" + "infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|" + "input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|" + "int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|" + "int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|" + "is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|" + "is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|" + "kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|" + "lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|" + "lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|" + "loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|" + "logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|" + "lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|" + "make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|" + "marshal|match_beginning|match_end|matched_group|matched_string|max|" + "max_array_length|max_big_int|max_elt|max_float|max_int|max_num|" + "max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|" + "min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|" + "minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|" + "mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|" + "nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|" + "new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|" + "nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|" + "num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|" + "of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|" + "of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|" + "open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|" + "open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|" + "open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|" + "open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|" + "out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|" + "output_char|output_string|output_value|over_max_boxes|pack|params|" + "parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|" + "place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|" + "power_big_int_positive_big_int|power_big_int_positive_int|" + "power_int_positive_big_int|power_int_positive_int|power_num|" + "pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|" + "pp_get_all_formatter_output_functions|pp_get_ellipsis_text|" + "pp_get_formatter_output_functions|pp_get_formatter_tag_functions|" + "pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|" + "pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|" + "pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|" + "pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|" + "pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|" + "pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|" + "pp_set_all_formatter_output_functions|pp_set_ellipsis_text|" + "pp_set_formatter_out_channel|pp_set_formatter_output_functions|" + "pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|" + "pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|" + "pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|" + "prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|" + "print_bool|print_break|print_char|print_cut|print_endline|print_float|" + "print_flush|print_if_newline|print_int|print_newline|print_space|" + "print_stat|print_string|print_tab|print_tbreak|printf|prohibit|" + "public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|" + "raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|" + "read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|" + "recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|" + "regexp_string_case_fold|register|register_exception|rem|remember_mode|" + "remove|remove_assoc|remove_assq|rename|replace|replace_first|" + "replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|" + "rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|" + "rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|" + "run_initializers|run_initializers_opt|scanf|search_backward|" + "search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|" + "set_all_formatter_output_functions|set_approx_printing|" + "set_binary_mode_in|set_binary_mode_out|set_close_on_exec|" + "set_close_on_exec|set_color|set_ellipsis_text|" + "set_error_when_null_denominator|set_field|set_floating_precision|" + "set_font|set_formatter_out_channel|set_formatter_output_functions|" + "set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|" + "set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|" + "set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|" + "set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|" + "set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|" + "setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|" + "setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|" + "shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|" + "shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|" + "shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|" + "sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|" + "sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|" + "sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|" + "sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|" + "sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|" + "slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|" + "slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|" + "split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|" + "square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|" + "stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|" + "stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|" + "str_formatter|string|string_after|string_before|string_match|" + "string_of_big_int|string_of_bool|string_of_float|string_of_format|" + "string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|" + "string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|" + "sub_right|subset|subset|substitute_first|substring|succ|succ|" + "succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|" + "symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|" + "tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|" + "tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|" + "temp_file|text_size|time|time|time|timed_read|timed_write|times|times|" + "tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|" + "to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|" + "to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|" + "truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|" + "uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|" + "unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|" + "update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|" + "wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|" + "wait_timed_read|wait_timed_write|wait_write|waitpid|white|" + "widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|" + "Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|" + "Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|" + "Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|" + "Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|" + "MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|" + "Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|" + "Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak" ).split("|")); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : '\\(\\*.*?\\*\\)\\s*?$' }, { token : "comment", merge : true, regex : '\\(\\*.*', next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single char regex : "'.'" }, { token : "string", // " string merge : true, regex : '"', next : "qstring" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+\\.|\\-\\.|\\*\\.|\\/\\.|#|;;|\\+|\\-|\\*|\\*\\*\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|<-|=" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\)", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qstring" : [ { token : "string", regex : '"', next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(OcamlHighlightRules, TextHighlightRules); exports.OcamlHighlightRules = OcamlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/html_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/html'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var Mode = function() { var highlighter = new HtmlHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$behaviour = new XmlBehaviour(); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { return 0; }; this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/html_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(HtmlHighlightRules, TextHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/folding/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function() { MixedFoldMode.call(this, new XmlFoldMode({ // void elements "area": 1, "base": 1, "br": 1, "col": 1, "command": 1, "embed": 1, "hr": 1, "img": 1, "input": 1, "keygen": 1, "link": 1, "meta": 1, "param": 1, "source": 1, "track": 1, "wbr": 1, // optional tags "li": 1, "dt": 1, "dd": 1, "p": 1, "rt": 1, "rp": 1, "optgroup": 1, "option": 1, "colgroup": 1, "td": 1, "th": 1 }), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_eighties', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-eighties"; exports.cssText = "\ .ace-tomorrow-night-eighties .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night-eighties .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night-eighties .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow-night-eighties .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night-eighties .ace_scroller {\ background-color: #2D2D2D;\ }\ \ .ace-tomorrow-night-eighties .ace_text-layer {\ cursor: text;\ color: #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_cursor {\ border-left: 2px solid #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selection {\ background: #515151;\ }\ \ .ace-tomorrow-night-eighties.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #2D2D2D;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #6A6A6A;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_active_line {\ background: #393939;\ }\ \ .ace-tomorrow-night-eighties .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow-night-eighties .ace_marker-layer .ace_selected_word {\ border: 1px solid #515151;\ }\ \ .ace-tomorrow-night-eighties .ace_invisible {\ color: #6A6A6A;\ }\ \ .ace-tomorrow-night-eighties .ace_keyword, .ace-tomorrow-night-eighties .ace_meta {\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_keyword.ace_operator {\ color:#66CCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_language {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_numeric {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_constant.ace_other {\ color:#CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_invalid {\ color:#CDCDCD;\ background-color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_invalid.ace_deprecated {\ color:#CDCDCD;\ background-color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_support.ace_constant {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_fold {\ background-color: #6699CC;\ border-color: #CCCCCC;\ }\ \ .ace-tomorrow-night-eighties .ace_support.ace_function {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_storage {\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_storage.ace_type, .ace-tomorrow-night-eighties .ace_support.ace_type{\ color:#CC99CC;\ }\ \ .ace-tomorrow-night-eighties .ace_variable {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_variable.ace_parameter {\ color:#F99157;\ }\ \ .ace-tomorrow-night-eighties .ace_string {\ color:#99CC99;\ }\ \ .ace-tomorrow-night-eighties .ace_comment {\ color:#999999;\ }\ \ .ace-tomorrow-night-eighties .ace_variable {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_meta.ace_tag {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_entity.ace_other.ace_attribute-name {\ color:#F2777A;\ }\ \ .ace-tomorrow-night-eighties .ace_entity.ace_name.ace_function {\ color:#6699CC;\ }\ \ .ace-tomorrow-night-eighties .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night-eighties .ace_markup.ace_heading {\ color:#99CC99;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/merbivore', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-merbivore"; exports.cssText = "\ .ace-merbivore .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-merbivore .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-merbivore .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-merbivore .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-merbivore .ace_scroller {\ background-color: #161616;\ }\ \ .ace-merbivore .ace_text-layer {\ cursor: text;\ color: #E6E1DC;\ }\ \ .ace-merbivore .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-merbivore .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-merbivore .ace_marker-layer .ace_selection {\ background: #454545;\ }\ \ .ace-merbivore.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #161616;\ border-radius: 2px;\ }\ \ .ace-merbivore .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-merbivore .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-merbivore .ace_marker-layer .ace_active_line {\ background: #333435;\ }\ \ .ace-merbivore .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-merbivore .ace_marker-layer .ace_selected_word {\ border: 1px solid #454545;\ }\ \ .ace-merbivore .ace_invisible {\ color: #404040;\ }\ \ .ace-merbivore .ace_keyword, .ace-merbivore .ace_meta {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_constant, .ace-merbivore .ace_constant.ace_other {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_character, {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_character.ace_escape, {\ color:#1EDAFB;\ }\ \ .ace-merbivore .ace_constant.ace_language {\ color:#FDC251;\ }\ \ .ace-merbivore .ace_constant.ace_library {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_constant.ace_numeric {\ color:#58C554;\ }\ \ .ace-merbivore .ace_invalid {\ color:#FFFFFF;\ background-color:#990000;\ }\ \ .ace-merbivore .ace_support.ace_constant {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_fold {\ background-color: #FC6F09;\ border-color: #E6E1DC;\ }\ \ .ace-merbivore .ace_support.ace_function {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_storage {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_string {\ color:#8DFF0A;\ }\ \ .ace-merbivore .ace_comment {\ font-style:italic;\ color:#AD2EA4;\ }\ \ .ace-merbivore .ace_meta.ace_tag {\ color:#FC6F09;\ }\ \ .ace-merbivore .ace_entity.ace_other.ace_attribute-name {\ color:#FFFF89;\ }\ \ .ace-merbivore .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/idle_fingers', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-idle-fingers"; exports.cssText = "\ .ace-idle-fingers .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-idle-fingers .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-idle-fingers .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-idle-fingers .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-idle-fingers .ace_scroller {\ background-color: #323232;\ }\ \ .ace-idle-fingers .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-idle-fingers .ace_cursor {\ border-left: 2px solid #91FF00;\ }\ \ .ace-idle-fingers .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #91FF00;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_selection {\ background: rgba(90, 100, 126, 0.88);\ }\ \ .ace-idle-fingers.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #323232;\ border-radius: 2px;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_active_line {\ background: #353637;\ }\ \ .ace-idle-fingers .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-idle-fingers .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(90, 100, 126, 0.88);\ }\ \ .ace-idle-fingers .ace_invisible {\ color: #404040;\ }\ \ .ace-idle-fingers .ace_keyword, .ace-idle-fingers .ace_meta {\ color:#CC7833;\ }\ \ .ace-idle-fingers .ace_constant, .ace-idle-fingers .ace_constant.ace_other {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_constant.ace_character, {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_constant.ace_character.ace_escape, {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_invalid {\ color:#FFFFFF;\ background-color:#FF0000;\ }\ \ .ace-idle-fingers .ace_support.ace_constant {\ color:#6C99BB;\ }\ \ .ace-idle-fingers .ace_fold {\ background-color: #CC7833;\ border-color: #FFFFFF;\ }\ \ .ace-idle-fingers .ace_support.ace_function {\ color:#B83426;\ }\ \ .ace-idle-fingers .ace_variable.ace_parameter {\ font-style:italic;\ }\ \ .ace-idle-fingers .ace_string {\ color:#A5C261;\ }\ \ .ace-idle-fingers .ace_string.ace_regexp {\ color:#CCCC33;\ }\ \ .ace-idle-fingers .ace_comment {\ font-style:italic;\ color:#BC9458;\ }\ \ .ace-idle-fingers .ace_meta.ace_tag {\ color:#FFE5BB;\ }\ \ .ace-idle-fingers .ace_entity.ace_name {\ color:#FFC66D;\ }\ \ .ace-idle-fingers .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-idle-fingers .ace_collab.ace_user1 {\ color:#323232;\ background-color:#FFF980;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Skywriter. * * The Initial Developer of the Original Code is * Mozilla. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Julian Viereck (julian.viereck@gmail.com) * Harutyun Amirjanyan (harutyun@c9.io) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/keyboard/emacs', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function(require, exports, module) { var dom = require("../lib/dom"); var screenToTextBlockCoordinates = function(pageX, pageY) { var canvasPos = this.scroller.getBoundingClientRect(); var col = Math.floor( (pageX + this.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft()) / this.characterWidth ); var row = Math.floor( (pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop()) / this.lineHeight ); return this.session.screenToDocumentPosition(row, col); }; var HashHandler = require("./hash_handler").HashHandler; exports.handler = new HashHandler(); var initialized = false; exports.handler.attach = function(editor) { if (!initialized) { initialized = true; dom.importCssString('\ .emacs-mode .ace_cursor{\ border: 2px rgba(50,250,50,0.8) solid!important;\ -moz-box-sizing: border-box!important;\ box-sizing: border-box!important;\ background-color: rgba(0,250,0,0.9);\ opacity: 0.5;\ }\ .emacs-mode .ace_cursor.ace_hidden{\ opacity: 1;\ background-color: transparent;\ }\ .emacs-mode .ace_cursor.ace_overwrite {\ opacity: 1;\ background-color: transparent;\ border-width: 0 0 2px 2px !important;\ }\ .emacs-mode .ace_text-layer {\ z-index: 4\ }\ .emacs-mode .ace_cursor-layer {\ z-index: 2\ }', 'emacsMode' ); } editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; editor.setStyle("emacs-mode"); }; exports.handler.detach = function(editor) { delete editor.renderer.screenToTextCoordinates; editor.unsetStyle("emacs-mode"); }; var keys = require("../lib/keys").KEY_MODS; var eMods = { C: "ctrl", S: "shift", M: "alt" }; ["S-C-M", "S-C", "S-M", "C-M", "S", "C", "M"].forEach(function(c) { var hashId = 0; c.split("-").forEach(function(c){ hashId = hashId | keys[eMods[c]]; }); eMods[hashId] = c.toLowerCase() + "-"; }); exports.handler.bindKey = function(key, command) { if (!key) return; var ckb = this.commmandKeyBinding; key.split("|").forEach(function(keyPart) { keyPart = keyPart.toLowerCase(); ckb[keyPart] = command; keyPart = keyPart.split(" ")[0]; if (!ckb[keyPart]) ckb[keyPart] = "null"; }, this); }; exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { if (hashId == -1) { if (data.count) { var str = Array(data.count + 1).join(key); data.count = null; return {command: "insertstring", args: str}; } } if (key == "\x00") return; var modifier = eMods[hashId]; if (modifier == "c-" || data.universalArgument) { var count = parseInt(key[key.length - 1]); if (count) { data.count = count; return {command: "null"}; } } data.universalArgument = false; if (modifier) key = modifier + key; if (data.keyChain) key = data.keyChain += " " + key; var command = this.commmandKeyBinding[key]; data.keyChain = command == "null" ? key : ""; if (!command) return; if (command == "null") return {command: "null"}; if (command == "universalArgument") { data.universalArgument = true; return {command: "null"}; } if (typeof command != "string") { var args = command.args; command = command.command; } if (typeof command == "string") { command = this.commands[command] || data.editor.commands.commands[command]; } if (!command.readonly && !command.isYank) data.lastCommand = null; if (data.count) { var count = data.count; data.count = 0; return { args: args, command: { exec: function(editor, args) { for (var i = 0; i < count; i++) command.exec(editor, args); } } }; } return {command: command, args: args}; }; exports.emacsKeys = { // movement "Up|C-p" : "golineup", "Down|C-n" : "golinedown", "Left|C-b" : "gotoleft", "Right|C-f" : "gotoright", "C-Left|M-b" : "gotowordleft", "C-Right|M-f" : "gotowordright", "Home|C-a" : "gotolinestart", "End|C-e" : "gotolineend", "C-Home|S-M-,": "gotostart", "C-End|S-M-." : "gotoend", // selection "S-Up|S-C-p" : "selectup", "S-Down|S-C-n" : "selectdown", "S-Left|S-C-b" : "selectleft", "S-Right|S-C-f" : "selectright", "S-C-Left|S-M-b" : "selectwordleft", "S-C-Right|S-M-f" : "selectwordright", "S-Home|S-C-a" : "selecttolinestart", "S-End|S-C-e" : "selecttolineend", "S-C-Home" : "selecttostart", "S-C-End" : "selecttoend", "C-l|M-s" : "centerselection", "M-g": "gotoline", "C-x C-p": "selectall", // todo fix these "C-Down": "gotopagedown", "C-Up": "gotopageup", "PageDown|C-v": "gotopagedown", "PageUp|M-v": "gotopageup", "S-C-Down": "selectpagedown", "S-C-Up": "selectpageup", "C-s": "findnext", "C-r": "findprevious", "M-C-s": "findnext", "M-C-r": "findprevious", "S-M-5": "replace", // basic editing "Backspace": "backspace", "Delete|C-d": "del", "Return|C-m": {command: "insertstring", args: "\n"}, // "newline" "C-o": "splitline", "M-d|C-Delete": {command: "killWord", args: "right"}, "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"}, "C-k": "killLine", "C-y|S-Delete": "yank", "M-y": "yankRotate", "C-g": "keyboardQuit", "C-w": "killRegion", "M-w": "killRingSave", "C-Space": "setMark", "C-x C-x": "exchangePointAndMark", "C-t": "transposeletters", "M-u": "touppercase", "M-l": "tolowercase", "M-/": "autocomplete", "C-u": "universalArgument", "M-;": "togglecomment", "C-/|C-x u|S-C--|C-z": "undo", "S-C-/|S-C-x u|C--|S-C-z": "redo", //infinite undo? // vertical editing "C-x r": "selectRectangularRegion" // todo // "M-x" "C-x C-t" "M-t" "M-c" "F11" "C-M- "M-q" }; exports.handler.bindKeys(exports.emacsKeys); exports.handler.addCommands({ selectRectangularRegion: function(editor) { editor.multiSelect.toggleBlockSelection(); }, setMark: function() { }, exchangePointAndMark: { exec: function(editor) { var range = editor.selection.getRange(); editor.selection.setSelectionRange(range, !editor.selection.isBackwards()); }, readonly: true, multiselectAction: "forEach" }, killWord: { exec: function(editor, dir) { editor.clearSelection(); if (dir == "left") editor.selection.selectWordLeft(); else editor.selection.selectWordRight(); var range = editor.getSelectionRange(); var text = editor.session.getTextRange(range); exports.killRing.add(text); editor.session.remove(range); editor.clearSelection(); }, multiselectAction: "forEach" }, killLine: function(editor) { editor.selection.selectLine(); var range = editor.getSelectionRange(); var text = editor.session.getTextRange(range); exports.killRing.add(text); editor.session.remove(range); editor.clearSelection(); }, yank: function(editor) { editor.onPaste(exports.killRing.get()); editor.keyBinding.$data.lastCommand = "yank"; }, yankRotate: function(editor) { if (editor.keyBinding.$data.lastCommand != "yank") return; editor.undo(); editor.onPaste(exports.killRing.rotate()); editor.keyBinding.$data.lastCommand = "yank"; }, killRegion: function(editor) { exports.killRing.add(editor.getCopyText()); editor.cut(); }, killRingSave: function(editor) { exports.killRing.add(editor.getCopyText()); } }); var commands = exports.handler.commands; commands.yank.isYank = true; commands.yankRotate.isYank = true; exports.killRing = { $data: [], add: function(str) { str && this.$data.push(str); if (this.$data.length > 30) this.$data.shift(); }, get: function() { return this.$data[this.$data.length - 1] || ""; }, pop: function() { if (this.$data.length > 1) this.$data.pop(); return this.get(); }, rotate: function() { this.$data.unshift(this.$data.pop()); return this.get(); } }; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/scss', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/scss_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ScssHighlightRules = require("./scss_highlight_rules").ScssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new ScssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/scss_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ScssHighlightRules = function() { var properties = lang.arrayToMap( (function () { var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|"); var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" + "background-size|binding|border-bottom-colors|border-left-colors|" + "border-right-colors|border-top-colors|border-end|border-end-color|" + "border-end-style|border-end-width|border-image|border-start|" + "border-start-color|border-start-style|border-start-width|box-align|" + "box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" + "box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" + "column-rule-width|column-rule-style|column-rule-color|float-edge|" + "font-feature-settings|font-language-override|force-broken-image-icon|" + "image-region|margin-end|margin-start|opacity|outline|outline-color|" + "outline-offset|outline-radius|outline-radius-bottomleft|" + "outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" + "outline-style|outline-width|padding-end|padding-start|stack-sizing|" + "tab-size|text-blink|text-decoration-color|text-decoration-line|" + "text-decoration-style|transform|transform-origin|transition|" + "transition-delay|transition-duration|transition-property|" + "transition-timing-function|user-focus|user-input|user-modify|user-select|" + "window-shadow|border-radius").split("|"); var properties = ("azimuth|background-attachment|background-color|background-image|" + "background-position|background-repeat|background|border-bottom-color|" + "border-bottom-style|border-bottom-width|border-bottom|border-collapse|" + "border-color|border-left-color|border-left-style|border-left-width|" + "border-left|border-right-color|border-right-style|border-right-width|" + "border-right|border-spacing|border-style|border-top-color|" + "border-top-style|border-top-width|border-top|border-width|border|" + "bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" + "counter-reset|cue-after|cue-before|cue|cursor|direction|display|" + "elevation|empty-cells|float|font-family|font-size-adjust|font-size|" + "font-stretch|font-style|font-variant|font-weight|font|height|left|" + "letter-spacing|line-height|list-style-image|list-style-position|" + "list-style-type|list-style|margin-bottom|margin-left|margin-right|" + "margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" + "min-width|opacity|orphans|outline-color|" + "outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" + "padding-left|padding-right|padding-top|padding|page-break-after|" + "page-break-before|page-break-inside|page|pause-after|pause-before|" + "pause|pitch-range|pitch|play-during|position|quotes|richness|right|" + "size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" + "stress|table-layout|text-align|text-decoration|text-indent|" + "text-shadow|text-transform|top|unicode-bidi|vertical-align|" + "visibility|voice-family|volume|white-space|widows|width|word-spacing|" + "z-index").split("|"); //The return array var ret = []; //All prefixProperties will get the browserPrefix in //the begning by join the prefixProperties array with the value of browserPrefix for (var i=0, ln=browserPrefix.length; i<ln; i++) { Array.prototype.push.apply( ret, (( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|")) ); } //Add also prefixProperties and properties without any browser prefix Array.prototype.push.apply(ret, prefixProperties); Array.prototype.push.apply(ret, properties); return ret; })() ); var functions = lang.arrayToMap( ("hsl|hsla|rgb|rgba|url|attr|counter|counters|abs|adjust_color|adjust_hue|" + "alpha|join|blue|ceil|change_color|comparable|complement|darken|desaturate|" + "floor|grayscale|green|hue|if|invert|join|length|lighten|lightness|mix|" + "nth|opacify|opacity|percentage|quote|red|round|saturate|saturation|" + "scale_color|transparentize|type_of|unit|unitless|unqoute").split("|") ); var constants = lang.arrayToMap( ("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" + "block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" + "char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" + "decimal-leading-zero|decimal|default|disabled|disc|" + "distribute-all-lines|distribute-letter|distribute-space|" + "distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" + "hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" + "ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" + "ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" + "inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" + "keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" + "lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" + "medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" + "nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" + "overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" + "ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" + "solid|square|static|strict|super|sw-resize|table-footer-group|" + "table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" + "transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" + "vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" + "zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var keywords = lang.arrayToMap( ("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|def|end|declare").split("|") ) var tags = lang.arrayToMap( ("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" + "big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" + "command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" + "figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" + "header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" + "link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" + "option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" + "small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" + "textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : "constant.numeric", regex : numRe }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) return "support.type"; if (keywords.hasOwnProperty(value)) return "keyword"; else if (constants.hasOwnProperty(value)) return "constant.language"; else if (functions.hasOwnProperty(value)) return "support.function"; else if (colors.hasOwnProperty(value.toLowerCase())) return "support.constant.color"; else if (tags.hasOwnProperty(value.toLowerCase())) return "variable.language"; else return "text"; }, regex : "\\-?[@a-z_][@a-z0-9_\\-]*" }, { token : "variable", regex : "[a-z_\\-$][a-z0-9_\\-$]*\\b" }, { token: "variable.language", regex: "#[a-z0-9-_]+" }, { token: "variable.language", regex: "\\.[a-z0-9-_]+" }, { token: "variable.language", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { token : "keyword.operator", regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(ScssHighlightRules, TextHighlightRules); exports.ScssHighlightRules = ScssHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/chrome', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.cssClass = "ace-chrome"; exports.cssText = ".ace-chrome .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-chrome .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-chrome .ace_gutter {\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-chrome .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-chrome .ace_text-layer {\ cursor: text;\ }\ \ .ace-chrome .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-chrome .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-chrome .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-chrome .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-chrome .ace_line .ace_invalid {\ background-color: rgb(153, 0, 0);\ color: white;\ }\ \ .ace-chrome .ace_line .ace_fold {\ }\ \ .ace-chrome .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-chrome .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-chrome .ace_line .ace_support.ace_type,\ .ace-chrome .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-chrome .ace_variable.ace_parameter {\ font-style:italic;\ color:#FD971F;\ }\ .ace-chrome .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-chrome .ace_line .ace_comment {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_comment.ace_doc {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_comment.ace_doc.ace_tag {\ color: #236e24;\ }\ \ .ace-chrome .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-chrome .ace_line .ace_variable {\ color: rgb(49, 132, 149);\ }\ \ .ace-chrome .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-chrome .ace_entity.ace_name.ace_function {\ color: #0000A2;\ }\ \ .ace-chrome .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-chrome .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-chrome .ace_markup.ace_list {\ color:rgb(185, 6, 144);\ }\ \ .ace-chrome .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-chrome .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-chrome .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-chrome .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-chrome .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.07);\ }\ \ .ace-chrome .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-chrome .ace_storage,\ .ace-chrome .ace_line .ace_keyword,\ .ace-chrome .ace_meta.ace_tag {\ color: rgb(147, 15, 128);\ }\ \ .ace-chrome .ace_string.ace_regex {\ color: rgb(255, 0, 0)\ }\ \ .ace-chrome .ace_line .ace_string,\ .ace-chrome .ace_entity.ace_other.ace_attribute-name{\ color: #994409;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/liquid', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/liquid_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LiquidHighlightRules = require("./liquid_highlight_rules").LiquidHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new LiquidHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/liquid_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/lib/lang', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var lang = require("../lib/lang"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LiquidHighlightRules = function() { // see: https://developer.mozilla.org/en/Liquid/Reference/Global_Objects var functions = lang.arrayToMap( // Standard Filters ("date|capitalize|downcase|upcase|first|last|join|sort|map|size|escape|" + "escape_once|strip_html|strip_newlines|newline_to_br|replace|replace_first|" + "truncate|truncatewords|prepend|append|minus|plus|times|divided_by|split" ).split("|") ); var keywords = lang.arrayToMap( // Standard Tags ("capture|endcapture|case|endcase|when|comment|endcomment|" + "cycle|for|endfor|in|reversed|if|endif|else|elsif|include|endinclude|unless|endunless|" + // Commonly used tags "style|text|image|widget|plugin|marker|endmarker|tablerow|endtablerow").split("|") ); var builtinVariables = lang.arrayToMap( ['forloop'] // ("forloop\\.(length|index|index0|rindex|rindex0|first|last)|limit|offset|range" + // "tablerowloop\\.(length|index|index0|rindex|rindex0|first|last|col|col0|"+ // "col_first|col_last)").split("|") ); var definitions = lang.arrayToMap(("assign").split("|")); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "variable", regex : "{%", next : "liquid_start" }, { token : "variable", regex : "{{", next : "liquid_start" }, { token : "meta.tag", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "meta.tag", regex : "<(?=\\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] , liquid_start : [{ token: "variable", regex: "}}", next: "start" }, { token: "variable", regex: "%}", next: "start" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (functions.hasOwnProperty(value)) return "support.function"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (definitions.hasOwnProperty(value)) return "keyword.definition"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\/|\\*|\\-|\\+|=|!=|\\?\\:" }, { token : "paren.lparen", regex : /[\[\({]/ }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "text", regex : "\\s+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(LiquidHighlightRules, TextHighlightRules); exports.LiquidHighlightRules = LiquidHighlightRules; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sergi Mansilla <sergi AT c9 DOT io> * Harutyun Amirjanyan <harutyun AT c9 DOT io> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/keyboard/vim', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/keyboard/vim/commands', 'ace/keyboard/vim/maps/util'], function(require, exports, module) { var keyUtil = require("../lib/keys"); var cmds = require("./vim/commands"); var coreCommands = cmds.coreCommands; var util = require("./vim/maps/util"); var startCommands = { "i": { command: coreCommands.start }, "I": { command: coreCommands.startBeginning }, "a": { command: coreCommands.append }, "A": { command: coreCommands.appendEnd }, "ctrl-f": { command: "gotopagedown" }, "ctrl-b": { command: "gotopageup" }, }; exports.handler = { handleKeyboard: function(data, hashId, key, keyCode, e) { // ignore command keys (shift, ctrl etc.) if (hashId != 0 && (key == "" || key == "\x00")) return null; if (hashId == 1) key = "ctrl-" + key; if (data.state == "start") { if (hashId == -1 || hashId == 1) { if (cmds.inputBuffer.idle && startCommands[key]) return startCommands[key]; return { command: { exec: function(editor) {cmds.inputBuffer.push(editor, key);} } }; } // wait for input else if (key.length == 1 && (hashId == 0 || hashId == 4)) { //no modifier || shift return {command: "null", passEvent: true}; } else if (key == "esc") { return {command: coreCommands.stop}; } } else { if (key == "esc" || key == "ctrl-[") { data.state = "start"; return {command: coreCommands.stop}; } else if (key == "ctrl-w") { return {command: "removewordleft"}; } } }, attach: function(editor) { editor.on("click", exports.onCursorMove); if (util.currentMode !== "insert") cmds.coreCommands.stop.exec(editor); }, detach: function(editor) { editor.removeListener("click", exports.onCursorMove); util.noMode(editor); util.currentMode = "normal"; }, actions: cmds.actions }; exports.onCursorMove = function(e) { cmds.onCursorMove(e.editor, e); exports.onCursorMove.scheduled = false; }; }); define('ace/keyboard/vim/commands', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/maps/motions', 'ace/keyboard/vim/maps/operators', 'ace/keyboard/vim/maps/aliases', 'ace/keyboard/vim/registers'], function(require, exports, module) { "never use strict"; var util = require("./maps/util"); var motions = require("./maps/motions"); var operators = require("./maps/operators"); var alias = require("./maps/aliases"); var registers = require("./registers"); var NUMBER = 1; var OPERATOR = 2; var MOTION = 3; var ACTION = 4; var HMARGIN = 8; // Minimum amount of line separation between margins; var repeat = function repeat(fn, count, args) { while (0 < count--) fn.apply(this, args); }; var ensureScrollMargin = function(editor) { var renderer = editor.renderer; var pos = renderer.$cursorLayer.getPixelPosition(); var top = pos.top; var margin = HMARGIN * renderer.layerConfig.lineHeight; if (2 * margin > renderer.$size.scrollerHeight) margin = renderer.$size.scrollerHeight / 2; if (renderer.scrollTop > top - margin) { renderer.session.setScrollTop(top - margin); } if (renderer.scrollTop + renderer.$size.scrollerHeight < top + margin + renderer.lineHeight) { renderer.session.setScrollTop(top + margin + renderer.lineHeight - renderer.$size.scrollerHeight); } }; var actions = exports.actions = { "z": { param: true, fn: function(editor, range, count, param) { switch (param) { case "z": editor.alignCursor(null, 0.5); break; case "t": editor.alignCursor(null, 0); break; case "b": editor.alignCursor(null, 1); break; } } }, "r": { param: true, fn: function(editor, range, count, param) { if (param && param.length) { repeat(function() { editor.insert(param); }, count || 1); editor.navigateLeft(); } } }, "R": { fn: function(editor, range, count, param) { util.insertMode(editor); editor.setOverwrite(true); } }, "~": { fn: function(editor, range, count) { repeat(function() { var range = editor.selection.getRange(); if (range.isEmpty()) range.end.column++; var text = editor.session.getTextRange(range); var toggled = text.toUpperCase(); if (toggled == text) editor.navigateRight(); else editor.session.replace(range, toggled); }, count || 1); } }, "*": { fn: function(editor, range, count, param) { editor.selection.selectWord(); editor.findNext(); ensureScrollMargin(editor); var r = editor.selection.getRange(); editor.selection.setSelectionRange(r, true); } }, "#": { fn: function(editor, range, count, param) { editor.selection.selectWord(); editor.findPrevious(); ensureScrollMargin(editor); var r = editor.selection.getRange(); editor.selection.setSelectionRange(r, true); } }, "n": { fn: function(editor, range, count, param) { var options = editor.getLastSearchOptions(); options.backwards = false; editor.selection.moveCursorRight(); editor.selection.clearSelection(); editor.findNext(options); ensureScrollMargin(editor); var r = editor.selection.getRange(); r.end.row = r.start.row; r.end.column = r.start.column; editor.selection.setSelectionRange(r, true); } }, "N": { fn: function(editor, range, count, param) { var options = editor.getLastSearchOptions(); options.backwards = true; editor.findPrevious(options); ensureScrollMargin(editor); var r = editor.selection.getRange(); r.end.row = r.start.row; r.end.column = r.start.column; editor.selection.setSelectionRange(r, true); } }, "v": { fn: function(editor, range, count, param) { editor.selection.selectRight(); util.visualMode(editor, false); }, acceptsMotion: true }, "V": { fn: function(editor, range, count, param) { //editor.selection.selectLine(); //editor.selection.selectLeft(); var row = editor.getCursorPosition().row; editor.selection.clearSelection(); editor.selection.moveCursorTo(row, 0); editor.selection.selectLineEnd(); editor.selection.visualLineStart = row; util.visualMode(editor, true); }, acceptsMotion: true }, "Y": { fn: function(editor, range, count, param) { util.copyLine(editor); } }, "p": { fn: function(editor, range, count, param) { var defaultReg = registers._default; editor.setOverwrite(false); if (defaultReg.isLine) { var pos = editor.getCursorPosition(); var lines = defaultReg.text.split("\n"); editor.session.getDocument().insertLines(pos.row + 1, lines); editor.moveCursorTo(pos.row + 1, 0); } else { editor.navigateRight(); editor.insert(defaultReg.text); editor.navigateLeft(); } editor.setOverwrite(true); editor.selection.clearSelection(); } }, "P": { fn: function(editor, range, count, param) { var defaultReg = registers._default; editor.setOverwrite(false); if (defaultReg.isLine) { var pos = editor.getCursorPosition(); var lines = defaultReg.text.split("\n"); editor.session.getDocument().insertLines(pos.row, lines); editor.moveCursorTo(pos.row, 0); } else { editor.insert(defaultReg.text); } editor.setOverwrite(true); editor.selection.clearSelection(); } }, "J": { fn: function(editor, range, count, param) { var session = editor.session; range = editor.getSelectionRange(); var pos = {row: range.start.row, column: range.start.column}; count = count || range.end.row - range.start.row; var maxRow = Math.min(pos.row + (count || 1), session.getLength() - 1); range.start.column = session.getLine(pos.row).length; range.end.column = session.getLine(maxRow).length; range.end.row = maxRow; var text = ""; for (var i = pos.row; i < maxRow; i++) { var nextLine = session.getLine(i + 1); text += " " + /^\s*(.*)$/.exec(nextLine)[1] || ""; } session.replace(range, text); editor.moveCursorTo(pos.row, pos.column); } }, "u": { fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); for (var i = 0; i < count; i++) { editor.undo(); } editor.selection.clearSelection(); } }, "ctrl-r": { fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); for (var i = 0; i < count; i++) { editor.redo(); } editor.selection.clearSelection(); } }, ":": { fn: function(editor, range, count, param) { // not implemented } }, "/": { fn: function(editor, range, count, param) { // not implemented } }, "?": { fn: function(editor, range, count, param) { // not implemented } }, ".": { fn: function(editor, range, count, param) { util.onInsertReplaySequence = inputBuffer.lastInsertCommands; var previous = inputBuffer.previous; if (previous) // If there is a previous action inputBuffer.exec(editor, previous.action, previous.param); } } }; var inputBuffer = exports.inputBuffer = { accepting: [NUMBER, OPERATOR, MOTION, ACTION], currentCmd: null, //currentMode: 0, currentCount: "", // Types operator: null, motion: null, lastInsertCommands: [], push: function(editor, char, keyId) { this.idle = false; var wObj = this.waitingForParam; if (wObj) { this.exec(editor, wObj, char); } // If input is a number (that doesn't start with 0) else if (!(char === "0" && !this.currentCount.length) && (char.match(/^\d+$/) && this.isAccepting(NUMBER))) { // Assuming that char is always of type String, and not Number this.currentCount += char; this.currentCmd = NUMBER; this.accepting = [NUMBER, OPERATOR, MOTION, ACTION]; } else if (!this.operator && this.isAccepting(OPERATOR) && operators[char]) { this.operator = { char: char, count: this.getCount() }; this.currentCmd = OPERATOR; this.accepting = [NUMBER, MOTION, ACTION]; this.exec(editor, { operator: this.operator }); } else if (motions[char] && this.isAccepting(MOTION)) { this.currentCmd = MOTION; var ctx = { operator: this.operator, motion: { char: char, count: this.getCount() } }; if (motions[char].param) this.waitForParam(ctx); else this.exec(editor, ctx); } else if (alias[char] && this.isAccepting(MOTION)) { alias[char].operator.count = this.getCount(); this.exec(editor, alias[char]); } else if (actions[char] && this.isAccepting(ACTION)) { var actionObj = { action: { fn: actions[char].fn, count: this.getCount() } }; if (actions[char].param) { this.waitForParam(actionObj); } else { this.exec(editor, actionObj); } if (actions[char].acceptsMotion) this.idle = false; } else if (this.operator) { this.exec(editor, { operator: this.operator }, char); } else { this.reset(); } }, waitForParam: function(cmd) { this.waitingForParam = cmd; }, getCount: function() { var count = this.currentCount; this.currentCount = ""; return count && parseInt(count, 10); }, exec: function(editor, action, param) { var m = action.motion; var o = action.operator; var a = action.action; if (!param) param = action.param; if (o) { this.previous = { action: action, param: param }; } if (o && !editor.selection.isEmpty()) { if (operators[o.char].selFn) { operators[o.char].selFn(editor, editor.getSelectionRange(), o.count, param); this.reset(); } return; } // There is an operator, but no motion or action. We try to pass the // current char to the operator to see if it responds to it (an example // of this is the 'dd' operator). else if (!m && !a && o && param) { operators[o.char].fn(editor, null, o.count, param); this.reset(); } else if (m) { var run = function(fn) { if (fn && typeof fn === "function") { // There should always be a motion if (m.count && !motionObj.handlesCount) repeat(fn, m.count, [editor, null, m.count, param]); else fn(editor, null, m.count, param); } }; var motionObj = motions[m.char]; var selectable = motionObj.sel; if (!o) { if ((util.onVisualMode || util.onVisualLineMode) && selectable) run(motionObj.sel); else run(motionObj.nav); } else if (selectable) { repeat(function() { run(motionObj.sel); operators[o.char].fn(editor, editor.getSelectionRange(), o.count, param); }, o.count || 1); } this.reset(); } else if (a) { a.fn(editor, editor.getSelectionRange(), a.count, param); this.reset(); } handleCursorMove(editor); }, isAccepting: function(type) { return this.accepting.indexOf(type) !== -1; }, reset: function() { this.operator = null; this.motion = null; this.currentCount = ""; this.accepting = [NUMBER, OPERATOR, MOTION, ACTION]; this.idle = true; this.waitingForParam = null; } }; function setPreviousCommand(fn) { inputBuffer.previous = { action: { action: { fn: fn } } }; } exports.coreCommands = { start: { exec: function start(editor) { util.insertMode(editor); setPreviousCommand(start); } }, startBeginning: { exec: function startBeginning(editor) { editor.navigateLineStart(); util.insertMode(editor); setPreviousCommand(startBeginning); } }, // Stop Insert mode as soon as possible. Works like typing <Esc> in // insert mode. stop: { exec: function stop(editor) { inputBuffer.reset(); util.onVisualMode = false; util.onVisualLineMode = false; inputBuffer.lastInsertCommands = util.normalMode(editor); } }, append: { exec: function append(editor) { var pos = editor.getCursorPosition(); var lineLen = editor.session.getLine(pos.row).length; if (lineLen) editor.navigateRight(); util.insertMode(editor); setPreviousCommand(append); } }, appendEnd: { exec: function appendEnd(editor) { editor.navigateLineEnd(); util.insertMode(editor); setPreviousCommand(appendEnd); } } }; var handleCursorMove = exports.onCursorMove = function(editor, e) { if (util.currentMode === 'insert' || handleCursorMove.running) return; else if(!editor.selection.isEmpty()) { handleCursorMove.running = true; if (util.onVisualLineMode) { var originRow = editor.selection.visualLineStart; var cursorRow = editor.getCursorPosition().row; if(originRow <= cursorRow) { var endLine = editor.session.getLine(cursorRow); editor.selection.clearSelection(); editor.selection.moveCursorTo(originRow, 0); editor.selection.selectTo(cursorRow, endLine.length); } else { var endLine = editor.session.getLine(originRow); editor.selection.clearSelection(); editor.selection.moveCursorTo(originRow, endLine.length); editor.selection.selectTo(cursorRow, 0); } } handleCursorMove.running = false; return; } else { if (e && (util.onVisualLineMode || util.onVisualMode)) { editor.selection.clearSelection(); util.normalMode(editor); } handleCursorMove.running = true; var pos = editor.getCursorPosition(); var lineLen = editor.session.getLine(pos.row).length; if (lineLen && pos.column === lineLen) editor.navigateLeft(); handleCursorMove.running = false; } }; }); define('ace/keyboard/vim/maps/util', ['require', 'exports', 'module' , 'ace/keyboard/vim/registers', 'ace/lib/dom'], function(require, exports, module) { var registers = require("../registers"); var dom = require("../../../lib/dom"); dom.importCssString('.insert-mode. ace_cursor{\ border-left: 2px solid #333333;\ }\ .ace_dark.insert-mode .ace_cursor{\ border-left: 2px solid #eeeeee;\ }\ .normal-mode .ace_cursor{\ border: 0!important;\ background-color: red;\ opacity: 0.5;\ }', 'vimMode'); module.exports = { onVisualMode: false, onVisualLineMode: false, currentMode: 'normal', noMode: function(editor) { editor.unsetStyle('insert-mode'); editor.unsetStyle('normal-mode'); if (editor.commands.recording) editor.commands.toggleRecording(); editor.setOverwrite(false); }, insertMode: function(editor) { this.currentMode = 'insert'; // Switch editor to insert mode editor.setStyle('insert-mode'); editor.unsetStyle('normal-mode'); editor.setOverwrite(false); editor.keyBinding.$data.buffer = ""; editor.keyBinding.$data.state = "insertMode"; this.onVisualMode = false; this.onVisualLineMode = false; if(this.onInsertReplaySequence) { // Ok, we're apparently replaying ("."), so let's do it editor.commands.macro = this.onInsertReplaySequence; editor.commands.replay(editor); this.onInsertReplaySequence = null; this.normalMode(editor); } else { editor._emit("vimMode", "insert"); // Record any movements, insertions in insert mode if(!editor.commands.recording) editor.commands.toggleRecording(); } }, normalMode: function(editor) { // Switch editor to normal mode this.currentMode = 'normal'; editor.unsetStyle('insert-mode'); editor.setStyle('normal-mode'); editor.clearSelection(); var pos; if (!editor.getOverwrite()) { pos = editor.getCursorPosition(); if (pos.column > 0) editor.navigateLeft(); } editor.setOverwrite(true); editor.keyBinding.$data.buffer = ""; editor.keyBinding.$data.state = "start"; this.onVisualMode = false; this.onVisualLineMode = false; editor._emit("changeVimMode", "normal"); // Save recorded keystrokes if (editor.commands.recording) { editor.commands.toggleRecording(); return editor.commands.macro; } else { return []; } }, visualMode: function(editor, lineMode) { if ( (this.onVisualLineMode && lineMode) || (this.onVisualMode && !lineMode) ) { this.normalMode(editor); return; } editor.setStyle('insert-mode'); editor.unsetStyle('normal-mode'); editor._emit("changeVimMode", "visual"); if (lineMode) { this.onVisualLineMode = true; } else { this.onVisualMode = true; this.onVisualLineMode = false; } }, getRightNthChar: function(editor, cursor, char, n) { var line = editor.getSession().getLine(cursor.row); var matches = line.substr(cursor.column + 1).split(char); return n < matches.length ? matches.slice(0, n).join(char).length : null; }, getLeftNthChar: function(editor, cursor, char, n) { var line = editor.getSession().getLine(cursor.row); var matches = line.substr(0, cursor.column).split(char); return n < matches.length ? matches.slice(-1 * n).join(char).length : null; }, toRealChar: function(char) { if (char.length === 1) return char; if (/^shift-./.test(char)) return char[char.length - 1].toUpperCase(); else return ""; }, copyLine: function(editor) { var pos = editor.getCursorPosition(); editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); editor.selection.selectLine(); registers._default.isLine = true; registers._default.text = editor.getCopyText().replace(/\n$/, ""); editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); } }; }); define('ace/keyboard/vim/registers', ['require', 'exports', 'module' ], function(require, exports, module) { "never use strict"; module.exports = { _default: { text: "", isLine: false } }; }); "use strict" define('ace/keyboard/vim/maps/motions', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/search', 'ace/range'], function(require, exports, module) { var util = require("./util"); var keepScrollPosition = function(editor, fn) { var scrollTopRow = editor.renderer.getScrollTopRow(); var initialRow = editor.getCursorPosition().row; var diff = initialRow - scrollTopRow; fn && fn.call(editor); editor.renderer.scrollToRow(editor.getCursorPosition().row - diff); }; function Motion(getRange, type){ if (type == 'extend') var extend = true; else var reverse = type; this.nav = function(editor) { var r = getRange(editor); if (!r) return; if (!r.end) var a = r; else if (reverse) var a = r.start; else var a = r.end; editor.clearSelection(); editor.moveCursorTo(a.row, a.column); } this.sel = function(editor){ var r = getRange(editor); if (!r) return; if (extend) return editor.selection.setSelectionRange(r); if (!r.end) var a = r; else if (reverse) var a = r.start; else var a = r.end; editor.selection.selectTo(a.row, a.column); } } var nonWordRe = /[\s.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/; var wordSeparatorRe = /[.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/; var whiteRe = /\s/; var StringStream = function(editor, cursor) { var sel = editor.selection; this.range = sel.getRange(); cursor = cursor || sel.selectionLead; this.row = cursor.row; this.col = cursor.column; var line = editor.session.getLine(this.row); var maxRow = editor.session.getLength() this.ch = line[this.col] || '\n' this.skippedLines = 0; this.next = function() { this.ch = line[++this.col] || this.handleNewLine(1); //this.debug() return this.ch; } this.prev = function() { this.ch = line[--this.col] || this.handleNewLine(-1); //this.debug() return this.ch; } this.peek = function(dir) { var ch = line[this.col + dir]; if (ch) return ch; if (dir == -1) return '\n'; if (this.col == line.length - 1) return '\n'; return editor.session.getLine(this.row + 1)[0] || '\n'; } this.handleNewLine = function(dir) { if (dir == 1){ if (this.col == line.length) return '\n'; if (this.row == maxRow - 1) return ''; this.col = 0; this.row ++; line = editor.session.getLine(this.row); this.skippedLines++; return line[0] || '\n'; } if (dir == -1) { if (this.row == 0) return ''; this.row --; line = editor.session.getLine(this.row); this.col = line.length; this.skippedLines--; return '\n'; } } this.debug = function() { console.log(line.substring(0, this.col)+'|'+this.ch+'\''+this.col+'\''+line.substr(this.col+1)); } } var Search = require("ace/search").Search; var search = new Search(); function find(editor, needle, dir) { search.$options.needle = needle; search.$options.backwards = dir == -1; return search.find(editor.session); } var Range = require("ace/range").Range; module.exports = { "w": new Motion(function(editor) { var str = new StringStream(editor); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.next(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.next(); } while (str.ch && whiteRe.test(str.ch) && str.skippedLines < 2) str.next(); str.skippedLines == 2 && str.prev(); return {column: str.col, row: str.row}; }), "W": new Motion(function(editor) { var str = new StringStream(editor); while(str.ch && !(whiteRe.test(str.ch) && !whiteRe.test(str.peek(1))) && str.skippedLines < 2) str.next(); if (str.skippedLines == 2) str.prev(); else str.next(); return {column: str.col, row: str.row} }), "b": new Motion(function(editor) { var str = new StringStream(editor); str.prev(); while (str.ch && whiteRe.test(str.ch) && str.skippedLines > -2) str.prev(); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.prev(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.prev(); } str.ch && str.next(); return {column: str.col, row: str.row}; }), "B": new Motion(function(editor) { var str = new StringStream(editor) str.prev(); while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(-1))) && str.skippedLines > -2) str.prev(); if (str.skippedLines == -2) str.next(); return {column: str.col, row: str.row}; }, true), "e": new Motion(function(editor) { var str = new StringStream(editor); str.next(); while (str.ch && whiteRe.test(str.ch)) str.next(); if (str.ch && wordSeparatorRe.test(str.ch)) { while (str.ch && wordSeparatorRe.test(str.ch)) str.next(); } else { while (str.ch && !nonWordRe.test(str.ch)) str.next(); } str.ch && str.prev(); return {column: str.col, row: str.row}; }), "E": new Motion(function(editor) { var str = new StringStream(editor); str.next(); while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(1)))) str.next(); return {column: str.col, row: str.row}; }), "l": { nav: function(editor) { editor.navigateRight(); }, sel: function(editor) { var pos = editor.getCursorPosition(); var col = pos.column; var lineLen = editor.session.getLine(pos.row).length; // Solving the behavior at the end of the line due to the // different 0 index-based colum positions in ACE. if (lineLen && col !== lineLen) //In selection mode you can select the newline editor.selection.selectRight(); } }, "h": { nav: function(editor) { var pos = editor.getCursorPosition(); if (pos.column > 0) editor.navigateLeft(); }, sel: function(editor) { var pos = editor.getCursorPosition(); if (pos.column > 0) editor.selection.selectLeft(); } }, "k": { nav: function(editor) { editor.navigateUp(); }, sel: function(editor) { editor.selection.selectUp(); } }, "j": { nav: function(editor) { editor.navigateDown(); }, sel: function(editor) { editor.selection.selectDown(); } }, "i": { param: true, sel: function(editor, range, count, param) { switch (param) { case "w": editor.selection.selectWord(); break; case "W": editor.selection.selectAWord(); break; case "(": case "{": case "[": var cursor = editor.getCursorPosition() var end = editor.session.$findClosingBracket(param, cursor, /paren/) if (!end) return; var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/) if (!start) return; start.column ++; editor.selection.setSelectionRange(Range.fromPoints(start, end)) break case "'": case "\"": case "/": var end = find(editor, param, 1) if (!end) return; var start = find(editor, param, -1) if (!start) return; editor.selection.setSelectionRange(Range.fromPoints(start.end, end.start)) break } } }, "a": { param: true, sel: function(editor, range, count, param) { switch (param) { case "w": editor.selection.selectAWord(); break; case "W": editor.selection.selectAWord(); break; case "(": case "{": case "[": var cursor = editor.getCursorPosition(); var end = editor.session.$findClosingBracket(param, cursor, /paren/); if (!end) return; var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/); if (!start) return; end.column ++; editor.selection.setSelectionRange(Range.fromPoints(start, end)); break; case "'": case "\"": case "/": var end = find(editor, param, 1); if (!end) return; var start = find(editor, param, -1); if (!start) return; end.column ++; editor.selection.setSelectionRange(Range.fromPoints(start.start, end.end)); break; } } }, "f": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, column + cursor.column + 1); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, column + cursor.column + 1); } } }, "F": { param: true, handlesCount: true, nav: function(editor, range, count, param) { count = parseInt(count, 10) || 1; var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, cursor.column - column - 1); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, cursor.column - column - 1); } } }, "t": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, column + cursor.column); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getRightNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, column + cursor.column); } } }, "T": { param: true, handlesCount: true, nav: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.selection.clearSelection(); // Why does it select in the first place? ed.moveCursorTo(cursor.row, -column + cursor.column); } }, sel: function(editor, range, count, param) { var ed = editor; var cursor = ed.getCursorPosition(); var column = util.getLeftNthChar(editor, cursor, param, count || 1); if (typeof column === "number") { ed.moveCursorTo(cursor.row, -column + cursor.column); } } }, "^": { nav: function(editor) { editor.navigateLineStart(); }, sel: function(editor) { editor.selection.selectLineStart(); } }, "$": { nav: function(editor) { editor.navigateLineEnd(); }, sel: function(editor) { editor.selection.selectLineEnd(); } }, "0": { nav: function(editor) { var ed = editor; ed.navigateTo(ed.selection.selectionLead.row, 0); }, sel: function(editor) { var ed = editor; ed.selectTo(ed.selection.selectionLead.row, 0); } }, "G": { nav: function(editor, range, count, param) { if (!count && count !== 0) { // Stupid JS count = editor.session.getLength(); } editor.gotoLine(count); }, sel: function(editor, range, count, param) { if (!count && count !== 0) { // Stupid JS count = editor.session.getLength(); } editor.selection.selectTo(count, 0); } }, "g": { param: true, nav: function(editor, range, count, param) { switch(param) { case "m": console.log("Middle line"); break; case "e": console.log("End of prev word"); break; case "g": editor.gotoLine(count || 0); case "u": editor.gotoLine(count || 0); case "U": editor.gotoLine(count || 0); } }, sel: function(editor, range, count, param) { switch(param) { case "m": console.log("Middle line"); break; case "e": console.log("End of prev word"); break; case "g": editor.selection.selectTo(count || 0, 0); } } }, "o": { nav: function(editor, range, count, param) { count = count || 1; var content = ""; while (0 < count--) content += "\n"; if (content.length) { editor.navigateLineEnd() editor.insert(content); util.insertMode(editor); } } }, "O": { nav: function(editor, range, count, param) { var row = editor.getCursorPosition().row; count = count || 1; var content = ""; while (0 < count--) content += "\n"; if (content.length) { if(row > 0) { editor.navigateUp(); editor.navigateLineEnd() editor.insert(content); } else { editor.session.insert({row: 0, column: 0}, content); editor.navigateUp(); } util.insertMode(editor); } } }, "%": new Motion(function(editor){ var brRe = /[\[\]{}()]/g; var cursor = editor.getCursorPosition(); var ch = editor.session.getLine(cursor.row)[cursor.column]; if (!brRe.test(ch)) { var range = find(editor, brRe); if (!range) return; cursor = range.start; } var match = editor.session.findMatchingBracket({ row: cursor.row, column: cursor.column + 1 }); return match; }), "ctrl-d": { nav: function(editor, range, count, param) { editor.selection.clearSelection(); keepScrollPosition(editor, editor.gotoPageDown); }, sel: function(editor, range, count, param) { keepScrollPosition(editor, editor.selectPageDown); } }, "ctrl-u": { nav: function(editor, range, count, param) { editor.selection.clearSelection(); keepScrollPosition(editor, editor.gotoPageUp); }, sel: function(editor, range, count, param) { keepScrollPosition(editor, editor.selectPageUp); } }, }; module.exports.backspace = module.exports.left = module.exports.h; module.exports.right = module.exports.l; module.exports.up = module.exports.k; module.exports.down = module.exports.j; module.exports.pagedown = module.exports["ctrl-d"]; module.exports.pageup = module.exports["ctrl-u"]; }); define('ace/keyboard/vim/maps/operators', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/registers'], function(require, exports, module) { "never use strict"; var util = require("./util"); var registers = require("../registers"); module.exports = { "d": { selFn: function(editor, range, count, param) { registers._default.text = editor.getCopyText(); registers._default.isLine = util.onVisualLineMode; if(util.onVisualLineMode) editor.removeLines(); else editor.session.remove(range); util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "d": registers._default.text = ""; registers._default.isLine = true; for (var i = 0; i < count; i++) { editor.selection.selectLine(); registers._default.text += editor.getCopyText(); var selRange = editor.getSelectionRange(); editor.session.remove(selRange); editor.selection.clearSelection(); } registers._default.text = registers._default.text.replace(/\n$/, ""); break; default: if (range) { editor.selection.setSelectionRange(range); registers._default.text = editor.getCopyText(); registers._default.isLine = false; editor.session.remove(range); editor.selection.clearSelection(); } } } }, "c": { selFn: function(editor, range, count, param) { editor.session.remove(range); util.insertMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "c": for (var i = 0; i < count; i++) { editor.removeLines(); util.insertMode(editor); } break; default: if (range) { // range.end.column ++; editor.session.remove(range); util.insertMode(editor); } } } }, "y": { selFn: function(editor, range, count, param) { registers._default.text = editor.getCopyText(); registers._default.isLine = util.onVisualLineMode; editor.selection.clearSelection(); util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "y": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } registers._default.text = editor.getCopyText().replace(/\n$/, ""); editor.selection.clearSelection(); registers._default.isLine = true; editor.moveCursorToPosition(pos); break; default: if (range) { var pos = editor.getCursorPosition(); editor.selection.setSelectionRange(range); registers._default.text = editor.getCopyText(); registers._default.isLine = false; editor.selection.clearSelection(); editor.moveCursorTo(pos.row, pos.column); } } } }, ">": { selFn: function(editor, range, count, param) { count = count || 1; for (var i = 0; i < count; i++) { editor.indent(); } util.normalMode(editor); }, fn: function(editor, range, count, param) { count = parseInt(count || 1, 10); switch (param) { case ">": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } editor.indent(); editor.selection.clearSelection(); editor.moveCursorToPosition(pos); editor.navigateLineEnd(); editor.navigateLineStart(); break; } } }, "<": { selFn: function(editor, range, count, param) { count = count || 1; for (var i = 0; i < count; i++) { editor.blockOutdent(); } util.normalMode(editor); }, fn: function(editor, range, count, param) { count = count || 1; switch (param) { case "<": var pos = editor.getCursorPosition(); editor.selection.selectLine(); for (var i = 0; i < count - 1; i++) { editor.selection.moveCursorDown(); } editor.blockOutdent(); editor.selection.clearSelection(); editor.moveCursorToPosition(pos); editor.navigateLineEnd(); editor.navigateLineStart(); break; } } } }; }); "use strict" define('ace/keyboard/vim/maps/aliases', ['require', 'exports', 'module' ], function(require, exports, module) { module.exports = { "x": { operator: { char: "d", count: 1 }, motion: { char: "l", count: 1 } }, "X": { operator: { char: "d", count: 1 }, motion: { char: "h", count: 1 } }, "D": { operator: { char: "d", count: 1 }, motion: { char: "$", count: 1 } }, "C": { operator: { char: "c", count: 1 }, motion: { char: "$", count: 1 } }, "s": { operator: { char: "c", count: 1 }, motion: { char: "l", count: 1 } }, "S": { operator: { char: "c", count: 1 }, param: "c" } }; });
JavaScript
define('ace/mode/groovy', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/groovy_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GroovyHighlightRules = require("./groovy_highlight_rules").GroovyHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new GroovyHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/groovy_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GroovyHighlightRules = function() { var keywords = lang.arrayToMap( ("assert|with|abstract|continue|for|new|switch|" + "assert|default|goto|package|synchronized|" + "boolean|do|if|private|this|" + "break|double|implements|protected|throw|" + "byte|else|import|public|throws|" + "case|enum|instanceof|return|transient|" + "catch|extends|int|short|try|" + "char|final|interface|static|void|" + "class|finally|long|strictfp|volatile|" + "def|float|native|super|while").split("|") ); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object").split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", regex : '"""', next : "qqstring" }, { token : "string", regex : "'''", next : "qstring" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\?:|\\?\\.|\\*\\.|<=>|=~|==~|\\.@|\\*\\.@|\\.&|as|in|is|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "constant.language.escape", regex : /\$[\w\d]+/ }, { token : "constant.language.escape", regex : /\$\{[^"\}]+\}?/ }, { token : "string", regex : '"{3,5}', next : "start" }, { token : "string", regex : '.+?' } ], "qstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "string", regex : "'{3,5}", next : "start" }, { token : "string", regex : ".+?" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(GroovyHighlightRules, TextHighlightRules); exports.GroovyHighlightRules = GroovyHighlightRules; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/textmate', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tm"; exports.cssText = ".ace-tm .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tm .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tm .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tm .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tm .ace_fold {\ background-color: #6B72E6;\ }\ \ .ace-tm .ace_text-layer {\ cursor: text;\ }\ \ .ace-tm .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-tm .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-tm .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-tm .ace_line .ace_storage,\ .ace-tm .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-tm .ace_line .ace_constant {\ color: rgb(197, 6, 11);\ }\ \ .ace-tm .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-tm .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-tm .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-tm .ace_line .ace_invalid {\ background-color: rgba(255, 0, 0, 0.1);\ color: red;\ }\ \ .ace-tm .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-tm .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-tm .ace_line .ace_support.ace_type,\ .ace-tm .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-tm .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-tm .ace_line .ace_string {\ color: rgb(3, 106, 7);\ }\ \ .ace-tm .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-tm .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-tm .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-tm .ace_line .ace_variable {\ color: rgb(49, 132, 149);\ }\ \ .ace-tm .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-tm .ace_entity.ace_name.ace_function {\ color: #0000A2;\ }\ \ .ace-tm .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-tm .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-tm .ace_markup.ace_list {\ color:rgb(185, 6, 144);\ }\ \ .ace-tm .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ .ace-tm.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px white;\ border-radius: 2px;\ }\ .ace-tm .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-tm .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-tm .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-tm .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.07);\ }\ .ace-tm .ace_gutter_active_line{\ background-color : #dcdcdc;\ }\ \ .ace-tm .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-tm .ace_meta.ace_tag {\ color:rgb(0, 50, 198);\ }\ \ .ace-tm .ace_string.ace_regex {\ color: rgb(255, 0, 0)\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Jimenez <adam AT shiftcreate DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/dreamweaver', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-dreamweaver"; exports.cssText = ".ace-dreamweaver .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-dreamweaver .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-dreamweaver .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-dreamweaver .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-dreamweaver .ace_fold {\ background-color: #00F;\ }\ \ .ace-dreamweaver .ace_text-layer {\ cursor: text;\ }\ \ .ace-dreamweaver .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-dreamweaver .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-dreamweaver .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-dreamweaver .ace_line .ace_storage,\ .ace-dreamweaver .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_language {\ color: rgb(88, 92, 246);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-dreamweaver .ace_line .ace_invalid {\ background-color: rgb(153, 0, 0);\ color: white;\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_function {\ color: rgb(60, 76, 114);\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_type,\ .ace-dreamweaver .ace_line .ace_support.ace_class {\ color: #009;\ }\ \ .ace-dreamweaver .ace_line .ace_support.ace_php_tag {\ color: #f00;\ }\ \ .ace-dreamweaver .ace_line .ace_keyword.ace_operator {\ color: rgb(104, 118, 135);\ }\ \ .ace-dreamweaver .ace_line .ace_string {\ color: #00F;\ }\ \ .ace-dreamweaver .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-dreamweaver .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-dreamweaver .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-dreamweaver .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 205);\ }\ \ .ace-dreamweaver .ace_line .ace_variable {\ color: #06F\ }\ \ .ace-dreamweaver .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-dreamweaver .ace_entity.ace_name.ace_function {\ color: #00F;\ }\ \ .ace-dreamweaver .ace_markup.ace_markupine {\ text-decoration:underline;\ }\ \ .ace-dreamweaver .ace_markup.ace_heading {\ color: rgb(12, 7, 255);\ }\ \ .ace-dreamweaver .ace_markup.ace_list {\ color:rgb(185, 6, 144);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.07);\ }\ \ .ace-dreamweaver .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-dreamweaver .ace_meta.ace_tag {\ color:#009;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_anchor {\ color:#060;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_form {\ color:#F90;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_image {\ color:#909;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_script {\ color:#900;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_style {\ color:#909;\ }\ \ .ace-dreamweaver .ace_meta.ace_tag.ace_table {\ color:#099;\ }\ \ .ace-dreamweaver .ace_string.ace_regex {\ color: rgb(255, 0, 0)\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Jonathan Camile <jonathan.camile AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/sql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sql_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new SqlHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)--/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "--"); } }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/sql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SqlHighlightRules = function() { var keywords = lang.arrayToMap( ("select|from|where|and|or|group|by|order|limit|offset|having|as|case|" + "when|else|end|type|left|right|join|on|outer|desc|asc").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false|null").split("|") ); var builtinFunctions = lang.arrayToMap( ("count|min|max|avg|sum|rank|now|coalesce").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "--.*$" }, { token : "string", // " string regex : '".*"' }, { token : "string", // ' string regex : "'.*'" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { value = value.toLowerCase(); if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\(]" }, { token : "paren.rparen", regex : "[\\)]" }, { token : "text", regex : "\\s+" } ] }; }; oop.inherits(SqlHighlightRules, TextHighlightRules); exports.SqlHighlightRules = SqlHighlightRules; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/solarized_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-solarized-dark"; exports.cssText = "\ .ace-solarized-dark .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-solarized-dark .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-solarized-dark .ace_gutter {\ background: #09222b;\ color: #d0edf7;\ }\ \ .ace-solarized-dark .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-solarized-dark .ace_scroller {\ background-color: #002B36;\ }\ \ .ace-solarized-dark .ace_text-layer {\ cursor: text;\ color: #93A1A1;\ }\ \ .ace-solarized-dark .ace_cursor {\ border-left: 2px solid #D30102;\ }\ \ .ace-solarized-dark .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #D30102;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_selection {\ background: #073642;\ }\ \ .ace-solarized-dark.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002B36;\ border-radius: 2px;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_active_line {\ background: #073642;\ }\ \ .ace-solarized-dark .ace_gutter_active_line {\ background-color: #0d3440;\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_selected_word {\ border: 1px solid #073642;\ }\ \ .ace-solarized-dark .ace_invisible {\ color: rgba(147, 161, 161, 0.50);\ }\ \ .ace-solarized-dark .ace_keyword, .ace-solarized-dark .ace_meta {\ color:#859900;\ }\ \ .ace-solarized-dark .ace_constant.ace_language {\ color:#B58900;\ }\ \ .ace-solarized-dark .ace_constant.ace_numeric {\ color:#D33682;\ }\ \ .ace-solarized-dark .ace_constant.ace_other {\ color:#CB4B16;\ }\ \ .ace-solarized-dark .ace_fold {\ background-color: #268BD2;\ border-color: #93A1A1;\ }\ \ .ace-solarized-dark .ace_support.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_storage {\ color:#93A1A1;\ }\ \ .ace-solarized-dark .ace_variable {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_string {\ color:#2AA198;\ }\ \ .ace-solarized-dark .ace_string.ace_regexp {\ color:#D30102;\ }\ \ .ace-solarized-dark .ace_comment {\ font-style:italic;\ color:#657B83;\ }\ \ .ace-solarized-dark .ace_variable.ace_language {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_entity.ace_other.ace_attribute-name {\ color:#93A1A1;\ }\ \ .ace-solarized-dark .ace_entity.ace_name.ace_function {\ color:#268BD2;\ }\ \ .ace-solarized-dark .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/crimson_editor', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssText = ".ace-crimson-editor .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-crimson-editor .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-crimson-editor .ace_gutter {\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-crimson-editor .ace_gutter-layer {\ width: 100%;\ text-align: right;\ }\ \ .ace-crimson-editor .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-crimson-editor .ace_text-layer {\ cursor: text;\ color: rgb(64, 64, 64);\ }\ \ .ace-crimson-editor .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-crimson-editor .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-crimson-editor .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_identifier {\ color: black;\ }\ \ .ace-crimson-editor .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_language {\ color: rgb(255, 156, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_invalid {\ text-decoration: line-through;\ color: rgb(224, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_fold {\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_function {\ color: rgb(192, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_type,\ .ace-crimson-editor .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-crimson-editor .ace_line .ace_keyword.ace_operator {\ color: rgb(49, 132, 149);\ }\ \ .ace-crimson-editor .ace_line .ace_string {\ color: rgb(128, 0, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 64);\ }\ \ .ace-crimson-editor .ace_line .ace_variable {\ color: rgb(0, 64, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_active_line {\ background: rgb(232, 242, 254);\ }\ \ .ace-crimson-editor .ace_meta.ace_tag {\ color:rgb(28, 2, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-crimson-editor .ace_string.ace_regex {\ color: rgb(192, 0, 192);\ }"; exports.cssClass = "ace-crimson-editor"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/mono_industrial', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-mono-industrial"; exports.cssText = "\ .ace-mono-industrial .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-mono-industrial .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-mono-industrial .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-mono-industrial .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-mono-industrial .ace_scroller {\ background-color: #222C28;\ }\ \ .ace-mono-industrial .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selection {\ background: rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #222C28;\ border-radius: 2px;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_active_line {\ background: rgba(12, 13, 12, 0.25);\ }\ \ .ace-mono-industrial .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial .ace_invisible {\ color: rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_keyword, .ace-mono-industrial .ace_meta {\ color:#A39E64;\ }\ \ .ace-mono-industrial .ace_keyword.ace_operator {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_constant, .ace-mono-industrial .ace_constant.ace_other {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character.ace_escape, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_numeric {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_invalid {\ color:#FFFFFF;\ background-color:rgba(153, 0, 0, 0.68);\ }\ \ .ace-mono-industrial .ace_support.ace_constant {\ color:#C87500;\ }\ \ .ace-mono-industrial .ace_fold {\ background-color: #A8B3AB;\ border-color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_support.ace_function {\ color:#588E60;\ }\ \ .ace-mono-industrial .ace_storage {\ color:#C23B00;\ }\ \ .ace-mono-industrial .ace_variable {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_variable.ace_parameter {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_comment {\ color:#666C68;\ background-color:#151C19;\ }\ \ .ace-mono-industrial .ace_variable.ace_language {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_entity.ace_other.ace_attribute-name {\ color:#909993;\ }\ \ .ace-mono-industrial .ace_entity.ace_name {\ color:#5778B6;\ }\ \ .ace-mono-industrial .ace_entity.ace_name.ace_function {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
define('ace/mode/golang', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/golang_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GolangHighlightRules = require("./golang_highlight_rules").GolangHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new GolangHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; };//end getNextLineIndent this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/golang_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GolangHighlightRules = function() { var keywords = lang.arrayToMap( ("true|else|false|break|case|return|goto|if|const|" + "continue|struct|default|switch|for|" + "func|import|package|chan|defer|fallthrough|go|interface|map|range" + "select|type|var").split("|") ); var buildinConstants = lang.arrayToMap( ("nit|true|false|iota").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); } oop.inherits(GolangHighlightRules, TextHighlightRules); exports.GolangHighlightRules = GolangHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
define('ace/mode/haxe', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/haxe_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HaxeHighlightRules = require("./haxe_highlight_rules").HaxeHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new HaxeHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/haxe_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HaxeHighlightRules = function() { var keywords = lang.arrayToMap( ("break|case|cast|catch|class|continue|default|else|enum|extends|for|function|if|implements|import|in|inline|interface|new|override|package|private|public|return|static|super|switch|this|throw|trace|try|typedef|untyped|var|while|Array|Void|Bool|Int|UInt|Float|Dynamic|String|List|Hash|IntHash|Error|Unknown|Type|Std").split("|") ); var buildinConstants = lang.arrayToMap( ("null|true|false").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", merge : true, next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({<]" }, { token : "paren.rparen", regex : "[\\])}>]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(HaxeHighlightRules, TextHighlightRules); exports.HaxeHighlightRules = HaxeHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/tomorrow_night_bright', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-tomorrow-night-bright"; exports.cssText = "\ .ace-tomorrow-night-bright .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow-night-bright .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow-night-bright .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow-night-bright .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow-night-bright .ace_scroller {\ background-color: #000000;\ }\ \ .ace-tomorrow-night-bright .ace_text-layer {\ cursor: text;\ color: #DEDEDE;\ }\ \ .ace-tomorrow-night-bright .ace_cursor {\ border-left: 2px solid #9F9F9F;\ }\ \ .ace-tomorrow-night-bright .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #9F9F9F;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_selection {\ background: #424242;\ }\ \ .ace-tomorrow-night-bright.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #000000;\ border-radius: 2px;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #343434;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_active_line {\ background: #2A2A2A;\ }\ \ .ace-tomorrow-night-bright .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow-night-bright .ace_marker-layer .ace_selected_word {\ border: 1px solid #424242;\ }\ \ .ace-tomorrow-night-bright .ace_invisible {\ color: #343434;\ }\ \ .ace-tomorrow-night-bright .ace_keyword, .ace-tomorrow-night-bright .ace_meta {\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_keyword.ace_operator {\ color:#70C0B1;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_language {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_numeric {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_constant.ace_other {\ color:#EEEEEE;\ }\ \ .ace-tomorrow-night-bright .ace_invalid {\ color:#CED2CF;\ background-color:#DF5F5F;\ }\ \ .ace-tomorrow-night-bright .ace_invalid.ace_deprecated {\ color:#CED2CF;\ background-color:#B798BF;\ }\ \ .ace-tomorrow-night-bright .ace_support.ace_constant {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_fold {\ background-color: #7AA6DA;\ border-color: #DEDEDE;\ }\ \ .ace-tomorrow-night-bright .ace_support.ace_function {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_storage {\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_storage.ace_type, .ace-tomorrow-night-bright .ace_support.ace_type{\ color:#C397D8;\ }\ \ .ace-tomorrow-night-bright .ace_variable {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_variable.ace_parameter {\ color:#E78C45;\ }\ \ .ace-tomorrow-night-bright .ace_string {\ color:#B9CA4A;\ }\ \ .ace-tomorrow-night-bright .ace_string.ace_regexp {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_comment {\ color:#969896;\ }\ \ .ace-tomorrow-night-bright .ace_variable {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_meta.ace_tag {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_entity.ace_other.ace_attribute-name {\ color:#D54E53;\ }\ \ .ace-tomorrow-night-bright .ace_entity.ace_name.ace_function {\ color:#7AA6DA;\ }\ \ .ace-tomorrow-night-bright .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow-night-bright .ace_markup.ace_heading {\ color:#B9CA4A;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Wolfgang Meier * William Candillon <wcandillon AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/xquery', ['require', 'exports', 'module' , 'ace/worker/worker_client', 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xquery_highlight_rules', 'ace/mode/behaviour/xquery', 'ace/range'], function(require, exports, module) { var WorkerClient = require("../worker/worker_client").WorkerClient; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XQueryHighlightRules = require("./xquery_highlight_rules").XQueryHighlightRules; var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour; //var XQueryBackgroundHighlighter = require("./xquery_background_highlighter").XQueryBackgroundHighlighter; var Range = require("../range").Range; var Mode = function(parent) { this.$tokenizer = new Tokenizer(new XQueryHighlightRules().getRules()); this.$behaviour = new XQueryBehaviour(parent); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/); if (match) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*[\}\)]/.test(input); }; this.autoOutdent = function(state, doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*[\}\)])/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(:(.*):\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)"); } }; this.createWorker = function(session) { this.$deltas = []; var worker = new WorkerClient(["ace"], "worker-xquery.js", "ace/mode/xquery_worker", "XQueryWorker"); var that = this; session.getDocument().on('change', function(evt){ that.$deltas.push(evt.data); }); worker.attachToDocument(session.getDocument()); worker.on("start", function(e) { //console.log("start"); that.$deltas = []; }); worker.on("error", function(e) { session.setAnnotations([e.data]); }); worker.on("ok", function(e) { session.clearAnnotations(); }); worker.on("highlight", function(tokens) { var firstRow = 0; var lastRow = session.getLength() - 1; var lines = tokens.data.lines; var states = tokens.data.states; for(var i=0; i < that.$deltas.length; i++) { var delta = that.$deltas[i]; if (delta.action === "insertLines") { var newLineCount = delta.lines.length; for (var i = 0; i < newLineCount; i++) { lines.splice(delta.range.start.row + i, 0, undefined); states.splice(delta.range.start.row + i, 0, undefined); } } else if (delta.action === "insertText") { if (session.getDocument().isNewLine(delta.text)) { lines.splice(delta.range.end.row, 0, undefined); states.splice(delta.range.end.row, 0, undefined); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } else if (delta.action === "removeLines") { var oldLineCount = delta.lines.length; lines.splice(delta.range.start.row, oldLineCount); states.splice(delta.range.start.row, oldLineCount); } else if (delta.action === "removeText") { if (session.getDocument().isNewLine(delta.text)) { lines[delta.range.start.row] = undefined; lines.splice(delta.range.end.row, 1); states[delta.range.start.row] = undefined; states.splice(delta.range.end.row, 1); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } } session.bgTokenizer.lines = lines; session.bgTokenizer.states = states; session.bgTokenizer.fireUpdateEvent(firstRow, lastRow); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xquery_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XQueryHighlightRules = function() { var keywords = lang.arrayToMap( ("after|ancestor|ancestor-or-self|and|as|ascending|attribute|before|case|cast|castable|child|collation|comment|copy|count|declare|default|delete|descendant|descendant-or-self|descending|div|document|document-node|element|else|empty|empty-sequence|end|eq|every|except|first|following|following-sibling|for|function|ge|group|gt|idiv|if|import|insert|instance|intersect|into|is|item|last|le|let|lt|mod|modify|module|namespace|namespace-node|ne|node|only|or|order|ordered|parent|preceding|preceding-sibling|processing-instruction|rename|replace|return|satisfies|schema-attribute|schema-element|self|some|stable|start|switch|text|to|treat|try|typeswitch|union|unordered|validate|where|with|xquery|contains|paragraphs|sentences|times|words|by|collectionreturn|variable|version|option|when|encoding|toswitch|catch|tumbling|sliding|window|at|using|stemming|collection|schema|while|on|nodes|index|external|then|in|updating|value|of|containsbreak|loop|continue|exit|returning").split("|") ); // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", regex : "<\\!--", next : "comment" }, { token : "comment", regex : "\\(:", next : "comment" }, { token : "text", // opening tag regex : "<\\/?", next : "tag" }, { token : "constant", // number regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "variable", // variable regex : "\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b" }, { token: "string", regex : '".*?"' }, { token: "string", regex : "'.*?'" }, { token : "text", regex : "\\s+" }, { token: "support.function", regex: "\\w[\\w+_\\-:]+(?=\\()" }, { token : function(value) { if (keywords[value]) return "keyword"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token: "keyword.operator", regex: "\\*|=|<|>|\\-|\\+" }, { token: "lparen", regex: "[[({]" }, { token: "rparen", regex: "[\\])}]" } ], tag : [ { token : "text", regex : ">", next : "start" }, { token : "meta.tag", regex : "[-_a-zA-Z0-9:]+" }, { token : "text", regex : "\\s+" }, { token : "string", regex : '".*?"' }, { token : "string", regex : "'.*?'" } ], cdata : [ { token : "comment", regex : "\\]\\]>", next : "start" }, { token : "comment", regex : "\\s+" }, { token : "comment", regex : "(?:[^\\]]|\\](?!\\]>))+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token: "comment", regex : ".*:\\)", next : "start" }, { token : "comment", regex : ".+" } ] }; }; oop.inherits(XQueryHighlightRules, TextHighlightRules); exports.XQueryHighlightRules = XQueryHighlightRules; }); define('ace/mode/behaviour/xquery', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require('../behaviour').Behaviour; var CstyleBehaviour = require('./cstyle').CstyleBehaviour; var XQueryBehaviour = function (parent) { this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour this.parent = parent; this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } return false; }); // Check for open tag if user enters / and auto-close it. this.add("slash", "insertion", function (state, action, editor, session, text) { if (text == "/") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (cursor.column > 0 && line.charAt(cursor.column - 1) == "<") { line = line.substring(0, cursor.column) + "/" + line.substring(cursor.column); var lines = session.doc.getAllLines(); lines[cursor.row] = line; // call mode helper to close the tag if possible parent.exec("closeTag", lines.join(session.doc.getNewLineCharacter()), cursor.row); } } return false; }); } oop.inherits(XQueryBehaviour, Behaviour); exports.XQueryBehaviour = XQueryBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/clouds_midnight', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-clouds-midnight"; exports.cssText = "\ .ace-clouds-midnight .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-clouds-midnight .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-clouds-midnight .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-clouds-midnight .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-clouds-midnight .ace_scroller {\ background-color: #191919;\ }\ \ .ace-clouds-midnight .ace_text-layer {\ cursor: text;\ color: #929292;\ }\ \ .ace-clouds-midnight .ace_cursor {\ border-left: 2px solid #7DA5DC;\ }\ \ .ace-clouds-midnight .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #7DA5DC;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_selection {\ background: #000000;\ }\ \ .ace-clouds-midnight.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #191919;\ border-radius: 2px;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #BFBFBF;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_active_line {\ background: rgba(215, 215, 215, 0.031);\ }\ \ .ace-clouds-midnight .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-clouds-midnight .ace_marker-layer .ace_selected_word {\ border: 1px solid #000000;\ }\ \ .ace-clouds-midnight .ace_invisible {\ color: #BFBFBF;\ }\ \ .ace-clouds-midnight .ace_keyword, .ace-clouds-midnight .ace_meta {\ color:#927C5D;\ }\ \ .ace-clouds-midnight .ace_keyword.ace_operator {\ color:#4B4B4B;\ }\ \ .ace-clouds-midnight .ace_constant.ace_language {\ color:#39946A;\ }\ \ .ace-clouds-midnight .ace_constant.ace_numeric {\ color:#46A609;\ }\ \ .ace-clouds-midnight .ace_invalid {\ color:#FFFFFF;\ background-color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_fold {\ background-color: #927C5D;\ border-color: #929292;\ }\ \ .ace-clouds-midnight .ace_support.ace_function {\ color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_storage {\ color:#E92E2E;\ }\ \ .ace-clouds-midnight .ace_string {\ color:#5D90CD;\ }\ \ .ace-clouds-midnight .ace_comment {\ color:#3C403B;\ }\ \ .ace-clouds-midnight .ace_entity.ace_other.ace_attribute-name {\ color:#606060;\ }\ \ .ace-clouds-midnight .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/coldfusion', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/coldfusion_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var XmlMode = require("./xml").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ColdfusionHighlightRules = require("./coldfusion_highlight_rules").ColdfusionHighlightRules; var Mode = function() { XmlMode.call(this); var highlighter = new ColdfusionHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); }; oop.inherits(Mode, XmlMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("jslint", function(results) { var errors = []; for (var i=0; i<results.data.length; i++) { var error = results.data[i]; if (error) errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: "warning", lint: error }); } session.setAnnotations(errors); }); worker.on("narcissus", function(e) { session.setAnnotations([e.data]); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/coldfusion_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/xml_util'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var xml_util = require("./xml_util"); var ColdfusionHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "meta.tag", regex : "<(?=\s*script)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xml_util.tag(this.$rules, "tag", "start"); xml_util.tag(this.$rules, "style", "css-start"); xml_util.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(ColdfusionHighlightRules, TextHighlightRules); exports.ColdfusionHighlightRules = ColdfusionHighlightRules; });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/python', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/python_highlight_rules', 'ace/mode/folding/pythonic', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var PythonFoldMode = require("./folding/pythonic").FoldMode; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new PythonHighlightRules().getRules()); this.foldingRules = new PythonFoldMode("\\:"); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; if (!tokens) return false; // ignore trailing comments do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { // outdenting in python is slightly different because it always applies // to the next line and only of a new line is inserted row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = lang.arrayToMap( ("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield").split("|") ); var builtinConstants = lang.arrayToMap( ("True|False|None|NotImplemented|Ellipsis|__debug__").split("|") ); var builtinFunctions = lang.arrayToMap( ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // """ string regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}' }, { token : "string", // multi line """ string start merge : true, regex : strPre + '"{3}.*$', next : "qqstring" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ''' string regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}" }, { token : "string", // multi line ''' string start merge : true, regex : strPre + "'{3}.*$", next : "qstring" }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // long integer regex : integer + "[lL]\\b" }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", // multi line """ string end regex : '(?:[^\\\\]|\\\\.)*?"{3}', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", // multi line ''' string end regex : "(?:[^\\\\]|\\\\.)*?'{3}", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; }); define('ace/mode/folding/pythonic', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(markers) { this.foldingStartMarker = new RegExp("(?:([\\[{])|(" + markers + "))(?:\\s*)(?:#.*)?$"); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { if (match[1]) return this.openingBracketBlock(session, match[1], row, match.index); if (match[2]) return this.indentationBlock(session, row, match.index + match[2].length); return this.indentationBlock(session, row); } } }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Shlomo Zalman Heigh <shlomozalmanheigh AT gmail DOT com> * Carin Meier * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ define('ace/mode/clojure', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/clojure_highlight_rules', 'ace/mode/matching_parens_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ClojureHighlightRules = require("./clojure_highlight_rules").ClojureHighlightRules; var MatchingParensOutdent = require("./matching_parens_outdent").MatchingParensOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new ClojureHighlightRules().getRules()); this.$outdent = new MatchingParensOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, ";"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/[\(\[]/); if (match) { indent += " "; } match = line.match(/[\)]/); if (match) { indent = ""; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/clojure_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ClojureHighlightRules = function() { var builtinFunctions = lang.arrayToMap( ('* *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* ' + '*command-line-args* *compile-files* *compile-path* *e *err* *file* ' + '*flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* ' + '*print-dup* *print-length* *print-level* *print-meta* *print-readably* ' + '*read-eval* *source-path* *use-context-classloader* ' + '*warn-on-reflection* + - -> -&gt; ->> -&gt;&gt; .. / < &lt; <= &lt;= = ' + '== > &gt; >= &gt;= accessor aclone ' + 'add-classpath add-watch agent agent-errors aget alength alias all-ns ' + 'alter alter-meta! alter-var-root amap ancestors and apply areduce ' + 'array-map aset aset-boolean aset-byte aset-char aset-double aset-float ' + 'aset-int aset-long aset-short assert assoc assoc! assoc-in associative? ' + 'atom await await-for await1 bases bean bigdec bigint binding bit-and ' + 'bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left ' + 'bit-shift-right bit-test bit-xor boolean boolean-array booleans ' + 'bound-fn bound-fn* butlast byte byte-array bytes cast char char-array ' + 'char-escape-string char-name-string char? chars chunk chunk-append ' + 'chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? ' + 'class class? clear-agent-errors clojure-version coll? comment commute ' + 'comp comparator compare compare-and-set! compile complement concat cond ' + 'condp conj conj! cons constantly construct-proxy contains? count ' + 'counted? create-ns create-struct cycle dec decimal? declare definline ' + 'defmacro defmethod defmulti defn defn- defonce defstruct delay delay? ' + 'deliver deref derive descendants destructure disj disj! dissoc dissoc! ' + 'distinct distinct? doall doc dorun doseq dosync dotimes doto double ' + 'double-array doubles drop drop-last drop-while empty empty? ensure ' + 'enumeration-seq eval even? every? false? ffirst file-seq filter find ' + 'find-doc find-ns find-var first float float-array float? floats flush ' + 'fn fn? fnext for force format future future-call future-cancel ' + 'future-cancelled? future-done? future? gen-class gen-interface gensym ' + 'get get-in get-method get-proxy-class get-thread-bindings get-validator ' + 'hash hash-map hash-set identical? identity if-let if-not ifn? import ' + 'in-ns inc init-proxy instance? int int-array integer? interleave intern ' + 'interpose into into-array ints io! isa? iterate iterator-seq juxt key ' + 'keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list ' + 'list* list? load load-file load-reader load-string loaded-libs locking ' + 'long long-array longs loop macroexpand macroexpand-1 make-array ' + 'make-hierarchy map map? mapcat max max-key memfn memoize merge ' + 'merge-with meta method-sig methods min min-key mod name namespace neg? ' + 'newline next nfirst nil? nnext not not-any? not-empty not-every? not= ' + 'ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ' + 'ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? ' + 'or parents partial partition pcalls peek persistent! pmap pop pop! ' + 'pop-thread-bindings pos? pr pr-str prefer-method prefers ' + 'primitives-classnames print print-ctor print-doc print-dup print-method ' + 'print-namespace-doc print-simple print-special-doc print-str printf ' + 'println println-str prn prn-str promise proxy proxy-call-with-super ' + 'proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot ' + 'rand rand-int range ratio? rational? rationalize re-find re-groups ' + 're-matcher re-matches re-pattern re-seq read read-line read-string ' + 'reduce ref ref-history-count ref-max-history ref-min-history ref-set ' + 'refer refer-clojure release-pending-sends rem remove remove-method ' + 'remove-ns remove-watch repeat repeatedly replace replicate require ' + 'reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq ' + 'rsubseq second select-keys send send-off seq seq? seque sequence ' + 'sequential? set set-validator! set? short short-array shorts ' + 'shutdown-agents slurp some sort sort-by sorted-map sorted-map-by ' + 'sorted-set sorted-set-by sorted? special-form-anchor special-symbol? ' + 'split-at split-with str stream? string? struct struct-map subs subseq ' + 'subvec supers swap! symbol symbol? sync syntax-symbol-anchor take ' + 'take-last take-nth take-while test the-ns time to-array to-array-2d ' + 'trampoline transient tree-seq true? type unchecked-add unchecked-dec ' + 'unchecked-divide unchecked-inc unchecked-multiply unchecked-negate ' + 'unchecked-remainder unchecked-subtract underive unquote ' + 'unquote-splicing update-in update-proxy use val vals var-get var-set ' + 'var? vary-meta vec vector vector? when when-first when-let when-not ' + 'while with-bindings with-bindings* with-in-str with-loading-context ' + 'with-local-vars with-meta with-open with-out-str with-precision xml-seq ' + 'zero? zipmap ').split(" ") ); var keywords = lang.arrayToMap( ('def do fn if let loop monitor-enter monitor-exit new quote recur set! ' + 'throw try var').split(" ") ); var buildinConstants = lang.arrayToMap( ("true false nil").split(" ") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : ";.*$" }, { token : "comment", // multi line comment regex : "^=begin$", next : "comment" }, { token : "keyword", //parens regex : "[\\(|\\)]" }, { token : "keyword", //lists regex : "[\\'\\(]" }, { token : "keyword", //vectors regex : "[\\[|\\]]" }, { token : "keyword", //sets and maps regex : "[\\{|\\}|\\#\\{|\\#\\}]" }, { token : "keyword", // ampersands regex : '[\\&]' }, { token : "keyword", // metadata regex : '[\\#\\^\\{]' }, { token : "keyword", // anonymous fn syntactic sugar regex : '[\\%]' }, { token : "keyword", // deref reader macro regex : '[@]' }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", regex : '[!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+||=|!=|<=|>=|<>|<|>|!|&&]' }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?$', next: "string" }, { token : "string", // symbol regex : "[:](?:[a-zA-Z]|\\d)+" }, { token : "string.regexp", //Regular Expressions regex : '/#"(?:\\.|(?:\\\")|[^\""\n])*"/g' } ], "comment" : [ { token : "comment", // closing comment regex : "^=end$", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "string" : [ { token : "string", merge : true, regex : "\\\\." }, { token : "string", regex : '[^"\\\\]*?"', next : "start" } ] }; }; oop.inherits(ClojureHighlightRules, TextHighlightRules); exports.ClojureHighlightRules = ClojureHighlightRules; }); define('ace/mode/matching_parens_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingParensOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\)/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\))/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingParensOutdent.prototype); exports.MatchingParensOutdent = MatchingParensOutdent; });
JavaScript
/******************** *System js Chinese Language Pack ********************/ var lang = { 'delnotice':'Are you sure you want to delete the data?', 'auditnotice':'Determine audit through?', 'unnotice':'You cancelled the operation!', 'nocolor':'No color', 'add':'Add', 'edit':'Edit', 'login':'Login', 'audit':'Audit', 'grant':'Grant', 'pselect':'Select the record', 'submit':'Submit', 'opersuccess':'The success of the operation', 'colorpicker':'Color picker', 'clearcolor':'Clear color', 'nopurivew':'No Permission', 'userorpasserror':'Login ID or password error', 'duplicate':'Duplicate record', 'notfound':'This page does not exist', 'iswater':'Whether to add a watermark' } /******************** *The validation form js Chinese language package ********************/ lang.validform = { 'onlyform':'Only supports form validation!', 'required':{ 'text':'* Here the content cannot be empty', 'checkmultiple':'* Please select at least one project', 'select':'* Please select an item', 'checkbox':'* You must select this box' }, 'min':{ 'text':'* At least ', 'text1':' characters ' }, 'max':{ 'text':'* A maximum of ', 'text1':'characters' }, 'email':{ 'text':'* The email address is invalid.' }, 'equals':{ 'text':'* Please enter the same password' } }; /**************** *编辑器js中文语言包 ****************/ /******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : 'Source', preview : 'Preview', undo : 'Undo(Ctrl+Z)', redo : 'Redo(Ctrl+Y)', cut : 'Cut(Ctrl+X)', copy : 'Copy(Ctrl+C)', paste : 'Paste(Ctrl+V)', plainpaste : 'Paste as plain text', wordpaste : 'Paste from Word', selectall : 'Select all', justifyleft : 'Align left', justifycenter : 'Align center', justifyright : 'Align right', justifyfull : 'Align full', insertorderedlist : 'Ordered list', insertunorderedlist : 'Unordered list', indent : 'Increase indent', outdent : 'Decrease indent', subscript : 'Subscript', superscript : 'Superscript', formatblock : 'Paragraph format', fontname : 'Font family', fontsize : 'Font size', forecolor : 'Text color', hilitecolor : 'Highlight color', bold : 'Bold(Ctrl+B)', italic : 'Italic(Ctrl+I)', underline : 'Underline(Ctrl+U)', strikethrough : 'Strikethrough', removeformat : 'Remove format', image : 'Image', multiimage : 'Multi image', flash : 'Flash', media : 'Embeded media', table : 'Table', tablecell : 'Cell', hr : 'Insert horizontal line', emoticons : 'Insert emoticon', link : 'Link', unlink : 'Unlink', fullscreen : 'Toggle fullscreen mode(Esc)', about : 'About', print : 'Print', filemanager : 'File Manager', code : 'Insert code', map : 'Google Maps', baidumap : 'Baidu Maps', lineheight : 'Line height', clearhtml : 'Clear HTML code', pagebreak : 'Insert Page Break', quickformat : 'Quick Format', insertfile : 'Insert file', template : 'Insert Template', anchor : 'Anchor', yes : 'OK', no : 'Cancel', close : 'Close', editImage : 'Image properties', deleteImage : 'Delete image', editFlash : 'Flash properties', deleteFlash : 'Delete flash', editMedia : 'Media properties', deleteMedia : 'Delete media', editLink : 'Link properties', deleteLink : 'Unlink', editAnchor : 'Anchor properties', deleteAnchor : 'Delete Anchor', tableprop : 'Table Properties', tablecellprop : 'Cell properties', tableinsert : 'Insert table', tabledelete : 'Delete table', tablecolinsertleft : 'Insert column left', tablecolinsertright : 'Insert column right', tablerowinsertabove : 'Insert row above', tablerowinsertbelow : 'Insert row below', tablerowmerge : 'Merge down', tablecolmerge : 'Merge right', tablerowsplit : 'Split row', tablecolsplit : 'Split column', tablecoldelete : 'Delete column', tablerowdelete : 'Delete row', noColor : 'Default', pleaseSelectFile : 'Please select file.', invalidImg : "Please type valid URL.\nAllowed file extension: jpg,gif,bmp,png", invalidMedia : "Please type valid URL.\nAllowed file extension: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb", invalidWidth : "The width must be number.", invalidHeight : "The height must be number.", invalidBorder : "The border must be number.", invalidUrl : "Please type valid URL.", invalidRows : 'Invalid rows.', invalidCols : 'Invalid columns.', invalidPadding : 'The padding must be number.', invalidSpacing : 'The spacing must be number.', invalidJson : 'Invalid JSON string.', uploadSuccess : 'Upload success.', cutError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+X) instead.', copyError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+C) instead.', pasteError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+V) instead.', ajaxLoading : 'Loading ...', uploadLoading : 'Uploading ...', uploadError : 'Upload Error', 'plainpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'wordpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.', 'link.url' : 'URL', 'link.linkType' : 'Target', 'link.newWindow' : 'New window', 'link.selfWindow' : 'Same window', 'flash.url' : 'URL', 'flash.width' : 'Width', 'flash.height' : 'Height', 'flash.upload' : 'Upload', 'flash.viewServer' : 'Browse', 'media.url' : 'URL', 'media.width' : 'Width', 'media.height' : 'Height', 'media.autostart' : 'Auto start', 'media.upload' : 'Upload', 'media.viewServer' : 'Browse', 'image.remoteImage' : 'Insert URL', 'image.localImage' : 'Upload', 'image.remoteUrl' : 'URL', 'image.localUrl' : 'File', 'image.size' : 'Size', 'image.width' : 'Width', 'image.height' : 'Height', 'image.resetSize' : 'Reset dimensions', 'image.align' : 'Align', 'image.defaultAlign' : 'Default', 'image.leftAlign' : 'Left', 'image.rightAlign' : 'Right', 'image.imgTitle' : 'Title', 'image.iswater' : 'watermark', 'image.upload' : 'Browse', 'image.viewServer' : 'Browse', 'multiimage.uploadDesc' : 'Allows users to upload <%=uploadLimit%> images, single image size not exceeding <%=sizeLimit%>', 'multiimage.iswater' : 'watermark', 'multiimage.startUpload' : 'Start upload', 'multiimage.clearAll' : 'Clear all', 'multiimage.insertAll' : 'Insert all', 'multiimage.queueLimitExceeded' : 'Queue limit exceeded.', 'multiimage.fileExceedsSizeLimit' : 'File exceeds size limit.', 'multiimage.zeroByteFile' : 'Zero byte file.', 'multiimage.invalidFiletype' : 'Invalid file type.', 'multiimage.unknownError' : 'Unknown upload error.', 'multiimage.pending' : 'Pending ...', 'multiimage.uploadError' : 'Upload error', 'filemanager.emptyFolder' : 'Blank', 'filemanager.moveup' : 'Parent folder', 'filemanager.viewType' : 'Display: ', 'filemanager.viewImage' : 'Thumbnails', 'filemanager.listImage' : 'List', 'filemanager.orderType' : 'Sorting: ', 'filemanager.fileName' : 'By name', 'filemanager.fileSize' : 'By size', 'filemanager.fileType' : 'By type', 'insertfile.url' : 'URL', 'insertfile.title' : 'Title', 'insertfile.upload' : 'Upload', 'insertfile.viewServer' : 'Browse', 'table.cells' : 'Cells', 'table.rows' : 'Rows', 'table.cols' : 'Columns', 'table.size' : 'Dimensions', 'table.width' : 'Width', 'table.height' : 'Height', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : 'Space', 'table.padding' : 'Padding', 'table.spacing' : 'Spacing', 'table.align' : 'Align', 'table.textAlign' : 'Horizontal', 'table.verticalAlign' : 'Vertical', 'table.alignDefault' : 'Default', 'table.alignLeft' : 'Left', 'table.alignCenter' : 'Center', 'table.alignRight' : 'Right', 'table.alignTop' : 'Top', 'table.alignMiddle' : 'Middle', 'table.alignBottom' : 'Bottom', 'table.alignBaseline' : 'Baseline', 'table.border' : 'Border', 'table.borderWidth' : 'Width', 'table.borderColor' : 'Color', 'table.backgroundColor' : 'Background', 'map.address' : 'Address: ', 'map.search' : 'Search', 'baidumap.address' : 'Address: ', 'baidumap.search' : 'Search', 'baidumap.insertDynamicMap' : 'Dynamic Map', 'anchor.name' : 'Anchor name', 'formatblock.formatBlock' : { h1 : 'Heading 1', h2 : 'Heading 2', h3 : 'Heading 3', h4 : 'Heading 4', p : 'Normal' }, 'fontname.fontName' : { 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Comic Sans MS' : 'Comic Sans MS', 'Courier New' : 'Courier New', 'Garamond' : 'Garamond', 'Georgia' : 'Georgia', 'Tahoma' : 'Tahoma', 'Times New Roman' : 'Times New Roman', 'Trebuchet MS' : 'Trebuchet MS', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : 'Line height 1'}, {'1.5' : 'Line height 1.5'}, {'2' : 'Line height 2'}, {'2.5' : 'Line height 2.5'}, {'3' : 'Line height 3'} ], 'template.selectTemplate' : 'Template', 'template.replaceContent' : 'Replace current content', 'template.fileList' : { '1.html' : 'Image and Text', '2.html' : 'Table', '3.html' : 'List' } }, 'zh_CN');
JavaScript
/******************** *系统js中文语言包 ********************/ var lang = { 'delnotice':'确定要删除数据吗?', 'auditnotice':'确定审核通过吗?', 'unnotice':'您取消了操作!', 'nocolor':'无颜色', 'add':'添加', 'edit':'编辑', 'login':'登录', 'audit':'审核', 'grant':'授权', 'pselect':'请选择记录', 'submit':'提交', 'opersuccess':'操作成功', 'colorpicker':'取色器', 'clearcolor':'清除颜色', 'nopurivew':'无权限', 'userorpasserror':'用户名或密码错误', 'duplicate':'记录重复', 'notfound':'该页面不存在', 'iswater':'是否添加水印' } /******************** *验证表单js中文语言包 ********************/ lang.validform = { 'onlyform':'只支持form验证!', 'required':{ 'text':'* 此处内容不可为空', 'checkmultiple':'* 请至少选择一个项目', 'select':'* 请选择一个项目', 'checkbox':'* 您必须钩选此栏' }, 'min':{ 'text':'* 最少 ', 'text1':'个字符 ' }, 'max':{ 'text':'* 最多 ', 'text1':'个字符 ' }, 'email':{ 'text':'* 邮件地址无效' }, 'equals':{ 'text':'* 请输入与上面相同的密码' } }; /**************** *编辑器js中文语言包 ****************/ /******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.lang({ source : 'HTML代码', preview : '预览', undo : '后退(Ctrl+Z)', redo : '前进(Ctrl+Y)', cut : '剪切(Ctrl+X)', copy : '复制(Ctrl+C)', paste : '粘贴(Ctrl+V)', plainpaste : '粘贴为无格式文本', wordpaste : '从Word粘贴', selectall : '全选(Ctrl+A)', justifyleft : '左对齐', justifycenter : '居中', justifyright : '右对齐', justifyfull : '两端对齐', insertorderedlist : '编号', insertunorderedlist : '项目符号', indent : '增加缩进', outdent : '减少缩进', subscript : '下标', superscript : '上标', formatblock : '段落', fontname : '字体', fontsize : '文字大小', forecolor : '文字颜色', hilitecolor : '文字背景', bold : '粗体(Ctrl+B)', italic : '斜体(Ctrl+I)', underline : '下划线(Ctrl+U)', strikethrough : '删除线', removeformat : '删除格式', image : '图片', multiimage : '批量图片上传', flash : 'Flash', media : '视音频', table : '表格', tablecell : '单元格', hr : '插入横线', emoticons : '插入表情', link : '超级链接', unlink : '取消超级链接', fullscreen : '全屏显示(Esc)', about : '关于', print : '打印(Ctrl+P)', filemanager : '文件空间', code : '插入程序代码', map : 'Google地图', baidumap : '百度地图', lineheight : '行距', clearhtml : '清理HTML代码', pagebreak : '插入分页符', quickformat : '一键排版', insertfile : '插入文件', template : '插入模板', anchor : '锚点', yes : '确定', no : '取消', close : '关闭', editImage : '图片属性', deleteImage : '删除图片', editFlash : 'Flash属性', deleteFlash : '删除Flash', editMedia : '视音频属性', deleteMedia : '删除视音频', editLink : '超级链接属性', deleteLink : '取消超级链接', editAnchor : '锚点属性', deleteAnchor : '删除锚点', tableprop : '表格属性', tablecellprop : '单元格属性', tableinsert : '插入表格', tabledelete : '删除表格', tablecolinsertleft : '左侧插入列', tablecolinsertright : '右侧插入列', tablerowinsertabove : '上方插入行', tablerowinsertbelow : '下方插入行', tablerowmerge : '向下合并单元格', tablecolmerge : '向右合并单元格', tablerowsplit : '拆分行', tablecolsplit : '拆分列', tablecoldelete : '删除列', tablerowdelete : '删除行', noColor : '无颜色', pleaseSelectFile : '请选择文件。', invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。", invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。", invalidWidth : "宽度必须为数字。", invalidHeight : "高度必须为数字。", invalidBorder : "边框必须为数字。", invalidUrl : "请输入有效的URL地址。", invalidRows : '行数为必选项,只允许输入大于0的数字。', invalidCols : '列数为必选项,只允许输入大于0的数字。', invalidPadding : '边距必须为数字。', invalidSpacing : '间距必须为数字。', invalidJson : '服务器发生故障。', uploadSuccess : '上传成功。', cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。', copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。', pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。', ajaxLoading : '加载中,请稍候 ...', uploadLoading : '上传中,请稍候 ...', uploadError : '上传错误', 'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。', 'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。', 'link.url' : 'URL', 'link.linkType' : '打开类型', 'link.newWindow' : '新窗口', 'link.selfWindow' : '当前窗口', 'flash.url' : 'URL', 'flash.width' : '宽度', 'flash.height' : '高度', 'flash.upload' : '上传', 'flash.viewServer' : '文件空间', 'media.url' : 'URL', 'media.width' : '宽度', 'media.height' : '高度', 'media.autostart' : '自动播放', 'media.upload' : '上传', 'media.viewServer' : '文件空间', 'image.remoteImage' : '网络图片', 'image.localImage' : '本地上传', 'image.remoteUrl' : '图片地址', 'image.localUrl' : '上传文件', 'image.size' : '图片大小', 'image.width' : '宽', 'image.height' : '高', 'image.resetSize' : '重置大小', 'image.align' : '对齐方式', 'image.defaultAlign' : '默认方式', 'image.leftAlign' : '左对齐', 'image.rightAlign' : '右对齐', 'image.imgTitle' : '图片说明', 'image.iswater' : '是否添加水印', 'image.upload' : '浏览...', 'image.viewServer' : '图片空间', 'multiimage.uploadDesc' : '允许用户同时上传<%=uploadLimit%>张图片,单张图片容量不超过<%=sizeLimit%>', 'multiimage.iswater' : '是否添加水印', 'multiimage.startUpload' : '开始上传', 'multiimage.clearAll' : '全部清空', 'multiimage.insertAll' : '全部插入', 'multiimage.queueLimitExceeded' : '文件数量超过限制。', 'multiimage.fileExceedsSizeLimit' : '文件大小超过限制。', 'multiimage.zeroByteFile' : '无法上传空文件。', 'multiimage.invalidFiletype' : '文件类型不正确。', 'multiimage.unknownError' : '发生异常,无法上传。', 'multiimage.pending' : '等待上传', 'multiimage.uploadError' : '上传失败', 'filemanager.emptyFolder' : '空文件夹', 'filemanager.moveup' : '移到上一级文件夹', 'filemanager.viewType' : '显示方式:', 'filemanager.viewImage' : '缩略图', 'filemanager.listImage' : '详细信息', 'filemanager.orderType' : '排序方式:', 'filemanager.fileName' : '名称', 'filemanager.fileSize' : '大小', 'filemanager.fileType' : '类型', 'insertfile.url' : 'URL', 'insertfile.title' : '文件说明', 'insertfile.upload' : '上传', 'insertfile.viewServer' : '文件空间', 'table.cells' : '单元格数', 'table.rows' : '行数', 'table.cols' : '列数', 'table.size' : '大小', 'table.width' : '宽度', 'table.height' : '高度', 'table.percent' : '%', 'table.px' : 'px', 'table.space' : '边距间距', 'table.padding' : '边距', 'table.spacing' : '间距', 'table.align' : '对齐方式', 'table.textAlign' : '水平对齐', 'table.verticalAlign' : '垂直对齐', 'table.alignDefault' : '默认', 'table.alignLeft' : '左对齐', 'table.alignCenter' : '居中', 'table.alignRight' : '右对齐', 'table.alignTop' : '顶部', 'table.alignMiddle' : '中部', 'table.alignBottom' : '底部', 'table.alignBaseline' : '基线', 'table.border' : '边框', 'table.borderWidth' : '边框', 'table.borderColor' : '颜色', 'table.backgroundColor' : '背景颜色', 'map.address' : '地址: ', 'map.search' : '搜索', 'baidumap.address' : '地址: ', 'baidumap.search' : '搜索', 'baidumap.insertDynamicMap' : '插入动态地图', 'anchor.name' : '锚点名称', 'formatblock.formatBlock' : { h1 : '标题 1', h2 : '标题 2', h3 : '标题 3', h4 : '标题 4', p : '正 文' }, 'fontname.fontName' : { 'SimSun' : '宋体', 'NSimSun' : '新宋体', 'FangSong_GB2312' : '仿宋_GB2312', 'KaiTi_GB2312' : '楷体_GB2312', 'SimHei' : '黑体', 'Microsoft YaHei' : '微软雅黑', 'Arial' : 'Arial', 'Arial Black' : 'Arial Black', 'Times New Roman' : 'Times New Roman', 'Courier New' : 'Courier New', 'Tahoma' : 'Tahoma', 'Verdana' : 'Verdana' }, 'lineheight.lineHeight' : [ {'1' : '单倍行距'}, {'1.5' : '1.5倍行距'}, {'2' : '2倍行距'}, {'2.5' : '2.5倍行距'}, {'3' : '3倍行距'} ], 'template.selectTemplate' : '可选模板', 'template.replaceContent' : '替换当前内容', 'template.fileList' : { '1.html' : '图片和文字', '2.html' : '表格', '3.html' : '项目编号' } }, 'zh_CN');
JavaScript
// BigInt, a suite of routines for performing multiple-precision arithmetic in // JavaScript. // // Copyright 1998-2005 David Shapiro. // // You may use, re-use, abuse, // copy, and modify this code to your liking, but please keep this header. // Thanks! // // Dave Shapiro // dave@ohdave.com // IMPORTANT THING: Be sure to set maxDigits according to your precision // needs. Use the setMaxDigits() function to do this. See comments below. // // Tweaked by Ian Bunning // Alterations: // Fix bug in function biFromHex(s) to allow // parsing of strings of length != 0 (mod 4) // Changes made by Dave Shapiro as of 12/30/2004: // // The BigInt() constructor doesn't take a string anymore. If you want to // create a BigInt from a string, use biFromDecimal() for base-10 // representations, biFromHex() for base-16 representations, or // biFromString() for base-2-to-36 representations. // // biFromArray() has been removed. Use biCopy() instead, passing a BigInt // instead of an array. // // The BigInt() constructor now only constructs a zeroed-out array. // Alternatively, if you pass <true>, it won't construct any array. See the // biCopy() method for an example of this. // // Be sure to set maxDigits depending on your precision needs. The default // zeroed-out array ZERO_ARRAY is constructed inside the setMaxDigits() // function. So use this function to set the variable. DON'T JUST SET THE // VALUE. USE THE FUNCTION. // // ZERO_ARRAY exists to hopefully speed up construction of BigInts(). By // precalculating the zero array, we can just use slice(0) to make copies of // it. Presumably this calls faster native code, as opposed to setting the // elements one at a time. I have not done any timing tests to verify this // claim. // Max number = 10^16 - 2 = 9999999999999998; // 2^53 = 9007199254740992; var biRadixBase = 2; var biRadixBits = 16; var bitsPerDigit = biRadixBits; var biRadix = 1 << 16; // = 2^16 = 65536 var biHalfRadix = biRadix >>> 1; var biRadixSquared = biRadix * biRadix; var maxDigitVal = biRadix - 1; var maxInteger = 9999999999999998; // maxDigits: // Change this to accommodate your largest number size. Use setMaxDigits() // to change it! // // In general, if you're working with numbers of size N bits, you'll need 2*N // bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need // // 1024 * 2 / 16 = 128 digits of storage. // var maxDigits; var ZERO_ARRAY; var bigZero, bigOne; function setMaxDigits(value) { maxDigits = value; ZERO_ARRAY = new Array(maxDigits); for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0; bigZero = new BigInt(); bigOne = new BigInt(); bigOne.digits[0] = 1; } setMaxDigits(20); // The maximum number of digits in base 10 you can convert to an // integer without JavaScript throwing up on you. var dpl10 = 15; // lr10 = 10 ^ dpl10 var lr10 = biFromNumber(1000000000000000); function BigInt(flag) { if (typeof flag == "boolean" && flag == true) { this.digits = null; } else { this.digits = ZERO_ARRAY.slice(0); } this.isNeg = false; } function biFromDecimal(s) { var isNeg = s.charAt(0) == '-'; var i = isNeg ? 1 : 0; var result; // Skip leading zeros. while (i < s.length && s.charAt(i) == '0') ++i; if (i == s.length) { result = new BigInt(); } else { var digitCount = s.length - i; var fgl = digitCount % dpl10; if (fgl == 0) fgl = dpl10; result = biFromNumber(Number(s.substr(i, fgl))); i += fgl; while (i < s.length) { result = biAdd(biMultiply(result, lr10), biFromNumber(Number(s.substr(i, dpl10)))); i += dpl10; } result.isNeg = isNeg; } return result; } function biCopy(bi) { var result = new BigInt(true); result.digits = bi.digits.slice(0); result.isNeg = bi.isNeg; return result; } function biFromNumber(i) { var result = new BigInt(); result.isNeg = i < 0; i = Math.abs(i); var j = 0; while (i > 0) { result.digits[j++] = i & maxDigitVal; i >>= biRadixBits; } return result; } function reverseStr(s) { var result = ""; for (var i = s.length - 1; i > -1; --i) { result += s.charAt(i); } return result; } var hexatrigesimalToChar = new Array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ); function biToString(x, radix) // 2 <= radix <= 36 { var b = new BigInt(); b.digits[0] = radix; var qr = biDivideModulo(x, b); var result = hexatrigesimalToChar[qr[1].digits[0]]; while (biCompare(qr[0], bigZero) == 1) { qr = biDivideModulo(qr[0], b); digit = qr[1].digits[0]; result += hexatrigesimalToChar[qr[1].digits[0]]; } return (x.isNeg ? "-" : "") + reverseStr(result); } function biToDecimal(x) { var b = new BigInt(); b.digits[0] = 10; var qr = biDivideModulo(x, b); var result = String(qr[1].digits[0]); while (biCompare(qr[0], bigZero) == 1) { qr = biDivideModulo(qr[0], b); result += String(qr[1].digits[0]); } return (x.isNeg ? "-" : "") + reverseStr(result); } var hexToChar = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); function digitToHex(n) { var mask = 0xf; var result = ""; for (i = 0; i < 4; ++i) { result += hexToChar[n & mask]; n >>>= 4; } return reverseStr(result); } function biToHex(x) { var result = ""; var n = biHighIndex(x); for (var i = biHighIndex(x); i > -1; --i) { result += digitToHex(x.digits[i]); } return result; } function charToHex(c) { var ZERO = 48; var NINE = ZERO + 9; var littleA = 97; var littleZ = littleA + 25; var bigA = 65; var bigZ = 65 + 25; var result; if (c >= ZERO && c <= NINE) { result = c - ZERO; } else if (c >= bigA && c <= bigZ) { result = 10 + c - bigA; } else if (c >= littleA && c <= littleZ) { result = 10 + c - littleA; } else { result = 0; } return result; } function hexToDigit(s) { var result = 0; var sl = Math.min(s.length, 4); for (var i = 0; i < sl; ++i) { result <<= 4; result |= charToHex(s.charCodeAt(i)) } return result; } function biFromHex(s) { var result = new BigInt(); var sl = s.length; for (var i = sl, j = 0; i > 0; i -= 4, ++j) { result.digits[j] = hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4))); } return result; } function biFromString(s, radix) { var isNeg = s.charAt(0) == '-'; var istop = isNeg ? 1 : 0; var result = new BigInt(); var place = new BigInt(); place.digits[0] = 1; // radix^0 for (var i = s.length - 1; i >= istop; i--) { var c = s.charCodeAt(i); var digit = charToHex(c); var biDigit = biMultiplyDigit(place, digit); result = biAdd(result, biDigit); place = biMultiplyDigit(place, radix); } result.isNeg = isNeg; return result; } function biDump(b) { return (b.isNeg ? "-" : "") + b.digits.join(" "); } function biAdd(x, y) { var result; if (x.isNeg != y.isNeg) { y.isNeg = !y.isNeg; result = biSubtract(x, y); y.isNeg = !y.isNeg; } else { result = new BigInt(); var c = 0; var n; for (var i = 0; i < x.digits.length; ++i) { n = x.digits[i] + y.digits[i] + c; result.digits[i] = n & 0xffff; c = Number(n >= biRadix); } result.isNeg = x.isNeg; } return result; } function biSubtract(x, y) { var result; if (x.isNeg != y.isNeg) { y.isNeg = !y.isNeg; result = biAdd(x, y); y.isNeg = !y.isNeg; } else { result = new BigInt(); var n, c; c = 0; for (var i = 0; i < x.digits.length; ++i) { n = x.digits[i] - y.digits[i] + c; result.digits[i] = n & 0xffff; // Stupid non-conforming modulus operation. if (result.digits[i] < 0) result.digits[i] += biRadix; c = 0 - Number(n < 0); } // Fix up the negative sign, if any. if (c == -1) { c = 0; for (var i = 0; i < x.digits.length; ++i) { n = 0 - result.digits[i] + c; result.digits[i] = n & 0xffff; // Stupid non-conforming modulus operation. if (result.digits[i] < 0) result.digits[i] += biRadix; c = 0 - Number(n < 0); } // Result is opposite sign of arguments. result.isNeg = !x.isNeg; } else { // Result is same sign. result.isNeg = x.isNeg; } } return result; } function biHighIndex(x) { var result = x.digits.length - 1; while (result > 0 && x.digits[result] == 0) --result; return result; } function biNumBits(x) { var n = biHighIndex(x); var d = x.digits[n]; var m = (n + 1) * bitsPerDigit; var result; for (result = m; result > m - bitsPerDigit; --result) { if ((d & 0x8000) != 0) break; d <<= 1; } return result; } function biMultiply(x, y) { var result = new BigInt(); var c; var n = biHighIndex(x); var t = biHighIndex(y); var u, uv, k; for (var i = 0; i <= t; ++i) { c = 0; k = i; for (j = 0; j <= n; ++j, ++k) { uv = result.digits[k] + x.digits[j] * y.digits[i] + c; result.digits[k] = uv & maxDigitVal; c = uv >>> biRadixBits; } result.digits[i + n + 1] = c; } // Someone give me a logical xor, please. result.isNeg = x.isNeg != y.isNeg; return result; } function biMultiplyDigit(x, y) { var n, c, uv; result = new BigInt(); n = biHighIndex(x); c = 0; for (var j = 0; j <= n; ++j) { uv = result.digits[j] + x.digits[j] * y + c; result.digits[j] = uv & maxDigitVal; c = uv >>> biRadixBits; } result.digits[1 + n] = c; return result; } function arrayCopy(src, srcStart, dest, destStart, n) { var m = Math.min(srcStart + n, src.length); for (var i = srcStart, j = destStart; i < m; ++i, ++j) { dest[j] = src[i]; } } var highBitMasks = new Array(0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800, 0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0, 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF); function biShiftLeft(x, n) { var digitCount = Math.floor(n / bitsPerDigit); var result = new BigInt(); arrayCopy(x.digits, 0, result.digits, digitCount, result.digits.length - digitCount); var bits = n % bitsPerDigit; var rightBits = bitsPerDigit - bits; for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) { result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) | ((result.digits[i1] & highBitMasks[bits]) >>> (rightBits)); } result.digits[0] = ((result.digits[i] << bits) & maxDigitVal); result.isNeg = x.isNeg; return result; } var lowBitMasks = new Array(0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF); function biShiftRight(x, n) { var digitCount = Math.floor(n / bitsPerDigit); var result = new BigInt(); arrayCopy(x.digits, digitCount, result.digits, 0, x.digits.length - digitCount); var bits = n % bitsPerDigit; var leftBits = bitsPerDigit - bits; for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) { result.digits[i] = (result.digits[i] >>> bits) | ((result.digits[i1] & lowBitMasks[bits]) << leftBits); } result.digits[result.digits.length - 1] >>>= bits; result.isNeg = x.isNeg; return result; } function biMultiplyByRadixPower(x, n) { var result = new BigInt(); arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n); return result; } function biDivideByRadixPower(x, n) { var result = new BigInt(); arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n); return result; } function biModuloByRadixPower(x, n) { var result = new BigInt(); arrayCopy(x.digits, 0, result.digits, 0, n); return result; } function biCompare(x, y) { if (x.isNeg != y.isNeg) { return 1 - 2 * Number(x.isNeg); } for (var i = x.digits.length - 1; i >= 0; --i) { if (x.digits[i] != y.digits[i]) { if (x.isNeg) { return 1 - 2 * Number(x.digits[i] > y.digits[i]); } else { return 1 - 2 * Number(x.digits[i] < y.digits[i]); } } } return 0; } function biDivideModulo(x, y) { var nb = biNumBits(x); var tb = biNumBits(y); var origYIsNeg = y.isNeg; var q, r; if (nb < tb) { // |x| < |y| if (x.isNeg) { q = biCopy(bigOne); q.isNeg = !y.isNeg; x.isNeg = false; y.isNeg = false; r = biSubtract(y, x); // Restore signs, 'cause they're references. x.isNeg = true; y.isNeg = origYIsNeg; } else { q = new BigInt(); r = biCopy(x); } return new Array(q, r); } q = new BigInt(); r = x; // Normalize Y. var t = Math.ceil(tb / bitsPerDigit) - 1; var lambda = 0; while (y.digits[t] < biHalfRadix) { y = biShiftLeft(y, 1); ++lambda; ++tb; t = Math.ceil(tb / bitsPerDigit) - 1; } // Shift r over to keep the quotient constant. We'll shift the // remainder back at the end. r = biShiftLeft(r, lambda); nb += lambda; // Update the bit count for x. var n = Math.ceil(nb / bitsPerDigit) - 1; var b = biMultiplyByRadixPower(y, n - t); while (biCompare(r, b) != -1) { ++q.digits[n - t]; r = biSubtract(r, b); } for (var i = n; i > t; --i) { var ri = (i >= r.digits.length) ? 0 : r.digits[i]; var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1]; var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2]; var yt = (t >= y.digits.length) ? 0 : y.digits[t]; var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1]; if (ri == yt) { q.digits[i - t - 1] = maxDigitVal; } else { q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt); } var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1); var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2); while (c1 > c2) { --q.digits[i - t - 1]; c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1); c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2); } b = biMultiplyByRadixPower(y, i - t - 1); r = biSubtract(r, biMultiplyDigit(b, q.digits[i - t - 1])); if (r.isNeg) { r = biAdd(r, b); --q.digits[i - t - 1]; } } r = biShiftRight(r, lambda); // Fiddle with the signs and stuff to make sure that 0 <= r < y. q.isNeg = x.isNeg != origYIsNeg; if (x.isNeg) { if (origYIsNeg) { q = biAdd(q, bigOne); } else { q = biSubtract(q, bigOne); } y = biShiftRight(y, lambda); r = biSubtract(y, r); } // Check for the unbelievably stupid degenerate case of r == -0. if (r.digits[0] == 0 && biHighIndex(r) == 0) r.isNeg = false; return new Array(q, r); } function biDivide(x, y) { return biDivideModulo(x, y)[0]; } function biModulo(x, y) { return biDivideModulo(x, y)[1]; } function biMultiplyMod(x, y, m) { return biModulo(biMultiply(x, y), m); } function biPow(x, y) { var result = bigOne; var a = x; while (true) { if ((y & 1) != 0) result = biMultiply(result, a); y >>= 1; if (y == 0) break; a = biMultiply(a, a); } return result; } function biPowMod(x, y, m) { var result = bigOne; var a = x; var k = y; while (true) { if ((k.digits[0] & 1) != 0) result = biMultiplyMod(result, a, m); k = biShiftRight(k, 1); if (k.digits[0] == 0 && biHighIndex(k) == 0) break; a = biMultiplyMod(a, a, m); } return result; } // BarrettMu, a class for performing Barrett modular reduction computations in // JavaScript. // // Requires BigInt.js. // // Copyright 2004-2005 David Shapiro. // // You may use, re-use, abuse, copy, and modify this code to your liking, but // please keep this header. // // Thanks! // // Dave Shapiro // dave@ohdave.com function BarrettMu(m) { this.modulus = biCopy(m); this.k = biHighIndex(this.modulus) + 1; var b2k = new BigInt(); b2k.digits[2 * this.k] = 1; // b2k = b^(2k) this.mu = biDivide(b2k, this.modulus); this.bkplus1 = new BigInt(); this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1) this.modulo = BarrettMu_modulo; this.multiplyMod = BarrettMu_multiplyMod; this.powMod = BarrettMu_powMod; } function BarrettMu_modulo(x) { var q1 = biDivideByRadixPower(x, this.k - 1); var q2 = biMultiply(q1, this.mu); var q3 = biDivideByRadixPower(q2, this.k + 1); var r1 = biModuloByRadixPower(x, this.k + 1); var r2term = biMultiply(q3, this.modulus); var r2 = biModuloByRadixPower(r2term, this.k + 1); var r = biSubtract(r1, r2); if (r.isNeg) { r = biAdd(r, this.bkplus1); } var rgtem = biCompare(r, this.modulus) >= 0; while (rgtem) { r = biSubtract(r, this.modulus); rgtem = biCompare(r, this.modulus) >= 0; } return r; } function BarrettMu_multiplyMod(x, y) { /* x = this.modulo(x); y = this.modulo(y); */ var xy = biMultiply(x, y); return this.modulo(xy); } function BarrettMu_powMod(x, y) { var result = new BigInt(); result.digits[0] = 1; var a = x; var k = y; while (true) { if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a); k = biShiftRight(k, 1); if (k.digits[0] == 0 && biHighIndex(k) == 0) break; a = this.multiplyMod(a, a); } return result; } // RSA, a suite of routines for performing RSA public-key computations in // JavaScript. // // Requires BigInt.js and Barrett.js. // // Copyright 1998-2005 David Shapiro. // // You may use, re-use, abuse, copy, and modify this code to your liking, but // please keep this header. // // Thanks! // // Dave Shapiro // dave@ohdave.com function RSAKeyPair(encryptionExponent, decryptionExponent, modulus) { this.e = biFromHex(encryptionExponent); this.d = biFromHex(decryptionExponent); this.m = biFromHex(modulus); // We can do two bytes per digit, so // chunkSize = 2 * (number of digits in modulus - 1). // Since biHighIndex returns the high index, not the number of digits, 1 has // already been subtracted. this.chunkSize = 2 * biHighIndex(this.m); this.radix = 16; this.barrett = new BarrettMu(this.m); } function twoDigit(n) { return (n < 10 ? "0" : "") + String(n); } function encryptedString(key, s) // Altered by Rob Saunders (rob@robsaunders.net). New routine pads the // string after it has been converted to an array. This fixes an // incompatibility with Flash MX's ActionScript. { var a = new Array(); var sl = s.length; var i = 0; while (i < sl) { a[i] = s.charCodeAt(i); i++; } while (a.length % key.chunkSize != 0) { a[i++] = 0; } var al = a.length; var result = ""; var j, k, block; for (i = 0; i < al; i += key.chunkSize) { block = new BigInt(); j = 0; for (k = i; k < i + key.chunkSize; ++j) { block.digits[j] = a[k++]; block.digits[j] += a[k++] << 8; } var crypt = key.barrett.powMod(block, key.e); var text = key.radix == 16 ? biToHex(crypt) : biToString(crypt, key.radix); result += text + " "; } return result.substring(0, result.length - 1); // Remove last space. } function decryptedString(key, s) { var blocks = s.split(" "); var result = ""; var i, j, block; for (i = 0; i < blocks.length; ++i) { var bi; if (key.radix == 16) { bi = biFromHex(blocks[i]); } else { bi = biFromString(blocks[i], key.radix); } block = key.barrett.powMod(bi, key.d); for (j = 0; j <= biHighIndex(block); ++j) { result += String.fromCharCode(block.digits[j] & 255, block.digits[j] >> 8); } } // Remove trailing null, if any. if (result.charCodeAt(result.length - 1) == 0) { result = result.substring(0, result.length - 1); } return result; } setMaxDigits(131); // Put this statement in your code to create a new RSA key with these parameters key = new RSAKeyPair( "210aaf1f35503622739895f23e9351e6127b486bb5e99b218c1a39a0f8263524f0f85bcb9ee7382df33f066e6f1d8a25126b80a97cdcc19cfa388bd850620f0300cf8a71186b6829f02d1f1d35b571f986d56016abd0e4735bb7fac2432a64ea1160e38f6858127e04656e0e14a740d9e10be9544be31d2fcc391c8efb673971", "26b6ebb4c1c5951df95b9106f9b6d86f9eb269fd552406dc4b2fa7acd0ee507b80c7046491ccac1b27f62b31d0cc64ec5f3313b979f3e5149b2b72b0771d67f37e3bf0d9b85deac0c1c7dd4b6aa13bbe66e41a56e7a434eb86ed46187a6de9f332c16359cbd5a3bcf0acd35c5a7a6ea47a863448749eda35ce2085c7170afc91", "36290d0b3fc705b554a3bbebf359ef00e27c7dabdc03de3b1ea887ed4315a8df4c7310448b1313ddc2283970652b7bcdcf3c28c4dd5e02db23b18b3caaa81f55a39036846ca30316f9d840f32a522bb6fccc0ba31d145f5e9a552696d9412ac5b916d10017a0487ed2e98c29c4ada4794f9a1ba2a458aa37f7e3311d530cb3b7" );
JavaScript
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u8303\u56F4,\u9700\u8981\u64A4\u9500\u5417?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u786E\u5B9A", updateStr: "\u786E\u5B9A", timeStr: "\u65F6\u95F4", quickStr: "\u5FEB\u901F\u9009\u62E9", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u65E5\u671F!' }
JavaScript
var $lang={ errAlertMsg: "Invalid date or the date out of range,redo or not?", aWeekStr: ["wk", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], aLongWeekStr:["wk","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"], aMonStr: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], aLongMonStr: ["January","February","March","April","May","June","July","August","September","October","November","December"], clearStr: "Clear", todayStr: "Today", okStr: "OK", updateStr: "OK", timeStr: "Time", quickStr: "Quick Selection", err_1: 'MinDate Cannot be bigger than MaxDate!' }
JavaScript
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u7BC4\u570D,\u9700\u8981\u64A4\u92B7\u55CE?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u78BA\u5B9A", updateStr: "\u78BA\u5B9A", timeStr: "\u6642\u9593", quickStr: "\u5FEB\u901F\u9078\u64C7", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u65BC\u6700\u5927\u65E5\u671F!' }
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('pagebreak', function(K) { var self = this; var name = 'pagebreak'; var pagebreakHtml = K.undef(self.pagebreakHtml, '<hr class="x6cmspage"/>'); self.clickToolbar(name, function() { var cmd = self.cmd, range = cmd.range; self.focus(); range.enlarge(true); cmd.split(true); var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<p id="__kindeditor_tail_tag__"></p>'; self.insertHtml(pagebreakHtml + tail); if (tail !== '') { var p = K('#__kindeditor_tail_tag__', self.edit.doc); range.selectNodeContents(p[0]); p.removeAttr('id'); cmd.select(); } }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('plainpaste', function(K) { var self = this, name = 'plainpaste'; self.clickToolbar(name, function() { var lang = self.lang(name + '.'), html = '<div style="padding:10px 20px;">' + '<div style="margin-bottom:10px;">' + lang.comment + '</div>' + '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' + '</div>', dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var html = textarea.val(); html = K.escape(html); html = html.replace(/ {2}/g, ' &nbsp;'); if (self.newlineTag == 'p') { html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>'); } else { html = html.replace(/\n/g, '<br />$&'); } self.insertHtml(html).hideDialog().focus(); } } }), textarea = K('textarea', dialog.div); textarea[0].focus(); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ // Google Maps: http://code.google.com/apis/maps/index.html KindEditor.plugin('map', function(K) { var self = this, name = 'map', lang = self.lang(name + '.'); self.clickToolbar(name, function() { var html = ['<div style="padding:10px 20px;">', '<div class="ke-dialog-row">', lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ', '<span class="ke-button-common ke-button-outer">', '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />', '</span>', '</div>', '<div class="ke-map" style="width:558px;height:360px;"></div>', '</div>'].join(''); var dialog = self.createDialog({ name : name, width : 600, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var geocoder = win.geocoder, map = win.map, center = map.getCenter().lat() + ',' + map.getCenter().lng(), zoom = map.getZoom(), maptype = map.getMapTypeId(), url = 'http://maps.googleapis.com/maps/api/staticmap'; url += '?center=' + encodeURIComponent(center); url += '&zoom=' + encodeURIComponent(zoom); url += '&size=558x360'; url += '&maptype=' + encodeURIComponent(maptype); url += '&markers=' + encodeURIComponent(center); url += '&language=' + self.langType; url += '&sensor=false'; self.exec('insertimage', url).hideDialog().focus(); } }, beforeRemove : function() { searchBtn.remove(); if (doc) { doc.write(''); } iframe.remove(); } }); var div = dialog.div, addressBox = K('[name="address"]', div), searchBtn = K('[name="searchBtn"]', div), win, doc; var iframeHtml = ['<!doctype html><html><head>', '<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />', '<style>', ' html { height: 100% }', ' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }', ' #map_canvas { height: 100% }', '</style>', '<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>', '<script>', 'var map, geocoder;', 'function initialize() {', ' var latlng = new google.maps.LatLng(31.230393, 121.473704);', ' var options = {', ' zoom: 11,', ' center: latlng,', ' disableDefaultUI: true,', ' panControl: true,', ' zoomControl: true,', ' mapTypeControl: true,', ' scaleControl: true,', ' streetViewControl: false,', ' overviewMapControl: true,', ' mapTypeId: google.maps.MapTypeId.ROADMAP', ' };', ' map = new google.maps.Map(document.getElementById("map_canvas"), options);', ' geocoder = new google.maps.Geocoder();', ' geocoder.geocode({latLng: latlng}, function(results, status) {', ' if (status == google.maps.GeocoderStatus.OK) {', ' if (results[3]) {', ' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;', ' }', ' }', ' });', '}', 'function search(address) {', ' if (!map) return;', ' geocoder.geocode({address : address}, function(results, status) {', ' if (status == google.maps.GeocoderStatus.OK) {', ' map.setZoom(11);', ' map.setCenter(results[0].geometry.location);', ' var marker = new google.maps.Marker({', ' map: map,', ' position: results[0].geometry.location', ' });', ' } else {', ' alert("Invalid address: " + address);', ' }', ' });', '}', '</script>', '</head>', '<body onload="initialize();">', '<div id="map_canvas" style="width:100%; height:100%"></div>', '</body></html>'].join('\n'); // TODO:用doc.write(iframeHtml)方式加载时,在IE6上第一次加载报错,暂时使用src方式 var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>'); function ready() { win = iframe[0].contentWindow; doc = K.iframeDoc(iframe); //doc.open(); //doc.write(iframeHtml); //doc.close(); } iframe.bind('load', function() { iframe.unbind('load'); if (K.IE) { ready(); } else { setTimeout(ready, 0); } }); K('.ke-map', div).replaceWith(iframe); // search map searchBtn.click(function() { win.search(addressBox.val()); }); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('flash', function(K) { var self = this, name = 'flash', lang = self.lang(name + '.'), allowFlashUpload = K.undef(self.allowFlashUpload, true), allowFileManager = K.undef(self.allowFileManager, false), formatUploadUrl = K.undef(self.formatUploadUrl, true), extraParams = K.undef(self.extraFileUploadParams, {}), filePostName = K.undef(self.filePostName, 'imgFile'), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'); self.plugin.flash = { edit : function() { var html = [ '<div style="padding:20px;">', //url '<div class="ke-dialog-row">', '<label for="keUrl" style="width:60px;">' + lang.url + '</label>', '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', //width '<div class="ke-dialog-row">', '<label for="keWidth" style="width:60px;">' + lang.width + '</label>', '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ', '</div>', //height '<div class="ke-dialog-row">', '<label for="keHeight" style="width:60px;">' + lang.height + '</label>', '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var url = K.trim(urlBox.val()), width = widthBox.val(), height = heightBox.val(); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } var html = K.mediaImg(self.themesPath + 'common/blank.gif', { src : url, type : K.mediaType('.swf'), width : width, height : height, quality : 'high' }); self.insertHtml(html).hideDialog().focus(); } } }), div = dialog.div, urlBox = K('[name="url"]', div), viewServerBtn = K('[name="viewServer"]', div), widthBox = K('[name="width"]', div), heightBox = K('[name="height"]', div); urlBox.val('http://'); if (allowFlashUpload) { var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : filePostName, extraParams : extraParams, url : uploadJson+'?dir=flash', afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var url = data.url; if (formatUploadUrl) { url = K.formatUrl(url, 'absolute'); } urlBox.val(url); if (self.afterUpload) { self.afterUpload.call(self, url, data, name); } alert(self.lang('uploadSuccess')); } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); }); } else { K('.ke-upload-button', div).hide(); } if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'LIST', dirName : 'flash', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); if (self.afterSelectFile) { self.afterSelectFile.call(self, url); } self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } var img = self.plugin.getSelectedFlash(); if (img) { var attrs = K.mediaAttrs(img.attr('data-ke-tag')); urlBox.val(attrs.src); widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0); heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0); } urlBox[0].focus(); urlBox[0].select(); }, 'delete' : function() { self.plugin.getSelectedFlash().remove(); } }; self.clickToolbar(name, self.plugin.flash.edit); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('preview', function(K) { var self = this, name = 'preview', undefined; self.clickToolbar(name, function() { var lang = self.lang(name + '.'), html = '<div style="padding:10px 20px;">' + '<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' + '</div>', dialog = self.createDialog({ name : name, width : 750, title : self.lang(name), body : html }), iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe); doc.open(); doc.write(self.fullHtml()); doc.close(); K(doc.body).css('background-color', '#FFF'); iframe[0].contentWindow.focus(); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('link', function(K) { var self = this, name = 'link'; self.plugin.link = { edit : function() { var lang = self.lang(name + '.'), html = '<div style="padding:20px;">' + //url '<div class="ke-dialog-row">' + '<label for="keUrl" style="width:60px;">' + lang.url + '</label>' + '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:260px;" /></div>' + //type '<div class="ke-dialog-row"">' + '<label for="keType" style="width:60px;">' + lang.linkType + '</label>' + '<select id="keType" name="type"></select>' + '</div>' + '</div>', dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var url = K.trim(urlBox.val()); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } self.exec('createlink', url, typeBox.val()).hideDialog().focus(); } } }), div = dialog.div, urlBox = K('input[name="url"]', div), typeBox = K('select[name="type"]', div); urlBox.val('http://'); typeBox[0].options[0] = new Option(lang.newWindow, '_blank'); typeBox[0].options[1] = new Option(lang.selfWindow, ''); self.cmd.selection(); var a = self.plugin.getSelectedLink(); if (a) { self.cmd.range.selectNode(a[0]); self.cmd.select(); urlBox.val(a.attr('data-ke-src')); typeBox.val(a.attr('target')); } urlBox[0].focus(); urlBox[0].select(); }, 'delete' : function() { self.exec('unlink', null); } }; self.clickToolbar(name, self.plugin.link.edit); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('insertfile', function(K) { var self = this, name = 'insertfile', allowFileUpload = K.undef(self.allowFileUpload, true), allowFileManager = K.undef(self.allowFileManager, false), formatUploadUrl = K.undef(self.formatUploadUrl, true), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'), extraParams = K.undef(self.extraFileUploadParams, {}), filePostName = K.undef(self.filePostName, 'imgFile'), lang = self.lang(name + '.'); self.plugin.fileDialog = function(options) { var fileUrl = K.undef(options.fileUrl, 'http://'), fileTitle = K.undef(options.fileTitle, ''), clickFn = options.clickFn; var html = [ '<div style="padding:20px;">', '<div class="ke-dialog-row">', '<label for="keUrl" style="width:60px;">' + lang.url + '</label>', '<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', //title '<div class="ke-dialog-row">', '<label for="keTitle" style="width:60px;">' + lang.title + '</label>', '<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>', '</div>', //form end '</form>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var url = K.trim(urlBox.val()), title = titleBox.val(); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (K.trim(title) === '') { title = url; } clickFn.call(self, url, title); } } }), div = dialog.div; var urlBox = K('[name="url"]', div), viewServerBtn = K('[name="viewServer"]', div), titleBox = K('[name="title"]', div); if (allowFileUpload) { var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : filePostName, url : uploadJson+'?dir=file', extraParams : extraParams, afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var url = data.url; if (formatUploadUrl) { url = K.formatUrl(url, 'absolute'); } urlBox.val(url); if (self.afterUpload) { self.afterUpload.call(self, url, data, name); } alert(self.lang('uploadSuccess')); } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); }); } else { K('.ke-upload-button', div).hide(); } if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'LIST', dirName : 'file', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); if (self.afterSelectFile) { self.afterSelectFile.call(self, url); } self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } urlBox.val(fileUrl); titleBox.val(fileTitle); urlBox[0].focus(); urlBox[0].select(); }; self.clickToolbar(name, function() { self.plugin.fileDialog({ clickFn : function(url, title) { var html = '<a href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>'; self.insertHtml(html).hideDialog().focus(); } }); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('media', function(K) { var self = this, name = 'media', lang = self.lang(name + '.'), allowMediaUpload = K.undef(self.allowMediaUpload, true), allowFileManager = K.undef(self.allowFileManager, false), formatUploadUrl = K.undef(self.formatUploadUrl, true), extraParams = K.undef(self.extraFileUploadParams, {}), filePostName = K.undef(self.filePostName, 'imgFile'), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'); self.plugin.media = { edit : function() { var html = [ '<div style="padding:20px;">', //url '<div class="ke-dialog-row">', '<label for="keUrl" style="width:60px;">' + lang.url + '</label>', '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', //width '<div class="ke-dialog-row">', '<label for="keWidth" style="width:60px;">' + lang.width + '</label>', '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />', '</div>', //height '<div class="ke-dialog-row">', '<label for="keHeight" style="width:60px;">' + lang.height + '</label>', '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />', '</div>', //autostart '<div class="ke-dialog-row">', '<label for="keAutostart">' + lang.autostart + '</label>', '<input type="checkbox" id="keAutostart" name="autostart" value="" /> ', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 450, height : 230, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var url = K.trim(urlBox.val()), width = widthBox.val(), height = heightBox.val(); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } var html = K.mediaImg(self.themesPath + 'common/blank.gif', { src : url, type : K.mediaType(url), width : width, height : height, autostart : autostartBox[0].checked ? 'true' : 'false', loop : 'true' }); self.insertHtml(html).hideDialog().focus(); } } }), div = dialog.div, urlBox = K('[name="url"]', div), viewServerBtn = K('[name="viewServer"]', div), widthBox = K('[name="width"]', div), heightBox = K('[name="height"]', div), autostartBox = K('[name="autostart"]', div); urlBox.val('http://'); if (allowMediaUpload) { var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : filePostName, extraParams : extraParams, url : uploadJson+'?dir=media', afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var url = data.url; if (formatUploadUrl) { url = K.formatUrl(url, 'absolute'); } urlBox.val(url); if (self.afterUpload) { self.afterUpload.call(self, url, data, name); } alert(self.lang('uploadSuccess')); } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); }); } else { K('.ke-upload-button', div).hide(); } if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'LIST', dirName : 'media', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); if (self.afterSelectFile) { self.afterSelectFile.call(self, url); } self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } var img = self.plugin.getSelectedMedia(); if (img) { var attrs = K.mediaAttrs(img.attr('data-ke-tag')); urlBox.val(attrs.src); widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0); heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0); autostartBox[0].checked = (attrs.autostart === 'true'); } urlBox[0].focus(); urlBox[0].select(); }, 'delete' : function() { self.plugin.getSelectedMedia().remove(); } }; self.clickToolbar(name, self.plugin.media.edit); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('wordpaste', function(K) { var self = this, name = 'wordpaste'; self.clickToolbar(name, function() { var lang = self.lang(name + '.'), html = '<div style="padding:10px 20px;">' + '<div style="margin-bottom:10px;">' + lang.comment + '</div>' + '<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' + '</div>', dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var str = doc.body.innerHTML; str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags); self.insertHtml(str).hideDialog().focus(); } } }), div = dialog.div, iframe = K('iframe', div), doc = K.iframeDoc(iframe); if (!K.IE) { doc.designMode = 'on'; } doc.open(); doc.write('<!doctype html><html><head><title>WordPaste</title></head>'); doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">'); if (!K.IE) { doc.write('<br />'); } doc.write('</body></html>'); doc.close(); if (K.IE) { doc.body.contentEditable = 'true'; } iframe[0].contentWindow.focus(); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('quickformat', function(K) { var self = this, name = 'quickformat', blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p'); function getFirstChild(knode) { var child = knode.first(); while (child && child.first()) { child = child.first(); } return child; } self.clickToolbar(name, function() { self.focus(); var doc = self.edit.doc, range = self.cmd.range, child = K(doc.body).first(), next, nodeList = [], subList = [], bookmark = range.createBookmark(true); while(child) { next = child.next(); var firstChild = getFirstChild(child); if (!firstChild || firstChild.name != 'img') { if (blockMap[child.name]) { child.html(child.html().replace(/^(\s|&nbsp;| )+/ig, '')); child.css('text-indent', '2em'); } else { subList.push(child); } if (!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) { if (subList.length > 0) { nodeList.push(subList); } subList = []; } } child = next; } K.each(nodeList, function(i, subList) { var wrapper = K('<p style="text-indent:2em;"></p>', doc); subList[0].before(wrapper); K.each(subList, function(i, knode) { wrapper.append(knode); }); }); range.moveToBookmark(bookmark); self.addBookmark(); }); }); /** -------------------------- abcd<br /> 1234<br /> to <p style="text-indent:2em;"> abcd<br /> 1234<br /> </p> -------------------------- &nbsp; abcd<img>1233 <p>1234</p> to <p style="text-indent:2em;">abcd<img>1233</p> <p style="text-indent:2em;">1234</p> -------------------------- */
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('clearhtml', function(K) { var self = this, name = 'clearhtml'; self.clickToolbar(name, function() { self.focus(); var html = self.html(); html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, ''); html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, ''); html = K.formatHtml(html, { a : ['href', 'target'], embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'], img : ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'], table : ['border'], 'td,th' : ['rowspan', 'colspan'], 'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [] }); self.html(html); self.cmd.selection(true); self.addBookmark(); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('lineheight', function(K) { var self = this, name = 'lineheight', lang = self.lang(name + '.'); self.clickToolbar(name, function() { var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'}); if (commonNode) { curVal = commonNode.css('line-height'); } var menu = self.createMenu({ name : name, width : 150 }); K.each(lang.lineHeight, function(i, row) { K.each(row, function(key, val) { menu.addItem({ title : val, checked : curVal === key, click : function() { self.cmd.toggle('<span style="line-height:' + key + ';"></span>', { span : '.line-height=' + key }); self.updateState(); self.addBookmark(); self.hideMenu(); } }); }); }); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('image', function(K) { var self = this, name = 'image', allowImageUpload = K.undef(self.allowImageUpload, true), formatUploadUrl = K.undef(self.formatUploadUrl, true), allowFileManager = K.undef(self.allowFileManager, false), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'), imageTabIndex = K.undef(self.imageTabIndex, 0), imgPath = self.pluginsPath + 'image/images/', extraParams = K.undef(self.extraFileUploadParams, {}), filePostName = K.undef(self.filePostName, 'imgFile'), fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false), lang = self.lang(name + '.'); self.plugin.imageDialog = function(options) { var imageUrl = options.imageUrl, imageWidth = K.undef(options.imageWidth, ''), imageHeight = K.undef(options.imageHeight, ''), imageTitle = K.undef(options.imageTitle, ''), imageAlign = K.undef(options.imageAlign, ''), showRemote = K.undef(options.showRemote, true), showLocal = K.undef(options.showLocal, true), tabIndex = K.undef(options.tabIndex, 0), clickFn = options.clickFn; var target = 'kindeditor_upload_iframe_' + new Date().getTime(); var hiddenElements = []; for(var k in extraParams){ hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />'); } var html = [ '<div style="padding:20px;">', //tabs '<div class="tabs"></div>', //remote image - start '<div class="tab1" style="display:none;">', //url '<div class="ke-dialog-row">', '<label for="remoteUrl" style="width:60px;">' + lang.remoteUrl + '</label>', '<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;', '<span class="ke-button-common ke-button-outer">', '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />', '</span>', '</div>', //size '<div class="ke-dialog-row">', '<label for="remoteWidth" style="width:60px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ', '<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + lang.resetSize + '" />', '</div>', //align '<div class="ke-dialog-row">', '<label style="width:60px;">' + lang.align + '</label>', '<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />', ' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />', ' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />', '</div>', //title '<div class="ke-dialog-row">', '<label for="remoteTitle" style="width:60px;">' + lang.imgTitle + '</label>', '<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />', '</div>', '</div>', //remote image - end //local upload - start '<div class="tab2" style="display:none;">', '<iframe name="' + target + '" style="display:none;"></iframe>', '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + uploadJson+'?dir=image' + '">', //file '<div class="ke-dialog-row">', '<label style="width:80px;">' + lang.iswater + '</label>', '<input type="checkbox" name="iswater" checked=true value="1">&nbsp;', '</div>', '<div class="ke-dialog-row">', hiddenElements.join(''), '<label style="width:80px;">' + lang.localUrl + '</label>', '<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;', '<input type="button" class="ke-upload-button" value="' + lang.upload + '" />', '</div>', '</form>', '</div>', //local upload - end '</div>' ].join(''); var dialogWidth = showLocal || allowFileManager ? 450 : 400, dialogHeight = showLocal && showRemote ? 300 : 250; var dialog = self.createDialog({ name : name, width : dialogWidth, height : dialogHeight, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { // Bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319 if (dialog.isLoading) { return; } // insert local image if (showLocal && showRemote && tabs && tabs.selectedIndex === 1 || !showRemote) { if (uploadbutton.fileBox.val() == '') { alert(self.lang('pleaseSelectFile')); return; } dialog.showLoading(self.lang('uploadLoading')); uploadbutton.submit(); localUrlBox.val(''); return; } // insert remote image var url = K.trim(urlBox.val()), width = widthBox.val(), height = heightBox.val(), title = titleBox.val(), align = ''; alignBox.each(function() { if (this.checked) { align = this.value; return false; } }); if (url == 'http://' || K.invalidUrl(url)) { alert(self.lang('invalidUrl')); urlBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } clickFn.call(self, url, title, width, height, 0, align); } }, beforeRemove : function() { viewServerBtn.unbind(); widthBox.unbind(); heightBox.unbind(); refreshBtn.unbind(); } }), div = dialog.div; var urlBox = K('[name="url"]', div), localUrlBox = K('[name="localUrl"]', div), viewServerBtn = K('[name="viewServer"]', div), widthBox = K('.tab1 [name="width"]', div), heightBox = K('.tab1 [name="height"]', div), refreshBtn = K('.ke-refresh-btn', div), titleBox = K('.tab1 [name="title"]', div), alignBox = K('.tab1 [name="align"]', div); var tabs; if (showRemote && showLocal) { tabs = K.tabs({ src : K('.tabs', div), afterSelect : function(i) {} }); tabs.add({ title : lang.remoteImage, panel : K('.tab1', div) }); tabs.add({ title : lang.localImage, panel : K('.tab2', div) }); tabs.select(tabIndex); } else if (showRemote) { K('.tab1', div).show(); } else if (showLocal) { K('.tab2', div).show(); } var uploadbutton = K.uploadbutton({ button : K('.ke-upload-button', div)[0], fieldName : filePostName, form : K('.ke-form', div), target : target, width: 60, afterUpload : function(data) { dialog.hideLoading(); if (data.error === 0) { var url = data.url; if (formatUploadUrl) { url = K.formatUrl(url, 'absolute'); } if (self.afterUpload) { self.afterUpload.call(self, url, data, name); } if (!fillDescAfterUploadImage) { clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align); } else { K(".ke-dialog-row #remoteUrl", div).val(url); K(".ke-tabs-li", div)[0].click(); K(".ke-refresh-btn", div).click(); } } else { alert(data.message); } }, afterError : function(html) { dialog.hideLoading(); self.errorDialog(html); } }); uploadbutton.fileBox.change(function(e) { localUrlBox.val(uploadbutton.fileBox.val()); }); if (allowFileManager) { viewServerBtn.click(function(e) { self.loadPlugin('filemanager', function() { self.plugin.filemanagerDialog({ viewType : 'VIEW', dirName : 'image', clickFn : function(url, title) { if (self.dialogs.length > 1) { K('[name="url"]', div).val(url); if (self.afterSelectFile) { self.afterSelectFile.call(self, url); } self.hideDialog(); } } }); }); }); } else { viewServerBtn.hide(); } var originalWidth = 0, originalHeight = 0; function setSize(width, height) { widthBox.val(width); heightBox.val(height); originalWidth = width; originalHeight = height; } refreshBtn.click(function(e) { var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({ position : 'absolute', visibility : 'hidden', top : 0, left : '-1000px' }); tempImg.bind('load', function() { setSize(tempImg.width(), tempImg.height()); tempImg.remove(); }); K(document.body).append(tempImg); }); widthBox.change(function(e) { if (originalWidth > 0) { heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10))); } }); heightBox.change(function(e) { if (originalHeight > 0) { widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10))); } }); urlBox.val(options.imageUrl); setSize(options.imageWidth, options.imageHeight); titleBox.val(options.imageTitle); alignBox.each(function() { if (this.value === options.imageAlign) { this.checked = true; return false; } }); if (showRemote && tabIndex === 0) { urlBox[0].focus(); urlBox[0].select(); } return dialog; }; self.plugin.image = { edit : function() { var img = self.plugin.getSelectedImage(); self.plugin.imageDialog({ imageUrl : img ? img.attr('data-ke-src') : 'http://', imageWidth : img ? img.width() : '', imageHeight : img ? img.height() : '', imageTitle : img ? img.attr('title') : '', imageAlign : img ? img.attr('align') : '', showRemote : true, showLocal : allowImageUpload, tabIndex: img ? 0 : imageTabIndex, clickFn : function(url, title, width, height, border, align) { self.exec('insertimage', url, title, width, height, border, align); // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog setTimeout(function() { self.hideDialog().focus(); }, 0); } }); }, 'delete' : function() { var target = self.plugin.getSelectedImage(); if (target.parent().name == 'a') { target = target.parent(); } target.remove(); } }; self.clickToolbar(name, self.plugin.image.edit); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('anchor', function(K) { var self = this, name = 'anchor', lang = self.lang(name + '.'); self.plugin.anchor = { edit : function() { var html = ['<div style="padding:20px;">', '<div class="ke-dialog-row">', '<label for="keName">' + lang.name + '</label>', '<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />', '</div>', '</div>'].join(''); var dialog = self.createDialog({ name : name, width : 300, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus(); } } }); var div = dialog.div, nameBox = K('input[name="name"]', div); var img = self.plugin.getSelectedAnchor(); if (img) { nameBox.val(unescape(img.attr('data-ke-name'))); } nameBox[0].focus(); nameBox[0].select(); }, 'delete' : function() { self.plugin.getSelectedAnchor().remove(); } }; self.clickToolbar(name, self.plugin.anchor.edit); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ // google code prettify: http://google-code-prettify.googlecode.com/ // http://google-code-prettify.googlecode.com/ KindEditor.plugin('code', function(K) { var self = this, name = 'code'; self.clickToolbar(name, function() { var lang = self.lang(name + '.'), html = ['<div style="padding:10px 20px;">', '<div class="ke-dialog-row">', '<select class="ke-code-type">', '<option value="js">JavaScript</option>', '<option value="html">HTML</option>', '<option value="css">CSS</option>', '<option value="php">PHP</option>', '<option value="pl">Perl</option>', '<option value="py">Python</option>', '<option value="rb">Ruby</option>', '<option value="java">Java</option>', '<option value="vb">ASP/VB</option>', '<option value="cpp">C/C++</option>', '<option value="cs">C#</option>', '<option value="xml">XML</option>', '<option value="bsh">Shell</option>', '<option value="">Other</option>', '</select>', '</div>', '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>', '</div>'].join(''), dialog = self.createDialog({ name : name, width : 450, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var type = K('.ke-code-type', dialog.div).val(), code = textarea.val(), cls = type === '' ? '' : ' lang-' + type, html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> '; self.insertHtml(html).hideDialog().focus(); } } }), textarea = K('textarea', dialog.div); textarea[0].focus(); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('autoheight', function(K) { var self = this; if (!self.autoHeightMode) { return; } var edit = self.edit; var body = edit.doc.body; var minHeight = K.removeUnit(self.height); edit.iframe[0].scroll = 'no'; body.style.overflowY = 'hidden'; edit.afterChange(function() { self.resize(null, Math.max((K.IE ? body.scrollHeight : body.offsetHeight) + 62, minHeight)); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('template', function(K) { var self = this, name = 'template', lang = self.lang(name + '.'), htmlPath = self.pluginsPath + name + '/html/'; function getFilePath(fileName) { return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION); } self.clickToolbar(name, function() { var lang = self.lang(name + '.'), arr = ['<div style="padding:10px 20px;">', '<div class="ke-header">', // left start '<div class="ke-left">', lang. selectTemplate + ' <select>']; K.each(lang.fileList, function(key, val) { arr.push('<option value="' + key + '">' + val + '</option>'); }); html = [arr.join(''), '</select></div>', // right start '<div class="ke-right">', '<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>', '</div>', '<div class="ke-clearfix"></div>', '</div>', '<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>', '</div>'].join(''); var dialog = self.createDialog({ name : name, width : 500, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var doc = K.iframeDoc(iframe); self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus(); } } }); var selectBox = K('select', dialog.div), checkbox = K('[name="replaceFlag"]', dialog.div), iframe = K('iframe', dialog.div); checkbox[0].checked = true; iframe.attr('src', getFilePath(selectBox.val())); selectBox.change(function() { iframe.attr('src', getFilePath(this.value)); }); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('filemanager', function(K) { var self = this, name = 'filemanager', fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'), imgPath = self.pluginsPath + name + '/images/', lang = self.lang(name + '.'); function makeFileTitle(filename, filesize, datetime) { return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')'; } function bindTitle(el, data) { if (data.is_dir) { el.attr('title', data.filename); } else { el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime)); } } self.plugin.filemanagerDialog = function(options) { var width = K.undef(options.width, 650), height = K.undef(options.height, 510), dirName = K.undef(options.dirName, ''), viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST" or "VIEW" clickFn = options.clickFn; var html = [ '<div style="padding:10px 20px;">', // header start '<div class="ke-plugin-filemanager-header">', // left start '<div class="ke-left">', '<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ', '<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>', '</div>', // right start '<div class="ke-right">', lang.viewType + ' <select class="ke-inline-block" name="viewType">', '<option value="VIEW">' + lang.viewImage + '</option>', '<option value="LIST">' + lang.listImage + '</option>', '</select> ', lang.orderType + ' <select class="ke-inline-block" name="orderType">', '<option value="NAME">' + lang.fileName + '</option>', '<option value="SIZE">' + lang.fileSize + '</option>', '<option value="TYPE">' + lang.fileType + '</option>', '</select>', '</div>', '<div class="ke-clearfix"></div>', '</div>', // body start '<div class="ke-plugin-filemanager-body"></div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : width, height : height, title : self.lang(name), body : html }), div = dialog.div, bodyDiv = K('.ke-plugin-filemanager-body', div), moveupImg = K('[name="moveupImg"]', div), moveupLink = K('[name="moveupLink"]', div), viewServerBtn = K('[name="viewServer"]', div), viewTypeBox = K('[name="viewType"]', div), orderTypeBox = K('[name="orderType"]', div); function reloadPage(path, order, func) { var param = 'path=' + path + '&order=' + order + '&dir=' + dirName; dialog.showLoading(self.lang('ajaxLoading')); K.ajax(fileManagerJson+'?'+param+'&' + new Date().getTime(), function(data) { dialog.hideLoading(); func(data); }); } var elList = []; function bindEvent(el, result, data, createFunc) { var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'), dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/'); if (data.is_dir) { el.click(function(e) { reloadPage(dirPath, orderTypeBox.val(), createFunc); }); } else if (data.is_photo) { el.click(function(e) { clickFn.call(this, fileUrl, data.filename); }); } else { el.click(function(e) { clickFn.call(this, fileUrl, data.filename); }); } elList.push(el); } function createCommon(result, createFunc) { // remove events K.each(elList, function() { this.unbind(); }); moveupLink.unbind(); viewTypeBox.unbind(); orderTypeBox.unbind(); // add events if (result.current_dir_path) { moveupLink.click(function(e) { reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc); }); } function changeFunc() { if (viewTypeBox.val() == 'VIEW') { reloadPage(result.current_dir_path, orderTypeBox.val(), createView); } else { reloadPage(result.current_dir_path, orderTypeBox.val(), createList); } } viewTypeBox.change(changeFunc); orderTypeBox.change(changeFunc); bodyDiv.html(''); } function createList(result) { createCommon(result, createList); var table = document.createElement('table'); table.className = 'ke-table'; table.cellPadding = 0; table.cellSpacing = 0; table.border = 0; bodyDiv.append(table); var fileList = result.file_list; for (var i = 0, len = fileList.length; i < len; i++) { var data = fileList[i], row = K(table.insertRow(i)); row.mouseover(function(e) { K(this).addClass('ke-on'); }) .mouseout(function(e) { K(this).removeClass('ke-on'); }); var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'), img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'), cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename)); if (!data.is_dir || data.has_file) { row.css('cursor', 'pointer'); cell0.attr('title', data.filename); bindEvent(cell0, result, data, createList); } else { cell0.attr('title', lang.emptyFolder); } K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB'); K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime); } } function createView(result) { createCommon(result, createView); var fileList = result.file_list; for (var i = 0, len = fileList.length; i < len; i++) { var data = fileList[i], div = K('<div class="ke-inline-block ke-item"></div>'); bodyDiv.append(div); var photoDiv = K('<div class="ke-inline-block ke-photo"></div>') .mouseover(function(e) { K(this).addClass('ke-on'); }) .mouseout(function(e) { K(this).removeClass('ke-on'); }); div.append(photoDiv); var fileUrl = result.current_url + data.filename, iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif'); var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />'); if (!data.is_dir || data.has_file) { photoDiv.css('cursor', 'pointer'); bindTitle(photoDiv, data); bindEvent(photoDiv, result, data, createView); } else { photoDiv.attr('title', lang.emptyFolder); } photoDiv.append(img); div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>'); } } viewTypeBox.val(viewType); reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList); return dialog; } });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ (function(K) { function KSWFUpload(options) { this.init(options); } K.extend(KSWFUpload, { init : function(options) { var self = this; options.afterError = options.afterError || function(str) { alert(str); }; self.options = options; self.progressbars = {}; // template self.div = K(options.container).html([ '<div class="ke-swfupload">', '<div class="ke-swfupload-top">', '<div class="ke-inline-block ke-swfupload-button">', '<input type="button" value="Browse" />', '</div>', '<div class="ke-inline-block ke-swfupload-desc">'+options.iswater+'<input type="checkbox" name="iswater" id="iswater" checked=true value="1">&nbsp;&nbsp;' + options.uploadDesc + '</div>', '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">', '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />', '</span>', '</div>', '<div class="ke-swfupload-body"></div>', '</div>' ].join('')); self.bodyDiv = K('.ke-swfupload-body', self.div); function showError(itemDiv, msg) { K('.ke-status > div', itemDiv).hide(); K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg)); } var settings = { debug : false, upload_url : options.uploadUrl, flash_url : options.flashUrl, file_post_name : options.filePostName, button_placeholder : K('.ke-swfupload-button > input', self.div)[0], button_image_url: options.buttonImageUrl, button_width: options.buttonWidth, button_height: options.buttonHeight, button_cursor : SWFUpload.CURSOR.HAND, file_types : options.fileTypes, file_types_description : options.fileTypesDesc, file_upload_limit : options.fileUploadLimit, file_size_limit : options.fileSizeLimit, post_params : options.postParams, file_queued_handler : function(file) { file.url = self.options.fileIconUrl; self.appendFile(file); }, file_queue_error_handler : function(file, errorCode, message) { var errorName = ''; switch (errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: errorName = options.queueLimitExceeded; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: errorName = options.fileExceedsSizeLimit; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: errorName = options.zeroByteFile; break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: errorName = options.invalidFiletype; break; default: errorName = options.unknownError; break; } K.DEBUG && alert(errorName); }, upload_start_handler : function(file) { var self = this; var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv); K('.ke-status > div', itemDiv).hide(); K('.ke-progressbar', itemDiv).show(); }, upload_progress_handler : function(file, bytesLoaded, bytesTotal) { var percent = Math.round(bytesLoaded * 100 / bytesTotal); var progressbar = self.progressbars[file.id]; progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px'); progressbar.percent.html(percent + '%'); }, upload_error_handler : function(file, errorCode, message) { if (file && file.filestatus == SWFUpload.FILE_STATUS.ERROR) { var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0); showError(itemDiv, self.options.errorMessage); } }, upload_success_handler : function(file, serverData) { var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0); var data = {}; try { data = K.json(serverData); } catch (e) { self.options.afterError.call(this, '<!doctype html><html>' + serverData + '</html>'); } if (data.error !== 0) { showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage); return; } file.url = data.url; K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data); K('.ke-status > div', itemDiv).hide(); } }; self.swfu = new SWFUpload(settings); K('.ke-swfupload-startupload input', self.div).click(function() { self.swfu.startUpload(); }); }, getUrlList : function() { var list = []; K('.ke-img', self.bodyDiv).each(function() { var img = K(this); var status = img.attr('data-status'); if (status == SWFUpload.FILE_STATUS.COMPLETE) { list.push(img.data('data')); } }); return list; }, removeFile : function(fileId) { var self = this; self.swfu.cancelUpload(fileId); var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv); K('.ke-photo', itemDiv).unbind(); K('.ke-delete', itemDiv).unbind(); itemDiv.remove(); }, removeFiles : function() { var self = this; K('.ke-item', self.bodyDiv).each(function() { self.removeFile(K(this).attr('data-id')); }); }, appendFile : function(file) { var self = this; var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>'); self.bodyDiv.append(itemDiv); var photoDiv = K('<div class="ke-inline-block ke-photo"></div>') .mouseover(function(e) { K(this).addClass('ke-on'); }) .mouseout(function(e) { K(this).removeClass('ke-on'); }); itemDiv.append(photoDiv); var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />'); photoDiv.append(img); K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function() { self.removeFile(file.id); }); var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv); // progressbar K(['<div class="ke-progressbar">', '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>', '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv); // message K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv); itemDiv.append('<div class="ke-name">' + file.name + '</div>'); self.progressbars[file.id] = { bar : K('.ke-progressbar-bar-inner', photoDiv), percent : K('.ke-progressbar-percent', photoDiv) }; }, remove : function() { this.removeFiles(); this.swfu.destroy(); this.div.html(''); } }); K.swfupload = function(element, options) { return new KSWFUpload(element, options); }; })(KindEditor); KindEditor.plugin('multiimage', function(K) { var self = this, name = 'multiimage', formatUploadUrl = K.undef(self.formatUploadUrl, true), uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'), imgPath = self.pluginsPath + 'multiimage/images/', imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'), imageFileTypes = K.undef(self.imageFileTypes, '*.gif;*.jpg;*.jpeg;*.png;*.bmp'), imageUploadLimit = K.undef(self.imageUploadLimit, 20), filePostName = K.undef(self.filePostName, 'imgFile'), lang = self.lang(name + '.'); self.plugin.multiImageDialog = function(options) { var clickFn = options.clickFn, uploadDesc = K.tmpl(lang.uploadDesc, {uploadLimit : imageUploadLimit, sizeLimit : imageSizeLimit}); var html = [ '<div style="padding:20px;">', '<div class="swfupload">', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 650, height : 510, title : self.lang(name), body : html, previewBtn : { name : lang.insertAll, click : function(e) { clickFn.call(self, swfupload.getUrlList()); } }, yesBtn : { name : lang.clearAll, click : function(e) { swfupload.removeFiles(); } }, beforeRemove : function() { swfupload.remove(); } }), div = dialog.div; var swfupload = K.swfupload({ container : K('.swfupload', div), buttonImageUrl : imgPath + (self.langType == 'zh_CN' ? 'select-files-zh_CN.png' : 'select-files-en.png'), buttonWidth : self.langType == 'zh_CN' ? 72 : 88, buttonHeight : 23, fileIconUrl : imgPath + 'image.png', uploadDesc : uploadDesc, iswater : lang.iswater, startButtonValue : lang.startUpload, uploadUrl : uploadJson+'?dir=image', flashUrl : imgPath + 'swfupload.swf', filePostName : filePostName, fileTypes : '*.jpg;*.jpeg;*.gif;*.png;*.bmp', fileTypesDesc : 'Image Files', fileUploadLimit : imageUploadLimit, fileSizeLimit : imageSizeLimit, postParams : K.undef(self.extraFileUploadParams, {}), queueLimitExceeded : lang.queueLimitExceeded, fileExceedsSizeLimit : lang.fileExceedsSizeLimit, zeroByteFile : lang.zeroByteFile, invalidFiletype : lang.invalidFiletype, unknownError : lang.unknownError, pendingMessage : lang.pending, errorMessage : lang.uploadError, afterError : function(html) { self.errorDialog(html); } }); return dialog; }; self.clickToolbar(name, function() { self.plugin.multiImageDialog({ clickFn : function (urlList) { if (urlList.length === 0) { return; } K.each(urlList, function(i, data) { if (self.afterUpload) { self.afterUpload.call(self, data.url, data, 'multiimage'); } self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align); }); // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog setTimeout(function() { self.hideDialog().focus(); }, 0); } }); }); }); /** * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* Constructor & Init */ /* ******************* */ (function() { if (window.SWFUpload) { return; } window.SWFUpload = function (settings) { this.initSWFUpload(settings); }; SWFUpload.prototype.initSWFUpload = function (settings) { try { this.customSettings = {}; // A container where developers can place their own settings associated with this instance. this.settings = settings; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; // Setup global control tracking SWFUpload.instances[this.movieName] = this; // Load the settings. Load the Flash movie. this.initSettings(); this.loadFlash(); this.displayDebugInfo(); } catch (ex) { delete SWFUpload.instances[this.movieName]; throw ex; } }; /* *************** */ /* Static Members */ /* *************** */ SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 2009-03-25"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 }; SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, COMPLETE : -4, CANCELLED : -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }; SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }; SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" }; // Private: takes a URL, determines if it is relative and converts to an absolute URL // using the current site. Only processes the URL if it can, otherwise returns the URL untouched SWFUpload.completeURL = function(url) { if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) { return url; } var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); var indexSlash = window.location.pathname.lastIndexOf("/"); if (indexSlash <= 0) { path = "/"; } else { path = window.location.pathname.substr(0, indexSlash) + "/"; } return /*currentURL +*/ path + url; }; /* ******************** */ /* Instance Members */ /* ******************** */ // Private: initSettings ensures that all the // settings are set, getting a default value if one was not assigned. SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // Upload backend settings this.ensureDefault("upload_url", ""); this.ensureDefault("preserve_relative_urls", false); this.ensureDefault("file_post_name", "Filedata"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); this.ensureDefault("assume_success_timeout", 0); // File Settings this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited" this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); // Flash Settings this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); // Button Settings this.ensureDefault("button_image_url", ""); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", ""); this.ensureDefault("button_placeholder", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW); // Debug Settings this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API // Event Handlers this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); // Other settings this.customSettings = this.settings.custom_settings; // Update the flash url if needed if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime(); } if (!this.settings.preserve_relative_urls) { //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url); this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url); } delete this.ensureDefault; }; // Private: loadFlash replaces the button_placeholder element with the flash movie. SWFUpload.prototype.loadFlash = function () { var targetElement, tempParent; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the element where we will be placing the flash movie targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (targetElement == undefined) { throw "Could not find the placeholder element: " + this.settings.button_placeholder_id; } // Append the container and load the flash tempParent = document.createElement("div"); tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement); // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: getFlashHTML generates the object tag needed to embed the flash in to the document SWFUpload.prototype.getFlashHTML = function () { // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay // Fix bug for IE9 // http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1 var classid = ''; if (KindEditor.IE && KindEditor.V > 8) { classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"'; } return ['<object id="', this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="', this.settings.button_window_mode, '" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', '</object>'].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url), "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string), "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&amp;httpSuccess=", encodeURIComponent(httpSuccessString), "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "&amp;params=", encodeURIComponent(paramString), "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name), "&amp;fileTypes=", encodeURIComponent(this.settings.file_types), "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width), "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height), "&amp;buttonText=", encodeURIComponent(this.settings.button_text), "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&amp;buttonAction=", encodeURIComponent(this.settings.button_action), "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName); } if (this.movieElement === null) { throw "Could not find Flash element"; } return this.movieElement; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&amp;name=value" SWFUpload.prototype.buildParamString = function () { var postParams = this.settings.post_params; var paramStringPairs = []; if (typeof(postParams) === "object") { for (var name in postParams) { if (postParams.hasOwnProperty(name)) { paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString())); } } } return paramStringPairs.join("&amp;"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true; } catch (ex2) { return false; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. SWFUpload.prototype.displayDebugInfo = function () { this.debug( [ "---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.toString(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n", "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n", "\t", "button_width: ", this.settings.button_width.toString(), "\n", "\t", "button_height: ", this.settings.button_height.toString(), "\n", "\t", "button_text: ", this.settings.button_text.toString(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action: ", this.settings.button_action.toString(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n" ].join("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>'); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callFlash("SetHTTPSuccess", [http_status_codes]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button SWFUpload.prototype.setButtonDimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getMovieElement(); if (movie != undefined) { movie.style.width = width + "px"; movie.style.height = height + "px"; } this.callFlash("SetButtonDimensions", [width, height]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay SWFUpload.prototype.setButtonTextPadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callFlash("SetButtonTextPadding", [left, top]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) { // Warning: Don't call this.debug inside here or you'll create an infinite loop if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. SWFUpload.prototype.executeNextEvent = function () { // Warning: Don't call this.debug inside here or you'll create an infinite loop var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. SWFUpload.prototype.unescapeFilePostParams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedPost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasOwnProperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16))); } unescapedPost[uk] = file.post[k]; } } file.post = unescapedPost; } return file; }; // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working) SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface"); } catch (ex) { return false; } }; // Private: This event is called by Flash when it has finished loading. Don't modify this. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded. SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); if (!movieElement) { this.debug("Flash called back ready but the flash movie can't be found."); return; } this.cleanUp(movieElement); this.queueEvent("swfupload_loaded_handler"); }; // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE. // This function is called by Flash each time the ExternalInterface functions are created. SWFUpload.prototype.cleanUp = function (movieElement) { // Pro-actively unhook all the Flash functions try { if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var key in movieElement) { try { if (typeof(movieElement[key]) === "function") { movieElement[key] = null; } } catch (ex) { } } } } catch (ex1) { } // Fix Flashes own cleanup code so if the SWFMovie was removed from the page // it doesn't display errors. window["__flash__removeCallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) { this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]); }; SWFUpload.prototype.uploadStart = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("return_upload_start_handler", file); }; SWFUpload.prototype.returnUploadStart = function (file) { var returnValue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapeFilePostParams(file); var iswater = $("#iswater").is(':checked')?1:0; this.setPostParams({"iswater":iswater }); returnValue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnValue === undefined) { returnValue = true; } returnValue = !!returnValue; this.callFlash("ReturnUploadStart", [returnValue]); }; SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]); }; SWFUpload.prototype.uploadError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_error_handler", [file, errorCode, message]); }; SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_success_handler", [file, serverData, responseReceived]); }; SWFUpload.prototype.uploadComplete = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_complete_handler", file); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. SWFUpload.prototype.debugMessage = function (message) { if (this.settings.debug) { var exceptionMessage, exceptionValues = []; // Check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasOwnProperty(key)) { exceptionValues.push(key + ": " + message[key]); } } exceptionMessage = exceptionValues.join("\n") || ""; exceptionValues = exceptionMessage.split("\n"); exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(exceptionMessage); } else { SWFUpload.Console.writeLine(message); } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (message) { var console, documentForm; try { console = document.getElementById("SWFUpload_Console"); if (!console) { documentForm = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(documentForm); console = document.createElement("textarea"); console.id = "SWFUpload_Console"; console.style.fontFamily = "monospace"; console.setAttribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentForm.appendChild(console); } console.value += message + "\n"; console.scrollTop = console.scrollHeight - console.clientHeight; } catch (ex) { alert("Exception: " + ex.name + " Message: " + ex.message); } }; })(); (function() { /* Queue Plug-in Features: *Adds a cancelQueue() method for cancelling the entire queue. *All queued files are uploaded when startUpload() is called. *If false is returned from uploadComplete then the queue upload is stopped. If false is not returned (strict comparison) then the queue upload is continued. *Adds a QueueComplete event that is fired when all the queued files have finished uploading. Set the event handler with the queue_complete_handler setting. */ if (typeof(SWFUpload) === "function") { SWFUpload.queue = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.queueSettings = {}; this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler; this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.startUpload = function (fileID) { this.queueSettings.queue_cancelled_flag = false; this.callFlash("StartUpload", [fileID]); }; SWFUpload.prototype.cancelQueue = function () { this.queueSettings.queue_cancelled_flag = true; this.stopUpload(); var stats = this.getStats(); while (stats.files_queued > 0) { this.cancelUpload(); stats = this.getStats(); } }; SWFUpload.queue.uploadStartHandler = function (file) { var returnValue; if (typeof(this.queueSettings.user_upload_start_handler) === "function") { returnValue = this.queueSettings.user_upload_start_handler.call(this, file); } // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value. returnValue = (returnValue === false) ? false : true; this.queueSettings.queue_cancelled_flag = !returnValue; return returnValue; }; SWFUpload.queue.uploadCompleteHandler = function (file) { var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler; var continueUpload; if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) { this.queueSettings.queue_upload_count++; } if (typeof(user_upload_complete_handler) === "function") { continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true; } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) { // If the file was stopped and re-queued don't restart the upload continueUpload = false; } else { continueUpload = true; } if (continueUpload) { var stats = this.getStats(); if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) { this.startUpload(); } else if (this.queueSettings.queue_cancelled_flag === false) { this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]); this.queueSettings.queue_upload_count = 0; } else { this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; } } }; } })();
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('table', function(K) { var self = this, name = 'table', lang = self.lang(name + '.'), zeroborder = 'ke-zeroborder'; // 设置颜色 function _setColor(box, color) { color = color.toUpperCase(); box.css('background-color', color); box.css('color', color === '#000000' ? '#FFFFFF' : '#000000'); box.html(color); } // 初始化取色器 var pickerList = []; function _initColorPicker(dialogDiv, colorBox) { colorBox.bind('click,mousedown', function(e){ e.stopPropagation(); }); function removePicker() { K.each(pickerList, function() { this.remove(); }); pickerList = []; K(document).unbind('click,mousedown', removePicker); dialogDiv.unbind('click,mousedown', removePicker); } colorBox.click(function(e) { removePicker(); var box = K(this), pos = box.pos(); var picker = K.colorpicker({ x : pos.x, y : pos.y + box.height(), z : 811214, selectedColor : K(this).html(), colors : self.colorTable, noColor : self.lang('noColor'), shadowMode : self.shadowMode, click : function(color) { _setColor(box, color); removePicker(); } }); pickerList.push(picker); K(document).bind('click,mousedown', removePicker); dialogDiv.bind('click,mousedown', removePicker); }); } // 取得下一行cell的index function _getCellIndex(table, row, cell) { var rowSpanCount = 0; for (var i = 0, len = row.cells.length; i < len; i++) { if (row.cells[i] == cell) { break; } rowSpanCount += row.cells[i].rowSpan - 1; } return cell.cellIndex - rowSpanCount; } self.plugin.table = { //insert or modify table prop : function(isInsert) { var html = [ '<div style="padding:20px;">', //rows, cols '<div class="ke-dialog-row">', '<label for="keRows" style="width:90px;">' + lang.cells + '</label>', lang.rows + ' <input type="text" id="keRows" class="ke-input-text ke-input-number" name="rows" value="" maxlength="4" /> &nbsp; ', lang.cols + ' <input type="text" class="ke-input-text ke-input-number" name="cols" value="" maxlength="4" />', '</div>', //width, height '<div class="ke-dialog-row">', '<label for="keWidth" style="width:90px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ', '<select name="widthType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select> &nbsp; ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ', '<select name="heightType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select>', '</div>', //space, padding '<div class="ke-dialog-row">', '<label for="kePadding" style="width:90px;">' + lang.space + '</label>', lang.padding + ' <input type="text" id="kePadding" class="ke-input-text ke-input-number" name="padding" value="" maxlength="4" /> &nbsp; ', lang.spacing + ' <input type="text" class="ke-input-text ke-input-number" name="spacing" value="" maxlength="4" />', '</div>', //align '<div class="ke-dialog-row">', '<label for="keAlign" style="width:90px;">' + lang.align + '</label>', '<select id="keAlign" name="align">', '<option value="">' + lang.alignDefault + '</option>', '<option value="left">' + lang.alignLeft + '</option>', '<option value="center">' + lang.alignCenter + '</option>', '<option value="right">' + lang.alignRight + '</option>', '</select>', '</div>', //border '<div class="ke-dialog-row">', '<label for="keBorder" style="width:90px;">' + lang.border + '</label>', lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ', lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>', '</div>', //background color '<div class="ke-dialog-row">', '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>', '<span class="ke-inline-block ke-input-color"></span>', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 500, title : self.lang(name), body : html, beforeRemove : function() { colorBox.unbind(); }, yesBtn : { name : self.lang('yes'), click : function(e) { var rows = rowsBox.val(), cols = colsBox.val(), width = widthBox.val(), height = heightBox.val(), widthType = widthTypeBox.val(), heightType = heightTypeBox.val(), padding = paddingBox.val(), spacing = spacingBox.val(), align = alignBox.val(), border = borderBox.val(), borderColor = K(colorBox[0]).html() || '', bgColor = K(colorBox[1]).html() || ''; if (rows == 0 || !/^\d+$/.test(rows)) { alert(self.lang('invalidRows')); rowsBox[0].focus(); return; } if (cols == 0 || !/^\d+$/.test(cols)) { alert(self.lang('invalidRows')); colsBox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } if (!/^\d*$/.test(padding)) { alert(self.lang('invalidPadding')); paddingBox[0].focus(); return; } if (!/^\d*$/.test(spacing)) { alert(self.lang('invalidSpacing')); spacingBox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidBorder')); borderBox[0].focus(); return; } //modify table if (table) { if (width !== '') { table.width(width + widthType); } else { table.css('width', ''); } if (table[0].width !== undefined) { table.removeAttr('width'); } if (height !== '') { table.height(height + heightType); } else { table.css('height', ''); } if (table[0].height !== undefined) { table.removeAttr('height'); } table.css('background-color', bgColor); if (table[0].bgColor !== undefined) { table.removeAttr('bgColor'); } if (padding !== '') { table[0].cellPadding = padding; } else { table.removeAttr('cellPadding'); } if (spacing !== '') { table[0].cellSpacing = spacing; } else { table.removeAttr('cellSpacing'); } if (align !== '') { table[0].align = align; } else { table.removeAttr('align'); } if (border !== '') { table.attr('border', border); } else { table.removeAttr('border'); } if (border === '' || border === '0') { table.addClass(zeroborder); } else { table.removeClass(zeroborder); } if (borderColor !== '') { table.attr('borderColor', borderColor); } else { table.removeAttr('borderColor'); } self.hideDialog().focus(); return; } //insert new table var style = ''; if (width !== '') { style += 'width:' + width + widthType + ';'; } if (height !== '') { style += 'height:' + height + heightType + ';'; } if (bgColor !== '') { style += 'background-color:' + bgColor + ';'; } var html = '<table'; if (style !== '') { html += ' style="' + style + '"'; } if (padding !== '') { html += ' cellpadding="' + padding + '"'; } if (spacing !== '') { html += ' cellspacing="' + spacing + '"'; } if (align !== '') { html += ' align="' + align + '"'; } if (border !== '') { html += ' border="' + border + '"'; } if (border === '' || border === '0') { html += ' class="' + zeroborder + '"'; } if (borderColor !== '') { html += ' bordercolor="' + borderColor + '"'; } html += '>'; for (var i = 0; i < rows; i++) { html += '<tr>'; for (var j = 0; j < cols; j++) { html += '<td>' + (K.IE ? '&nbsp;' : '<br />') + '</td>'; } html += '</tr>'; } html += '</table>'; if (!K.IE) { html += '<br />'; } self.insertHtml(html); self.select().hideDialog().focus(); self.addBookmark(); } } }), div = dialog.div, rowsBox = K('[name="rows"]', div).val(3), colsBox = K('[name="cols"]', div).val(2), widthBox = K('[name="width"]', div).val(100), heightBox = K('[name="height"]', div), widthTypeBox = K('[name="widthType"]', div), heightTypeBox = K('[name="heightType"]', div), paddingBox = K('[name="padding"]', div).val(2), spacingBox = K('[name="spacing"]', div).val(0), alignBox = K('[name="align"]', div), borderBox = K('[name="border"]', div).val(1), colorBox = K('.ke-input-color', div); _initColorPicker(div, colorBox.eq(0)); _initColorPicker(div, colorBox.eq(1)); _setColor(colorBox.eq(0), '#000000'); _setColor(colorBox.eq(1), ''); // foucs and select rowsBox[0].focus(); rowsBox[0].select(); var table; if (isInsert) { return; } //get selected table node table = self.plugin.getSelectedTable(); if (table) { rowsBox.val(table[0].rows.length); colsBox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0); rowsBox.attr('disabled', true); colsBox.attr('disabled', true); var match, tableWidth = table[0].style.width || table[0].width, tableHeight = table[0].style.height || table[0].height; if (tableWidth !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableWidth))) { widthBox.val(match[1]); widthTypeBox.val(match[2]); } else { widthBox.val(''); } if (tableHeight !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableHeight))) { heightBox.val(match[1]); heightTypeBox.val(match[2]); } paddingBox.val(table[0].cellPadding || ''); spacingBox.val(table[0].cellSpacing || ''); alignBox.val(table[0].align || ''); borderBox.val(table[0].border === undefined ? '' : table[0].border); _setColor(colorBox.eq(0), K.toHex(table.attr('borderColor') || '')); _setColor(colorBox.eq(1), K.toHex(table[0].style.backgroundColor || table[0].bgColor || '')); widthBox[0].focus(); widthBox[0].select(); } }, //modify cell cellprop : function() { var html = [ '<div style="padding:20px;">', //width, height '<div class="ke-dialog-row">', '<label for="keWidth" style="width:90px;">' + lang.size + '</label>', lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ', '<select name="widthType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select> &nbsp; ', lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ', '<select name="heightType">', '<option value="%">' + lang.percent + '</option>', '<option value="px">' + lang.px + '</option>', '</select>', '</div>', //align '<div class="ke-dialog-row">', '<label for="keAlign" style="width:90px;">' + lang.align + '</label>', lang.textAlign + ' <select id="keAlign" name="textAlign">', '<option value="">' + lang.alignDefault + '</option>', '<option value="left">' + lang.alignLeft + '</option>', '<option value="center">' + lang.alignCenter + '</option>', '<option value="right">' + lang.alignRight + '</option>', '</select> ', lang.verticalAlign + ' <select name="verticalAlign">', '<option value="">' + lang.alignDefault + '</option>', '<option value="top">' + lang.alignTop + '</option>', '<option value="middle">' + lang.alignMiddle + '</option>', '<option value="bottom">' + lang.alignBottom + '</option>', '<option value="baseline">' + lang.alignBaseline + '</option>', '</select>', '</div>', //border '<div class="ke-dialog-row">', '<label for="keBorder" style="width:90px;">' + lang.border + '</label>', lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ', lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>', '</div>', //background color '<div class="ke-dialog-row">', '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>', '<span class="ke-inline-block ke-input-color"></span>', '</div>', '</div>' ].join(''); var dialog = self.createDialog({ name : name, width : 500, title : self.lang('tablecell'), body : html, beforeRemove : function() { colorBox.unbind(); }, yesBtn : { name : self.lang('yes'), click : function(e) { var width = widthBox.val(), height = heightBox.val(), widthType = widthTypeBox.val(), heightType = heightTypeBox.val(), padding = paddingBox.val(), spacing = spacingBox.val(), textAlign = textAlignBox.val(), verticalAlign = verticalAlignBox.val(), border = borderBox.val(), borderColor = K(colorBox[0]).html() || '', bgColor = K(colorBox[1]).html() || ''; if (!/^\d*$/.test(width)) { alert(self.lang('invalidWidth')); widthBox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidHeight')); heightBox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidBorder')); borderBox[0].focus(); return; } cell.css({ width : width !== '' ? (width + widthType) : '', height : height !== '' ? (height + heightType) : '', 'background-color' : bgColor, 'text-align' : textAlign, 'vertical-align' : verticalAlign, 'border-width' : border, 'border-style' : border !== '' ? 'solid' : '', 'border-color' : borderColor }); self.hideDialog().focus(); self.addBookmark(); } } }), div = dialog.div, widthBox = K('[name="width"]', div).val(100), heightBox = K('[name="height"]', div), widthTypeBox = K('[name="widthType"]', div), heightTypeBox = K('[name="heightType"]', div), paddingBox = K('[name="padding"]', div).val(2), spacingBox = K('[name="spacing"]', div).val(0), textAlignBox = K('[name="textAlign"]', div), verticalAlignBox = K('[name="verticalAlign"]', div), borderBox = K('[name="border"]', div).val(1), colorBox = K('.ke-input-color', div); _initColorPicker(div, colorBox.eq(0)); _initColorPicker(div, colorBox.eq(1)); _setColor(colorBox.eq(0), '#000000'); _setColor(colorBox.eq(1), ''); // foucs and select widthBox[0].focus(); widthBox[0].select(); // get selected cell var cell = self.plugin.getSelectedCell(); var match, cellWidth = cell[0].style.width || cell[0].width || '', cellHeight = cell[0].style.height || cell[0].height || ''; if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) { widthBox.val(match[1]); widthTypeBox.val(match[2]); } else { widthBox.val(''); } if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) { heightBox.val(match[1]); heightTypeBox.val(match[2]); } textAlignBox.val(cell[0].style.textAlign || ''); verticalAlignBox.val(cell[0].style.verticalAlign || ''); var border = cell[0].style.borderWidth || ''; if (border) { border = parseInt(border); } borderBox.val(border); _setColor(colorBox.eq(0), K.toHex(cell[0].style.borderColor || '')); _setColor(colorBox.eq(1), K.toHex(cell[0].style.backgroundColor || '')); widthBox[0].focus(); widthBox[0].select(); }, insert : function() { this.prop(true); }, 'delete' : function() { var table = self.plugin.getSelectedTable(); self.cmd.range.setStartBefore(table[0]).collapse(true); self.cmd.select(); table.remove(); self.addBookmark(); }, colinsert : function(offset) { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], index = cell.cellIndex + offset; // 取得第一行的index index += table.rows[0].cells.length - row.cells.length; for (var i = 0, len = table.rows.length; i < len; i++) { var newRow = table.rows[i], newCell = newRow.insertCell(index); newCell.innerHTML = K.IE ? '' : '<br />'; // 调整下一行的单元格index index = _getCellIndex(table, newRow, newCell); } self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colinsertleft : function() { this.colinsert(0); }, colinsertright : function() { this.colinsert(1); }, rowinsert : function(offset) { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0]; var rowIndex = row.rowIndex; if (offset === 1) { rowIndex = row.rowIndex + (cell.rowSpan - 1) + offset; } var newRow = table.insertRow(rowIndex); for (var i = 0, len = row.cells.length; i < len; i++) { // 调整cell个数 if (row.cells[i].rowSpan > 1) { len -= row.cells[i].rowSpan - 1; } var newCell = newRow.insertCell(i); // copy colspan if (offset === 1 && row.cells[i].colSpan > 1) { newCell.colSpan = row.cells[i].colSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; } // 调整rowspan for (var j = rowIndex; j >= 0; j--) { var cells = table.rows[j].cells; if (cells.length > i) { for (var k = cell.cellIndex; k >= 0; k--) { if (cells[k].rowSpan > 1) { cells[k].rowSpan += 1; } } break; } } self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, rowinsertabove : function() { this.rowinsert(0); }, rowinsertbelow : function() { this.rowinsert(1); }, rowmerge : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex, // 当前行的index nextRowIndex = rowIndex + cell.rowSpan, // 下一行的index nextRow = table.rows[nextRowIndex]; // 下一行 // 最后一行不能合并 if (table.rows.length <= nextRowIndex) { return; } var cellIndex = _getCellIndex(table, row, cell); // 下一行单元格的index if (nextRow.cells.length <= cellIndex) { return; } var nextCell = nextRow.cells[cellIndex]; // 下一行单元格 // 上下行的colspan不一致时不能合并 if (cell.colSpan !== nextCell.colSpan) { return; } cell.rowSpan += nextCell.rowSpan; nextRow.deleteCell(cellIndex); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colmerge : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex, // 当前行的index cellIndex = cell.cellIndex, nextCellIndex = cellIndex + 1; // 最后一列不能合并 if (row.cells.length <= nextCellIndex) { return; } var nextCell = row.cells[nextCellIndex]; // 左右列的rowspan不一致时不能合并 if (cell.rowSpan !== nextCell.rowSpan) { return; } cell.colSpan += nextCell.colSpan; row.deleteCell(nextCellIndex); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, rowsplit : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex; // 不是可分割单元格 if (cell.rowSpan === 1) { return; } var cellIndex = _getCellIndex(table, row, cell); for (var i = 1, len = cell.rowSpan; i < len; i++) { var newRow = table.rows[rowIndex + i], newCell = newRow.insertCell(cellIndex); if (cell.colSpan > 1) { newCell.colSpan = cell.colSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; // 调整下一行的单元格index cellIndex = _getCellIndex(table, newRow, newCell); } K(cell).removeAttr('rowSpan'); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, colsplit : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], cellIndex = cell.cellIndex; // 不是可分割单元格 if (cell.colSpan === 1) { return; } for (var i = 1, len = cell.colSpan; i < len; i++) { var newCell = row.insertCell(cellIndex + i); if (cell.rowSpan > 1) { newCell.rowSpan = cell.rowSpan; } newCell.innerHTML = K.IE ? '' : '<br />'; } K(cell).removeAttr('colSpan'); self.cmd.range.selectNodeContents(cell).collapse(true); self.cmd.select(); self.addBookmark(); }, coldelete : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], index = cell.cellIndex; for (var i = 0, len = table.rows.length; i < len; i++) { var newRow = table.rows[i], newCell = newRow.cells[index]; if (newCell.colSpan > 1) { newCell.colSpan -= 1; if (newCell.colSpan === 1) { K(newCell).removeAttr('colSpan'); } } else { newRow.deleteCell(index); } // 跳过不需要删除的行 if (newCell.rowSpan > 1) { i += newCell.rowSpan - 1; } } if (row.cells.length === 0) { self.cmd.range.setStartBefore(table).collapse(true); self.cmd.select(); K(table).remove(); } else { self.cmd.selection(true); } self.addBookmark(); }, rowdelete : function() { var table = self.plugin.getSelectedTable()[0], row = self.plugin.getSelectedRow()[0], cell = self.plugin.getSelectedCell()[0], rowIndex = row.rowIndex; // 从下到上删除 for (var i = cell.rowSpan - 1; i >= 0; i--) { table.deleteRow(rowIndex + i); } if (table.rows.length === 0) { self.cmd.range.setStartBefore(table).collapse(true); self.cmd.select(); K(table).remove(); } else { self.cmd.selection(true); } self.addBookmark(); } }; self.clickToolbar(name, self.plugin.table.prop); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ // Baidu Maps: http://dev.baidu.com/wiki/map/index.php?title=%E9%A6%96%E9%A1%B5 KindEditor.plugin('baidumap', function(K) { var self = this, name = 'baidumap', lang = self.lang(name + '.'); var mapWidth = K.undef(self.mapWidth, 558); var mapHeight = K.undef(self.mapHeight, 360); self.clickToolbar(name, function() { var html = ['<div style="padding:10px 20px;">', '<div class="ke-header">', // left start '<div class="ke-left">', lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ', '<span class="ke-button-common ke-button-outer">', '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />', '</span>', '</div>', // right start '<div class="ke-right">', '<input type="checkbox" id="keInsertDynamicMap" name="insertDynamicMap" value="1" /> <label for="keInsertDynamicMap">' + lang.insertDynamicMap + '</label>', '</div>', '<div class="ke-clearfix"></div>', '</div>', '<div class="ke-map" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></div>', '</div>'].join(''); var dialog = self.createDialog({ name : name, width : mapWidth + 42, title : self.lang(name), body : html, yesBtn : { name : self.lang('yes'), click : function(e) { var map = win.map; var centerObj = map.getCenter(); var center = centerObj.lng + ',' + centerObj.lat; var zoom = map.getZoom(); var url = [checkbox[0].checked ? self.pluginsPath + 'baidumap/index.html' : 'http://api.map.baidu.com/staticimage', '?center=' + encodeURIComponent(center), '&zoom=' + encodeURIComponent(zoom), '&width=' + mapWidth, '&height=' + mapHeight, '&markers=' + encodeURIComponent(center), '&markerStyles=' + encodeURIComponent('l,A')].join(''); if (checkbox[0].checked) { self.insertHtml('<iframe src="' + url + '" frameborder="0" style="width:' + (mapWidth + 2) + 'px;height:' + (mapHeight + 2) + 'px;"></iframe>'); } else { self.exec('insertimage', url); } self.hideDialog().focus(); } }, beforeRemove : function() { searchBtn.remove(); if (doc) { doc.write(''); } iframe.remove(); } }); var div = dialog.div, addressBox = K('[name="address"]', div), searchBtn = K('[name="searchBtn"]', div), checkbox = K('[name="insertDynamicMap"]', dialog.div), win, doc; var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'baidumap/map.html" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></iframe>'); function ready() { win = iframe[0].contentWindow; doc = K.iframeDoc(iframe); } iframe.bind('load', function() { iframe.unbind('load'); if (K.IE) { ready(); } else { setTimeout(ready, 0); } }); K('.ke-map', div).replaceWith(iframe); // search map searchBtn.click(function() { win.search(addressBox.val()); }); }); });
JavaScript
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ KindEditor.plugin('emoticons', function(K) { var self = this, name = 'emoticons', path = (self.emoticonsPath || self.pluginsPath + 'emoticons/images/'), allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons, currentPageNum = 1; self.clickToolbar(name, function() { var rows = 5, cols = 9, total = 135, startNum = 0, cells = rows * cols, pages = Math.ceil(total / cells), colsHalf = Math.floor(cols / 2), wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'), elements = [], menu = self.createMenu({ name : name, beforeRemove : function() { removeEvent(); } }); menu.div.append(wrapperDiv); var previewDiv, previewImg; if (allowPreview) { previewDiv = K('<div class="ke-preview"></div>').css('right', 0); previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />'); wrapperDiv.append(previewDiv); previewDiv.append(previewImg); } function bindCellEvent(cell, j, num) { if (previewDiv) { cell.mouseover(function() { if (j > colsHalf) { previewDiv.css('left', 0); previewDiv.css('right', ''); } else { previewDiv.css('left', ''); previewDiv.css('right', 0); } previewImg.attr('src', path + num + '.gif'); K(this).addClass('ke-on'); }); } else { cell.mouseover(function() { K(this).addClass('ke-on'); }); } cell.mouseout(function() { K(this).removeClass('ke-on'); }); cell.click(function(e) { self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus(); e.stop(); }); } function createEmoticonsTable(pageNum, parentDiv) { var table = document.createElement('table'); parentDiv.append(table); if (previewDiv) { K(table).mouseover(function() { previewDiv.show('block'); }); K(table).mouseout(function() { previewDiv.hide(); }); elements.push(K(table)); } table.className = 'ke-table'; table.cellPadding = 0; table.cellSpacing = 0; table.border = 0; var num = (pageNum - 1) * cells + startNum; for (var i = 0; i < rows; i++) { var row = table.insertRow(i); for (var j = 0; j < cols; j++) { var cell = K(row.insertCell(j)); cell.addClass('ke-cell'); bindCellEvent(cell, j, num); var span = K('<span class="ke-img"></span>') .css('background-position', '-' + (24 * num) + 'px 0px') .css('background-image', 'url(' + path + 'static.gif)'); cell.append(span); elements.push(cell); num++; } } return table; } var table = createEmoticonsTable(currentPageNum, wrapperDiv); function removeEvent() { K.each(elements, function() { this.unbind(); }); } var pageDiv; function bindPageEvent(el, pageNum) { el.click(function(e) { removeEvent(); table.parentNode.removeChild(table); pageDiv.remove(); table = createEmoticonsTable(pageNum, wrapperDiv); createPageTable(pageNum); currentPageNum = pageNum; e.stop(); }); } function createPageTable(currentPageNum) { pageDiv = K('<div class="ke-page"></div>'); wrapperDiv.append(pageDiv); for (var pageNum = 1; pageNum <= pages; pageNum++) { if (currentPageNum !== pageNum) { var a = K('<a href="javascript:;">[' + pageNum + ']</a>'); bindPageEvent(a, pageNum); pageDiv.append(a); elements.push(a); } else { pageDiv.append(K('@[' + pageNum + ']')); } pageDiv.append(K('@&nbsp;')); } } createPageTable(currentPageNum); }); });
JavaScript
/*! * artDialog 4.1.6 * Date: 2012-07-16 22:57 * http://code.google.com/p/artdialog/ * (c) 2009-2012 TangBin, http://www.planeArt.cn * * This is licensed under the GNU LGPL, version 2.1 or later. * For details, see: http://creativecommons.org/licenses/LGPL/2.1/ */ ;(function ($, window, undefined) { $.noop = $.noop || function () {}; // jQuery 1.3.2 var _box, _thisScript, _skin, _path, _count = 0, _$window = $(window), _$document = $(document), _$html = $('html'), _elem = document.documentElement, _isIE6 = window.VBArray && !window.XMLHttpRequest, _isMobile = 'createTouch' in document && !('onmousemove' in _elem) || /(iPhone|iPad|iPod)/i.test(navigator.userAgent), _expando = 'artDialog' + + new Date; var artDialog = function (config, ok, cancel) { config = config || {}; if (typeof config === 'string' || config.nodeType === 1) { config = {content: config, fixed: !_isMobile}; }; var api, defaults = artDialog.defaults, elem = config.follow = this.nodeType === 1 && this || config.follow; // 合并默认配置 for (var i in defaults) { if (config[i] === undefined) config[i] = defaults[i]; }; // 兼容v4.1.0之前的参数,未来版本将删除此 $.each({ok:"yesFn",cancel:"noFn",close:"closeFn",init:"initFn",okVal:"yesText",cancelVal:"noText"}, function(i,o){config[i]=config[i]!==undefined?config[i]:config[o]}); // 返回跟随模式或重复定义的ID if (typeof elem === 'string') elem = $(elem)[0]; config.id = elem && elem[_expando + 'follow'] || config.id || _expando + _count; api = artDialog.list[config.id]; if (elem && api) return api.follow(elem).zIndex().focus(); if (api) return api.zIndex().focus(); // 目前主流移动设备对fixed支持不好 if (_isMobile) config.fixed = false; // 按钮队列 if (!$.isArray(config.button)) { config.button = config.button ? [config.button] : []; }; if (ok !== undefined) config.ok = ok; if (cancel !== undefined) config.cancel = cancel; config.ok && config.button.push({ name: config.okVal, callback: config.ok, focus: true }); config.cancel && config.button.push({ name: config.cancelVal, callback: config.cancel }); // zIndex全局配置 artDialog.defaults.zIndex = config.zIndex; _count ++; return artDialog.list[config.id] = _box ? _box._init(config) : new artDialog.fn._init(config); }; artDialog.fn = artDialog.prototype = { version: '4.1.6', closed: true, _init: function (config) { var that = this, DOM, icon = config.icon, iconBg = icon && (_isIE6 ? {png: 'icons/' + icon + '.png'} : {backgroundImage: 'url(\'' + config.path + '/skins/icons/' + icon + '.png\')'}); that.closed = false; that.config = config; that.DOM = DOM = that.DOM || that._getDOM(); DOM.wrap.addClass(config.skin); DOM.close[config.cancel === false ? 'hide' : 'show'](); DOM.icon[0].style.display = icon ? '' : 'none'; DOM.iconBg.css(iconBg || {background: 'none'}); DOM.se.css('cursor', config.resize ? 'se-resize' : 'auto'); DOM.title.css('cursor', config.drag ? 'move' : 'auto'); DOM.content.css('padding', config.padding); that[config.show ? 'show' : 'hide'](true) that.button(config.button) .title(config.title) .content(config.content, true) .size(config.width, config.height) .time(config.time); config.follow ? that.follow(config.follow) : that.position(config.left, config.top); that.zIndex().focus(); config.lock && that.lock(); that._addEvent(); that._ie6PngFix(); _box = null; config.init && config.init.call(that, window); return that; }, /** * 设置内容 * @param {String, HTMLElement} 内容 (可选) * @return {this, HTMLElement} 如果无参数则返回内容容器DOM对象 */ content: function (msg) { var prev, next, parent, display, that = this, DOM = that.DOM, wrap = DOM.wrap[0], width = wrap.offsetWidth, height = wrap.offsetHeight, left = parseInt(wrap.style.left), top = parseInt(wrap.style.top), cssWidth = wrap.style.width, $content = DOM.content, content = $content[0]; that._elemBack && that._elemBack(); wrap.style.width = 'auto'; if (msg === undefined) return content; if (typeof msg === 'string') { $content.html(msg); } else if (msg && msg.nodeType === 1) { // 让传入的元素在对话框关闭后可以返回到原来的地方 display = msg.style.display; prev = msg.previousSibling; next = msg.nextSibling; parent = msg.parentNode; that._elemBack = function () { if (prev && prev.parentNode) { prev.parentNode.insertBefore(msg, prev.nextSibling); } else if (next && next.parentNode) { next.parentNode.insertBefore(msg, next); } else if (parent) { parent.appendChild(msg); }; msg.style.display = display; that._elemBack = null; }; $content.html(''); content.appendChild(msg); msg.style.display = 'block'; }; // 新增内容后调整位置 if (!arguments[1]) { if (that.config.follow) { that.follow(that.config.follow); } else { width = wrap.offsetWidth - width; height = wrap.offsetHeight - height; left = left - width / 2; top = top - height / 2; wrap.style.left = Math.max(left, 0) + 'px'; wrap.style.top = Math.max(top, 0) + 'px'; }; if (cssWidth && cssWidth !== 'auto') { wrap.style.width = wrap.offsetWidth + 'px'; }; that._autoPositionType(); }; that._ie6SelectFix(); that._runScript(content); return that; }, /** * 设置标题 * @param {String, Boolean} 标题内容. 为false则隐藏标题栏 * @return {this, HTMLElement} 如果无参数则返回内容器DOM对象 */ title: function (text) { var DOM = this.DOM, wrap = DOM.wrap, title = DOM.title, className = 'aui_state_noTitle'; if (text === undefined) return title[0]; if (text === false) { title.hide().html(''); wrap.addClass(className); } else { title.show().html(text || ''); wrap.removeClass(className); }; return this; }, /** * 位置(相对于可视区域) * @param {Number, String} * @param {Number, String} */ position: function (left, top) { var that = this, config = that.config, wrap = that.DOM.wrap[0], isFixed = _isIE6 ? false : config.fixed, ie6Fixed = _isIE6 && that.config.fixed, docLeft = _$document.scrollLeft(), docTop = _$document.scrollTop(), dl = isFixed ? 0 : docLeft, dt = isFixed ? 0 : docTop, ww = _$window.width(), wh = _$window.height(), ow = wrap.offsetWidth, oh = wrap.offsetHeight, style = wrap.style; if (left || left === 0) { that._left = left.toString().indexOf('%') !== -1 ? left : null; left = that._toNumber(left, ww - ow); if (typeof left === 'number') { left = ie6Fixed ? (left += docLeft) : left + dl; style.left = Math.max(left, dl) + 'px'; } else if (typeof left === 'string') { style.left = left; }; }; if (top || top === 0) { that._top = top.toString().indexOf('%') !== -1 ? top : null; top = that._toNumber(top, wh - oh); if (typeof top === 'number') { top = ie6Fixed ? (top += docTop) : top + dt; style.top = Math.max(top, dt) + 'px'; } else if (typeof top === 'string') { style.top = top; }; }; if (left !== undefined && top !== undefined) { that._follow = null; that._autoPositionType(); }; return that; }, /** * 尺寸 * @param {Number, String} 宽度 * @param {Number, String} 高度 */ size: function (width, height) { var maxWidth, maxHeight, scaleWidth, scaleHeight, that = this, config = that.config, DOM = that.DOM, wrap = DOM.wrap, main = DOM.main, wrapStyle = wrap[0].style, style = main[0].style; if (width) { that._width = width.toString().indexOf('%') !== -1 ? width : null; maxWidth = _$window.width() - wrap[0].offsetWidth + main[0].offsetWidth; scaleWidth = that._toNumber(width, maxWidth); width = scaleWidth; if (typeof width === 'number') { wrapStyle.width = 'auto'; style.width = Math.max(that.config.minWidth, width) + 'px'; wrapStyle.width = wrap[0].offsetWidth + 'px'; // 防止未定义宽度的表格遇到浏览器右边边界伸缩 } else if (typeof width === 'string') { style.width = width; width === 'auto' && wrap.css('width', 'auto'); }; }; if (height) { that._height = height.toString().indexOf('%') !== -1 ? height : null; maxHeight = _$window.height() - wrap[0].offsetHeight + main[0].offsetHeight; scaleHeight = that._toNumber(height, maxHeight); height = scaleHeight; if (typeof height === 'number') { style.height = Math.max(that.config.minHeight, height) + 'px'; } else if (typeof height === 'string') { style.height = height; }; }; that._ie6SelectFix(); return that; }, /** * 跟随元素 * @param {HTMLElement, String} */ follow: function (elem) { var $elem, that = this, config = that.config; if (typeof elem === 'string' || elem && elem.nodeType === 1) { $elem = $(elem); elem = $elem[0]; }; // 隐藏元素不可用 if (!elem || !elem.offsetWidth && !elem.offsetHeight) { return that.position(that._left, that._top); }; var expando = _expando + 'follow', winWidth = _$window.width(), winHeight = _$window.height(), docLeft = _$document.scrollLeft(), docTop = _$document.scrollTop(), offset = $elem.offset(), width = elem.offsetWidth, height = elem.offsetHeight, isFixed = _isIE6 ? false : config.fixed, left = isFixed ? offset.left - docLeft : offset.left, top = isFixed ? offset.top - docTop : offset.top, wrap = that.DOM.wrap[0], style = wrap.style, wrapWidth = wrap.offsetWidth, wrapHeight = wrap.offsetHeight, setLeft = left - (wrapWidth - width) / 2, setTop = top + height, dl = isFixed ? 0 : docLeft, dt = isFixed ? 0 : docTop; setLeft = setLeft < dl ? left : (setLeft + wrapWidth > winWidth) && (left - wrapWidth > dl) ? left - wrapWidth + width : setLeft; setTop = (setTop + wrapHeight > winHeight + dt) && (top - wrapHeight > dt) ? top - wrapHeight : setTop; style.left = setLeft + 'px'; style.top = setTop + 'px'; that._follow && that._follow.removeAttribute(expando); that._follow = elem; elem[expando] = config.id; that._autoPositionType(); return that; }, /** * 自定义按钮 * @example button({ name: 'login', callback: function () {}, disabled: false, focus: true }, .., ..) */ button: function () { var that = this, ags = arguments, DOM = that.DOM, buttons = DOM.buttons, elem = buttons[0], strongButton = 'aui_state_highlight', listeners = that._listeners = that._listeners || {}, list = $.isArray(ags[0]) ? ags[0] : [].slice.call(ags); if (ags[0] === undefined) return elem; $.each(list, function (i, val) { var name = val.name, isNewButton = !listeners[name], button = !isNewButton ? listeners[name].elem : document.createElement('button'); if (!listeners[name]) listeners[name] = {}; if (val.callback) listeners[name].callback = val.callback; if (val.className) button.className = val.className; if (val.focus) { that._focus && that._focus.removeClass(strongButton); that._focus = $(button).addClass(strongButton); that.focus(); }; // Internet Explorer 的默认类型是 "button", // 而其他浏览器中(包括 W3C 规范)的默认值是 "submit" // @see http://www.w3school.com.cn/tags/att_button_type.asp button.setAttribute('type', 'button'); button[_expando + 'callback'] = name; button.disabled = !!val.disabled; if (isNewButton) { button.innerHTML = name; listeners[name].elem = button; elem.appendChild(button); }; }); buttons[0].style.display = list.length ? '' : 'none'; that._ie6SelectFix(); return that; }, /** 显示对话框 */ show: function () { this.DOM.wrap.show(); !arguments[0] && this._lockMaskWrap && this._lockMaskWrap.show(); return this; }, /** 隐藏对话框 */ hide: function () { this.DOM.wrap.hide(); !arguments[0] && this._lockMaskWrap && this._lockMaskWrap.hide(); return this; }, /** 关闭对话框 */ close: function () { if (this.closed) return this; var that = this, DOM = that.DOM, wrap = DOM.wrap, list = artDialog.list, fn = that.config.close, follow = that.config.follow; that.time(); if (typeof fn === 'function' && fn.call(that, window) === false) { return that; }; that.unlock(); // 置空内容 that._elemBack && that._elemBack(); wrap[0].className = wrap[0].style.cssText = ''; DOM.title.html(''); DOM.content.html(''); DOM.buttons.html(''); if (artDialog.focus === that) artDialog.focus = null; if (follow) follow.removeAttribute(_expando + 'follow'); delete list[that.config.id]; that._removeEvent(); that.hide(true)._setAbsolute(); // 清空除this.DOM之外临时对象,恢复到初始状态,以便使用单例模式 for (var i in that) { if (that.hasOwnProperty(i) && i !== 'DOM') delete that[i]; }; // 移除HTMLElement或重用 _box ? wrap.remove() : _box = that; return that; }, /** * 定时关闭 * @param {Number} 单位为秒, 无参数则停止计时器 */ time: function (second) { var that = this, cancel = that.config.cancelVal, timer = that._timer; timer && clearTimeout(timer); if (second) { that._timer = setTimeout(function(){ that._click(cancel); }, 1000 * second); }; return that; }, /** 设置焦点 */ focus: function () { try { var elem = this._focus && this._focus[0] || this.DOM.close[0]; elem && elem.focus(); } catch (e) {}; // IE对不可见元素设置焦点会报错 return this; }, /** 置顶对话框 */ zIndex: function () { var that = this, DOM = that.DOM, wrap = DOM.wrap, top = artDialog.focus, index = artDialog.defaults.zIndex ++; // 设置叠加高度 wrap.css('zIndex', index); that._lockMask && that._lockMask.css('zIndex', index - 1); // 设置最高层的样式 top && top.DOM.wrap.removeClass('aui_state_focus'); artDialog.focus = that; wrap.addClass('aui_state_focus'); return that; }, /** 设置屏锁 */ lock: function () { if (this._lock) return this; var that = this, index = artDialog.defaults.zIndex - 1, wrap = that.DOM.wrap, config = that.config, docWidth = _$document.width(), docHeight = _$document.height(), lockMaskWrap = that._lockMaskWrap || $(document.body.appendChild(document.createElement('div'))), lockMask = that._lockMask || $(lockMaskWrap[0].appendChild(document.createElement('div'))), domTxt = '(document).documentElement', sizeCss = _isMobile ? 'width:' + docWidth + 'px;height:' + docHeight + 'px' : 'width:100%;height:100%', ie6Css = _isIE6 ? 'position:absolute;left:expression(' + domTxt + '.scrollLeft);top:expression(' + domTxt + '.scrollTop);width:expression(' + domTxt + '.clientWidth);height:expression(' + domTxt + '.clientHeight)' : ''; that.zIndex(); wrap.addClass('aui_state_lock'); lockMaskWrap[0].style.cssText = sizeCss + ';position:fixed;z-index:' + index + ';top:0;left:0;overflow:hidden;' + ie6Css; lockMask[0].style.cssText = 'height:100%;background:' + config.background + ';filter:alpha(opacity=0);opacity:0'; // 让IE6锁屏遮罩能够盖住下拉控件 if (_isIE6) lockMask.html( '<iframe src="about:blank" style="width:100%;height:100%;position:absolute;' + 'top:0;left:0;z-index:-1;filter:alpha(opacity=0)"></iframe>'); lockMask.stop(); lockMask.bind('click', function () { that._reset(); }).bind('dblclick', function () { that._click(that.config.cancelVal); }); if (config.duration === 0) { lockMask.css({opacity: config.opacity}); } else { lockMask.animate({opacity: config.opacity}, config.duration); }; that._lockMaskWrap = lockMaskWrap; that._lockMask = lockMask; that._lock = true; return that; }, /** 解开屏锁 */ unlock: function () { var that = this, lockMaskWrap = that._lockMaskWrap, lockMask = that._lockMask; if (!that._lock) return that; var style = lockMaskWrap[0].style; var un = function () { if (_isIE6) { style.removeExpression('width'); style.removeExpression('height'); style.removeExpression('left'); style.removeExpression('top'); }; style.cssText = 'display:none'; _box && lockMaskWrap.remove(); }; lockMask.stop().unbind(); that.DOM.wrap.removeClass('aui_state_lock'); if (!that.config.duration) {// 取消动画,快速关闭 un(); } else { lockMask.animate({opacity: 0}, that.config.duration, un); }; that._lock = false; return that; }, // 获取元素 _getDOM: function () { var wrap = document.createElement('div'), body = document.body; wrap.style.cssText = 'position:absolute;left:0;top:0'; wrap.innerHTML = artDialog._templates; body.insertBefore(wrap, body.firstChild); var name, i = 0, DOM = {wrap: $(wrap)}, els = wrap.getElementsByTagName('*'), elsLen = els.length; for (; i < elsLen; i ++) { name = els[i].className.split('aui_')[1]; if (name) DOM[name] = $(els[i]); }; return DOM; }, // px与%单位转换成数值 (百分比单位按照最大值换算) // 其他的单位返回原值 _toNumber: function (thisValue, maxValue) { if (!thisValue && thisValue !== 0 || typeof thisValue === 'number') { return thisValue; }; var last = thisValue.length - 1; if (thisValue.lastIndexOf('px') === last) { thisValue = parseInt(thisValue); } else if (thisValue.lastIndexOf('%') === last) { thisValue = parseInt(maxValue * thisValue.split('%')[0] / 100); }; return thisValue; }, // 让IE6 CSS支持PNG背景 _ie6PngFix: _isIE6 ? function () { var i = 0, elem, png, pngPath, runtimeStyle, path = artDialog.defaults.path + '/skins/', list = this.DOM.wrap[0].getElementsByTagName('*'); for (; i < list.length; i ++) { elem = list[i]; png = elem.currentStyle['png']; if (png) { pngPath = path + png; runtimeStyle = elem.runtimeStyle; runtimeStyle.backgroundImage = 'none'; runtimeStyle.filter = "progid:DXImageTransform.Microsoft." + "AlphaImageLoader(src='" + pngPath + "',sizingMethod='crop')"; }; }; } : $.noop, // 强制覆盖IE6下拉控件 _ie6SelectFix: _isIE6 ? function () { var $wrap = this.DOM.wrap, wrap = $wrap[0], expando = _expando + 'iframeMask', iframe = $wrap[expando], width = wrap.offsetWidth, height = wrap.offsetHeight; width = width + 'px'; height = height + 'px'; if (iframe) { iframe.style.width = width; iframe.style.height = height; } else { iframe = wrap.appendChild(document.createElement('iframe')); $wrap[expando] = iframe; iframe.src = 'about:blank'; iframe.style.cssText = 'position:absolute;z-index:-1;left:0;top:0;' + 'filter:alpha(opacity=0);width:' + width + ';height:' + height; }; } : $.noop, // 解析HTML片段中自定义类型脚本,其this指向artDialog内部 // <script type="text/dialog">/* [code] */</script> _runScript: function (elem) { var fun, i = 0, n = 0, tags = elem.getElementsByTagName('script'), length = tags.length, script = []; for (; i < length; i ++) { if (tags[i].type === 'text/dialog') { script[n] = tags[i].innerHTML; n ++; }; }; if (script.length) { script = script.join(''); fun = new Function(script); fun.call(this); }; }, // 自动切换定位类型 _autoPositionType: function () { this[this.config.fixed ? '_setFixed' : '_setAbsolute']();///////////// }, // 设置静止定位 // IE6 Fixed @see: http://www.planeart.cn/?p=877 _setFixed: (function () { _isIE6 && $(function () { var bg = 'backgroundAttachment'; if (_$html.css(bg) !== 'fixed' && $('body').css(bg) !== 'fixed') { _$html.css({ zoom: 1,// 避免偶尔出现body背景图片异常的情况 backgroundImage: 'url(about:blank)', backgroundAttachment: 'fixed' }); }; }); return function () { var $elem = this.DOM.wrap, style = $elem[0].style; if (_isIE6) { var left = parseInt($elem.css('left')), top = parseInt($elem.css('top')), sLeft = _$document.scrollLeft(), sTop = _$document.scrollTop(), txt = '(document.documentElement)'; this._setAbsolute(); style.setExpression('left', 'eval(' + txt + '.scrollLeft + ' + (left - sLeft) + ') + "px"'); style.setExpression('top', 'eval(' + txt + '.scrollTop + ' + (top - sTop) + ') + "px"'); } else { style.position = 'fixed'; }; }; }()), // 设置绝对定位 _setAbsolute: function () { var style = this.DOM.wrap[0].style; if (_isIE6) { style.removeExpression('left'); style.removeExpression('top'); }; style.position = 'absolute'; }, // 按钮回调函数触发 _click: function (name) { var that = this, fn = that._listeners[name] && that._listeners[name].callback; return typeof fn !== 'function' || fn.call(that, window) !== false ? that.close() : that; }, // 重置位置与尺寸 _reset: function (test) { var newSize, that = this, oldSize = that._winSize || _$window.width() * _$window.height(), elem = that._follow, width = that._width, height = that._height, left = that._left, top = that._top; if (test) { // IE6~7 window.onresize bug newSize = that._winSize = _$window.width() * _$window.height(); if (oldSize === newSize) return; }; if (width || height) that.size(width, height); if (elem) { that.follow(elem); } else if (left || top) { that.position(left, top); }; }, // 事件代理 _addEvent: function () { var resizeTimer, that = this, config = that.config, isIE = 'CollectGarbage' in window, DOM = that.DOM; // 窗口调节事件 that._winResize = function () { resizeTimer && clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { that._reset(isIE); }, 40); }; _$window.bind('resize', that._winResize); // 监听点击 DOM.wrap .bind('click', function (event) { var target = event.target, callbackID; if (target.disabled) return false; // IE BUG if (target === DOM.close[0]) { that._click(config.cancelVal); return false; } else { callbackID = target[_expando + 'callback']; callbackID && that._click(callbackID); }; that._ie6SelectFix(); }) .bind('mousedown', function () { that.zIndex(); }); }, // 卸载事件代理 _removeEvent: function () { var that = this, DOM = that.DOM; DOM.wrap.unbind(); _$window.unbind('resize', that._winResize); } }; artDialog.fn._init.prototype = artDialog.fn; $.fn.dialog = $.fn.artDialog = function () { var config = arguments; this[this.live ? 'live' : 'bind']('click', function () { artDialog.apply(this, config); return false; }); return this; }; /** 最顶层的对话框API */ artDialog.focus = null; /** 获取某对话框API */ artDialog.get = function (id) { return id === undefined ? artDialog.list : artDialog.list[id]; }; artDialog.list = {}; // 全局快捷键 _$document.bind('keydown', function (event) { var target = event.target, nodeName = target.nodeName, rinput = /^INPUT|TEXTAREA$/, api = artDialog.focus, keyCode = event.keyCode; if (!api || !api.config.esc || rinput.test(nodeName)) return; keyCode === 27 && api._click(api.config.cancelVal); }); // 获取artDialog路径 _path = window['_artDialog_path'] || (function (script, i, me) { for (i in script) { // 如果通过第三方脚本加载器加载本文件,请保证文件名含有"artDialog"字符 if (script[i].src && script[i].src.indexOf('artDialog') !== -1) me = script[i]; }; _thisScript = me || script[script.length - 1]; me = _thisScript.src.replace(/\\/g, '/'); return me.lastIndexOf('/') < 0 ? '.' : me.substring(0, me.lastIndexOf('/')); }(document.getElementsByTagName('script'))); // 无阻塞载入CSS (如"artDialog.js?skin=aero") _skin = _thisScript.src.split('skin=')[1]; if (_skin) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = _path + '/skins/' + _skin + '.css?' + artDialog.fn.version; _thisScript.parentNode.insertBefore(link, _thisScript); }; // 触发浏览器预先缓存背景图片 _$window.bind('load', function () { setTimeout(function () { if (_count) return; artDialog({left: '-9999em',time: 9,fixed: false,lock: false,focus: false}); }, 150); }); // 开启IE6 CSS背景图片缓存 try { document.execCommand('BackgroundImageCache', false, true); } catch (e) {}; // 使用uglifyjs压缩能够预先处理"+"号合并字符串 // uglifyjs: http://marijnhaverbeke.nl/uglifyjs artDialog._templates = '<div class="aui_outer">' + '<table class="aui_border">' + '<tbody>' + '<tr>' + '<td class="aui_nw"></td>' + '<td class="aui_n"></td>' + '<td class="aui_ne"></td>' + '</tr>' + '<tr>' + '<td class="aui_w"></td>' + '<td class="aui_c">' + '<div class="aui_inner">' + '<table class="aui_dialog">' + '<tbody>' + '<tr>' + '<td colspan="2" class="aui_header">' + '<div class="aui_titleBar">' + '<div class="aui_title"></div>' + '<a class="aui_close" href="javascript:void(0);">' + '\xd7' + '</a>' + '</div>' + '</td>' + '</tr>' + '<tr>' + '<td class="aui_icon">' + '<div class="aui_iconBg"></div>' + '</td>' + '<td class="aui_main">' + '<div class="aui_content"></div>' + '</td>' + '</tr>' + '<tr>' + '<td colspan="2" class="aui_footer">' + '<div class="aui_buttons"></div>' + '</td>' + '</tr>' + '</tbody>' + '</table>' + '</div>' + '</td>' + '<td class="aui_e"></td>' + '</tr>' + '<tr>' + '<td class="aui_sw"></td>' + '<td class="aui_s"></td>' + '<td class="aui_se"></td>' + '</tr>' + '</tbody>' + '</table>' +'</div>'; /** * 默认配置 */ artDialog.defaults = { // 消息内容 content: '<div class="aui_loading"><span>loading..</span></div>', title: '\u6d88\u606f', // 标题. 默认'消息' button: null, // 自定义按钮 ok: null, // 确定按钮回调函数 cancel: null, // 取消按钮回调函数 init: null, // 对话框初始化后执行的函数 close: null, // 对话框关闭前执行的函数 okVal: '\u786E\u5B9A', // 确定按钮文本. 默认'确定' cancelVal: '\u53D6\u6D88', // 取消按钮文本. 默认'取消' width: 'auto', // 内容宽度 height: 'auto', // 内容高度 minWidth: 96, // 最小宽度限制 minHeight: 32, // 最小高度限制 padding: '10px 15px', // 内容与边界填充距离 skin: '', // 皮肤名(预留接口,尚未实现) icon: null, // 消息图标名称 time: null, // 自动关闭时间 esc: true, // 是否支持Esc键关闭 focus: true, // 是否支持对话框按钮自动聚焦 show: true, // 初始化后是否显示对话框 follow: null, // 跟随某元素(即让对话框在元素附近弹出) path: _path, // artDialog路径 lock: false, // 是否锁屏 background: '#000', // 遮罩颜色 opacity: .7, // 遮罩透明度 duration: 300, // 遮罩透明度渐变动画速度 fixed: false, // 是否静止定位 left: '50%', // X轴坐标 top: '38.2%', // Y轴坐标 zIndex: 1987, // 对话框叠加高度值(重要:此值不能超过浏览器最大限制) resize: true, // 是否允许用户调节尺寸 drag: true // 是否允许用户拖动位置 }; window.artDialog = $.dialog = $.artDialog = artDialog; }(this.art || this.jQuery && (this.art = jQuery), this)); //------------------------------------------------ // 对话框模块-拖拽支持(可选外置模块) //------------------------------------------------ ;(function ($) { var _dragEvent, _use, _$window = $(window), _$document = $(document), _elem = document.documentElement, _isIE6 = !('minWidth' in _elem.style), _isLosecapture = 'onlosecapture' in _elem, _isSetCapture = 'setCapture' in _elem; // 拖拽事件 artDialog.dragEvent = function () { var that = this, proxy = function (name) { var fn = that[name]; that[name] = function () { return fn.apply(that, arguments); }; }; proxy('start'); proxy('move'); proxy('end'); }; artDialog.dragEvent.prototype = { // 开始拖拽 onstart: $.noop, start: function (event) { _$document .bind('mousemove', this.move) .bind('mouseup', this.end); this._sClientX = event.clientX; this._sClientY = event.clientY; this.onstart(event.clientX, event.clientY); return false; }, // 正在拖拽 onmove: $.noop, move: function (event) { this._mClientX = event.clientX; this._mClientY = event.clientY; this.onmove( event.clientX - this._sClientX, event.clientY - this._sClientY ); return false; }, // 结束拖拽 onend: $.noop, end: function (event) { _$document .unbind('mousemove', this.move) .unbind('mouseup', this.end); this.onend(event.clientX, event.clientY); return false; } }; _use = function (event) { var limit, startWidth, startHeight, startLeft, startTop, isResize, api = artDialog.focus, //config = api.config, DOM = api.DOM, wrap = DOM.wrap, title = DOM.title, main = DOM.main; // 清除文本选择 var clsSelect = 'getSelection' in window ? function () { window.getSelection().removeAllRanges(); } : function () { try { document.selection.empty(); } catch (e) {}; }; // 对话框准备拖动 _dragEvent.onstart = function (x, y) { if (isResize) { startWidth = main[0].offsetWidth; startHeight = main[0].offsetHeight; } else { startLeft = wrap[0].offsetLeft; startTop = wrap[0].offsetTop; }; _$document.bind('dblclick', _dragEvent.end); !_isIE6 && _isLosecapture ? title.bind('losecapture', _dragEvent.end) : _$window.bind('blur', _dragEvent.end); _isSetCapture && title[0].setCapture(); wrap.addClass('aui_state_drag'); api.focus(); }; // 对话框拖动进行中 _dragEvent.onmove = function (x, y) { if (isResize) { var wrapStyle = wrap[0].style, style = main[0].style, width = x + startWidth, height = y + startHeight; wrapStyle.width = 'auto'; style.width = Math.max(0, width) + 'px'; wrapStyle.width = wrap[0].offsetWidth + 'px'; style.height = Math.max(0, height) + 'px'; } else { var style = wrap[0].style, left = Math.max(limit.minX, Math.min(limit.maxX, x + startLeft)), top = Math.max(limit.minY, Math.min(limit.maxY, y + startTop)); style.left = left + 'px'; style.top = top + 'px'; }; clsSelect(); api._ie6SelectFix(); }; // 对话框拖动结束 _dragEvent.onend = function (x, y) { _$document.unbind('dblclick', _dragEvent.end); !_isIE6 && _isLosecapture ? title.unbind('losecapture', _dragEvent.end) : _$window.unbind('blur', _dragEvent.end); _isSetCapture && title[0].releaseCapture(); _isIE6 && !api.closed && api._autoPositionType(); wrap.removeClass('aui_state_drag'); }; isResize = event.target === DOM.se[0] ? true : false; limit = (function () { var maxX, maxY, wrap = api.DOM.wrap[0], fixed = wrap.style.position === 'fixed', ow = wrap.offsetWidth, oh = wrap.offsetHeight, ww = _$window.width(), wh = _$window.height(), dl = fixed ? 0 : _$document.scrollLeft(), dt = fixed ? 0 : _$document.scrollTop(), // 坐标最大值限制 maxX = ww - ow + dl; maxY = wh - oh + dt; return { minX: dl, minY: dt, maxX: maxX, maxY: maxY }; })(); _dragEvent.start(event); }; // 代理 mousedown 事件触发对话框拖动 _$document.bind('mousedown', function (event) { var api = artDialog.focus; if (!api) return; var target = event.target, config = api.config, DOM = api.DOM; if (config.drag !== false && target === DOM.title[0] || config.resize !== false && target === DOM.se[0]) { _dragEvent = _dragEvent || new artDialog.dragEvent(); _use(event); return false;// 防止firefox与chrome滚屏 }; }); })(this.art || this.jQuery && (this.art = jQuery)); /*! * artDialog iframeTools * Date: 2011-11-25 13:54 * http://code.google.com/p/artdialog/ * (c) 2009-2011 TangBin, http://www.planeArt.cn * * This is licensed under the GNU LGPL, version 2.1 or later. * For details, see: http://creativecommons.org/licenses/LGPL/2.1/ */ ;(function ($, window, artDialog, undefined) { var _topDialog, _proxyDialog, _zIndex, _data = '@ARTDIALOG.DATA', _open = '@ARTDIALOG.OPEN', _opener = '@ARTDIALOG.OPENER', _winName = window.name = window.name || '@ARTDIALOG.WINNAME' + + new Date, _isIE6 = window.VBArray && !window.XMLHttpRequest; $(function () { !window.jQuery && document.compatMode === 'BackCompat' // 不支持怪异模式,请用主流的XHTML1.0或者HTML5的DOCTYPE申明 && alert('artDialog Error: document.compatMode === "BackCompat"'); }); /** 获取 artDialog 可跨级调用的最高层的 window 对象 */ var _top = artDialog.top = function () { var top = window, test = function (name) { try { var doc = window[name].document; // 跨域|无权限 doc.getElementsByTagName; // chrome 本地安全限制 } catch (e) { return false; }; return window[name].artDialog // 框架集无法显示第三方元素 && doc.getElementsByTagName('frameset').length === 0; }; if (test('top')) { top = window.top; } else if (test('parent')) { top = window.parent; }; return top; }(); artDialog.parent = _top; // 兼容v4.1之前版本,未来版本将删除此 _topDialog = _top.artDialog; // 获取顶层页面对话框叠加值 _zIndex = function () { return _topDialog.defaults.zIndex; }; /** * 跨框架数据共享接口 * @see http://www.planeart.cn/?p=1554 * @param {String} 存储的数据名 * @param {Any} 将要存储的任意数据(无此项则返回被查询的数据) */ artDialog.data = function (name, value) { var top = artDialog.top, cache = top[_data] || {}; top[_data] = cache; if (value !== undefined) { cache[name] = value; } else { return cache[name]; }; return cache; }; /** * 数据共享删除接口 * @param {String} 删除的数据名 */ artDialog.removeData = function (name) { var cache = artDialog.top[_data]; if (cache && cache[name]) delete cache[name]; }; /** 跨框架普通对话框 */ artDialog.through = _proxyDialog = function () { var api = _topDialog.apply(this, arguments); // 缓存从当前 window(可能为iframe)调出所有跨框架对话框, // 以便让当前 window 卸载前去关闭这些对话框。 // 因为iframe注销后也会从内存中删除其创建的对象,这样可以防止回调函数报错 if (_top !== window) artDialog.list[api.config.id] = api; return api; }; // 框架页面卸载前关闭所有穿越的对话框 _top !== window && $(window).bind('unload', function () { var list = artDialog.list, config; for (var i in list) { if (list[i]) { config = list[i].config; if (config) config.duration = 0; // 取消动画 list[i].close(); //delete list[i]; }; }; }); /** * 弹窗 (iframe) * @param {String} 地址 * @param {Object} 配置参数. 这里传入的回调函数接收的第1个参数为iframe内部window对象 * @param {Boolean} 是否允许缓存. 默认true */ artDialog.open = function (url, options, cache) { options = options || {}; var api, DOM, $content, $main, iframe, $iframe, $idoc, iwin, ibody, top = artDialog.top, initCss = 'position:absolute;left:-9999em;top:-9999em;border:none 0;background:transparent', loadCss = 'width:100%;height:100%;border:none 0'; if (cache === false) { var ts = + new Date, ret = url.replace(/([?&])_=[^&]*/, "$1_=" + ts ); url = ret + ((ret === url) ? (/\?/.test(url) ? "&" : "?") + "_=" + ts : ""); }; var load = function () { var iWidth, iHeight, loading = DOM.content.find('.aui_loading'), aConfig = api.config; $content.addClass('aui_state_full'); loading && loading.hide(); try { iwin = iframe.contentWindow; $idoc = $(iwin.document); ibody = iwin.document.body; } catch (e) {// 跨域 iframe.style.cssText = loadCss; aConfig.follow ? api.follow(aConfig.follow) : api.position(aConfig.left, aConfig.top); options.init && options.init.call(api, iwin, top); options.init = null; return; }; // 获取iframe内部尺寸 iWidth = aConfig.width === 'auto' ? $idoc.width() + (_isIE6 ? 0 : parseInt($(ibody).css('marginLeft'))) : aConfig.width; iHeight = aConfig.height === 'auto' ? $idoc.height() : aConfig.height; // 适应iframe尺寸 setTimeout(function () { iframe.style.cssText = loadCss; }, 0);// setTimeout: 防止IE6~7对话框样式渲染异常 api.size(iWidth, iHeight); // 调整对话框位置 aConfig.follow ? api.follow(aConfig.follow) : api.position(aConfig.left, aConfig.top); options.init && options.init.call(api, iwin, top); options.init = null; }; var config = { zIndex: _zIndex(), init: function () { api = this; DOM = api.DOM; $main = DOM.main; $content = DOM.content; iframe = api.iframe = top.document.createElement('iframe'); iframe.src = url; iframe.name = 'Open' + api.config.id; iframe.style.cssText = initCss; iframe.setAttribute('frameborder', 0, 0); iframe.setAttribute('allowTransparency', true); $iframe = $(iframe); api.content().appendChild(iframe); iwin = iframe.contentWindow; try { iwin.name = iframe.name; artDialog.data(iframe.name + _open, api); artDialog.data(iframe.name + _opener, window); } catch (e) {}; $iframe.bind('load', load); }, close: function () { $iframe.css('display', 'none').unbind('load', load); if (options.close && options.close.call(this, iframe.contentWindow, top) === false) { return false; }; $content.removeClass('aui_state_full'); // 重要!需要重置iframe地址,否则下次出现的对话框在IE6、7无法聚焦input // IE删除iframe后,iframe仍然会留在内存中出现上述问题,置换src是最容易解决的方法 $iframe[0].src = 'about:blank'; $iframe.remove(); try { artDialog.removeData(iframe.name + _open); artDialog.removeData(iframe.name + _opener); } catch (e) {}; } }; // 回调函数第一个参数指向iframe内部window对象 if (typeof options.ok === 'function') config.ok = function () { return options.ok.call(api, iframe.contentWindow, top); }; if (typeof options.cancel === 'function') config.cancel = function () { return options.cancel.call(api, iframe.contentWindow, top); }; delete options.content; for (var i in options) { if (config[i] === undefined) config[i] = options[i]; }; return _proxyDialog(config); }; /** 引用open方法扩展方法(在open打开的iframe内部私有方法) */ artDialog.open.api = artDialog.data(_winName + _open); /** 引用open方法触发来源页面window(在open打开的iframe内部私有方法) */ artDialog.opener = artDialog.data(_winName + _opener) || window; artDialog.open.origin = artDialog.opener; // 兼容v4.1之前版本,未来版本将删除此 /** artDialog.open 打开的iframe页面里关闭对话框快捷方法 */ artDialog.close = function () { var api = artDialog.data(_winName + _open); api && api.close(); return false; }; // 点击iframe内容切换叠加高度 _top != window && $(document).bind('mousedown', function () { var api = artDialog.open.api; api && api.zIndex(); }); /** * Ajax填充内容 * @param {String} 地址 * @param {Object} 配置参数 * @param {Boolean} 是否允许缓存. 默认true */ artDialog.load = function(url, options, cache){ cache = cache || false; var opt = options || {}; var config = { zIndex: _zIndex(), init: function(here){ var api = this, aConfig = api.config; $.ajax({ url: url, success: function (content) { api.content(content); opt.init && opt.init.call(api, here); }, cache: cache }); } }; delete options.content; for (var i in opt) { if (config[i] === undefined) config[i] = opt[i]; }; return _proxyDialog(config); }; /** * 警告 * @param {String} 消息内容 */ artDialog.alert = function (content, callback) { return _proxyDialog({ id: 'Alert', zIndex: _zIndex(), icon: 'warning', fixed: true, lock: true, content: content, ok: true, close: callback }); }; /** * 确认 * @param {String} 消息内容 * @param {Function} 确定按钮回调函数 * @param {Function} 取消按钮回调函数 */ artDialog.confirm = function (content, yes, no) { return _proxyDialog({ id: 'Confirm', zIndex: _zIndex(), icon: 'question', fixed: true, lock: true, opacity: .1, content: content, ok: function (here) { return yes.call(this, here); }, cancel: function (here) { return no && no.call(this, here); } }); }; /** * 提问 * @param {String} 提问内容 * @param {Function} 回调函数. 接收参数:输入值 * @param {String} 默认值 */ artDialog.prompt = function (content, yes, value) { value = value || ''; var input; return _proxyDialog({ id: 'Prompt', zIndex: _zIndex(), icon: 'question', fixed: true, lock: true, opacity: .1, content: [ '<div style="margin-bottom:5px;font-size:12px">', content, '</div>', '<div>', '<input value="', value, '" style="width:18em;padding:6px 4px" />', '</div>' ].join(''), init: function () { input = this.DOM.content.find('input')[0]; input.select(); input.focus(); }, ok: function (here) { return yes && yes.call(this, input.value, here); }, cancel: true }); }; /** * 短暂提示 * @param {String} 提示内容 * @param {Number} 显示时间 (默认1.5秒) */ artDialog.tips = function (content, time) { return _proxyDialog({ id: 'Tips', zIndex: _zIndex(), title: false, cancel: false, fixed: true, lock: false }) .content('<div style="padding: 0 1em;">' + content + '</div>') .time(time || 1.5); }; // 增强artDialog拖拽体验 // - 防止鼠标落入iframe导致不流畅 // - 对超大对话框拖动优化 $(function () { var event = artDialog.dragEvent; if (!event) return; var $window = $(window), $document = $(document), positionType = _isIE6 ? 'absolute' : 'fixed', dragEvent = event.prototype, mask = document.createElement('div'), style = mask.style; style.cssText = 'display:none;position:' + positionType + ';left:0;top:0;width:100%;height:100%;' + 'cursor:move;filter:alpha(opacity=0);opacity:0;background:#FFF'; document.body.appendChild(mask); dragEvent._start = dragEvent.start; dragEvent._end = dragEvent.end; dragEvent.start = function () { var DOM = artDialog.focus.DOM, main = DOM.main[0], iframe = DOM.content[0].getElementsByTagName('iframe')[0]; dragEvent._start.apply(this, arguments); style.display = 'block'; style.zIndex = artDialog.defaults.zIndex + 3; if (positionType === 'absolute') { style.width = $window.width() + 'px'; style.height = $window.height() + 'px'; style.left = $document.scrollLeft() + 'px'; style.top = $document.scrollTop() + 'px'; }; if (iframe && main.offsetWidth * main.offsetHeight > 307200) { main.style.visibility = 'hidden'; }; }; dragEvent.end = function () { var dialog = artDialog.focus; dragEvent._end.apply(this, arguments); style.display = 'none'; if (dialog) dialog.DOM.main[0].style.visibility = 'visible'; }; }); })(this.art || this.jQuery, this, this.artDialog);
JavaScript
var isdebugging = false;//是否调试JS var dataType = isdebugging?'text':'json'; function setLang(t){ var lang = $(t).val(); var win = $.dialog.top; var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: win.siteaurl+'/main/setlang',data: 'lang='+lang, success: function(data){ if(data.status==200){ parent.main.location.reload(); myDialog.close(); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'setLang'); } }); } function setUrl(t,urlid){ var val = $(t).val(); if(val){ $("#"+urlid).val(val); } } function submitTo(url,func,extra){ switch(func){ case 'add': add(url); break; case 'edit': edit(url); break; case 'del': del(url,true); break; case 'sdel': del(url,false,extra); break; case 'order': order(url); break; case 'grant': grant(url); break; case 'save': save(url); break; case 'backup': backup(url); break; case 'optimize': optimize(url); break; case 'upgrade': upgrade(url); break; case 'restore': restore(url); break; case 'generate': generate(url); break; default: break; } } function setClass(t){ if($(t).val()==0){ $("#tclass").show(); }else{ $("#tclass").hide(); } } function setTid(t){ var obj = $(t).children("td").children("input"); if(obj.attr('checked')=='checked'){ obj.prop('checked',false); $(t).children("td").removeClass('listhover'); }else{ obj.prop('checked',true); $(t).children("td").addClass('listhover'); } } function checkAll(t,tname){ tname = tname?tname:'optid[]'; var tcheck = $(t).is(':checked'); $("input[name='"+tname+"']").attr('checked',tcheck); } function checkAllMethod(t){ var tcheck = $(t).is(':checked'); $("input[name*='_method']").attr('checked',tcheck); } function gotopage(num){ $("#currentpage").val(num); $('#formpage').attr('action',$("#action").val()); $('#formpage').submit(); } function nTabs(t,tid,listid,hover,listclass){ $(t).parent().children().removeClass(hover); $(t).addClass(hover); $("."+listclass).hide(); $("#"+listid+tid).show(); } function add(url){ var throughBox = $.dialog.through; var myDialog = throughBox({title:lang.add,lock:true}); $.ajax({type: "POST",url:url,dataType:'json', success: function (data) { if(data.status==200){ var win = $.dialog.top; myDialog.content(data.remsg); win.$("#formview").validform(); var editors = setEditer(win); setSubBtn(win,myDialog,'add',editors); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'add'); } }); } function edit(url){ var throughBox = $.dialog.through; var myDialog = throughBox({title:lang.edit,lock:true}); $.ajax({type: "POST",url:url,dataType: 'json', success: function (data) { if(data.status==200){ var win = $.dialog.top; myDialog.content(data.remsg); win.$("#formview").validform(); var editors = setEditer(win); setSubBtn(win,myDialog,'edit',editors); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'edit'); } }); } function del(url,ismultiple,tid){ var data; $.dialog.confirm(lang.delnotice, function(){ if(ismultiple){ data = $("#formlist").find("input:checked").serialize(); }else{ data = "optid="+tid; } if(data==""){ $.dialog.tips(lang.pselect); return; } this.close(); var win = $.dialog.top; var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:"json",url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $("#content_list").children().each(function(){ if($.isArray(data.ids)){ if($.inArray(this.id.substr(4),data.ids)>=0){ $(this).remove(); } }else{ if(this.id.substr(4)==data.ids){ $(this).remove(); } } }); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'del'); } }); }, function(){ $.dialog.tips(lang.unnotice); }); } function order(url){ var win = $.dialog.top; var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); var data = $("#formlist").serialize(); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $("#content_list").html(data.remsg); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'order'); } }); } function grant(url){ var throughBox = $.dialog.through; var myDialog = throughBox({title:lang.grant,lock:true}); $.ajax({type: "POST",url:url,dataType: dataType, success: function (data) { if(data.status==200){ var win = $.dialog.top; myDialog.content(data.remsg); setSubBtn(win,myDialog,'grant',false); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'grant'); } }); } function debugging(tobj,url,XMLHttpRequest,textStatus,errorThrown,jsfunc){ var msg = '<table class="content_view"><tr><td width="110">Js Function:</td><td>function '+jsfunc+'(){}</td></tr>'; msg += '<tr><td width="110">URL:</td><td>'+url+'</td></tr>'; msg += '<tr><td>HTTP Status:</td><td>'+XMLHttpRequest.status+'</td></tr>'; msg += '<tr><td>readyStatus:</td><td>'+XMLHttpRequest.readyState+'</td></tr>'; msg += '<tr><td>textStatus:</td><td>'+textStatus+'</td></tr>'; msg += '<tr><td>errorThrown:</td><td>'+errorThrown+'</td></tr>'; msg += '<tr><td>help:</td><td>http://bbs.x6cms.com</td></tr>'; tobj.title('error'); tobj.content(msg); } function setEditer(win){ if(win.$(".editor").length>0){ var editors = new Array(); win.$(".editor").each(function(){ var idname = this.id; var editor=win.KindEditor.create('#'+idname,{ fileManagerJson:siteaurl+"/main/attrlist", uploadJson:siteaurl+"/main/attrupload" , allowFileManager:true }); editors.push(editor); }); return editors; }else{ return false; } } function setSubBtn(win,tobj,func,editors){ tobj.button({name:lang.submit, callback:function(){ if(win.$("#formview").validform('validall')){ if(editors){ var len = editors.length; for(var i=0;i<len;i++){ editors[i].sync(); } } subOK(win,tobj,func); }else{ } return false; }, focus: true }); } function subOK(win,tobj,type){ var data = win.$("#formview").serialize(); var url = win.$("#formview").find("#action").val()+'/'+type; var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ if(type=='add'){ $("#content_list").prepend(data.remsg); $('html,body').animate({scrollTop: 0}, 300); }else if(type=='edit'){ var thisline = $("#content_list").find("#tid_"+data.id); thisline.before(data.remsg); thisline.remove(); } myDialog.close(); tobj.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'subOK'); } }); } function backup(url){ var win = $.dialog.top; var data = $("#formlist").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'backup'); } }); } function optimize(url){ var win = $.dialog.top; var data = $("#formlist").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'optimize'); } }); } function upgrade(url){ if($("#formview").validform('validall')){ var win = $.dialog.top; var data = $("#formview").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'upgrade'); } }); } } function restore(url){ if($("#formview").validform('validall')){ var win = $.dialog.top; var data = $("#formview").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'restore'); } }); } } function generate(url){ if($("#formview").validform('validall')){ var win = $.dialog.top; var data = $("#formview").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'generate'); } }); } } function save(url){ if($("#formview").validform('validall')){ var win = $.dialog.top; var data = $("#formview").serialize(); var myDialog = win.$.dialog({fixed:true,lock:true,drag:false}); $.ajax({type: "POST",dataType:dataType,url: url,data: data, success: function(data){ if(data.status==200){ myDialog.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(myDialog,data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ debugging(myDialog,url,XMLHttpRequest,textStatus,errorThrown,'save'); } }); } } function shouquan(url){ $.dialog({title:lang.edit,lock:true, content:lang.loading, init:function(){ var thisobj = this; $.ajax({type: "POST",url: url,dataType:'json', success: function(data){ if(data.status==200){ thisobj.content(data.remsg); thisobj.button({ name:lang.submit, callback: function () { subOK(thisobj,'shouquan'); return false; }, focus: true }); }else{ thisobj.close(); showmsg(data); } } }); } }); } function audit(url,ismultiple,tid){ var data; $.dialog.confirm(lang.auditnotice, function(){ if(ismultiple){ data = $("#formlist").find("input:checked").serialize(); }else{ data = "optid="+tid; } if(data==""){ $.dialog.tips(lang.pselect); return; } $.dialog({title:lang.audit,lock:true, content:lang.loading, init:function(){ var thisobj = this; $.ajax({ type: "POST", url: url, dataType: dataType, data: data, success: function(data){ if(data.status==200){ thisobj.close(); $("#content_list").children().each(function(){ if(this.id.substr(4)==data.id){ $(this).before(data.remsg); $(this).remove(); } }); $.dialog.tips(lang.opersuccess); }else{ thisobj.close(); showmsg(data); } } }); } }); }, function(){ $.dialog.tips(lang.unnotice); }); } function editfile(url,page){ var win = $.dialog.top; win.$.dialog({title:lang.edit,lock:true, content:lang.loading, init:function(){ var thisobj = this; $.ajax({ type: "POST", url: url, data:"actiontype=0&page="+page, dataType: dataType, success: function(data){ if(data.status==200){ thisobj.content(data.remsg); thisobj.button({ name:lang.submit, callback: function () { subOK(win,thisobj,'editfile'); return false; }, focus: true }); }else{ thisobj.close(); showmsg(data); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ alert(errorThrown); } }); } }); } function unsetThumb(objid,imgobjid){ var win = $.dialog.top; win.$("#"+objid).val(''); win.$("#"+imgobjid).attr('src',win.baseurl+'data/nopic8080.gif'); } /* * status * 200 正常 * 201:(登录失效) * 202:(无权限) * 203:(请选择记录) * 204:(用户名或密码错误) * 205:(提交成功,需刷新本页面) * 206:(记录重复) * 207:(提交成功,但是验证失败,弹出错误消息) * 301:提交成功,需要跳转页面 * 404:该页不存在; */ function showmsg(tobj,data){ if(isdebugging){ alert(data);return; } if(data.status==201){ tobj.close(); showajaxlogin(); }else if(data.status==202){ tobj.close(); $.dialog.tips(lang.nopurivew); }else if(data.status==203){ tobj.close(); $.dialog.tips(lang.pselect); }else if(data.status==204){ tobj.close(); $.dialog.tips(lang.userorpasserror); }else if(data.status==205){ tobj.close(); location.reload(); }else if(data.status==206){ tobj.close(); $.dialog.tips(lang.duplicate); }else if(data.status==207){ tobj.close(); $.dialog.tips(data.remsg); }else if(data.status==301){ tobj.close(); location.href=data.reurl; }else if(data.status==404){ tobj.close(); $.dialog.tips(lang.notfound); }else{ tobj.close(); $.dialog.tips(data.remsg); } } function showajaxlogin(){ $.dialog({title:lang.login,lock:true, content:lang.loading, init:function(){ var thisobj = this; $.ajax({ type: "GET", url: siteaurl+'/login/ajaxlogin', dataType: dataType, cache:false, success: function(data){ if(data.status==200){ thisobj.content(data.remsg); thisobj.button({ name:lang.login, callback: function () { var postdata = $("#ajaxlogin").serialize(); $.ajax({ type: "POST", url: siteaurl+'/main/ajaxlogin', dataType: dataType, data:postdata, cache:false, success:function(data){ if(data.status==200){ thisobj.close(); $.dialog.tips(lang.opersuccess); }else{ showmsg(data); } } }); return false; }, focus: true }); }else{ thisobj.close(); showmsg(data); } } }); } }); } function uploadpic(t,picid){ var editor = KindEditor.editor({ fileManagerJson:siteaurl+"/main/attrlist", uploadJson:siteaurl+"/main/attrupload", allowFileManager : true }); editor.loadPlugin('image', function() { editor.plugin.imageDialog({ imageUrl : KindEditor('#'+picid).val(), clickFn : function(url, title, width, height, border, align) { newurl = url.substr(url.indexOf("data")); $('#'+picid).val(newurl); if(t){ $(t).attr('src',url); } editor.hideDialog(); } }); }); } function uploadfile(fileid,filename){ var editor = KindEditor.editor({ fileManagerJson:siteaurl+"/main/attrlist", uploadJson:siteaurl+"/main/attrupload", allowFileManager : true }); editor.loadPlugin('insertfile', function() { editor.plugin.fileDialog({ fileUrl : KindEditor('#'+fileid).val(), clickFn : function(url,title) { if($.trim(title)==url){ title=''; } newurl = url.substr(url.indexOf("data")); $('#'+fileid).val(newurl); if(filename!=''){ $('#'+filename).val(title); } editor.hideDialog(); } }); }); } function colorpicker(t,colorid,textid){ var colorarr = new Array("#000000","#000000","#000000","#000000","#003300","#006600","#009900","#00cc00","#00ff00","#330000","#333300","#336600","#339900","#33cc00","#33ff00","#660000","#663300","#666600","#669900","#66cc00","#66ff00","#000000","#333333","#000000","#000033","#003333","#006633","#009933","#00cc33","#00ff33","#330033","#333333","#336633","#339933","#33cc33","#33ff33","#660033","#663333","#666633","#669933","#66cc33","#66ff33","#000000","#666666","#000000","#000066","#003366","#006666","#009966","#00cc66","#00ff66","#330066","#333366","#336666","#339966","#33cc66","#33ff66","#660066","#663366","#666666","#669966","#66cc66","#66ff66","#000000","#999999","#000000","#000099","#003399","#006699","#009999","#00cc99","#00ff99","#330099","#333399","#336699","#339999","#33cc99","#33ff99","#660099","#663399","#666699","#669999","#66cc99","#66ff99","#000000","#cccccc","#000000","#0000cc","#0033cc","#0066cc","#0099cc","#00cccc","#00ffcc","#3300cc","#3333cc","#3366cc","#3399cc","#33cccc","#33ffcc","#6600cc","#6633cc","#6666cc","#6699cc","#66cccc","#66ffcc","#000000","#ffffff","#000000","#0000ff","#0033ff","#0066ff","#0099ff","#00ccff","#00ffff","#3300ff","#3333ff","#3366ff","#3399ff","#33ccff","#33ffff","#6600ff","#6633ff","#6666ff","#6699ff","#66ccff","#66ffff","#000000","#ff0000","#000000","#990000","#993300","#996600","#999900","#99cc00","#99ff00","#cc0000","#cc3300","#cc6600","#cc9900","#cccc00","#ccff00","#ff0000","#ff3300","#ff6600","#ff9900","#ffcc00","#ffff00","#000000","#00ff00","#000000","#990033","#993333","#996633","#999933","#99cc33","#99ff33","#cc0033","#cc3333","#cc6633","#cc9933","#cccc33","#ccff33","#ff0033","#ff3333","#ff6633","#ff9933","#ffcc33","#ffff33","#000000","#0000ff","#000000","#990066","#993366","#996666","#999966","#99cc66","#99ff66","#cc0066","#cc3366","#cc6666","#cc9966","#cccc66","#ccff66","#ff0066","#ff3366","#ff6666","#ff9966","#ffcc66","#ffff66","#000000","#ffff00","#000000","#990099","#993399","#996699","#999999","#99cc99","#99ff99","#cc0099","#cc3399","#cc6699","#cc9999","#cccc99","#ccff99","#ff0099","#ff3399","#ff6699","#ff9999","#ffcc99","#ffff99","#000000","#00ffff","#000000","#9900cc","#9933cc","#9966cc","#9999cc","#99cccc","#99ffcc","#cc00cc","#cc33cc","#cc66cc","#cc99cc","#cccccc","#ccffcc","#ff00cc","#ff33cc","#ff66cc","#ff99cc","#ffcccc","#ffffcc","#000000","#ff00ff","#000000","#9900ff","#9933ff","#9966ff","#9999ff","#99ccff","#99ffff","#cc00ff","#cc33ff","#cc66ff","#cc99ff","#ccccff","#ccffff","#ff00ff","#ff33ff","#ff66ff","#ff99ff","#ffccff","#ffffff"); var len = colorarr.length; var colorstr = '<table class="colorpicker" border="0"><tr><td colspan="21" height="22" class="currentColor"></td></tr><tr>'; for(var i=0;i<len;i++){ if(i==21||i==42||i==63||i==84||i==105||i==126||i==147||i==168||i==189||i==210||i==231){ colorstr+="</tr><tr>" } colorstr+='<td style="background-color: '+colorarr[i]+';" width="11" height="11" rel="'+colorarr[i]+'" onMouseOver="colorover(this)" onclick="colorclick(this,\''+colorid+'\',\''+textid+'\')"></td>'; } colorstr +='</tr></table>' $.dialog({id:'colorpicker',follow:t,title:lang.colorpicker,drag: false,resize: false,padding:'0 0',lock: true,opacity: 0,content: colorstr,button: [{name:lang.clearcolor,callback: function () {$("#"+colorid).val('');$("#"+textid).css('color','');}}]}); } function colorover(t){ var color=$(t).attr('rel'); $(t).parent().parent().find(".currentColor").css('background-color',color); } function colorclick(t,colorid,textid){ var color=$(t).attr('rel'); $(t).parent().parent().find(".currentColor").css('background-color',color); $("#"+colorid).val(color); if(textid){ $("#"+textid).css('color',color); } $.dialog({id:'colorpicker'}).close(); } function enterdir(folder){ if(folder==''){ var folder = $("#folder").val(); var s = folder.lastIndexOf("/"); var folder = folder.substr(0,s); } $("#folder").val(folder); $("#formlist").submit(); } (function($) { $.fn.validform = function(type){ var options = new Array(); var methods = { init:function(){ var validfields = form.find(".validate").each(function(){ options.push(this); $(this).bind('blur',function(){ methods.testing(this); }); }); }, back:function(form){ var isvalidok = true; var firstobj; form.find(".validate").each(function(){ if(!methods.testing(this)){ if(isvalidok){ firstobj = this; } isvalidok = false; } }); if(!isvalidok){ $('html,body').animate({scrollTop: $(firstobj).prev().offset().top}, 300); $(firstobj).focus(); } return isvalidok; }, testing:function(obj){ var rules = $(obj).attr('validtip'); var val = $(obj).val(); var rulearr = rules.split(","); var len = rulearr.length; var msg = ''; var isrequire = rules.indexOf("required")>=0?true:false; for(var i=0;i<len;i++){ var rule = rulearr[i].split(":"); switch(rule[0]){ case "required": msg+=methods.required(obj,val); break; case "minsize": msg+=methods.minsize(val,rule[1],isrequire); break; case "maxsize": msg+=methods.maxsize(val,rule[1],isrequire); break; case "email": msg+=methods.email(val,isrequire); break; case "equals": msg+=methods.equals(val,rule[1]); default: break; } } if($(obj).prev().hasClass("parentFormformID")){ $(obj).prev().remove(); } if(msg!=''){ methods.showmsg(obj,msg); return false; }else{ return true; } }, required:function(obj,val){ if(val==''){ if($(obj).is("input")){ return lang.validform.required.text+"<br>"; }else if($(obj).is("select")){ return lang.validform.required.select+"<br>"; }else{ return lang.validform.required.text+"<br>"; } } return ''; }, minsize:function(val,dlen,isrequire){ if(val==""&&!isrequire){ return ''; } var len = val.length; if(len<dlen){ return lang.validform.min.text+dlen+lang.validform.min.text1+"<br>"; } return ''; }, maxsize:function(val,dlen,isrequire){ if(val==""&&!isrequire){ return ''; } var len = val.length; if(len>dlen){ return lang.validform.max.text+dlen+lang.validform.max.text1+"<br>"; } return ''; }, email:function(val,isrequire){ if(val==""&&!isrequire){ return ''; } var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i; if(!regex.test(val)){ return lang.validform.email.text+"<br>"; } return ''; }, equals:function(val,equalsid){ if(val!=$("#"+equalsid).val()){ return lang.validform.equals.text+"<br>"; } return ''; }, showmsg:function(obj,msg){ var msgcontent = '<div class="reqformError parentFormformID formError"><div class="formErrorContent">'+msg+'<br /></div><div class="formErrorArrow"><div class="line10"></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div> <div class="line2"><!-- --></div><div class="line1"><!-- --></div></div></div>'; $(obj).before(msgcontent); var objprev = $(obj).prev(); objprev.css('margin-top','-'+objprev.height()+'px'); objprev.css('margin-left',($(obj).width()-20)+'px'); objprev.bind('click',function(){ $(this).remove(); }); } }; if(!this.is("form")){ alert(validform.onlyform); return false; } form = this; if(type=='validall'){ return methods.back(form); }else{ methods.init(form); } }; })(jQuery);
JavaScript
$(document).ready(function(){ $(".keful").mouseover(function(){ $(".keful").hide(); $(".kefur").show(); }); $(".kefucolose").click(function(){ $(".kefur").hide(); $(".keful").show(); }); }); function subGuestBook(url){ if($("#guestbook").validform('validall')){ $("#guestbook").attr('action',url); $("#guestbook").submit(); }else{ return false; } } /*validform*/ (function($) { $.fn.validform = function(type){ var options = new Array(); var methods = { init:function(){ var validfields = form.find(".validate").each(function(){ options.push(this); $(this).bind('blur',function(){ methods.testing(this); }); }); }, back:function(form){ var isvalidok = true; var firstobj; form.find(".validate").each(function(){ if(!methods.testing(this)){ if(isvalidok){ firstobj = this; } isvalidok = false; } }); if(!isvalidok){ $('html,body').animate({scrollTop: $(firstobj).prev().offset().top}, 300); $(firstobj).focus(); } return isvalidok; }, testing:function(obj){ var rules = $(obj).attr('validtip'); var val = $(obj).val(); var rulearr = rules.split(","); var len = rulearr.length; var msg = ''; var isrequire = rules.indexOf("required")>=0?true:false; for(var i=0;i<len;i++){ var rule = rulearr[i].split(":"); switch(rule[0]){ case "required": msg+=methods.required(obj,val); break; case "minsize": msg+=methods.minsize(val,rule[1],isrequire); break; case "maxsize": msg+=methods.maxsize(val,rule[1],isrequire); break; case "email": msg+=methods.email(val,isrequire); break; case "equals": msg+=methods.equals(val,rule[1]); default: break; } } if($(obj).prev().hasClass("parentFormformID")){ $(obj).prev().remove(); } if(msg!=''){ methods.showmsg(obj,msg); return false; }else{ return true; } }, required:function(obj,val){ if(val==''){ if($(obj).is("input")){ return lang.validform.required.text+"<br>"; }else if($(obj).is("select")){ return lang.validform.required.select+"<br>"; }else{ return lang.validform.required.text+"<br>"; } } return ''; }, minsize:function(val,dlen,isrequire){ if(val==""&&!isrequire){ return ''; } var len = val.length; if(len<dlen){ return lang.validform.min.text+dlen+lang.validform.min.text1+"<br>"; } return ''; }, maxsize:function(val,dlen,isrequire){ if(val==""&&!isrequire){ return ''; } var len = val.length; if(len>dlen){ return lang.validform.max.text+dlen+lang.validform.max.text1+"<br>"; } return ''; }, email:function(val,isrequire){ if(val==""&&!isrequire){ return ''; } var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i; if(!regex.test(val)){ return lang.validform.email.text+"<br>"; } return ''; }, equals:function(val,equalsid){ if(val!=$("#"+equalsid).val()){ return lang.validform.equals.text+"<br>"; } return ''; }, showmsg:function(obj,msg){ var msgcontent = '<div class="reqformError parentFormformID formError"><div class="formErrorContent">'+msg+'<br /></div><div class="formErrorArrow"><div class="line10"></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div> <div class="line2"><!-- --></div><div class="line1"><!-- --></div></div></div>'; $(obj).before(msgcontent); var objprev = $(obj).prev(); objprev.css('margin-top','-'+objprev.height()+'px'); objprev.css('margin-left',($(obj).width()-20)+'px'); objprev.bind('click',function(){ $(this).remove(); }); } }; if(!this.is("form")){ alert(validform.onlyform); return false; } form = this; if(type=='validall'){ return methods.back(form); }else{ methods.init(form); } }; })(jQuery); stuHover = function() { var cssRule; var newSelector; for (var i = 0; i < document.styleSheets.length; i++) for (var x = 0; x < document.styleSheets[i].rules.length ; x++) { cssRule = document.styleSheets[i].rules[x]; if (cssRule.selectorText.indexOf("LI:hover") != -1) { newSelector = cssRule.selectorText.replace(/LI:hover/gi, "LI.iehover"); document.styleSheets[i].addRule(newSelector , cssRule.style.cssText); } } var getElm = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<getElm.length; i++) { getElm[i].onmouseover=function() { this.className+=" iehover"; } getElm[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" iehover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", stuHover);
JavaScript
/* * FeatureList - simple and easy creation of an interactive "Featured Items" widget * Examples and documentation at: http://jqueryglobe.com/article/feature_list/ * Version: 1.0.0 (01/09/2009) * Copyright (c) 2009 jQueryGlobe * Licensed under the MIT License: http://en.wikipedia.org/wiki/MIT_License * Requires: jQuery v1.3+ */ ;(function($) { $.fn.featureList = function(options) { var tabs = $(this); var output = $(options.output); new jQuery.featureList(tabs, output, options); return this; }; $.featureList = function(tabs, output, options) { function slide(nr) { if (typeof nr == "undefined") { nr = visible_item + 1; nr = nr >= total_items ? 0 : nr; } tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current'); output.stop(true, true).filter(":visible").fadeOut(); output.filter(":eq(" + nr + ")").fadeIn(function() { visible_item = nr; }); } var options = options || {}; var total_items = tabs.length; var visible_item = options.start_item || 0; options.pause_on_hover = options.pause_on_hover || true; options.transition_interval = options.transition_interval || 5000; output.hide().eq( visible_item ).show(); tabs.eq( visible_item ).addClass('current'); tabs.click(function() { if ($(this).hasClass('current')) { return false; } slide( tabs.index( this) ); }); if (options.transition_interval > 0) { var timer = setInterval(function () { slide(); }, options.transition_interval); if (options.pause_on_hover) { tabs.mouseenter(function() { clearInterval( timer ); }).mouseleave(function() { clearInterval( timer ); timer = setInterval(function () { slide(); }, options.transition_interval); }); } } }; })(jQuery);
JavaScript
function emptyValidate(form){ var list_1=form.getElementsByTagName('input'); for(var i=0;i< list_1.length;i++){ if(list_1[i].getAttribute('type')=="text"|| list_1[i].getAttribute('type')=="password"){ if(list_1[i].getAttribute('class')=="require"){ var result = inputEmptyValidate(list_1[i]); if(!result){ return false; } } } } var list_2=form.getElementsByTagName('textarea'); for(var i=0;i< list_2.length;i++){ if(list_1[i].getAttribute('class')=="require"){ var result = inputEmptyValidate(list_2[i]); if(!result){ return false; } } } return true; } //定义一个简单通用的非空验证 function inputEmptyValidate(element){ var child=element.parentElement.childNodes; if(element.value==""){ element.focus(); //先检查是否存在错误信息 for(var j=0;j<child.length;j++){ if(child[j].tagName=="SPAN"){ element.parentElement.removeChild(child[j]); } } var text=document.createElement("span"); text.innerHTML="Field is required"; element.parentElement.appendChild(text); return false; }else{ for(var j=0;j<child.length;j++){ if(child[j].tagName=="SPAN"){ element.parentElement.removeChild(child[j]); } } } return true; }
JavaScript
// JavaScript Document function onMap(){ //经纬度,全局变量 var latLng; $('body').append('<div id="dialog"></div>'); $('#dialog').append('<div class="item gradient ui-corner-all"><div id="map_canvas">map can not show!</div></div>'); openDialog(); $('#map_canvas').gmap( { 'center' : getSourceLatLng(), //初始位置为中心 'zoom': 7, //回调函数1 'callback': function(map){ //响应点击 $(map).click( function(event) { latLng = event.latLng; //清除所有标记 $('#map_canvas').gmap('clearMarkers'); //添加一个标记 $('#map_canvas').gmap('addMarker', { 'position': latLng, 'title': '', 'draggable': true }, //回调函数2 function(map, marker) { //保存地址 findLocation(marker.getPosition(), marker); } ) //标记响应拖拉结束事件 .dragend( function(event) { getLatLng(event.latLng); var self = this; //保存地址 findLocation(event.latLng, this); }) //标记响应点击事件 .click(function(event) { var temp = $(this).get(0).getPosition(); getLatLng(temp); findLocation(temp, this); }); getLatLng(latLng); }); $('#map_canvas').gmap('option', 'zoom', 7); } }); } //查找地址 function findLocation(location, marker) { $('#map_canvas').gmap('search', {'location': location}, function(found, results) { if ( found ) { $('#address').val(results[0].formatted_address); } else {alert("not find!");} }); } //弹出对话框 function openDialog() { $('#dialog').dialog({ 'modal':true, 'title': 'Edit and save point', 'width': 800, 'height': 450, 'buttons': { "关闭": function() { $(this).empty(); $(this).dialog( "close" ); } } }); } //获取事件对应的经纬度,保存到经度、纬度输入框 function getLatLng(latLng) { $('#latitude').val(latLng.lat()); $('#longitude').val(latLng.lng()); } //获取初始位置 function getSourceLatLng() { if (google.loader.ClientLocation != null) { return new google.maps.LatLng( google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude); } return new google.maps.LatLng(23.049489158954536, 113.4016574920654); }
JavaScript
function loadImage(sender){ var objPreview = document.getElementById( 'preview' ).cloneNode(false); var objPreviewFake = document.getElementById( 'preview_fake' ).cloneNode(false); objPreviewFake.appendChild(objPreview); var list=sender.parentNode.getElementsByTagName('div'); sender.parentNode.removeChild(list[0]); sender.parentNode.appendChild(objPreviewFake); if(window.navigator.userAgent.indexOf("Firefox")>=1){ try{ //Firefox9以前 objPreview.src = sender.files[0].getAsDataURL(); }catch(e){ //Firefox9以后 objPreview.src = window.URL.createObjectURL(sender.files[0]); } }else if(window.navigator.userAgent.indexOf("MSIE")>=1 ){ // IE7,IE8 在设置本地图片地址为 img.src 相同环境有时能显示,有时不显示,因此只能用滤镜来解决 sender.select(); var imgSrc = document.selection.createRange().text; objPreviewFake.filters.item( 'DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc; autoSizePreview( objPreviewFake ); objPreview.style.display = 'none'; } } function onPreviewLoad(sender){ autoSizePreview( sender); } function autoSizePreview( objPre){ objPre.style.width = 100 + 'px'; objPre.style.height = 100 + 'px'; }
JavaScript
/* * * jQuery Timer plugin v0.1 * Matt Schmidt [http://www.mattptr.net] * * Licensed under the BSD License: * http://mattptr.net/license/license.txt * */ jQuery.timer = function (interval, callback) { /** * * timer() provides a cleaner way to handle intervals * * @usage * $.timer(interval, callback); * * * @example * $.timer(1000, function (timer) { * alert("hello"); * timer.stop(); * }); * @desc Show an alert box after 1 second and stop * * @example * var second = false; * $.timer(1000, function (timer) { * if (!second) { * alert('First time!'); * second = true; * timer.reset(3000); * } * else { * alert('Second time'); * timer.stop(); * } * }); * @desc Show an alert box after 1 second and show another after 3 seconds * * */ var interval = interval || 100; if (!callback) return false; _timer = function (interval, callback) { this.stop = function () { clearInterval(self.id); }; this.internalCallback = function () { callback(self); }; this.reset = function (val) { if (self.id) clearInterval(self.id); var val = val || 100; this.id = setInterval(this.internalCallback, val); }; this.interval = interval; this.id = setInterval(this.internalCallback, this.interval); var self = this; }; return new _timer(interval, callback); };
JavaScript
(function(){ window.shSetup = window.shSetup || {}; shSetup.userCSS = shSetup.userCSS || ""; shSetup.libs = shSetup.libs || ['shBrushGroovy.js', 'shBrushXml.js','shBrushJScript.js', 'shBrushBash.js', 'shBrushDiff.js', 'shBrushPython.js', 'shBrushSql.js', 'shBrushCpp.js', 'shBrushCss.js', 'shBrushJava.js', 'shBrushPhp.js', 'shBrushCSharp.js', 'shBrushPerl.js', 'shBrushRuby.js', 'shBrushPowerShell.js', 'shBrushVb.js', 'shBrushPlain.js', 'shBrushVb.js', 'shBrushJavaFX.js','shBrushAS3.js']; shSetup.path = shSetup.path || "http://alexgorbatchev.com/pub/sh/current/"; shSetup.br = shSetup.br === false ? false :true; shSetup.jQuery = (window.jQuery) ? true : false; var xLink = function(url) { document.write('<link href="'+url+'" rel="stylesheet" type="text/css" />'); } var xScript = function(url) { document.write('<script src="'+url+'" type="text/javascript"></'+'script>'); } xLink(shSetup.path + "styles/shCore.css"); if (shSetup.userCSS) xLink(shSetup.userCSS); else xLink(shSetup.path + "styles/shThemeDefault.css"); if (!shSetup.jQuery) xScript("http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"); var path = shSetup.path + "scripts/"; var files = shSetup.libs; files.unshift("shCore.js"); for (var i=0; i < files.length ; i++) { xScript(path+files[i]); } xScript("http://tsyntax.googlecode.com/hg/dev/hooker.js"); })();
JavaScript
(function(){ if (!shSetup.jQuery) jQuery.noConflict(); jQuery(document).ready(function(){ jQuery("blockquote").each( function() { var temp = jQuery(this).html(); var starter = "###"; if (starter.substring(0, starter.length) == starter) { temp = temp.replace(/\n/gi, ""); temp = temp.replace(/<BR>/gi, "\n"); temp = temp.replace(/<BR \/>/gi, "\n"); temp = temp.split("\n"); var fl = temp[0].replace(starter,"brush: "); temp.shift(); temp = temp.join("\n"); temp = '<pre class="'+ fl + '">'+temp+'</pre>' jQuery(this).replaceWith(temp); } }); SyntaxHighlighter.all(); }); })();
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * * Patched Version by Jamie Thompson - Fixes IE7 Positioning Issues * http://jamazon.co.uk/web/2008/03/17/thickbox-31-ie7-positioning-bug/ */ var tb_pathToImage = "images/loadingAnimation.gif"; /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ // fixes the fact that ie7 now reports itself as MSIE 6.0 compatible $.browser.msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent); //on page load call tb_init $(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ $(domChunk).click(function(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; }).removeClass('thickbox'); } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try{ $('#reader').css('visibility','hidden'); }catch(e){ } try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 $("body","html").css({height: "100%", width: "100%"}); $("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page $('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = $("a[@rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; $("#TB_window").append("<img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>关闭</a>或按ESC键关闭</div>"); $("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);} $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } $("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } $("#TB_next").click(goNext); } document.onkeydown = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } else if(keycode == 190){ // display previous image if(!(TB_NextHTML == "")){ document.onkeydown = ""; goNext(); } } else if(keycode == 188){ // display next image if(!(TB_PrevHTML == "")){ document.onkeydown = ""; goPrev(); } } }; tb_position(); $("#TB_load").remove(); $("#TB_Image").click(tb_remove); $("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); $("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='关闭'><b>关闭</b></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>"); }else{//iframe modal $("#TB_overlay").unbind(); $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>"); } }else{// not an iframe, ajax if($("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal $("#TB_overlay").unbind(); $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; $("#TB_ajaxContent")[0].scrollTop = 0; $("#TB_ajaxWindowTitle").html(caption); } } $("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ $("#TB_ajaxContent").append($('#' + params['inlineId']).children()); $("#TB_window").unload(function () { $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); $("#TB_load").remove(); $("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if($.browser.safari){//safari needs help because it will not fire iframe onload $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } }else{ $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); $("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); $("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ document.onkeyup = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } }; } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } function tb_remove() { $("#TB_imageOff").unbind("click"); $("#TB_closeWindowButton").unbind("click"); $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); $("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 $("body","html").css({height: "auto", width: "auto"}); $("html").css("overflow",""); } document.onkeydown = ""; document.onkeyup = ""; try{ $('#reader').css('visibility','visible'); }catch(e){ } return false; } function tb_position() { $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( !(jQuery.browser.msie6)) { // take away IE6 $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
 if(window.addEventListener) window.addEventListener('DOMMouseScroll', handleWheel, false); window.onmousewheel = document.onmousewheel = handleWheel; if (window.attachEvent) window.attachEvent("onmousewheel", handleWheel); function handleWheel(event){ try{ if(!window.document.reader.hasFocus()){return true;} window.document.reader.setViewerFocus(true); window.document.reader.focus(); if(navigator.appName == "Netscape"){ if (event.detail) delta = 0; if (event.preventDefault){ event.preventDefault(); event.returnValue = false; } } return false; }catch(err){return true;} } $(document).ready(function(){ $('#summary-hide').click(function(){ $('#summary-content').show(); $('#summary-fullcontent').hide(); return false; }); $('#summary-show').click(function(){ $('#summary-content').hide(); $('#summary-fullcontent').fadeIn("slow"); return false; }); $('#rate').mouseout(function(){ setRate(wgDocScoreByUser); }); $('#rate span').mouseover(function(){ var nScore = $(this).attr('id').substring(4); setRate(nScore); }).click(function(){ var nScore = $(this).attr('id').substring(4); rateDoc(nScore); }); getDocFavoriteByUser(); $('#favorite-box').dialog({ autoOpen:false, title:'收藏提示', modal:true, resizable:false, buttons:{ '取消':function(){ $('#favorite-box').dialog('close'); }, '确认':function(){ //favorite; if(favoriteDocument()){ $('#favorite-box').dialog('close'); } } }, close:function(){ $('#reader').css('visibility','visible'); //$('#reader').css('margin-top','0'); //fix for firefox } }); $('#upload').click(function(){ if (wgUserLogined){ window.location.href=rooturl+'/submit'; }else{ gologin('upload'); } }); $('#favorite').click(function(){ if (!wgUserLogined){ gologin('favorite'); return false; } loadUserFolders(); $('#fav_folderlist').change(function(){ if ($(this).val() == "-1" ){ $('#newfolder-input').css('display',''); }else{ $('#newfolder-input').css('display','none'); } return false; }); $('#reader').css('visibility','hidden'); $('#favorite-box').dialog('open'); return false; }); getDocScoreByUser(); //download $('#download-confirm').dialog({ autoOpen:false, modal:true, resizable:false, title:'下载提示', buttons:{ '取消':function(){ $('#download-confirm').dialog('close'); }, '确认':function(){ //download; downloadSubmit(); $('#download-confirm').dialog('close'); } }, close:function(){ $('#reader').css('visibility','visible'); } }); $('#download').click(function(){ if(wgUserLogined){ $('#reader').css('visibility','hidden'); $('#download-confirm').dialog('open'); }else{ gologin('download'); } return false; }); if(viewflash){//有些文档不能在线查看 var swfVersionStr = "10.0.0"; var xiSwfUrlStr = rooturl+"/flash/expressInstall.swf"; var flashvars = { RootPath:rooturl, Doc:wgDocKey, fpath:fpath }; var params = { } params.quality = "high"; params.bgcolor = "#ffffff"; params.allowscriptaccess = "sameDomain"; params.allowfullscreen = "true"; var attributes = {}; attributes.id = "reader"; attributes.name = "reader"; swfobject.embedSWF(rooturl+"/flash/OpenViewer.swf", "readercontainer","780", "700",swfVersionStr, xiSwfUrlStr,flashvars, params, attributes); swfobject.createCSS("#readercontainer", "display:block;text-align:left;"); } }); function gologin(download){ $('#reader').css('visibility','hidden'); tb_show('登录OPEN文档',rooturl+'/members/login?forward='+download+'&TB_iframe=true&height=177&width=278'); } function rateDoc(nScore){ $.ajax({ url :rooturl+"/view/filerate/"+wgDocKey, type :"GET", dataType:"json", data :"score="+nScore, success : function(data){ if (data.status=='success'){ wgDocScoreByUser = nScore; setRate(wgDocScoreByUser); }else if (data.status=='nologin'){ gologin("rating"); }else if (data.status=='false'){ alert(data.message); } } }); } function getDocScoreByUser(){ if (wgDocScoreByUser!=null && wgDocScoreByUser!=0){ setRate(wgDocScoreByUser); } } function getDocFavoriteByUser(){ if (wgDocFavoriteByUser==false){ $.ajax({ type:'GET', url: rooturl+'/view/getfilefavorite', data:"id="+wgDocKey, dataType:"json", success :function(data) { if (data.status == 'favorited'){ wgDocFavoriteByUser=data.folder; setFavorite(wgDocFavoriteByUser); } return false; } }); }else{ setFavorite(wgDocFavoriteByUser); } } function loadUserFolders(){ if (wgUserFolders==null){ //read folders; $.ajax({ type:'POST', url: rooturl+'/view/getfolders', dataType:"json", success :function(data) { wgUserFolders=data; if (data.length>0){ $('#newfolder-sp').before('<option value="" disabled=disabled>-------------</option>'); for(i=0;i<data.length;i++){ f=data[i]; $('<option value="'+f.id+'">'+f.name+'('+f.fnum+')</option>').insertBefore('#newfolder-sp'); } } return false; } }); } } function favoriteDocument(){ var fid = $('#fav_folderlist').val(); var ftags = $('#fav_tags').val(); var newfolder = $('#fav_newfolder').val(); if(fid==0 && newfolder==''){ alert('请选择或新增一个收藏夹!'); return false; } $.ajax({ type:'POST', url: rooturl+'/user/filefavorite', dataType:"json", data:"id="+wgDocKey+"&folder="+fid+"&newfolder="+newfolder+"&tags="+ftags, success :function(data) { if (data.status = 'success'){ wgDocFavoriteByUser=data.folder; setFavorite(data.folder); }else{ alert(data.message); } $('#favorite-box').hide(); return true; } }); return true; } function opendownDialog(){ $('#reader').css('visibility','hidden'); $('#download-confirm').dialog('open'); } function openfavDialog(){ $('#reader').css('visibility','hidden'); loadUserFolders(); $('#fav_folderlist').change(function(){ if ($(this).val() == "-1" ){ $('#newfolder-input').css('display',''); }else{ $('#newfolder-input').css('display','none'); } return false; }); $('#favorite-box').dialog('open'); return false; } function downloadSubmit(){ if (wgDownFrame==null){ wgDownFrame = '<iframe frameborder=0 width=0 height=0 src="about:blank" name="downframe"></iframe>'; $('#download-confirm').append(wgDownFrame); } $('#downloadform').attr('target','downframe'); $('#downloadform').submit(); } function setRate(nScore){ var i; for(i=1;i<=5;i++){ $('#star'+i).attr('class',(i <= nScore ? 'star-big-on':'star-big-off')); } var tip = $('#star'+nScore).attr('title'); $('#rate-tip').html(tip); } function setFavorite(folder){ var tip = '已收藏到'; if (folder != null){ tip += '<a target=_blank href="'+rooturl+'/user/myfavorite/'+folder.id+'">'+folder.name+'</a>'; }else{ tip += '<a target=_blank href="'+rooturl+'/user/myfavorite/0">我的收藏夹</a>'; } tip += '!'; $('#favorite-container').html(tip); }
JavaScript
/* begin Page */ /* */ (function() { // fix ie blinking var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand; try { if (!!m) { m('BackgroundImageCache', false, true); } } catch (oh) { }; // css helper var u = navigator.userAgent.toLowerCase(); var is = function(t) { return (u.indexOf(t) != -1) }; jQuery('html').addClass([(!(/opera|webtv/i.test(u)) && /msie (\d)/.test(u)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? 'gecko firefox2' : is('firefox/3') ? 'gecko firefox3' : is('gecko/') ? 'gecko' : is('chrome/') ? 'chrome' : is('opera/9') ? 'opera opera9' : /opera (\d)/.test(u) ? 'opera opera' + RegExp.$1 : is('konqueror') ? 'konqueror' : is('applewebkit/') ? 'webkit safari' : is('mozilla/') ? 'gecko' : '', (is('x11') || is('linux')) ? ' linux' : is('mac') ? ' mac' : is('win') ? ' win' : '' ].join(' ')); })(); var _artStyleUrlCached = null; function artGetStyleUrl() { if (null == _artStyleUrlCached) { var ns; _artStyleUrlCached = ''; ns = jQuery('link'); for (var i = 0; i < ns.length; i++) { var l = ns[i].href; if (l && /style\.ie6\.css(\?.*)?$/.test(l)) return _artStyleUrlCached = l.replace(/style\.ie6\.css(\?.*)?$/, ''); } ns = jQuery('style'); for (var i = 0; i < ns.length; i++) { var matches = new RegExp('import\\s+"([^"]+\\/)style\\.ie6\\.css"').exec(ns[i].html()); if (null != matches && matches.length > 0) return _artStyleUrlCached = matches[1]; } } return _artStyleUrlCached; } function artFixPNG(element) { if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) { var src; if (element.tagName == 'IMG') { if (/\.png$/.test(element.src)) { src = element.src; element.src = artGetStyleUrl() + 'images/spacer.gif'; } } else { src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i); if (src) { src = src[1]; element.runtimeStyle.backgroundImage = 'none'; } } if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "')"; } } jQuery(function() { jQuery.each(jQuery('ul.henismenu>li:not(.henismenu-li-separator),ul.henisvmenu>li:not(.henisvmenu-separator)'), function (i, val) { var l = jQuery(val); var s = l.children('span'); if (s.length == 0) return; var t = l.find('span.t').last(); l.children('a').append(t.html(t.text())); s.remove(); }); });/* end Page */ /* begin Menu */ jQuery(function() { jQuery.each(jQuery('ul.henismenu>li:not(:last-child)'), function(i, val) { jQuery('<li class="henismenu-li-separator"><span class="henismenu-separator"> </span></li>').insertAfter(val); }); if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 6) return; jQuery.each(jQuery('ul.henismenu li'), function(i, val) { val.j = jQuery(val); val.UL = val.j.children('ul:first'); if (val.UL.length == 0) return; val.A = val.j.children('a:first'); this.onmouseenter = function() { this.j.addClass('henismenuhover'); this.UL.addClass('henismenuhoverUL'); this.A.addClass('henismenuhoverA'); }; this.onmouseleave = function() { this.j.removeClass('henismenuhover'); this.UL.removeClass('henismenuhoverUL'); this.A.removeClass('henismenuhoverA'); }; }); }); /* end Menu */ /* begin Flash */ jQuery(function () { swfobject.switchOffAutoHideShow(); swfobject.registerObject("henisflash-object", "9.0.0", "../swf/expressInstall.swf"); }); /* end Flash */ /* begin Box, Sheet */ function artFluidSheetComputedWidth(percent, minval, maxval) { percent = parseInt(percent); var val = document.body.clientWidth / 100 * percent; return val < minval ? minval + 'px' : val > maxval ? maxval + 'px' : percent + '%'; }/* end Box, Sheet */ /* begin Layout */ jQuery(function () { if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 7) return; var c = jQuery('div.heniscontent'); if (c.length !== 1) return; var s = c.parent().children('.henislayout-cell:not(.heniscontent)'); jQuery(window).bind('resize', function () { var w = 0; c.css('width', "100%"); s.each(function () { w += this.clientWidth; }); c.w = c.parent().width();c.css('width', c.w - w); }).trigger('resize'); jQuery('div.heniscontent-layout-row').each(function () { this.c = jQuery(this).children('.henislayout-cell'); }).bind('resize', function () { if (this.h == this.clientHeight) return; this.c.css('height', 'auto'); this.h = this.clientHeight; this.c.css('height', this.h + 'px'); }).trigger('resize'); }); /* end Layout */ /* begin VMenu */ jQuery(function() { jQuery('ul.henisvmenu li').not(':first').before('<li class="henisvsubmenu-separator"><span class="henisvsubmenu-separator-span"> </span></li>'); jQuery('ul.henisvmenu > li.henisvsubmenu-separator').removeClass('henisvsubmenu-separator').addClass('henisvmenu-separator').children('span').removeClass('henisvsubmenu-separator-span').addClass('henisvmenu-separator-span'); jQuery('ul.henisvmenu > li > ul > li.henisvsubmenu-separator:first-child').removeClass('henisvsubmenu-separator').addClass('henisvmenu-separator').addClass('henisvmenu-separator-first').children('span').removeClass('henisvsubmenu-separator-span').addClass('henisvmenu-separator-span'); }); /* end VMenu */ /* begin VMenuItem */ jQuery(function() { jQuery.each(jQuery('ul.henisvmenu'), function(idx, val) { var m = jQuery(val); m.find("ul, a").removeClass('active'); var links = m.find('a'); for (var i = 0; i < links.length; i++){ if (links[i].href == window.location.href) { var a = jQuery(links[i]); a.parent().children('ul').addClass('active'); a.parents('ul.henisvmenu ul').addClass('active'); a.parents('ul.henisvmenu li').children('a').addClass('active'); break; } } }); }); /* end VMenuItem */ /* begin Button */ function artButtonSetup(className) { jQuery.each(jQuery("a." + className + ", button." + className + ", input." + className), function(i, val) { var b = jQuery(val); if (!b.parent().hasClass('henisbutton-wrapper')) { if (!b.hasClass('henisbutton')) b.addClass('henisbutton'); jQuery("<span class='henisbutton-wrapper'><span class='henisbutton-l'> </span><span class='henisbutton-r'> </span></span>").insertBefore(b).append(b); if (b.hasClass('active')) b.parent().addClass('active'); } b.mouseover(function() { jQuery(this).parent().addClass("hover"); }); b.mouseout(function() { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().removeClass('active'); }); b.mousedown(function() { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().addClass('active'); }); b.mouseup(function() { var b = jQuery(this); if (!b.hasClass('active')) b.parent().removeClass('active'); }); }); } jQuery(function() { artButtonSetup("henisbutton"); }); /* end Button */ jQuery(function () { artButtonSetup("button"); });
JavaScript
/* begin Page */ /* */ (function() { // fix ie blinking var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand; try { if (!!m) { m('BackgroundImageCache', false, true); } } catch (oh) { }; // css helper var u = navigator.userAgent.toLowerCase(); var is = function(t) { return (u.indexOf(t) != -1) }; jQuery('html').addClass([(!(/opera|webtv/i.test(u)) && /msie (\d)/.test(u)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? 'gecko firefox2' : is('firefox/3') ? 'gecko firefox3' : is('gecko/') ? 'gecko' : is('chrome/') ? 'chrome' : is('opera/9') ? 'opera opera9' : /opera (\d)/.test(u) ? 'opera opera' + RegExp.$1 : is('konqueror') ? 'konqueror' : is('applewebkit/') ? 'webkit safari' : is('mozilla/') ? 'gecko' : '', (is('x11') || is('linux')) ? ' linux' : is('mac') ? ' mac' : is('win') ? ' win' : '' ].join(' ')); })(); var _artStyleUrlCached = null; function artGetStyleUrl() { if (null == _artStyleUrlCached) { var ns; _artStyleUrlCached = ''; ns = jQuery('link'); for (var i = 0; i < ns.length; i++) { var l = ns[i].href; if (l && /style\.ie6\.css(\?.*)?$/.test(l)) return _artStyleUrlCached = l.replace(/style\.ie6\.css(\?.*)?$/, ''); } ns = jQuery('style'); for (var i = 0; i < ns.length; i++) { var matches = new RegExp('import\\s+"([^"]+\\/)style\\.ie6\\.css"').exec(ns[i].html()); if (null != matches && matches.length > 0) return _artStyleUrlCached = matches[1]; } } return _artStyleUrlCached; } function artFixPNG(element) { if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) { var src; if (element.tagName == 'IMG') { if (/\.png$/.test(element.src)) { src = element.src; element.src = artGetStyleUrl() + 'images/spacer.gif'; } } else { src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i); if (src) { src = src[1]; element.runtimeStyle.backgroundImage = 'none'; } } if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "')"; } } jQuery(function() { jQuery.each(jQuery('ul.henismenu>li:not(.henismenu-li-separator),ul.henisvmenu>li:not(.henisvmenu-separator)'), function (i, val) { var l = jQuery(val); var s = l.children('span'); if (s.length == 0) return; var t = l.find('span.t').last(); l.children('a').append(t.html(t.text())); s.remove(); }); });/* end Page */ /* begin Menu */ jQuery(function() { jQuery.each(jQuery('ul.henismenu>li:not(:last-child)'), function(i, val) { jQuery('<li class="henismenu-li-separator"><span class="henismenu-separator"> </span></li>').insertAfter(val); }); if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 6) return; jQuery.each(jQuery('ul.henismenu li'), function(i, val) { val.j = jQuery(val); val.UL = val.j.children('ul:first'); if (val.UL.length == 0) return; val.A = val.j.children('a:first'); this.onmouseenter = function() { this.j.addClass('henismenuhover'); this.UL.addClass('henismenuhoverUL'); this.A.addClass('henismenuhoverA'); }; this.onmouseleave = function() { this.j.removeClass('henismenuhover'); this.UL.removeClass('henismenuhoverUL'); this.A.removeClass('henismenuhoverA'); }; }); }); /* end Menu */ /* begin Box, Sheet */ function artFluidSheetComputedWidth(percent, minval, maxval) { percent = parseInt(percent); var val = document.body.clientWidth / 100 * percent; return val < minval ? minval + 'px' : val > maxval ? maxval + 'px' : percent + '%'; }/* end Box, Sheet */ /* begin Layout */ jQuery(function () { if (!jQuery.browser.msie || parseInt(jQuery.browser.version) > 7) return; var c = jQuery('div.heniscontent'); if (c.length !== 1) return; var s = c.parent().children('.henislayout-cell:not(.heniscontent)'); jQuery(window).bind('resize', function () { var w = 0; c.css('width', "100%"); s.each(function () { w += this.clientWidth; }); c.w = c.parent().width();c.css('width', c.w - w); }).trigger('resize'); jQuery('div.heniscontent-layout-row').each(function () { this.c = jQuery(this).children('.henislayout-cell'); }).bind('resize', function () { if (this.h == this.clientHeight) return; this.c.css('height', 'auto'); this.h = this.clientHeight; this.c.css('height', this.h + 'px'); }).trigger('resize'); }); /* end Layout */ /* begin Button */ function artButtonSetup(className) { jQuery.each(jQuery("a." + className + ", button." + className + ", input." + className), function(i, val) { var b = jQuery(val); if (!b.parent().hasClass('henisbutton-wrapper')) { if (!b.hasClass('henisbutton')) b.addClass('henisbutton'); jQuery("<span class='henisbutton-wrapper'><span class='henisbutton-l'> </span><span class='henisbutton-r'> </span></span>").insertBefore(b).append(b); if (b.hasClass('active')) b.parent().addClass('active'); } b.mouseover(function() { jQuery(this).parent().addClass("hover"); }); b.mouseout(function() { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().removeClass('active'); }); b.mousedown(function() { var b = jQuery(this); b.parent().removeClass("hover"); if (!b.hasClass('active')) b.parent().addClass('active'); }); b.mouseup(function() { var b = jQuery(this); if (!b.hasClass('active')) b.parent().removeClass('active'); }); }); } jQuery(function() { artButtonSetup("henisbutton"); }); /* end Button */ jQuery(function () { artButtonSetup("button"); });
JavaScript
/* Form Manager: A simple method of constructing complex dynamic forms. Written by Twey, http://www.twey.co.uk/. Use, copying, and modification allowed, so long as credit remains intact, under the terms of the GNU General Public License, version 2 or later. See http://www.gnu.org/copyleft/gpl.html for details. */ var FORM_MANAGER_CONDITION_SEPARATOR = " AND "; var FORM_MANAGER_POSSIBILITY_SEPARATOR = " OR "; var FORM_MANAGER_NAME_VALUE_SEPARATOR = " BEING "; var FORM_MANAGER_DEPENDS = "DEPENDS ON "; var FORM_MANAGER_CONFLICTS = "CONFLICTS WITH "; var FORM_MANAGER_EMPTY = "EMPTY"; function addEvent(el, ev, f) { if(el.addEventListener) el.addEventListener(ev, f, false); else if(el.attachEvent) { var t = function() { f.apply(el); }; addEvent.events.push({'element': el, 'event': ev, 'handler': f}); el.attachEvent("on" + ev, t); } else el['on' + ev] = f; } function addEvents(els, evs, f) { for(var i = 0; i < els.length; ++i) for(var j = 0; j < evs.length; ++j) addEvent(els[i], evs[j], f); } addEvent.events = []; if(typeof window.event !== "undefined") addEvent(window, "unload", function() { for(var i = 0, e = addEvent.events; i < e.length; ++i) e[i].element.detachEvent("on" + e[i].event, e[i].handler); } ); function getRadioValue(el) { if(!el.length) return null; for(var i = 0; i < el.length; ++i) if(el[i].checked) return el[i].value; return null; } function getSelectValue(el) { if(!el.tagName || el.tagName.toLowerCase() !== "select") return null; return el.options[el.selectedIndex].value; } function isElementValue(el, v) { if(v === FORM_MANAGER_EMPTY) v = ''; return ( getRadioValue(el) == v || getSelectValue(el) == v || ( el.tagName && el.tagName.toLowerCase() !== "select" && el.value == v ) ); } function setupDependencies() { var showEl = function() { this.style.display = ""; if(this.parentNode.tagName.toLowerCase() == "label") this.parentNode.style.display = ""; }; var hideEl = function() { this.style.display = "none"; if(typeof this.checked !== "undefined") this.checked = false; else this.value = ""; if(this.parentNode.tagName.toLowerCase() == "label") this.parentNode.style.display = "none"; this.hidden = true; }; var calcDeps = function() { for(var i = 0, e = this.elements; i < e.length; ++i) { e[i].hidden = false; for(var j = 0, f = e[i].className.split(FORM_MANAGER_CONDITION_SEPARATOR); j < f.length; ++j) if(f[j].indexOf(FORM_MANAGER_DEPENDS) === 0) { for(var k = 0, g = f[j].substr(FORM_MANAGER_DEPENDS.length).split(FORM_MANAGER_POSSIBILITY_SEPARATOR); k < g.length; ++k) if(g[k].indexOf(FORM_MANAGER_NAME_VALUE_SEPARATOR) === -1) { if(e[g[k]] && e[g[k]].checked) break; else if(k + 1 == g.length) e[i].hide(); } else { var n = g[k].split(FORM_MANAGER_NAME_VALUE_SEPARATOR), v = n[1]; n = n[0]; if(e[n]) if(isElementValue(e[n], v)) break; else if(k + 1 == g.length) e[i].hide(); } } else if(f[j].indexOf(FORM_MANAGER_CONFLICTS) === 0) { if(f[j].indexOf(FORM_MANAGER_NAME_VALUE_SEPARATOR) === -1) { if(e[f[j].substr(FORM_MANAGER_CONFLICTS.length)] && e[f[j].substr(FORM_MANAGER_CONFLICTS.length)].checked) { e[i].hide(); break; } } else { var n = f[j].substr(FORM_MANAGER_CONFLICTS.length).split(FORM_MANAGER_NAME_VALUE_SEPARATOR), v = n[1]; n = n[0]; if(e[n]) { if(isElementValue(e[n], v)) { e[i].hide(); break; } } } } if(!e[i].hidden) e[i].show(); } }; var changeHandler = function() { this.form.calculateDependencies(); return true; }; for(var i = 0; i < arguments.length; ++i) { for(var j = 0, e = window.document.forms[arguments[i]].elements; j < e.length; ++j) { addEvents([e[j]], ["change", "keyup", "focus", "click", "keydown"], changeHandler); e[j].hide = hideEl; e[j].show = showEl; } (e = window.document.forms[arguments[i]]).calculateDependencies = calcDeps; e.calculateDependencies(); } }
JavaScript
/*! * jQuery Form Plugin * version: 2.84 (12-AUG-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr('method'); action = this.attr('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if( $.isArray(options.data[n]) ) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { fileUpload(a); }); } else { fileUpload(a); } } else { // IE7 massage (see issue 57) if ($.browser.msie && method == 'get') { var ieMeth = $form[0].getAttribute('method'); if (typeof ieMeth === 'string') options.type = ieMeth; } $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var useProp = !!$.fn.prop; if (a) { // ensure that every serialized input is still enabled for (i=0; i < a.length; i++) { el = $(form[a[i].name]); el[ useProp ? 'prop' : 'attr' ]('disabled', false); } } if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (n == null) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, status); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; return doc; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); timeoutHandle && clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" />').attr('value',s.extraData[n]) .appendTo(form)[0]); } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } try { doc = getDoc(io); } catch(ex) { log('cannot access response document: ', ex); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = s.dataType || ''; var scr = /(json|script|text)/.test(dt.toLowerCase()); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, s.dataType, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught: ',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg == undefined) errMsg = xhr.statusText; s.error && s.error.call(s.context, xhr, status, errMsg); g && $.event.trigger("ajaxError", [xhr, s, errMsg]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging function log() { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } }; })(jQuery);
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ tinyMCE.init({ mode : "textareas", // =========================================== // !!! [DO NOT FORGET TO SET THEME TO ADVANCED] // =========================================== theme : "advanced", skin : "o2k7", skin_variant : "silver", width : "540", // =========================================== // !!! [DO NOT FORGET TO INCLUDE THE PLUGIN] // =========================================== plugins : "jbimages,autolink,lists,pagebreak,layer,table,advhr,advlink,emotions,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist", // =========================================== // !!! [DO NOT FORGET TO SET LANGUAGE TO EN] // =========================================== // Otherwise, you'll need to use plugin translation file language : "en", theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview", theme_advanced_buttons2 : "undo,redo,|,bold,italic,underline,strikethrough,|,forecolor,backcolor,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect", theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr", // =========================================== // !!! [DO NOT FORGET TO INCLUDE PLUGIN'S BUTTON] // =========================================== theme_advanced_buttons4 : "jbimages,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, // =========================================== // !!! [DO NOT FORGET TO SET RELATIVE URL FALSE] // =========================================== // This is required to images display properly relative_urls : false });
JavaScript
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:false, browser:true, jquery:false */ /*global jQuery BackgroundHelper */ // css helper (function ($) { 'use strict'; var data = [ { str: navigator.userAgent, sub: 'Chrome', ver: 'Chrome', name: 'chrome' }, { str: navigator.vendor, sub: 'Apple', ver: 'Version', name: 'safari' }, { prop: window.opera, ver: 'Opera', name: 'opera' }, { str: navigator.userAgent, sub: 'Firefox', ver: 'Firefox', name: 'firefox' }, { str: navigator.userAgent, sub: 'MSIE', ver: 'MSIE', name: 'ie' } ]; var v = function (s, n) { var i = s.indexOf(data[n].ver); return (i !== -1) ? parseInt(s.substring(i + data[n].ver.length + 1), 10) : ''; }; var html = $('html'); for (var n = 0; n < data.length; n++) { if ((data[n].str && (data[n].str.indexOf(data[n].sub) !== -1)) || data[n].prop) { html.addClass(data[n].name + ' ' + data[n].name + v(navigator.userAgent, n) || v(navigator.appVersion, n)); break; } } // 'desktop' class is used as responsive design initial value html.addClass('desktop'); })(jQuery); jQuery(function ($) { 'use strict'; var i, j, k, l, m; if (!$.browser.msie || parseInt($.browser.version, 10) !== 9) { return; } var splitByTokens = function (str, startToken, endToken, last) { if (!last) { last = false; } var startPos = str.indexOf(startToken); if (startPos !== -1) { startPos += startToken.length; var endPos = last ? str.lastIndexOf(endToken) : str.indexOf(endToken, startPos); if (endPos !== -1 && endPos > startPos) { return str.substr(startPos, endPos - startPos); } } return ''; }; var splitWithBrackets = function (str, token, brackets) { /*jshint nonstandard:true */ if (!token) { token = ','; } if (!brackets) { brackets = '()'; } var bracket = 0; var startPos = 0; var result = []; if (brackets.lenght < 2) { return result; } var pos = 0; while (pos < str.length) { var ch = str[pos]; if (ch === brackets[0]) { bracket++; } if (ch === brackets[1]) { bracket--; } if (ch === token && bracket < 1) { result.push(str.substr(startPos, pos - startPos)); startPos = pos + token.length; } pos++; } result.push(str.substr(startPos, pos - startPos)); return result; }; var byteToHex = function (d) { var hex = Number(d).toString(16); while (hex.length < 2) { hex = "0" + hex; } return hex; }; for (i = 0; i < document.styleSheets.length; i++) { var s = document.styleSheets[i]; var r = [s]; for (j = 0; j < s.imports.length; j++) { r.push(s.imports[j]); } for (j = 0; j < r.length; j++) { s = r[j]; var n = []; for (k = 0; k < s.rules.length; k++) { var css = s.rules[k].cssText || s.rules[k].style.cssText; if (!css) { continue; } var value = splitByTokens(css, '-svg-background:', ';'); if (value === '') { continue; } var values = splitWithBrackets(value); for (l = 0; l < values.length; l++) { var g = splitByTokens(values[l], 'linear-gradient(', ')', true); if (g === '') { continue; } var args = splitWithBrackets(g); if (args.length < 3) { continue; } var maxOffset = 0; var stops = []; for (m = 1; m < args.length; m++) { var stopValues = splitWithBrackets($.trim(args[m]), ' '); if (stopValues.length < 2) { continue; } var stopColor = $.trim(stopValues[0]); var stopOpacity = 1; var colorRgba = splitByTokens(stopColor, 'rgba(', ')', true); var stopOffset = $.trim(stopValues[1]); if (colorRgba !== "") { var rgba = colorRgba.split(','); if (rgba.length < 4) { continue; } stopColor = '#' + byteToHex(rgba[0]) + byteToHex(rgba[1]) + byteToHex(rgba[2]); stopOpacity = rgba[3]; } var isPx = stopOffset.indexOf('px') !== -1; if (isPx) { maxOffset = Math.max(maxOffset, parseInt(stopOffset, 10) || 0); } stops.push({ offset: stopOffset, color: stopColor, opacity: stopOpacity, isPx: isPx }); } var stopsXML = ''; var lastStop = null; for (m = 0; m < stops.length; m++) { if (stops[m].isPx) { stops[m].offset = ((parseInt(stops[m].offset, 10) || 0) / (maxOffset / 100)) + '%'; } stopsXML += '<stop offset="' + stops[m].offset + '" stop-color="' + stops[m].color + '" stop-opacity="' + stops[m].opacity + '"/>'; if (m === stops.length - 1) { lastStop = stops[m]; } } var isLeft = $.trim(args[0]) === 'left'; var direction = 'x1="0%" y1="0%" ' + (isLeft ? 'x2="100%" y2="0%"' : 'x2="0%" y2="100%"'); var gradientLength = '100%'; if (maxOffset > 0) { gradientLength = maxOffset + 'px'; } var size = (isLeft ? 'width="' + gradientLength + '" height="100%"' : 'width="100%" height="' + gradientLength + '"'); var last = ""; if (lastStop !== null && maxOffset > 0) { last = '<rect ' + (isLeft ? 'x="' + maxOffset + '" y="0"' : 'x="0" y="' + maxOffset + '"') + ' width="100%" height="100%" style="fill:' + lastStop.color + ';opacity:' + lastStop.opacity + ';"/>'; } var svgGradient = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none"><linearGradient id="g" gradientUnits="objectBoundingBox" ' + direction + '>' + stopsXML + '</linearGradient><rect x="0" y="0" ' + size + ' fill="url(#g)" />' + last + '</svg>'; values[l] = values[l].replace('linear-gradient(' + g + ')', 'url(data:image/svg+xml,' + escape(svgGradient) + ')'); } n.push({ s: s.rules[k].selectorText, v: 'background: ' + values.join(",") }); } for (k = 0; k < n.length; k++) { s.addRule(n[k].s, n[k].v); } } } }); jQuery(function ($) { 'use strict'; // ie < 9 slider multiple background fix if (!$.browser.msie || $.browser.version > 8) return; function split(str) { str = str.replace(/"/g, '').replace(/%20/g, ''); return str.split(/\s*,\s*/); } $('.henisslider .henisslide-item').each(function () { var bgs = split($(this).css('background-image')); // needs to use the last image if (bgs.length > 1) { $(this).css("background-image", bgs[bgs.length - 1]); } }); }); /* Set wmode=transparent for iframes to show it under the menus, lightboxes etc. */ jQuery(function ($) { "use strict"; $("iframe[src]").each(function () { var iframe = $(this); var src = iframe.attr("src"); if (src.lastIndexOf("?") !== -1) { src += "&amp;wmode=transparent"; } else { src += "?wmode=transparent"; } iframe.attr("src", src); }); }); jQuery(window).bind("resize", (function ($) { /*global responsiveDesign */ "use strict"; return function () { if (typeof responsiveDesign !== "undefined" && responsiveDesign.isResponsive) return; var sheetLeft = $(".henissheet").offset().left; $("header.henisheader #henisflash-area").each(function () { var object = $(this); object.css("left", sheetLeft + "px"); }); }; })(jQuery)); jQuery(function ($) { 'use strict'; $(window).bind('resize', function () { var bh = $('body').height(); var mh = 0; var c = $('div.heniscontent'); c.removeAttr('style'); $('#henismain').children().each(function() { if ($(this).css('position') !== 'absolute') { mh += $(this).outerHeight(true); } }); if (mh < bh) { var r = bh - mh; c.css('height', (c.outerHeight(true) + r) + 'px'); } }); if ($.browser.msie && parseInt($.browser.version, 10) < 8) { $(window).bind('resize', function() { var c = $('div.heniscontent'); var s = c.parent().children('.henislayout-cell:not(.heniscontent)'); var w = 0; c.hide(); s.each(function() { w += $(this).outerWidth(true); }); c.w = c.parent().width(); c.css('width', c.w - w + 'px'); c.show(); }); } $(window).trigger('resize'); }); var artButtonSetup = (function ($) { 'use strict'; return (function (className) { $.each($("a." + className + ", button." + className + ", input." + className), function (i, val) { var b = $(val); if (!b.hasClass('henisbutton')) { b.addClass('henisbutton'); } if (b.is('input')) { b.val(b.val().replace(/^\s*/, '')).css('zoom', '1'); } b.mousedown(function () { var b = $(this); b.addClass("active"); }); b.mouseup(function () { var b = $(this); if (b.hasClass('active')) { b.removeClass('active'); } }); b.mouseleave(function () { var b = $(this); if (b.hasClass('active')) { b.removeClass('active'); } }); }); }); })(jQuery); jQuery(function () { 'use strict'; artButtonSetup("henisbutton"); }); jQuery(function($) { 'use strict'; $('input.henissearch-button, form.henissearch input[type="submit"]').attr('value', ''); }); var Control = (function ($) { 'use strict'; return (function () { this.init = function(label, type, callback) { var chAttr = label.find('input[type="' +type + '"]').attr('checked'); if (chAttr === 'checked') { label.addClass('henischecked'); } label.mouseleave(function () { $(this).removeClass('hovered').removeClass('active'); }); label.mouseover(function () { $(this).addClass('hovered').removeClass('active'); }); label.mousedown(function (event) { if (event.which !== 1) { return; } $(this).addClass('active').removeClass('hovered'); }); label.mouseup(function (event) { if (event.which !== 1) { return; } callback.apply(this); $(this).removeClass('active').addClass('hovered'); }); }; }); })(jQuery); jQuery(function ($) { 'use strict'; $('.henispager').contents().filter( function () { return this.nodeType === this.TEXT_NODE; } ).remove(); }); var fixRssIconLineHeight = (function ($) { "use strict"; return function (className) { $("." + className).css("line-height", $("." + className).height() + "px"); }; })(jQuery); jQuery(function ($) { "use strict"; var rssIcons = $(".henisrss-tag-icon"); if (rssIcons.length){ fixRssIconLineHeight("henisrss-tag-icon"); if ($.browser.msie && parseInt($.browser.version, 10) < 9) { rssIcons.each(function () { if ($.trim($(this).html()) === "") { $(this).css("vertical-align", "middle"); } }); } } }); /** * @license * jQuery Tools 1.2.6 Mousewheel * * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE. * * http://flowplayer.org/tools/toolbox/mousewheel.html * * based on jquery.event.wheel.js ~ rev 1 ~ * Copyright (c) 2008, Three Dub Media * http://threedubmedia.com * * Since: Mar 2010 * Date: */ (function ($) { 'use strict'; $.fn.mousewheel = function (fn) { return this[fn ? "bind" : "trigger"]("wheel", fn); }; // special event config $.event.special.wheel = { setup: function () { $.event.add(this, wheelEvents, wheelHandler, {}); }, teardown: function () { $.event.remove(this, wheelEvents, wheelHandler); } }; // events to bind ( browser sniffed... ) var wheelEvents = !$.browser.mozilla ? "mousewheel" : // IE, opera, safari "DOMMouseScroll" + ($.browser.version < "1.9" ? " mousemove" : ""); // firefox // shared event handler function wheelHandler(event) { /*jshint validthis:true*/ switch (event.type) { // FF2 has incorrect event positions case "mousemove": return $.extend(event.data, { // store the correct properties clientX: event.clientX, clientY: event.clientY, pageX: event.pageX, pageY: event.pageY }); // firefox case "DOMMouseScroll": $.extend(event, event.data); // fix event properties in FF2 event.delta = -event.detail / 3; // normalize delta break; // IE, opera, safari case "mousewheel": event.delta = event.wheelDelta / 120; break; } event.type = "wheel"; // hijack the event return $.event.handle.call(this, event, event.delta); } })(jQuery); var ThemeLightbox = (function ($) { 'use strict'; return (function () { var current; var images = $("img.henislightbox"); var b = $("body"); this.init = function (ctrl) { $("img.henislightbox").live("click", { _ctrl: ctrl }, function (e) { if (e.data._ctrl === true && !e.ctrlKey) { return; } reload(); current = images.index(this); show(this); }); $(".arrow.left:not(.disabled)").live("click", function () { move(current - 1); }); $(".arrow.right:not(.disabled)").live("click", function () { move(current + 1); }); $("img.active").live("click", function () { move(current + 1); }); $(".close").live("click", function () { close(); }); }; function show(src) { var d = $('<div id="henislightbox-bg"><div class="close"><div class="cw"> </div><div class="ccw"> </div><div class="close-alt">&#10007;</div></div></div>'); var img = $('<img class="henislightbox-image active" alt="" src="' + getFullImgSrc($(src).attr("src")) + '" />'); resizeOnLoad(img); img.appendTo(b); showArrows(); showLoader(true); img.load(function () { showLoader(false); d.appendTo(b).height(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)); }); img.error(function () { showLoader(false); d.appendTo(b).height(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)); //showError(true); img.attr("src", $(src).attr("src")); }); d.click(close); bindMouse($(".arrow").add(img).add(d)); } function reload() { images = $("img.henislightbox"); } function move(index) { if (index < 0 || index >= images.length) { return; } showError(false); current = index; $("img.henislightbox-image:not(.active)").remove(); var active = $("img.active"); var target = $('<img class="henislightbox-image" alt="" src="' + getFullImgSrc($(images[current]).attr("src")) + '" />'); resizeOnLoad(target); active.after(target); showArrows(); showLoader(true); bindMouse($("#henislightbox-bg").add(target)); target.load(function () { showLoader(false); active.removeClass("active"); target.addClass("active"); }); target.error(function () { showLoader(false); //showError(true); active.removeClass("active"); target.addClass("active"); target.attr("src", $(images[current]).attr("src")); }); } function showArrows() { if ($(".arrow").length === 0) { b.append($('<div class="arrow left"><div class="arrow-t ccw"> </div><div class="arrow-b cw"> </div><div class="arrow-left-alt">&#8592;</div></div>').css("top", $(window).height() / 2 - 40)); b.append($('<div class="arrow right"><div class="arrow-t cw"> </div><div class="arrow-b ccw"> </div><div class="arrow-right-alt">&#8594;</div></div>').css("top", $(window).height() / 2 - 40)); } if (current === 0) { $(".arrow.left").addClass("disabled"); } else { $(".arrow.left").removeClass("disabled"); } if (current === images.length - 1) { $(".arrow.right").addClass("disabled"); } else { $(".arrow.right").removeClass("disabled"); } } function showError(enable) { if (enable) { b.append($('<div class="lightbox-error">Le contenu demandé ne peut pas être chargé.<br/>Veuillez réessayer plus tard.</div>') .css({ "top": $(window).height() / 2 - 60, "left": $(window).width() / 2 - 170 })); } else { $(".lightbox-error").remove(); } } function showLoader(enable) { if (!enable) { $(".loading").remove(); } else { $('<div class="loading"> </div>').css({ "top": $(window).height() / 2 - 16, "left": $(window).width() / 2 - 16 }).appendTo(b); } } var close = function () { $("#henislightbox-bg, .henislightbox-image, .arrow, .lightbox-error").remove(); }; function resizeOnLoad(img) { var width = $(window).width(); var height = $(window).height(); img.load(function () { var imgHeight = $(this).height(); var imgWidth = $(this).width(); // additional space is needed for the next|prev items and border around the images if (height < (imgHeight + 10) || width < (imgWidth + 410)) { var hScale = Math.abs(imgWidth / (width - 410)); var vScale = Math.abs(imgHeight / (height - 100)); var scale = Math.max(vScale, hScale); imgWidth = imgWidth / scale; imgHeight = imgHeight / scale; img.width(imgWidth); img.height(imgHeight); } img.css({ "top": (height / 2 - imgHeight / 2) - 5, "left": (width / 2 - imgWidth / 2 - 5) }); }); return img; } function bindMouse(img) { img.unbind("wheel").mousewheel(function (event, delta) { delta = delta > 0 ? 1 : -1; move(current + delta); event.preventDefault(); }); img.mousedown(function (e) { // close on middle button click if (e.which === 2) { close(); } e.preventDefault(); }); } function getFullImgSrc(src) { var webArchiveRegex = new RegExp("http://www.[A-z0-9-]+-image.com/.webarchive/"); if ((src.indexOf("http://") === 0 || src.indexOf("https://") === 0) && !webArchiveRegex.test(src)) { return src; } var fileName = src.substring(0, src.lastIndexOf('.')); var ext = src.substring(src.lastIndexOf('.')); src = fileName + "-large" + ext; return src; } }); })(jQuery); jQuery(function () { 'use strict'; new ThemeLightbox().init(); }); (function($) { 'use strict'; // transition && transitionEnd && browser prefix $.support.transition = (function() { var thisBody = document.body || document.documentElement, thisStyle = thisBody.style, support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined; return support && { event: (function() { var e = "transitionend"; if ($.browser.opera) { var version = parseFloat($.browser.version); e = version >= 12 ? (version < 12.50 ? "otransitionend" : "transitionend") : "oTransitionEnd"; } else if ($.browser.webkit) { e = "webkitTransitionEnd"; } return e; })(), prefix: (function() { var result; $.each($.browser, function(key, value) { if (key === "version") { return true; } return (result = { opera: "-o-", mozilla: "-moz-", webkit: "-webkit-", msie: "-ms-" }[key]) ? false : true; }); return result || ""; })() }; })(); window.BackgroundHelper = function () { var slides = []; var direction = "next"; var motion = "horizontal"; var width = 0; var height = 0; var multiplier = 1; var transitionDuration = ""; this.init = function(motionType, dir, duration) { direction = dir; motion = motionType; slides = []; width = 0; height = 0; multiplier = 1; transitionDuration = duration; }; this.processSlide = function(element, modify) { this.updateSize(element, null); var pos = []; var bgPosition = element.css("background-position"); var positions = bgPosition.split(","); $.each(positions, function (i) { var position = $.trim(this); var point = position.split(" "); if (point.length > 1) { var x = parseInt(point[0], 10); var y = parseInt(point[1], 10); pos.push({ x: x, y: y }); } }); slides.push({ "images": element.css("background-image"), "sizes": element.css("background-size"), "positions": pos }); if (modify) element.css("background-image", "none"); }; this.updateSize = function (element, initialSize) { width = element.outerWidth(false); height = element.outerHeight(); if (initialSize && parseInt(initialSize.width, 10) !== 0) { multiplier = width / initialSize.width; if (motion === "fade") { $.each(element.children(), function (i) { $(this).css("background-position", getCssPositions(slides[i].positions, { x: 0, y: 0 })); }); } } }; this.setBackground = function(element, items) { var bg = []; var sizes = []; $.each(items, function (i, o) { bg.push(o.images); sizes.push(o.sizes); }); element.css({ "background-image": bg.join(", "), "background-size": sizes.join(", "), "background-repeat": "no-repeat" }); }; this.setPosition = function(element, items) { var pos = []; $.each(items, function(i, o) { pos.push(o.positions); }); element.css({ "background-position": pos.join(", ") }); }; this.current = function(index) { return slides[index] || null; }; this.next = function(index) { var next; if (direction === "next") { next = (index + 1) % slides.length; } else { next = index - 1; if (next < 0) { next = slides.length - 1; } } return slides[next]; }; this.items = function(prev, next, move) { var prevItem = { x: 0, y: 0 }; var nextItem = { x: 0, y: 0 }; var isDirectionNext = direction === "next"; if (motion === "horizontal") { nextItem.x = isDirectionNext ? width : -width; nextItem.y = 0; if (move) { prevItem.x += isDirectionNext ? -width : width; nextItem.x += isDirectionNext ? -width : width; } } else if (motion === "vertical") { nextItem.x = 0; nextItem.y = isDirectionNext ? height : -height; if (move) { prevItem.y += isDirectionNext ? -height : height; nextItem.y += isDirectionNext ? -height : height; } } var result = [ ]; if (!!prev) { result.push({ images: prev.images, positions: getCssPositions(prev.positions, prevItem), sizes: prev.sizes }); } if (!!next) { result.push({ images: next.images, positions: getCssPositions(next.positions, nextItem), sizes: next.sizes }); } if (direction === "next") { result.reverse(); } return result; }; this.transition = function(container, on) { container.css($.support.transition.prefix + "transition", on ? transitionDuration + " ease-in-out background-position" : ""); }; function getCssPositions(positions, offset) { var result = []; if (positions === undefined) { return ""; } offset.x = offset.x || 0; offset.y = offset.y || 0; for (var i = 0; i < positions.length; i++) { result.push((positions[i].x * multiplier + offset.x) + "px " + (positions[i].y * multiplier + offset.y) + "px"); } return result.join(", "); } }; var Slider = function (element, settings) { var interval = null; var active = false; var children = element.find(".active").parent().children(); var last = false; var running = false; this.settings = $.extend({ }, { "animation": "horizontal", "direction": "next", "speed": 600, "pause": 2500, "auto": true, "repeat": true, "navigator": null, "clickevents": true, "hover": true, "helper": null }, settings); this.move = function (direction, next) { var activeItem = element.find(".active"), nextItem = next || activeItem[direction](), innerDirection = this.settings.direction === "next" ? "forward" : "back", reset = direction === "next" ? "first" : "last", moving = interval, slider = this, tmp; active = true; if (moving) { this.stop(true); } if (!nextItem.length) { nextItem = element.find(".henisslide-item")[reset](); if (!this.settings.repeat) { last = true; active = false; return; } } if ($.support.transition) { nextItem.addClass(this.settings.direction); tmp = nextItem.get(0).offsetHeight; activeItem.addClass(innerDirection); nextItem.addClass(innerDirection); element.trigger("beforeSlide", children.length); element.one($.support.transition.event, function () { nextItem.removeClass(slider.settings.direction) .removeClass(innerDirection) .addClass("active"); activeItem.removeClass("active") .removeClass(innerDirection); active = false; setTimeout(function () { element.trigger("afterSlide", children.length); }, 0); }); } else { element.trigger("beforeSlide", children.length); activeItem.removeClass("active"); nextItem.addClass("active"); active = false; element.trigger("afterSlide", children.length); } this.navigate(nextItem); if (moving) { this.start(); } }; this.navigate = function (position) { var index = children.index(position); $(this.settings.navigator).children().removeClass("active").eq(index).addClass("active"); }; this.to = function (index) { var activeItem = element.find(".active"), children = activeItem.parent().children(), activeIndex = children.index(activeItem), slider = this; if (index > (children.length - 1) || index < 0) { return; } if (active) { return element.one("afterSlide", function () { slider.to(index); }); } if (activeIndex === index) { return; } this.move(index > activeIndex ? "next" : "prev", $(children[index])); }; this.next = function () { if (!active) { if (last) { this.stop(); return; } this.move("next"); } }; this.prev = function () { if (!active) { if (last) { this.stop(); return; } this.move("prev"); } }; this.start = function (force) { if (!!force) { setTimeout($.proxy(this.next, this), 10); } interval = setInterval($.proxy(this.next, this), this.settings.pause); running = true; }; this.stop = function (pause) { clearInterval(interval); interval = null; running = !!pause; active = false; }; this.active = function () { return running; }; this.moving = function () { return active; }; this.navigate(children.filter(".active")); if (this.settings.clickevents) { $(this.settings.navigator).on("click", "a", { slider: this }, function (event) { var activeIndex = children.index(children.filter(".active")); var index = $(this).parent().children().index($(this)); if (activeIndex !== index) { event.data.slider.to(index); } event.preventDefault(); }); } if (this.settings.hover) { var slider = this; element.add(this.settings.navigator) .add(element.siblings(".henisshapes")).hover(function () { if (element.is(":visible") && !last) { slider.stop(true); } }, function () { if (element.is(":visible") && !last) { slider.start(); } }); } }; $.fn.slider = function (arg) { return this.each(function () { var element = $(this), data = element.data("slider"), options = typeof arg === "object" && arg; if (!data) { data = new Slider(element, options); element.data("slider", data); } if (typeof arg === "string" && data[arg]) { data[arg](); } else if (data.settings.auto && element.is(":visible")) { data.start(); } }); }; })(jQuery); jQuery(window).bind("resize", (function ($) { /*global responsiveDesign */ "use strict"; return function () { if (typeof responsiveDesign !== "undefined" && responsiveDesign.isResponsive) { $("header.henisheader .henisshapes").children().css("left", ""); return; } var sheetWidth = $(".henissheet").width(); var sheetLeft = $(".henissheet").offset().left; $("header.henisheader .henisshapes>*, header.henisheader>.henistextblock").each(function () { var object = $(this); var objectLeft = sheetWidth * parseFloat(object.attr("data-left") || "0") / 100 + sheetLeft; object.css("left", objectLeft + "px"); }); }; })(jQuery)); jQuery(function ($) { "use strict"; $(window).trigger("resize"); }); jQuery(function ($) { "use strict"; if (!$.browser.msie || parseInt($.browser.version, 10) > 8) return; var path = ""; var scripts = $("script[src*='script.js']"); if (scripts.length > 0) { var src = scripts.last().attr('src'); path = src.substr(0, src.indexOf("script.js")); } var header = $(".henisheader"); var bgimages = "".split(","); var bgpositions = "".split(","); for (var i = bgimages.length - 1; i >= 0; i--) { var bgimage = $.trim(bgimages[i]); if (bgimage === "") continue; if (path !== "") { bgimage = bgimage.replace(/(url\(['"]?)/i, "$1" + path); } header.append("<div style=\"position:absolute;top:0;left:0;width:100%;height:100%;background:" + bgimage + " " + bgpositions[i] + " no-repeat\">"); } header.css('background-image', "url('images/header.png')".replace(/(url\(['"]?)/i, "$1" + path)); header.css('background-position', "center top"); });
JavaScript
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:false, browser:true, jquery:false */ /*global jQuery */ var responsiveDesign = { isResponsive: false, isDesktop: false, isTablet: false, isPhone: false, windowWidth: 0, responsive: (function ($) { "use strict"; return function () { var html = $("html"); this.windowWidth = $(window).width(); var triggerEvent = false; var isRespVisible = $("#henisresp").is(":visible"); if (isRespVisible && !this.isResponsive) { html.addClass("responsive").removeClass("desktop"); this.isResponsive = true; this.isDesktop = false; triggerEvent = true; } else if (!isRespVisible && !this.isDesktop) { html.addClass("desktop").removeClass("responsive responsive-tablet responsive-phone"); this.isResponsive = this.isTablet = this.isPhone = false; this.isDesktop = true; triggerEvent = true; } if (this.isResponsive) { if ($("#henisresp-t").is(":visible") && !this.isTablet) { html.addClass("responsive-tablet").removeClass("responsive-phone"); this.isTablet = true; this.isPhone = false; triggerEvent = true; } else if ($("#henisresp-m").is(":visible") && !this.isPhone) { html.addClass("responsive-phone").removeClass("responsive-tablet"); this.isTablet = false; this.isPhone = true; triggerEvent = true; } } if (triggerEvent) { $(window).trigger("responsive", this); } $(window).trigger("responsiveResize", this); }; })(jQuery), initialize: (function ($) { "use strict"; return function () { $("<div id=\"henisresp\"><div id=\"henisresp-m\"></div><div id=\"henisresp-t\"></div></div>").appendTo("body"); var resizeTimeout; $(window).resize(function () { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(function () { responsiveDesign.responsive(); }, 25); }); $(window).trigger("resize"); }; })(jQuery) }; function responsiveAbsBg(responsiveDesign, el, bg) { "use strict"; if (bg.length === 0) return; var desktopBgTop = bg.attr("data-bg-top"); var desktopBgHeight = bg.attr("data-bg-height"); if (responsiveDesign.isResponsive) { if (typeof desktopBgTop === "undefined" || desktopBgTop === false) { bg.attr("data-bg-top", bg.css("top")); bg.attr("data-bg-height", bg.css("height")); } var elTop = el.offset().top; var elHeight = el.outerHeight(); bg.css("top", elTop + "px"); bg.css("height", elHeight + "px"); } else if (typeof desktopBgTop !== "undefined" && desktopBgTop !== false) { bg.css("top", desktopBgTop); bg.css("height", desktopBgHeight); bg.removeAttr("data-bg-top"); bg.removeAttr("data-bg-height"); } } var responsiveImages = (function ($) { "use strict"; return function (responsiveDesign) { $("img[width]").each(function () { var img = $(this), newWidth = "", newMaxWidth = "", newHeight = ""; if (responsiveDesign.isResponsive) { newWidth = "auto"; newHeight = "auto"; newMaxWidth = "100%"; var widthAttr = img.attr("width"); if (widthAttr !== null && typeof (widthAttr) === "string" && widthAttr.indexOf("%") === -1) { newWidth = "100%"; newMaxWidth = parseInt($.trim(widthAttr), 10) + "px"; } } img.css("width", newWidth).css("max-width", newMaxWidth).css("height", newHeight); }); }; })(jQuery); var responsiveVideos = (function ($) { "use strict"; return function (responsiveDesign) { $("iframe,object,embed").each(function () { var obj = $(this); var container = obj.parent(".henisresponsive-embed"); if (responsiveDesign.isResponsive) { if (container.length !== 0) return; container = $("<div class=\"henisresponsive-embed\">").insertBefore(obj); obj.appendTo(container); } else if (container.length > 0) { obj.insertBefore(container); container.remove(); } }); }; })(jQuery); var responsiveTextblocks = (function ($) { "use strict"; return function (slider, responsiveDesign) { slider.find(".henistextblock").each(function () { if (parseInt(slider.attr("data-width"), 10) === 0) { return true; } var tb = $(this); var c = slider.width() / slider.attr("data-width"); tb.css({ "height": "", "width": "", "top": "", "margin-left": "" }); if (responsiveDesign.isResponsive) { var tbHeight = parseInt(tb.css("height"), 10); var tbWidth = parseInt(tb.css("width"), 10); var tbTop = parseInt(tb.css("top"), 10); var tbMargin = parseInt(tb.css("margin-left"), 10); tb.add(tb.children()).css({ "height": tbHeight * c, "width": tbWidth * c }); tb.css("top", tbTop * c); tb.attr("style", function (i, s) { return s + "margin-left: " + (tbMargin * c) + "px !important"; }); } }); }; })(jQuery); var responsiveSlider = (function ($) { "use strict"; return function (responsiveDesign) { $(".henisslider").each(function () { var s = $(this); responsiveTextblocks(s, responsiveDesign); if (!responsiveDesign.isResponsive) { s.removeAttr("style"); return; } // set size var initialWidth = s.attr("data-width"); var initialHeight = s.attr("data-height"); var c = s.width() / initialWidth; var h = c * initialHeight; s.css("height", h + "px"); // set slider var obj = s.data("slider"); if (obj && obj.settings.helper) { var inner = s.find(".henisslider-inner"); obj.settings.helper.updateSize(inner, { width: initialWidth, height: initialHeight }); } }); }; })(jQuery); var responsiveCollages = (function ($) { "use strict"; return function (responsiveDesign) { $(".heniscollage").each(function () { var collage = $(this); var parent = collage.closest(":not(.image-caption-wrapper, .heniscollage)"); var parentWidth = parent.width(); var collageWidth = collage.width(); var sliderOriginalWidth = collage.children(".henisslider").attr("data-width"); if (responsiveDesign.isResponsive && collageWidth > parentWidth) { collage .add(collage.find(".henisslider")) .add(collage.closest(".image-caption-wrapper")) .css("width", "100%"); } else if (!responsiveDesign.isResponsive || collageWidth > sliderOriginalWidth) { collage .add(collage.find(".henisslider")) .add(collage.closest(".image-caption-wrapper")) .css("width", ""); } }); }; })(jQuery); var responsiveNavigator = (function ($) { "use strict"; return function (responsiveDesign) { $(".henisslider").each(function () { var slider = $(this); var sliderWidth = slider.width(); var nav = slider.siblings(".henisslidenavigator"); if (nav.length) { if (responsiveDesign.isResponsive) { // left offset var left = nav.attr("data-left"); // (margin = containerWidth - (objectPosition + objectWidth)) < 0 var margin = sliderWidth - sliderWidth * parseFloat(left) / 100 - nav.outerWidth(false); if (margin < 0) { nav.css("margin-left", margin); } // top var sliderHeight = slider.css("height"); // reset top to original value nav.css("top", ""); // newTop = oldTop - (sliderOrinalHeight - sliderCurrentHeight) var offset = parseInt(nav.attr("data-offset") || 0, 10); nav.css("top", parseInt(nav.css("top"), 10) - (slider.attr("data-height") - parseInt(sliderHeight, 10)) + offset); } else { nav.removeAttr("data-offset"); nav.removeAttr("style"); } } }); }; })(jQuery); jQuery(window).bind("responsive", (function ($) { "use strict"; return function (event, responsiveDesign) { responsiveImages(responsiveDesign); responsiveVideos(responsiveDesign); if ($.browser.msie && $.browser.version <= 8) return; if (responsiveDesign.isResponsive) { $(window).on("responsiveResize.slider", function () { responsiveSlideshow(responsiveDesign); }); } else { $(window).trigger("responsiveResize.slider"); $(window).off("responsiveResize.slider"); } }; })(jQuery)); function responsiveSlideshow(responsiveDesign) { "use strict"; responsiveCollages(responsiveDesign); // must be first responsiveSlider(responsiveDesign); responsiveNavigator(responsiveDesign); } var responsiveHeader = (function ($) { "use strict"; return function(responsiveDesign) { var header = $("header.henisheader"); var headerSlider = header.find(".henisslider"); if (headerSlider.length) { var firstSlide = headerSlider.find(".henisslide-item").first(); var slidebg = firstSlide.css("background-image").split(","); var previousSibling = headerSlider.prev(); var sliderNav = headerSlider.siblings(".henisslidenavigator"); if (slidebg.length && responsiveDesign.isResponsive) { header.css("background-image", slidebg[slidebg.length - 1]); // if prev is menu in header if (previousSibling.is("nav.henisnav")) { sliderNav.attr("data-offset", previousSibling.height()); } } else { sliderNav.removeAttr("data-offset"); header.removeAttr("style"); } } }; })(jQuery); jQuery(window).bind("responsiveResize", (function ($) { "use strict"; return function (event, responsiveDesign) { responsiveAbsBg(responsiveDesign, $(".henisheader"), $("#henisheader-bg")); }; })(jQuery)); jQuery(window).bind("responsive", (function ($) { "use strict"; return function (event, responsiveDesign) { if ($.browser.msie && $.browser.version <= 8) return; if (responsiveDesign.isResponsive) { $(window).on("responsiveResize.header", function () { responsiveHeader(responsiveDesign); }); } else { $(window).trigger("responsiveResize.header"); $(window).off("responsiveResize.header"); } }; })(jQuery)); var responsiveLayoutCell = (function ($) { "use strict"; return function (responsiveDesign) { $(".heniscontent .heniscontent-layout-row,.henisfooter .heniscontent-layout-row").each(function () { var row = $(this); var rowChildren = row.children(".henislayout-cell"); if (rowChildren.length > 1) { if (responsiveDesign.isTablet) { rowChildren.addClass("responsive-tablet-layout-cell").each(function (i) { if ((i + 1) % 2 === 0) { $(this).after("<div class=\"cleared responsive-cleared\">"); } }); } else { rowChildren.removeClass("responsive-tablet-layout-cell"); row.children(".responsive-cleared").remove(); } } }); }; })(jQuery); jQuery(window).bind("responsive", function (event, responsiveDesign) { "use strict"; responsiveLayoutCell(responsiveDesign); }); jQuery(responsiveDesign.initialize);
JavaScript
/* Copyright 2010 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 Bookmark bubble library. This is meant to be included in the * main JavaScript binary of a mobile web application. * * Supported browsers: iPhone / iPod / iPad Safari 3.0+ */ var google = google || {}; google.bookmarkbubble = google.bookmarkbubble || {}; /** * Binds a context object to the function. * @param {Function} fn The function to bind to. * @param {Object} context The "this" object to use when the function is run. * @return {Function} A partially-applied form of fn. */ google.bind = function(fn, context) { return function() { return fn.apply(context, arguments); }; }; /** * Function used to define an abstract method in a base class. If a subclass * fails to override the abstract method, then an error will be thrown whenever * that method is invoked. */ google.abstractMethod = function() { throw Error('Unimplemented abstract method.'); }; /** * The bubble constructor. Instantiating an object does not cause anything to * be rendered yet, so if necessary you can set instance properties before * showing the bubble. * @constructor */ google.bookmarkbubble.Bubble = function() { /** * Handler for the scroll event. Keep a reference to it here, so it can be * unregistered when the bubble is destroyed. * @type {function()} * @private */ this.boundScrollHandler_ = google.bind(this.setPosition, this); /** * The bubble element. * @type {Element} * @private */ this.element_ = null; /** * Whether the bubble has been destroyed. * @type {boolean} * @private */ this.hasBeenDestroyed_ = false; }; /** * Shows the bubble if allowed. It is not allowed if: * - The browser is not Mobile Safari, or * - The user has dismissed it too often already, or * - The hash parameter is present in the location hash, or * - The application is in fullscreen mode, which means it was already loaded * from a homescreen bookmark. * @return {boolean} True if the bubble is being shown, false if it is not * allowed to show for one of the aforementioned reasons. */ google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() { if (!this.isAllowedToShow_()) { return false; } this.show_(); return true; }; /** * Shows the bubble if allowed after loading the icon image. This method creates * an image element to load the image into the browser's cache before showing * the bubble to ensure that the image isn't blank. Use this instead of * showIfAllowed if the image url is http and cacheable. * This hack is necessary because Mobile Safari does not properly render * image elements with border-radius CSS. * @param {function()} opt_callback Closure to be called if and when the bubble * actually shows. * @return {boolean} True if the bubble is allowed to show. */ google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded = function(opt_callback) { if (!this.isAllowedToShow_()) { return false; } var self = this; // Attach to self to avoid garbage collection. var img = self.loadImg_ = document.createElement('img'); img.src = self.getIconUrl_(); img.onload = function() { if (img.complete) { delete self.loadImg_; img.onload = null; // Break the circular reference. self.show_(); opt_callback && opt_callback(); } }; img.onload(); return true; }; /** * Sets the parameter in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * This gets called automatically when the bubble is shown. The idea is that if * the user then creates a bookmark, we can later recognize on application * startup whether it was from a bookmark suggested with this bubble. * * NOTE: Using a hash parameter to track whether the bubble has been shown * conflicts with the navigation system in jQuery Mobile. If you are using that * library, you should implement this function to track the bubble's status in * a different way, e.g. using window.localStorage in HTML5. */ google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod; /** * Whether the parameter is present in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * Call this method during application startup if you want to log whether the * application was loaded from a bookmark with the bookmark bubble promotion * parameter in it. * * @return {boolean} Whether the bookmark bubble parameter is present in the * location hash. */ google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod; /** * The number of times the user must dismiss the bubble before we stop showing * it. This is a public property and can be changed by the host application if * necessary. * @type {number} */ google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2; /** * Time in milliseconds. If the user does not dismiss the bubble, it will auto * destruct after this amount of time. * @type {number} */ google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000; /** * The prefix for keys in local storage. This is a public property and can be * changed by the host application if necessary. * @type {string} */ google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_'; /** * The key name for the dismissed state. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT'; /** * The arrow image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII='; /** * The close image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII='; /** * The link used to locate the application's home screen icon to display inside * the bubble. The default link used here is for an iPhone home screen icon * without gloss. If your application uses a glossy icon, change this to * 'apple-touch-icon'. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.REL_ICON_ = 'apple-touch-icon-precomposed'; /** * Regular expression for detecting an iPhone or iPod or iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ = /iPhone|iPod|iPad/; /** * Regular expression for detecting an iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/; /** * Regular expression for extracting the iOS version. Only matches 2.0 and up. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ = /OS (\d)_(\d)(?:_(\d))?/; /** * Determines whether the bubble should be shown or not. * @return {boolean} Whether the bubble should be shown or not. * @private */ google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() { return this.isMobileSafari_() && !this.hasBeenDismissedTooManyTimes_() && !this.isFullscreen_() && !this.hasHashParameter(); }; /** * Builds and shows the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.show_ = function() { this.element_ = this.build_(); document.body.appendChild(this.element_); this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; this.setHashParameter(); window.setTimeout(this.boundScrollHandler_, 1); window.addEventListener('scroll', this.boundScrollHandler_, false); // If the user does not dismiss the bubble, slide out and destroy it after // some time. window.setTimeout(google.bind(this.autoDestruct_, this), this.TIME_UNTIL_AUTO_DESTRUCT); }; /** * Destroys the bubble by removing its DOM nodes from the document. */ google.bookmarkbubble.Bubble.prototype.destroy = function() { if (this.hasBeenDestroyed_) { return; } window.removeEventListener('scroll', this.boundScrollHandler_, false); if (this.element_ && this.element_.parentNode == document.body) { document.body.removeChild(this.element_); this.element_ = null; } this.hasBeenDestroyed_ = true; }; /** * Remember that the user has dismissed the bubble once more. * @private */ google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() { if (window.localStorage) { try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; var value = Number(window.localStorage[key]) || 0; window.localStorage[key] = String(value + 1); } catch (ex) { // Looks like we've hit the storage size limit. Currently we have no // fallback for this scenario, but we could use cookie storage instead. // This would increase the code bloat though. } } }; /** * Whether the user has dismissed the bubble often enough that we will not * show it again. * @return {boolean} Whether the user has dismissed the bubble often enough * that we will not show it again. * @private */ google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ = function() { if (!window.localStorage) { // If we can not use localStorage to remember how many times the user has // dismissed the bubble, assume he has dismissed it. Otherwise we might end // up showing it every time the host application loads, into eternity. return true; } try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; // If the key has never been set, localStorage yields undefined, which // Number() turns into NaN. In that case we'll fall back to zero for // clarity's sake. var value = Number(window.localStorage[key]) || 0; return value >= this.NUMBER_OF_TIMES_TO_DISMISS; } catch (ex) { // If we got here, something is wrong with the localStorage. Make the same // assumption as when it does not exist at all. Exceptions should only // occur when setting a value (due to storage limitations) but let's be // extra careful. return true; } }; /** * Whether the application is running in fullscreen mode. * @return {boolean} Whether the application is running in fullscreen mode. * @private */ google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() { return !!window.navigator.standalone; }; /** * Whether the application is running inside Mobile Safari. * @return {boolean} True if the current user agent looks like Mobile Safari. * @private */ google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() { return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Whether the application is running on an iPad. * @return {boolean} True if the current user agent looks like an iPad. * @private */ google.bookmarkbubble.Bubble.prototype.isIpad_ = function() { return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Creates a version number from 4 integer pieces between 0 and 127 (inclusive). * @param {*=} opt_a The major version. * @param {*=} opt_b The minor version. * @param {*=} opt_c The revision number. * @param {*=} opt_d The build number. * @return {number} A representation of the version. * @private */ google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b, opt_c, opt_d) { // We want to allow implicit conversion of any type to number while avoiding // compiler warnings about the type. return /** @type {number} */ (opt_a) << 21 | /** @type {number} */ (opt_b) << 14 | /** @type {number} */ (opt_c) << 7 | /** @type {number} */ (opt_d); }; /** * Gets the iOS version of the device. Only works for 2.0+. * @return {number} The iOS version. * @private */ google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() { var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec( window.navigator.userAgent) || []; groups.shift(); return this.getVersion_.apply(this, groups); }; /** * Positions the bubble at the bottom of the viewport using an animated * transition. */ google.bookmarkbubble.Bubble.prototype.setPosition = function() { this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)'; }; /** * Destroys the bubble by removing its DOM nodes from the document, and * remembers that it was dismissed. * @private */ google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() { this.destroy(); this.rememberDismissal_(); }; /** * Gets called after a while if the user ignores the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() { if (this.hasBeenDestroyed_) { return; } this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; window.setTimeout(google.bind(this.destroy, this), 700); }; /** * Gets the y offset used to show the bubble (i.e., position it on-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() { return this.isIpad_() ? window.pageYOffset + 17 : window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17; }; /** * Gets the y offset used to hide the bubble (i.e., position it off-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() { return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight : window.pageYOffset + window.innerHeight; }; /** * The url of the app's bookmark icon. * @type {string|undefined} * @private */ google.bookmarkbubble.Bubble.prototype.iconUrl_; /** * Scrapes the document for a link element that specifies an Apple favicon and * returns the icon url. Returns an empty data url if nothing can be found. * @return {string} A url string. * @private */ google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() { if (!this.iconUrl_) { var link = this.getLink(this.REL_ICON_); if (!link || !(this.iconUrl_ = link.href)) { this.iconUrl_ = 'data:image/png;base64,'; } } return this.iconUrl_; }; /** * Gets the requested link tag if it exists. * @param {string} rel The rel attribute of the link tag to get. * @return {Element} The requested link tag or null. */ google.bookmarkbubble.Bubble.prototype.getLink = function(rel) { rel = rel.toLowerCase(); var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; ++i) { var currLink = /** @type {Element} */ (links[i]); if (currLink.getAttribute('rel').toLowerCase() == rel) { return currLink; } } return null; }; /** * Creates the bubble and appends it to the document. * @return {Element} The bubble element. * @private */ google.bookmarkbubble.Bubble.prototype.build_ = function() { var bubble = document.createElement('div'); var isIpad = this.isIpad_(); bubble.style.position = 'absolute'; bubble.style.zIndex = 1000; bubble.style.width = '100%'; bubble.style.left = '0'; bubble.style.top = '0'; var bubbleInner = document.createElement('div'); bubbleInner.style.position = 'relative'; bubbleInner.style.width = '214px'; bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto'; bubbleInner.style.border = '2px solid #fff'; bubbleInner.style.padding = '20px 20px 20px 10px'; bubbleInner.style.WebkitBorderRadius = '8px'; bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)'; bubbleInner.style.WebkitBackgroundSize = '100% 8px'; bubbleInner.style.backgroundColor = '#b0c8ec'; bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' + 'left bottom, left top, ' + isIpad ? 'from(#cddcf3), to(#b3caed)) no-repeat top' : 'from(#b3caed), to(#cddcf3)) no-repeat bottom'; bubbleInner.style.font = '13px/17px sans-serif'; bubble.appendChild(bubbleInner); // The "Add to Home Screen" text is intended to be the exact same text // that is displayed in the menu of Mobile Safari. if (this.getIosVersion_() >= this.getVersion_(4, 2)) { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap on the arrow and then <b>\'Add to Home Screen\'</b>'; } else { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap <b style="font-size:15px">+</b> and then ' + '<b>\'Add to Home Screen\'</b>'; } var icon = document.createElement('div'); icon.style['float'] = 'left'; icon.style.width = '55px'; icon.style.height = '55px'; icon.style.margin = '-2px 7px 3px 5px'; icon.style.background = '#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px'; icon.style.WebkitBackgroundSize = '57px'; icon.style.WebkitBorderRadius = '10px'; icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)'; bubbleInner.insertBefore(icon, bubbleInner.firstChild); var arrow = document.createElement('div'); arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')'; arrow.style.width = '25px'; arrow.style.height = '19px'; arrow.style.position = 'absolute'; arrow.style.left = '111px'; if (isIpad) { arrow.style.WebkitTransform = 'rotate(180deg)'; arrow.style.top = '-19px'; } else { arrow.style.bottom = '-19px'; } bubbleInner.appendChild(arrow); var close = document.createElement('a'); close.onclick = google.bind(this.closeClickHandler_, this); close.style.position = 'absolute'; close.style.display = 'block'; close.style.top = '-3px'; close.style.right = '-3px'; close.style.width = '16px'; close.style.height = '16px'; close.style.border = '10px solid transparent'; close.style.background = 'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat'; bubbleInner.appendChild(close); return bubble; };
JavaScript
/* Copyright 2010 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 Example of how to use the bookmark bubble. */ window.addEventListener('load', function() { window.setTimeout(function() { var bubble = new google.bookmarkbubble.Bubble(); var parameter = 'bmb=1'; bubble.hasHashParameter = function() { return window.location.hash.indexOf(parameter) != -1; }; bubble.setHashParameter = function() { if (!this.hasHashParameter()) { window.location.hash += parameter; } }; bubble.getViewportHeight = function() { window.console.log('Example of how to override getViewportHeight.'); return window.innerHeight; }; bubble.getViewportScrollY = function() { window.console.log('Example of how to override getViewportScrollY.'); return window.pageYOffset; }; bubble.registerScrollHandler = function(handler) { window.console.log('Example of how to override registerScrollHandler.'); window.addEventListener('scroll', handler, false); }; bubble.deregisterScrollHandler = function(handler) { window.console.log('Example of how to override deregisterScrollHandler.'); window.removeEventListener('scroll', handler, false); }; bubble.showIfAllowed(); }, 1000); }, false);
JavaScript
function polling_task() { check_message(); } function check_message() { console.log("check_message"); data = loadFile('http://127.0.0.1/~yishii/kobe_hackathon/test.txt'); // data = loadFile('http://192.168.254.101/~yishii/kobe_hackathon/test.txt'); console.log(data); } function loadFile(fileName){ var data=""; httpObj = new XMLHttpRequest(); httpObj.open('GET',fileName+"?"+(new Date()).getTime(),true); httpObj.send(null); httpObj.onreadystatechange = function(){ if ( (httpObj.readyState == 4) && (httpObj.status == 200) ){ //document.getElementById("text1").value=httpObj.responseText; returnedData = httpObj.responseText; // console.log("in"+returnedData); } } // console.log(httpObj.responseText); return(returnedData); }
JavaScript
/* Copyright(c) 2010 Sencha Inc. licensing@sencha.com http://www.sencha.com/touchlicense */ if (typeof Ext === "undefined") { Ext = {}; } Ext.apply = (function() { for(var key in {valueOf:1}) { return function(object, config, defaults) { if (defaults) { Ext.apply(object, defaults); } if (object && config && typeof config === 'object') { for (var key in config) { object[key] = config[key]; } } return object; }; } return function(object, config, defaults) { if (defaults) { Ext.apply(object, defaults); } if (object && config && typeof config === 'object') { for (var key in config) { object[key] = config[key]; } if (config.toString !== Object.prototype.toString) { object.toString = config.toString; } if (config.valueOf !== Object.prototype.valueOf) { object.valueOf = config.valueOf; } } return object; }; })(); Ext.apply(Ext, { platformVersion: '1.0', platformVersionDetail: { major: 1, minor: 0, patch: 2 }, userAgent: navigator.userAgent.toLowerCase(), cache: {}, idSeed: 1000, BLANK_IMAGE_URL : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', isStrict: document.compatMode == "CSS1Compat", windowId: 'ext-window', documentId: 'ext-document', emptyFn : function() {}, isSecure : /^https/i.test(window.location.protocol), isReady : false, enableGarbageCollector : true, enableListenerCollection : true, applyIf : function(object, config) { var property, undefined; if (object) { for (property in config) { if (object[property] === undefined) { object[property] = config[property]; } } } return object; }, repaint : function() { var mask = Ext.getBody().createChild({ cls: 'x-mask x-mask-transparent' }); setTimeout(function() { mask.remove(); }, 0); }, id : function(el, prefix) { el = Ext.getDom(el) || {}; if (el === document) { el.id = this.documentId; } else if (el === window) { el.id = this.windowId; } el.id = el.id || ((prefix || 'ext-gen') + (++Ext.idSeed)); return el.id; }, extend : function() { var inlineOverrides = function(o){ for (var m in o) { if (!o.hasOwnProperty(m)) { continue; } this[m] = o[m]; } }; var objectConstructor = Object.prototype.constructor; return function(subclass, superclass, overrides){ if (Ext.isObject(superclass)) { overrides = superclass; superclass = subclass; subclass = overrides.constructor != objectConstructor ? overrides.constructor : function(){ superclass.apply(this, arguments); }; } if (!superclass) { throw "Attempting to extend from a class which has not been loaded on the page."; } var F = function(){}, subclassProto, superclassProto = superclass.prototype; F.prototype = superclassProto; subclassProto = subclass.prototype = new F(); subclassProto.constructor = subclass; subclass.superclass = superclassProto; if(superclassProto.constructor == objectConstructor){ superclassProto.constructor = superclass; } subclass.override = function(overrides){ Ext.override(subclass, overrides); }; subclassProto.superclass = subclassProto.supr = (function(){ return superclassProto; }); subclassProto.override = inlineOverrides; subclassProto.proto = subclassProto; subclass.override(overrides); subclass.extend = function(o) { return Ext.extend(subclass, o); }; return subclass; }; }(), override : function(origclass, overrides) { Ext.apply(origclass.prototype, overrides); }, namespace : function() { var ln = arguments.length, i, value, split, x, xln, parts, object; for (i = 0; i < ln; i++) { value = arguments[i]; parts = value.split("."); if (window.Ext) { object = window[parts[0]] = Object(window[parts[0]]); } else { object = arguments.callee.caller.arguments[0]; } for (x = 1, xln = parts.length; x < xln; x++) { object = object[parts[x]] = Object(object[parts[x]]); } } return object; }, urlEncode : function(o, pre) { var empty, buf = [], e = encodeURIComponent; Ext.iterate(o, function(key, item){ empty = Ext.isEmpty(item); Ext.each(empty ? key : item, function(val){ buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : ''); }); }); if(!pre){ buf.shift(); pre = ''; } return pre + buf.join(''); }, urlDecode : function(string, overwrite) { if (Ext.isEmpty(string)) { return {}; } var obj = {}, pairs = string.split('&'), d = decodeURIComponent, name, value; Ext.each(pairs, function(pair) { pair = pair.split('='); name = d(pair[0]); value = d(pair[1]); obj[name] = overwrite || !obj[name] ? value : [].concat(obj[name]).concat(value); }); return obj; }, htmlEncode : function(value) { return Ext.util.Format.htmlEncode(value); }, htmlDecode : function(value) { return Ext.util.Format.htmlDecode(value); }, urlAppend : function(url, s) { if (!Ext.isEmpty(s)) { return url + (url.indexOf('?') === -1 ? '?' : '&') + s; } return url; }, toArray : function(array, start, end) { return Array.prototype.slice.call(array, start || 0, end || array.length); }, each : function(array, fn, scope) { if (Ext.isEmpty(array, true)) { return 0; } if (!Ext.isIterable(array) || Ext.isPrimitive(array)) { array = [array]; } for (var i = 0, len = array.length; i < len; i++) { if (fn.call(scope || array[i], array[i], i, array) === false) { return i; } } return true; }, iterate : function(obj, fn, scope) { if (Ext.isEmpty(obj)) { return; } if (Ext.isIterable(obj)) { Ext.each(obj, fn, scope); return; } else if (Ext.isObject(obj)) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (fn.call(scope || obj, prop, obj[prop], obj) === false) { return; } } } } }, pluck : function(arr, prop) { var ret = []; Ext.each(arr, function(v) { ret.push(v[prop]); }); return ret; }, getBody : function() { return Ext.get(document.body || false); }, getHead : function() { var head; return function() { if (head == undefined) { head = Ext.get(DOC.getElementsByTagName("head")[0]); } return head; }; }(), getDoc : function() { return Ext.get(document); }, getCmp : function(id) { return Ext.ComponentMgr.get(id); }, getOrientation: function() { return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape'; }, isIterable : function(v) { if (!v) { return false; } if (Ext.isArray(v) || v.callee) { return true; } if (/NodeList|HTMLCollection/.test(Object.prototype.toString.call(v))) { return true; } return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length)) || false; }, num : function(v, defaultValue) { v = Number(Ext.isEmpty(v) || Ext.isArray(v) || typeof v == 'boolean' || (typeof v == 'string' && Ext.util.Format.trim(v).length == 0) ? NaN : v); return isNaN(v) ? defaultValue : v; }, isEmpty : function(value, allowBlank) { var isNull = value == null, emptyArray = (Ext.isArray(value) && !value.length), blankAllowed = !allowBlank ? value === '' : false; return isNull || emptyArray || blankAllowed; }, isArray : function(v) { return Object.prototype.toString.apply(v) === '[object Array]'; }, isDate : function(v) { return Object.prototype.toString.apply(v) === '[object Date]'; }, isObject : function(v) { return !!v && !v.tagName && Object.prototype.toString.call(v) === '[object Object]'; }, isPrimitive : function(v) { return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v); }, isFunction : function(v) { return Object.prototype.toString.apply(v) === '[object Function]'; }, isNumber : function(v) { return Object.prototype.toString.apply(v) === '[object Number]' && isFinite(v); }, isString : function(v) { return typeof v === 'string'; }, isBoolean : function(v) { return Object.prototype.toString.apply(v) === '[object Boolean]'; }, isElement : function(v) { return v ? !!v.tagName : false; }, isDefined : function(v){ return typeof v !== 'undefined'; }, destroy : function() { var ln = arguments.length, i, arg; for (i = 0; i < ln; i++) { arg = arguments[i]; if (arg) { if (Ext.isArray(arg)) { this.destroy.apply(this, arg); } else if (Ext.isFunction(arg.destroy)) { arg.destroy(); } else if (arg.dom) { arg.remove(); } } } } }); Ext.SSL_SECURE_URL = Ext.isSecure && 'about:blank'; Ext.ns = Ext.namespace; Ext.ns( 'Ext.util', 'Ext.data', 'Ext.list', 'Ext.form', 'Ext.menu', 'Ext.state', 'Ext.layout', 'Ext.app', 'Ext.ux', 'Ext.plugins', 'Ext.direct', 'Ext.lib', 'Ext.gesture' ); Ext.util.Observable = Ext.extend(Object, { isObservable: true, constructor: function(config) { var me = this; Ext.apply(me, config); if (me.listeners) { me.on(me.listeners); delete me.listeners; } me.events = me.events || {}; if (this.bubbleEvents) { this.enableBubble(this.bubbleEvents); } }, eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal)$/, addManagedListener : function(item, ename, fn, scope, options) { var me = this, managedListeners = me.managedListeners = me.managedListeners || [], config; if (Ext.isObject(ename)) { options = ename; for (ename in options) { if (!options.hasOwnProperty(ename)) { continue; } config = options[ename]; if (!me.eventOptionsRe.test(ename)) { me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options); } } } else { managedListeners.push({ item: item, ename: ename, fn: fn, scope: scope, options: options }); item.on(ename, fn, scope, options); } }, removeManagedListener : function(item, ename, fn, scope) { var me = this, o, config, managedListeners, managedListener, length, i; if (Ext.isObject(ename)) { o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.removeManagedListener(item, ename, config.fn || config, config.scope || o.scope); } } } managedListeners = this.managedListeners ? this.managedListeners.slice() : []; length = managedListeners.length; for (i = 0; i < length; i++) { managedListener = managedListeners[i]; if (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope)) { this.managedListeners.remove(managedListener); item.un(managedListener.ename, managedListener.fn, managedListener.scope); } } }, fireEvent: function() { var me = this, a = Ext.toArray(arguments), ename = a[0].toLowerCase(), ret = true, ev = me.events[ename], queue = me.eventQueue, parent; if (me.eventsSuspended === true) { if (queue) { queue.push(a); } return false; } else if (ev && Ext.isObject(ev) && ev.bubble) { if (ev.fire.apply(ev, a.slice(1)) === false) { return false; } parent = me.getBubbleTarget && me.getBubbleTarget(); if (parent && parent.isObservable) { if (!parent.events[ename] || !Ext.isObject(parent.events[ename]) || !parent.events[ename].bubble) { parent.enableBubble(ename); } return parent.fireEvent.apply(parent, a); } } else if (ev && Ext.isObject(ev)) { a.shift(); ret = ev.fire.apply(ev, a); } return ret; }, addListener: function(ename, fn, scope, o) { var me = this, config, ev; if (Ext.isObject(ename)) { o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.addListener(ename, config.fn || config, config.scope || o.scope, config.fn ? config : o); } } } else { ename = ename.toLowerCase(); me.events[ename] = me.events[ename] || true; ev = me.events[ename] || true; if (Ext.isBoolean(ev)) { me.events[ename] = ev = new Ext.util.Event(me, ename); } ev.addListener(fn, scope, Ext.isObject(o) ? o: {}); } }, removeListener: function(ename, fn, scope) { var me = this, config, ev; if (Ext.isObject(ename)) { var o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.removeListener(ename, config.fn || config, config.scope || o.scope); } } } else { ename = ename.toLowerCase(); ev = me.events[ename]; if (ev.isEvent) { ev.removeListener(fn, scope); } } }, clearListeners: function() { var events = this.events, ev, key; for (key in events) { if (!events.hasOwnProperty(key)) { continue; } ev = events[key]; if (ev.isEvent) { ev.clearListeners(); } } this.clearManagedListeners(); }, purgeListeners : function() { console.warn('MixedCollection: purgeListeners has been deprecated. Please use clearListeners.'); return this.clearListeners.apply(this, arguments); }, clearManagedListeners : function() { var managedListeners = this.managedListeners || [], ln = managedListeners.length, i, managedListener; for (i = 0; i < ln; i++) { managedListener = managedListeners[i]; managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope); } this.managedListener = []; }, purgeManagedListeners : function() { console.warn('MixedCollection: purgeManagedListeners has been deprecated. Please use clearManagedListeners.'); return this.clearManagedListeners.apply(this, arguments); }, addEvents: function(o) { var me = this; me.events = me.events || {}; if (Ext.isString(o)) { var a = arguments, i = a.length; while (i--) { me.events[a[i]] = me.events[a[i]] || true; } } else { Ext.applyIf(me.events, o); } }, hasListener: function(ename) { var e = this.events[ename]; return e.isEvent === true && e.listeners.length > 0; }, suspendEvents: function(queueSuspended) { this.eventsSuspended = true; if (queueSuspended && !this.eventQueue) { this.eventQueue = []; } }, resumeEvents: function() { var me = this, queued = me.eventQueue || []; me.eventsSuspended = false; delete me.eventQueue; Ext.each(queued, function(e) { me.fireEvent.apply(me, e); }); }, relayEvents : function(origin, events, prefix) { prefix = prefix || ''; var me = this, len = events.length, i, ename; function createHandler(ename){ return function(){ return me.fireEvent.apply(me, [prefix + ename].concat(Array.prototype.slice.call(arguments, 0, -1))); }; } for(i = 0, len = events.length; i < len; i++){ ename = events[i].substr(prefix.length); me.events[ename] = me.events[ename] || true; origin.on(ename, createHandler(ename), me); } }, enableBubble: function(events) { var me = this; if (!Ext.isEmpty(events)) { events = Ext.isArray(events) ? events: Ext.toArray(arguments); Ext.each(events, function(ename) { ename = ename.toLowerCase(); var ce = me.events[ename] || true; if (Ext.isBoolean(ce)) { ce = new Ext.util.Event(me, ename); me.events[ename] = ce; } ce.bubble = true; }); } } }); Ext.override(Ext.util.Observable, { on: Ext.util.Observable.prototype.addListener, un: Ext.util.Observable.prototype.removeListener, mon: Ext.util.Observable.prototype.addManagedListener, mun: Ext.util.Observable.prototype.removeManagedListener }); Ext.util.Observable.releaseCapture = function(o) { o.fireEvent = Ext.util.Observable.prototype.fireEvent; }; Ext.util.Observable.capture = function(o, fn, scope) { o.fireEvent = Ext.createInterceptor(o.fireEvent, fn, scope); }; Ext.util.Observable.observe = function(cls, listeners) { if (cls) { if (!cls.isObservable) { Ext.applyIf(cls, new Ext.util.Observable()); Ext.util.Observable.capture(cls.prototype, cls.fireEvent, cls); } if (typeof listeners == 'object') { cls.on(listeners); } return cls; } }; Ext.util.Observable.observeClass = Ext.util.Observable.observe; Ext.util.Event = Ext.extend(Object, (function() { function createBuffered(handler, listener, o, scope) { listener.task = new Ext.util.DelayedTask(); return function() { listener.task.delay(o.buffer, handler, scope, Ext.toArray(arguments)); }; }; function createDelayed(handler, listener, o, scope) { return function() { var task = new Ext.util.DelayedTask(); if (!listener.tasks) { listener.tasks = []; } listener.tasks.push(task); task.delay(o.delay || 10, handler, scope, Ext.toArray(arguments)); }; }; function createSingle(handler, listener, o, scope) { return function() { listener.ev.removeListener(listener.fn, scope); return handler.apply(scope, arguments); }; }; return { isEvent: true, constructor: function(observable, name) { this.name = name; this.observable = observable; this.listeners = []; }, addListener: function(fn, scope, options) { var me = this, listener; scope = scope || me.observable; if (!me.isListening(fn, scope)) { listener = me.createListener(fn, scope, options); if (me.firing) { me.listeners = me.listeners.slice(0); } me.listeners.push(listener); } }, createListener: function(fn, scope, o) { o = o || {}; scope = scope || this.observable; var listener = { fn: fn, scope: scope, o: o, ev: this }, handler = fn; if (o.delay) { handler = createDelayed(handler, listener, o, scope); } if (o.buffer) { handler = createBuffered(handler, listener, o, scope); } if (o.single) { handler = createSingle(handler, listener, o, scope); } listener.fireFn = handler; return listener; }, findListener: function(fn, scope) { var listeners = this.listeners, i = listeners.length, listener, s; while (i--) { listener = listeners[i]; if (listener) { s = listener.scope; if (listener.fn == fn && (s == scope || s == this.observable)) { return i; } } } return - 1; }, isListening: function(fn, scope) { return this.findListener(fn, scope) !== -1; }, removeListener: function(fn, scope) { var me = this, index, listener, k; index = me.findListener(fn, scope); if (index != -1) { listener = me.listeners[index]; if (me.firing) { me.listeners = me.listeners.slice(0); } if (listener.task) { listener.task.cancel(); delete listener.task; } k = listener.tasks && listener.tasks.length; if (k) { while (k--) { listener.tasks[k].cancel(); } delete listener.tasks; } me.listeners.splice(index, 1); return true; } return false; }, clearListeners: function() { var listeners = this.listeners, i = listeners.length; while (i--) { this.removeListener(listeners[i].fn, listeners[i].scope); } }, fire: function() { var me = this, listeners = me.listeners, count = listeners.length, i, args, listener; if (count > 0) { me.firing = true; for (i = 0; i < count; i++) { listener = listeners[i]; args = arguments.length ? Array.prototype.slice.call(arguments, 0) : []; if (listener.o) { args.push(listener.o); } if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) { return (me.firing = false); } } } me.firing = false; return true; } }; })()); Ext.util.Stateful = Ext.extend(Ext.util.Observable, { editing : false, dirty : false, persistanceProperty: 'data', constructor: function(config) { Ext.applyIf(this, { data: {} }); this.modified = {}; this[this.persistanceProperty] = {}; Ext.util.Stateful.superclass.constructor.call(this, config); }, get: function(field) { return this[this.persistanceProperty][field]; }, set: function(fieldName, value) { var fields = this.fields, convertFields = [], field, key, i; if (arguments.length == 1 && Ext.isObject(fieldName)) { for (key in fieldName) { if (!fieldName.hasOwnProperty(key)) { continue; } field = fields.get(key); if (field && field.convert !== field.type.convert) { convertFields.push(key); continue; } this.set(key, fieldName[key]); } for (i = 0; i < convertFields.length; i++) { field = convertFields[i]; this.set(field, fieldName[field]); } } else { if (fields) { field = fields.get(fieldName); if (field && field.convert) { value = field.convert(value, this); } } this[this.persistanceProperty][fieldName] = value; this.dirty = true; if (!this.editing) { this.afterEdit(); } } }, getChanges : function(){ var modified = this.modified, changes = {}, field; for (field in modified) { if (modified.hasOwnProperty(field)){ changes[field] = this[this.persistanceProperty][field]; } } return changes; }, isModified : function(fieldName) { return !!(this.modified && this.modified.hasOwnProperty(fieldName)); }, setDirty : function() { this.dirty = true; if (!this.modified) { this.modified = {}; } this.fields.each(function(field) { this.modified[field.name] = this[this.persistanceProperty][field.name]; }, this); }, markDirty : function() { throw new Error("Stateful: markDirty has been deprecated. Please use setDirty."); }, reject : function(silent) { var modified = this.modified, field; for (field in modified) { if (!modified.hasOwnProperty(field)) { continue; } if (typeof modified[field] != "function") { this[this.persistanceProperty][field] = modified[field]; } } this.dirty = false; this.editing = false; delete this.modified; if (silent !== true) { this.afterReject(); } }, commit : function(silent) { this.dirty = false; this.editing = false; delete this.modified; if (silent !== true) { this.afterCommit(); } }, copy : function(newId) { return new this.constructor(Ext.apply({}, this[this.persistanceProperty]), newId || this.internalId); } }); Ext.util.HashMap = Ext.extend(Ext.util.Observable, { constructor: function(config) { this.addEvents( 'add', 'clear', 'remove', 'replace' ); Ext.util.HashMap.superclass.constructor.call(this, config); this.clear(true); }, getCount: function() { return this.length; }, getData: function(key, value) { if (value === undefined) { value = key; key = this.getKey(value); } return [key, value]; }, getKey: function(o) { return o.id; }, add: function(key, value) { var me = this, data; if (me.containsKey(key)) { throw new Error('This key already exists in the HashMap'); } data = this.getData(key, value); key = data[0]; value = data[1]; me.map[key] = value; ++me.length; me.fireEvent('add', me, key, value); return value; }, replace: function(key, value) { var me = this, map = me.map, old; if (!me.containsKey(key)) { me.add(key, value); } old = map[key]; map[key] = value; me.fireEvent('replace', me, key, value, old); return value; }, remove: function(o) { var key = this.findKey(o); if (key !== undefined) { return this.removeByKey(key); } return false; }, removeByKey: function(key) { var me = this, value; if (me.containsKey(key)) { value = me.map[key]; delete me.map[key]; --me.length; me.fireEvent('remove', me, key, value); return true; } return false; }, get: function(key) { return this.map[key]; }, clear: function( initial) { var me = this; me.map = {}; me.length = 0; if (initial !== true) { me.fireEvent('clear', me); } return me; }, containsKey: function(key) { return this.map[key] !== undefined; }, contains: function(value) { return this.containsKey(this.findKey(value)); }, getKeys: function() { return this.getArray(true); }, getValues: function() { return this.getArray(false); }, getArray: function(isKey) { var arr = [], key, map = this.map; for (key in map) { if (map.hasOwnProperty(key)) { arr.push(isKey ? key: map[key]); } } return arr; }, each: function(fn, scope) { var items = Ext.apply({}, this.map), key, length = this.length; scope = scope || this; for (key in items) { if (items.hasOwnProperty(key)) { if (fn.call(scope, key, items[key], length) === false) { break; } } } return this; }, clone: function() { var hash = new Ext.util.HashMap(), map = this.map, key; hash.suspendEvents(); for (key in map) { if (map.hasOwnProperty(key)) { hash.add(key, map[key]); } } hash.resumeEvents(); return hash; }, findKey: function(value) { var key, map = this.map; for (key in map) { if (map.hasOwnProperty(key) && map[key] === value) { return key; } } return undefined; } }); Ext.util.MixedCollection = function(allowFunctions, keyFn) { this.items = []; this.map = {}; this.keys = []; this.length = 0; this.addEvents( 'clear', 'add', 'replace', 'remove', 'sort' ); this.allowFunctions = allowFunctions === true; if (keyFn) { this.getKey = keyFn; } Ext.util.MixedCollection.superclass.constructor.call(this); }; Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { allowFunctions : false, add : function(key, obj){ var myObj = obj, myKey = key; if(arguments.length == 1){ myObj = myKey; myKey = this.getKey(myObj); } if(typeof myKey != 'undefined' && myKey !== null){ var old = this.map[myKey]; if(typeof old != 'undefined'){ return this.replace(myKey, myObj); } this.map[myKey] = myObj; } this.length++; this.items.push(myObj); this.keys.push(myKey); this.fireEvent('add', this.length-1, myObj, myKey); return myObj; }, getKey : function(o){ return o.id; }, replace : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } var old = this.map[key]; if(typeof key == 'undefined' || key === null || typeof old == 'undefined'){ return this.add(key, o); } var index = this.indexOfKey(key); this.items[index] = o; this.map[key] = o; this.fireEvent('replace', key, old, o); return o; }, addAll : function(objs){ if(arguments.length > 1 || Ext.isArray(objs)){ var args = arguments.length > 1 ? arguments : objs; for(var i = 0, len = args.length; i < len; i++){ this.add(args[i]); } }else{ for(var key in objs){ if (!objs.hasOwnProperty(key)) { continue; } if(this.allowFunctions || typeof objs[key] != 'function'){ this.add(key, objs[key]); } } } }, each : function(fn, scope){ var items = [].concat(this.items); for(var i = 0, len = items.length; i < len; i++){ if(fn.call(scope || items[i], items[i], i, len) === false){ break; } } }, eachKey : function(fn, scope){ for(var i = 0, len = this.keys.length; i < len; i++){ fn.call(scope || window, this.keys[i], this.items[i], i, len); } }, findBy : function(fn, scope) { for(var i = 0, len = this.items.length; i < len; i++){ if(fn.call(scope || window, this.items[i], this.keys[i])){ return this.items[i]; } } return null; }, insert : function(index, key, obj){ var myKey = key, myObj = obj; if(arguments.length == 2){ myObj = myKey; myKey = this.getKey(myObj); } if(this.containsKey(myKey)){ this.suspendEvents(); this.removeByKey(myKey); this.resumeEvents(); } if(index >= this.length){ return this.add(myKey, myObj); } this.length++; this.items.splice(index, 0, myObj); if(typeof myKey != 'undefined' && myKey !== null){ this.map[myKey] = myObj; } this.keys.splice(index, 0, myKey); this.fireEvent('add', index, myObj, myKey); return myObj; }, remove : function(o){ return this.removeAt(this.indexOf(o)); }, removeAll : function(items){ Ext.each(items || [], function(item) { this.remove(item); }, this); return this; }, removeAt : function(index){ if(index < this.length && index >= 0){ this.length--; var o = this.items[index]; this.items.splice(index, 1); var key = this.keys[index]; if(typeof key != 'undefined'){ delete this.map[key]; } this.keys.splice(index, 1); this.fireEvent('remove', o, key); return o; } return false; }, removeByKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, removeKey : function() { console.warn('MixedCollection: removeKey has been deprecated. Please use removeByKey.'); return this.removeByKey.apply(this, arguments); }, getCount : function(){ return this.length; }, indexOf : function(o){ return this.items.indexOf(o); }, indexOfKey : function(key){ return this.keys.indexOf(key); }, get : function(key) { var mk = this.map[key], item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined; return typeof item != 'function' || this.allowFunctions ? item : null; }, item : function() { console.warn('MixedCollection: item has been deprecated. Please use get.'); return this.get.apply(this, arguments); }, getAt : function(index) { return this.items[index]; }, itemAt : function() { console.warn('MixedCollection: itemAt has been deprecated. Please use getAt.'); return this.getAt.apply(this, arguments); }, getByKey : function(key) { return this.map[key]; }, key : function() { console.warn('MixedCollection: key has been deprecated. Please use getByKey.'); return this.getByKey.apply(this, arguments); }, contains : function(o){ return this.indexOf(o) != -1; }, containsKey : function(key){ return typeof this.map[key] != 'undefined'; }, clear : function(){ this.length = 0; this.items = []; this.keys = []; this.map = {}; this.fireEvent('clear'); }, first : function() { return this.items[0]; }, last : function() { return this.items[this.length-1]; }, _sort : function(property, dir, fn){ var i, len, dsc = String(dir).toUpperCase() == 'DESC' ? -1 : 1, c = [], keys = this.keys, items = this.items; fn = fn || function(a, b) { return a - b; }; for(i = 0, len = items.length; i < len; i++){ c[c.length] = { key : keys[i], value: items[i], index: i }; } c.sort(function(a, b){ var v = fn(a[property], b[property]) * dsc; if(v === 0){ v = (a.index < b.index ? -1 : 1); } return v; }); for(i = 0, len = c.length; i < len; i++){ items[i] = c[i].value; keys[i] = c[i].key; } this.fireEvent('sort', this); }, sort : function(property, direction) { var sorters = property; if (Ext.isString(property)) { sorters = [new Ext.util.Sorter({ property : property, direction: direction || "ASC" })]; } else if (property instanceof Ext.util.Sorter) { sorters = [property]; } else if (Ext.isObject(property)) { sorters = [new Ext.util.Sorter(property)]; } var length = sorters.length; if (length == 0) { return; } var sorterFn = function(r1, r2) { var result = sorters[0].sort(r1, r2), length = sorters.length, i; for (i = 1; i < length; i++) { result = result || sorters[i].sort.call(this, r1, r2); } return result; }; this.sortBy(sorterFn); }, sortBy: function(sorterFn) { var items = this.items, keys = this.keys, length = items.length, temp = [], i; for (i = 0; i < length; i++) { temp[i] = { key : keys[i], value: items[i], index: i }; } temp.sort(function(a, b) { var v = sorterFn(a.value, b.value); if (v === 0) { v = (a.index < b.index ? -1 : 1); } return v; }); for (i = 0; i < length; i++) { items[i] = temp[i].value; keys[i] = temp[i].key; } this.fireEvent('sort', this); }, reorder: function(mapping) { this.suspendEvents(); var items = this.items, index = 0, length = items.length, order = [], remaining = [], oldIndex; for (oldIndex in mapping) { order[mapping[oldIndex]] = items[oldIndex]; } for (index = 0; index < length; index++) { if (mapping[index] == undefined) { remaining.push(items[index]); } } for (index = 0; index < length; index++) { if (order[index] == undefined) { order[index] = remaining.shift(); } } this.clear(); this.addAll(order); this.resumeEvents(); this.fireEvent('sort', this); }, sortByKey : function(dir, fn){ this._sort('key', dir, fn || function(a, b){ var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase(); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }); }, keySort : function() { console.warn('MixedCollection: keySort has been deprecated. Please use sortByKey.'); return this.sortByKey.apply(this, arguments); }, getRange : function(start, end){ var items = this.items; if(items.length < 1){ return []; } start = start || 0; end = Math.min(typeof end == 'undefined' ? this.length-1 : end, this.length-1); var i, r = []; if(start <= end){ for(i = start; i <= end; i++) { r[r.length] = items[i]; } }else{ for(i = start; i >= end; i--) { r[r.length] = items[i]; } } return r; }, filter : function(property, value, anyMatch, caseSensitive) { var filters = []; if (Ext.isString(property)) { filters.push(new Ext.util.Filter({ property : property, value : value, anyMatch : anyMatch, caseSensitive: caseSensitive })); } else if (Ext.isArray(property) || property instanceof Ext.util.Filter) { filters = filters.concat(property); } var filterFn = function(record) { var isMatch = true, length = filters.length, i; for (i = 0; i < length; i++) { var filter = filters[i], fn = filter.filterFn, scope = filter.scope; isMatch = isMatch && fn.call(scope, record); } return isMatch; }; return this.filterBy(filterFn); }, filterBy : function(fn, scope) { var newMC = new Ext.util.MixedCollection(), keys = this.keys, items = this.items, length = items.length, i; newMC.getKey = this.getKey; for (i = 0; i < length; i++) { if (fn.call(scope||this, items[i], keys[i])) { newMC.add(keys[i], items[i]); } } return newMC; }, findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, findIndexBy : function(fn, scope, start){ var k = this.keys, it = this.items; for(var i = (start||0), len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } return -1; }, createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) { if (!value.exec) { var er = Ext.util.Format.escapeRegex; value = String(value); if (anyMatch === true) { value = er(value); } else { value = '^' + er(value); if (exactMatch === true) { value += '$'; } } value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; }, clone : function(){ var r = new Ext.util.MixedCollection(); var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ r.add(k[i], it[i]); } r.getKey = this.getKey; return r; } }); Ext.AbstractManager = Ext.extend(Object, { typeName: 'type', constructor: function(config) { Ext.apply(this, config || {}); this.all = new Ext.util.HashMap(); this.types = {}; }, get : function(id) { return this.all.get(id); }, register: function(item) { this.all.add(item); }, unregister: function(item) { this.all.remove(item); }, registerType : function(type, cls) { this.types[type] = cls; cls[this.typeName] = type; }, isRegistered : function(type){ return this.types[type] !== undefined; }, create: function(config, defaultType) { var type = config[this.typeName] || config.type || defaultType, Constructor = this.types[type]; if (Constructor == undefined) { throw new Error(Ext.util.Format.format("The '{0}' type has not been registered with this manager", type)); } return new Constructor(config); }, onAvailable : function(id, fn, scope){ var all = this.all; all.on("add", function(index, o){ if (o.id == id) { fn.call(scope || o, o); all.un("add", fn, scope); } }); }, each: function(fn, scope){ this.all.each(fn, scope || this); }, getCount: function(){ return this.all.getCount(); } }); Ext.util.DelayedTask = function(fn, scope, args) { var me = this, id, call = function() { clearInterval(id); id = null; fn.apply(scope, args || []); }; this.delay = function(delay, newFn, newScope, newArgs) { me.cancel(); fn = newFn || fn; scope = newScope || scope; args = newArgs || args; id = setInterval(call, delay); }; this.cancel = function(){ if (id) { clearInterval(id); id = null; } }; }; Ext.util.GeoLocation = Ext.extend(Ext.util.Observable, { autoUpdate: true, latitude: null, longitude: null, accuracy: null, altitude: null, altitudeAccuracy: null, heading: null, speed: null, timestamp: null, allowHighAccuracy: false, timeout: Infinity, maximumAge: 0, setMaximumAge: function(maximumAge) { this.maximumAge = maximumAge; this.setAutoUpdate(this.autoUpdate); }, setTimeout: function(timeout) { this.timeout = timeout; this.setAutoUpdate(this.autoUpdate); }, setAllowHighAccuracy: function(allowHighAccuracy) { this.allowHighAccuracy = allowHighAccuracy; this.setAutoUpdate(this.autoUpdate); }, provider : null, watchOperation : null, constructor : function(config) { Ext.apply(this, config); this.coords = this; //@deprecated if (Ext.supports.GeoLocation) { this.provider = this.provider || (navigator.geolocation ? navigator.geolocation : (window.google || {}).gears ? google.gears.factory.create('beta.geolocation') : null); } this.addEvents( 'update', 'locationerror', 'locationupdate' ); Ext.util.GeoLocation.superclass.constructor.call(this); if(this.autoUpdate){ var me = this; setTimeout(function(){ me.setAutoUpdate(me.autoUpdate); }, 0); } }, setAutoUpdate : function(autoUpdate) { if (this.watchOperation !== null) { this.provider.clearWatch(this.watchOperation); this.watchOperation = null; } if (!autoUpdate) { return true; } if (!Ext.supports.GeoLocation) { this.fireEvent('locationerror', this, false, false, true, null); return false; } try{ this.watchOperation = this.provider.watchPosition( Ext.createDelegate(this.fireUpdate, this), Ext.createDelegate(this.fireError, this), this.parseOptions()); } catch(e){ this.autoUpdate = false; this.fireEvent('locationerror', this, false, false, true, e.message); return false; } return true; }, updateLocation : function(callback, scope, positionOptions) { var me = this; var failFunction = function(message, error){ if(error){ me.fireError(error); } else{ me.fireEvent('locationerror', me, false, false, true, message); } if(callback){ callback.call(scope || me, null, me); } me.fireEvent('update', false, me); }; if (!Ext.supports.GeoLocation) { setTimeout(function() { failFunction(null); }, 0); return; } try{ this.provider.getCurrentPosition( function(position){ me.fireUpdate(position); if(callback){ callback.call(scope || me, me, me); } me.fireEvent('update', me, me); }, function(error){ failFunction(null, error); }, positionOptions ? positionOptions : this.parseOptions()); } catch(e){ setTimeout(function(){ failFunction(e.message); }, 0); } }, fireUpdate: function(position){ this.timestamp = position.timestamp; this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; this.accuracy = position.coords.accuracy; this.altitude = position.coords.altitude; this.altitudeAccuracy = position.coords.altitudeAccuracy; this.heading = typeof position.coords.heading == 'undefined' ? null : position.coords.heading; this.speed = typeof position.coords.speed == 'undefined' ? null : position.coords.speed; this.fireEvent('locationupdate', this); }, fireError: function(error){ this.fireEvent('locationerror', this, error.code == error.TIMEOUT, error.code == error.PERMISSION_DENIED, error.code == error.POSITION_UNAVAILABLE, error.message == undefined ? null : error.message); }, parseOptions: function(){ var ret = { maximumAge: this.maximumAge, allowHighAccuracy: this.allowHighAccuracy }; if(this.timeout !== Infinity){ ret.timeout = this.timeout; } return ret; }, getLocation : function(callback, scope) { var me = this; if(this.latitude !== null){ callback.call(scope || me, me, me); } else { me.updateLocation(callback, scope); } } }); Ext.util.Point = Ext.extend(Object, { constructor: function(x, y) { this.x = (x != null && !isNaN(x)) ? x : 0; this.y = (y != null && !isNaN(y)) ? y : 0; return this; }, copy: function() { return new Ext.util.Point(this.x, this.y); }, copyFrom: function(p) { this.x = p.x; this.y = p.y; return this; }, toString: function() { return "Point[" + this.x + "," + this.y + "]"; }, equals: function(p) { return (this.x == p.x && this.y == p.y); }, isWithin: function(p, threshold) { if (!Ext.isObject(threshold)) { threshold = {x: threshold}; threshold.y = threshold.x; } return (this.x <= p.x + threshold.x && this.x >= p.x - threshold.x && this.y <= p.y + threshold.y && this.y >= p.y - threshold.y); }, translate: function(x, y) { if (x != null && !isNaN(x)) this.x += x; if (y != null && !isNaN(y)) this.y += y; }, roundedEquals: function(p) { return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y)); } }); Ext.util.Point.fromEvent = function(e) { var a = (e.changedTouches && e.changedTouches.length > 0) ? e.changedTouches[0] : e; return new Ext.util.Point(a.pageX, a.pageY); }; Ext.util.Offset = Ext.extend(Object, { constructor: function(x, y) { this.x = (x != null && !isNaN(x)) ? x : 0; this.y = (y != null && !isNaN(y)) ? y : 0; return this; }, copy: function() { return new Ext.util.Offset(this.x, this.y); }, copyFrom: function(p) { this.x = p.x; this.y = p.y; }, toString: function() { return "Offset[" + this.x + "," + this.y + "]"; }, equals: function(offset) { if(!(offset instanceof Ext.util.Offset)) throw new Error('offset must be an instance of Ext.util.Offset'); return (this.x == offset.x && this.y == offset.y); }, round: function(to) { if (!isNaN(to)) { var factor = Math.pow(10, to); this.x = Math.round(this.x * factor) / factor; this.y = Math.round(this.y * factor) / factor; } else { this.x = Math.round(this.x); this.y = Math.round(this.y); } }, isZero: function() { return this.x == 0 && this.y == 0; } }); Ext.util.Offset.fromObject = function(obj) { return new Ext.util.Offset(obj.x, obj.y); }; Ext.util.Region = Ext.extend(Object, { constructor : function(t, r, b, l) { var me = this; me.top = t; me[1] = t; me.right = r; me.bottom = b; me.left = l; me[0] = l; }, contains : function(region) { var me = this; return (region.left >= me.left && region.right <= me.right && region.top >= me.top && region.bottom <= me.bottom); }, intersect : function(region) { var me = this, t = Math.max(me.top, region.top), r = Math.min(me.right, region.right), b = Math.min(me.bottom, region.bottom), l = Math.max(me.left, region.left); if (b > t && r > l) { return new Ext.util.Region(t, r, b, l); } else { return false; } }, union : function(region) { var me = this, t = Math.min(me.top, region.top), r = Math.max(me.right, region.right), b = Math.max(me.bottom, region.bottom), l = Math.min(me.left, region.left); return new Ext.util.Region(t, r, b, l); }, constrainTo : function(r) { var me = this, constrain = Ext.util.Numbers.constrain; me.top = constrain(me.top, r.top, r.bottom); me.bottom = constrain(me.bottom, r.top, r.bottom); me.left = constrain(me.left, r.left, r.right); me.right = constrain(me.right, r.left, r.right); return me; }, adjust : function(t, r, b, l) { var me = this; me.top += t; me.left += l; me.right += r; me.bottom += b; return me; }, getOutOfBoundOffset: function(axis, p) { if (!Ext.isObject(axis)) { if (axis == 'x') { return this.getOutOfBoundOffsetX(p); } else { return this.getOutOfBoundOffsetY(p); } } else { p = axis; var d = new Ext.util.Offset(); d.x = this.getOutOfBoundOffsetX(p.x); d.y = this.getOutOfBoundOffsetY(p.y); return d; } }, getOutOfBoundOffsetX: function(p) { if (p <= this.left) { return this.left - p; } else if (p >= this.right) { return this.right - p; } return 0; }, getOutOfBoundOffsetY: function(p) { if (p <= this.top) { return this.top - p; } else if (p >= this.bottom) { return this.bottom - p; } return 0; }, isOutOfBound: function(axis, p) { if (!Ext.isObject(axis)) { if (axis == 'x') { return this.isOutOfBoundX(p); } else { return this.isOutOfBoundY(p); } } else { p = axis; return (this.isOutOfBoundX(p.x) || this.isOutOfBoundY(p.y)); } }, isOutOfBoundX: function(p) { return (p < this.left || p > this.right); }, isOutOfBoundY: function(p) { return (p < this.top || p > this.bottom); }, restrict: function(axis, p, factor) { if (Ext.isObject(axis)) { var newP; factor = p; p = axis; if (p.copy) { newP = p.copy(); } else { newP = { x: p.x, y: p.y }; } newP.x = this.restrictX(p.x, factor); newP.y = this.restrictY(p.y, factor); return newP; } else { if (axis == 'x') { return this.restrictX(p, factor); } else { return this.restrictY(p, factor); } } }, restrictX : function(p, factor) { if (!factor) { factor = 1; } if (p <= this.left) { p -= (p - this.left) * factor; } else if (p >= this.right) { p -= (p - this.right) * factor; } return p; }, restrictY : function(p, factor) { if (!factor) { factor = 1; } if (p <= this.top) { p -= (p - this.top) * factor; } else if (p >= this.bottom) { p -= (p - this.bottom) * factor; } return p; }, getSize: function() { return { width: this.right - this.left, height: this.bottom - this.top }; }, copy: function() { return new Ext.util.Region(this.top, this.right, this.bottom, this.left); }, toString: function() { return "Region[" + this.top + "," + this.right + "," + this.bottom + "," + this.left + "]"; }, translateBy: function(offset) { this.left += offset.x; this.right += offset.x; this.top += offset.y; this.bottom += offset.y; return this; }, round: function() { this.top = Math.round(this.top); this.right = Math.round(this.right); this.bottom = Math.round(this.bottom); this.left = Math.round(this.left); return this; }, equals: function(region) { return (this.top == region.top && this.right == region.right && this.bottom == region.bottom && this.left == region.left) } }); Ext.util.Region.getRegion = function(el) { return Ext.fly(el).getPageBox(true); }; Ext.util.Region.from = function(o) { return new Ext.util.Region(o.top, o.right, o.bottom, o.left); }; Ext.Template = Ext.extend(Object, { constructor: function(html) { var me = this, args = arguments, buffer = [], value, i, length; me.initialConfig = {}; if (Ext.isArray(html)) { html = html.join(""); } else if (args.length > 1) { for (i = 0, length = args.length; i < length; i++) { value = args[i]; if (typeof value == 'object') { Ext.apply(me.initialConfig, value); Ext.apply(me, value); } else { buffer.push(value); } } html = buffer.join(''); } me.html = html; if (me.compiled) { me.compile(); } }, isTemplate: true, disableFormats: false, re: /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, applyTemplate: function(values) { var me = this, useFormat = me.disableFormats !== true, fm = Ext.util.Format, tpl = me; if (me.compiled) { return me.compiled(values); } function fn(m, name, format, args) { if (format && useFormat) { if (args) { args = [values[name]].concat(new Function('return ['+ args +'];')()); } else { args = [values[name]]; } if (format.substr(0, 5) == "this.") { return tpl[format.substr(5)].apply(tpl, args); } else { return fm[format].apply(fm, args); } } else { return values[name] !== undefined ? values[name] : ""; } } return me.html.replace(me.re, fn); }, set: function(html, compile) { var me = this; me.html = html; me.compiled = null; return compile ? me.compile() : me; }, compileARe: /\\/g, compileBRe: /(\r\n|\n)/g, compileCRe: /'/g, /** * Compiles the template into an internal function, eliminating the RegEx overhead. * @return {Ext.Template} this * @hide repeat doc */ compile: function() { var me = this, fm = Ext.util.Format, useFormat = me.disableFormats !== true, body, bodyReturn; function fn(m, name, format, args) { if (format && useFormat) { args = args ? ',' + args: ""; if (format.substr(0, 5) != "this.") { format = "fm." + format + '('; } else { format = 'this.' + format.substr(5) + '('; } } else { args = ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'," + format + "values['" + name + "']" + args + ") ,'"; } bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn); body = "this.compiled = function(values){ return ['" + bodyReturn + "'].join('');};"; eval(body); return me; }, /** * Applies the supplied values to the template and inserts the new node(s) as the first child of el. * @param {Mixed} el The context element * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ insertFirst: function(el, values, returnElement) { return this.doInsert('afterBegin', el, values, returnElement); }, /** * Applies the supplied values to the template and inserts the new node(s) before el. * @param {Mixed} el The context element * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ insertBefore: function(el, values, returnElement) { return this.doInsert('beforeBegin', el, values, returnElement); }, /** * Applies the supplied values to the template and inserts the new node(s) after el. * @param {Mixed} el The context element * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ insertAfter: function(el, values, returnElement) { return this.doInsert('afterEnd', el, values, returnElement); }, /** * Applies the supplied <code>values</code> to the template and appends * the new node(s) to the specified <code>el</code>. * <p>For example usage {@link #Template see the constructor}.</p> * @param {Mixed} el The context element * @param {Object/Array} values * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>) * or an object (i.e. <code>{foo: 'bar'}</code>). * @param {Boolean} returnElement (optional) true to return an Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ append: function(el, values, returnElement) { return this.doInsert('beforeEnd', el, values, returnElement); }, doInsert: function(where, el, values, returnEl) { el = Ext.getDom(el); var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values)); return returnEl ? Ext.get(newNode, true) : newNode; }, /** * Applies the supplied values to the template and overwrites the content of el with the new node(s). * @param {Mixed} el The context element * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ overwrite: function(el, values, returnElement) { el = Ext.getDom(el); el.innerHTML = this.applyTemplate(values); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; } }); /** * Alias for {@link #applyTemplate} * Returns an HTML fragment of this template with the specified <code>values</code> applied. * @param {Object/Array} values * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>) * or an object (i.e. <code>{foo: 'bar'}</code>). * @return {String} The HTML fragment * @member Ext.Template * @method apply */ Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; /** * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML. * @param {String/HTMLElement} el A DOM element or its id * @param {Object} config A configuration object * @return {Ext.Template} The created template * @static */ Ext.Template.from = function(el, config) { el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML, config || ''); }; /** * @class Ext.XTemplate * @extends Ext.Template * <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul> * <li>Autofilling arrays using templates and sub-templates</li> * <li>Conditional processing with basic comparison operators</li> * <li>Basic math function support</li> * <li>Execute arbitrary inline code with special built-in template variables</li> * <li>Custom member functions</li> * <li>Many special tags and built-in operators that aren't defined as part of * the API, but are supported in the templates that can be created</li> * </ul></div></p> * <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul> * <li>{@link Ext.DataView}</li> * </ul></div></p> * * The {@link Ext.Template} describes * the acceptable parameters to pass to the constructor. The following * examples demonstrate all of the supported features.</p> * * <div class="mdetail-params"><ul> * * <li><b><u>Sample Data</u></b> * <div class="sub-desc"> * <p>This is the data object used for reference in each code example:</p> * <pre><code> var data = { name: 'Tommy Maintz', title: 'Lead Developer', company: 'Ext JS, Inc', email: 'tommy@extjs.com', address: '5 Cups Drive', city: 'Palo Alto', state: 'CA', zip: '44102', drinks: ['Coffee', 'Soda', 'Water'], kids: [{ name: 'Joshua', age:3 },{ name: 'Matthew', age:2 },{ name: 'Solomon', age:0 }] }; </code></pre> * </div> * </li> * * * <li><b><u>Auto filling of arrays</u></b> * <div class="sub-desc"> * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used * to process the provided data object: * <ul> * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill, * repeating the template block inside the <tt>tpl</tt> tag for each item in the * array.</li> * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li> * <li>While processing an array, the special variable <tt>{#}</tt> * will provide the current array index + 1 (starts at 1, not 0).</li> * </ul> * </p> * <pre><code> &lt;tpl <b>for</b>=".">...&lt;/tpl> // loop through array at root node &lt;tpl <b>for</b>="foo">...&lt;/tpl> // loop through array at foo node &lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node </code></pre> * Using the sample data above: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Kids: ', '&lt;tpl <b>for</b>=".">', // process the data.kids node '&lt;p>{#}. {name}&lt;/p>', // use current array index to autonumber '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object </code></pre> * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged * to access specified members of the provided data object to populate the template:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Title: {title}&lt;/p>', '&lt;p>Company: {company}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl <b>for="kids"</b>>', // interrogate the kids property within the data '&lt;p>{name}&lt;/p>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); // pass the root node of the data object </code></pre> * <p>Flat arrays that contain values (and not objects) can be auto-rendered * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable * will represent the value of the array at the current index:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>{name}\&#39;s favorite beverages:&lt;/p>', '&lt;tpl for="drinks">', '&lt;div> - {.}&lt;/div>', '&lt;/tpl>' ); tpl.overwrite(panel.body, data); </code></pre> * <p>When processing a sub-template, for example while looping through a child array, * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', '&lt;p>{name}&lt;/p>', '&lt;p>Dad: {<b>parent</b>.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * * <li><b><u>Conditional processing with basic comparison operators</u></b> * <div class="sub-desc"> * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used * to provide conditional checks for deciding whether or not to render specific * parts of the template. Notes:<div class="sub-desc"><ul> * <li>Double quotes must be encoded if used within the conditional</li> * <li>There is no <tt>else</tt> operator &mdash; if needed, two opposite * <tt>if</tt> statements should be used.</li> * </ul></div> * <pre><code> &lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl> &lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl> &lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl> &lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl> &lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl> // no good: &lt;tpl if="name == "Tommy"">Hello&lt;/tpl> // encode &#34; if it is part of the condition, e.g. &lt;tpl if="name == &#38;quot;Tommy&#38;quot;">Hello&lt;/tpl> * </code></pre> * Using the sample data above: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', '&lt;p>{name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * * <li><b><u>Basic math support</u></b> * <div class="sub-desc"> * <p>The following basic math operators may be applied directly on numeric * data values:</p><pre> * + - * / * </pre> * For example: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', // <-- Note that the &gt; is encoded '&lt;p>{#}: {name}&lt;/p>', // <-- Auto-number each item '&lt;p>In 5 Years: {age+5}&lt;/p>', // <-- Basic math '&lt;p>Dad: {parent.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * * <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b> * <div class="sub-desc"> * <p>Anything between <code>{[ ... ]}</code> is considered code to be executed * in the scope of the template. There are some special variables available in that code: * <ul> * <li><b><tt>values</tt></b>: The values in the current scope. If you are using * scope changing sub-templates, you can change what <tt>values</tt> is.</li> * <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li> * <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the * loop you are in (1-based).</li> * <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length * of the array you are looping.</li> * </ul> * This example demonstrates basic row striping using an inline code block and the * <tt>xindex</tt> variable:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">', '{name}', '&lt;/div>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * <li><b><u>Template member functions</u></b> * <div class="sub-desc"> * <p>One or more member functions can be specified in a configuration * object passed into the XTemplate constructor for more complex processing:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="this.isGirl(name)">', '&lt;p>Girl: {name} - {age}&lt;/p>', '&lt;/tpl>', // use opposite if statement to simulate 'else' processing: '&lt;tpl if="this.isGirl(name) == false">', '&lt;p>Boy: {name} - {age}&lt;/p>', '&lt;/tpl>', '&lt;tpl if="this.isBaby(age)">', '&lt;p>{name} is a baby!&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>', { // XTemplate configuration: compiled: true, // member functions: isGirl: function(name){ return name == 'Sara Grace'; }, isBaby: function(age){ return age < 1; } } ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * </ul></div> * * @param {Mixed} config */ Ext.XTemplate = Ext.extend(Ext.Template, { argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/, nameRe: /^<tpl\b[^>]*?for="(.*?)"/, ifRe: /^<tpl\b[^>]*?if="(.*?)"/, execRe: /^<tpl\b[^>]*?exec="(.*?)"/, constructor: function() { Ext.XTemplate.superclass.constructor.apply(this, arguments); var me = this, html = me.html, argsRe = me.argsRe, nameRe = me.nameRe, ifRe = me.ifRe, execRe = me.execRe, id = 0, tpls = [], VALUES = 'values', PARENT = 'parent', XINDEX = 'xindex', XCOUNT = 'xcount', RETURN = 'return ', WITHVALUES = 'with(values){ ', m, matchName, matchIf, matchExec, exp, fn, exec, name, i; html = ['<tpl>', html, '</tpl>'].join(''); while ((m = html.match(argsRe))) { exp = null; fn = null; exec = null; matchName = m[0].match(nameRe); matchIf = m[0].match(ifRe); matchExec = m[0].match(execRe); exp = matchIf ? matchIf[1] : null; if (exp) { fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.util.Format.htmlDecode(exp) + ';}catch(e){return;}}'); } exp = matchExec ? matchExec[1] : null; if (exp) { exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.util.Format.htmlDecode(exp) + ';}'); } name = matchName ? matchName[1] : null; if (name) { if (name === '.') { name = VALUES; } else if (name === '..') { name = PARENT; } name = new Function(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}'); } tpls.push({ id: id, target: name, exec: exec, test: fn, body: m[1] || '' }); html = html.replace(m[0], '{xtpl' + id + '}'); id = id + 1; } for (i = tpls.length - 1; i >= 0; --i) { me.compileTpl(tpls[i]); } me.master = tpls[tpls.length - 1]; me.tpls = tpls; }, // @private applySubTemplate: function(id, values, parent, xindex, xcount) { var me = this, t = me.tpls[id]; return t.compiled.call(me, values, parent, xindex, xcount); }, /** * @cfg {RegExp} codeRe The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>). */ codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g, re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g, // @private compileTpl: function(tpl) { var fm = Ext.util.Format, me = this, useFormat = me.disableFormats !== true, body, bodyReturn, evaluatedFn; function fn(m, name, format, args, math) { var v; // name is what is inside the {} // Name begins with xtpl, use a Sub Template if (name.substr(0, 4) == 'xtpl') { return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'"; } // name = "." - Just use the values object. if (name == '.') { v = 'typeof values == "string" ? values : ""'; } // name = "#" - Use the xindex else if (name == '#') { v = 'xindex'; } else if (name.substr(0, 7) == "parent.") { v = name; } // name has a . in it - Use object literal notation, starting from values else if (name.indexOf('.') != -1) { v = "values." + name; } // name is a property of values else { v = "values['" + name + "']"; } if (math) { v = '(' + v + math + ')'; } if (format && useFormat) { args = args ? ',' + args : ""; if (format.substr(0, 5) != "this.") { format = "fm." + format + '('; } else { format = 'this.' + format.substr(5) + '('; } } else { args = ''; format = "(" + v + " === undefined ? '' : "; } return "'," + format + v + args + "),'"; } function codeFn(m, code) { // Single quotes get escaped when the template is compiled, however we want to undo this when running code. return "',(" + code.replace(me.compileARe, "'") + "),'"; } bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn); body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};"; eval(body); tpl.compiled = function(values, parent, xindex, xcount) { var vs, length, buffer, i; if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) { return ''; } vs = tpl.target ? tpl.target.call(me, values, parent) : values; if (!vs) { return ''; } parent = tpl.target ? values : parent; if (tpl.target && Ext.isArray(vs)) { buffer = [], length = vs.length; if (tpl.exec) { for (i = 0; i < length; i++) { buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length); tpl.exec.call(me, vs[i], parent, i + 1, length); } } else { for (i = 0; i < length; i++) { buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length); } } return buffer.join(''); } if (tpl.exec) { tpl.exec.call(me, vs, parent, xindex, xcount); } return evaluatedFn.call(me, vs, parent, xindex, xcount); } return this; }, /** * Returns an HTML fragment of this template with the specified values applied. * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @return {String} The HTML fragment */ applyTemplate: function(values) { return this.master.compiled.call(this, values, {}, 1, 1); }, /** * Compile the template to a function for optimized performance. Recommended if the template will be used frequently. * @return {Function} The compiled function */ compile: function() { return this; } }); /** * Alias for {@link #applyTemplate} * Returns an HTML fragment of this template with the specified values applied. * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @return {String} The HTML fragment * @member Ext.XTemplate * @method apply */ Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate; /** * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML. * @param {String/HTMLElement} el A DOM element or its id * @return {Ext.Template} The created template * @static */ Ext.XTemplate.from = function(el, config) { el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML, config || {}); }; Ext.util.Sorter = Ext.extend(Object, { direction: "ASC", constructor: function(config) { Ext.apply(this, config); if (this.property == undefined && this.sorterFn == undefined) { throw "A Sorter requires either a property or a sorter function"; } this.sort = this.createSortFunction(this.sorterFn || this.defaultSorterFn); }, createSortFunction: function(sorterFn) { var me = this, property = me.property, direction = me.direction, modifier = direction.toUpperCase() == "DESC" ? -1 : 1; return function(o1, o2) { return modifier * sorterFn.call(me, o1, o2); }; }, defaultSorterFn: function(o1, o2) { var v1 = this.getRoot(o1)[this.property], v2 = this.getRoot(o2)[this.property]; return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }, getRoot: function(item) { return this.root == undefined ? item : item[this.root]; } }); Ext.util.Filter = Ext.extend(Object, { anyMatch: false, exactMatch: false, caseSensitive: false, constructor: function(config) { Ext.apply(this, config); this.filter = this.filter || this.filterFn; if (this.filter == undefined) { if (this.property == undefined || this.value == undefined) { } else { this.filter = this.createFilterFn(); } this.filterFn = this.filter; } }, createFilterFn: function() { var me = this, matcher = me.createValueMatcher(), property = me.property; return function(item) { return matcher.test(me.getRoot.call(me, item)[property]); }; }, getRoot: function(item) { return this.root == undefined ? item : item[this.root]; }, createValueMatcher : function() { var me = this, value = me.value, anyMatch = me.anyMatch, exactMatch = me.exactMatch, caseSensitive = me.caseSensitive, escapeRe = Ext.util.Format.escapeRegex; if (!value.exec) { value = String(value); if (anyMatch === true) { value = escapeRe(value); } else { value = '^' + escapeRe(value); if (exactMatch === true) { value += '$'; } } value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; } }); Ext.util.Functions = { createInterceptor: function(origFn, newFn, scope, returnValue) { var method = origFn; if (!Ext.isFunction(newFn)) { return origFn; } else { return function() { var me = this, args = arguments; newFn.target = me; newFn.method = origFn; return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null; }; } }, createDelegate: function(fn, obj, args, appendArgs) { if (!Ext.isFunction(fn)) { return fn; } return function() { var callArgs = args || arguments; if (appendArgs === true) { callArgs = Array.prototype.slice.call(arguments, 0); callArgs = callArgs.concat(args); } else if (Ext.isNumber(appendArgs)) { callArgs = Array.prototype.slice.call(arguments, 0); var applyArgs = [appendArgs, 0].concat(args); Array.prototype.splice.apply(callArgs, applyArgs); } return fn.apply(obj || window, callArgs); }; }, defer: function(fn, millis, obj, args, appendArgs) { fn = Ext.util.Functions.createDelegate(fn, obj, args, appendArgs); if (millis > 0) { return setTimeout(fn, millis); } fn(); return 0; }, createSequence: function(origFn, newFn, scope) { if (!Ext.isFunction(newFn)) { return origFn; } else { return function() { var retval = origFn.apply(this || window, arguments); newFn.apply(scope || this || window, arguments); return retval; }; } } }; Ext.defer = Ext.util.Functions.defer; Ext.createInterceptor = Ext.util.Functions.createInterceptor; Ext.createSequence = Ext.util.Functions.createSequence; Ext.createDelegate = Ext.util.Functions.createDelegate; Ext.util.Date = { getElapsed: function(dateA, dateB) { return Math.abs(dateA - (dateB || new Date)); } }; Ext.util.Numbers = { toFixedBroken: (0.9).toFixed() != 1, constrain : function(number, min, max) { number = parseFloat(number); if (!isNaN(min)) { number = Math.max(number, min); } if (!isNaN(max)) { number = Math.min(number, max); } return number; }, toFixed : function(value, precision) { if(Ext.util.Numbers.toFixedBroken) { precision = precision || 0; var pow = Math.pow(10, precision); return Math.round(value * pow) / pow; } return value.toFixed(precision); } }; Ext.util.Format = { defaultDateFormat: 'm/d/Y', escapeRe: /('|\\)/g, trimRe: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, formatRe: /\{(\d+)\}/g, escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g, /** * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length * @param {String} value The string to truncate * @param {Number} length The maximum length to allow before truncating * @param {Boolean} word True to try to find a common word break * @return {String} The converted text */ ellipsis: function(value, len, word) { if (value && value.length > len) { if (word) { var vs = value.substr(0, len - 2), index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?')); if (index != -1 && index >= (len - 15)) { return vs.substr(0, index) + "..."; } } return value.substr(0, len - 3) + "..."; } return value; }, /** * Escapes the passed string for use in a regular expression * @param {String} str * @return {String} */ escapeRegex : function(s) { return s.replace(Ext.util.Format.escapeRegexRe, "\\$1"); }, /** * Escapes the passed string for ' and \ * @param {String} string The string to escape * @return {String} The escaped string * @static */ escape : function(string) { return string.replace(Ext.util.Format.escapeRe, "\\$1"); }, toggle : function(string, value, other) { return string == value ? other : value; }, trim : function(string) { return string.replace(Ext.util.Format.trimRe, ""); }, leftPad : function (val, size, ch) { var result = String(val); ch = ch || " "; while (result.length < size) { result = ch + result; } return result; }, format : function (format) { var args = Ext.toArray(arguments, 1); return format.replace(Ext.util.Format.formatRe, function(m, i) { return args[i]; }); }, htmlEncode: function(value) { return ! value ? value: String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }, htmlDecode: function(value) { return ! value ? value: String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&"); }, date: function(v, format) { if (!v) { return ""; } if (!Ext.isDate(v)) { v = new Date(Date.parse(v)); } return v.dateFormat(format || Ext.util.Format.defaultDateFormat); } }; Ext.LoadMask = Ext.extend(Ext.util.Observable, { msg : 'Loading...', msgCls : 'x-mask-loading', disabled: false, constructor : function(el, config) { this.el = Ext.get(el); Ext.apply(this, config); this.addEvents('show', 'hide'); if (this.store) { this.bindStore(this.store, true); } Ext.LoadMask.superclass.constructor.call(this); }, bindStore : function(store, initial) { if (!initial && this.store) { this.mun(this.store, { scope: this, beforeload: this.onBeforeLoad, load: this.onLoad, exception: this.onLoad }); if(!store) { this.store = null; } } if (store) { store = Ext.StoreMgr.lookup(store); this.mon(store, { scope: this, beforeload: this.onBeforeLoad, load: this.onLoad, exception: this.onLoad }); } this.store = store; if (store && store.isLoading()) { this.onBeforeLoad(); } }, disable : function() { this.disabled = true; }, enable : function() { this.disabled = false; }, isDisabled : function() { return this.disabled; }, onLoad : function() { this.el.unmask(); this.fireEvent('hide', this, this.el, this.store); }, onBeforeLoad : function() { if (!this.disabled) { this.el.mask('<div class="x-loading-spinner"><span class="x-loading-top"></span><span class="x-loading-right"></span><span class="x-loading-bottom"></span><span class="x-loading-left"></span></div><div class="x-loading-msg">' + this.msg + '</div>', this.msgCls, false); this.fireEvent('show', this, this.el, this.store); } }, show: function() { this.onBeforeLoad(); }, hide: function() { this.onLoad(); }, destroy : function() { this.hide(); this.clearListeners(); } }); Ext.applyIf(Array.prototype, { indexOf: function(o, from) { var len = this.length; from = from || 0; from += (from < 0) ? len: 0; for (; from < len; ++from) { if (this[from] === o) { return from; } } return - 1; }, remove: function(o) { var index = this.indexOf(o); if (index != -1) { this.splice(index, 1); } return this; }, contains: function(o) { return this.indexOf(o) !== -1; } }); Ext.ComponentMgr = new Ext.AbstractManager({ typeName: 'xtype', create : function(config, defaultType){ if (config.isComponent) { return config; } else { var type = config.xtype || defaultType, Class = this.types[type]; if (!Class) { throw "Attempting to create a component with an xtype that has not been registered: " + type } return new Class(config); } return config.render ? config : new (config); }, registerType : function(type, cls) { this.types[type] = cls; cls[this.typeName] = type; cls.prototype[this.typeName] = type; } }); Ext.reg = function() { return Ext.ComponentMgr.registerType.apply(Ext.ComponentMgr, arguments); }; Ext.create = function() { return Ext.ComponentMgr.create.apply(Ext.ComponentMgr, arguments); }; Ext.ComponentQuery = new function() { var cq = this, filterFnPattern = [ 'var r = [],', 'i = 0,', 'it = arguments[0],', 'l = it.length,', 'c;', 'for (; i < l; i++) {', 'c = it[i].{0};', 'if (c) {', 'r.push(c);', '}', '}', 'return r;' ].join(''), filterItems = function(items, operation) { return operation.method.apply(this, [ items ].concat(operation.args)); }, getItems = function(items, mode) { var result = [], i, ln = items.length, candidate, deep = mode != '>'; for (i = 0; i < ln; i++) { candidate = items[i]; if (candidate.getRefItems) { result = result.concat(candidate.getRefItems(deep)); } } return result; }, getAncestors = function(items) { var result = [], i, ln = items.length, candidate; for (i = 0; i < ln; i++) { candidate = items[i]; while (!!(candidate = candidate.ownerCt)) { result.push(candidate); } } return result; }, filterByXType = function(items, xtype, shallow) { if (xtype == '*') { return items.slice(); } else { var result = [], i, ln = items.length, candidate; for (i = 0; i < ln; i++) { candidate = items[i]; if (candidate.isXType(xtype, shallow)) { result.push(candidate); } } return result; } }, filterByClassName = function(items, className) { var result = [], i, ln = items.length, candidate; for (i = 0; i < ln; i++) { candidate = items[i]; if (candidate.el ? candidate.el.hasCls(className) : candidate.initCls().contains(className)) { result.push(candidate); } } return result; }, filterByAttribute = function(items, property, operator, value) { var result = [], i, ln = items.length, candidate; for (i = 0; i < ln; i++) { candidate = items[i]; if ((value === undefined) ? !!candidate[property] : (candidate[property] == value)) { result.push(candidate); } } return result; }, filterById = function(items, id) { var result = [], i, ln = items.length, candidate; for (i = 0; i < ln; i++) { candidate = items[i]; if (candidate.getItemId() == id) { result.push(candidate); } } return result; }, filterByPseudo = function(items, name, value) { return cq.pseudos[name](items, value); }, modeRe = /^(\s?([>\^])\s?|\s|$)/, tokenRe = /^(?:(#)?([\w-]+|\*)(?:\((true|false)\))?)|(?:\{([^\}]+)\})/, matchers = [{ re: /^\.([\w-]+)(?:\((true|false)\))?/, method: filterByXType },{ re: /^(?:[\[\{](?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, method: filterByAttribute }, { re: /^#([\w-]+)/, method: filterById }, { re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, method: filterByPseudo }]; cq.Query = Ext.extend(Object, { constructor: function(cfg) { cfg = cfg || {}; Ext.apply(this, cfg); }, execute : function(root) { var operations = this.operations, ln = operations.length, operation, i, workingItems; if (!root) { workingItems = Ext.ComponentMgr.all.items.slice(); } for (i = 0; i < ln; i++) { operation = operations[i]; if (operation.mode == '^') { workingItems = getAncestors(workingItems || [root]); } else if (operation.mode) { workingItems = getItems(workingItems || [root], operation.mode); } else { workingItems = filterItems(workingItems || getItems([root]), operation); } if (i == ln -1) { return workingItems; } } return []; }, is: function(component) { var operations = this.operations, ln = operations.length, i, workingItems = Ext.isArray(component) ? component : [ component ]; for (i = 0; i < ln && workingItems.length; i++) { workingItems = filterItems(workingItems, operations[i]); } return workingItems.length != 0; } }); Ext.apply(this, { cache: {}, pseudos: {}, query: function(selector, root) { var selectors = selector.split(','), ln = selectors.length, i, query, results = [], noDupResults = [], dupMatcher = {}, resultsLn, cmp; for (i = 0; i < ln; i++) { selector = Ext.util.Format.trim(selectors[i]); query = this.cache[selector]; if (!query) { this.cache[selector] = query = this.parse(selector); } results = results.concat(query.execute(root)); } if (ln > 1) { resultsLn = results.length; for (i = 0; i < resultsLn; i++) { cmp = results[i]; if (!dupMatcher[cmp.id]) { noDupResults.push(cmp); dupMatcher[cmp.id] = true; } } results = noDupResults; } return results; }, is: function(component, selector) { if (!selector) { return true; } var query = this.cache[selector]; if (!query) { this.cache[selector] = query = this.parse(selector); } return query.is(component); }, parse: function(selector) { var operations = [], ln = matchers.length, lastSelector, tokenMatch, matchedChar, modeMatch, selectorMatch, args, i, matcher; while (selector && lastSelector != selector) { lastSelector = selector; tokenMatch = selector.match(tokenRe); if (tokenMatch) { matchedChar = tokenMatch[1]; if (matchedChar == '#') { operations.push({ method: filterById, args: [Ext.util.Format.trim(tokenMatch[2])] }); } else if (matchedChar == '.') { operations.push({ method: filterByClassName, args: [Ext.util.Format.trim(tokenMatch[2])] }); } else if (tokenMatch[4]) { operations.push({ method: new Function(Ext.util.Format.format(filterFnPattern, tokenMatch[4])), args: [] }); } else { operations.push({ method: filterByXType, args: [Ext.util.Format.trim(tokenMatch[2]), Boolean(tokenMatch[3])] }); } selector = selector.replace(tokenMatch[0], ''); } while (!(modeMatch = selector.match(modeRe))) { for (i = 0; selector && i < ln; i++) { matcher = matchers[i]; selectorMatch = selector.match(matcher.re); if (selectorMatch) { operations.push({ method: matcher.method, args: selectorMatch.splice(1) }); selector = selector.replace(selectorMatch[0], ''); break; } if (i == (ln - 1)) { throw "Invalid ComponentQuery selector: \"" + arguments[0] + "\""; } } } if (modeMatch[1]) { operations.push({ mode: modeMatch[2]||modeMatch[1] }); selector = selector.replace(modeMatch[0], ''); } } return new cq.Query({ operations: operations }); } }); }; Ext.PluginMgr = new Ext.AbstractManager({ typeName: 'ptype', create : function(config, defaultType){ var PluginCls = this.types[config.ptype || defaultType]; if (PluginCls.init) { return PluginCls; } else { return new PluginCls(config); } }, findByType: function(type, defaultsOnly) { var matches = [], types = this.types; for (var name in types) { if (!types.hasOwnProperty(name)) { continue; } var item = types[name]; if (item.type == type && (!defaultsOnly || (defaultsOnly === true && item.isDefault))) { matches.push(item); } } return matches; } }); Ext.preg = function() { return Ext.PluginMgr.registerType.apply(Ext.PluginMgr, arguments); }; Ext.EventManager = { optionsRe: /^(?:capture|scope|delay|buffer|single|stopEvent|disableLocking|preventDefault|stopPropagation|normalized|args|delegate|horizontal|vertical|dragThreshold|holdThreshold|doubleTapThreshold|cancelThreshold|singleTapThreshold|fireClickEvent)$/, touchRe: /^(?:pinch|pinchstart|pinchend|tap|singletap|doubletap|swipe|swipeleft|swiperight|drag|dragstart|dragend|touchdown|touchstart|touchmove|touchend|taphold|tapstart|tapcancel)$/i, addListener : function(element, eventName, fn, scope, o){ if (Ext.isObject(eventName)) { this.handleListenerConfig(element, eventName); return; } var dom = Ext.getDom(element); if (!dom){ throw "Error listening for \"" + eventName + '\". Element "' + element + '" doesn\'t exist.'; } if (!fn) { throw 'Error listening for "' + eventName + '". No handler function specified'; } var touch = this.touchRe.test(eventName); var wrap = this.createListenerWrap(dom, eventName, fn, scope, o, touch); this.getEventListenerCache(dom, eventName).push({ fn: fn, wrap: wrap, scope: scope }); if (touch) { Ext.gesture.Manager.addEventListener(dom, eventName, wrap, o); } else { o = o || {}; dom.addEventListener(eventName, wrap, o.capture || false); } }, removeListener : function(element, eventName, fn, scope) { if (Ext.isObject(eventName)) { this.handleListenerConfig(element, eventName, true); return; } var dom = Ext.getDom(element), cache = this.getEventListenerCache(dom, eventName), i = cache.length, j, listener, wrap, tasks; while (i--) { listener = cache[i]; if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) { wrap = listener.wrap; if (wrap.task) { clearTimeout(wrap.task); delete wrap.task; } j = wrap.tasks && wrap.tasks.length; if (j) { while (j--) { clearTimeout(wrap.tasks[j]); } delete wrap.tasks; } if (this.touchRe.test(eventName)) { Ext.gesture.Manager.removeEventListener(dom, eventName, wrap); } else { dom.removeEventListener(eventName, wrap, false); } cache.splice(i, 1); } } }, removeAll : function(element){ var dom = Ext.getDom(element), cache = this.getElementEventCache(dom), ev; for (ev in cache) { if (!cache.hasOwnProperty(ev)) { continue; } this.removeListener(dom, ev); } Ext.cache[dom.id].events = {}; }, purgeElement : function(element, recurse, eventName) { var dom = Ext.getDom(element), i = 0, len; if(eventName) { this.removeListener(dom, eventName); } else { this.removeAll(dom); } if(recurse && dom && dom.childNodes) { for(len = element.childNodes.length; i < len; i++) { this.purgeElement(element.childNodes[i], recurse, eventName); } } }, handleListenerConfig : function(element, config, remove) { var key, value; for (key in config) { if (!config.hasOwnProperty(key)) { continue; } if (!this.optionsRe.test(key)) { value = config[key]; if (Ext.isFunction(value)) { this[(remove ? 'remove' : 'add') + 'Listener'](element, key, value, config.scope, config); } else { this[(remove ? 'remove' : 'add') + 'Listener'](element, key, config.fn, config.scope, config); } } } }, getId : function(element) { var skip = false, id; element = Ext.getDom(element); if (element === document || element === window) { skip = true; } id = Ext.id(element); if (!Ext.cache[id]){ Ext.Element.addToCache(new Ext.Element(element), id); if(skip){ Ext.cache[id].skipGarbageCollection = true; } } return id; }, createListenerWrap : function(dom, ename, fn, scope, o, touch) { o = !Ext.isObject(o) ? {} : o; var f = ["if(!window.Ext) {return;}"]; if (touch) { f.push('e = new Ext.TouchEventObjectImpl(e, args);'); } else { if(o.buffer || o.delay) { f.push('e = new Ext.EventObjectImpl(e);'); } else { f.push('e = Ext.EventObject.setEvent(e);'); } } if (o.delegate) { f.push('var t = e.getTarget("' + o.delegate + '", this);'); f.push('if(!t) {return;}'); } else { f.push('var t = e.target;'); } if (o.target) { f.push('if(e.target !== o.target) {return;}'); } if(o.stopEvent) { f.push('e.stopEvent();'); } else { if(o.preventDefault) { f.push('e.preventDefault();'); } if(o.stopPropagation) { f.push('e.stopPropagation();'); } } if(o.normalized === false) { f.push('e = e.browserEvent;'); } if(o.buffer) { f.push('(wrap.task && clearTimeout(wrap.task));'); f.push('wrap.task = setTimeout(function(){'); } if(o.delay) { f.push('wrap.tasks = wrap.tasks || [];'); f.push('wrap.tasks.push(setTimeout(function(){'); } f.push('fn.call(scope || dom, e, t, o);'); if(o.single) { f.push('Ext.EventManager.removeListener(dom, ename, fn, scope);'); } if(o.delay) { f.push('}, ' + o.delay + '));'); } if(o.buffer) { f.push('}, ' + o.buffer + ');'); } var gen = new Function('e', 'o', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', f.join("\n")); return function(e, args) { gen.call(dom, e, o, fn, scope, ename, dom, arguments.callee, args); }; }, getEventListenerCache : function(element, eventName) { var eventCache = this.getElementEventCache(element); return eventCache[eventName] || (eventCache[eventName] = []); }, getElementEventCache : function(element) { var elementCache = Ext.cache[this.getId(element)]; return elementCache.events || (elementCache.events = {}); }, onDocumentReady : function(fn, scope, options){ var me = this, readyEvent = me.readyEvent, intervalId; if(Ext.isReady){ readyEvent || (readyEvent = new Ext.util.Event()); readyEvent.addListener(fn, scope, options); readyEvent.fire(); readyEvent.listeners = []; } else { if(!readyEvent) { readyEvent = me.readyEvent = new Ext.util.Event(); var fireReady = function() { Ext.isReady = true; window.removeEventListener('load', arguments.callee, false); if (intervalId) { clearInterval(intervalId); } setTimeout(function() { Ext.supports.init(); Ext.gesture.Manager.init(); Ext.orientation = Ext.Element.getOrientation(); readyEvent.fire({ orientation: Ext.orientation, width: Ext.Element.getViewportWidth(), height: Ext.Element.getViewportHeight() }); readyEvent.listeners = []; }, 50); }; intervalId = setInterval(function(){ if(/loaded|complete/.test(document.readyState)) { clearInterval(intervalId); intervalId = null; fireReady(); } }, 10); window.addEventListener('load', fireReady, false); } options = options || {}; options.delay = options.delay || 1; readyEvent.addListener(fn, scope, options); } }, onWindowResize : function(fn, scope, options) { var me = this, resizeEvent = me.resizeEvent; if(!resizeEvent){ me.resizeEvent = resizeEvent = new Ext.util.Event(); var onResize = function() { resizeEvent.fire(Ext.Element.getViewportWidth(), Ext.Element.getViewportHeight()); }; this.addListener(window, 'resize', onResize, this); } resizeEvent.addListener(fn, scope, options); }, onOrientationChange : function(fn, scope, options) { var me = this, orientationEvent = me.orientationEvent; if (!orientationEvent) { me.orientationEvent = orientationEvent = new Ext.util.Event(); var onOrientationChange = function(viewport, size) { Ext.orientation = Ext.Viewport.getOrientation(); orientationEvent.fire(Ext.orientation, size.width, size.height); }; Ext.Viewport.on('resize', onOrientationChange, this); } orientationEvent.addListener(fn, scope, options); }, unOrientationChange : function(fn, scope, options) { var me = this, orientationEvent = me.orientationEvent; if (orientationEvent) { orientationEvent.removeListener(fn, scope, options); } } }; Ext.EventManager.on = Ext.EventManager.addListener; Ext.EventManager.un = Ext.EventManager.removeListener; Ext.onReady = Ext.EventManager.onDocumentReady; Ext.EventObjectImpl = Ext.extend(Object, { constructor : function(e) { if (e) { this.setEvent(e.browserEvent || e); } }, setEvent : function(e){ var me = this; if (e == me || (e && e.browserEvent)){ return e; } me.browserEvent = e; if(e) { me.type = e.type; var node = e.target; me.target = node && node.nodeType == 3 ? node.parentNode : node; me.xy = [e.pageX, e.pageY]; me.timestamp = e.timeStamp; } else { me.target = null; me.xy = [0, 0]; } return me; }, stopEvent : function(){ this.stopPropagation(); this.preventDefault(); }, preventDefault : function(){ if(this.browserEvent) { this.browserEvent.preventDefault(); } }, stopPropagation : function() { if(this.browserEvent) { this.browserEvent.stopPropagation(); } }, getPageX : function(){ return this.xy[0]; }, getPageY : function(){ return this.xy[1]; }, getXY : function(){ return this.xy; }, getTarget : function(selector, maxDepth, returnEl) { return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target); }, getTime : function() { return this.timestamp; } }); Ext.EventObject = new Ext.EventObjectImpl(); Ext.is = { init : function(navigator) { var platforms = this.platforms, ln = platforms.length, i, platform; navigator = navigator || window.navigator; for (i = 0; i < ln; i++) { platform = platforms[i]; this[platform.identity] = platform.regex.test(navigator[platform.property]); } this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android); this.Tablet = this.iPad; this.Phone = !this.Desktop && !this.Tablet; this.iOS = this.iPhone || this.iPad || this.iPod; this.Standalone = !!window.navigator.standalone; }, platforms: [{ property: 'platform', regex: /iPhone/i, identity: 'iPhone' }, { property: 'platform', regex: /iPod/i, identity: 'iPod' }, { property: 'userAgent', regex: /iPad/i, identity: 'iPad' }, { property: 'userAgent', regex: /Blackberry/i, identity: 'Blackberry' }, { property: 'userAgent', regex: /Android/i, identity: 'Android' }, { property: 'platform', regex: /Mac/i, identity: 'Mac' }, { property: 'platform', regex: /Win/i, identity: 'Windows' }, { property: 'platform', regex: /Linux/i, identity: 'Linux' }] }; Ext.is.init(); Ext.supports = { init : function() { var doc = document, div = doc.createElement('div'), tests = this.tests, ln = tests.length, i, test; div.innerHTML = [ '<div style="height:30px;width:50px;">', '<div style="height:20px;width:20px;"></div>', '</div>', '<div style="float:left; background-color:transparent;"></div>' ].join(''); doc.body.appendChild(div); for (i = 0; i < ln; i++) { test = tests[i]; this[test.identity] = test.fn.call(this, doc, div); } doc.body.removeChild(div); }, OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)), DeviceMotion: ('ondevicemotion' in window), Touch: ('ontouchstart' in window) && (!Ext.is.Desktop), tests: [ { identity: 'Transitions', fn: function(doc, div) { var prefix = [ 'webkit', 'Moz', 'o', 'ms', 'khtml' ], TE = 'TransitionEnd', transitionEndName = [ prefix[0] + TE, 'transitionend', prefix[2] + TE, prefix[3] + TE, prefix[4] + TE ], ln = prefix.length, i = 0, out = false; div = Ext.get(div); for (; i < ln; i++) { if (div.getStyle(prefix[i] + "TransitionProperty")) { Ext.supports.CSS3Prefix = prefix[i]; Ext.supports.CSS3TransitionEnd = transitionEndName[i]; out = true; break; } } return out; } }, { identity: 'RightMargin', fn: function(doc, div, view) { view = doc.defaultView; return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'); } }, { identity: 'TransparentColor', fn: function(doc, div, view) { view = doc.defaultView; return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent'); } }, { identity: 'SVG', fn: function(doc) { return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect; } }, { identity: 'Canvas', fn: function(doc) { return !!doc.createElement('canvas').getContext; } }, { identity: 'VML', fn: function(doc) { var d = doc.createElement("div"); d.innerHTML = "<!--[if vml]><br><br><![endif]-->"; return (d.childNodes.length == 2); } }, { identity: 'Float', fn: function(doc, div) { return !!div.lastChild.style.cssFloat; } }, { identity: 'AudioTag', fn: function(doc) { return !!doc.createElement('audio').canPlayType; } }, { identity: 'History', fn: function() { return !!(window.history && history.pushState); } }, { identity: 'CSS3DTransform', fn: function() { return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41')); } }, { identity: 'CSS3LinearGradient', fn: function(doc, div) { var property = 'background-image:', webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))', w3c = 'linear-gradient(left top, black, white)', moz = '-moz-' + w3c, options = [property + webkit, property + w3c, property + moz]; div.style.cssText = options.join(';'); return ("" + div.style.backgroundImage).indexOf('gradient') !== -1; } }, { identity: 'CSS3BorderRadius', fn: function(doc, div) { var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'], pass = false, i; for (i = 0; i < domPrefixes.length; i++) { if (document.body.style[domPrefixes[i]] !== undefined) { return pass = true; } } return pass; } }, { identity: 'GeoLocation', fn: function() { return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined'); } } ] }; Ext.data.Batch = Ext.extend(Ext.util.Observable, { autoStart: false, current: -1, total: 0, isRunning: false, isComplete: false, hasException: false, pauseOnException: true, constructor: function(config) { this.addEvents( 'complete', 'exception', 'operationcomplete', 'operation-complete' ); Ext.data.Batch.superclass.constructor.call(this, config); this.operations = []; }, add: function(operation) { this.total++; operation.setBatch(this); this.operations.push(operation); }, start: function() { this.hasException = false; this.isRunning = true; this.runNextOperation(); }, runNextOperation: function() { this.runOperation(this.current + 1); }, pause: function() { this.isRunning = false; }, runOperation: function(index) { var operations = this.operations, operation = operations[index]; if (operation == undefined) { this.isRunning = false; this.isComplete = true; this.fireEvent('complete', this, operations[operations.length - 1]); } else { this.current = index; var onProxyReturn = function(operation) { var hasException = operation.hasException(); if (hasException) { this.hasException = true; this.fireEvent('exception', this, operation); } else { this.fireEvent('operation-complete', this, operation); this.fireEvent('operationcomplete', this, operation); } if (hasException && this.pauseOnException) { this.pause(); } else { operation.setCompleted(); this.runNextOperation(); } }; operation.setStarted(); this.proxy[operation.action](operation, onProxyReturn, this); } } }); Ext.data.Model = Ext.extend(Ext.util.Stateful, { evented: false, isModel: true, phantom : false, idProperty: 'id', constructor: function(data, id) { data = data || {}; this.internalId = (id || id === 0) ? id : Ext.data.Model.id(this); Ext.data.Model.superclass.constructor.apply(this); var fields = this.fields.items, length = fields.length, field, name, i; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (data[name] == undefined) { data[name] = field.defaultValue; } } this.set(data); this.dirty = false; if (this.getId()) { this.phantom = false; } if (typeof this.init == 'function') { this.init(); } }, validate: function() { var errors = new Ext.data.Errors(), validations = this.validations, validators = Ext.data.validations, length, validation, field, valid, type, i; if (validations) { length = validations.length; for (i = 0; i < length; i++) { validation = validations[i]; field = validation.field || validation.name; type = validation.type; valid = validators[type](validation, this.get(field)); if (!valid) { errors.add({ field : field, message: validation.message || validators[type + 'Message'] }); } } } return errors; }, getProxy: function() { return this.constructor.proxy; }, save: function(options) { var me = this, action = me.phantom ? 'create' : 'update'; options = options || {}; Ext.apply(options, { records: [me], action : action }); var operation = new Ext.data.Operation(options), successFn = options.success, failureFn = options.failure, callbackFn = options.callback, scope = options.scope, record; var callback = function(operation) { record = operation.getRecords()[0]; if (operation.wasSuccessful()) { me.set(record.data); record.dirty = false; if (typeof successFn == 'function') { successFn.call(scope, record, operation); } } else { if (typeof failureFn == 'function') { failureFn.call(scope, record, operation); } } if (typeof callbackFn == 'function') { callbackFn.call(scope, record, operation); } }; me.getProxy()[action](operation, callback, me); return me; }, getId: function() { return this.get(this.idProperty); }, setId: function(id) { this.set(this.idProperty, id); }, join : function(store) { this.store = store; }, unjoin: function(store) { delete this.store; }, afterEdit : function() { this.callStore('afterEdit'); }, afterReject : function() { this.callStore("afterReject"); }, afterCommit: function() { this.callStore('afterCommit'); }, callStore: function(fn) { var store = this.store; if (store != undefined && typeof store[fn] == "function") { store[fn](this); } } }); Ext.apply(Ext.data.Model, { setProxy: function(proxy) { proxy = Ext.data.ProxyMgr.create(proxy); proxy.setModel(this); this.proxy = proxy; return proxy; }, load: function(id, config) { config = Ext.applyIf(config || {}, { action: 'read', id : id }); var operation = new Ext.data.Operation(config), callbackFn = config.callback, successFn = config.success, failureFn = config.failure, scope = config.scope, record, callback; callback = function(operation) { record = operation.getRecords()[0]; if (operation.wasSuccessful()) { if (typeof successFn == 'function') { successFn.call(scope, record, operation); } } else { if (typeof failureFn == 'function') { failureFn.call(scope, record, operation); } } if (typeof callbackFn == 'function') { callbackFn.call(scope, record, operation); } }; this.proxy.read(operation, callback, this); } }); Ext.data.Model.id = function(rec) { rec.phantom = true; return [Ext.data.Model.PREFIX, '-', Ext.data.Model.AUTO_ID++].join(''); }; Ext.ns('Ext.data.Record'); Ext.data.Record.id = Ext.data.Model.id; Ext.data.Model.PREFIX = 'ext-record'; Ext.data.Model.AUTO_ID = 1; Ext.data.Model.EDIT = 'edit'; Ext.data.Model.REJECT = 'reject'; Ext.data.Model.COMMIT = 'commit'; Ext.data.Association = Ext.extend(Object, { primaryKey: 'id', constructor: function(config) { Ext.apply(this, config); var types = Ext.ModelMgr.types, ownerName = config.ownerModel, associatedName = config.associatedModel, ownerModel = types[ownerName], associatedModel = types[associatedName], ownerProto; if (ownerModel == undefined) { throw new Error("The configured ownerModel was not valid (you tried " + ownerName + ")"); } if (associatedModel == undefined) { throw new Error("The configured associatedModel was not valid (you tried " + associatedName + ")"); } this.ownerModel = ownerModel; this.associatedModel = associatedModel; Ext.applyIf(this, { ownerName : ownerName, associatedName: associatedName }); } }); Ext.data.HasManyAssociation = Ext.extend(Ext.data.Association, { constructor: function(config) { Ext.data.HasManyAssociation.superclass.constructor.apply(this, arguments); var ownerProto = this.ownerModel.prototype, name = this.name; Ext.applyIf(this, { storeName : name + "Store", foreignKey: this.ownerName.toLowerCase() + "_id" }); ownerProto[name] = this.createStore(); }, createStore: function() { var associatedModel = this.associatedModel, storeName = this.storeName, foreignKey = this.foreignKey, primaryKey = this.primaryKey, filterProperty = this.filterProperty, storeConfig = this.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] == undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, storeConfig, { model : associatedModel, filters : [filter], remoteFilter : false, modelDefaults: modelDefaults }); me[storeName] = new Ext.data.Store(config); } return me[storeName]; }; } }); Ext.data.BelongsToAssociation = Ext.extend(Ext.data.Association, { constructor: function(config) { Ext.data.BelongsToAssociation.superclass.constructor.apply(this, arguments); var me = this, ownerProto = me.ownerModel.prototype, associatedName = me.associatedName, getterName = me.getterName || 'get' + associatedName, setterName = me.setterName || 'set' + associatedName; Ext.applyIf(me, { name : associatedName, foreignKey : associatedName.toLowerCase() + "_id", instanceName: associatedName + 'BelongsToInstance' }); ownerProto[getterName] = me.createGetter(); ownerProto[setterName] = me.createSetter(); }, createSetter: function() { var me = this, ownerModel = me.ownerModel, associatedModel = me.associatedModel, foreignKey = me.foreignKey, primaryKey = me.primaryKey; return function(value, options, scope) { this.set(foreignKey, value); if (typeof options == 'function') { options = { callback: options, scope: scope || this }; } if (Ext.isObject(options)) { return this.save(options); } }; }, createGetter: function() { var me = this, ownerModel = me.ownerModel, associatedName = me.associatedName, associatedModel = me.associatedModel, foreignKey = me.foreignKey, primaryKey = me.primaryKey, instanceName = me.instanceName; return function(options, scope) { options = options || {}; var foreignKeyId = this.get(foreignKey), instance, callbackFn; if (this[instanceName] == undefined) { instance = Ext.ModelMgr.create({}, associatedName); instance.set(primaryKey, foreignKeyId); if (typeof options == 'function') { options = { callback: options, scope: scope || this }; } associatedModel.load(foreignKeyId, options); } else { instance = this[instanceName]; if (typeof options == 'function') { options.call(scope || this, instance); } if (options.success) { options.success.call(scope || this, instance); } if (options.callback) { options.callback.call(scope || this, instance); } return instance; } }; } }); Ext.data.PolymorphicAssociation = Ext.extend(Ext.data.Association, { constructor: function(config) { Ext.data.PolymorphicAssociation.superclass.constructor.call(this, config); var ownerProto = this.ownerModel.prototype, name = this.name; Ext.applyIf(this, { associationIdField: this.ownerName.toLowerCase() + "_id" }); ownerProto[name] = this.createStore(); }, createStore: function() { var association = this, ownerName = this.ownerName, storeName = this.name + "Store", associatedModel = this.associatedModel, primaryKey = this.primaryKey, associationIdField = 'associated_id', associationModelField = 'associated_model'; return function() { var me = this, modelDefaults = {}, config, filters; if (me[storeName] == undefined) { filters = [ { property : associationIdField, value : me.get(primaryKey), exactMatch: true }, { property : associationModelField, value : ownerName, exactMatch: true } ]; modelDefaults[associationIdField] = me.get(primaryKey); modelDefaults[associationModelField] = ownerName; config = Ext.apply({}, association.storeConfig || {}, { model : associatedModel, filters : filters, remoteFilter : false, modelDefaults: modelDefaults }); me[storeName] = new Ext.data.Store(config); } return me[storeName]; }; } }); Ext.data.validations = { presenceMessage: 'must be present', lengthMessage: 'is the wrong length', formatMessage: 'is the wrong format', inclusionMessage: 'is not included in the list of acceptable values', exclusionMessage: 'is not an acceptable value', presence: function(config, value) { if (value == undefined) { value = config; } return !!value; }, length: function(config, value) { if (value == undefined) { return false; } var length = value.length, min = config.min, max = config.max; if ((min && length < min) || (max && length > max)) { return false; } else { return true; } }, format: function(config, value) { return !!(config.matcher && config.matcher.test(value)); }, inclusion: function(config, value) { return config.list && config.list.indexOf(value) != -1; }, exclusion: function(config, value) { return config.list && config.list.indexOf(value) == -1; } }; Ext.data.Errors = Ext.extend(Ext.util.MixedCollection, { isValid: function() { return this.length == 0; }, getByField: function(fieldName) { var errors = [], error, field, i; for (i = 0; i < this.length; i++) { error = this.items[i]; if (error.field == fieldName) { errors.push(error); } } return errors; } }); Ext.data.Field = Ext.extend(Object, { constructor : function(config) { if (Ext.isString(config)) { config = {name: config}; } Ext.apply(this, config); var types = Ext.data.Types, st = this.sortType, t; if (this.type) { if (Ext.isString(this.type)) { this.type = types[this.type.toUpperCase()] || types.AUTO; } } else { this.type = types.AUTO; } if (Ext.isString(st)) { this.sortType = Ext.data.SortTypes[st]; } else if(Ext.isEmpty(st)) { this.sortType = this.type.sortType; } if (!this.convert) { this.convert = this.type.convert; } }, dateFormat: null, useNull: false, defaultValue: "", mapping: null, sortType : null, sortDir : "ASC", allowBlank : true }); Ext.data.SortTypes = { none : function(s) { return s; }, stripTagsRE : /<\/?[^>]+>/gi, asText : function(s) { return String(s).replace(this.stripTagsRE, ""); }, asUCText : function(s) { return String(s).toUpperCase().replace(this.stripTagsRE, ""); }, asUCString : function(s) { return String(s).toUpperCase(); }, asDate : function(s) { if(!s){ return 0; } if(Ext.isDate(s)){ return s.getTime(); } return Date.parse(String(s)); }, asFloat : function(s) { var val = parseFloat(String(s).replace(/,/g, "")); return isNaN(val) ? 0 : val; }, asInt : function(s) { var val = parseInt(String(s).replace(/,/g, ""), 10); return isNaN(val) ? 0 : val; } }; Ext.data.Types = new function() { var st = Ext.data.SortTypes; Ext.apply(this, { stripRe: /[\$,%]/g, AUTO: { convert: function(v) { return v; }, sortType: st.none, type: 'auto' }, STRING: { convert: function(v) { return (v === undefined || v === null) ? '' : String(v); }, sortType: st.asUCString, type: 'string' }, INT: { convert: function(v) { return v !== undefined && v !== null && v !== '' ? parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); }, sortType: st.none, type: 'int' }, FLOAT: { convert: function(v) { return v !== undefined && v !== null && v !== '' ? parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); }, sortType: st.none, type: 'float' }, BOOL: { convert: function(v) { return v === true || v === 'true' || v == 1; }, sortType: st.none, type: 'bool' }, DATE: { convert: function(v) { var df = this.dateFormat; if (!v) { return null; } if (Ext.isDate(v)) { return v; } if (df) { if (df == 'timestamp') { return new Date(v*1000); } if (df == 'time') { return new Date(parseInt(v, 10)); } return Date.parseDate(v, df); } var parsed = Date.parse(v); return parsed ? new Date(parsed) : null; }, sortType: st.asDate, type: 'date' } }); Ext.apply(this, { BOOLEAN: this.BOOL, INTEGER: this.INT, NUMBER: this.FLOAT }); }; Ext.ModelMgr = new Ext.AbstractManager({ typeName: 'mtype', defaultProxyType: 'ajax', associationStack: [], registerType: function(name, config) { var PluginMgr = Ext.PluginMgr, plugins = PluginMgr.findByType('model', true), fields = config.fields || [], associations = config.associations || [], belongsTo = config.belongsTo, hasMany = config.hasMany, extendName = config.extend, modelPlugins = config.plugins || [], association, model, length, i, extendModel, extendModelProto, extendValidations, proxy; if (belongsTo) { if (!Ext.isArray(belongsTo)) { belongsTo = [belongsTo]; } for (i = 0; i < belongsTo.length; i++) { association = belongsTo[i]; if (!Ext.isObject(association)) { association = {model: association}; } Ext.apply(association, {type: 'belongsTo'}); associations.push(association); } delete config.belongsTo; } if (hasMany) { if (!Ext.isArray(hasMany)) { hasMany = [hasMany]; } for (i = 0; i < hasMany.length; i++) { association = hasMany[i]; if (!Ext.isObject(association)) { association = {model: association}; } Ext.apply(association, {type: 'hasMany'}); associations.push(association); } delete config.hasMany; } if (extendName) { extendModel = this.types[extendName]; extendModelProto = extendModel.prototype; extendValidations = extendModelProto.validations; proxy = extendModel.proxy; fields = extendModelProto.fields.items.concat(fields); associations = extendModelProto.associations.items.concat(associations); config.validations = extendValidations ? extendValidations.concat(config.validations) : config.validations; } else { extendModel = Ext.data.Model; proxy = config.proxy; } model = Ext.extend(extendModel, config); for (i = 0, length = modelPlugins.length; i < length; i++) { plugins.push(PluginMgr.create(modelPlugins[i])); } this.types[name] = model; Ext.override(model, { plugins : plugins, fields : this.createFields(fields), associations: this.createAssociations(associations, name) }); model.modelName = name; Ext.data.Model.setProxy.call(model, proxy || this.defaultProxyType); model.getProxy = model.prototype.getProxy; model.load = function() { Ext.data.Model.load.apply(this, arguments); }; for (i = 0, length = plugins.length; i < length; i++) { plugins[i].bootstrap(model, config); } model.defined = true; this.onModelDefined(model); return model; }, onModelDefined: function(model) { var stack = this.associationStack, length = stack.length, create = [], association, i; for (i = 0; i < length; i++) { association = stack[i]; if (association.associatedModel == model.modelName) { create.push(association); } } length = create.length; for (i = 0; i < length; i++) { this.addAssociation(create[i], this.types[create[i].ownerModel].prototype.associations); stack.remove(create[i]); } }, createAssociations: function(associations, name) { var length = associations.length, i, associationsMC, association; associationsMC = new Ext.util.MixedCollection(false, function(association) { return association.name; }); for (i = 0; i < length; i++) { association = associations[i]; Ext.apply(association, { ownerModel: name, associatedModel: association.model }); if (this.types[association.model] == undefined) { this.associationStack.push(association); } else { this.addAssociation(association, associationsMC); } } return associationsMC; }, addAssociation: function(association, associationsMC) { var type = association.type; if (type == 'belongsTo') { associationsMC.add(new Ext.data.BelongsToAssociation(association)); } if (type == 'hasMany') { associationsMC.add(new Ext.data.HasManyAssociation(association)); } if (type == 'polymorphic') { associationsMC.add(new Ext.data.PolymorphicAssociation(association)); } }, createFields: function(fields) { var length = fields.length, i, fieldsMC; fieldsMC = new Ext.util.MixedCollection(false, function(field) { return field.name; }); for (i = 0; i < length; i++) { fieldsMC.add(new Ext.data.Field(fields[i])); } return fieldsMC; }, getModel: function(id) { var model = id; if (typeof model == 'string') { model = this.types[model]; } return model; }, create: function(config, name, id) { var con = typeof name == 'function' ? name : this.types[name || config.name]; return new con(config, id); } }); Ext.regModel = function() { return Ext.ModelMgr.registerType.apply(Ext.ModelMgr, arguments); }; Ext.data.Operation = Ext.extend(Object, { synchronous: true, action: undefined, filters: undefined, sorters: undefined, group: undefined, start: undefined, limit: undefined, batch: undefined, started: false, running: false, complete: false, success: undefined, exception: false, error: undefined, constructor: function(config) { Ext.apply(this, config || {}); }, setStarted: function() { this.started = true; this.running = true; }, setCompleted: function() { this.complete = true; this.running = false; }, setSuccessful: function() { this.success = true; }, setException: function(error) { this.exception = true; this.success = false; this.running = false; this.error = error; }, markStarted: function() { console.warn("Operation: markStarted has been deprecated. Please use setStarted"); return this.setStarted(); }, markCompleted: function() { console.warn("Operation: markCompleted has been deprecated. Please use setCompleted"); return this.setCompleted(); }, markSuccessful: function() { console.warn("Operation: markSuccessful has been deprecated. Please use setSuccessful"); return this.setSuccessful(); }, markException: function() { console.warn("Operation: markException has been deprecated. Please use setException"); return this.setException(); }, hasException: function() { return this.exception === true; }, getError: function() { return this.error; }, getRecords: function() { var resultSet = this.getResultSet(); return (resultSet == undefined ? this.records : resultSet.records); }, getResultSet: function() { return this.resultSet; }, isStarted: function() { return this.started === true; }, isRunning: function() { return this.running === true; }, isComplete: function() { return this.complete === true; }, wasSuccessful: function() { return this.isComplete() && this.success === true; }, setBatch: function(batch) { this.batch = batch; }, allowWrite: function() { return this.action != 'read'; } }); Ext.data.ProxyMgr = new Ext.AbstractManager({ create: function(config) { if (config == undefined || typeof config == 'string') { config = { type: config }; } if (!(config instanceof Ext.data.Proxy)) { Ext.applyIf(config, { type : this.defaultProxyType, model: this.model }); var type = config[this.typeName] || config.type, Constructor = this.types[type]; if (Constructor == undefined) { throw new Error(Ext.util.Format.format("The '{0}' type has not been registered with this manager", type)); } return new Constructor(config); } else { return config; } } }); Ext.data.ReaderMgr = new Ext.AbstractManager({ typeName: 'rtype' }); Ext.data.Request = Ext.extend(Object, { action: undefined, params: undefined, method: 'GET', url: undefined, constructor: function(config) { Ext.apply(this, config); } }); Ext.data.ResultSet = Ext.extend(Object, { loaded: true, count: 0, total: 0, success: false, constructor: function(config) { Ext.apply(this, config); this.totalRecords = this.total; if (config.count == undefined) { this.count = this.records.length; } } }); Ext.data.AbstractStore = Ext.extend(Ext.util.Observable, { remoteSort : false, remoteFilter: false, autoLoad: false, autoSave: false, batchUpdateMode: 'operation', filterOnLoad: true, sortOnLoad: true, defaultSortDirection: "ASC", implicitModel: false, defaultProxyType: 'memory', isDestroyed: false, isStore: true, constructor: function(config) { this.addEvents( 'add', 'remove', 'update', 'datachanged', 'beforeload', 'load', 'beforesync' ); Ext.apply(this, config); this.removed = []; this.sortToggle = {}; Ext.data.AbstractStore.superclass.constructor.apply(this, arguments); this.model = Ext.ModelMgr.getModel(config.model); Ext.applyIf(this, { modelDefaults: {} }); if (!this.model && config.fields) { this.model = Ext.regModel('ImplicitModel-' + this.storeId || Ext.id(), { fields: config.fields }); delete this.fields; this.implicitModel = true; } this.setProxy(config.proxy || this.model.proxy); if (this.id && !this.storeId) { this.storeId = this.id; delete this.id; } if (this.storeId) { Ext.StoreMgr.register(this); } this.sorters = new Ext.util.MixedCollection(); this.sorters.addAll(this.decodeSorters(config.sorters)); this.filters = new Ext.util.MixedCollection(); this.filters.addAll(this.decodeFilters(config.filters)); }, setProxy: function(proxy) { if (proxy instanceof Ext.data.Proxy) { proxy.setModel(this.model); } else { Ext.applyIf(proxy, { model: this.model }); proxy = Ext.data.ProxyMgr.create(proxy); } this.proxy = proxy; return this.proxy; }, getProxy: function() { return this.proxy; }, create: function(data, options) { var instance = Ext.ModelMgr.create(Ext.applyIf(data, this.modelDefaults), this.model.modelName), operation; options = options || {}; Ext.applyIf(options, { action : 'create', records: [instance] }); operation = new Ext.data.Operation(options); this.proxy.create(operation, this.onProxyWrite, this); return instance; }, read: function() { return this.load.apply(this, arguments); }, onProxyRead: Ext.emptyFn, update: function(options) { options = options || {}; Ext.applyIf(options, { action : 'update', records: this.getUpdatedRecords() }); var operation = new Ext.data.Operation(options); return this.proxy.update(operation, this.onProxyWrite, this); }, onProxyWrite: Ext.emptyFn, destroy: function(options) { options = options || {}; Ext.applyIf(options, { action : 'destroy', records: this.getRemovedRecords() }); var operation = new Ext.data.Operation(options); return this.proxy.destroy(operation, this.onProxyWrite, this); }, onBatchOperationComplete: function(batch, operation) { return this.onProxyWrite(operation); }, onBatchComplete: function(batch, operation) { var operations = batch.operations, length = operations.length, i; this.suspendEvents(); for (i = 0; i < length; i++) { this.onProxyWrite(operations[i]); } this.resumeEvents(); this.fireEvent('datachanged', this); }, onBatchException: function(batch, operation) { }, filterNew: function(item) { return item.phantom == true || item.needsAdd == true; }, getNewRecords: function() { return []; }, getUpdatedRecords: function() { return []; }, filterDirty: function(item) { return item.dirty == true; }, getRemovedRecords: function() { return this.removed; }, sort: function(sorters, direction) { }, decodeSorters: function(sorters) { if (!Ext.isArray(sorters)) { if (sorters == undefined) { sorters = []; } else { sorters = [sorters]; } } var length = sorters.length, Sorter = Ext.util.Sorter, config, i; for (i = 0; i < length; i++) { config = sorters[i]; if (!(config instanceof Sorter)) { if (Ext.isString(config)) { config = { property: config }; } Ext.applyIf(config, { root : 'data', direction: "ASC" }); if (config.fn) { config.sorterFn = config.fn; } if (typeof config == 'function') { config = { sorterFn: config }; } sorters[i] = new Sorter(config); } } return sorters; }, filter: function(filters, value) { }, createSortFunction: function(field, direction) { direction = direction || "ASC"; var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1; var fields = this.model.prototype.fields, sortType = fields.get(field).sortType; return function(r1, r2) { var v1 = sortType(r1.data[field]), v2 = sortType(r2.data[field]); return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0)); }; }, decodeFilters: function(filters) { if (!Ext.isArray(filters)) { if (filters == undefined) { filters = []; } else { filters = [filters]; } } var length = filters.length, Filter = Ext.util.Filter, config, i; for (i = 0; i < length; i++) { config = filters[i]; if (!(config instanceof Filter)) { Ext.apply(config, { root: 'data' }); if (config.fn) { config.filterFn = config.fn; } if (typeof config == 'function') { config = { filterFn: config }; } filters[i] = new Filter(config); } } return filters; }, clearFilter: function(supressEvent) { }, isFiltered: function() { }, filterBy: function(fn, scope) { }, sync: function() { var me = this, options = {}, toCreate = me.getNewRecords(), toUpdate = me.getUpdatedRecords(), toDestroy = me.getRemovedRecords(), needsSync = false; if (toCreate.length > 0) { options.create = toCreate; needsSync = true; } if (toUpdate.length > 0) { options.update = toUpdate; needsSync = true; } if (toDestroy.length > 0) { options.destroy = toDestroy; needsSync = true; } if (needsSync && me.fireEvent('beforesync', options) !== false) { me.proxy.batch(options, me.getBatchListeners()); } }, getBatchListeners: function() { var listeners = { scope: this, exception: this.onBatchException }; if (this.batchUpdateMode == 'operation') { listeners['operationcomplete'] = this.onBatchOperationComplete; } else { listeners['complete'] = this.onBatchComplete; } return listeners; }, save: function() { return this.sync.apply(this, arguments); }, load: function(options) { var me = this, operation; options = options || {}; Ext.applyIf(options, { action : 'read', filters: me.filters.items, sorters: me.sorters.items }); operation = new Ext.data.Operation(options); if (me.fireEvent('beforeload', me, operation) !== false) { me.loading = true; me.proxy.read(operation, me.onProxyLoad, me); } return me; }, afterEdit : function(record) { this.fireEvent('update', this, record, Ext.data.Model.EDIT); }, afterReject : function(record) { this.fireEvent('update', this, record, Ext.data.Model.REJECT); }, afterCommit : function(record) { if (this.autoSave) { this.sync(); } this.fireEvent('update', this, record, Ext.data.Model.COMMIT); }, clearData: Ext.emptyFn, destroyStore: function() { if (!this.isDestroyed) { if (this.storeId) { Ext.StoreMgr.unregister(this); } this.clearData(); this.data = null; this.tree = null; this.reader = this.writer = null; this.clearListeners(); this.isDestroyed = true; if (this.implicitModel) { Ext.destroy(this.model); } } }, getSortState : function() { return this.sortInfo; }, getCount: function() { }, getById: function(id) { }, removeAll: function() { } }); Ext.data.Store = Ext.extend(Ext.data.AbstractStore, { remoteSort: false, remoteFilter: false, groupField: undefined, groupDir: "ASC", pageSize: 25, currentPage: 1, clearOnPageLoad: true, implicitModel: false, loading: false, sortOnFilter: true, isStore: true, constructor: function(config) { config = config || {}; this.data = new Ext.util.MixedCollection(false, function(record) { return record.internalId; }); if (config.data) { this.inlineData = config.data; delete config.data; } Ext.data.Store.superclass.constructor.call(this, config); var proxy = this.proxy, data = this.inlineData; if (data) { if (proxy instanceof Ext.data.MemoryProxy) { proxy.data = data; this.read(); } else { this.add.apply(this, data); } this.sort(); delete this.inlineData; } else if (this.autoLoad) { Ext.defer(this.load, 10, this, [typeof this.autoLoad == 'object' ? this.autoLoad : undefined]); } }, getGroups: function() { var records = this.data.items, length = records.length, groups = [], pointers = {}, record, groupStr, group, i; for (i = 0; i < length; i++) { record = records[i]; groupStr = this.getGroupString(record); group = pointers[groupStr]; if (group == undefined) { group = { name: groupStr, children: [] }; groups.push(group); pointers[groupStr] = group; } group.children.push(record); } return groups; }, getGroupString: function(instance) { return instance.get(this.groupField); }, first: function() { return this.data.first(); }, last: function() { return this.data.last(); }, insert : function(index, records) { var i, record, len; records = [].concat(records); for (i = 0, len = records.length; i < len; i++) { record = this.createModel(records[i]); record.set(this.modelDefaults); this.data.insert(index + i, record); record.join(this); } if (this.snapshot) { this.snapshot.addAll(records); } this.fireEvent('add', this, records, index); this.fireEvent('datachanged', this); }, add: function(records) { if (!Ext.isArray(records)) { records = Array.prototype.slice.apply(arguments); } var length = records.length, record, i; for (i = 0; i < length; i++) { record = this.createModel(records[i]); if (record.phantom == false) { record.needsAdd = true; } records[i] = record; } this.insert(this.data.length, records); return records; }, createModel: function(record) { if (!(record instanceof Ext.data.Model)) { record = Ext.ModelMgr.create(record, this.model); } return record; }, each : function(fn, scope) { this.data.each(fn, scope); }, remove: function(records) { if (!Ext.isArray(records)) { records = [records]; } var length = records.length, i, index, record; for (i = 0; i < length; i++) { record = records[i]; index = this.data.indexOf(record); if (index > -1) { this.removed.push(record); if (this.snapshot) { this.snapshot.remove(record); } record.unjoin(this); this.data.remove(record); this.fireEvent('remove', this, record, index); } } this.fireEvent('datachanged', this); }, removeAt: function(index) { var record = this.getAt(index); if (record) { this.remove(record); } }, load: function(options) { options = options || {}; if (Ext.isFunction(options)) { options = { callback: options }; } Ext.applyIf(options, { group : {field: this.groupField, direction: this.groupDir}, start : 0, limit : this.pageSize, addRecords: false }); return Ext.data.Store.superclass.load.call(this, options); }, isLoading: function() { return this.loading; }, onProxyLoad: function(operation) { var records = operation.getRecords(); this.loadRecords(records, operation.addRecords); this.loading = false; this.fireEvent('load', this, records, operation.wasSuccessful()); this.fireEvent('read', this, records, operation.wasSuccessful()); var callback = operation.callback; if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, onProxyWrite: function(operation) { var data = this.data, action = operation.action, records = operation.getRecords(), length = records.length, callback = operation.callback, record, i; if (operation.wasSuccessful()) { if (action == 'create' || action == 'update') { for (i = 0; i < length; i++) { record = records[i]; record.phantom = false; record.join(this); data.replace(record); } } else if (action == 'destroy') { for (i = 0; i < length; i++) { record = records[i]; record.unjoin(this); data.remove(record); } this.removed = []; } this.fireEvent('datachanged'); } if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, getNewRecords: function() { return this.data.filterBy(this.filterNew).items; }, getUpdatedRecords: function() { return this.data.filterBy(this.filterDirty).items; }, sort: function(sorters, direction) { if (Ext.isString(sorters)) { var property = sorters, sortToggle = this.sortToggle, toggle = Ext.util.Format.toggle; if (direction == undefined) { sortToggle[property] = toggle(sortToggle[property] || "", "ASC", "DESC"); direction = sortToggle[property]; } sorters = { property : property, direction: direction }; } if (arguments.length != 0) { this.sorters.clear(); } this.sorters.addAll(this.decodeSorters(sorters)); if (this.remoteSort) { this.load(); } else { this.data.sort(this.sorters.items); this.fireEvent('datachanged', this); } }, filter: function(filters, value) { if (Ext.isString(filters)) { filters = { property: filters, value : value }; } this.filters.addAll(this.decodeFilters(filters)); if (this.remoteFilter) { this.load(); } else { this.snapshot = this.snapshot || this.data.clone(); this.data = this.data.filter(this.filters.items); if (this.sortOnFilter && !this.remoteSort) { this.sort(); } else { this.fireEvent('datachanged', this); } } }, clearFilter : function(suppressEvent) { this.filters.clear(); if (this.isFiltered()) { this.data = this.snapshot.clone(); delete this.snapshot; if (suppressEvent !== true) { this.fireEvent('datachanged', this); } } }, isFiltered : function() { return !!this.snapshot && this.snapshot != this.data; }, filterBy : function(fn, scope) { this.snapshot = this.snapshot || this.data.clone(); this.data = this.queryBy(fn, scope || this); this.fireEvent('datachanged', this); }, queryBy : function(fn, scope) { var data = this.snapshot || this.data; return data.filterBy(fn, scope||this); }, loadData: function(data, append) { var model = this.model, length = data.length, i, record; for (i = 0; i < length; i++) { record = data[i]; if (!(record instanceof Ext.data.Model)) { data[i] = Ext.ModelMgr.create(record, model); } } this.loadRecords(data, append); }, loadRecords: function(records, add) { if (!add) { this.data.clear(); } this.data.addAll(records); for (var i = 0, length = records.length; i < length; i++) { records[i].needsAdd = false; records[i].join(this); } this.suspendEvents(); if (this.filterOnLoad && !this.remoteFilter) { this.filter(); } if (this.sortOnLoad && !this.remoteSort) { this.sort(); } this.resumeEvents(); this.fireEvent('datachanged', this, records); }, loadPage: function(page) { this.currentPage = page; this.read({ page : page, start: (page - 1) * this.pageSize, limit: this.pageSize, addRecords: !this.clearOnPageLoad }); }, nextPage: function() { this.loadPage(this.currentPage + 1); }, previousPage: function() { this.loadPage(this.currentPage - 1); }, clearData: function(){ this.data.each(function(record) { record.unjoin(); }); this.data.clear(); }, find : function(property, value, start, anyMatch, caseSensitive, exactMatch) { var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch); return fn ? this.data.findIndexBy(fn, null, start) : -1; }, findRecord : function() { var index = this.find.apply(this, arguments); return index != -1 ? this.getAt(index) : null; }, createFilterFn : function(property, value, anyMatch, caseSensitive, exactMatch) { if(Ext.isEmpty(value)){ return false; } value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch); return function(r) { return value.test(r.data[property]); }; }, findExact: function(property, value, start) { return this.data.findIndexBy(function(rec){ return rec.get(property) === value; }, this, start); }, findBy : function(fn, scope, start) { return this.data.findIndexBy(fn, scope, start); }, collect : function(dataIndex, allowNull, bypassFilter) { var values = [], uniques = {}, length, value, strValue, data, i; if (bypassFilter === true && this.snapshot) { data = this.snapshot.items; } else { data = this.data.items; } length = data.length; for (i = 0; i < length; i++) { value = data[i].data[dataIndex]; strValue = String(value); if ((allowNull || !Ext.isEmpty(value)) && !uniques[strValue]) { uniques[strValue] = true; values[values.length] = value; } } return values; }, sum : function(property, start, end) { var records = this.data.items, value = 0, i; start = start || 0; end = (end || end === 0) ? end : records.length - 1; for (i = start; i <= end; i++) { value += (records[i].data[property] || 0); } return value; }, getCount : function() { return this.data.length || 0; }, getAt : function(index) { return this.data.getAt(index); }, getRange : function(start, end) { return this.data.getRange(start, end); }, getById : function(id) { return (this.snapshot || this.data).findBy(function(record) { return record.getId() === id; }); }, indexOf : function(record) { return this.data.indexOf(record); }, indexOfId : function(id) { return this.data.indexOfKey(id); }, removeAll: function(silent) { var items = []; this.each(function(rec){ items.push(rec); }); this.clearData(); if(this.snapshot){ this.snapshot.clear(); } if (silent !== true) { this.fireEvent('clear', this, items); } } }); Ext.data.TreeStore = Ext.extend(Ext.data.AbstractStore, { clearOnLoad : true, nodeParam: 'node', defaultRootId: 'root', constructor: function(config) { config = config || {}; var rootCfg = config.root || {}; rootCfg.id = rootCfg.id || this.defaultRootId; var rootNode = new Ext.data.RecordNode(rootCfg); this.tree = new Ext.data.Tree(rootNode); this.tree.treeStore = this; Ext.data.TreeStore.superclass.constructor.call(this, config); if (config.root) { this.read({ node: rootNode, doPreload: true }); } }, getRootNode: function() { return this.tree.getRootNode(); }, getNodeById: function(id) { return this.tree.getNodeById(id); }, load: function(options) { options = options || {}; options.params = options.params || {}; var node = options.node || this.tree.getRootNode(), records, record, reader = this.proxy.reader, root; if (this.clearOnLoad) { while (node.firstChild){ node.removeChild(node.firstChild); } } if (!options.doPreload) { Ext.applyIf(options, { node: node }); record = node.getRecord(); options.params[this.nodeParam] = record ? record.getId() : 'root'; return Ext.data.TreeStore.superclass.load.call(this, options); } else { root = reader.getRoot(node.isRoot ? node.attributes : node.getRecord().raw); records = reader.extractData(root, true); this.fillNode(node, records); return true; } }, fillNode: function(node, records) { node.loaded = true; var ln = records.length, recordNode, i = 0, raw, subStore = node.subStore; for (; i < ln; i++) { raw = records[i].raw; records[i].data.leaf = raw.leaf; recordNode = new Ext.data.RecordNode({ id: records[i].getId(), leaf: raw.leaf, record: records[i], expanded: raw.expanded }); node.appendChild(recordNode); if (records[i].doPreload) { this.load({ node: recordNode, doPreload: true }); } } if (subStore) { if (this.clearOnLoad) { subStore.removeAll(); } subStore.add.apply(subStore, records); } }, onProxyLoad: function(operation) { var records = operation.getRecords(); this.fillNode(operation.node, records); this.fireEvent('read', this, operation.node, records, operation.wasSuccessful()); var callback = operation.callback; if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, getSubStore: function(node) { if (node && node.node) { node = node.node; } return node.getSubStore(); }, removeAll: function() { var rootNode = this.getRootNode(); rootNode.destroy(); } }); Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), { register : function() { for (var i = 0, s; (s = arguments[i]); i++) { this.add(s); } }, unregister : function() { for (var i = 0, s; (s = arguments[i]); i++) { this.remove(this.lookup(s)); } }, lookup : function(id) { if (Ext.isArray(id)) { var fields = ['field1'], expand = !Ext.isArray(id[0]); if(!expand){ for(var i = 2, len = id[0].length; i <= len; ++i){ fields.push('field' + i); } } return new Ext.data.ArrayStore({ data : id, fields: fields, expandData : expand, autoDestroy: true, autoCreated: true }); } return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id); }, getKey : function(o) { return o.storeId; } }); Ext.regStore = function(name, config) { var store; if (Ext.isObject(name)) { config = name; } else { config.storeId = name; } if (config instanceof Ext.data.Store) { store = config; } else { store = new Ext.data.Store(config); } return Ext.StoreMgr.register(store); }; Ext.getStore = function(name) { return Ext.StoreMgr.lookup(name); }; Ext.data.WriterMgr = new Ext.AbstractManager({ }); Ext.data.Tree = Ext.extend(Ext.util.Observable, { constructor: function(root) { this.nodeHash = {}; this.root = null; if (root) { this.setRootNode(root); } this.addEvents( "append", "remove", "move", "insert", "beforeappend", "beforeremove", "beforemove", "beforeinsert" ); Ext.data.Tree.superclass.constructor.call(this); }, pathSeparator: "/", proxyNodeEvent : function(){ return this.fireEvent.apply(this, arguments); }, getRootNode : function() { return this.root; }, setRootNode : function(node) { this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); return node; }, getNodeById : function(id) { return this.nodeHash[id]; }, registerNode : function(node) { this.nodeHash[node.id] = node; }, unregisterNode : function(node) { delete this.nodeHash[node.id]; }, toString : function() { return "[Tree"+(this.id?" "+this.id:"")+"]"; } }); Ext.data.Node = Ext.extend(Ext.util.Observable, { constructor: function(attributes) { this.attributes = attributes || {}; this.leaf = !!this.attributes.leaf; this.id = this.attributes.id; if (!this.id) { this.id = Ext.id(null, "xnode-"); this.attributes.id = this.id; } this.childNodes = []; this.parentNode = null; this.firstChild = null; this.lastChild = null; this.previousSibling = null; this.nextSibling = null; this.addEvents({ "append" : true, "remove" : true, "move" : true, "insert" : true, "beforeappend" : true, "beforeremove" : true, "beforemove" : true, "beforeinsert" : true }); this.listeners = this.attributes.listeners; Ext.data.Node.superclass.constructor.call(this); }, fireEvent : function(evtName) { if (Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false) { return false; } var ot = this.getOwnerTree(); if (ot) { if (ot.proxyNodeEvent.apply(ot, arguments) === false) { return false; } } return true; }, isLeaf : function() { return this.leaf === true; }, setFirstChild : function(node) { this.firstChild = node; }, setLastChild : function(node) { this.lastChild = node; }, isLast : function() { return (!this.parentNode ? true : this.parentNode.lastChild == this); }, isFirst : function() { return (!this.parentNode ? true : this.parentNode.firstChild == this); }, hasChildNodes : function() { return !this.isLeaf() && this.childNodes.length > 0; }, isExpandable : function() { return this.attributes.expandable || this.hasChildNodes(); }, appendChild : function(node) { var multi = false, i, len; if (Ext.isArray(node)) { multi = node; } else if (arguments.length > 1) { multi = arguments; } if (multi) { len = multi.length; for (i = 0; i < len; i++) { this.appendChild(multi[i]); } } else { if (this.fireEvent("beforeappend", this.ownerTree, this, node) === false) { return false; } var index = this.childNodes.length; var oldParent = node.parentNode; if (oldParent) { if (node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false) { return false; } oldParent.removeChild(node); } index = this.childNodes.length; if (index === 0) { this.setFirstChild(node); } this.childNodes.push(node); node.parentNode = this; var ps = this.childNodes[index-1]; if (ps) { node.previousSibling = ps; ps.nextSibling = node; } else { node.previousSibling = null; } node.nextSibling = null; this.setLastChild(node); node.setOwnerTree(this.getOwnerTree()); this.fireEvent("append", this.ownerTree, this, node, index); if (oldParent) { node.fireEvent("move", this.ownerTree, node, oldParent, this, index); } return node; } }, removeChild : function(node, destroy) { var index = this.indexOf(node); if (index == -1) { return false; } if (this.fireEvent("beforeremove", this.ownerTree, this, node) === false) { return false; } this.childNodes.splice(index, 1); if (node.previousSibling) { node.previousSibling.nextSibling = node.nextSibling; } if (node.nextSibling) { node.nextSibling.previousSibling = node.previousSibling; } if (this.firstChild == node) { this.setFirstChild(node.nextSibling); } if (this.lastChild == node) { this.setLastChild(node.previousSibling); } this.fireEvent("remove", this.ownerTree, this, node); if (destroy) { node.destroy(true); } else { node.clear(); } return node; }, clear : function(destroy) { this.setOwnerTree(null, destroy); this.parentNode = this.previousSibling = this.nextSibling = null; if (destroy) { this.firstChild = this.lastChild = null; } }, destroy : function(silent) { if (silent === true) { this.clearListeners(); this.clear(true); Ext.each(this.childNodes, function(n) { n.destroy(true); }); this.childNodes = null; } else { this.remove(true); } }, insertBefore : function(node, refNode) { if (!refNode) { return this.appendChild(node); } if (node == refNode) { return false; } if (this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false) { return false; } var index = this.indexOf(refNode), oldParent = node.parentNode, refIndex = index; if (oldParent == this && this.indexOf(node) < index) { refIndex--; } if (oldParent) { if (node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false) { return false; } oldParent.removeChild(node); } if (refIndex === 0) { this.setFirstChild(node); } this.childNodes.splice(refIndex, 0, node); node.parentNode = this; var ps = this.childNodes[refIndex-1]; if (ps) { node.previousSibling = ps; ps.nextSibling = node; } else { node.previousSibling = null; } node.nextSibling = refNode; refNode.previousSibling = node; node.setOwnerTree(this.getOwnerTree()); this.fireEvent("insert", this.ownerTree, this, node, refNode); if (oldParent) { node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode); } return node; }, remove : function(destroy) { var parentNode = this.parentNode; if (parentNode) { parentNode.removeChild(this, destroy); } return this; }, removeAll : function(destroy) { var cn = this.childNodes, n; while ((n = cn[0])) { this.removeChild(n, destroy); } return this; }, getChildAt : function(index) { return this.childNodes[index]; }, replaceChild : function(newChild, oldChild) { var s = oldChild ? oldChild.nextSibling : null; this.removeChild(oldChild); this.insertBefore(newChild, s); return oldChild; }, indexOf : function(child) { return this.childNodes.indexOf(child); }, getOwnerTree : function() { if (!this.ownerTree) { var p = this; while (p) { if (p.ownerTree) { this.ownerTree = p.ownerTree; break; } p = p.parentNode; } } return this.ownerTree; }, getDepth : function() { var depth = 0, p = this; while (p.parentNode) { ++depth; p = p.parentNode; } return depth; }, setOwnerTree : function(tree, destroy) { if (tree != this.ownerTree) { if (this.ownerTree) { this.ownerTree.unregisterNode(this); } this.ownerTree = tree; if (destroy !== true) { Ext.each(this.childNodes, function(n) { n.setOwnerTree(tree); }); } if (tree) { tree.registerNode(this); } } }, setId: function(id) { if (id !== this.id) { var t = this.ownerTree; if (t) { t.unregisterNode(this); } this.id = this.attributes.id = id; if (t) { t.registerNode(this); } this.onIdChange(id); } }, onIdChange: Ext.emptyFn, getPath : function(attr) { attr = attr || "id"; var p = this.parentNode, b = [this.attributes[attr]]; while (p) { b.unshift(p.attributes[attr]); p = p.parentNode; } var sep = this.getOwnerTree().pathSeparator; return sep + b.join(sep); }, bubble : function(fn, scope, args) { var p = this; while (p) { if (fn.apply(scope || p, args || [p]) === false) { break; } p = p.parentNode; } }, cascadeBy : function(fn, scope, args) { if (fn.apply(scope || this, args || [this]) !== false) { var childNodes = this.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { childNodes[i].cascadeBy(fn, scope, args); } } }, eachChild : function(fn, scope, args) { var childNodes = this.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { if (fn.apply(scope || this, args || [childNodes[i]]) === false) { break; } } }, findChild : function(attribute, value, deep) { return this.findChildBy(function(){ return this.attributes[attribute] == value; }, null, deep); }, findChildBy : function(fn, scope, deep) { var cs = this.childNodes, len = cs.length, i = 0, n, res; for(; i < len; i++){ n = cs[i]; if(fn.call(scope || n, n) === true){ return n; }else if (deep){ res = n.findChildBy(fn, scope, deep); if(res != null){ return res; } } } return null; }, sort : function(fn, scope) { var cs = this.childNodes, len = cs.length, i, n; if (len > 0) { var sortFn = scope ? function(){return fn.apply(scope, arguments);} : fn; cs.sort(sortFn); for (i = 0; i < len; i++) { n = cs[i]; n.previousSibling = cs[i-1]; n.nextSibling = cs[i+1]; if (i === 0){ this.setFirstChild(n); } if (i == len - 1) { this.setLastChild(n); } } } }, contains : function(node) { return node.isAncestor(this); }, isAncestor : function(node) { var p = this.parentNode; while (p) { if (p == node) { return true; } p = p.parentNode; } return false; }, toString : function() { return "[Node" + (this.id ? " " + this.id : "") + "]"; } }); Ext.data.RecordNode = Ext.extend(Ext.data.Node, { constructor: function(config) { config = config || {}; if (config.record) { config.record.node = this; } Ext.data.RecordNode.superclass.constructor.call(this, config); }, getChildRecords: function() { var cn = this.childNodes, ln = cn.length, i = 0, rs = [], r; for (; i < ln; i++) { r = cn[i].attributes.record; r.data.leaf = cn[i].leaf; rs.push(r); } return rs; }, getRecord: function() { return this.attributes.record; }, getSubStore: function() { if (this.isLeaf()) { throw "Attempted to get a substore of a leaf node."; } var treeStore = this.getOwnerTree().treeStore; if (!this.subStore) { this.subStore = new Ext.data.Store({ model: treeStore.model }); var children = this.getChildRecords(); this.subStore.add.apply(this.subStore, children); } if (!this.loaded) { treeStore.load({ node: this }); } return this.subStore; }, destroy : function(silent) { if (this.subStore) { this.subStore.destroyStore(); } var attr = this.attributes; if (attr.record) { delete attr.record.node; delete attr.record; } return Ext.data.RecordNode.superclass.destroy.call(this, silent); } }); Ext.data.Proxy = Ext.extend(Ext.util.Observable, { batchOrder: 'create,update,destroy', defaultReaderType: 'json', defaultWriterType: 'json', constructor: function(config) { config = config || {}; if (config.model == undefined) { delete config.model; } Ext.data.Proxy.superclass.constructor.call(this, config); if (this.model != undefined && !(this.model instanceof Ext.data.Model)) { this.setModel(this.model); } }, setModel: function(model, setOnStore) { this.model = Ext.ModelMgr.getModel(model); var reader = this.reader, writer = this.writer; this.setReader(reader); this.setWriter(writer); if (setOnStore && this.store) { this.store.setModel(this.model); } }, getModel: function() { return this.model; }, setReader: function(reader) { if (reader == undefined || typeof reader == 'string') { reader = { type: reader }; } if (reader instanceof Ext.data.Reader) { reader.setModel(this.model); } else { Ext.applyIf(reader, { proxy: this, model: this.model, type : this.defaultReaderType }); reader = Ext.data.ReaderMgr.create(reader); } this.reader = reader; return this.reader; }, getReader: function() { return this.reader; }, setWriter: function(writer) { if (writer == undefined || typeof writer == 'string') { writer = { type: writer }; } if (!(writer instanceof Ext.data.Writer)) { Ext.applyIf(writer, { model: this.model, type : this.defaultWriterType }); writer = Ext.data.WriterMgr.create(writer); } this.writer = writer; return this.writer; }, getWriter: function() { return this.writer; }, create: Ext.emptyFn, read: Ext.emptyFn, update: Ext.emptyFn, destroy: Ext.emptyFn, batch: function(operations, listeners) { var batch = new Ext.data.Batch({ proxy: this, listeners: listeners || {} }); Ext.each(this.batchOrder.split(','), function(action) { if (operations[action]) { batch.add(new Ext.data.Operation({ action : action, records: operations[action] })); } }, this); batch.start(); return batch; } }); Ext.data.DataProxy = Ext.data.Proxy; Ext.data.ProxyMgr.registerType('proxy', Ext.data.Proxy); Ext.data.ServerProxy = Ext.extend(Ext.data.Proxy, { pageParam: 'page', startParam: 'start', limitParam: 'limit', groupParam: 'group', sortParam: 'sort', filterParam: 'filter', noCache : true, cacheString: "_dc", timeout : 30000, constructor: function(config) { config = config || {}; Ext.data.ServerProxy.superclass.constructor.call(this, config); this.extraParams = config.extraParams || {}; this.nocache = this.noCache; }, create: function() { return this.doRequest.apply(this, arguments); }, read: function() { return this.doRequest.apply(this, arguments); }, update: function() { return this.doRequest.apply(this, arguments); }, destroy: function() { return this.doRequest.apply(this, arguments); }, buildRequest: function(operation) { var params = Ext.applyIf(operation.params || {}, this.extraParams || {}); params = Ext.applyIf(params, this.getParams(params, operation)); var request = new Ext.data.Request({ params : params, action : operation.action, records : operation.records, operation: operation }); request.url = this.buildUrl(request); operation.request = request; return request; }, encodeSorters: function(sorters) { var min = [], length = sorters.length, i; for (i = 0; i < length; i++) { min[i] = { property : sorters[i].property, direction: sorters[i].direction }; } return Ext.encode(min); }, encodeFilters: function(filters) { var min = [], length = filters.length, i; for (i = 0; i < length; i++) { min[i] = { property: filters[i].property, value : filters[i].value }; } return Ext.encode(min); }, encodeGroupers: function(group) { return Ext.encode(group); }, getParams: function(params, operation) { params = params || {}; var group = operation.group, sorters = operation.sorters, filters = operation.filters, page = operation.page, start = operation.start, limit = operation.limit, pageParam = this.pageParam, startParam = this.startParam, limitParam = this.limitParam, groupParam = this.groupParam, sortParam = this.sortParam, filterParam = this.filterParam; if (pageParam && page) { params[pageParam] = page; } if (startParam && start) { params[startParam] = start; } if (limitParam && limit) { params[limitParam] = limit; } if (groupParam && group && group.field) { params[groupParam] = this.encodeGroupers(group); } if (sortParam && sorters && sorters.length > 0) { params[sortParam] = this.encodeSorters(sorters); } if (filterParam && filters && filters.length > 0) { params[filterParam] = this.encodeFilters(filters); } return params; }, buildUrl: function(request) { var url = request.url || this.url; if (!url) { throw new Error("You are using a ServerProxy but have not supplied it with a url."); } if (this.noCache) { url = Ext.urlAppend(url, Ext.util.Format.format("{0}={1}", this.cacheString, (new Date().getTime()))); } return url; }, doRequest: function(operation, callback, scope) { throw new Error("The doRequest function has not been implemented on your Ext.data.ServerProxy subclass. See src/data/ServerProxy.js for details"); }, afterRequest: Ext.emptyFn, onDestroy: function() { Ext.destroy(this.reader, this.writer); Ext.data.ServerProxy.superclass.destroy.apply(this, arguments); } }); Ext.data.AjaxProxy = Ext.extend(Ext.data.ServerProxy, { actionMethods: { create : 'POST', read : 'GET', update : 'POST', destroy: 'POST' }, constructor: function() { this.addEvents( 'exception' ); Ext.data.AjaxProxy.superclass.constructor.apply(this, arguments); }, doRequest: function(operation, callback, scope) { var writer = this.getWriter(), request = this.buildRequest(operation, callback, scope); if (operation.allowWrite()) { request = writer.write(request); } Ext.apply(request, { headers : this.headers, timeout : this.timeout, scope : this, callback : this.createRequestCallback(request, operation, callback, scope), method : this.getMethod(request), disableCaching: false }); Ext.Ajax.request(request); return request; }, getMethod: function(request) { return this.actionMethods[request.action]; }, createRequestCallback: function(request, operation, callback, scope) { var me = this; return function(options, success, response) { if (success === true) { var reader = me.getReader(), result = reader.read(response); Ext.apply(operation, { response : response, resultSet: result }); operation.setCompleted(); operation.setSuccessful(); } else { me.fireEvent('exception', this, response, operation); operation.setException(); } if (typeof callback == 'function') { callback.call(scope || me, operation); } me.afterRequest(request, true); }; } }); Ext.data.ProxyMgr.registerType('ajax', Ext.data.AjaxProxy); Ext.data.HttpProxy = Ext.data.AjaxProxy; Ext.data.RestProxy = Ext.extend(Ext.data.AjaxProxy, { appendId: true, actionMethods: { create : 'POST', read : 'GET', update : 'PUT', destroy: 'DELETE' }, api: { create : 'create', read : 'read', update : 'update', destroy: 'destroy' }, buildUrl: function(request) { var records = request.operation.records || [], record = records[0], format = this.format, url = request.url || this.url; if (this.appendId && record) { if (!url.match(/\/$/)) { url += '/'; } url += record.getId(); } if (format) { if (!url.match(/\.$/)) { url += '.'; } url += format; } request.url = url; return Ext.data.RestProxy.superclass.buildUrl.apply(this, arguments); } }); Ext.data.ProxyMgr.registerType('rest', Ext.data.RestProxy); Ext.apply(Ext, { getHead : function() { var head; return function() { if (head == undefined) { head = Ext.get(document.getElementsByTagName("head")[0]); } return head; }; }() }); Ext.data.ScriptTagProxy = Ext.extend(Ext.data.ServerProxy, { defaultWriterType: 'base', callbackParam : "callback", scriptIdPrefix: 'stcScript', callbackPrefix: 'stcCallback', recordParam: 'records', lastRequest: undefined, autoAppendParams: true, constructor: function(){ this.addEvents( 'exception' ); Ext.data.ScriptTagProxy.superclass.constructor.apply(this, arguments); }, doRequest: function(operation, callback, scope) { var format = Ext.util.Format.format, transId = ++Ext.data.ScriptTagProxy.TRANS_ID, scriptId = format("{0}{1}", this.scriptIdPrefix, transId), stCallback = format("{0}{1}", this.callbackPrefix, transId); var writer = this.getWriter(), request = this.buildRequest(operation), url = Ext.urlAppend(request.url, format("{0}={1}", this.callbackParam, stCallback)); if (operation.allowWrite()) { request = writer.write(request); } Ext.apply(request, { url : url, transId : transId, scriptId : scriptId, stCallback: stCallback }); request.timeoutId = Ext.defer(this.createTimeoutHandler, this.timeout, this, [request, operation]); window[stCallback] = this.createRequestCallback(request, operation, callback, scope); var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("async", true); script.setAttribute("type", "text/javascript"); script.setAttribute("id", scriptId); Ext.getHead().appendChild(script); operation.setStarted(); this.lastRequest = request; return request; }, createRequestCallback: function(request, operation, callback, scope) { var me = this; return function(response) { var reader = me.getReader(), result = reader.read(response); Ext.apply(operation, { response : response, resultSet: result }); operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || me, operation); } me.afterRequest(request, true); }; }, afterRequest: function() { var cleanup = function(functionName) { return function() { window[functionName] = undefined; try { delete window[functionName]; } catch(e) {} }; }; return function(request, isLoaded) { Ext.get(request.scriptId).remove(); clearTimeout(request.timeoutId); var callbackName = request.stCallback; if (isLoaded) { cleanup(callbackName)(); this.lastRequest.completed = true; } else { window[callbackName] = cleanup(callbackName); } }; }(), buildUrl: function(request) { var url = Ext.data.ScriptTagProxy.superclass.buildUrl.call(this, request), params = Ext.apply({}, request.params), filters = params.filters, filter, i; delete params.filters; if (this.autoAppendParams) { url = Ext.urlAppend(url, Ext.urlEncode(params)); } if (filters && filters.length) { for (i = 0; i < filters.length; i++) { filter = filters[i]; if (filter.value) { url = Ext.urlAppend(url, filter.property + "=" + filter.value); } } } var records = request.records; if (Ext.isArray(records) && records.length > 0) { url = Ext.urlAppend(url, Ext.util.Format.format("{0}={1}", this.recordParam, this.encodeRecords(records))); } return url; }, destroy: function() { this.abort(); Ext.data.ScriptTagProxy.superclass.destroy.apply(this, arguments); }, isLoading : function(){ var lastRequest = this.lastRequest; return (lastRequest != undefined && !lastRequest.completed); }, abort: function() { if (this.isLoading()) { this.afterRequest(this.lastRequest); } }, encodeRecords: function(records) { var encoded = ""; for (var i = 0, length = records.length; i < length; i++) { encoded += Ext.urlEncode(records[i].data); } return encoded; }, createTimeoutHandler: function(request, operation) { this.afterRequest(request, false); this.fireEvent('exception', this, request, operation); if (typeof request.callback == 'function') { request.callback.call(request.scope || window, null, request.options, false); } } }); Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.data.ProxyMgr.registerType('scripttag', Ext.data.ScriptTagProxy); Ext.data.ClientProxy = Ext.extend(Ext.data.Proxy, { clear: function() { throw new Error("The Ext.data.ClientProxy subclass that you are using has not defined a 'clear' function. See src/data/ClientProxy.js for details."); } }); Ext.data.MemoryProxy = Ext.extend(Ext.data.ClientProxy, { constructor: function(config) { Ext.data.MemoryProxy.superclass.constructor.call(this, config); this.setReader(this.reader); }, read: function(operation, callback, scope) { var reader = this.getReader(), result = reader.read(this.data); Ext.apply(operation, { resultSet: result }); operation.setCompleted(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, clear: Ext.emptyFn }); Ext.data.ProxyMgr.registerType('memory', Ext.data.MemoryProxy); Ext.data.WebStorageProxy = Ext.extend(Ext.data.ClientProxy, { id: undefined, constructor: function(config) { Ext.data.WebStorageProxy.superclass.constructor.call(this, config); this.cache = {}; if (this.getStorageObject() == undefined) { throw "Local Storage is not supported in this browser, please use another type of data proxy"; } this.id = this.id || (this.store ? this.store.storeId : undefined); if (this.id == undefined) { throw "No unique id was provided to the local storage proxy. See Ext.data.LocalStorageProxy documentation for details"; } this.initialize(); }, create: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), id, record, i; operation.setStarted(); for (i = 0; i < length; i++) { record = records[i]; if (record.phantom) { record.phantom = false; id = this.getNextId(); } else { id = record.getId(); } this.setRecord(record, id); ids.push(id); } this.setIds(ids); operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, read: function(operation, callback, scope) { var records = [], ids = this.getIds(), length = ids.length, i, recordData, record; if (operation.id) { record = this.getRecord(operation.id); if (record) { records.push(record); operation.setSuccessful(); } } else { for (i = 0; i < length; i++) { records.push(this.getRecord(ids[i])); } operation.setSuccessful(); } operation.setCompleted(); operation.resultSet = new Ext.data.ResultSet({ records: records, total : records.length, loaded : true }); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, update: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), record, id, i; operation.setStarted(); for (i = 0; i < length; i++) { record = records[i]; this.setRecord(record); id = record.getId(); if (id !== undefined && ids.indexOf(id) == -1) { ids.push(id); } } this.setIds(ids); operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, destroy: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), newIds = [].concat(ids), i; for (i = 0; i < length; i++) { newIds.remove(records[i].getId()); this.removeRecord(records[i], false); } this.setIds(newIds); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, getRecord: function(id) { if (this.cache[id] == undefined) { var rawData = Ext.decode(this.getStorageObject().getItem(this.getRecordKey(id))), data = {}, Model = this.model, fields = Model.prototype.fields.items, length = fields.length, i, field, name, record; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (typeof field.decode == 'function') { data[name] = field.decode(rawData[name]); } else { data[name] = rawData[name]; } } record = new Model(data); record.phantom = false; this.cache[id] = record; } return this.cache[id]; }, setRecord: function(record, id) { if (id) { record.setId(id); } else { id = record.getId(); } var rawData = record.data, data = {}, model = this.model, fields = model.prototype.fields.items, length = fields.length, i, field, name; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (typeof field.encode == 'function') { data[name] = field.encode(rawData[name], record); } else { data[name] = rawData[name]; } } var obj = this.getStorageObject(), key = this.getRecordKey(id); this.cache[id] = record; obj.removeItem(key); obj.setItem(key, Ext.encode(data)); }, removeRecord: function(id, updateIds) { if (id instanceof Ext.data.Model) { id = id.getId(); } if (updateIds !== false) { var ids = this.getIds(); ids.remove(id); this.setIds(ids); } this.getStorageObject().removeItem(this.getRecordKey(id)); }, getRecordKey: function(id) { if (id instanceof Ext.data.Model) { id = id.getId(); } return Ext.util.Format.format("{0}-{1}", this.id, id); }, getRecordCounterKey: function() { return Ext.util.Format.format("{0}-counter", this.id); }, getIds: function() { var ids = (this.getStorageObject().getItem(this.id) || "").split(","), length = ids.length, i; if (length == 1 && ids[0] == "") { ids = []; } else { for (i = 0; i < length; i++) { ids[i] = parseInt(ids[i], 10); } } return ids; }, setIds: function(ids) { var obj = this.getStorageObject(), str = ids.join(","); obj.removeItem(this.id); if (!Ext.isEmpty(str)) { obj.setItem(this.id, str); } }, getNextId: function() { var obj = this.getStorageObject(), key = this.getRecordCounterKey(), last = obj[key], ids, id; if (last == undefined) { ids = this.getIds(); last = ids[ids.length - 1] || 0; } id = parseInt(last, 10) + 1; obj.setItem(key, id); return id; }, initialize: function() { var storageObject = this.getStorageObject(); storageObject.setItem(this.id, storageObject.getItem(this.id) || ""); }, clear: function() { var obj = this.getStorageObject(), ids = this.getIds(), len = ids.length, i; for (i = 0; i < len; i++) { this.removeRecord(ids[i]); } obj.removeItem(this.getRecordCounterKey()); obj.removeItem(this.id); }, getStorageObject: function() { throw new Error("The getStorageObject function has not been defined in your Ext.data.WebStorageProxy subclass"); } }); Ext.data.LocalStorageProxy = Ext.extend(Ext.data.WebStorageProxy, { getStorageObject: function() { return window.localStorage; } }); Ext.data.ProxyMgr.registerType('localstorage', Ext.data.LocalStorageProxy); Ext.data.SessionStorageProxy = Ext.extend(Ext.data.WebStorageProxy, { getStorageObject: function() { return window.sessionStorage; } }); Ext.data.ProxyMgr.registerType('sessionstorage', Ext.data.SessionStorageProxy); Ext.data.Reader = Ext.extend(Object, { idProperty: 'id', totalProperty: 'total', successProperty: 'success', root: '', implicitIncludes: true, nullResultSet: new Ext.data.ResultSet({ total : 0, count : 0, records: [], success: true }), constructor: function(config) { Ext.apply(this, config || {}); this.model = Ext.ModelMgr.getModel(config.model); if (this.model) { this.buildExtractors(); } }, setModel: function(model, setOnProxy) { this.model = Ext.ModelMgr.getModel(model); this.buildExtractors(true); if (setOnProxy && this.proxy) { this.proxy.setModel(this.model, true); } }, read: function(response) { var data = response; if (response) { if (response.responseText) { data = this.getResponseData(response); } return this.readRecords(data); } else { return this.nullResultSet; } }, readRecords: function(data) { this.rawData = data; data = this.getData(data); var root = this.getRoot(data), total = root.length, success = true, value, records, recordCount; if (this.totalProperty) { value = parseInt(this.getTotal(data), 10); if (!isNaN(value)) { total = value; } } if (this.successProperty) { value = this.getSuccess(data); if (value === false || value === 'false') { success = false; } } records = this.extractData(root, true); recordCount = records.length; return new Ext.data.ResultSet({ total : total || recordCount, count : recordCount, records: records, success: success }); }, extractData : function(root, returnRecords) { var values = [], records = [], Model = this.model, length = root.length, idProp = this.idProperty, node, id, record, i; for (i = 0; i < length; i++) { node = root[i]; values = this.extractValues(node); id = this.getId(node); if (returnRecords === true) { record = new Model(values, id); record.raw = node; records.push(record); if (this.implicitIncludes) { this.readAssociated(record, node); } } else { values[idProp] = id; records.push(values); } } return records; }, readAssociated: function(record, data) { var associations = record.associations.items, length = associations.length, association, associationName, associatedModel, associationData, inverseAssociation, proxy, reader, store, i; for (i = 0; i < length; i++) { association = associations[i]; associationName = association.name; associationData = this.getAssociatedDataRoot(data, association.associationKey || associationName); associatedModel = association.associatedModel; if (associationData) { proxy = associatedModel.proxy; if (proxy) { reader = proxy.getReader(); } else { reader = new this.constructor({ model: association.associatedName }); } if (association.type == 'hasMany') { store = record[associationName](); store.add.apply(store, reader.read(associationData).records); inverseAssociation = associatedModel.prototype.associations.findBy(function(assoc) { return assoc.type == 'belongsTo' && assoc.associatedName == record.constructor.modelName; }); if (inverseAssociation) { store.data.each(function(associatedRecord) { associatedRecord[inverseAssociation.instanceName] = record; }); } } else if (association.type == 'belongsTo') { record[association.instanceName] = reader.read([associationData]).records[0]; } } } }, getAssociatedDataRoot: function(data, associationName) { return data[associationName]; }, extractValues: function(data) { var fields = this.model.prototype.fields.items, length = fields.length, output = {}, field, value, i; for (i = 0; i < length; i++) { field = fields[i]; value = this.extractorFunctions[i](data) || field.defaultValue; output[field.name] = value; } return output; }, getData: function(data) { return data; }, getRoot: function(data) { return data; }, getResponseData: function(response) { throw new Error("getResponseData must be implemented in the Ext.data.Reader subclass"); }, onMetaChange : function(meta) { var fields = meta.fields, newModel; Ext.apply(this, meta); if (fields) { newModel = Ext.regModel("JsonReader-Model" + Ext.id(), {fields: fields}); this.setModel(newModel, true); } else { this.buildExtractors(true); } }, buildExtractors: function(force) { if (force === true) { delete this.extractorFunctions; } if (this.extractorFunctions) { return; } var idProp = this.id || this.idProperty, totalProp = this.totalProperty, successProp = this.successProperty, messageProp = this.messageProperty; if (totalProp) { this.getTotal = this.createAccessor(totalProp); } if (successProp) { this.getSuccess = this.createAccessor(successProp); } if (messageProp) { this.getMessage = this.createAccessor(messageProp); } if (idProp) { var accessor = this.createAccessor(idProp); this.getId = function(record) { var id = accessor(record); return (id == undefined || id == '') ? null : id; }; } else { this.getId = function() { return null; }; } this.buildFieldExtractors(); }, buildFieldExtractors: function() { var fields = this.model.prototype.fields.items, ln = fields.length, i = 0, extractorFunctions = [], field, map; for (; i < ln; i++) { field = fields[i]; map = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name; extractorFunctions.push(this.createAccessor(map)); } this.extractorFunctions = extractorFunctions; } }); Ext.data.Writer = Ext.extend(Object, { constructor: function(config) { Ext.apply(this, config); }, write: function(request) { var operation = request.operation, records = operation.records || [], ln = records.length, i = 0, data = []; for (; i < ln; i++) { data.push(this.getRecordData(records[i])); } return this.writeRecords(request, data); }, getRecordData: function(record) { return record.data; } }); Ext.data.WriterMgr.registerType('base', Ext.data.Writer); Ext.data.JsonWriter = Ext.extend(Ext.data.Writer, { root: 'records', encode: false, writeRecords: function(request, data) { if (this.encode === true) { data = Ext.encode(data); } request.jsonData = request.jsonData || {}; request.jsonData[this.root] = data; return request; } }); Ext.data.WriterMgr.registerType('json', Ext.data.JsonWriter); Ext.data.JsonReader = Ext.extend(Ext.data.Reader, { root: '', readRecords: function(data) { if (data.metaData) { this.onMetaChange(data.metaData); } this.jsonData = data; return Ext.data.JsonReader.superclass.readRecords.call(this, data); }, getResponseData: function(response) { try { var data = Ext.decode(response.responseText); } catch (ex) { throw 'Ext.data.JsonReader.getResponseData: Unable to parse JSON returned by Server.'; } if (!data) { throw 'Ext.data.JsonReader.getResponseData: JSON object not found'; } return data; }, buildExtractors : function() { Ext.data.JsonReader.superclass.buildExtractors.apply(this, arguments); if (this.root) { this.getRoot = this.createAccessor(this.root); } else { this.getRoot = function(root) { return root; }; } }, extractData: function(root, returnRecords) { var recordName = this.record, data = [], length, i; if (recordName) { length = root.length; for (i = 0; i < length; i++) { data[i] = root[i][recordName]; } } else { data = root; } return Ext.data.XmlReader.superclass.extractData.call(this, data, returnRecords); }, createAccessor: function() { var re = /[\[\.]/; return function(expr) { if (Ext.isEmpty(expr)) { return Ext.emptyFn; } if (Ext.isFunction(expr)) { return expr; } var i = String(expr).search(re); if (i >= 0) { return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr); } return function(obj) { return obj[expr]; }; }; }() }); Ext.data.ReaderMgr.registerType('json', Ext.data.JsonReader); Ext.data.TreeReader = Ext.extend(Ext.data.JsonReader, { extractData : function(root, returnRecords) { var records = Ext.data.TreeReader.superclass.extractData.call(this, root, returnRecords), ln = records.length, i = 0, record; if (returnRecords) { for (; i < ln; i++) { record = records[i]; record.doPreload = !!this.getRoot(record.raw); } } return records; } }); Ext.data.ReaderMgr.registerType('tree', Ext.data.TreeReader); Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, { buildExtractors: function() { Ext.data.ArrayReader.superclass.buildExtractors.apply(this, arguments); var fields = this.model.prototype.fields.items, length = fields.length, extractorFunctions = [], i; for (i = 0; i < length; i++) { extractorFunctions.push(function(index) { return function(data) { return data[index]; }; }(fields[i].mapping || i)); } this.extractorFunctions = extractorFunctions; } }); Ext.data.ReaderMgr.registerType('array', Ext.data.ArrayReader); Ext.data.ArrayStore = Ext.extend(Ext.data.Store, { constructor: function(config) { config = config || {}; Ext.applyIf(config, { proxy: { type: 'memory', reader: 'array' } }); Ext.data.ArrayStore.superclass.constructor.call(this, config); }, loadData: function(data, append) { if (this.expandData === true) { var r = [], i = 0, ln = data.length; for (; i < ln; i++) { r[r.length] = [data[i]]; } data = r; } Ext.data.ArrayStore.superclass.loadData.call(this, data, append); } }); Ext.reg('arraystore', Ext.data.ArrayStore); Ext.data.SimpleStore = Ext.data.ArrayStore; Ext.reg('simplestore', Ext.data.SimpleStore); Ext.data.JsonStore = Ext.extend(Ext.data.Store, { constructor: function(config) { config = config || {}; Ext.applyIf(config, { proxy: { type : 'ajax', reader: 'json', writer: 'json' } }); Ext.data.JsonStore.superclass.constructor.call(this, config); } }); Ext.reg('jsonstore', Ext.data.JsonStore); Ext.data.JsonPStore = Ext.extend(Ext.data.Store, { constructor: function(config) { Ext.data.JsonPStore.superclass.constructor.call(this, Ext.apply(config, { reader: new Ext.data.JsonReader(config), proxy : new Ext.data.ScriptTagProxy(config) })); } }); Ext.reg('jsonpstore', Ext.data.JsonPStore); Ext.data.XmlWriter = Ext.extend(Ext.data.Writer, { documentRoot: 'xmlData', header: '', record: 'record', writeRecords: function(request, data) { var tpl = this.buildTpl(request, data); request.xmlData = tpl.apply(data); return request; }, buildTpl: function(request, data) { if (this.tpl) { return this.tpl; } var tpl = [], root = this.documentRoot, record = this.record, first, key; if (this.header) { tpl.push(this.header); } tpl.push('<', root, '>'); if (data.length > 0) { tpl.push('<tpl for="."><', record, '>'); first = data[0]; for (key in first) { if (first.hasOwnProperty(key)) { tpl.push('<', key, '>{', key, '}</', key, '>'); } } tpl.push('</', record, '></tpl>'); } tpl.push('</', root, '>'); this.tpl = new Ext.XTemplate(tpl.join('')); return this.tpl; } }); Ext.data.WriterMgr.registerType('xml', Ext.data.XmlWriter); Ext.data.XmlReader = Ext.extend(Ext.data.Reader, { createAccessor: function() { var selectValue = function(key, root, defaultValue){ var node = Ext.DomQuery.selectNode(key, root), val; if (node && node.firstChild) { val = node.firstChild.nodeValue; } return Ext.isEmpty(val) ? defaultValue : val; }; return function(key) { var fn; if (key == this.totalProperty) { fn = function(root, defaultValue) { var value = selectValue(key, root, defaultValue); return parseFloat(value); }; } else if (key == this.successProperty) { fn = function(root, defaultValue) { var value = selectValue(key, root, true); return (value !== false && value !== 'false'); }; } else { fn = function(root, defaultValue) { return selectValue(key, root, defaultValue); }; } return fn; }; }(), getResponseData: function(response) { var xml = response.responseXML; if (!xml) { throw {message: 'Ext.data.XmlReader.read: XML data not found'}; } return xml; }, getData: function(data) { return data.documentElement || data; }, getRoot: function(data) { var nodeName = data.nodeName, root = this.root; if (!root || (nodeName && nodeName == root)) { return data; } else { return Ext.DomQuery.selectNode(root, data); } }, constructor: function(config) { config = config || {}; Ext.applyIf(config, { idProperty : config.idPath || config.id, successProperty: config.success }); Ext.data.XmlReader.superclass.constructor.call(this, config); }, extractData: function(root, returnRecords) { var recordName = this.record; if (recordName != root.nodeName) { root = Ext.DomQuery.select(recordName, root); } else { root = [root]; } return Ext.data.XmlReader.superclass.extractData.call(this, root, returnRecords); }, getAssociatedDataRoot: function(data, associationName) { return Ext.DomQuery.select(associationName, data)[0]; }, readRecords: function(doc) { if (Ext.isArray(doc)) { doc = doc[0]; } this.xmlData = doc; return Ext.data.XmlReader.superclass.readRecords.call(this, doc); } }); Ext.data.ReaderMgr.registerType('xml', Ext.data.XmlReader); Ext.data.XmlStore = Ext.extend(Ext.data.Store, { constructor: function(config){ config = config || {}; config = config || {}; Ext.applyIf(config, { proxy: { type: 'ajax', reader: 'xml', writer: 'xml' } }); Ext.data.XmlStore.superclass.constructor.call(this, config); } }); Ext.reg('xmlstore', Ext.data.XmlStore); Ext.History = new Ext.util.Observable({ constructor: function() { Ext.History.superclass.constructor.call(this, config); this.addEvents( 'change' ); }, init: function() { var me = this; me.setToken(window.location.hash); if (Ext.supports.History) { window.addEventListener('hashchange', this.onChange); } else { setInterval(function() { var newToken = me.cleanToken(window.location.hash), oldToken = me.getToken(); if (newToken != oldToken) { me.onChange(); } }, 50); } }, onChange: function() { var me = Ext.History, newToken = me.cleanToken(window.location.hash); if (me.token != newToken) { me.fireEvent('change', newToken); } me.setToken(newToken); }, setToken: function(token) { return this.token = this.cleanToken(token); }, cleanToken: function(token) { return token[0] == '#' ? token.substr(1) : token; }, getToken: function() { return this.token; }, add: function(token) { window.location.hash = this.setToken(token); if (!Ext.supports.History) { this.onChange(); } } }); Ext.ControllerManager = new Ext.AbstractManager({ register: function(id, options) { options.id = id; Ext.applyIf(options, { application: Ext.ApplicationManager.currentApplication }); var controller = new Ext.Controller(options); if (controller.init) { controller.init(); } this.all.add(controller); return controller; } }); Ext.regController = function() { return Ext.ControllerManager.register.apply(Ext.ControllerManager, arguments); }; Ext.Controller = Ext.extend(Ext.util.Observable, { constructor: function(config) { this.addEvents( 'instance-created', 'instance-creation-failed', 'instance-updated', 'instance-update-failed', 'instance-destroyed', 'instance-destruction-failed' ); Ext.Controller.superclass.constructor.call(this, config); Ext.apply(this, config || {}); if (typeof this.model == 'string') { this.model = Ext.ModelMgr.getModel(this.model); } }, index: function() { this.render('index', { listeners: { scope : this, edit : this.edit, build : this.build, create : this.onCreateInstance, destroy: this.onDestroyInstance } }); }, edit: function(instance) { var view = this.render('edit', { listeners: this.getEditListeners() }); view.loadModel(instance); }, build: function() { this.render('build', { listeners: this.getBuildListeners() }); }, create: function(data, options) { options = options || {}; var model = this.getModel(), instance = new model(data), successCb = options.success, failureCb = options.failure, scope = options.scope || this; instance.save({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-created', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-creation-failed', instance, errors); } }); }, update: function(instance, updates, options) { options = options || {}; var successCb = options.success, failureCb = options.failure, scope = options.scope || this; if (Ext.isObject(updates)) { instance.set(updates); } instance.save({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-updated', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-update-failed', instance, errors); } }); }, destroy: function(instance, options) { options = options || {}; var successCb = options.success, failureCb = options.failure, scope = options.scope || this; instance.destroy({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-destroyed', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-destruction-failed', instance, errors); } }); }, getBuildListeners: function() { return { scope : this, save : this.onCreateInstance, cancel: this.onCancelBuild }; }, getEditListeners: function() { return { scope : this, save : this.onUpdateInstance, cancel: this.onCancelEdit }; }, onCancelEdit: function(view) { return this.closeView(view); }, onCancelBuild: function(view) { return this.closeView(view); }, onCreateInstance: function(view) { this.create(view.getValues(), { scope : this, success: function(instance) { this.closeView(view); }, failure: function(instance, errors) { console.log('fail'); } }); }, onUpdateInstance: function(view) { this.update(view.getRecord(), view.getValues(), { scope : this, success: function(instance) { this.closeView(view); }, failure: function(instance, errors) { } }); }, onDestroyInstance: function(instance, view) { this.destroy(instance, { scope : this, success: function(instance) { }, failure: function(instance, errors) { } }); }, setRenderTarget: function(target) { Ext.Controller.renderTarget = target; }, render: function(config, target) { var Controller = Ext.Controller, application = this.application, profile = application ? application.currentProfile : undefined, profileTarget, view; Ext.applyIf(config, { profile: profile }); view = Ext.ComponentMgr.create(config); if (target !== false) { profileTarget = profile ? profile.getRenderTarget(config, application) : target; if (target == undefined) { target = profileTarget || (application ? application.defaultTarget : undefined); } if (typeof target == 'string') { target = Ext.getCmp(target); } if (target != undefined && target.add) { if (profile) { profile.beforeLayout(view, target, application); } target.add(view); if (target.layout && target.layout.setActiveItem) { target.layout.setActiveItem(view); } target.doComponentLayout(); if (profile) { profile.afterLayout(view, target, application); } } } return view; }, control : function(view, actions, itemName) { if (!view || !view.isView) { throw 'Trying to control a view that doesnt exist'; } var item = itemName ? view.refs[itemName] : view, key, value, name, child, listener; if (!item) { throw "No item called " + itemName + " found inside the " + view.name + " view."; } for (key in actions) { value = actions[key]; if (Ext.isObject(value) && !value.fn) { this.control(view, value, key); } else { if (item.refs) { for (name in item.refs) { child = item.refs[name]; if (child.isObservable && child.events[key]) { child.enableBubble(key); } } } if (!value.fn) { listener = {}; listener[key] = value; listener.scope = this; } else { listener = value; if (listener.scope === undefined) { listener.scope = this; } } item.addListener(listener); } } return view; }, getModel: function() { return Ext.ModelMgr.getModel(this.model); }, closeView: function(view) { var ownerCt = view.ownerCt; if (ownerCt) { ownerCt.remove(view); ownerCt.doLayout(); ownerCt.setActiveItem(ownerCt.items.last()); } } }); Ext.util.Dispatcher = Ext.extend(Ext.util.Observable, { constructor: function(config) { this.addEvents( 'before-dispatch', 'dispatch' ); Ext.util.Dispatcher.superclass.constructor.call(this, config); }, dispatch: function(options) { var interaction = new Ext.Interaction(options), controller = interaction.controller, action = interaction.action, History = Ext.History; if (this.fireEvent('before-dispatch', interaction) !== false) { if (History && options.historyUrl) { History.suspendEvents(false); History.add(options.historyUrl); Ext.defer(History.resumeEvents, 100, History); } if (controller && action) { controller[action].call(controller, interaction); interaction.dispatched = true; } this.fireEvent('dispatch', interaction); } }, redirect: function(options) { if (options instanceof Ext.data.Model) { } else if (typeof options == 'string') { var route = Ext.Router.recognize(options); if (route) { return this.dispatch(route); } } return null; }, createRedirect: function(url) { return function() { Ext.Dispatcher.redirect(url); }; } }); Ext.Dispatcher = new Ext.util.Dispatcher(); Ext.dispatch = function() { return Ext.Dispatcher.dispatch.apply(Ext.Dispatcher, arguments); }; Ext.redirect = function() { return Ext.Dispatcher.redirect.apply(Ext.Dispatcher, arguments); }; Ext.createRedirect = Ext.Dispatcher.createRedirect; Ext.util.Router = Ext.extend(Ext.util.Observable, { constructor: function(config) { config = config || {}; Ext.apply(this, config, { defaults: { action: 'index' } }); this.routes = []; Ext.util.Router.superclass.constructor.call(this, config); }, connect: function(url, params) { params = Ext.apply({url: url}, params || {}, this.defaults); var route = new Ext.util.Route(params); this.routes.push(route); return route; }, recognize: function(url) { var routes = this.routes, length = routes.length, i, result; for (i = 0; i < length; i++) { result = routes[i].recognize(url); if (result != undefined) { return result; } } return undefined; }, draw: function(fn) { fn.call(this, this); } }); Ext.Router = new Ext.util.Router(); Ext.util.Route = Ext.extend(Object, { constructor: function(config) { Ext.apply(this, config, { conditions: {} }); this.paramMatchingRegex = new RegExp(/:([0-9A-Za-z\_]*)/g); this.paramsInMatchString = this.url.match(this.paramMatchingRegex) || []; this.matcherRegex = this.createMatcherRegex(this.url); }, recognize: function(url) { if (this.recognizes(url)) { var matches = this.matchesFor(url); return Ext.applyIf(matches, { controller: this.controller, action : this.action, historyUrl: url }); } }, recognizes: function(url) { return this.matcherRegex.test(url); }, matchesFor: function(url) { var params = {}, keys = this.paramsInMatchString, values = url.match(this.matcherRegex), length = keys.length, i; values.shift(); for (i = 0; i < length; i++) { params[keys[i].replace(":", "")] = values[i]; } return params; }, urlFor: function(config) { }, createMatcherRegex: function(url) { var paramsInMatchString = this.paramsInMatchString, length = paramsInMatchString.length, i, cond, matcher; for (i = 0; i < length; i++) { cond = this.conditions[paramsInMatchString[i]]; matcher = Ext.util.Format.format("({0})", cond || "[%a-zA-Z0-9\\_\\s,]+"); url = url.replace(new RegExp(paramsInMatchString[i]), matcher); } return new RegExp("^" + url + "$"); } }); Ext.Interaction = Ext.extend(Ext.util.Observable, { controller: '', action: '', dispatched: false, constructor: function(config) { Ext.Interaction.superclass.constructor.apply(this, arguments); config = config || {}; Ext.applyIf(config, { scope: this }); Ext.apply(this, config); if (typeof this.controller == 'string') { this.controller = Ext.ControllerManager.get(this.controller); } } }); Ext.Application = Ext.extend(Ext.util.Observable, { scope: undefined, useHistory: true, autoUpdateComponentProfiles: true, setProfilesOnLaunch: true, constructor: function(config) { this.addEvents( 'launch', 'beforeprofilechange', 'profilechange' ); Ext.Application.superclass.constructor.call(this, config); this.bindReady(); var name = this.name; if (name) { window[name] = this; Ext.ns( name, name + ".views", name + ".stores", name + ".models", name + ".controllers" ); } if (Ext.addMetaTags) { Ext.addMetaTags(config); } }, bindReady : function() { Ext.onReady(this.onReady, this); }, launch: Ext.emptyFn, useLoadMask: false, loadMaskFadeDuration: 1000, loadMaskRemoveDuration: 1050, autoInitViewport: true, dispatch: function(options) { return Ext.dispatch(options); }, initLoadMask: function() { var useLoadMask = this.useLoadMask, defaultId = 'loading-mask', loadMaskId = typeof useLoadMask == 'string' ? useLoadMask : defaultId; if (useLoadMask) { if (loadMaskId == defaultId) { Ext.getBody().createChild({id: defaultId}); } var loadingMask = Ext.get('loading-mask'), fadeDuration = this.loadMaskFadeDuration, hideDuration = this.loadMaskRemoveDuration; Ext.defer(function() { loadingMask.addCls('fadeout'); Ext.defer(function() { loadingMask.remove(); }, hideDuration); }, fadeDuration); } }, onBeforeLaunch: function() { var History = Ext.History, useHistory = History && this.useHistory, profile = this.determineProfile(true); if (useHistory) { this.historyForm = Ext.getBody().createChild({ id : 'history-form', cls : 'x-hide-display', style : 'display: none;', tag : 'form', action: '#', children: [ { tag: 'div', children: [ { tag : 'input', id : History.fieldId, type: 'hidden' }, { tag: 'iframe', id : History.iframeId } ] } ] }); History.init(); History.on('change', this.onHistoryChange, this); var token = History.getToken(); if (this.launch.call(this.scope || this, profile) !== false) { Ext.redirect(token || this.defaultUrl || {controller: 'application', action: 'index'}); } } else { this.launch.call(this.scope || this, profile); } this.launched = true; this.fireEvent('launch', this); if (this.setProfilesOnLaunch) { this.updateComponentProfiles(profile); } }, onReady: function() { if (this.useLoadMask) { this.initLoadMask(); } Ext.EventManager.onOrientationChange(this.determineProfile, this); if (this.autoInitViewport) { Ext.Viewport.init(this.onBeforeLaunch, this); } else { this.onBeforeLaunch(); } return this; }, determineProfile: function(silent) { var currentProfile = this.currentProfile, profiles = this.profiles, name; for (name in profiles) { if (profiles[name]() === true) { if (name != currentProfile && this.fireEvent('beforeprofilechange', name, currentProfile) !== false) { if (this.autoUpdateComponentProfiles) { this.updateComponentProfiles(name); } if (silent !== true) { this.fireEvent('profilechange', name, currentProfile); } } this.currentProfile = name; break; } } return this.currentProfile; }, updateComponentProfiles: function(profile) { Ext.ComponentMgr.each(function(key, component){ if (component.setProfile) { component.setProfile(profile); } }); }, getProfile: function() { return this.currentProfile; }, onHistoryChange: function(token) { return Ext.redirect(token); } }); Ext.ApplicationManager = new Ext.AbstractManager({ register: function(name, options) { if (Ext.isObject(name)) { options = name; } else { options.name = name; } var application = new Ext.Application(options); this.all.add(application); this.currentApplication = application; return application; } }); Ext.regApplication = function() { return Ext.ApplicationManager.register.apply(Ext.ApplicationManager, arguments); }; (function() { var El = Ext.Element = Ext.extend(Object, { defaultUnit : "px", constructor : function(element, forceNew) { var dom = typeof element == 'string' ? document.getElementById(element) : element, id; if (!dom) { return null; } id = dom.id; if (!forceNew && id && Ext.cache[id]) { return Ext.cache[id].el; } this.dom = dom; this.id = id || Ext.id(dom); return this; }, set : function(o, useSet) { var el = this.dom, attr, value; for (attr in o) { if (o.hasOwnProperty(attr)) { value = o[attr]; if (attr == 'style') { this.applyStyles(value); } else if (attr == 'cls') { el.className = value; } else if (useSet !== false) { el.setAttribute(attr, value); } else { el[attr] = value; } } } return this; }, is : function(simpleSelector) { return Ext.DomQuery.is(this.dom, simpleSelector); }, getValue : function(asNumber){ var val = this.dom.value; return asNumber ? parseInt(val, 10) : val; }, addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); return this; }, removeListener : function(eventName, fn, scope) { Ext.EventManager.un(this.dom, eventName, fn, scope); return this; }, removeAllListeners : function(){ Ext.EventManager.removeAll(this.dom); return this; }, purgeAllListeners : function() { Ext.EventManager.purgeElement(this, true); return this; }, remove : function() { var me = this, dom = me.dom; if (dom) { delete me.dom; Ext.removeNode(dom); } }, isAncestor : function(c) { var p = this.dom; c = Ext.getDom(c); if (p && c) { return p.contains(c); } return false; }, isDescendent : function(p) { return Ext.fly(p, '_internal').isAncestor(this); }, contains : function(el) { return !el ? false : this.isAncestor(el); }, getAttribute : function(name, ns) { var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name) || d.getAttribute(name) || d[name]; }, setHTML : function(html) { if(this.dom) { this.dom.innerHTML = html; } return this; }, getHTML : function() { return this.dom ? this.dom.innerHTML : ''; }, hide : function() { this.setVisible(false); return this; }, show : function() { this.setVisible(true); return this; }, setVisible : function(visible, animate) { var me = this, dom = me.dom, mode = this.getVisibilityMode(); switch (mode) { case El.VISIBILITY: this.removeCls(['x-hidden-display', 'x-hidden-offsets']); this[visible ? 'removeCls' : 'addCls']('x-hidden-visibility'); break; case El.DISPLAY: this.removeCls(['x-hidden-visibility', 'x-hidden-offsets']); this[visible ? 'removeCls' : 'addCls']('x-hidden-display'); break; case El.OFFSETS: this.removeCls(['x-hidden-visibility', 'x-hidden-display']); this[visible ? 'removeCls' : 'addCls']('x-hidden-offsets'); break; } return me; }, getVisibilityMode: function() { var dom = this.dom, mode = El.data(dom, 'visibilityMode'); if (mode === undefined) { El.data(dom, 'visibilityMode', mode = El.DISPLAY); } return mode; }, setDisplayMode : function(mode) { El.data(this.dom, 'visibilityMode', mode); return this; } }); var Elp = El.prototype; El.VISIBILITY = 1; El.DISPLAY = 2; El.OFFSETS = 3; El.addMethods = function(o){ Ext.apply(Elp, o); }; Elp.on = Elp.addListener; Elp.un = Elp.removeListener; Elp.update = Elp.setHTML; El.get = function(el){ var extEl, dom, id; if(!el){ return null; } if (typeof el == "string") { if (!(dom = document.getElementById(el))) { return null; } if (Ext.cache[el] && Ext.cache[el].el) { extEl = Ext.cache[el].el; extEl.dom = dom; } else { extEl = El.addToCache(new El(dom)); } return extEl; } else if (el.tagName) { if(!(id = el.id)){ id = Ext.id(el); } if (Ext.cache[id] && Ext.cache[id].el) { extEl = Ext.cache[id].el; extEl.dom = el; } else { extEl = El.addToCache(new El(el)); } return extEl; } else if (el instanceof El) { if(el != El.docEl){ el.dom = document.getElementById(el.id) || el.dom; } return el; } else if(el.isComposite) { return el; } else if(Ext.isArray(el)) { return El.select(el); } else if(el == document) { if(!El.docEl){ var F = function(){}; F.prototype = Elp; El.docEl = new F(); El.docEl.dom = document; El.docEl.id = Ext.id(document); } return El.docEl; } return null; }; El.addToCache = function(el, id){ id = id || el.id; Ext.cache[id] = { el: el, data: {}, events: {} }; return el; }; El.data = function(el, key, value) { el = El.get(el); if (!el) { return null; } var c = Ext.cache[el.id].data; if (arguments.length == 2) { return c[key]; } else { return (c[key] = value); } }; El.garbageCollect = function() { if (!Ext.enableGarbageCollector) { clearInterval(El.collectorThreadId); } else { var id, dom, EC = Ext.cache; for (id in EC) { if (!EC.hasOwnProperty(id)) { continue; } if(EC[id].skipGarbageCollection){ continue; } dom = EC[id].el.dom; if(!dom || !dom.parentNode || (!dom.offsetParent && !document.getElementById(id))){ if(Ext.enableListenerCollection){ Ext.EventManager.removeAll(dom); } delete EC[id]; } } } }; El.Flyweight = function(dom) { this.dom = dom; }; var F = function(){}; F.prototype = Elp; El.Flyweight.prototype = new F; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; El.fly = function(el, named) { var ret = null; named = named || '_global'; el = Ext.getDom(el); if (el) { (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el; ret = El._flyweights[named]; } return ret; }; Ext.get = El.get; Ext.fly = El.fly; })(); Ext.applyIf(Ext.Element, { unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, camelRe: /(-[a-z])/gi, opacityRe: /alpha\(opacity=(.*)\)/i, propertyCache: {}, defaultUnit : "px", borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'}, paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'}, margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'}, addUnits : function(size, units) { if (size === "" || size == "auto" || size === null || size === undefined) { size = size || ''; } else if (!isNaN(size) || !this.unitRe.test(size)) { size = size + (units || this.defaultUnit || 'px'); } return size; }, parseBox : function(box) { if (typeof box != 'string') { box = box.toString(); } var parts = box.split(' '), ln = parts.length; if (ln == 1) { parts[1] = parts[2] = parts[3] = parts[0]; } else if (ln == 2) { parts[2] = parts[0]; parts[3] = parts[1]; } else if (ln == 3) { parts[3] = parts[1]; } return { top :parseFloat(parts[0]) || 0, right :parseFloat(parts[1]) || 0, bottom:parseFloat(parts[2]) || 0, left :parseFloat(parts[3]) || 0 }; }, unitizeBox : function(box, units) { var A = this.addUnits, B = this.parseBox(box); return A(B.top, units) + ' ' + A(B.right, units) + ' ' + A(B.bottom, units) + ' ' + A(B.left, units); }, camelReplaceFn : function(m, a) { return a.charAt(1).toUpperCase(); }, normalize : function(prop) { return this.propertyCache[prop] || (this.propertyCache[prop] = prop == 'float' ? 'cssFloat' : prop.replace(this.camelRe, this.camelReplaceFn)); }, getDocumentHeight: function() { return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight()); }, getDocumentWidth: function() { return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth()); }, getViewportHeight: function(){ return window.innerHeight; }, getViewportWidth : function() { return window.innerWidth; }, getViewSize : function() { return { width: window.innerWidth, height: window.innerHeight }; }, getOrientation : function() { if (Ext.supports.OrientationChange) { return (window.orientation == 0) ? 'portrait' : 'landscape'; } return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; }, fromPoint: function(x, y) { return Ext.get(document.elementFromPoint(x, y)); } }); Ext.applyIf(Ext.Element, { getComputedTransformOffset: function(el) { if (el instanceof Ext.Element) el = el.dom; var transform = window.getComputedStyle(el).webkitTransform, cssMatrix = transform != 'none' ? new WebKitCSSMatrix(transform) : new WebKitCSSMatrix(); if (typeof cssMatrix.m41 != 'undefined') { return new Ext.util.Offset(cssMatrix.m41, cssMatrix.m42); } else if (typeof cssMatrix.d != 'undefined') { return new Ext.util.Offset(cssMatrix.d, cssMatrix.e); } return new Ext.util.Offset(0, 0); }, cssTransform: function(el, transforms) { if (el instanceof Ext.Element) el = el.dom; var m = new WebKitCSSMatrix(); Ext.iterate(transforms, function(n, v) { v = Ext.isArray(v) ? v : [v]; m = m[n].apply(m, v); }); if (Ext.supports.CSS3DTransform) { el.style.webkitTransform = 'matrix3d(' + m.m11+', '+m.m12+', '+m.m13+', '+m.m14+', '+ m.m21+', '+m.m22+', '+m.m23+', '+m.m24+', '+ m.m31+', '+m.m32+', '+m.m33+', '+m.m34+', '+ m.m41+', '+m.m42+', '+m.m43+', '+m.m44+ ')'; } else { el.style.webkitTransform = m; } }, cssTranslate: function(el, offset) { if (el instanceof Ext.Element) el = el.dom; if (Ext.supports.CSS3DTransform) { el.style.webkitTransform = 'translate3d('+offset.x+'px, '+offset.y+'px, 0px)'; } else { el.style.webkitTransform = 'translate('+offset.x+'px, '+offset.y+'px)'; } } }); Ext.Element.addMethods({ getY : function(el) { return this.getXY(el)[1]; }, getX : function(el) { return this.getXY(el)[0]; }, getXY : function() { var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0)); return [point.x, point.y]; }, getOffsetsTo : function(el){ var o = this.getXY(), e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, setXY : function(pos) { var me = this; if(arguments.length > 1) { pos = [pos, arguments[1]]; } var pts = me.translatePoints(pos), style = me.dom.style; for (pos in pts) { if (!pts.hasOwnProperty(pos)) { continue; } if(!isNaN(pts[pos])) style[pos] = pts[pos] + "px"; } return me; }, setX : function(x){ return this.setXY([x, this.getY()]); }, setY : function(y) { return this.setXY([this.getX(), y]); }, setLeft : function(left) { this.setStyle('left', Ext.Element.addUnits(left)); return this; }, setTop : function(top) { this.setStyle('top', Ext.Element.addUnits(top)); return this; }, setTopLeft: function(top, left) { var addUnits = Ext.Element.addUnits; this.setStyle('top', addUnits(top)); this.setStyle('left', addUnits(left)); return this; }, setRight : function(right) { this.setStyle('right', Ext.Element.addUnits(right)); return this; }, setBottom : function(bottom) { this.setStyle('bottom', Ext.Element.addUnits(bottom)); return this; }, getLeft : function(local) { return parseInt(this.getStyle('left'), 10) || 0; }, getRight : function(local) { return parseInt(this.getStyle('right'), 10) || 0; }, getTop : function(local) { return parseInt(this.getStyle('top'), 10) || 0; }, getBottom : function(local) { return parseInt(this.getStyle('bottom'), 10) || 0; }, setBox : function(left, top, width, height) { var undefined; if (Ext.isObject(left)) { width = left.width; height = left.height; top = left.top; left = left.left; } if (left !== undefined) { this.setLeft(left); } if (top !== undefined) { this.setTop(top); } if (width !== undefined) { this.setWidth(width); } if (height !== undefined) { this.setHeight(height); } return this; }, getBox : function(contentBox, local) { var me = this, dom = me.dom, width = dom.offsetWidth, height = dom.offsetHeight, xy, box, l, r, t, b; if (!local) { xy = me.getXY(); } else if (contentBox) { xy = [0,0]; } else { xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0]; } if (!contentBox) { box = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: width, height: height }; } else { l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l"); r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r"); t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t"); b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b"); box = { x: xy[0] + l, y: xy[1] + t, 0: xy[0] + l, 1: xy[1] + t, width: width - (l + r), height: height - (t + b) }; } box.left = box.x; box.top = box.y; box.right = box.x + box.width; box.bottom = box.y + box.height; return box; }, getPageBox : function(getRegion) { var me = this, el = me.dom, w = el.offsetWidth, h = el.offsetHeight, xy = me.getXY(), t = xy[1], r = xy[0] + w, b = xy[1] + h, l = xy[0]; if (!el) { return new Ext.util.Region(); } if (getRegion) { return new Ext.util.Region(t, r, b, l); } else { return { left: l, top: t, width: w, height: h, right: r, bottom: b }; } }, translatePoints : function(x, y) { y = isNaN(x[1]) ? y : x[1]; x = isNaN(x[0]) ? x : x[0]; var me = this, relative = me.isStyle('position', 'relative'), o = me.getXY(), l = parseInt(me.getStyle('left'), 10), t = parseInt(me.getStyle('top'), 10); l = !isNaN(l) ? l : (relative ? 0 : me.dom.offsetLeft); t = !isNaN(t) ? t : (relative ? 0 : me.dom.offsetTop); return {left: (x - o[0] + l), top: (y - o[1] + t)}; } }); (function() { Ext.Element.classReCache = {}; var El = Ext.Element, view = document.defaultView; El.addMethods({ marginRightRe: /marginRight/i, trimRe: /^\s+|\s+$/g, spacesRe: /\s+/, addCls: function(className) { var me = this, i, len, v, cls = []; if (!Ext.isArray(className)) { if (className && !this.hasCls(className)) { me.dom.className += " " + className; } } else { for (i = 0, len = className.length; i < len; i++) { v = className[i]; if (v && !me.hasCls(v)) { cls.push(v); } } if (cls.length) { me.dom.className += " " + cls.join(" "); } } return me; }, addClass : function() { throw new Error("Component: addClass has been deprecated. Please use addCls."); }, removeCls: function(className) { var me = this, i, idx, len, cls, elClasses; if (!Ext.isArray(className)) { className = [className]; } if (me.dom && me.dom.className) { elClasses = me.dom.className.replace(this.trimRe, '').split(this.spacesRe); for (i = 0, len = className.length; i < len; i++) { cls = className[i]; if (typeof cls == 'string') { cls = cls.replace(this.trimRe, ''); idx = elClasses.indexOf(cls); if (idx != -1) { elClasses.splice(idx, 1); } } } me.dom.className = elClasses.join(" "); } return me; }, removeClass : function() { throw new Error("Component: removeClass has been deprecated. Please use removeCls."); }, mask: function(msg, msgCls, transparent) { var me = this, dom = me.dom, el = Ext.Element.data(dom, 'mask'), mask, size, cls = ''; me.addCls('x-masked'); if (me.getStyle("position") == "static") { me.addCls('x-masked-relative'); } if (el) { el.remove(); } if (Ext.isString(msgCls) && !Ext.isEmpty(msgCls)) { cls = ' ' + msgCls; } else { if (msgCls) { cls = ' x-mask-gray'; } } mask = me.createChild({ cls: 'x-mask' + ((transparent !== false) ? '' : ' x-mask-gray'), html: msg ? ('<div class="' + (msgCls || 'x-mask-message') + '">' + msg + '</div>') : '' }); size = me.getSize(); Ext.Element.data(dom, 'mask', mask); if (dom === document.body) { size.height = window.innerHeight; if (me.orientationHandler) { Ext.EventManager.unOrientationChange(me.orientationHandler, me); } me.orientationHandler = function() { size = me.getSize(); size.height = window.innerHeight; mask.setSize(size); }; Ext.EventManager.onOrientationChange(me.orientationHandler, me); } mask.setSize(size); if (Ext.is.iPad) { Ext.repaint(); } }, unmask: function() { var me = this, dom = me.dom, mask = Ext.Element.data(dom, 'mask'); if (mask) { mask.remove(); Ext.Element.data(dom, 'mask', undefined); } me.removeCls(['x-masked', 'x-masked-relative']); if (dom === document.body) { Ext.EventManager.unOrientationChange(me.orientationHandler, me); delete me.orientationHandler; } }, radioCls: function(className) { var cn = this.dom.parentNode.childNodes, v; className = Ext.isArray(className) ? className: [className]; for (var i = 0, len = cn.length; i < len; i++) { v = cn[i]; if (v && v.nodeType == 1) { Ext.fly(v, '_internal').removeCls(className); } }; return this.addCls(className); }, radioClass : function() { throw new Error("Component: radioClass has been deprecated. Please use radioCls."); }, toggleCls: function(className) { return this.hasCls(className) ? this.removeCls(className) : this.addCls(className); }, toggleClass : function() { throw new Error("Component: toggleClass has been deprecated. Please use toggleCls."); }, hasCls: function(className) { return className && (' ' + this.dom.className + ' ').indexOf(' ' + className + ' ') != -1; }, hasClass : function() { throw new Error("Element: hasClass has been deprecated. Please use hasCls."); return this.hasCls.apply(this, arguments); }, replaceCls: function(oldClassName, newClassName) { return this.removeCls(oldClassName).addCls(newClassName); }, replaceClass : function() { throw new Error("Component: replaceClass has been deprecated. Please use replaceCls."); }, isStyle: function(style, val) { return this.getStyle(style) == val; }, getStyle: function(prop) { var dom = this.dom, result, display, cs, platform = Ext.is, style = dom.style; prop = El.normalize(prop); cs = (view) ? view.getComputedStyle(dom, '') : dom.currentStyle; result = (cs) ? cs[prop] : null; if (result && !platform.correctRightMargin && this.marginRightRe.test(prop) && style.position != 'absolute' && result != '0px') { display = style.display; style.display = 'inline-block'; result = view.getComputedStyle(dom, null)[prop]; style.display = display; } result || (result = style[prop]); if (!platform.correctTransparentColor && result == 'rgba(0, 0, 0, 0)') { result = 'transparent'; } return result; }, setStyle: function(prop, value) { var tmp, style; if (typeof prop == 'string') { tmp = {}; tmp[prop] = value; prop = tmp; } for (style in prop) { if (prop.hasOwnProperty(style)) { this.dom.style[El.normalize(style)] = prop[style]; } } return this; }, applyStyles: function(styles) { if (styles) { var i, len, dom = this.dom; if (typeof styles == 'function') { styles = styles.call(); } if (typeof styles == 'string') { styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); for (i = 0, len = styles.length; i < len;) { dom.style[El.normalize(styles[i++])] = styles[i++]; } } else if (typeof styles == 'object') { this.setStyle(styles); } } }, getHeight: function(contentHeight) { var dom = this.dom, height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight; return height > 0 ? height: 0; }, getWidth: function(contentWidth) { var dom = this.dom, width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth; return width > 0 ? width: 0; }, setWidth: function(width) { var me = this; me.dom.style.width = El.addUnits(width); return me; }, setHeight: function(height) { var me = this; me.dom.style.height = El.addUnits(height); return me; }, setSize: function(width, height) { var me = this, style = me.dom.style; if (Ext.isObject(width)) { height = width.height; width = width.width; } style.width = El.addUnits(width); style.height = El.addUnits(height); return me; }, getBorderWidth: function(side) { return this.sumStyles(side, El.borders); }, getPadding: function(side) { return this.sumStyles(side, El.paddings); }, getMargin: function(side) { return this.sumStyles(side, El.margins); }, getViewSize: function() { var doc = document, dom = this.dom; if (dom == doc || dom == doc.body) { return { width: El.getViewportWidth(), height: El.getViewportHeight() }; } else { return { width: dom.clientWidth, height: dom.clientHeight }; } }, getSize: function(contentSize) { var dom = this.dom; return { width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth), height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight) }; }, repaint: function() { var dom = this.dom; this.addCls("x-repaint"); dom.style.background = 'transparent none'; setTimeout(function() { dom.style.background = null; Ext.get(dom).removeCls("x-repaint"); }, 1); return this; }, getOuterWidth: function() { return this.getWidth() + this.getMargin('lr'); }, getOuterHeight: function() { return this.getHeight() + this.getMargin('tb'); }, sumStyles: function(sides, styles) { var val = 0, m = sides.match(/\w/g), len = m.length, s, i; for (i = 0; i < len; i++) { s = m[i] && parseFloat(this.getStyle(styles[m[i]])) || 0; if (s) { val += Math.abs(s); } } return val; } }); })(); Ext.Element.addMethods({ findParent : function(simpleSelector, maxDepth, returnEl) { var p = this.dom, b = document.body, depth = 0, stopEl; maxDepth = maxDepth || 50; if (isNaN(maxDepth)) { stopEl = Ext.getDom(maxDepth); maxDepth = Number.MAX_VALUE; } while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) { if (Ext.DomQuery.is(p, simpleSelector)) { return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, findParentNode : function(simpleSelector, maxDepth, returnEl) { var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, up : function(simpleSelector, maxDepth) { return this.findParentNode(simpleSelector, maxDepth, true); }, select : function(selector, composite) { return Ext.Element.select(selector, this.dom, composite); }, query : function(selector) { return Ext.DomQuery.select(selector, this.dom); }, down : function(selector, returnDom) { var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, child : function(selector, returnDom) { var node, me = this, id; id = Ext.get(me).id; id = id.replace(/[\.:]/g, "\\$0"); node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom); return returnDom ? node : Ext.get(node); }, parent : function(selector, returnDom) { return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, next : function(selector, returnDom) { return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, prev : function(selector, returnDom) { return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, first : function(selector, returnDom) { return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, last : function(selector, returnDom) { return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom) { if (!this.dom) return null; var n = this.dom[start]; while (n) { if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) { return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; } }); Ext.Element.addMethods({ getScrollParent : function() { var parent = this.dom, scroller; while (parent && parent != document.body) { if (parent.id && (scroller = Ext.ScrollManager.get(parent.id))) { return scroller; } parent = parent.parentNode; } return null; } }); Ext.Element.addMethods({ appendChild : function(el) { return Ext.get(el).appendTo(this); }, appendTo : function(el) { Ext.getDom(el).appendChild(this.dom); return this; }, insertBefore : function(el) { el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, insertAfter : function(el) { el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, insertFirst : function(el, returnDom) { el = el || {}; if (el.nodeType || el.dom || typeof el == 'string') { el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } else { return this.createChild(el, this.dom.firstChild, returnDom); } }, insertSibling: function(el, where, returnDom){ var me = this, rt, isAfter = (where || 'before').toLowerCase() == 'after', insertEl; if(Ext.isArray(el)){ insertEl = me; Ext.each(el, function(e) { rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom); if(isAfter){ insertEl = rt; } }); return rt; } el = el || {}; if(el.nodeType || el.dom){ rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom); if (!returnDom) { rt = Ext.get(rt); } }else{ if (isAfter && !me.dom.nextSibling) { rt = Ext.DomHelper.append(me.dom.parentNode, el, !returnDom); } else { rt = Ext.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom); } } return rt; }, replace : function(el) { el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, replaceWith: function(el){ var me = this; if(el.nodeType || el.dom || typeof el == 'string'){ el = Ext.get(el); me.dom.parentNode.insertBefore(el, me.dom); }else{ el = Ext.DomHelper.insertBefore(me.dom, el); } delete Ext.cache[me.id]; Ext.removeNode(me.dom); me.id = Ext.id(me.dom = el); Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me); return me; }, createChild : function(config, insertBefore, returnDom) { config = config || {tag:'div'}; if (insertBefore) { return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } else { return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); } }, wrap : function(config, returnDom) { var newEl = Ext.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, insertHtml : function(where, html, returnEl) { var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; } }); Ext.Element.addMethods({ getAnchorXY: function(anchor, local, size) { anchor = (anchor || "tl").toLowerCase(); size = size || {}; var me = this, vp = me.dom == document.body || me.dom == document, width = size.width || vp ? window.innerWidth: me.getWidth(), height = size.height || vp ? window.innerHeight: me.getHeight(), xy, rnd = Math.round, myXY = me.getXY(), extraX = vp ? 0: !local ? myXY[0] : 0, extraY = vp ? 0: !local ? myXY[1] : 0, hash = { c: [rnd(width * 0.5), rnd(height * 0.5)], t: [rnd(width * 0.5), 0], l: [0, rnd(height * 0.5)], r: [width, rnd(height * 0.5)], b: [rnd(width * 0.5), height], tl: [0, 0], bl: [0, height], br: [width, height], tr: [width, 0] }; xy = hash[anchor]; return [xy[0] + extraX, xy[1] + extraY]; }, getAlignToXY: function(el, position, offsets) { el = Ext.get(el); if (!el || !el.dom) { throw new Error("Element.alignToXY with an element that doesn't exist"); } offsets = offsets || [0, 0]; if (!position || position == '?') { position = 'tl-bl?'; } else if (! (/-/).test(position) && position !== "") { position = 'tl-' + position; } position = position.toLowerCase(); var me = this, matches = position.match(/^([a-z]+)-([a-z]+)(\?)?$/), dw = window.innerWidth, dh = window.innerHeight, p1 = "", p2 = "", a1, a2, x, y, swapX, swapY, p1x, p1y, p2x, p2y, width, height, region, constrain; if (!matches) { throw "Element.alignTo with an invalid alignment " + position; } p1 = matches[1]; p2 = matches[2]; constrain = !!matches[3]; a1 = me.getAnchorXY(p1, true); a2 = el.getAnchorXY(p2, false); x = a2[0] - a1[0] + offsets[0]; y = a2[1] - a1[1] + offsets[1]; if (constrain) { width = me.getWidth(); height = me.getHeight(); region = el.getPageBox(); p1y = p1.charAt(0); p1x = p1.charAt(p1.length - 1); p2y = p2.charAt(0); p2x = p2.charAt(p2.length - 1); swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t")); swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r")); if (x + width > dw) { x = swapX ? region.left - width: dw - width; } if (x < 0) { x = swapX ? region.right: 0; } if (y + height > dh) { y = swapY ? region.top - height: dh - height; } if (y < 0) { y = swapY ? region.bottom: 0; } } return [x, y]; } }); Ext.CompositeElement = function(els, root) { this.elements = []; this.add(els, root); this.el = new Ext.Element.Flyweight(); }; Ext.CompositeElement.prototype = { isComposite: true, getElement : function(el) { var e = this.el; e.dom = el; e.id = el.id; return e; }, transformElement : function(el) { return Ext.getDom(el); }, getCount : function() { return this.elements.length; }, add : function(els, root) { var me = this, elements = me.elements; if (!els) { return this; } if (typeof els == 'string') { els = Ext.Element.selectorFunction(els, root); } else if (els.isComposite) { els = els.elements; } else if (!Ext.isIterable(els)) { els = [els]; } for (var i = 0, len = els.length; i < len; ++i) { elements.push(me.transformElement(els[i])); } return me; }, invoke : function(fn, args) { var me = this, els = me.elements, len = els.length, e, i; for (i = 0; i < len; i++) { e = els[i]; if (e) { Ext.Element.prototype[fn].apply(me.getElement(e), args); } } return me; }, item : function(index) { var me = this, el = me.elements[index], out = null; if (el){ out = me.getElement(el); } return out; }, addListener : function(eventName, handler, scope, opt) { var els = this.elements, len = els.length, i, e; for (i = 0; i<len; i++) { e = els[i]; if (e) { Ext.EventManager.on(e, eventName, handler, scope || e, opt); } } return this; }, each : function(fn, scope) { var me = this, els = me.elements, len = els.length, i, e; for (i = 0; i<len; i++) { e = els[i]; if (e) { e = this.getElement(e); if(fn.call(scope || e, e, me, i)){ break; } } } return me; }, fill : function(els) { var me = this; me.elements = []; me.add(els); return me; }, filter : function(selector) { var els = [], me = this, elements = me.elements, fn = Ext.isFunction(selector) ? selector : function(el){ return el.is(selector); }; me.each(function(el, self, i){ if(fn(el, i) !== false){ els[els.length] = me.transformElement(el); } }); me.elements = els; return me; }, first : function() { return this.item(0); }, last : function() { return this.item(this.getCount()-1); }, contains : function(el) { return this.indexOf(el) != -1; }, indexOf : function(el) { return this.elements.indexOf(this.transformElement(el)); }, clear : function() { this.elements = []; } }; Ext.CompositeElement.prototype.on = Ext.CompositeElement.prototype.addListener; (function(){ var fnName, ElProto = Ext.Element.prototype, CelProto = Ext.CompositeElement.prototype; for (fnName in ElProto) { if (Ext.isFunction(ElProto[fnName])) { (function(fnName) { CelProto[fnName] = CelProto[fnName] || function(){ return this.invoke(fnName, arguments); }; }).call(CelProto, fnName); } } })(); if(Ext.DomQuery) { Ext.Element.selectorFunction = Ext.DomQuery.select; } Ext.Element.select = function(selector, root, composite) { var els; composite = (composite === false) ? false : true; if (typeof selector == "string") { els = Ext.Element.selectorFunction(selector, root); } else if (selector.length !== undefined) { els = selector; } else { throw new Error("Invalid selector"); } return composite ? new Ext.CompositeElement(els) : els; }; Ext.select = Ext.Element.select; Ext.CompositeElementLite = Ext.CompositeElement; Ext.apply(Ext.CompositeElementLite.prototype, { addElements : function(els, root){ if(!els){ return this; } if(typeof els == "string"){ els = Ext.Element.selectorFunction(els, root); } var yels = this.elements; Ext.each(els, function(e) { yels.push(Ext.get(e)); }); return this; }, removeElement : function(keys, removeDom){ var me = this, els = this.elements, el; Ext.each(keys, function(val){ if ((el = (els[val] || els[val = me.indexOf(val)]))) { if(removeDom){ if(el.dom){ el.remove(); }else{ Ext.removeNode(el); } } els.splice(val, 1); } }); return this; }, replaceElement : function(el, replacement, domReplace){ var index = !isNaN(el) ? el : this.indexOf(el), d; if(index > -1){ replacement = Ext.getDom(replacement); if(domReplace){ d = this.elements[index]; d.parentNode.insertBefore(replacement, d); Ext.removeNode(d); } this.elements.splice(index, 1, replacement); } return this; } }); Ext.DomHelper = { emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i, confRe : /tag|children|cn|html$/i, endRe : /end/i, markup : function(o) { var b = '', attr, val, key, keyVal, cn; if (typeof o == "string") { b = o; } else if (Ext.isArray(o)) { for (var i=0; i < o.length; i++) { if (o[i]) { b += this.markup(o[i]); } }; } else { b += '<' + (o.tag = o.tag || 'div'); for (attr in o) { if (!o.hasOwnProperty(attr)) { continue; } val = o[attr]; if (!this.confRe.test(attr)) { if (typeof val == "object") { b += ' ' + attr + '="'; for (key in val) { if (!val.hasOwnProperty(key)) { continue; } b += key + ':' + val[key] + ';'; }; b += '"'; } else { b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"'; } } }; if (this.emptyTags.test(o.tag)) { b += '/>'; } else { b += '>'; if ((cn = o.children || o.cn)) { b += this.markup(cn); } else if (o.html) { b += o.html; } b += '</' + o.tag + '>'; } } return b; }, applyStyles : function(el, styles) { if (styles) { var i = 0, len, style; el = Ext.fly(el); if (typeof styles == 'function') { styles = styles.call(); } if (typeof styles == 'string'){ styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); for(len = styles.length; i < len;){ el.setStyle(styles[i++], styles[i++]); } } else if (Ext.isObject(styles)) { el.setStyle(styles); } } }, insertHtml : function(where, el, html) { var hash = {}, hashVal, setStart, range, frag, rangeEl, rs; where = where.toLowerCase(); hash['beforebegin'] = ['BeforeBegin', 'previousSibling']; hash['afterend'] = ['AfterEnd', 'nextSibling']; range = el.ownerDocument.createRange(); setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); if (hash[where]) { range[setStart](el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling); return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling']; } else { rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child'; if (el.firstChild) { range[setStart](el[rangeEl]); frag = range.createContextualFragment(html); if (where == 'afterbegin') { el.insertBefore(frag, el.firstChild); } else { el.appendChild(frag); } } else { el.innerHTML = html; } return el[rangeEl]; } throw 'Illegal insertion point -> "' + where + '"'; }, insertBefore : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'beforebegin'); }, insertAfter : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling'); }, insertFirst : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild'); }, append : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'beforeend', '', true); }, overwrite : function(el, o, returnElement) { el = Ext.getDom(el); el.innerHTML = this.markup(o); return returnElement ? Ext.get(el.firstChild) : el.firstChild; }, doInsert : function(el, o, returnElement, pos, sibling, append) { var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o)); return returnElement ? Ext.get(newNode, true) : newNode; } }; Ext.DomQuery = { select : function(q, root) { var results = [], nodes, i, j, qlen, nlen; root = root || document; if (typeof root == 'string') { root = document.getElementById(root); } q = q.split(","); for (i = 0, qlen = q.length; i < qlen; i++) { if (typeof q[i] == 'string') { nodes = root.querySelectorAll(q[i]); for (j = 0, nlen = nodes.length; j < nlen; j++) { results.push(nodes[j]); } } } return results; }, selectNode : function(q, root) { return Ext.DomQuery.select(q, root)[0]; }, is : function(el, q) { if (typeof el == "string") { el = document.getElementById(el); } return Ext.DomQuery.select(q).indexOf(el) !== -1; } }; Ext.Element.selectorFunction = Ext.DomQuery.select; Ext.query = Ext.DomQuery.select; Ext.Anim = Ext.extend(Object, { isAnim: true, disableAnimations: false, defaultConfig: { from: {}, to: {}, duration: 250, delay: 0, easing: 'ease-in-out', autoClear: true, out: true, direction: null, reverse: false }, opposites: { 'left': 'right', 'right': 'left', 'up': 'down', 'down': 'up' }, constructor: function(config) { config = Ext.apply({}, config || {}, this.defaultConfig); this.config = config; Ext.Anim.superclass.constructor.call(this); this.running = []; }, initConfig : function(el, runConfig) { var me = this, runtime = {}, config = Ext.apply({}, runConfig || {}, me.config); config.el = el = Ext.get(el); if (config.reverse && me.opposites[config.direction]) { config.direction = me.opposites[config.direction]; } if (me.config.before) { me.config.before.call(config, el, config); } if (runConfig.before) { runConfig.before.call(config.scope || config, el, config); } return config; }, run: function(el, config) { el = Ext.get(el); config = config || {}; var me = this, style = el.dom.style, property, after = config.after; config = this.initConfig(el, config); if (this.disableAnimations) { for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = config.to[property]; } this.onTransitionEnd(null, el, { config: config, after: after }); return me; } el.un('webkitTransitionEnd', me.onTransitionEnd, me); style.webkitTransitionDuration = '0ms'; for (property in config.from) { if (!config.from.hasOwnProperty(property)) { continue; } style[property] = config.from[property]; } setTimeout(function() { if (!el.dom) { return; } if (config.is3d === true) { el.parent().setStyle({ '-webkit-perspective': '1200', '-webkit-transform-style': 'preserve-3d' }); } style.webkitTransitionDuration = config.duration + 'ms'; style.webkitTransitionProperty = 'all'; style.webkitTransitionTimingFunction = config.easing; el.on('webkitTransitionEnd', me.onTransitionEnd, me, { single: true, config: config, after: after }); for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = config.to[property]; } }, config.delay || 5); me.running[el.id] = config; return me; }, onTransitionEnd: function(ev, el, o) { el = Ext.get(el); var style = el.dom.style, config = o.config, property, me = this; if (config.autoClear) { for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = ''; } } style.webkitTransitionDuration = null; style.webkitTransitionProperty = null; style.webkitTransitionTimingFunction = null; if (config.is3d) { el.parent().setStyle({ '-webkit-perspective': '', '-webkit-transform-style': '' }); } if (me.config.after) { me.config.after.call(config, el, config); } if (o.after) { o.after.call(config.scope || me, el, config); } delete me.running[el.id]; } }); Ext.Anim.seed = 1000; Ext.Anim.run = function(el, anim, config) { if (el.isComponent) { el = el.el; } config = config || {}; if (anim.isAnim) { anim.run(el, config); } else { if (Ext.isObject(anim)) { if (config.before && anim.before) { config.before = Ext.createInterceptor(config.before, anim.before, anim.scope); } if (config.after && anim.after) { config.after = Ext.createInterceptor(config.after, anim.after, anim.scope); } config = Ext.apply({}, config, anim); anim = anim.type; } if (!Ext.anims[anim]) { throw anim + ' is not a valid animation type.'; } else { if (el && el.dom) { Ext.anims[anim].run(el, config); } } } }; Ext.anims = { fade: new Ext.Anim({ before: function(el) { var fromOpacity = 1, toOpacity = 1, curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), zIndex = curZ; if (this.out) { toOpacity = 0; } else { zIndex = curZ + 1; fromOpacity = 0; } this.from = { 'opacity': fromOpacity, 'z-index': zIndex }; this.to = { 'opacity': toOpacity, 'z-index': zIndex }; } }), slide: new Ext.Anim({ direction: 'left', cover: false, reveal: false, before: function(el) { var curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), zIndex = curZ + 1, toX = 0, toY = 0, fromX = 0, fromY = 0, elH = el.getHeight(), elW = el.getWidth(); if (this.direction == 'left' || this.direction == 'right') { if (this.out == true) { toX = -elW; } else { fromX = elW; } } else if (this.direction == 'up' || this.direction == 'down') { if (this.out == true) { toY = -elH; } else { fromY = elH; } } if (this.direction == 'right' || this.direction == 'down') { toY *= -1; toX *= -1; fromY *= -1; fromX *= -1; } if (this.cover && this.out) { toX = 0; toY = 0; zIndex = curZ; } else if (this.reveal && !this.out) { fromX = 0; fromY = 0; zIndex = curZ; } this.from = { '-webkit-transform': 'translate3d(' + fromX + 'px, ' + fromY + 'px, 0)', 'z-index': zIndex, 'opacity': 0.99 }; this.to = { '-webkit-transform': 'translate3d(' + toX + 'px, ' + toY + 'px, 0)', 'z-index': zIndex, 'opacity': 1 }; } }), pop: new Ext.Anim({ scaleOnExit: true, before: function(el) { var fromScale = 1, toScale = 1, fromOpacity = 1, toOpacity = 1, curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), fromZ = curZ, toZ = curZ; if (!this.out) { fromScale = 0.01; fromZ = curZ + 1; toZ = curZ + 1; fromOpacity = 0; } else { if (this.scaleOnExit) { toScale = 0.01; toOpacity = 0; } else { toOpacity = 0.8; } } this.from = { '-webkit-transform': 'scale(' + fromScale + ')', '-webkit-transform-origin': '50% 50%', 'opacity': fromOpacity, 'z-index': fromZ }; this.to = { '-webkit-transform': 'scale(' + toScale + ')', '-webkit-transform-origin': '50% 50%', 'opacity': toOpacity, 'z-index': toZ }; } }) }; Ext.apply(Ext.anims, { flip: new Ext.Anim({ is3d: true, direction: 'left', before: function(el) { var rotateProp = 'Y', fromScale = 1, toScale = 1, fromRotate = 0, toRotate = 0; if (this.out) { toRotate = -180; toScale = 0.8; } else { fromRotate = 180; fromScale = 0.8; } if (this.direction == 'up' || this.direction == 'down') { rotateProp = 'X'; } if (this.direction == 'right' || this.direction == 'left') { toRotate *= -1; fromRotate *= -1; } this.from = { '-webkit-transform': 'rotate' + rotateProp + '(' + fromRotate + 'deg) scale(' + fromScale + ')', '-webkit-backface-visibility': 'hidden' }; this.to = { '-webkit-transform': 'rotate' + rotateProp + '(' + toRotate + 'deg) scale(' + toScale + ')', '-webkit-backface-visibility': 'hidden' }; } }), cube: new Ext.Anim({ is3d: true, direction: 'left', style: 'outer', before: function(el) { var origin = '0% 0%', fromRotate = 0, toRotate = 0, rotateProp = 'Y', fromZ = 0, toZ = 0, fromOpacity = 1, toOpacity = 1, zDepth, elW = el.getWidth(), elH = el.getHeight(), showTranslateZ = true, fromTranslate = ' translateX(0)', toTranslate = ''; if (this.direction == 'left' || this.direction == 'right') { if (this.out) { origin = '100% 100%'; toZ = elW; toOpacity = 0.5; toRotate = -90; } else { origin = '0% 0%'; fromZ = elW; fromOpacity = 0.5; fromRotate = 90; } } else if (this.direction == 'up' || this.direction == 'down') { rotateProp = 'X'; if (this.out) { origin = '100% 100%'; toZ = elH; toRotate = 90; } else { origin = '0% 0%'; fromZ = elH; fromRotate = -90; } } if (this.direction == 'down' || this.direction == 'right') { fromRotate *= -1; toRotate *= -1; origin = (origin == '0% 0%') ? '100% 100%': '0% 0%'; } if (this.style == 'inner') { fromZ *= -1; toZ *= -1; fromRotate *= -1; toRotate *= -1; if (!this.out) { toTranslate = ' translateX(0px)'; origin = '0% 50%'; } else { toTranslate = fromTranslate; origin = '100% 50%'; } } this.from = { '-webkit-transform': 'rotate' + rotateProp + '(' + fromRotate + 'deg)' + (showTranslateZ ? ' translateZ(' + fromZ + 'px)': '') + fromTranslate, '-webkit-transform-origin': origin }; this.to = { '-webkit-transform': 'rotate' + rotateProp + '(' + toRotate + 'deg) translateZ(' + toZ + 'px)' + toTranslate, '-webkit-transform-origin': origin }; }, duration: 250 }), wipe: new Ext.Anim({ before: function(el) { var curZ = el.getStyle('z-index'), mask = '', toSize = '100%', fromSize = '100%'; if (!this.out) { zIndex = curZ + 1; mask = '-webkit-gradient(linear, left bottom, right bottom, from(transparent), to(#000), color-stop(66%, #000), color-stop(33%, transparent))'; toSize = el.getHeight() * 100 + 'px'; fromSize = el.getHeight(); this.from = { '-webkit-mask-image': mask, '-webkit-mask-size': el.getWidth() * 3 + 'px ' + el.getHeight() + 'px', 'z-index': zIndex, '-webkit-mask-position-x': 0 }; this.to = { '-webkit-mask-image': mask, '-webkit-mask-size': el.getWidth() * 3 + 'px ' + el.getHeight() + 'px', 'z-index': zIndex, '-webkit-mask-position-x': -el.getWidth() * 2 + 'px' }; } }, duration: 500 }) }); Ext.apply(Ext, { version : '1.0.1', versionDetail : { major : 1, minor : 0, patch : 1 }, setup: function(config) { if (config && typeof config == 'object') { if (config.addMetaTags !== false) { this.addMetaTags(config); } if (Ext.isFunction(config.onReady)) { var me = this; Ext.onReady(function() { var args = arguments; if (config.fullscreen !== false) { Ext.Viewport.init(function() { config.onReady.apply(me, args); }); } else { config.onReady.apply(this, args); } }, config.scope); } } }, getDom : function(el) { if (!el || !document) { return null; } return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el); }, removeNode : function(node) { if (node && node.parentNode && node.tagName != 'BODY') { Ext.EventManager.removeAll(node); node.parentNode.removeChild(node); delete Ext.cache[node.id]; } }, addMetaTags: function(config) { if (!Ext.isObject(config)) { return; } var head = Ext.get(document.getElementsByTagName('head')[0]), tag, precomposed; if (!Ext.is.Desktop) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'viewport', content: 'width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0;' }); head.appendChild(tag); } if (Ext.is.iOS) { if (config.fullscreen !== false) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'apple-mobile-web-app-capable', content: 'yes' }); head.appendChild(tag); if (Ext.isString(config.statusBarStyle)) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'apple-mobile-web-app-status-bar-style', content: config.statusBarStyle }); head.appendChild(tag); } } if (config.tabletStartupScreen && Ext.is.iPad) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-startup-image', href: config.tabletStartupScreen }); head.appendChild(tag); } if (config.phoneStartupScreen && !Ext.is.iPad) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-startup-image', href: config.phoneStartupScreen }); head.appendChild(tag); } if (config.icon) { config.phoneIcon = config.tabletIcon = config.icon; } precomposed = (config.glossOnIcon === false) ? '-precomposed' : ''; if (Ext.is.iPad && Ext.isString(config.tabletIcon)) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-icon' + precomposed, href: config.tabletIcon }); head.appendChild(tag); } else if (!Ext.is.iPad && Ext.isString(config.phoneIcon)) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-icon' + precomposed, href: config.phoneIcon }); head.appendChild(tag); } } } }); (function() { var initExt = function() { var bd = Ext.getBody(), cls = []; if (!bd) { return false; } var Is = Ext.is; if (Is.Phone) { cls.push('x-phone'); } else if (Is.Tablet) { cls.push('x-tablet'); } else if (Is.Desktop) { cls.push('x-desktop'); } if (Is.iPad) { cls.push('x-ipad'); } if (Is.iOS) { cls.push('x-ios'); } if (Is.Android) { cls.push('x-android'); } if (Is.Blackberry) { cls.push('x-bb'); } if (Is.Standalone) { cls.push('x-standalone'); } if (cls.length) { bd.addCls(cls); } return true; }; if (!initExt()) { Ext.onReady(initExt); } })(); Ext.Viewport = new (Ext.extend(Ext.util.Observable, { constructor: function() { var me = this; this.addEvents( 'orientationchange', 'resize' ); this.stretchSizes = {}; if (Ext.supports.OrientationChange) { window.addEventListener('orientationchange', Ext.createDelegate(me.onOrientationChange, me), false); } else { window.addEventListener('resize', Ext.createDelegate(me.onResize, me), false); } if (!Ext.desktop) { document.addEventListener('touchstart', Ext.createDelegate(me.onTouchStartCapturing, me), true); } }, init: function(fn, scope) { var me = this, stretchSize = Math.max(window.innerHeight, window.innerWidth) * 2, body = Ext.getBody(); me.updateOrientation(); this.initialHeight = window.innerHeight; this.initialOrientation = this.orientation; body.setHeight(stretchSize); Ext.gesture.Manager.freeze(); this.scrollToTop(); setTimeout(function() { me.scrollToTop(); setTimeout(function() { me.scrollToTop(); me.initialHeight = Math.max(me.initialHeight, window.innerHeight); if (fn) { fn.apply(scope || window); } me.updateBodySize(); Ext.gesture.Manager.thaw(); }, 500); }, 500); }, scrollToTop: function() { if (Ext.is.iOS) { document.body.scrollTop = document.body.scrollHeight; } else { window.scrollTo(0, 1); } }, updateBodySize: function() { Ext.getBody().setSize(window.innerWidth, window.innerHeight); }, updateOrientation: function() { this.lastSize = this.getSize(); this.orientation = this.getOrientation(); }, onTouchStartCapturing: function(e) { if (!Ext.currentlyFocusedField && Ext.is.iOS) { this.scrollToTop(); } }, onOrientationChange: function() { var me = this, body = Ext.getBody(); Ext.gesture.Manager.freeze(); body.setHeight(body.getWidth()); this.updateOrientation(); this.fireEvent('orientationchange', this, this.orientation); setTimeout(function() { me.scrollToTop(); setTimeout(function() { me.updateBodySize(); me.fireResizeEvent(); Ext.gesture.Manager.thaw(); }, 200); }, 200); }, fireResizeEvent: function() { var me = this; if (!Ext.is.iOS) { if (this.resizeEventTimer) { clearTimeout(this.resizeEventTimer); } this.resizeEventTimer = setTimeout(function() { me.fireEvent('resize', me, me.getSize()); }, 500); } else { me.fireEvent('resize', me, me.getSize()); } }, onResize: function() { if (this.orientation != this.getOrientation()) { this.onOrientationChange(); } else { var size = this.getSize(); if (!Ext.is.iOS && !Ext.is.Desktop) { if ((size.width == this.lastSize.width && size.height > this.lastSize.height) || (size.height == this.lastSize.height && size.width > this.lastSize.width)) { this.fireEvent('resize', this, size); } } else { this.fireEvent('resize', this, size); } } }, getSize: function() { var size = { width: window.innerWidth, height: window.innerHeight }; if (!Ext.is.Desktop) { size.height = (this.orientation == this.initialOrientation) ? Math.max(this.initialHeight, size.height) : size.height } return size; }, getOffset: function() { return { x: window.pageXOffset, y: window.pageYOffset }; }, getOrientation: function() { var size = this.getSize(); if (window.hasOwnProperty('orientation')) { return (window.orientation == 0 || window.orientation == 180) ? 'portrait' : 'landscape'; } else { if (!Ext.is.iOS && !Ext.is.Desktop) { if ((size.width == this.lastSize.width && size.height < this.lastSize.height) || (size.height == this.lastSize.height && size.width < this.lastSize.width)) { return this.orientation; } } return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; } } })); Ext.util.TapRepeater = Ext.extend(Ext.util.Observable, { constructor: function(el, config) { this.el = Ext.get(el); Ext.apply(this, config); this.addEvents( "touchstart", "tap", "touchend" ); this.el.on({ touchstart: this.onTouchStart, touchend: this.onTouchEnd, scope: this }); if (this.preventDefault || this.stopDefault) { this.el.on('tap', this.eventOptions, this); } Ext.util.TapRepeater.superclass.constructor.call(this); }, interval: 10, delay: 250, preventDefault: true, stopDefault: false, timer: 0, eventOptions: function(e) { if (this.preventDefault) { e.preventDefault(); } if (this.stopDefault) { e.stopEvent(); } }, destroy: function() { Ext.destroy(this.el); this.clearListeners(); }, onTouchStart: function(e) { clearTimeout(this.timer); if (this.pressClass) { this.el.addCls(this.pressClass); } this.tapStartTime = new Date(); this.fireEvent("touchstart", this, e); this.fireEvent("tap", this, e); if (this.accelerate) { this.delay = 400; } this.timer = Ext.defer(this.tap, this.delay || this.interval, this, [e]); }, tap: function(e) { this.fireEvent("tap", this, e); this.timer = Ext.defer(this.tap, this.accelerate ? this.easeOutExpo(Ext.util.Date.getElapsed(this.tapStartTime), 400, -390, 12000) : this.interval, this, [e]); }, easeOutExpo: function(t, b, c, d) { return (t == d) ? b + c : c * ( - Math.pow(2, -10 * t / d) + 1) + b; }, onTouchEnd: function(e) { clearTimeout(this.timer); this.el.removeCls(this.pressClass); this.fireEvent("touchend", this, e); } }); if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } return v; } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', {'': value}); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse'); }; } }()); Ext.util.JSON = { encode : function(o) { return JSON.stringify(o); }, decode : function(s) { return JSON.parse(s); } }; Ext.encode = Ext.util.JSON.encode; Ext.decode = Ext.util.JSON.decode; Ext.util.JSONP = { queue: [], current: null, request : function(o) { o = o || {}; if (!o.url) { return; } var me = this; o.params = o.params || {}; if (o.callbackKey) { o.params[o.callbackKey] = 'Ext.util.JSONP.callback'; } var params = Ext.urlEncode(o.params); var script = document.createElement('script'); script.type = 'text/javascript'; this.queue.push({ url: o.url, script: script, callback: o.callback || function(){}, scope: o.scope || window, params: params || null }); if (!this.current) { this.next(); } }, next : function() { this.current = null; if (this.queue.length) { this.current = this.queue.shift(); this.current.script.src = this.current.url + (this.current.params ? ('?' + this.current.params) : ''); document.getElementsByTagName('head')[0].appendChild(this.current.script); } }, callback: function(json) { this.current.callback.call(this.current.scope, json); document.getElementsByTagName('head')[0].removeChild(this.current.script); this.next(); } }; Ext.util.Draggable = Ext.extend(Ext.util.Observable, { baseCls: 'x-draggable', draggingCls: 'x-dragging', proxyCls: 'x-draggable-proxy', outOfBoundRestrictFactor: 1, direction: 'both', constrain: window, threshold: 0, delay: 0, cancelSelector: null, disabled: false, revert: false, group: 'base', useCssTransform: true, grid: null, snap: null, proxy: null, stack: false, animationDuration: 300, updateBoundaryOnTouchStart: true, offsetBoundary: null, dragging: false, vertical: false, horizontal: false, monitorOrientation: true, constructor: function(el, config) { this.el = Ext.get(el); this.id = el.id; config = config || {}; Ext.apply(this, config); this.addEvents( 'offsetchange' ); Ext.util.Draggable.superclass.constructor.call(this, config); if (this.eventTarget === 'parent') { this.eventTarget = this.el.parent(); } else { this.eventTarget = (this.eventTarget) ? Ext.get(this.eventTarget) : this.el; } if (this.direction == 'both') { this.horizontal = true; this.vertical = true; } else if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } this.el.addCls(this.baseCls); if (this.proxy) { this.getProxyEl().addCls(this.proxyCls); } this.startEventName = (this.delay > 0) ? 'taphold' : 'dragstart'; this.dragOptions = (this.delay > 0) ? {holdThreshold: this.delay} : { direction: this.direction, dragThreshold: this.threshold }; this.container = window; if (this.constrain) { if (this.constrain === 'parent') { this.container = this.el.parent(); } else if (this.constrain !== window) { this.container = Ext.get(this.constrain); } } this.offset = new Ext.util.Offset(); this.linearAnimation = { x: new Ext.util.Draggable.Animation.Linear(), y: new Ext.util.Draggable.Animation.Linear() }; this.updateBoundary(true); this.setDragging(false); if (!this.disabled) { this.enable(); } return this; }, enable: function() { return this.setEnabled(true); }, disable: function() { return this.setEnabled(false); }, setEnabled: function(enabled) { this.eventTarget[enabled ? 'on' : 'un'](this.startEventName, this.onStart, this, this.dragOptions); this.eventTarget[enabled ? 'on' : 'un']('drag', this.onDrag, this, this.dragOptions); this.eventTarget[enabled ? 'on' : 'un']('dragend', this.onDragEnd, this, this.dragOptions); this.eventTarget[enabled ? 'on' : 'un']('touchstart', this.onTouchStart, this); if (enabled) { Ext.EventManager.onOrientationChange(this.onOrientationChange, this); } else { Ext.EventManager.orientationEvent.removeListener(this.onOrientationChange, this); } this.disabled = !enabled; return this; }, setUseCssTransform: function(useCssTransform) { if (typeof useCssTransform == 'undefined') { useCssTransform = true; } if (useCssTransform != this.useCssTransform) { this.useCssTransform = useCssTransform; var resetOffset = new Ext.util.Offset(); if (useCssTransform == false) { this.setStyleOffset(this.offset); this.setTransformOffset(resetOffset, true); } else { this.setTransformOffset(this.offset); this.setStyleOffset(resetOffset); } } return this; }, setOffset: function(offset, animate) { if (!this.horizontal) { offset.x = 0; } if (!this.vertical) { offset.y = 0; } if (!(offset instanceof Ext.util.Offset)) { offset = Ext.util.Offset.fromObject(offset); } offset.round(); if (!this.offset.equals(offset)) { if (animate) { this.startAnimation(offset, animate); } else { this.offset = offset; this.region = new Ext.util.Region( this.initialRegion.top + offset.y, this.initialRegion.right + offset.x, this.initialRegion.bottom + offset.y, this.initialRegion.left + offset.x ); if (this.useCssTransform) { this.setTransformOffset(offset); } else { this.setStyleOffset(offset); } this.fireEvent('offsetchange', this, this.offset); } } return this; }, setTransformOffset: function(offset, clean) { if (clean) { this.getProxyEl().dom.style.webkitTransform = ''; } else { Ext.Element.cssTranslate(this.getProxyEl(), offset); } return this; }, setStyleOffset: function(offset) { this.getProxyEl().setLeft(offset.x); this.getProxyEl().setTop(offset.y); return this; }, startAnimation: function(offset, animate) { this.stopAnimation(); var currentTime = Date.now(); animate = Ext.isNumber(animate) ? animate : this.animationDuration; this.linearAnimation.x.set({ startOffset: this.offset.x, endOffset: offset.x, startTime: currentTime, duration: animate }); this.linearAnimation.y.set({ startOffset: this.offset.y, endOffset: offset.y, startTime: currentTime, duration: animate }); this.isAnimating = true; this.animationTimer = Ext.defer(this.handleAnimationFrame, 0, this); return this; }, stopAnimation: function() { if (this.isAnimating) { clearTimeout(this.animationTimer); this.isAnimating = false; this.setDragging(false); } return this; }, handleAnimationFrame: function() { if (!this.isAnimating) { return; } var newOffset = new Ext.util.Offset(); newOffset.x = this.linearAnimation.x.getOffset(); newOffset.y = this.linearAnimation.y.getOffset(); this.setOffset(newOffset); this.animationTimer = Ext.defer(this.handleAnimationFrame, 10, this); if ((newOffset.x === this.linearAnimation.x.endOffset) && (newOffset.y === this.linearAnimation.y.endOffset)) { this.stopAnimation(); } }, getOffset: function() { var offset = this.offset.copy(); offset.y = -offset.y; offset.x = -offset.x; return offset; }, updateBoundary: function(init) { var offsetBoundary; if (typeof init == 'undefined') init = false; this.size = { width: this.el.dom.scrollWidth, height: this.el.dom.scrollHeight }; if (this.container === window) { this.containerBox = { left: 0, top: 0, right: this.container.innerWidth, bottom: this.container.innerHeight, width: this.container.innerWidth, height: this.container.innerHeight }; } else { this.containerBox = this.container.getPageBox(); } var elXY = this.el.getXY(); this.elBox = { left: elXY[0] - this.offset.x, top: elXY[1] - this.offset.y, width: this.size.width, height: this.size.height }; this.elBox.bottom = this.elBox.top + this.elBox.height; this.elBox.right = this.elBox.left + this.elBox.width; this.initialRegion = this.region = new Ext.util.Region( elXY[1], elXY[0] + this.elBox.width, elXY[1] + this.elBox.height, elXY[0] ); var top = 0, right = 0, bottom = 0, left = 0; if (this.elBox.left < this.containerBox.left) { right += this.containerBox.left - this.elBox.left; } else { left -= this.elBox.left - this.containerBox.left; } if (this.elBox.right > this.containerBox.right) { left -= this.elBox.right - this.containerBox.right; } else { right += this.containerBox.right - this.elBox.right; } if (this.elBox.top < this.containerBox.top) { bottom += this.containerBox.top - this.elBox.top; } else { top -= this.elBox.top - this.containerBox.top; } if (this.elBox.bottom > this.containerBox.bottom) { top -= this.elBox.bottom - this.containerBox.bottom; } else { bottom += this.containerBox.bottom - this.elBox.bottom; } offsetBoundary = new Ext.util.Region(top, right, bottom, left).round(); if (this.offsetBoundary && this.offsetBoundary.equals(offsetBoundary)) { return this; } this.offsetBoundary = offsetBoundary; var currentComputedOffset; if (this.useCssTransform) { currentComputedOffset = Ext.Element.getComputedTransformOffset(this.getProxyEl()); } else { currentComputedOffset = new Ext.util.Offset(this.getProxyEl().getLeft(), this.getProxyEl().getTop()); } if(!this.offset.equals(currentComputedOffset) || init) { this.setOffset(currentComputedOffset); } return this; }, onTouchStart: function() { }, onStart: function(e) { if (this.updateBoundaryOnTouchStart) { this.updateBoundary(); } this.stopAnimation(); if (this.dragging) { this.onDragEnd(e); } this.setDragging(true); this.startTouchPoint = new Ext.util.Point(e.startX, e.startY); this.startOffset = this.offset.copy(); this.fireEvent('dragstart', this, e); return true; }, getNewOffsetFromTouchPoint: function(touchPoint) { var xDelta = touchPoint.x - this.startTouchPoint.x, yDelta = touchPoint.y - this.startTouchPoint.y, newOffset = this.offset.copy(); if(xDelta == 0 && yDelta == 0) { return newOffset; } if (this.horizontal) newOffset.x = this.startOffset.x + xDelta; if (this.vertical) newOffset.y = this.startOffset.y + yDelta; return newOffset; }, onDrag: function(e) { if (!this.dragging) { return; } this.lastTouchPoint = Ext.util.Point.fromEvent(e); var newOffset = this.getNewOffsetFromTouchPoint(this.lastTouchPoint); if (this.offsetBoundary != null) { newOffset = this.offsetBoundary.restrict(newOffset, this.outOfBoundRestrictFactor); } this.setOffset(newOffset); this.fireEvent('drag', this, e); return true; }, onDragEnd: function(e) { if (this.dragging) { this.fireEvent('beforedragend', this, e); if (this.revert && !this.cancelRevert) { this.setOffset(this.startOffset, true); } else { this.setDragging(false); } this.fireEvent('dragend', this, e); } return true; }, onOrientationChange: function() { this.updateBoundary(); }, setDragging: function(dragging) { if (dragging) { if (!this.dragging) { this.dragging = true; this.getProxyEl().addCls(this.draggingCls); } } else { if (this.dragging) { this.dragging = false; this.getProxyEl().removeCls(this.draggingCls); } } return this; }, getProxyEl: function() { return this.proxy || this.el; }, destroy: function() { this.el.removeCls(this.baseCls); this.getProxyEl().removeCls(this.proxyCls); this.clearListeners(); this.disable(); }, reset: function() { this.startOffset = new Ext.util.Offset(0, 0); this.setOffset(this.startOffset); var oldInitialRegion = this.initialRegion.copy(); this.updateBoundary(); this.initialRegion = this.region = this.getProxyEl().getPageBox(true); this.startTouchPoint.x += this.initialRegion.left - oldInitialRegion.left; this.startTouchPoint.y += this.initialRegion.top - oldInitialRegion.top; }, moveTo: function(x, y) { this.setOffset(new Ext.util.Offset(x - this.initialRegion.left, y - this.initialRegion.top)); return this; }, isDragging: function() { return this.dragging; }, isVertical : function() { return this.vertical; }, isHorizontal : function() { return this.horizontal; } }); Ext.util.Draggable.Animation = {}; Ext.util.Draggable.Animation.Abstract = Ext.extend(Object, { startTime: null, startOffset: 0, constructor: function(config) { config = config || {}; this.set(config); if (!this.startTime) this.startTime = Date.now(); }, set: function(name, value) { if (Ext.isObject(name)) { Ext.apply(this, name); } else { this[name] = value; } return this; }, getOffset: Ext.emptyFn }); Ext.util.Draggable.Animation.Linear = Ext.extend(Ext.util.Draggable.Animation.Abstract, { duration: 0, endOffset: 0, getOffset : function() { var distance = this.endOffset - this.startOffset, deltaTime = Date.now() - this.startTime, omegaTime = Math.min(1, (deltaTime / this.duration)); return this.startOffset + (omegaTime * distance); } }); Ext.util.Droppable = Ext.extend(Ext.util.Observable, { baseCls: 'x-droppable', activeCls: 'x-drop-active', invalidCls: 'x-drop-invalid', hoverCls: 'x-drop-hover', validDropMode: 'intersect', disabled: false, group: 'base', tolerance: null, monitoring: false, constructor : function(el, config) { config = config || {}; Ext.apply(this, config); this.addEvents( 'dropactivate', 'dropdeactivate', 'dropenter', 'dropleave', 'drop' ); this.el = Ext.get(el); Ext.util.Droppable.superclass.constructor.call(this); if (!this.disabled) { this.enable(); } this.el.addCls(this.baseCls); }, onDragStart : function(draggable, e) { if (draggable.group === this.group) { this.monitoring = true; this.el.addCls(this.activeCls); this.region = this.el.getPageBox(true); draggable.on({ drag: this.onDrag, beforedragend: this.onBeforeDragEnd, dragend: this.onDragEnd, scope: this }); if (this.isDragOver(draggable)) { this.setCanDrop(true, draggable, e); } this.fireEvent('dropactivate', this, draggable, e); } else { draggable.on({ dragend: function() { this.el.removeCls(this.invalidCls); }, scope: this, single: true }); this.el.addCls(this.invalidCls); } }, isDragOver : function(draggable, region) { return this.region[this.validDropMode](draggable.region); }, onDrag : function(draggable, e) { this.setCanDrop(this.isDragOver(draggable), draggable, e); }, setCanDrop : function(canDrop, draggable, e) { if (canDrop && !this.canDrop) { this.canDrop = true; this.el.addCls(this.hoverCls); this.fireEvent('dropenter', this, draggable, e); } else if (!canDrop && this.canDrop) { this.canDrop = false; this.el.removeCls(this.hoverCls); this.fireEvent('dropleave', this, draggable, e); } }, onBeforeDragEnd: function(draggable, e) { draggable.cancelRevert = this.canDrop; }, onDragEnd : function(draggable, e) { this.monitoring = false; this.el.removeCls(this.activeCls); draggable.un({ drag: this.onDrag, beforedragend: this.onBeforeDragEnd, dragend: this.onDragEnd, scope: this }); if (this.canDrop) { this.canDrop = false; this.el.removeCls(this.hoverCls); this.fireEvent('drop', this, draggable, e); } this.fireEvent('dropdeactivate', this, draggable, e); }, enable : function() { if (!this.mgr) { this.mgr = Ext.util.Observable.observe(Ext.util.Draggable); } this.mgr.on({ dragstart: this.onDragStart, scope: this }); this.disabled = false; }, disable : function() { this.mgr.un({ dragstart: this.onDragStart, scope: this }); this.disabled = true; }, isDisabled : function() { return this.disabled; }, isMonitoring : function() { return this.monitoring; } }); (function(){ Ext.ScrollManager = new Ext.AbstractManager(); Ext.util.ScrollView = Ext.extend(Ext.util.Observable, { useIndicators: true, indicatorConfig: {}, indicatorMargin: 4, constructor: function(el, config) { var indicators = [], directions = ['vertical', 'horizontal']; Ext.util.ScrollView.superclass.constructor.call(this); ['useIndicators', 'indicatorConfig', 'indicatorMargin'].forEach(function(c) { if (config.hasOwnProperty(c)) { this[c] = config[c]; delete config[c]; } }, this); config.scrollView = this; this.scroller = new Ext.util.Scroller(el, config); if (this.useIndicators === true) { directions.forEach(function(d) { if (this.scroller[d]) { indicators.push(d); } }, this); } else if (directions.indexOf(this.useIndicators) !== -1) { indicators.push(this.useIndicators); } this.indicators = {}; indicators.forEach(function(i) { this.indicators[i] = new Ext.util.Scroller.Indicator(this.scroller.container, Ext.apply({}, this.indicatorConfig, {type: i})); }, this); this.mon(this.scroller, { scrollstart: this.onScrollStart, scrollend: this.onScrollEnd, scroll: this.onScroll, scope: this }); }, onScrollStart: function() { this.showIndicators(); }, onScrollEnd: function() { this.hideIndicators(); }, onScroll: function(scroller) { if (scroller.offsetBoundary == null || (!this.indicators.vertical && !this.indicators.horizontal)) return; var sizeAxis, offsetAxis, offsetMark, boundary = scroller.offsetBoundary, offset = scroller.offset; this.containerSize = scroller.containerBox; this.scrollerSize = scroller.size; this.outOfBoundOffset = boundary.getOutOfBoundOffset(offset); this.restrictedOffset = boundary.restrict(offset); this.boundarySize = boundary.getSize(); if (!this.indicatorSizes) { this.indicatorSizes = {vertical: 0, horizontal: 0}; } if (!this.indicatorOffsets) { this.indicatorOffsets = {vertical: 0, horizontal: 0}; } Ext.iterate(this.indicators, function(axis, indicator) { sizeAxis = (axis == 'vertical') ? 'height' : 'width'; offsetAxis = (axis == 'vertical') ? 'y' : 'x'; offsetMark = (axis == 'vertical') ? 'bottom' : 'right'; if (this.scrollerSize[sizeAxis] < this.containerSize[sizeAxis]) { this.indicatorSizes[axis] = this.containerSize[sizeAxis] * (this.scrollerSize[sizeAxis] / this.containerSize[sizeAxis]); } else { this.indicatorSizes[axis] = this.containerSize[sizeAxis] * (this.containerSize[sizeAxis] / this.scrollerSize[sizeAxis]); } this.indicatorSizes[axis] -= Math.abs(this.outOfBoundOffset[offsetAxis]); this.indicatorSizes[axis] = Math.max(this.indicatorMargin * 4, this.indicatorSizes[axis]); if (this.boundarySize[sizeAxis] != 0) { this.indicatorOffsets[axis] = (((boundary[offsetMark] - this.restrictedOffset[offsetAxis]) / this.boundarySize[sizeAxis]) * (this.containerSize[sizeAxis] - this.indicatorSizes[axis])); } else if (offset[offsetAxis] < boundary[offsetMark]) { this.indicatorOffsets[axis] = this.containerSize[sizeAxis] - this.indicatorSizes[axis]; } else { this.indicatorOffsets[axis] = 0; } indicator.setOffset(this.indicatorOffsets[axis] + this.indicatorMargin); indicator.setSize(this.indicatorSizes[axis] - (this.indicatorMargin * 2)); }, this); }, showIndicators : function() { Ext.iterate(this.indicators, function(axis, indicator) { indicator.show(); }, this); return this; }, hideIndicators : function() { Ext.iterate(this.indicators, function(axis, indicator) { indicator.hide(); }, this); }, destroy: function() { this.scroller.destroy(); if (this.indicators) { Ext.iterate(this.indicators, function(axis, indicator) { indicator.destroy(); }, this); } return Ext.util.ScrollView.superclass.destroy.apply(this, arguments); } }); Ext.util.Scroller = Ext.extend(Ext.util.Draggable, { baseCls: '', draggingCls: '', direction: 'both', constrain: 'parent', outOfBoundRestrictFactor: 0.5, acceleration: 30, fps: Ext.is.Blackberry ? 22 : 80, autoAdjustFps: !Ext.is.Blackberry, friction: 0.5, startMomentumResetTime: 350, springTension: 0.3, minVelocityForAnimation: 1, bounces: true, momentum: true, cancelRevert: true, threshold: 5, constructor: function(el, config) { el = Ext.get(el); var scroller = Ext.ScrollManager.get(el.id); if (scroller) { return Ext.apply(scroller, config); } Ext.util.Scroller.superclass.constructor.apply(this, arguments); this.addEvents( 'scrollstart', 'scroll', 'scrollend', 'bouncestart', 'bounceend' ); this.on({ dragstart: this.onDragStart, offsetchange: this.onOffsetChange, scope: this }); Ext.ScrollManager.register(this); this.el.addCls('x-scroller'); this.container.addCls('x-scroller-parent'); if (this.bounces !== false) { var both = this.bounces === 'both' || this.bounces === true, horizontal = both || this.bounces === 'horizontal', vertical = both || this.bounces === 'vertical'; this.bounces = { x: horizontal, y: vertical }; } this.theta = Math.log(1 - (this.friction / 10)); if (!this.decelerationAnimation) { this.decelerationAnimation = {}; } if (!this.bouncingAnimation) { this.bouncingAnimation = {}; } ['x', 'y'].forEach(function(a) { if (!this.decelerationAnimation[a]) { this.decelerationAnimation[a] = new Ext.util.Scroller.Animation.Deceleration({ acceleration: this.acceleration, theta: this.theta }); } if (!this.bouncingAnimation[a]) { this.bouncingAnimation[a] = new Ext.util.Scroller.Animation.Bouncing({ acceleration: this.acceleration, springTension: this.springTension }); } }, this); return this; }, getFrameDuration: function() { return 1000 / this.fps; }, updateBoundary: function() { Ext.util.Scroller.superclass.updateBoundary.apply(this, arguments); this.snapToBoundary(); return this; }, onOffsetChange: function(scroller, offset) { this.fireEvent('scroll', scroller, { x: -offset.x, y: -offset.y }); }, onTouchStart: function(e) { Ext.util.Scroller.superclass.onTouchStart.apply(this, arguments); this.stopMomentumAnimation(); }, onDragStart: function(e) { this.fireEvent('scrollstart', this, e); }, setStartTime: function(e) { this.startTime = e.time; this.originalStartTime = (e.event.originalTimeStamp) ? e.event.originalTimeStamp : e.time; }, onStart: function(e) { if (Ext.util.Scroller.superclass.onStart.apply(this, arguments) !== true) return; this.setStartTime(e); this.lastEventTime = e.time; this.startTimeOffset = this.offset.copy(); this.isScrolling = true; this.momentumAnimationFramesHandled = 0; }, onDrag: function(e) { if (Ext.util.Scroller.superclass.onDrag.apply(this, arguments) !== true) return; this.lastEventTime = e.time; if (this.lastEventTime - this.startTime > this.startMomentumResetTime) { this.setStartTime(e); this.startTimeOffset = this.offset.copy(); } }, onDragEnd: function(e) { if (Ext.util.Scroller.superclass.onDragEnd.apply(this, arguments) !== true) return; if (!this.startMomentumAnimation(e)) { this.fireScrollEndEvent(); } }, onOrientationChange: function() { Ext.util.Scroller.superclass.onOrientationChange.apply(this, arguments); this.snapToBoundary(); }, fireScrollEndEvent: function() { this.isScrolling = false; this.isMomentumAnimating = false; this.snapToBoundary(); this.fireEvent('scrollend', this, this.getOffset()); this.snapToSlot(); }, getLastActualFps: function() { var duration = (this.momentumAnimationEndTime - this.momentumAnimationStartTime - this.momentumAnimationProcessingTime) / 1000; return this.momentumAnimationFramesHandled / duration; }, scrollTo: function(pos, animate) { this.stopMomentumAnimation(); var newOffset = this.offsetBoundary.restrict(new Ext.util.Offset(-pos.x, -pos.y)); this.setOffset(newOffset, animate); return this; }, scrollBy: function(offset, animate) { this.stopMomentumAnimation(); var newOffset = this.offset.copy(); newOffset.x += offset.x; newOffset.y += offset.y; this.setOffset(newOffset, animate); return this; }, setSnap: function(snap) { this.snap = snap; }, snapToBoundary: function() { var offset = this.offsetBoundary.restrict(this.offset); this.setOffset(offset); return this; }, snapToSlot: function() { var offset = this.offsetBoundary.restrict(this.offset); offset.round(); if (this.snap) { if (this.snap === true) { this.snap = { x: 50, y: 50 }; } else if (Ext.isNumber(this.snap)) { this.snap = { x: this.snap, y: this.snap }; } if (this.snap.y) { offset.y = Math.round(offset.y / this.snap.y) * this.snap.y; } if (this.snap.x) { offset.x = Math.round(offset.x / this.snap.x) * this.snap.x; } if (!this.offset.equals(offset)) { this.scrollTo({x: -offset.x, y: -offset.y}, this.snapDuration); } } }, startMomentumAnimation: function(e) { var originalTime = (e.event.originalTimeStamp) ? e.event.originalTimeStamp : e.time, duration = originalTime - this.originalStartTime; if ( (!this.momentum || !(duration <= this.startMomentumResetTime)) && !this.offsetBoundary.isOutOfBound(this.offset) ) { return false; } var minVelocity = this.minVelocityForAnimation, currentVelocity, currentOffset = this.offset.copy(), restrictedOffset; this.isBouncing = {x: false, y: false}; this.isDecelerating = {x: false, y: false}; this.momentumAnimationStartTime = e.time; this.momentumAnimationProcessingTime = 0; this.momentumAnimationStartVelocity = { x: (this.offset.x - this.startTimeOffset.x) / (duration / this.acceleration), y: (this.offset.y - this.startTimeOffset.y) / (duration / this.acceleration) }; this.momentumAnimationStartOffset = currentOffset; ['x', 'y'].forEach(function(axis) { this.isDecelerating[axis] = (Math.abs(this.momentumAnimationStartVelocity[axis]) > minVelocity); if (this.bounces && this.bounces[axis]) { restrictedOffset = this.offsetBoundary.restrict(axis, currentOffset[axis]); if (restrictedOffset != currentOffset[axis]) { currentVelocity = (currentOffset[axis] - restrictedOffset) * this.springTension * Math.E; this.bouncingAnimation[axis].set({ startTime: this.momentumAnimationStartTime - ((1 / this.springTension) * this.acceleration), startOffset: restrictedOffset, startVelocity: currentVelocity }); this.isBouncing[axis] = true; this.fireEvent('bouncestart', this, { axis: axis, offset: restrictedOffset, time: this.momentumAnimationStartTime, velocity: currentVelocity }); this.isDecelerating[axis] = false; } } if (this.isDecelerating[axis]) { this.decelerationAnimation[axis].set({ startVelocity: this.momentumAnimationStartVelocity[axis], startOffset: this.momentumAnimationStartOffset[axis], startTime: this.momentumAnimationStartTime }); } }, this); if (this.isDecelerating.x || this.isDecelerating.y || this.isBouncing.x || this.isBouncing.y) { this.isMomentumAnimating = true; this.momentumAnimationFramesHandled = 0; this.fireEvent('momentumanimationstart'); this.momentumAnimationTimer = Ext.defer(this.handleMomentumAnimationFrame, this.getFrameDuration(), this); return true; } return false; }, stopMomentumAnimation: function() { if (this.isMomentumAnimating) { if (this.momentumAnimationTimer) { clearTimeout(this.momentumAnimationTimer); } this.momentumAnimationEndTime = Date.now(); var lastFps = this.getLastActualFps(); if (!this.maxFps || lastFps > this.maxFps) { this.maxFps = lastFps; } if (this.autoAdjustFps) { this.fps = this.maxFps; } this.isDecelerating = {}; this.isBouncing = {}; this.fireEvent('momentumanimationend'); this.fireScrollEndEvent(); } return this; }, handleMomentumAnimationFrame : function() { if (!this.isMomentumAnimating) { return; } this.momentumAnimationTimer = Ext.defer(this.handleMomentumAnimationFrame, this.getFrameDuration(), this); var currentTime = Date.now(), newOffset = this.offset.copy(), currentVelocity, restrictedOffset, outOfBoundDistance; ['x', 'y'].forEach(function(axis) { if (this.isDecelerating[axis]) { newOffset[axis] = this.decelerationAnimation[axis].getOffset(); currentVelocity = this.momentumAnimationStartVelocity[axis] * this.decelerationAnimation[axis].getFrictionFactor(); outOfBoundDistance = this.offsetBoundary.getOutOfBoundOffset(axis, newOffset[axis]); if (outOfBoundDistance != 0) { restrictedOffset = this.offsetBoundary.restrict(axis, newOffset[axis]); if (this.bounces && this.bounces[axis]) { this.bouncingAnimation[axis].set({ startTime: currentTime, startOffset: restrictedOffset, startVelocity: currentVelocity }); this.isBouncing[axis] = true; this.fireEvent('bouncestart', this, { axis: axis, offset: restrictedOffset, time: currentTime, velocity: currentVelocity }); } this.isDecelerating[axis] = false; } else if (Math.abs(currentVelocity) <= 1) { this.isDecelerating[axis] = false; } } else if (this.isBouncing[axis]) { newOffset[axis] = this.bouncingAnimation[axis].getOffset(); restrictedOffset = this.offsetBoundary.restrict(axis, newOffset[axis]); if (Math.abs(newOffset[axis] - restrictedOffset) <= 1) { this.isBouncing[axis] = false; this.fireEvent('bounceend', this, { axis: axis, offset: restrictedOffset, time: currentTime, velocity: 0 }); newOffset[axis] = restrictedOffset; } } }, this); if (!this.isDecelerating.x && !this.isDecelerating.y && !this.isBouncing.x && !this.isBouncing.y) { this.stopMomentumAnimation(); return; } this.momentumAnimationFramesHandled++; this.momentumAnimationProcessingTime += Date.now() - currentTime; this.setOffset(newOffset); }, destroy: function() { return Ext.util.Scroller.superclass.destroy.apply(this, arguments); } }); Ext.util.Scroller.Animation = {}; Ext.util.Scroller.Animation.Deceleration = Ext.extend(Ext.util.Draggable.Animation.Abstract, { acceleration: 30, theta: null, startVelocity: null, getOffset: function() { return this.startOffset - this.startVelocity * (1 - this.getFrictionFactor()) / this.theta; }, getFrictionFactor : function() { var deltaTime = Date.now() - this.startTime; return Math.exp(deltaTime / this.acceleration * this.theta); } }); Ext.util.Scroller.Animation.Bouncing = Ext.extend(Ext.util.Draggable.Animation.Abstract, { springTension: 0.3, acceleration: 30, startVelocity: null, getOffset: function() { var deltaTime = (Date.now() - this.startTime), powTime = (deltaTime / this.acceleration) * Math.pow(Math.E, -this.springTension * (deltaTime / this.acceleration)); return this.startOffset + (this.startVelocity * powTime); } }); Ext.util.Scroller.Indicator = Ext.extend(Object, { baseCls: 'x-scrollbar', ui: 'dark', type: 'horizontal', constructor: function(container, config) { this.container = container; Ext.apply(this, config); this.el = this.container.createChild({ cls: [this.baseCls, this.baseCls + '-' + this.type, this.baseCls + '-' + this.ui].join(' ') }); this.offset = new Ext.util.Offset(); this.hide(); }, hide: function() { var me = this; if (this.hideTimer) { clearTimeout(this.hideTimer); } this.hideTimer = setTimeout(function() { me.el.setStyle('opacity', 0); }, 100); return this; }, show: function() { if (this.hideTimer) { clearTimeout(this.hideTimer); } this.el.setStyle('opacity', 1); return this; }, setVisibility: function(isVisible) { return this[isVisible ? 'show' : 'hide'](); }, setSize: function(size) { if (this.size && size > this.size) { size = Math.round(size); } this.el.dom.style[(this.type == 'horizontal') ? 'width' : 'height'] = size + 'px'; this.size = size; return this; }, setOffset: function(offset) { if (this.type == 'vertical') { this.offset.y = offset; } else { this.offset.x = offset; } if (!Ext.is.iOS && !Ext.is.Desktop) { if (this.type == 'vertical') { this.el.dom.style.top = this.offset.y + 'px'; } else { this.el.dom.style.left = this.offset.x + 'px'; } } else { Ext.Element.cssTranslate(this.el, this.offset); } return this; } }); })(); Ext.util.Sortable = Ext.extend(Ext.util.Observable, { baseCls: 'x-sortable', direction: 'vertical', cancelSelector: null, constrain: window, group: 'base', revert: true, itemSelector: null, handleSelector: null, disabled: false, delay: 0, sorting: false, vertical: false, vertical: false, constructor : function(el, config) { config = config || {}; Ext.apply(this, config); this.addEvents( 'sortstart', 'sortend', 'sortchange' ); this.el = Ext.get(el); Ext.util.Sortable.superclass.constructor.call(this); if (this.direction == 'horizontal') { this.horizontal = true; } else if (this.direction == 'vertical') { this.vertical = true; } else { this.horizontal = this.vertical = true; } this.el.addCls(this.baseCls); if (!this.disabled) { this.enable(); } }, onTouchStart : function(e, t) { if (this.cancelSelector && e.getTarget(this.cancelSelector)) { return; } if (this.handleSelector && !e.getTarget(this.handleSelector)) { return; } if (!this.sorting) { this.onSortStart(e, t); } }, onSortStart : function(e, t) { this.sorting = true; var draggable = new Ext.util.Draggable(t, { delay: this.delay, revert: this.revert, direction: this.direction, constrain: this.constrain === true ? this.el : this.constrain, animationDuration: 100 }); draggable.on({ dragThreshold: 0, drag: this.onDrag, dragend: this.onDragEnd, scope: this }); this.dragEl = t; this.calculateBoxes(); if (!draggable.dragging) { draggable.onStart(e); } this.fireEvent('sortstart', this, e); }, calculateBoxes : function() { this.items = []; var els = this.el.select(this.itemSelector, false), ln = els.length, i, item, el, box; for (i = 0; i < ln; i++) { el = els[i]; if (el != this.dragEl) { item = Ext.fly(el).getPageBox(true); item.el = el; this.items.push(item); } } }, onDrag : function(draggable, e) { var items = this.items, ln = items.length, region = draggable.region, sortChange = false, i, intersect, overlap, item; for (i = 0; i < ln; i++) { item = items[i]; intersect = region.intersect(item); if (intersect) { if (this.vertical && Math.abs(intersect.top - intersect.bottom) > (region.bottom - region.top) / 2) { if (region.bottom > item.top && item.top > region.top) { draggable.el.insertAfter(item.el); } else { draggable.el.insertBefore(item.el); } sortChange = true; } else if (this.horizontal && Math.abs(intersect.left - intersect.right) > (region.right - region.left) / 2) { if (region.right > item.left && item.left > region.left) { draggable.el.insertAfter(item.el); } else { draggable.el.insertBefore(item.el); } sortChange = true; } if (sortChange) { draggable.reset(); draggable.moveTo(region.left, region.top); this.calculateBoxes(); this.fireEvent('sortchange', this, draggable.el, this.el.select(this.itemSelector, false).indexOf(draggable.el.dom)); return; } } } }, onDragEnd : function(draggable, e) { draggable.destroy(); this.sorting = false; this.fireEvent('sortend', this, draggable, e); }, enable : function() { this.el.on('touchstart', this.onTouchStart, this, {delegate: this.itemSelector}); this.disabled = false; }, disable : function() { this.el.un('touchstart', this.onTouchStart, this); this.disabled = true; }, isDisabled : function() { return this.disabled; }, isSorting : function() { return this.sorting; }, isVertical : function() { return this.vertical; }, isHorizontal : function() { return this.horizontal; } }); (function() { Date.useStrict = false; function xf(format) { var args = Array.prototype.slice.call(arguments, 1); return format.replace(/\{(\d+)\}/g, function(m, i) { return args[i]; }); } Date.formatCodeToRegex = function(character, currentGroup) { var p = Date.parseCodes[character]; if (p) { p = typeof p == 'function' ? p() : p; Date.parseCodes[character] = p; } return p ? Ext.applyIf({ c: p.c ? xf(p.c, currentGroup || "{0}") : p.c }, p) : { g: 0, c: null, s: Ext.util.Format.escapeRegex(character) }; }; var $f = Date.formatCodeToRegex; Ext.apply(Date, { parseFunctions: { "M$": function(input, strict) { var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'); var r = (input || '').match(re); return r ? new Date(((r[1] || '') + r[2]) * 1) : null; } }, parseRegexes: [], formatFunctions: { "M$": function() { return '\\/Date(' + this.getTime() + ')\\/'; } }, y2kYear: 50, MILLI: "ms", SECOND: "s", MINUTE: "mi", HOUR: "h", DAY: "d", MONTH: "mo", YEAR: "y", defaults: {}, dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], monthNumbers: { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }, getShortMonthName: function(month) { return Date.monthNames[month].substring(0, 3); }, getShortDayName: function(day) { return Date.dayNames[day].substring(0, 3); }, getMonthNumber: function(name) { return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }, formatCodes: { d: "Ext.util.Format.leftPad(this.getDate(), 2, '0')", D: "Date.getShortDayName(this.getDay())", j: "this.getDate()", l: "Date.dayNames[this.getDay()]", N: "(this.getDay() ? this.getDay() : 7)", S: "this.getSuffix()", w: "this.getDay()", z: "this.getDayOfYear()", W: "Ext.util.Format.leftPad(this.getWeekOfYear(), 2, '0')", F: "Date.monthNames[this.getMonth()]", m: "Ext.util.Format.leftPad(this.getMonth() + 1, 2, '0')", M: "Date.getShortMonthName(this.getMonth())", n: "(this.getMonth() + 1)", t: "this.getDaysInMonth()", L: "(this.isLeapYear() ? 1 : 0)", o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))", Y: "this.getFullYear()", y: "('' + this.getFullYear()).substring(2, 4)", a: "(this.getHours() < 12 ? 'am' : 'pm')", A: "(this.getHours() < 12 ? 'AM' : 'PM')", g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)", G: "this.getHours()", h: "Ext.util.Format.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')", H: "Ext.util.Format.leftPad(this.getHours(), 2, '0')", i: "Ext.util.Format.leftPad(this.getMinutes(), 2, '0')", s: "Ext.util.Format.leftPad(this.getSeconds(), 2, '0')", u: "Ext.util.Format.leftPad(this.getMilliseconds(), 3, '0')", O: "this.getGMTOffset()", P: "this.getGMTOffset(true)", T: "this.getTimezone()", Z: "(this.getTimezoneOffset() * -60)", c: function() { for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) { var e = c.charAt(i); code.push(e == "T" ? "'T'": Date.getFormatCode(e)); } return code.join(" + "); }, U: "Math.round(this.getTime() / 1000)" }, isValid: function(y, m, d, h, i, s, ms) { h = h || 0; i = i || 0; s = s || 0; ms = ms || 0; var dt = new Date(y, m - 1, d, h, i, s, ms); return y == dt.getFullYear() && m == dt.getMonth() + 1 && d == dt.getDate() && h == dt.getHours() && i == dt.getMinutes() && s == dt.getSeconds() && ms == dt.getMilliseconds(); }, parseDate: function(input, format, strict) { var p = Date.parseFunctions; if (p[format] == null) { Date.createParser(format); } return p[format](input, Ext.isDefined(strict) ? strict: Date.useStrict); }, getFormatCode: function(character) { var f = Date.formatCodes[character]; if (f) { f = typeof f == 'function' ? f() : f; Date.formatCodes[character] = f; } return f || ("'" + Ext.util.Format.escape(character) + "'"); }, createFormat: function(format) { var code = [], special = false, ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; code.push("'" + Ext.util.Format.escape(ch) + "'"); } else { code.push(Date.getFormatCode(ch)); } } Date.formatFunctions[format] = new Function("return " + code.join('+')); }, createParser: function() { var code = [ "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,", "def = Date.defaults,", "results = String(input).match(Date.parseRegexes[{0}]);", "if(results){", "{1}", "if(u != null){", "v = new Date(u * 1000);", "}else{", "dt = (new Date()).clearTime();", "y = Ext.num(y, Ext.num(def.y, dt.getFullYear()));", "m = Ext.num(m, Ext.num(def.m - 1, dt.getMonth()));", "d = Ext.num(d, Ext.num(def.d, dt.getDate()));", "h = Ext.num(h, Ext.num(def.h, dt.getHours()));", "i = Ext.num(i, Ext.num(def.i, dt.getMinutes()));", "s = Ext.num(s, Ext.num(def.s, dt.getSeconds()));", "ms = Ext.num(ms, Ext.num(def.ms, dt.getMilliseconds()));", "if(z >= 0 && y >= 0){", "v = new Date(y, 0, 1, h, i, s, ms);", "v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);", "}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){", "v = null;", "}else{", "v = new Date(y, m, d, h, i, s, ms);", "}", "}", "}", "if(v){", "if(zz != null){", "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", "}else if(o){", "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", "}", "}", "return v;" ].join('\n'); return function(format) { var regexNum = Date.parseRegexes.length, currentGroup = 1, calc = [], regex = [], special = false, ch = "", i = 0, obj, last; for (; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; regex.push(Ext.util.Format.escape(ch)); } else { obj = $f(ch, currentGroup); currentGroup += obj.g; regex.push(obj.s); if (obj.g && obj.c) { if (obj.last) { last = obj; } else { calc.push(obj.c); } } } } if (last) { calc.push(last); } Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$"); Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join(''))); }; }(), parseCodes: { d: { g: 1, c: "d = parseInt(results[{0}], 10);\n", s: "(\\d{2})" }, j: { g: 1, c: "d = parseInt(results[{0}], 10);\n", s: "(\\d{1,2})" }, D: function() { for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); return { g: 0, c: null, s: "(?:" + a.join("|") + ")" }; }, l: function() { return { g: 0, c: null, s: "(?:" + Date.dayNames.join("|") + ")" }; }, N: { g: 0, c: null, s: "[1-7]" }, S: { g: 0, c: null, s: "(?:st|nd|rd|th)" }, w: { g: 0, c: null, s: "[0-6]" }, z: { g: 1, c: "z = parseInt(results[{0}], 10);\n", s: "(\\d{1,3})" }, W: { g: 0, c: null, s: "(?:\\d{2})" }, F: function() { return { g: 1, c: "m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", s: "(" + Date.monthNames.join("|") + ")" }; }, M: function() { for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); return Ext.applyIf({ s: "(" + a.join("|") + ")" }, $f("F")); }, m: { g: 1, c: "m = parseInt(results[{0}], 10) - 1;\n", s: "(\\d{2})" }, n: { g: 1, c: "m = parseInt(results[{0}], 10) - 1;\n", s: "(\\d{1,2})" }, t: { g: 0, c: null, s: "(?:\\d{2})" }, L: { g: 0, c: null, s: "(?:1|0)" }, o: function() { return $f("Y"); }, Y: { g: 1, c: "y = parseInt(results[{0}], 10);\n", s: "(\\d{4})" }, y: { g: 1, c: "var ty = parseInt(results[{0}], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s: "(\\d{1,2})" }, a: function(){ return $f("A"); }, A: { calcLast: true, g: 1, c: "if (results[{0}] == 'AM') {\n" + "if (!h || h == 12) { h = 0; }\n" + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}", s: "(AM|PM)" }, g: function() { return $f("G"); }, G: { g: 1, c: "h = parseInt(results[{0}], 10);\n", s: "(\\d{1,2})" }, h: function() { return $f("H"); }, H: { g: 1, c: "h = parseInt(results[{0}], 10);\n", s: "(\\d{2})" }, i: { g: 1, c: "i = parseInt(results[{0}], 10);\n", s: "(\\d{2})" }, s: { g: 1, c: "s = parseInt(results[{0}], 10);\n", s: "(\\d{2})" }, u: { g: 1, c: "ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n", s: "(\\d+)" }, O: { g: 1, c: [ "o = results[{0}];", "var sn = o.substring(0,1),", "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", "mn = o.substring(3,5) % 60;", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.util.Format.leftPad(hr, 2, '0') + Ext.util.Format.leftPad(mn, 2, '0')) : null;\n" ].join("\n"), s: "([+\-]\\d{4})" }, P: { g: 1, c: [ "o = results[{0}];", "var sn = o.substring(0,1),", "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", "mn = o.substring(4,6) % 60;", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.util.Format.leftPad(hr, 2, '0') + Ext.util.Format.leftPad(mn, 2, '0')) : null;\n" ].join("\n"), s: "([+\-]\\d{2}:\\d{2})" }, T: { g: 0, c: null, s: "[A-Z]{1,4}" }, Z: { g: 1, c: "zz = results[{0}] * 1;\n" + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n", s: "([+\-]?\\d{1,5})" }, c: function() { var calc = [], arr = [ $f("Y", 1), $f("m", 2), $f("d", 3), $f("h", 4), $f("i", 5), $f("s", 6), { c: "ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n" }, { c: [ "if(results[8]) {", "if(results[8] == 'Z'){", "zz = 0;", "}else if (results[8].indexOf(':') > -1){", $f("P", 8).c, "}else{", $f("O", 8).c, "}", "}" ].join('\n') } ]; for (var i = 0, l = arr.length; i < l; ++i) { calc.push(arr[i].c); } return { g: 1, c: calc.join(""), s: [ arr[0].s, "(?:", "-", arr[1].s, "(?:", "-", arr[2].s, "(?:", "(?:T| )?", arr[3].s, ":", arr[4].s, "(?::", arr[5].s, ")?", "(?:(?:\\.|,)(\\d+))?", "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", ")?", ")?", ")?" ].join("") }; }, U: { g: 1, c: "u = parseInt(results[{0}], 10);\n", s: "(-?\\d+)" } } }); } ()); Ext.apply(Date.prototype, { dateFormat: function(format) { if (Date.formatFunctions[format] == null) { Date.createFormat(format); } return Date.formatFunctions[format].call(this); }, getTimezone: function() { return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); }, getGMTOffset: function(colon) { return (this.getTimezoneOffset() > 0 ? "-": "+") + Ext.util.Format.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0") + (colon ? ":": "") + Ext.util.Format.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0"); }, getDayOfYear: function() { var num = 0, d = this.clone(), m = this.getMonth(), i; for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { num += d.getDaysInMonth(); } return num + this.getDate() - 1; }, getWeekOfYear: function() { var ms1d = 864e5, ms7d = 7 * ms1d; return function() { var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, AWN = Math.floor(DC3 / 7), Wyr = new Date(AWN * ms7d).getUTCFullYear(); return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; }; }(), isLeapYear: function() { var year = this.getFullYear(); return !! ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }, getFirstDayOfMonth: function() { var day = (this.getDay() - (this.getDate() - 1)) % 7; return (day < 0) ? (day + 7) : day; }, getLastDayOfMonth: function() { return this.getLastDateOfMonth().getDay(); }, getFirstDateOfMonth: function() { return new Date(this.getFullYear(), this.getMonth(), 1); }, getLastDateOfMonth: function() { return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); }, getDaysInMonth: function() { var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return function() { var m = this.getMonth(); return m == 1 && this.isLeapYear() ? 29: daysInMonth[m]; }; }(), getSuffix: function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }, clone: function() { return new Date(this.getTime()); }, isDST: function() { return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset(); }, clearTime: function(clone) { if (clone) { return this.clone().clearTime(); } var d = this.getDate(); this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); if (this.getDate() != d) { for (var hr = 1, c = this.add(Date.HOUR, hr); c.getDate() != d; hr++, c = this.add(Date.HOUR, hr)); this.setDate(d); this.setHours(c.getHours()); } return this; }, add: function(interval, value) { var d = this.clone(); if (!interval || value === 0) return d; switch (interval.toLowerCase()) { case Date.MILLI: d.setMilliseconds(this.getMilliseconds() + value); break; case Date.SECOND: d.setSeconds(this.getSeconds() + value); break; case Date.MINUTE: d.setMinutes(this.getMinutes() + value); break; case Date.HOUR: d.setHours(this.getHours() + value); break; case Date.DAY: d.setDate(this.getDate() + value); break; case Date.MONTH: var day = this.getDate(); if (day > 28) { day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate()); } d.setDate(day); d.setMonth(this.getMonth() + value); break; case Date.YEAR: d.setFullYear(this.getFullYear() + value); break; } return d; }, between: function(start, end) { var t = this.getTime(); return start.getTime() <= t && t <= end.getTime(); } }); Date.prototype.format = Date.prototype.dateFormat; Ext.data.Connection = Ext.extend(Ext.util.Observable, { method: 'post', url: null, disableCaching: true, disableCachingParam: '_dc', timeout : 30000, useDefaultHeader : true, defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8', useDefaultXhrHeader : true, defaultXhrHeader : 'XMLHttpRequest', constructor : function(config) { config = config || {}; Ext.apply(this, config); this.addEvents( 'beforerequest', 'requestcomplete', 'requestexception' ); this.requests = {}; Ext.data.Connection.superclass.constructor.call(this); }, request : function(o) { var me = this; if (me.fireEvent('beforerequest', me, o) !== false) { var params = o.params, url = o.url || me.url, urlParams = o.urlParams, extraParams = me.extraParams, request, data, headers, method, key, xhr; if (Ext.isFunction(params)) { params = params.call(o.scope || window, o); } if (Ext.isFunction(url)) { url = url.call(o.scope || window, o); } data = o.rawData || o.xmlData || o.jsonData || null; if (o.jsonData && !Ext.isPrimitive(o.jsonData)) { data = Ext.encode(data); } params = Ext.urlEncode(extraParams, Ext.isObject(params) ? Ext.urlEncode(params) : params); urlParams = Ext.isObject(urlParams) ? Ext.urlEncode(urlParams) : urlParams; method = (o.method || ((params || data) ? 'POST' : 'GET')).toUpperCase(); if (method === 'GET' && o.disableCaching !== false && me.disableCaching) { url = Ext.urlAppend(url, o.disableCachingParam || me.disableCachingParam + '=' + (new Date().getTime())); } if ((method == 'GET' || data) && params){ url = Ext.urlAppend(url, params); params = null; } if (urlParams) { url = Ext.urlAppend(url, urlParams); } if (o.autoAbort === true || me.autoAbort) { me.abort(); } xhr = this.getXhrInstance(); xhr.open(method.toUpperCase(), url, true); headers = Ext.apply({}, o.headers || {}, me.defaultHeaders || {}); if (!headers['Content-Type'] && (data || params)) { var contentType = me.defaultPostHeader, jsonData = o.jsonData, xmlData = o.xmlData; if (data) { if (o.rawData) { contentType = 'text/plain'; } else { if (xmlData && Ext.isDefined(xmlData)) { contentType = 'text/xml'; } else if (jsonData && Ext.isDefined(jsonData)) { contentType = 'application/json'; } } } headers['Content-Type'] = contentType; } if (me.useDefaultXhrHeader && !headers['X-Requested-With']) { headers['X-Requested-With'] = me.defaultXhrHeader; } for (key in headers) { if (headers.hasOwnProperty(key)) { try { xhr.setRequestHeader(key, headers[key]); } catch(e) { me.fireEvent('exception', key, headers[key]); } } } request = { id: ++Ext.data.Connection.requestId, xhr: xhr, headers: headers, options: o, timeout: setTimeout(function() { request.timedout = true; me.abort(request); }, o.timeout || me.timeout) }; me.requests[request.id] = request; xhr.onreadystatechange = Ext.createDelegate(me.onStateChange, me, [request]); xhr.send(data || params || null); return request; } else { return o.callback ? o.callback.apply(o.scope, [o, undefined, undefined]) : null; } }, getXhrInstance : function() { return new XMLHttpRequest(); }, isLoading : function(r) { return r && !{0:true, 4:true}[r.xhr.readyState]; }, abort : function(r) { if (r && this.isLoading(r)) { r.xhr.abort(); clearTimeout(r.timeout); delete(r.timeout); r.aborted = true; this.onComplete(r); } else if (!r) { var id; for(id in this.requests) { if (!this.requests.hasOwnProperty(id)) { continue; } this.abort(this.requests[id]); } } }, onStateChange : function(r) { if (r.xhr.readyState == 4) { clearTimeout(r.timeout); delete r.timeout; this.onComplete(r); } }, onComplete : function(r) { var status = r.xhr.status, options = r.options, success = true, response; if ((status >= 200 && status < 300) || status == 304) { response = this.createResponse(r); this.fireEvent('requestcomplete', this, response, options); if (options.success) { if (!options.scope) { options.success(response, options); } else { options.success.call(options.scope, response, options); } } } else { success = false; switch (status) { case 12002: case 12029: case 12030: case 12031: case 12152: case 13030: response = this.createException(r); break; default: response = this.createResponse(r); } this.fireEvent('requestexception', this, response, options); if (options.failure) { if (!options.scope) { options.failure(response, options); } else { options.failure.call(options.scope, response, options); } } } if (options.callback) { if (!options.scope) { options.callback(options, success, response); } else { options.callback.call(options.scope, options, success, response); } } delete this.requests[r.id]; }, createResponse : function(r) { var xhr = r.xhr, headers = {}, lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'), count = lines.length, line, index, key, value; while (count--) { line = lines[count]; index = line.indexOf(':'); if(index >= 0) { key = line.substr(0, index).toLowerCase(); if (line.charAt(index + 1) == ' ') { ++index; } headers[key] = line.substr(index + 1); } } delete r.xhr; return { request: r, requestId : r.id, status : xhr.status, statusText : xhr.statusText, getResponseHeader : function(header){ return headers[header.toLowerCase()]; }, getAllResponseHeaders : function(){ return headers; }, responseText : xhr.responseText, responseXML : xhr.responseXML }; }, createException : function(r) { return { request : r, requestId : r.id, status : r.aborted ? -1 : 0, statusText : r.aborted ? 'transaction aborted' : 'communication failure', aborted: r.aborted, timedout: r.timedout }; } }); Ext.data.Connection.requestId = 0; Ext.Ajax = new Ext.data.Connection({ autoAbort : false }); Ext.util.EventSimulator = Ext.extend(Object, { supportedEvents: { touch: ['touchstart', 'touchmove', 'touchend', 'gesturestart', 'gesturechange', 'gestureend'], mouse: ['mousedown', 'mousemove', 'mouseup', 'click'] }, getEventTypeByName: function(name) { var ret = null; Ext.iterate(this.supportedEvents, function(type, events) { if (events.indexOf(name) != -1) ret = type; }); return ret; }, fire: function(type, target, options) { type = type.toLowerCase(); if (arguments.length == 2) { options = target; target = document; } switch(this.getEventTypeByName(type)) { case 'touch': this.fireTouchEvent.call(this, type, target, options); break; case 'mouse': this.fireMouseEvent.call(this, type, target, options); break; default: throw new Error("Event type " + type + " is currently not supported"); } return this; }, createEvent: function(data, serializable) { }, createEventData: function(event, serializable) { switch (this.getEventTypeByName(event.type)) { case 'touch': return this.createTouchEventData(event.type, event.target, event, serializable); break; case 'mouse': return this.createMouseEventData(event.type, event.target, event, serializable); break; default: throw new Error("Event type " + event.type + " is currently not supported"); } }, fireTouchEvent: function(type, target, options) { var touchEventData = this.createTouchEventData(type, target, options); var touchEvent = this.createTouchEvent(type, touchEventData); touchEvent.isSimulated = true; return target.dispatchEvent(touchEvent); }, createTouchEventData: function(type, target, options, serializable) { var touchEventData = { type: type, timeStamp: Date.now(), bubbles: true, cancelable: true, detail: 1, screenX: 0, screenY: 0, pageX: 0, pageY: 0, clientX: 0, clientY: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, scale: 1, rotation: 0 }; if (!serializable) { touchEventData.target = target; touchEventData.view = document.defaultView; } if (options) { Ext.iterate(touchEventData, function(key, value) { if (options.hasOwnProperty(key)) { touchEventData[key] = options[key]; } }); } ['touches', 'targetTouches', 'changedTouches'].forEach(function(touchListName) { if (options.hasOwnProperty(touchListName)) { touchEventData[touchListName] = this.createTouchList(options[touchListName], target, serializable); } else { touchEventData[touchListName] = this.createTouchList(touchEventData, target, serializable); } }, this); return touchEventData; }, createTouchEvent: function(type, data) { if (typeof type != 'string') { data = type; type = type.type; } var touchEvent = document.createEvent('TouchEvent'); if (touchEvent.initTouchEvent.length == 9) { touchEvent.initTouchEvent(data.touches, data.targetTouches, data.changedTouches, type, data.view, data.screenX, data.screenY, data.clientX, data.clientY); } else { touchEvent.initTouchEvent(type, data.bubbles, data.cancelable, data.view, data.detail, data.screenX, data.screenY, data.pageX, data.pageY, data.ctrlKey, data.altKey, data.shiftKey, data.metaKey, data.touches, data.targetTouches, data.changedTouches, data.scale, data.rotation); } return touchEvent; }, createTouch: function(target, options, serializable) { if (!document.createTouch || serializable) { return { pageX: options.pageX, pageY: options.pageY, clientX: options.pageX, clientY: options.pageY, screenX: options.pageX, screenY: options.pageY, identifier: +options.identifier || 0 }; } return document.createTouch( document.defaultView, target, +options.identifier || 0, +options.pageX || 0, +options.pageY || 0, +options.screenX || 0, +options.screenY || 0); }, createTouchList: function(data, target, serializable) { var touch, touches = []; if (Ext.isObject(data) && typeof data.target != 'undefined') { data = [data]; } if (data) { for (var i = 0; i < data.length; i++) { if (!serializable && !data[i].target) { data[i].target = target; } touch = this.createTouch(data[i].target, data[i], serializable); touches.push(touch); } } if (!document.createTouchList || serializable) { return touches; } return document.createTouchList.apply(document, touches); }, fireMouseEvent: function(type, target, options) { var eventData = this.createMouseEventData(type, target, options); var event = this.createMouseEvent(type, eventData); event.isSimulated = true; event.originalTimeStamp = eventData.timeStamp; return target.dispatchEvent(event); }, createMouseEventData: function(type, target, options, serializable) { var mouseEventData = { type: type, timeStamp: Date.now(), bubbles: true, cancelable: (type != 'mousemove'), detail: 1, screenX: 0, screenY: 0, pageX: 0, pageY: 0, clientX: 0, clientY: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, relatedTarget: null }, coordProperties = ['screen', 'client', 'page'], coords = { x: 0, y: 0 }; if (!serializable) { mouseEventData.target = target; mouseEventData.view = window; } if (options) { Ext.iterate(mouseEventData, function(key, value) { if (options.hasOwnProperty(key)) { mouseEventData[key] = options[key]; } }); } coordProperties.forEach(function(p) { if (mouseEventData[p + 'X'] != 0) { coords.x = mouseEventData[p + 'X'] } if (mouseEventData[p + 'Y'] != 0) { coords.y = mouseEventData[p + 'Y'] } }); coordProperties.forEach(function(p) { if (mouseEventData[p + 'X'] == 0 && coords.x != 0) { mouseEventData[p + 'X'] = coords.x; } if (mouseEventData[p + 'Y'] == 0 && coords.y != 0) { mouseEventData[p + 'Y'] = coords.y; } }); return mouseEventData; }, createMouseEvent: function(type, data) { var mouseEvent = document.createEvent('MouseEvents'); mouseEvent.initMouseEvent( type, data.bubbles, data.cancelable, data.view, data.detail, data.screenX, data.screenY, data.clientX, data.clientY, data.ctrlKey, data.altKey, data.shiftKey, data.metaKey, data.button, data.relatedTarget); return mouseEvent; } }); Ext.util.EventRecorder = Ext.extend(Ext.util.Observable, { eventCollection: null, currentEventSetName: null, constructor: function() { this.addEvents( 'replaystart', 'beforecalculatetarget', 'beforefire', 'afterfire', 'aftercalculatetarget', 'replayend', 'interrupted' ); this.eventSets = {}; this.interruptedIndexes = {}; return this; }, getEventSet: function(name) { if (typeof name != 'string') { if (this.currentEventSetName == null) throw new Error('No EventSet is currently used'); name = this.currentEventSetName; } if (typeof this.eventSets[name] == 'undefined') { this.eventSets[name] = []; } return this.eventSets[name]; }, start: function(name) { this.currentEventSetName = name; }, record: function(name, event) { if (typeof name != 'string') { if (this.currentEventSetName == null) return; event = name; name = this.currentEventSetName; } var eventData = this.getEventSimulator().createEventData(event, true); this.getEventSet(name).push(eventData); }, setEventSet: function(name, events) { this.eventSets[name] = events; }, erase: function(name) { this.getEventSet(name).length = 0; }, stopReplay: function() { this.interruptFlag = true; }, resumeReplay: function(name) { var index = this.interruptedIndexes[name] || 0; this.replay(name, index); }, replay: function(name, startIndex) { var simulator = this.getEventSimulator(), events = this.getEventSet(name), numEvents, delay = 0, index = 0, event, point, target, reserveTargetEvents = ['touchmove', 'touchend', 'mousemove', 'mouseup'], me = this; if (typeof startIndex == 'undefined') { startIndex = 0; } index = startIndex; numEvents = events.length; this.interruptFlag = false; if (numEvents > 0) { this.fireEvent('replaystart', name, startIndex); setTimeout(function() { event = events[index]; if (event) { if (reserveTargetEvents.indexOf(event.type) === -1) { me.fireEvent('beforecalculatetarget', event.type, event); point = Ext.util.Point.fromEvent(event); target = document.elementFromPoint(point.x, point.y); me.fireEvent('aftercalculatetarget', event.type, target, event); } if (target) { if (me.interruptFlag === true) { me.interruptFlag = false; me.interruptedIndexes[name] = index; me.fireEvent('interrupted', index); me.fireEvent('replayend', name, true); return; } me.fireEvent('beforefire', event.type, target, event); simulator.fire(event.type, target, event); me.fireEvent('afterfire', event.type, target, event); } if (++index < numEvents) { setTimeout(arguments.callee, events[index].timeStamp - event.timeStamp); } else { me.fireEvent('replayend', name, false); } } }, delay); } }, end: function() { this.currentEventSetName = null; }, getEventSimulator: function() { if (!this._eventSimulator) { this._eventSimulator = new Ext.util.EventSimulator(); } return this._eventSimulator; }, setEventSimulator: function(eventSimulator) { if (!(eventSimulator instanceof Ext.util.EventSimulator)) throw new Error('eventSimulator must be an instance of Ext.util.EventSimulator'); this._eventSimulator = eventSimulator; }, save: function(name) { } }); Ext.gesture.Manager = new Ext.AbstractManager({ eventNames: { start: 'touchstart', move: 'touchmove', end: 'touchend' }, defaultPreventedMouseEvents: ['click'], clickMoveThreshold: 5, init: function() { this.targets = []; this.followTouches = []; this.currentGestures = []; this.currentTargets = []; if (!Ext.supports.Touch) { Ext.apply(this.eventNames, { start: 'mousedown', move: 'mousemove', end: 'mouseup' }); } this.listenerWrappers = { start: Ext.createDelegate(this.onTouchStart, this), move: Ext.createDelegate(this.onTouchMove, this), end: Ext.createDelegate(this.onTouchEnd, this), mouse: Ext.createDelegate(this.onMouseEvent, this) }; this.attachListeners(); }, freeze: function() { this.isFrozen = true; }, thaw: function() { this.isFrozen = false; }, getEventSimulator: function() { if (!this.eventSimulator) { this.eventSimulator = new Ext.util.EventSimulator(); } return this.eventSimulator; }, attachListeners: function() { Ext.iterate(this.eventNames, function(key, name) { document.body.addEventListener(name, this.listenerWrappers[key], false); }, this); if (Ext.supports.Touch) { this.defaultPreventedMouseEvents.forEach(function(name) { document.body.addEventListener(name, this.listenerWrappers['mouse'], true); }, this); } }, detachListeners: function() { Ext.iterate(this.eventNames, function(key, name) { document.body.removeEventListener(name, this.listenerWrappers[key], false); }, this); if (Ext.supports.Touch) { this.defaultPreventedMouseEvents.forEach(function(name) { document.body.removeEventListener(name, this.listenerWrappers['mouse'], true); }, this); } }, onMouseEvent: function(e) { if (!e.isSimulated) { e.preventDefault(); e.stopPropagation(); } }, onTouchStart: function(e) { var targets = [], target = e.target, me = this; if (e.stopped === true) { return; } if (!Ext.is.iOS) { if (!(target.tagName && ['input', 'textarea', 'select'].indexOf(target.tagName.toLowerCase()) !== -1)) { e.preventDefault(); } } if (this.isFrozen) { return; } if (this.startEvent) { this.onTouchEnd(e); } this.locks = {}; this.currentTargets = [target]; while (target) { if (this.targets.indexOf(target) !== -1) { targets.unshift(target); } target = target.parentNode; this.currentTargets.push(target); } this.startEvent = e; this.startPoint = Ext.util.Point.fromEvent(e); this.lastMovePoint = null; this.isClick = true; this.handleTargets(targets, e); }, onTouchMove: function(e) { if (!this.startEvent) { return; } if (Ext.is.Desktop) { e.target = this.startEvent.target; } if (Ext.is.iOS) { e.preventDefault(); } if (this.isFrozen) { return; } var gestures = this.currentGestures, gesture, touch = e.changedTouches ? e.changedTouches[0] : e; this.lastMovePoint = Ext.util.Point.fromEvent(e); if (Ext.supports.Touch && this.isClick && !this.lastMovePoint.isWithin(this.startPoint, this.clickMoveThreshold)) { this.isClick = false; } for (var i = 0; i < gestures.length; i++) { if (e.stopped) { break; } gesture = gestures[i]; if (gesture.listenForMove) { gesture.onTouchMove(e, touch); } } }, onTouchEnd: function(e) { if (this.isFrozen) { return; } var gestures = this.currentGestures.slice(0), ln = gestures.length, i, gesture, endPoint, needsAnotherMove = false, touch = e.changedTouches ? e.changedTouches[0] : e; if (this.startPoint) { endPoint = Ext.util.Point.fromEvent(e); if (!(this.lastMovePoint || this.startPoint)['equals'](endPoint)) { needsAnotherMove = true; } } for (i = 0; i < ln; i++) { gesture = gestures[i]; if (!e.stopped && gesture.listenForEnd) { if (needsAnotherMove) { gesture.onTouchMove(e, touch); } gesture.onTouchEnd(e, touch); } this.stopGesture(gesture); } if (Ext.supports.Touch && this.isClick) { this.isClick = false; this.getEventSimulator().fire('click', this.startEvent.target, touch); } this.lastMovePoint = null; this.followTouches = []; this.startedChangedTouch = false; this.currentTargets = []; this.startEvent = null; this.startPoint = null; }, handleTargets: function(targets, e) { var ln = targets.length, i; this.startedChangedTouch = false; this.startedTouches = Ext.supports.Touch ? e.touches : [e]; for (i = 0; i < ln; i++) { if (e.stopped) { break; } this.handleTarget(targets[i], e, true); } for (i = ln - 1; i >= 0; i--) { if (e.stopped) { break; } this.handleTarget(targets[i], e, false); } if (this.startedChangedTouch) { this.followTouches = this.followTouches.concat((Ext.supports.Touch && e.targetTouches) ? Ext.toArray(e.targetTouches) : [e]); } }, handleTarget: function(target, e, capture) { var gestures = Ext.Element.data(target, 'x-gestures') || [], ln = gestures.length, i, gesture; for (i = 0; i < ln; i++) { gesture = gestures[i]; if ( (!!gesture.capture === !!capture) && (this.followTouches.length < gesture.touches) && ((Ext.supports.Touch && e.targetTouches) ? (e.targetTouches.length === gesture.touches) : true) ) { this.startedChangedTouch = true; this.startGesture(gesture); if (gesture.listenForStart) { gesture.onTouchStart(e, e.changedTouches ? e.changedTouches[0] : e); } if (e.stopped) { break; } } } }, startGesture: function(gesture) { gesture.started = true; this.currentGestures.push(gesture); }, stopGesture: function(gesture) { gesture.started = false; this.currentGestures.remove(gesture); }, addEventListener: function(target, eventName, listener, options) { target = Ext.getDom(target); var targets = this.targets, name = this.getGestureName(eventName), gestures = Ext.Element.data(target, 'x-gestures'), gesture; if (!gestures) { gestures = []; Ext.Element.data(target, 'x-gestures', gestures); } if (!name) { throw new Error('Trying to subscribe to unknown event ' + eventName); } if (targets.indexOf(target) === -1) { this.targets.push(target); } gesture = this.get(target.id + '-' + name); if (!gesture) { gesture = this.create(Ext.apply({}, options || {}, { target: target, type: name })); gestures.push(gesture); } gesture.addListener(eventName, listener); if (this.startedChangedTouch && this.currentTargets.contains(target) && !gesture.started && !options.subsequent) { this.startGesture(gesture); if (gesture.listenForStart) { gesture.onTouchStart(this.startEvent, this.startedTouches[0]); } } }, removeEventListener: function(target, eventName, listener) { target = Ext.getDom(target); var name = this.getGestureName(eventName), gestures = Ext.Element.data(target, 'x-gestures') || [], gesture; gesture = this.get(target.id + '-' + name); if (gesture) { gesture.removeListener(eventName, listener); for (name in gesture.listeners) { return; } gesture.destroy(); gestures.remove(gesture); Ext.Element.data(target, 'x-gestures', gestures); } }, getGestureName: function(ename) { return this.names && this.names[ename]; }, registerType: function(type, cls) { var handles = cls.prototype.handles, i, ln; this.types[type] = cls; cls[this.typeName] = type; if (!handles) { handles = cls.prototype.handles = [type]; } this.names = this.names || {}; for (i = 0, ln = handles.length; i < ln; i++) { this.names[handles[i]] = type; } } }); Ext.regGesture = function() { return Ext.gesture.Manager.registerType.apply(Ext.gesture.Manager, arguments); }; Ext.TouchEventObjectImpl = Ext.extend(Object, { constructor : function(e, args) { if (e) { this.setEvent(e, args); } }, setEvent : function(e, args) { Ext.apply(this, { event: e, time: e.timeStamp }); this.touches = e.touches || [e]; this.changedTouches = e.changedTouches || [e]; this.targetTouches = e.targetTouches || [e]; if (args) { this.target = args.target; Ext.apply(this, args); } else { this.target = e.target; } return this; }, stopEvent : function() { this.stopPropagation(); this.preventDefault(); }, stopPropagation : function() { this.event.stopped = true; }, preventDefault : function() { this.event.preventDefault(); }, getTarget : function(selector, maxDepth, returnEl) { if (selector) { return Ext.fly(this.target).findParent(selector, maxDepth, returnEl); } else { return returnEl ? Ext.get(this.target) : this.target; } } }); Ext.TouchEventObject = new Ext.TouchEventObjectImpl(); Ext.gesture.Gesture = Ext.extend(Object, { listenForStart: true, listenForEnd: true, listenForMove: true, disableLocking: false, touches: 1, constructor: function(config) { config = config || {}; Ext.apply(this, config); this.target = Ext.getDom(this.target); this.listeners = {}; if (!this.target) { throw new Error('Trying to bind a ' + this.type + ' event to element that does\'nt exist: ' + this.target); } this.id = this.target.id + '-' + this.type; Ext.gesture.Gesture.superclass.constructor.call(this); Ext.gesture.Manager.register(this); }, addListener: function(name, listener) { this.listeners[name] = this.listeners[name] || []; this.listeners[name].push(listener); }, removeListener: function(name, listener) { var listeners = this.listeners[name]; if (listeners) { listeners.remove(listener); if (listeners.length == 0) { delete this.listeners[name]; } for (name in this.listeners) { if (this.listeners.hasOwnProperty(name)) { return; } } this.listeners = {}; } }, fire: function(type, e, args) { var listeners = this.listeners[type], ln = listeners && listeners.length, i; if (!this.disableLocking && this.isLocked(type)) { return false; } if (ln) { args = Ext.apply(args || {}, { time: e.timeStamp, type: type, gesture: this, target: (e.target.nodeType == 3) ? e.target.parentNode: e.target }); for (i = 0; i < ln; i++) { listeners[i](e, args); } } return true; }, stop: function() { Ext.gesture.Manager.stopGesture(this); }, lock: function() { if (!this.disableLocking) { var args = arguments, ln = args.length, i; for (i = 0; i < ln; i++) { Ext.gesture.Manager.locks[args[i]] = this.id; } } }, unlock: function() { if (!this.disableLocking) { var args = arguments, ln = args.length, i; for (i = 0; i < ln; i++) { if (Ext.gesture.Manager.locks[args[i]] == this.id) { delete Ext.gesture.Manager.locks[args[i]]; } } } }, isLocked : function(type) { var lock = Ext.gesture.Manager.locks[type]; return !!(lock && lock !== this.id); }, getLockingGesture : function(type) { var lock = Ext.gesture.Manager.locks[type]; if (lock) { return Ext.gesture.Manager.get(lock) || null; } return null; }, onTouchStart: Ext.emptyFn, onTouchMove: Ext.emptyFn, onTouchEnd: Ext.emptyFn, destroy: function() { this.stop(); this.listeners = null; Ext.gesture.Manager.unregister(this); } }); Ext.gesture.Touch = Ext.extend(Ext.gesture.Gesture, { handles: ['touchstart', 'touchmove', 'touchend', 'touchdown'], touchDownInterval: 500, onTouchStart: function(e, touch) { this.startX = this.previousX = touch.pageX; this.startY = this.previousY = touch.pageY; this.startTime = this.previousTime = e.timeStamp; this.fire('touchstart', e); this.lastEvent = e; if (this.listeners && this.listeners.touchdown) { this.touchDownIntervalId = setInterval(Ext.createDelegate(this.touchDownHandler, this), this.touchDownInterval); } }, onTouchMove: function(e, touch) { this.fire('touchmove', e, this.getInfo(touch)); this.lastEvent = e; }, onTouchEnd: function(e) { this.fire('touchend', e, this.lastInfo); clearInterval(this.touchDownIntervalId); }, touchDownHandler : function() { this.fire('touchdown', this.lastEvent, this.lastInfo); }, getInfo : function(touch) { var time = Date.now(), deltaX = touch.pageX - this.startX, deltaY = touch.pageY - this.startY, info = { startX: this.startX, startY: this.startY, previousX: this.previousX, previousY: this.previousY, pageX: touch.pageX, pageY: touch.pageY, deltaX: deltaX, deltaY: deltaY, absDeltaX: Math.abs(deltaX), absDeltaY: Math.abs(deltaY), previousDeltaX: touch.pageX - this.previousX, previousDeltaY: touch.pageY - this.previousY, time: time, startTime: this.startTime, previousTime: this.previousTime, deltaTime: time - this.startTime, previousDeltaTime: time - this.previousTime }; this.previousTime = info.time; this.previousX = info.pageX; this.previousY = info.pageY; this.lastInfo = info; return info; } }); Ext.regGesture('touch', Ext.gesture.Touch); Ext.gesture.Tap = Ext.extend(Ext.gesture.Gesture, { handles: [ 'tapstart', 'tapcancel', 'tap', 'doubletap', 'taphold', 'singletap' ], cancelThreshold: 10, doubleTapThreshold: 800, singleTapThreshold: 400, holdThreshold: 1000, fireClickEvent: false, onTouchStart : function(e, touch) { var me = this; me.startX = touch.pageX; me.startY = touch.pageY; me.fire('tapstart', e, me.getInfo(touch)); if (this.listeners.taphold) { me.timeout = setTimeout(function() { me.fire('taphold', e, me.getInfo(touch)); delete me.timeout; }, me.holdThreshold); } me.lastTouch = touch; }, onTouchMove : function(e, touch) { var me = this; if (me.isCancel(touch)) { me.fire('tapcancel', e, me.getInfo(touch)); if (me.timeout) { clearTimeout(me.timeout); delete me.timeout; } me.stop(); } me.lastTouch = touch; }, onTouchEnd : function(e) { var me = this, info = me.getInfo(me.lastTouch); this.fireTapEvent(e, info); if (me.lastTapTime && e.timeStamp - me.lastTapTime <= me.doubleTapThreshold) { me.lastTapTime = null; e.preventDefault(); me.fire('doubletap', e, info); } else { me.lastTapTime = e.timeStamp; } if (me.listeners && me.listeners.singletap && me.singleTapThreshold && !me.preventSingleTap) { me.fire('singletap', e, info); me.preventSingleTap = true; setTimeout(function() { me.preventSingleTap = false; }, me.singleTapThreshold); } if (me.timeout) { clearTimeout(me.timeout); delete me.timeout; } }, fireTapEvent: function(e, info) { this.fire('tap', e, info); if (e.event) e = e.event; var target = (e.changedTouches ? e.changedTouches[0] : e).target; if (!target.disabled && this.fireClickEvent) { var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent('click', e.bubbles, e.cancelable, document.defaultView, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.metaKey, e.button, e.relatedTarget); clickEvent.isSimulated = true; target.dispatchEvent(clickEvent); } }, getInfo : function(touch) { return { pageX: touch.pageX, pageY: touch.pageY }; }, isCancel : function(touch) { var me = this; return ( Math.abs(touch.pageX - me.startX) >= me.cancelThreshold || Math.abs(touch.pageY - me.startY) >= me.cancelThreshold ); } }); Ext.regGesture('tap', Ext.gesture.Tap); Ext.gesture.Swipe = Ext.extend(Ext.gesture.Gesture, { listenForEnd: false, swipeThreshold: 35, swipeTime: 1000, onTouchStart : function(e, touch) { this.startTime = e.timeStamp; this.startX = touch.pageX; this.startY = touch.pageY; this.lock('scroll', 'scrollstart', 'scrollend'); }, onTouchMove : function(e, touch) { var deltaY = touch.pageY - this.startY, deltaX = touch.pageX - this.startX, absDeltaY = Math.abs(deltaY), absDeltaX = Math.abs(deltaX), deltaTime = e.timeStamp - this.startTime; if (absDeltaY - absDeltaX > 3 || deltaTime > this.swipeTime) { this.unlock('scroll', 'scrollstart', 'scrollend'); this.stop(); } else if (absDeltaX > this.swipeThreshold && absDeltaX > absDeltaY) { this.fire('swipe', e, { direction: (deltaX < 0) ? 'left' : 'right', distance: absDeltaX, deltaTime: deltaTime, deltaX: deltaX }); this.stop(); } } }); Ext.regGesture('swipe', Ext.gesture.Swipe); Ext.gesture.Drag = Ext.extend(Ext.gesture.Touch, { handles: ['dragstart', 'drag', 'dragend'], dragThreshold: 5, direction: 'both', horizontal: false, vertical: false, constructor: function() { Ext.gesture.Drag.superclass.constructor.apply(this, arguments); if (this.direction == 'both') { this.horizontal = true; this.vertical = true; } else if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } return this; }, onTouchStart: function(e, touch) { this.startX = this.previousX = touch.pageX; this.startY = this.previousY = touch.pageY; this.startTime = this.previousTime = e.timeStamp; this.dragging = false; }, onTouchMove: function(e, touch) { if (this.isLocked('drag')) { return; } var info = this.getInfo(touch); if (!this.dragging) { if (this.isDragging(info) && this.fire('dragstart', e, info)) { this.dragging = true; this.lock('drag', 'dragstart', 'dragend'); } } else { this.fire('drag', e, info); } }, onTouchEnd: function(e) { if (this.dragging) { this.fire('dragend', e, this.lastInfo); } this.dragging = false; }, isDragging: function(info) { return ( (this.horizontal && info.absDeltaX >= this.dragThreshold) || (this.vertical && info.absDeltaY >= this.dragThreshold) ); }, isVertical: function() { return this.vertical; }, isHorizontal: function() { return this.horizontal; } }); Ext.regGesture('drag', Ext.gesture.Drag); Ext.gesture.Pinch = Ext.extend(Ext.gesture.Gesture, { handles: [ 'pinchstart', 'pinch', 'pinchend' ], touches: 2, onTouchStart : function(e) { var me = this; if (Ext.supports.Touch && e.targetTouches.length >= 2) { me.lock('swipe', 'scroll', 'scrollstart', 'scrollend', 'touchmove', 'touchend', 'touchstart', 'tap', 'tapstart', 'taphold', 'tapcancel', 'doubletap'); me.pinching = true; var targetTouches = e.targetTouches, firstTouch = me.firstTouch = targetTouches[0], secondTouch = me.secondTouch = targetTouches[1]; me.previousDistance = me.startDistance = me.getDistance(); me.previousScale = 1; me.fire('pinchstart', e, { distance: me.startDistance, scale: me.previousScale }); } else if (me.pinching) { me.unlock('swipe', 'scroll', 'scrollstart', 'scrollend', 'touchmove', 'touchend', 'touchstart', 'tap', 'tapstart', 'taphold', 'tapcancel', 'doubletap'); me.pinching = false; } }, onTouchMove : function(e) { if (this.pinching) { this.fire('pinch', e, this.getPinchInfo()); } }, onTouchEnd : function(e) { if (this.pinching) { this.fire('pinchend', e, this.getPinchInfo()); } }, getPinchInfo : function() { var me = this, distance = me.getDistance(), scale = distance / me.startDistance, firstTouch = me.firstTouch, secondTouch = me.secondTouch, info = { scale: scale, deltaScale: scale - 1, previousScale: me.previousScale, previousDeltaScale: scale - me.previousScale, distance: distance, deltaDistance: distance - me.startDistance, startDistance: me.startDistance, previousDistance: me.previousDistance, previousDeltaDistance: distance - me.previousDistance, firstTouch: firstTouch, secondTouch: secondTouch, firstPageX: firstTouch.pageX, firstPageY: firstTouch.pageY, secondPageX: secondTouch.pageX, secondPageY: secondTouch.pageY, midPointX: (firstTouch.pageX + secondTouch.pageX) / 2, midPointY: (firstTouch.pageY + secondTouch.pageY) / 2 }; me.previousScale = scale; me.previousDistance = distance; return info; }, getDistance : function() { var me = this; return Math.sqrt( Math.pow(Math.abs(me.firstTouch.pageX - me.secondTouch.pageX), 2) + Math.pow(Math.abs(me.firstTouch.pageY - me.secondTouch.pageY), 2) ); } }); Ext.regGesture('pinch', Ext.gesture.Pinch); Ext.lib.Component = Ext.extend(Ext.util.Observable, { isComponent: true, renderTpl: null, tplWriteMode: 'overwrite', baseCls: 'x-component', disabledCls: 'x-item-disabled', hidden: false, disabled: false, draggable: false, floating: false, styleHtmlContent: false, styleHtmlCls: 'x-html', allowDomMove: true, autoShow: false, autoRender: false, needsLayout: false, rendered: false, constructor : function(config) { config = config || {}; this.initialConfig = config; Ext.apply(this, config); this.addEvents( 'beforeactivate', 'activate', 'beforedeactivate', 'deactivate', 'added', 'disable', 'enable', 'beforeshow', 'show', 'beforehide', 'hide', 'removed', 'beforerender', 'render', 'afterrender', 'beforedestroy', 'destroy', 'resize', 'move', 'beforestaterestore', 'staterestore', 'beforestatesave', 'statesave' ); this.getId(); this.mons = []; this.additionalCls = []; this.renderData = this.renderData || {}; this.renderSelectors = this.renderSelectors || {}; this.initComponent(); Ext.ComponentMgr.register(this); Ext.lib.Component.superclass.constructor.call(this); if (this.plugins) { this.plugins = [].concat(this.plugins); for (var i = 0, len = this.plugins.length; i < len; i++) { this.plugins[i] = this.initPlugin(this.plugins[i]); } } if (this.applyTo) { this.applyToMarkup(this.applyTo); delete this.applyTo; } else if (this.renderTo) { this.render(this.renderTo); delete this.renderTo; } if (Ext.isDefined(this.disabledClass)) { throw "Component: disabledClass has been deprecated. Please use disabledCls."; } }, initComponent: Ext.emptyFn, applyToMarkup: Ext.emptyFn, show: Ext.emptyFn, onShow : function() { var needsLayout = this.needsLayout; if (Ext.isObject(needsLayout)) { this.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize); } }, initPlugin : function(plugin) { if (plugin.ptype && typeof plugin.init != 'function') { plugin = Ext.PluginMgr.create(plugin); } else if (typeof plugin == 'string') { plugin = Ext.PluginMgr.create({ ptype: plugin }); } plugin.init(this); return plugin; }, render : function(container, position) { if (!this.rendered && this.fireEvent('beforerender', this) !== false) { if (this.el) { this.el = Ext.get(this.el); } container = this.initContainer(container); this.onRender(container, position); this.fireEvent('render', this); this.initContent(); this.afterRender(container); this.fireEvent('afterrender', this); this.initEvents(); if (this.autoShow) { this.show(); } if (this.hidden) { this.onHide(false); } if (this.disabled) { this.disable(true); } } return this; }, onRender : function(container, position) { var el = this.el, renderTpl, renderData; position = this.getInsertPosition(position); if (!el) { if (position) { el = Ext.DomHelper.insertBefore(position, this.getElConfig(), true); } else { el = Ext.DomHelper.append(container, this.getElConfig(), true); } } else if (this.allowDomMove !== false) { container.dom.insertBefore(el.dom, position); } el.addCls(this.initCls()); el.setStyle(this.initStyles()); renderTpl = this.initRenderTpl(); if (renderTpl) { renderData = this.initRenderData(); renderTpl.append(el, renderData); } this.el = el; this.applyRenderSelectors(); this.rendered = true; }, initCls: function() { var cls = [ this.baseCls ]; if (this.componentCls) { cls.push(this.componentCls); } else { this.componentCls = this.baseCls; } if (this.cls) { cls.push(this.cls); delete this.cls; } if (this.ui) { cls.push(this.componentCls + '-' + this.ui); } return cls.concat(this.additionalCls); }, afterRender : function() { this.getComponentLayout(); if (this.x || this.y) { this.setPosition(this.x, this.y); } if (this.styleHtmlContent) { this.getTargetEl().addCls(this.styleHtmlCls); } if (!this.ownerCt) { this.setSize(this.width, this.height); } }, getElConfig : function() { return {tag: 'div', id: this.id}; }, getInsertPosition: function(position) { if (position !== undefined) { if (Ext.isNumber(position)) { position = this.container.dom.childNodes[position]; } else { position = Ext.getDom(position); } } return position; }, initContainer: function(container) { if (!container && this.el) { container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if (this.ctCls) { this.container.addCls(this.ctCls); } return this.container; }, initRenderData: function() { return Ext.applyIf(this.renderData, { baseCls: this.baseCls, componentCls: this.componentCls }); }, initRenderTpl: function() { var renderTpl = this.renderTpl; if (renderTpl) { if (this.proto.renderTpl !== renderTpl) { if (Ext.isArray(renderTpl) || typeof renderTpl === "string") { renderTpl = new Ext.XTemplate(renderTpl); } } else if (Ext.isArray(this.proto.renderTpl)){ renderTpl = this.proto.renderTpl = new Ext.XTemplate(renderTpl); } } return renderTpl; }, initStyles: function() { var style = {}, Element = Ext.Element, i, ln, split, prop; if (Ext.isString(this.style)) { split = this.style.split(';'); for (i = 0, ln = split.length; i < ln; i++) { if (!Ext.isEmpty(split[i])) { prop = split[i].split(':'); style[Ext.util.Format.trim(prop[0])] = Ext.util.Format.trim(prop[1]); } } } else { style = Ext.apply({}, this.style); } if (this.padding != undefined) { style.padding = Element.unitizeBox((this.padding === true) ? 5 : this.padding); } if (this.margin != undefined) { style.margin = Element.unitizeBox((this.margin === true) ? 5 : this.margin); } if (this.border != undefined) { style.borderWidth = Element.unitizeBox((this.border === true) ? 1 : this.border); } delete this.style; return style; }, initContent: function() { var target = this.getTargetEl(); if (this.html) { target.update(Ext.DomHelper.markup(this.html)); delete this.html; } if (this.contentEl) { var contentEl = Ext.get(this.contentEl); contentEl.show(); target.appendChild(contentEl.dom); } if (this.tpl) { if (!this.tpl.isTemplate) { this.tpl = new Ext.XTemplate(this.tpl); } if (this.data) { this.tpl[this.tplWriteMode](target, this.data); delete this.data; } } }, initEvents : function() { var afterRenderEvents = this.afterRenderEvents, property, listeners; if (afterRenderEvents) { for (property in afterRenderEvents) { if (!afterRenderEvents.hasOwnProperty(property)) { continue; } listeners = afterRenderEvents[property]; if (this[property] && this[property].on) { this.mon(this[property], listeners); } } } }, applyRenderSelectors: function() { var selectors = this.renderSelectors || {}, el = this.el.dom, selector; for (selector in selectors) { if (!selectors.hasOwnProperty(selector)) { continue; } this[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], el)); } }, is: function(selector) { return Ext.ComponentQuery.is(this, selector); }, up: function(selector) { var result = this.ownerCt; if (selector) { for (; result; result = result.ownerCt) { if (Ext.ComponentQuery.is(result, selector)) { return result; } } } return result; }, nextSibling: function(selector) { var o = this.ownerCt, it, last, idx, c; if (o) { it = o.items; idx = it.indexOf(this) + 1; if (idx) { if (selector) { for (last = it.getCount(); idx < last; idx++) { if ((c = it.getAt(idx)).is(selector)) { return c; } } } else { if (idx < it.getCount()) { return it.getAt(idx); } } } } return null; }, previousSibling: function(selector) { var o = this.ownerCt, it, idx, c; if (o) { it = o.items; idx = it.indexOf(this); if (idx != -1) { if (selector) { for (--idx; idx >= 0; idx--) { if ((c = it.getAt(idx)).is(selector)) { return c; } } } else { if (idx) { return it.getAt(--idx); } } } } return null; }, getId : function() { return this.id || (this.id = 'ext-comp-' + (++Ext.lib.Component.AUTO_ID)); }, getItemId : function() { return this.itemId || this.id; }, getEl : function() { return this.el; }, getTargetEl: function() { return this.el; }, isXType: function(xtype, shallow) { if (Ext.isFunction(xtype)) { xtype = xtype.xtype; } else if (Ext.isObject(xtype)) { xtype = xtype.constructor.xtype; } return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1: this.constructor.xtype == xtype; }, getXTypes: function() { var constructor = this.constructor, xtypes = [], superclass = this, xtype; if (!constructor.xtypes) { while (superclass) { xtype = superclass.constructor.xtype; if (xtype != undefined) { xtypes.unshift(xtype); } superclass = superclass.constructor.superclass; } constructor.xtypeChain = xtypes; constructor.xtypes = xtypes.join('/'); } return constructor.xtypes; }, update : function(htmlOrData, loadScripts, cb) { if (this.tpl && !Ext.isString(htmlOrData)) { this.data = htmlOrData; if (this.rendered) { this.tpl[this.tplWriteMode](this.getTargetEl(), htmlOrData || {}); } } else { this.html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData; if (this.rendered) { this.getTargetEl().update(this.html, loadScripts, cb); } } if (this.rendered) { this.doComponentLayout(); } }, setVisible : function(visible) { return this[visible ? 'show': 'hide'](); }, isVisible: function() { var visible = !this.hidden, cmp = this.ownerCt; this.hiddenOwnerCt = false; if (this.destroyed) { return false; }; if (visible && this.rendered && cmp) { while (cmp) { if (cmp.hidden || cmp.collapsed) { this.hiddenOwnerCt = cmp; visible = false; break; } cmp = cmp.ownerCt; } } return visible; }, enable : function(silent) { if (this.rendered) { this.el.removeCls(this.disabledCls); this.el.dom.disabled = false; this.onEnable(); } this.disabled = false; if (silent !== true) { this.fireEvent('enable', this); } return this; }, disable : function(silent) { if (this.rendered) { this.el.addCls(this.disabledCls); this.el.dom.disabled = true; this.onDisable(); } this.disabled = true; if (silent !== true) { this.fireEvent('disable', this); } return this; }, isDisabled : function() { return this.disabled; }, setDisabled : function(disabled) { return this[disabled ? 'disable': 'enable'](); }, isHidden : function() { return this.hidden; }, addCls : function() { var me = this, args = Ext.toArray(arguments); if (me.rendered) { me.el.addCls(args); } else { me.additionalCls = me.additionalCls.concat(args); } return me; }, addClass : function() { throw "Component: addClass has been deprecated. Please use addCls."; }, removeCls : function() { var me = this, args = Ext.toArray(arguments); if (me.rendered) { me.el.removeCls(args); } else if (me.additionalCls.length) { Ext.each(args, function(cls) { me.additionalCls.remove(cls); }); } return me; }, removeClass : function() { throw "Component: removeClass has been deprecated. Please use removeCls."; }, addListener : function(element, listeners, scope, options) { if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) { if (options.element) { var fn = listeners, option; listeners = {}; listeners[element] = fn; element = options.element; if (scope) { listeners.scope = scope; } for (option in options) { if (!options.hasOwnProperty(option)) { continue; } if (this.eventOptionsRe.test(option)) { listeners[option] = options[option]; } } } if (this[element] && this[element].on) { this.mon(this[element], listeners); } else { this.afterRenderEvents = this.afterRenderEvents || {}; this.afterRenderEvents[element] = listeners; } } return Ext.lib.Component.superclass.addListener.apply(this, arguments); }, getBubbleTarget : function() { return this.ownerCt; }, isFloating : function() { return this.floating; }, isDraggable : function() { return !!this.draggable; }, isDroppable : function() { return !!this.droppable; }, onAdded : function(container, pos) { this.ownerCt = container; this.fireEvent('added', this, container, pos); }, onRemoved : function() { this.fireEvent('removed', this, this.ownerCt); delete this.ownerCt; }, onEnable : Ext.emptyFn, onDisable : Ext.emptyFn, beforeDestroy : Ext.emptyFn, onResize : Ext.emptyFn, setSize : function(width, height) { if (Ext.isObject(width)) { height = width.height; width = width.width; } if (!this.rendered || !this.isVisible()) { if (this.hiddenOwnerCt) { var layoutCollection = this.hiddenOwnerCt.layoutOnShow; layoutCollection.remove(this); layoutCollection.add(this); } this.needsLayout = { width: width, height: height, isSetSize: true }; if (!this.rendered) { this.width = (width !== undefined) ? width : this.width; this.height = (height !== undefined) ? height : this.height; } return this; } this.doComponentLayout(width, height, true); return this; }, setCalculatedSize : function(width, height) { if (Ext.isObject(width)) { height = width.height; width = width.width; } if (!this.rendered || !this.isVisible()) { if (this.hiddenOwnerCt) { var layoutCollection = this.hiddenOwnerCt.layoutOnShow; layoutCollection.remove(this); layoutCollection.add(this); } this.needsLayout = { width: width, height: height, isSetSize: false }; return this; } this.doComponentLayout(width, height); return this; }, doComponentLayout : function(width, height, isSetSize) { var componentLayout = this.getComponentLayout(); if (this.rendered && componentLayout) { width = (width !== undefined || this.collapsed === true) ? width : this.width; height = (height !== undefined || this.collapsed === true) ? height : this.height; if (isSetSize) { this.width = width; this.height = height; } componentLayout.layout(width, height); } return this; }, setComponentLayout : function(layout) { var currentLayout = this.componentLayout; if (currentLayout && currentLayout.isLayout && currentLayout != layout) { currentLayout.setOwner(null); } this.componentLayout = layout; layout.setOwner(this); }, getComponentLayout : function() { if (!this.componentLayout || !this.componentLayout.isLayout) { this.setComponentLayout(Ext.layout.LayoutManager.create(this.componentLayout, 'autocomponent')); } return this.componentLayout; }, afterComponentLayout: Ext.emptyFn, setPosition : function(x, y) { if (Ext.isObject(x)) { y = x.y; x = x.x; } if (!this.rendered) { return this; } if (x !== undefined || y !== undefined) { this.el.setBox(x, y); this.onPosition(x, y); this.fireEvent('move', this, x, y); } return this; }, onPosition: Ext.emptyFn, setWidth : function(width) { return this.setSize(width); }, setHeight : function(height) { return this.setSize(undefined, height); }, getSize : function() { return this.el.getSize(); }, getWidth : function() { return this.el.getWidth(); }, getHeight : function() { return this.el.getHeight(); }, setLoading : function(load, targetEl) { if (this.rendered) { if (load) { this.loadMask = this.loadMask || new Ext.LoadMask(targetEl ? this.getTargetEl() : this.el, Ext.applyIf(Ext.isObject(load) ? load : {})); this.loadMask.show(); } else { Ext.destroy(this.loadMask); this.loadMask = null; } } return this.loadMask; }, setDocked : function(dock, layoutParent) { this.dock = dock; if (layoutParent && this.ownerCt && this.rendered) { this.ownerCt.doComponentLayout(); } return this; }, onDestroy : function() { if (this.monitorResize && Ext.EventManager.resizeEvent) { Ext.EventManager.resizeEvent.removeListener(this.setSize, this); } Ext.destroy(this.componentLayout, this.loadMask); }, destroy : function() { if (!this.isDestroyed) { if (this.fireEvent('beforedestroy', this) !== false) { this.destroying = true; this.beforeDestroy(); if (this.ownerCt && this.ownerCt.remove) { this.ownerCt.remove(this, false); } if (this.rendered) { this.el.remove(); } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent('destroy', this); this.clearListeners(); this.destroying = false; this.isDestroyed = true; } } } }); Ext.lib.Component.prototype.on = Ext.lib.Component.prototype.addListener; Ext.lib.Component.prototype.prev = Ext.lib.Component.prototype.previousSibling; Ext.lib.Component.prototype.next = Ext.lib.Component.prototype.nextSibling; Ext.lib.Component.AUTO_ID = 1000; Ext.Component = Ext.extend(Ext.lib.Component, {}); Ext.reg('component', Ext.Component); Ext.Component = Ext.extend(Ext.lib.Component, { showAnimation: null, monitorOrientation: false, floatingCls: 'x-floating', hideOnMaskTap: true, stopMaskTapEvent: true, centered: false, modal: false, fullscreen: false, layoutOnOrientationChange: null, initComponent : function() { this.addEvents( 'beforeorientationchange', 'orientationchange' ); if (this.fullscreen || this.floating) { this.monitorOrientation = true; this.autoRender = true; } if (this.fullscreen) { var viewportSize = Ext.Viewport.getSize(); this.width = viewportSize.width; this.height = viewportSize.height; this.cls = (this.cls || '') + ' x-fullscreen'; this.renderTo = document.body; } }, onRender : function() { Ext.Component.superclass.onRender.apply(this, arguments); if (this.monitorOrientation) { this.el.addCls('x-' + Ext.Viewport.orientation); } if (this.floating) { this.setFloating(true); } if (this.draggable) { this.setDraggable(this.draggable); } if (this.scroll) { this.setScrollable(this.scroll); } }, afterRender : function() { if (this.fullscreen) { this.layoutOrientation(Ext.Viewport.orientation, this.width, this.height); } Ext.Component.superclass.afterRender.call(this); }, initEvents : function() { Ext.Component.superclass.initEvents.call(this); if (this.monitorOrientation) { Ext.EventManager.onOrientationChange(this.setOrientation, this); } }, afterComponentLayout : function() { var scrollEl = this.scrollEl, scroller = this.scroller, parentEl; if (scrollEl) { parentEl = scrollEl.parent(); if (scroller.horizontal) { scrollEl.setStyle('min-width', parentEl.getWidth(true) + 'px'); scrollEl.setHeight(parentEl.getHeight(true) || null); } if (scroller.vertical) { scrollEl.setStyle('min-height', parentEl.getHeight(true) + 'px'); scrollEl.setWidth(parentEl.getWidth(true) || null); } scroller.updateBoundary(true); } if (this.fullscreen && Ext.is.iPad) { Ext.repaint(); } }, layoutOrientation: Ext.emptyFn, update: function(){ Ext.Component.superclass.update.apply(this, arguments); var scroller = this.scroller; if (scroller && scroller.updateBoundary){ scroller.updateBoundary(true); } }, show : function(animation) { var rendered = this.rendered; if ((this.hidden || !rendered) && this.fireEvent('beforeshow', this) !== false) { if (this.anchorEl) { this.anchorEl.hide(); } if (!rendered && this.autoRender) { this.render(Ext.isBoolean(this.autoRender) ? Ext.getBody() : this.autoRender); } this.hidden = false; if (this.rendered) { this.onShow(animation); this.fireEvent('show', this); } } return this; }, showBy : function(alignTo, animation, allowSides, anchor) { if (!this.floating) { return this; } if (alignTo.isComponent) { alignTo = alignTo.el; } else { alignTo = Ext.get(alignTo); } this.x = 0; this.y = 0; this.show(animation); if (anchor !== false) { if (!this.anchorEl) { this.anchorEl = this.el.createChild({ cls: 'x-anchor' }); } this.anchorEl.show(); } this.alignTo(alignTo, allowSides, 20); }, alignTo : function(alignTo, allowSides, offset) { var alignBox = alignTo.getPageBox(), constrainBox = { width: window.innerWidth, height: window.innerHeight }, size = this.getSize(), newSize = { width: Math.min(size.width, constrainBox.width), height: Math.min(size.height, constrainBox.height) }, position, index = 2, positionMap = [ 'tl-bl', 't-b', 'tr-br', 'l-r', 'l-r', 'r-l', 'bl-tl', 'b-t', 'br-tr' ], anchorEl = this.anchorEl, offsets = [0, offset], targetBox, cls, onSides = false, arrowOffsets = [0, 0], alignCenterX = alignBox.left + (alignBox.width / 2), alignCenterY = alignBox.top + (alignBox.height / 2); if (alignCenterX <= constrainBox.width * (1/3)) { index = 1; arrowOffsets[0] = 25; } else if (alignCenterX >= constrainBox.width * (2/3)) { index = 3; arrowOffsets[0] = -30; } if (alignCenterY >= constrainBox.height * (2/3)) { index += 6; offsets = [0, -offset]; arrowOffsets[1] = -10; } else if (allowSides !== false && alignCenterY >= constrainBox.height * (1/3)) { index += 3; offsets = (index <= 5) ? [offset, 0] : [-offset, 0]; arrowOffsets = (index <= 5) ? [10, 0] : [-10, 0]; onSides = true; } else { arrowOffsets[1] = 10; } position = positionMap[index-1]; targetBox = this.el.getAlignToXY(alignTo, position, offsets); if (onSides) { if (targetBox[0] < 0) { newSize.width = alignBox.left - offset; } else if (targetBox[0] + newSize.width > constrainBox.width) { newSize.width = constrainBox.width - alignBox.right - offset; } } else { if (targetBox[1] < 0) { newSize.height = alignBox.top - offset; } else if (targetBox[1] + newSize.height > constrainBox.height) { newSize.height = constrainBox.height - alignBox.bottom - offset; } } if (newSize.width != size.width) { this.setSize(newSize.width); } else if (newSize.height != size.height) { this.setSize(undefined, newSize.height); } targetBox = this.el.getAlignToXY(alignTo, position, offsets); this.setPosition(targetBox[0], targetBox[1]); if (anchorEl) { anchorEl.removeCls(['x-anchor-bottom', 'x-anchor-left', 'x-anchor-right', 'x-anchor-top']); if (offsets[1] == offset) { cls = 'x-anchor-top'; } else if (offsets[1] == -offset) { cls = 'x-anchor-bottom'; } else if (offsets[0] == offset) { cls = 'x-anchor-left'; } else { cls = 'x-anchor-right'; } targetBox = anchorEl.getAlignToXY(alignTo, position, arrowOffsets); anchorEl.setXY(targetBox); anchorEl.addCls(cls); } return position; }, setCentered : function(centered, update) { this.centered = centered; if (this.rendered && update) { var x, y; if (!this.ownerCt) { x = (Ext.Element.getViewportWidth() / 2) - (this.getWidth() / 2); y = (Ext.Element.getViewportHeight() / 2) - (this.getHeight() / 2); } else { x = (this.ownerCt.getTargetEl().getWidth() / 2) - (this.getWidth() / 2); y = (this.ownerCt.getTargetEl().getHeight() / 2) - (this.getHeight() / 2); } this.setPosition(x, y); } return this; }, hide : function(animation) { if (!this.hidden && this.fireEvent('beforehide', this) !== false) { this.hidden = true; if (this.rendered) { this.onHide(animation, true); } } return this; }, onShow : function(animation) { this.el.show(); Ext.Component.superclass.onShow.call(this, animation); if (animation === undefined || animation === true) { animation = this.showAnimation; } if (this.floating) { this.el.dom.parentNode || this.el.appendTo(document.body); if (animation) { this.el.setStyle('opacity', 0.01); } if (this.centered) { this.setCentered(true, true); } else { this.setPosition(this.x, this.y); } if (this.modal) { this.el.parent().mask(null, 'x-mask-gray'); } if (this.hideOnMaskTap) { Ext.getDoc().on('touchstart', this.onFloatingTouchStart, this, {capture: true, subsequent: true}); } } if (animation) { Ext.Anim.run(this, animation, { out: false, autoClear: true }); this.showAnimation = animation; } }, onFloatingTouchStart: function(e) { if (!this.el.contains(e.target)) { this.hide(); if (this.stopMaskTapEvent || Ext.fly(e.target).hasCls('x-mask')) { e.stopEvent(); } } }, onHide : function(animation, fireHideEvent) { if (animation === undefined || animation === true) { animation = this.showAnimation; } if (this.hideOnMaskTap && this.floating) { Ext.getDoc().un('touchstart', this.onFloatingTouchStart, this, {capture: true, subsequent: true}); } if (animation) { Ext.Anim.run(this, animation, { out: true, reverse: true, autoClear: true, scope: this, fireHideEvent: fireHideEvent, after: this.doHide }); } else { this.doHide(null, {fireHideEvent: fireHideEvent}); } }, doHide : function(el, options) { var parent = this.el.parent(); this.el.hide(); if (parent && this.floating && this.modal) { parent.unmask(); } if (options && options.fireHideEvent) { this.fireEvent('hide', this); } }, setScrollable : function(config) { if (!this.rendered) { this.scroll = config; return; } Ext.destroy(this.scroller); this.scroller = null; if (config !== false) { var direction = Ext.isObject(config) ? config.direction: config; config = Ext.apply({}, Ext.isObject(config) ? config: {}, { direction: direction }); if (!this.scrollEl) { this.scrollEl = this.getTargetEl().createChild(); this.originalGetTargetEl = this.getTargetEl; this.getTargetEl = function() { return this.scrollEl; }; } this.scroller = (new Ext.util.ScrollView(this.scrollEl, config)).scroller; } else { this.getTargetEl = this.originalGetTargetEl; } }, setFloating : function(floating, autoShow) { this.floating = !!floating; this.hidden = true; if (this.rendered) { if (floating !== false) { this.el.addCls(this.floatingCls); if (autoShow) { this.show(); } } else { this.el.removeCls(this.floatingCls); Ext.getDoc().un('touchstart', this.onFloatingTouchStart, this); } } else if (floating !== false) { if (this.layoutOnOrientationChange !== false) { this.layoutOnOrientationChange = true; } this.autoRender = true; } }, setDraggable : function(draggable, autoShow) { this.isDraggable = draggable; if (this.rendered) { if (draggable === false) { if (this.dragObj) { this.dragObj.disable(); } } else { if (autoShow) { this.show(); } if (this.dragObj) { this.dragObj.enable(); } else { this.dragObj = new Ext.util.Draggable(this.el, Ext.apply({}, this.draggable || {})); this.relayEvents(this.dragObj, ['dragstart', 'beforedragend' ,'drag', 'dragend']); } } } }, setOrientation : function(orientation, w, h) { if (this.fireEvent('beforeorientationchange', this, orientation, w, h) !== false) { if (this.orientation != orientation) { this.el.removeCls('x-' + this.orientation); this.el.addCls('x-' + orientation); } this.orientation = orientation; this.layoutOrientation(orientation, w, h); if (this.fullscreen) { this.setSize(w, h); } else if (this.layoutOnOrientationChange) { this.doComponentLayout(); } if (this.floating && this.centered) { this.setCentered(true, true); } this.onOrientationChange(orientation, w, h); this.fireEvent('orientationchange', this, orientation, w, h); } }, onOrientationChange : Ext.emptyFn, beforeDestroy : function() { if (this.floating && this.modal && !this.hidden) { this.el.parent().unmask(); } Ext.destroy(this.scroller); Ext.Component.superclass.beforeDestroy.call(this); }, onDestroy : function() { if (this.monitorOrientation && Ext.EventManager.orientationEvent) { Ext.EventManager.orientationEvent.removeListener(this.setOrientation, this); } Ext.Component.superclass.onDestroy.call(this); } }); Ext.BoxComponent = Ext.Component; Ext.reg('component', Ext.Component); Ext.reg('box', Ext.BoxComponent); Ext.lib.Container = Ext.extend(Ext.Component, { autoDestroy : true, defaultType: 'panel', isContainer : true, baseCls: 'x-container', bubbleEvents: ['add', 'remove'], initComponent : function(){ this.addEvents( 'afterlayout', 'beforeadd', 'beforeremove', 'add', 'remove', 'beforecardswitch', 'cardswitch' ); this.layoutOnShow = new Ext.util.MixedCollection(); Ext.lib.Container.superclass.initComponent.call(this); this.initItems(); }, initItems : function() { var items = this.items; this.items = new Ext.util.MixedCollection(false, this.getComponentId); if (items) { if (!Ext.isArray(items)) { items = [items]; } this.add(items); } }, afterRender : function() { this.getLayout(); Ext.lib.Container.superclass.afterRender.apply(this, arguments); }, setLayout : function(layout) { var currentLayout = this.layout; if (currentLayout && currentLayout.isLayout && currentLayout != layout) { currentLayout.setOwner(null); } this.layout = layout; layout.setOwner(this); }, getLayout : function() { if (!this.layout || !this.layout.isLayout) { this.setLayout(Ext.layout.LayoutManager.create(this.layout, 'autocontainer')); } return this.layout; }, doLayout : function() { var layout = this.getLayout(); if (this.rendered && layout) { layout.layout(); } return this; }, afterLayout : function(layout) { this.fireEvent('afterlayout', this, layout); }, prepareItems : function(items, applyDefaults) { if (!Ext.isArray(items)) { items = [items]; } var item, i, ln; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; if (applyDefaults) { item = this.applyDefaults(item); } items[i] = this.lookupComponent(item); } return items; }, applyDefaults : function(config) { var defaults = this.defaults; if (defaults) { if (Ext.isFunction(defaults)) { defaults = defaults.call(this, config); } if (Ext.isString(config)) { config = Ext.ComponentMgr.get(config); Ext.apply(config, defaults); } else if (!config.isComponent) { Ext.applyIf(config, defaults); } else { Ext.apply(config, defaults); } } return config; }, lookupComponent : function(comp) { if (Ext.isString(comp)) { return Ext.ComponentMgr.get(comp); } else { return this.createComponent(comp); } return comp; }, createComponent : function(config, defaultType) { if (config.isComponent) { return config; } return Ext.create(config, defaultType || this.defaultType); }, getComponentId : function(comp) { return comp.getItemId(); }, add : function() { var args = Array.prototype.slice.call(arguments), index = -1; if (typeof args[0] == 'number') { index = args.shift(); } var hasMultipleArgs = args.length > 1; if (hasMultipleArgs || Ext.isArray(args[0])) { var items = hasMultipleArgs ? args : args[0], results = [], i, ln, item; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; if (!item) { throw "Trying to add a null item as a child of Container with itemId/id: " + this.getItemId(); } if (index != -1) { item = this.add(index + i, item); } else { item = this.add(item); } results.push(item); } return results; } var cmp = this.prepareItems(args[0], true)[0]; index = (index !== -1) ? index : this.items.length; if (this.fireEvent('beforeadd', this, cmp, index) !== false && this.onBeforeAdd(cmp) !== false) { this.items.insert(index, cmp); cmp.onAdded(this, index); this.onAdd(cmp, index); this.fireEvent('add', this, cmp, index); } return cmp; }, onAdd : Ext.emptyFn, onRemove : Ext.emptyFn, insert : function(index, comp){ return this.add(index, comp); }, onBeforeAdd : function(item) { if (item.ownerCt) { item.ownerCt.remove(item, false); } if (this.hideBorders === true){ item.border = (item.border === true); } }, remove : function(comp, autoDestroy) { var c = this.getComponent(comp); if (!c) { console.warn("Attempted to remove a component that does not exist. Ext.Container: remove takes an argument of the component to remove. cmp.remove() is incorrect usage."); } if (c && this.fireEvent('beforeremove', this, c) !== false) { this.doRemove(c, autoDestroy); this.fireEvent('remove', this, c); } return c; }, doRemove : function(component, autoDestroy) { var layout = this.layout, hasLayout = layout && this.rendered; this.items.remove(component); component.onRemoved(); if (hasLayout) { layout.onRemove(component); } this.onRemove(component, autoDestroy); if (autoDestroy === true || (autoDestroy !== false && this.autoDestroy)) { component.destroy(); } if (hasLayout && !autoDestroy) { layout.afterRemove(component); } }, removeAll : function(autoDestroy) { var item, removeItems = this.items.items.slice(), items = [], ln = removeItems.length, i; for (i = 0; i < ln; i++) { item = removeItems[i]; this.remove(item, autoDestroy); if (item.ownerCt !== this) { items.push(item); } } return items; }, getRefItems : function(deep) { var items = this.items.items.slice(), ln = items.length, i, item; if (deep) { for (i = 0; i < ln; i++) { item = items[i]; if (item.getRefItems) { items = items.concat(item.getRefItems(true)); } } } return items; }, getComponent : function(comp) { if (Ext.isObject(comp)) { comp = comp.getItemId(); } return this.items.get(comp); }, query : function(selector) { return Ext.ComponentQuery.query(selector, this); }, child : function(selector) { return this.query('> ' + selector)[0] || null; }, down : function(selector) { return this.query(selector)[0] || null; }, show : function() { Ext.lib.Container.superclass.show.apply(this, arguments); var layoutCollection = this.layoutOnShow, ln = layoutCollection.getCount(), i = 0, needsLayout, item; for (; i < ln; i++) { item = layoutCollection.get(i); needsLayout = item.needsLayout; if (Ext.isObject(needsLayout)) { item.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize); } } layoutCollection.clear(); }, beforeDestroy : function() { var items = this.items, c; if (items) { while ((c = items.first())) { this.doRemove(c, true); } } Ext.destroy(this.layout); Ext.lib.Container.superclass.beforeDestroy.call(this); } }); Ext.Container = Ext.extend(Ext.lib.Container, {}); Ext.reg('container', Ext.Container); Ext.Container = Ext.extend(Ext.lib.Container, { cardSwitchAnimation: null, initComponent: function() { if (this.scroll) { this.fields = new Ext.util.MixedCollection(); this.fields.on({ add: this.onFieldAdd, remove: this.onFieldRemove, scope: this }); this.on({ add: this.onItemAdd, remove: this.onItemRemove, scope: this }); } Ext.Container.superclass.initComponent.apply(this, arguments); }, afterRender: function() { Ext.Container.superclass.afterRender.apply(this, arguments); if (this.scroller) { if (Ext.is.Android && this.containsFormFields) { this.scroller.setUseCssTransform(false); } this.scroller.on('scrollstart', this.onFieldScrollStart, this); } }, onFieldScrollStart: function() { var focusedField = this.focusedField; if (focusedField && Ext.is.iOS) { focusedField.blur(); } }, onItemAdd: function(me, item) { this.fields.addAll(Ext.ComponentQuery.query('[isField]', item)); }, onItemRemove: function(me, item) { this.fields.removeAll(Ext.ComponentQuery.query('[isField]', item)); }, onFieldAdd: function(key, field) { this.handleFieldEventListener(true, field); }, onFieldRemove: function(key, field) { this.handleFieldEventListener(false, field); }, handleFieldEventListener: function(isAdding, item) { if (!this.fieldEventWrap) this.fieldEventWrap = {}; if (['textfield', 'passwordfield', 'emailfield', 'textareafield', 'searchfield', 'urlfield', 'numberfield', 'spinnerfield'].indexOf(item.xtype) !== -1) { if (isAdding) { this.fieldEventWrap[item.id] = { beforefocus: function(e) {this.onFieldBeforeFocus(item, e);}, focus: function(e) {this.onFieldFocus(item, e);}, blur: function(e) {this.onFieldBlur(item, e);}, keyup: function(e) {this.onFieldKeyUp(item, e);}, scope: this }; this.containsFormFields = true; } item[isAdding ? 'on' : 'un'](this.fieldEventWrap[item.id]); if (!isAdding) { delete this.fieldEventWrap[item.id]; } } }, onFieldKeyUp: function(field, e) { this.resetLastWindowScroll(); }, onFieldBeforeFocus: function(field, e) { this.focusingField = field; }, getLastWindowScroll: function() { if (!this.lastWindowScroll) { this.resetLastWindowScroll(); } return {x: this.lastWindowScroll.x, y: this.lastWindowScroll.y}; }, resetLastWindowScroll: function() { this.lastWindowScroll = { x: window.pageXOffset, y: window.pageYOffset }; }, adjustScroller: function(offset) { var scroller = this.getClosestScroller(), windowScroll = this.getLastWindowScroll(); scroller.setOffset(offset); if (Ext.is.iOS) { window.scrollTo(windowScroll.x, windowScroll.y); } this.resetLastWindowScroll(); }, onFieldFocus: function(field, e) { var scroller = this.getClosestScroller(), containerRegion = Ext.util.Region.from(scroller.containerBox), fieldRegion = field.fieldEl.getPageBox(true); if (this.focusingField == field || !Ext.is.iOS) { if (Ext.is.iOS && window.pageYOffset == 0) { window.scrollTo(0, 0); } var adjustment = new Ext.util.Offset(); if (fieldRegion.left < containerRegion.left) { adjustment.x = containerRegion.left - fieldRegion.left; } if (fieldRegion.top < containerRegion.top) { adjustment.y = containerRegion.top - fieldRegion.top; } if (!adjustment.isZero()) { var windowScroll = this.getLastWindowScroll(); scroller.scrollBy(adjustment); if (Ext.is.iOS) { window.scrollTo(windowScroll.x, windowScroll.y); } this.resetLastWindowScroll(); } } else { if (this.lastFocusedField) { var deltaY = fieldRegion.top - this.lastFocusedField.fieldEl.getY(), offsetY = scroller.offset.y - deltaY, selfHandling = false; if (!containerRegion.contains(fieldRegion) && (offsetY != 0 || (offsetY == 0 && scroller.offset.y != 0))) { selfHandling = true; } if (offsetY > 0) { offsetY = 0; } if (selfHandling) { this.adjustScroller(new Ext.util.Offset( scroller.offset.x, offsetY )); } } } this.resetLastWindowScroll(); this.lastFocusedField = field; this.focusedField = field; this.focusingField = null; }, getClosestScroller: function() { if (!this.closestScroller) { this.closestScroller = this.scroller || this.el.getScrollParent(); } return this.closestScroller; }, onFieldBlur: function(field, e) { if (this.focusingField == field) { this.focusingField = null; } if (this.focusedField == field) { this.focusedField = null; } }, afterLayout : function(layout) { if (this.floating && this.centered) { this.setCentered(true, true); } if (this.scroller) { this.scroller.updateBoundary(); } Ext.Container.superclass.afterLayout.call(this, layout); }, getActiveItem : function() { if (this.layout && this.layout.type == 'card') { return this.layout.activeItem; } else { return null; } }, setActiveItem : function(card, animation) { this.layout.setActiveItem(card, animation); return this; }, onBeforeCardSwitch : function(newCard, oldCard, newIndex, animated) { return this.fireEvent('beforecardswitch', this, newCard, oldCard, newIndex, animated); }, onCardSwitch : function(newCard, oldCard, newIndex, animated) { return this.fireEvent('cardswitch', this, newCard, oldCard, newIndex, animated); }, disable: function() { Ext.Container.superclass.disable.call(this); this.el.mask(null, 'x-mask-gray'); }, enable: function() { Ext.Container.superclass.enable.call(this); this.el.unmask(); } }); Ext.reg('container', Ext.Container); Ext.lib.Panel = Ext.extend(Ext.Container, { baseCls : 'x-panel', isPanel: true, componentLayout: 'dock', renderTpl: ['<div class="{baseCls}-body<tpl if="bodyCls"> {bodyCls}</tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>></div>'], initComponent : function() { this.addEvents( 'bodyresize' ); Ext.applyIf(this.renderSelectors, { body: '.' + this.baseCls + '-body' }); Ext.lib.Panel.superclass.initComponent.call(this); }, initItems : function() { Ext.lib.Panel.superclass.initItems.call(this); var items = this.dockedItems; this.dockedItems = new Ext.util.MixedCollection(false, this.getComponentId); if (items) { this.addDocked(items); } }, getDockedComponent: function(comp) { if (Ext.isObject(comp)) { comp = comp.getItemId(); } return this.dockedItems.get(comp); }, getComponent: function(comp) { var component = Ext.lib.Panel.superclass.getComponent.call(this, comp); if (component == undefined) { component = this.getDockedComponent(comp); } return component; }, initBodyStyles: function() { var bodyStyle = Ext.isString(this.bodyStyle) ? this.bodyStyle.split(';') : [], Element = Ext.Element; if (this.bodyPadding != undefined) { bodyStyle.push('padding: ' + Element.unitizeBox((this.bodyPadding === true) ? 5 : this.bodyPadding)); } if (this.bodyMargin != undefined) { bodyStyle.push('margin: ' + Element.unitizeBox((this.bodyMargin === true) ? 5 : this.bodyMargin)); } if (this.bodyBorder != undefined) { bodyStyle.push('border-width: ' + Element.unitizeBox((this.bodyBorder === true) ? 1 : this.bodyBorder)); } delete this.bodyStyle; return bodyStyle.length ? bodyStyle.join(';') : undefined; }, initRenderData: function() { return Ext.applyIf(Ext.lib.Panel.superclass.initRenderData.call(this), { bodyStyle: this.initBodyStyles(), bodyCls: this.bodyCls }); }, addDocked : function(items, pos) { items = this.prepareItems(items); var item, i, ln; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; item.dock = item.dock || 'top'; if (pos !== undefined) { this.dockedItems.insert(pos+i, item); } else { this.dockedItems.add(item); } item.onAdded(this, i); this.onDockedAdd(item); } if (this.rendered) { this.doComponentLayout(); } }, onDockedAdd : Ext.emptyFn, onDockedRemove : Ext.emptyFn, insertDocked : function(pos, items) { this.addDocked(items, pos); }, removeDocked : function(item, autoDestroy) { if (!this.dockedItems.contains(item)) { return item; } var layout = this.componentLayout, hasLayout = layout && this.rendered; if (hasLayout) { layout.onRemove(item); } this.dockedItems.remove(item); item.onRemoved(); this.onDockedRemove(item); if (autoDestroy === true || (autoDestroy !== false && this.autoDestroy)) { item.destroy(); } if (hasLayout && !autoDestroy) { layout.afterRemove(item); } this.doComponentLayout(); return item; }, getDockedItems : function() { if (this.dockedItems && this.dockedItems.items.length) { return this.dockedItems.items.slice(); } return []; }, getTargetEl : function() { return this.body; }, getRefItems: function(deep) { var refItems = Ext.lib.Panel.superclass.getRefItems.call(this, deep), dockedItems = this.getDockedItems(), ln = dockedItems.length, i = 0, item; refItems = refItems.concat(dockedItems); if (deep) { for (; i < ln; i++) { item = dockedItems[i]; if (item.getRefItems) { refItems = refItems.concat(item.getRefItems(true)); } } } return refItems; }, beforeDestroy: function(){ var docked = this.dockedItems, c; if (docked) { while ((c = docked.first())) { this.removeDocked(c, true); } } Ext.lib.Panel.superclass.beforeDestroy.call(this); } }); Ext.Panel = Ext.extend(Ext.lib.Panel, {}); Ext.reg('panel', Ext.Panel); Ext.Panel = Ext.extend(Ext.lib.Panel, { scroll: false }); Ext.reg('panel', Ext.Panel); Ext.Button = Ext.extend(Ext.Component, { initComponent: function(){ this.addEvents( 'tap', 'beforetap' ); Ext.Button.superclass.initComponent.call(this); this.createAutoHandler(); }, iconAlign: 'left', baseCls: 'x-button', pressedCls: 'x-button-pressed', badgeText: '', badgeCls: 'x-badge', hasBadgeCls: 'x-hasbadge', labelCls: 'x-button-label', ui: 'normal', isButton: true, pressedDelay: 0, iconMaskCls: 'x-icon-mask', iconMask: false, afterRender : function(ct, position) { var me = this; Ext.Button.superclass.afterRender.call(me, ct, position); var text = me.text, icon = me.icon, iconCls = me.iconCls, badgeText = me.badgeText; me.text = me.icon = me.iconCls = me.badgeText = null; me.setText(text); me.setIcon(icon); me.setIconClass(iconCls); if (me.iconMask && me.iconEl) { me.iconEl.addCls(me.iconMaskCls); } me.setBadge(badgeText); }, initEvents : function() { var me = this; Ext.Button.superclass.initEvents.call(me); me.mon(me.el, { scope: me, tap : me.onPress, tapstart : me.onTapStart, tapcancel: me.onTapCancel }); }, onTapStart : function() { var me = this; if (!me.disabled) { if (me.pressedDelay) { me.pressedTimeout = setTimeout(function() { me.el.addCls(me.pressedCls); }, Ext.isNumber(me.pressedDelay) ? me.pressedDelay : 100); } else { me.el.addCls(me.pressedCls); } } }, onTapCancel : function() { var me = this; if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); delete me.pressedTimeout; } me.el.removeCls(me.pressedCls); }, setHandler : function(handler, scope) { this.handler = handler; this.scope = scope; return this; }, setText: function(text) { var me = this; if (me.rendered) { if (!me.textEl && text) { me.textEl = me.el.createChild({ tag: 'span', html: text, cls: this.labelCls }); } else if (me.textEl && text != me.text) { if (text) { me.textEl.setHTML(text); } else { me.textEl.remove(); me.textEl = null; } } } me.text = text; return me; }, setIcon: function(icon) { var me = this; if (me.rendered) { if (!me.iconEl && icon) { me.iconEl = me.el.createChild({ tag: 'img', src: Ext.BLANK_IMAGE_URL, style: 'background-image: ' + (icon ? 'url(' + icon + ')' : '') }); me.setIconAlign(me.iconAlign); } else if (me.iconEl && icon != me.icon) { if (icon) { me.iconEl.setStyle('background-image', icon ? 'url(' + icon + ')' : ''); me.setIconAlign(me.iconAlign); } else { me.setIconAlign(false); me.iconEl.remove(); me.iconEl = null; } } } me.icon = icon; return me; }, setIconClass: function(cls) { var me = this; if (me.rendered) { if (!me.iconEl && cls) { me.iconEl = me.el.createChild({ tag: 'img', src: Ext.BLANK_IMAGE_URL, cls: cls }); me.setIconAlign(me.iconAlign); } else if (me.iconEl && cls != me.iconCls) { if (cls) { if (me.iconCls) { me.iconEl.removeCls(me.iconCls); } me.iconEl.addCls(cls); me.setIconAlign(me.iconAlign); } else { me.setIconAlign(false); me.iconEl.remove(); me.iconEl = null; } } } me.iconCls = cls; return me; }, setIconAlign: function(alignment) { var me = this, alignments = ['top', 'right', 'bottom', 'left'], alignment = ((alignments.indexOf(alignment) == -1 || !alignment) && alignment !== false) ? me.iconAlign : alignment, i; if (me.rendered && me.iconEl) { me.el.removeCls('x-iconalign-' + me.iconAlign); if (alignment) me.el.addCls('x-iconalign-' + alignment); } me.iconAlign = (alignment === false) ? me.iconAlign : alignment; return me; }, setBadge : function(text) { var me = this; if (me.rendered) { if (!me.badgeEl && text) { me.badgeEl = me.el.createChild({ tag: 'span', cls: me.badgeCls, html: text }); me.el.addCls(me.hasBadgeCls); } else if (me.badgeEl && text != me.badgeText) { if (text) { me.badgeEl.setHTML(text); me.el.addCls(me.hasBadgeCls); } else { me.badgeEl.remove(); me.badgeEl = null; me.el.removeCls(me.hasBadgeCls); } } } me.badgeText = text; return me; }, getText : function() { return this.text; }, getBadgeText : function() { return this.badgeText; }, onDisable : function() { this.onDisableChange(true); }, onEnable : function() { this.onDisableChange(false); }, onDisableChange : function(disabled) { var me = this; if (me.el) { me.el[disabled ? 'addCls' : 'removeCls'](me.disabledCls); me.el.dom.disabled = disabled; } me.disabled = disabled; }, onPress : function(e) { var me = this; if (!me.disabled && this.fireEvent('beforetap') !== false) { setTimeout(function() { if (!me.preventCancel) { me.onTapCancel(); } me.callHandler(e); me.fireEvent('tap', me, e); }, 10); } }, callHandler: function(e) { var me = this; if (me.handler) { me.handler.call(me.scope || me, me, e); } }, createAutoHandler: function() { var me = this, autoEvent = me.autoEvent; if (autoEvent) { if (typeof autoEvent == 'string') { autoEvent = { name: autoEvent, scope: me.scope || me }; } me.addEvents(autoEvent.name); me.setHandler(function() { autoEvent.scope.fireEvent(autoEvent.name, autoEvent.scope, me); }, autoEvent.scope); } } }); Ext.reg('button', Ext.Button); Ext.SegmentedButton = Ext.extend(Ext.Container, { defaultType: 'button', componentCls: 'x-segmentedbutton', pressedCls: 'x-button-pressed', allowMultiple: false, initComponent : function() { this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'stretch' }); Ext.SegmentedButton.superclass.initComponent.call(this); if (this.allowDepress === undefined) { this.allowDepress = this.allowMultiple; } this.addEvents( 'toggle' ); }, initEvents : function() { Ext.SegmentedButton.superclass.initEvents.call(this); this.mon(this.el, { tap: this.onTap, capture: true, scope: this }); }, afterLayout : function(layout) { var me = this; Ext.SegmentedButton.superclass.afterLayout.call(me, layout); if (!me.initialized) { me.items.each(function(item, index) { me.setPressed(item, !!item.pressed, true); }); if (me.allowMultiple) { me.pressedButtons = me.getPressedButtons(); } me.initialized = true; } }, onTap : function(e, t) { if (!this.disabled && (t = e.getTarget('.x-button'))) { this.setPressed(t.id, this.allowDepress ? undefined : true); } }, getPressed : function() { return this.allowMultiple ? this.getPressedButtons() : this.pressedButton; }, setPressed : function(btn, pressed, suppressEvents) { var me = this; btn = me.getComponent(btn); if (!btn || !btn.isButton || btn.disabled) { if (!me.allowMultiple && me.pressedButton) { me.setPressed(me.pressedButton, false); } return; } if (!Ext.isBoolean(pressed)) { pressed = !btn.pressed; } if (pressed) { if (!me.allowMultiple) { if (me.pressedButton && me.pressedButton !== btn) { me.pressedButton.el.removeCls(me.pressedCls); me.pressedButton.pressed = false; if (suppressEvents !== true) { me.fireEvent('toggle', me, me.pressedButton, false); } } me.pressedButton = btn; } btn.el.addCls(me.pressedCls); btn.pressed = true; btn.preventCancel = true; if (me.initialized && suppressEvents !== true) { me.fireEvent('toggle', me, btn, true); } } else if (!pressed) { if (!me.allowMultiple && btn === me.pressedButton) { me.pressedButton = null; } if (btn.pressed) { btn.el.removeCls(me.pressedCls); btn.pressed = false; if (suppressEvents !== true) { me.fireEvent('toggle', me, btn, false); } } } if (me.allowMultiple && me.initialized) { me.pressedButtons = me.getPressedButtons(); } }, getPressedButtons : function(toggleEvents) { var pressed = this.items.filterBy(function(item) { return item.isButton && !item.disabled && item.pressed; }); return pressed.items; }, disable : function() { this.items.each(function(item) { item.disable(); }); Ext.SegmentedButton.superclass.disable.apply(this, arguments); }, enable : function() { this.items.each(function(item) { item.enable(); }, this); Ext.SegmentedButton.superclass.enable.apply(this, arguments); } }); Ext.reg('segmentedbutton', Ext.SegmentedButton); Ext.AbstractStoreSelectionModel = Ext.extend(Ext.util.Observable, { allowDeselect: false, selected: null, constructor: function(cfg) { cfg = cfg || {}; Ext.apply(this, cfg); this.modes = { SINGLE: true, SIMPLE: true, MULTI: true }; this.setSelectionMode(cfg.mode); this.selected = new Ext.util.MixedCollection(); Ext.AbstractStoreSelectionModel.superclass.constructor.call(this, cfg); }, bind : function(store, initial){ if(!initial && this.store){ if(store !== this.store && this.store.autoDestroy){ this.store.destroy(); }else{ this.store.un("add", this.onStoreAdd, this); this.store.un("clear", this.onStoreClear, this); this.store.un("remove", this.onStoreRemove, this); this.store.un("update", this.onStoreUpdate, this); } } if(store){ store = Ext.StoreMgr.lookup(store); store.on({ add: this.onStoreAdd, clear: this.onStoreClear, remove: this.onStoreRemove, update: this.onStoreUpdate, scope: this }); } this.store = store; if(store && !initial) { this.refresh(); } }, selectAll: function(silent) { var selections = this.store.getRange(); for (var i = 0, ln = selections.length; i < ln; i++) { this.doSelect(selections[i], true, silent); } }, deselectAll: function() { var selections = this.getSelection(); for (var i = 0, ln = selections.length; i < ln; i++) { this.doDeselect(selections[i]); } }, selectWithEvent: function(record, e) { switch (this.selectionMode) { case 'MULTI': if (e.ctrlKey && this.isSelected(record)) { this.doDeselect(record, false); } else if (e.shiftKey && this.lastFocused) { this.selectRange(this.lastFocused, record, e.ctrlKey); } else if (e.ctrlKey) { this.doSelect(record, true, false); } else if (this.isSelected(record) && !e.shiftKey && !e.ctrlKey && this.selected.getCount() > 1) { this.doSelect(record, false, false); } else { this.doSelect(record, false); } break; case 'SIMPLE': if (this.isSelected(record)) { this.doDeselect(record); } else { this.doSelect(record, true); } break; case 'SINGLE': if (this.allowDeselect && this.isSelected(record)) { this.doDeselect(record); } else { this.doSelect(record, false); } break; } }, selectRange : function(startRecord, endRecord, keepExisting, dir){ var i, startRow = this.store.indexOf(startRecord), endRow = this.store.indexOf(endRecord), tmp, selectedCount = 0, dontDeselect; if (this.isLocked()){ return; } if (startRow > endRow){ tmp = endRow; endRow = startRow; startRow = tmp; } for (i = startRow; i <= endRow; i++) { if (this.isSelected(this.store.getAt(i))) { selectedCount++; } } if (!dir) { dontDeselect = -1; } else { dontDeselect = (dir == 'up') ? startRow : endRow; } for (i = startRow; i <= endRow; i++){ if (selectedCount == (endRow - startRow + 1)) { if (i != dontDeselect) { this.doDeselect(i, true); } } else { this.doSelect(i, true); } } }, select: function(records, keepExisting, suppressEvent) { this.doSelect(records, keepExisting, suppressEvent); }, deselect: function(records, suppressEvent) { this.doDeselect(records, suppressEvent); }, doSelect: function(records, keepExisting, suppressEvent) { if (this.locked) { return; } if (typeof records === "number") { records = [this.store.getAt(records)]; } if (this.selectionMode == "SINGLE" && records) { var record = records.length ? records[0] : records; this.doSingleSelect(record, suppressEvent); } else { this.doMultiSelect(records, keepExisting, suppressEvent); } }, doMultiSelect: function(records, keepExisting, suppressEvent) { if (this.locked) { return; } var selected = this.selected, change = false, record; records = !Ext.isArray(records) ? [records] : records; if (!keepExisting && selected.getCount() > 0) { change = true; this.doDeselect(this.getSelection(), true); } for (var i = 0, ln = records.length; i < ln; i++) { record = records[i]; if (keepExisting && this.isSelected(record)) { continue; } change = true; this.lastSelected = record; selected.add(record); if (!suppressEvent) { this.setLastFocused(record); } this.onSelectChange(record, true, suppressEvent); } this.maybeFireSelectionChange(change && !suppressEvent); }, doDeselect: function(records, suppressEvent) { if (this.locked) { return; } if (typeof records === "number") { records = [this.store.getAt(records)]; } var change = false, selected = this.selected, record; records = !Ext.isArray(records) ? [records] : records; for (var i = 0, ln = records.length; i < ln; i++) { record = records[i]; if (selected.remove(record)) { if (this.lastSelected == record) { this.lastSelected = selected.last(); } this.onSelectChange(record, false, suppressEvent); change = true; } } this.maybeFireSelectionChange(change && !suppressEvent); }, doSingleSelect: function(record, suppressEvent) { if (this.locked) { return; } if (this.isSelected(record)) { return; } var selected = this.selected; if (selected.getCount() > 0) { this.doDeselect(this.lastSelected, suppressEvent); } selected.add(record); this.lastSelected = record; this.onSelectChange(record, true, suppressEvent); this.setLastFocused(record); this.maybeFireSelectionChange(!suppressEvent); }, setLastFocused: function(record) { var recordBeforeLast = this.lastFocused; this.lastFocused = record; this.onLastFocusChanged(recordBeforeLast, record); }, maybeFireSelectionChange: function(fireEvent) { if (fireEvent) { this.fireEvent('selectionchange', this, this.getSelection()); } }, getLastSelected: function() { return this.lastSelected; }, getLastFocused: function() { return this.lastFocused; }, getSelection: function() { return this.selected.getRange(); }, getSelectionMode: function() { return this.selectionMode; }, setSelectionMode: function(selMode) { selMode = selMode ? selMode.toUpperCase() : 'SINGLE'; this.selectionMode = this.modes[selMode] ? selMode : 'SINGLE'; }, isLocked: function() { return this.locked; }, setLocked: function(locked) { this.locked = !!locked; }, isSelected: function(record) { record = Ext.isNumber(record) ? this.store.getAt(record) : record; return this.selected.indexOf(record) !== -1; }, hasSelection: function() { return this.selected.getCount() > 0; }, refresh: function() { var toBeSelected = [], oldSelections = this.getSelection(), ln = oldSelections.length, selection, change, i = 0; for (; i < ln; i++) { selection = oldSelections[i]; if (this.store.indexOf(selection) != -1) { toBeSelected.push(selection); } } if (this.selected.getCount() != toBeSelected.length) { change = true; } this.clearSelections(); if (toBeSelected.length) { this.doSelect(toBeSelected, false, true); } this.maybeFireSelectionChange(change); }, clearSelections: function() { this.selected.clear(); this.lastSelected = null; this.setLastFocused(null); }, onStoreAdd: function() { }, onStoreClear: function() { var selected = this.selected; if (selected.getCount > 0) { selected.clear(); this.lastSelected = null; this.setLastFocused(null); this.maybeFireSelectionChange(true); } }, onStoreRemove: function(store, record) { if (this.locked) { return; } var selected = this.selected; if (selected.remove(record)) { if (this.lastSelected == record) { this.lastSelected = null; } if (this.getLastFocused() == record) { this.setLastFocused(null); } this.maybeFireSelectionChange(true); } }, getCount: function() { return this.selected.getCount(); }, destroy: function() { }, onStoreUpdate: function() { }, onSelectChange: function(record, isSelected, suppressEvent) { }, onLastFocusChanged: function(oldFocused, newFocused) { }, onEditorKey: function(field, e) { }, bindComponent: function(cmp) { } }); Ext.DataViewSelectionModel = Ext.extend(Ext.AbstractStoreSelectionModel, { deselectOnContainerClick: true, bindComponent: function(view) { this.view = view; this.bind(view.getStore()); var eventListeners = { refresh: this.refresh, scope: this, el: { scope: this } }; eventListeners.el[view.triggerEvent] = this.onItemClick; eventListeners.el[view.triggerCtEvent] = this.onContainerClick; view.on(eventListeners); }, onItemClick: function(e) { var view = this.view, node = view.findTargetByEvent(e); if (node) { this.selectWithEvent(view.getRecord(node), e); } else { return false; } }, onContainerClick: function() { if (this.deselectOnContainerClick) { this.deselectAll(); } }, onSelectChange: function(record, isSelected, suppressEvent) { var view = this.view; if (isSelected) { view.onItemSelect(record); if (!suppressEvent) { this.fireEvent('select', this, record); } } else { view.onItemDeselect(record); if (!suppressEvent) { this.fireEvent('deselect', this, record); } } } }); Ext.DataView = Ext.extend(Ext.Component, { loadingText: 'Loading...', selectedItemCls: "x-item-selected", emptyText: "", deferEmptyText: true, trackOver: false, blockRefresh: false, last: false, triggerEvent: 'click', triggerCtEvent: 'containerclick', addCmpEvents: function() { }, initComponent : function(){ var isDef = Ext.isDefined; if (!isDef(this.tpl) || !isDef(this.store) || !isDef(this.itemSelector)) { throw "DataView requires tpl, store and itemSelector configurations to be defined."; } Ext.DataView.superclass.initComponent.call(this); if(Ext.isString(this.tpl) || Ext.isArray(this.tpl)){ this.tpl = new Ext.XTemplate(this.tpl); } if (Ext.isDefined(this.overCls) || Ext.isDefined(this.overClass)) { this.overItemCls = this.overCls || this.overClass; delete this.overCls; delete this.overClass; throw "Using the deprecated overCls or overClass configuration. Use overItemCls."; } if (Ext.isDefined(this.selectedCls) || Ext.isDefined(this.selectedClass)) { this.selectedItemCls = this.selectedCls || this.selectedClass; delete this.selectedCls; delete this.selectedClass; throw "Using the deprecated selectedCls or selectedClass configuration. Use selectedItemCls."; } this.addCmpEvents(); this.store = Ext.StoreMgr.lookup(this.store) this.all = new Ext.CompositeElementLite(); this.getSelectionModel().bindComponent(this); }, onRender : function() { Ext.DataView.superclass.onRender.apply(this, arguments); if (this.loadingText) { this.loadMask = new Ext.LoadMask(this.el, { msg: this.loadingText }); } }, getSelectionModel: function(){ if (!this.selModel) { this.selModel = {}; } var mode; switch(true) { case this.simpleSelect: mode = 'SIMPLE'; break; case this.multiSelect: mode = 'MULTI'; break; case this.singleSelect: default: mode = 'SINGLE'; break; } Ext.applyIf(this.selModel, { allowDeselect: this.allowDeselect, mode: mode }); if (!this.selModel.events) { this.selModel = new Ext.DataViewSelectionModel(this.selModel); } if (!this.selModel.hasRelaySetup) { this.relayEvents(this.selModel, ['selectionchange', 'select', 'deselect']); this.selModel.hasRelaySetup = true; } if (this.disableSelection) { this.selModel.locked = true; } return this.selModel; }, refresh: function() { if (!this.rendered) { return; } var el = this.getTargetEl(), records = this.store.getRange(); el.update(''); if (records.length < 1) { if (!this.deferEmptyText || this.hasSkippedEmptyText) { el.update(this.emptyText); } this.all.clear(); } else { this.tpl.overwrite(el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, el.dom)); this.updateIndexes(0); } this.hasSkippedEmptyText = true; this.fireEvent('refresh'); }, prepareData: function(data, index, record) { if (record) { Ext.apply(data, this.prepareAssociatedData(record)); } return data; }, prepareAssociatedData: function(record, ids) { ids = ids || []; var associations = record.associations.items, associationCount = associations.length, associationData = {}, associatedStore, associatedName, associatedRecords, associatedRecord, associatedRecordCount, association, internalId, i, j; for (i = 0; i < associationCount; i++) { association = associations[i]; associatedStore = record[association.storeName]; associationData[association.name] = []; if (associatedStore && associatedStore.data.length > 0) { associatedRecords = associatedStore.data.items; associatedRecordCount = associatedRecords.length; for (j = 0; j < associatedRecordCount; j++) { associatedRecord = associatedRecords[j]; internalId = associatedRecord.internalId; if (ids.indexOf(internalId) == -1) { ids.push(internalId); associationData[association.name][j] = associatedRecord.data; Ext.apply(associationData[association.name][j], this.prepareAssociatedData(associatedRecord, ids)); } } } } return associationData; }, collectData : function(records, startIndex){ var r = [], i = 0, len = records.length; for(; i < len; i++){ r[r.length] = this.prepareData(records[i].data, startIndex + i, records[i]); } return r; }, bufferRender : function(records, index){ var div = document.createElement('div'); this.tpl.overwrite(div, this.collectData(records, index)); return Ext.query(this.itemSelector, div); }, onUpdate : function(ds, record){ var index = this.store.indexOf(record), original, node; if (index > -1){ original = this.all.elements[index]; node = this.bufferRender([record], index)[0]; this.all.replaceElement(index, node, true); this.updateIndexes(index, index); this.selModel.refresh(); } }, onAdd : function(ds, records, index){ if (this.all.getCount() === 0) { this.refresh(); return; } var nodes = this.bufferRender(records, index), n, a = this.all.elements; if (index < this.all.getCount()) { n = this.all.item(index).insertSibling(nodes, 'before', true); a.splice.apply(a, [index, 0].concat(nodes)); } else { n = this.all.last().insertSibling(nodes, 'after', true); a.push.apply(a, nodes); } this.updateIndexes(index); }, onRemove : function(ds, record, index){ this.all.removeElement(index, true); this.updateIndexes(index); if (this.store.getCount() === 0){ this.refresh(); } }, refreshNode : function(index){ this.onUpdate(this.store, this.store.getAt(index)); }, updateIndexes : function(startIndex, endIndex){ var ns = this.all.elements; startIndex = startIndex || 0; endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1)); for(var i = startIndex; i <= endIndex; i++){ ns[i].viewIndex = i; } }, getStore : function(){ return this.store; }, bindStore : function(store, initial) { if (!initial && this.store) { if (store !== this.store && this.store.autoDestroy) { this.store.destroy(); } else { this.mun(this.store, { scope: this, beforeload: this.onBeforeLoad, datachanged: this.onDataChanged, add: this.onAdd, remove: this.onRemove, update: this.onUpdate, clear: this.refresh }); } if (!store) { if (this.loadMask) { this.loadMask.bindStore(null); } this.store = null; } } if (store) { store = Ext.StoreMgr.lookup(store); this.mon(store, { scope: this, beforeload: this.onBeforeLoad, datachanged: this.onDataChanged, add: this.onAdd, remove: this.onRemove, update: this.onUpdate, clear: this.refresh }); if (this.loadMask) { this.loadMask.bindStore(store); } } this.store = store; this.getSelectionModel().bind(store); if (store) { this.refresh(); } }, onDataChanged: function() { if (this.blockRefresh !== true) { this.refresh.apply(this, arguments); } }, findItemByChild: function(node){ return Ext.fly(node).findParent(this.itemSelector, this.getTargetEl()); }, findTargetByEvent: function(e) { return e.getTarget(this.itemSelector, this.getTargetEl()); }, getSelectedNodes: function(){ var nodes = [], records = this.selModel.getSelection(), ln = records.length, i = 0; for (; i < ln; i++) { nodes.push(this.getNode(records[i])); } return nodes; }, getRecords: function(nodes) { var records = [], i = 0, len = nodes.length; for (; i < len; i++) { records[records.length] = this.store.getAt(nodes[i].viewIndex); } return r; }, getRecord: function(node){ return this.store.getAt(node.viewIndex); }, isSelected : function(node) { var r = this.getRecord(node); return this.selModel.isSelected(r); }, select: function(records, keepExisting, suppressEvent) { this.selModel.select(records, keepExisting, suppressEvent); }, deselect: function(records, suppressEvent) { this.selModel.deselect(records, suppressEvent); }, getNode : function(nodeInfo) { if (Ext.isString(nodeInfo)) { return document.getElementById(nodeInfo); } else if (Ext.isNumber(nodeInfo)) { return this.all.elements[nodeInfo]; } else if (nodeInfo instanceof Ext.data.Model) { var idx = this.store.indexOf(nodeInfo); return this.all.elements[idx]; } return nodeInfo; }, getNodes: function(start, end) { var ns = this.all.elements, nodes = [], i; start = start || 0; end = !Ext.isDefined(end) ? Math.max(ns.length - 1, 0) : end; if (start <= end) { for (i = start; i <= end && ns[i]; i++) { nodes.push(ns[i]); } } else { for (i = start; i >= end && ns[i]; i--) { nodes.push(ns[i]); } } return nodes; }, indexOf: function(node) { node = this.getNode(node); if (Ext.isNumber(node.viewIndex)) { return node.viewIndex; } return this.all.indexOf(node); }, onBeforeLoad: function() { if (this.loadingText) { this.getTargetEl().update(''); this.all.clear(); } }, onDestroy : function() { this.all.clear(); Ext.DataView.superclass.onDestroy.call(this); this.bindStore(null); this.selModel.destroy(); }, onItemSelect: function(record) { var node = this.getNode(record); Ext.fly(node).addCls(this.selectedItemCls); }, onItemDeselect: function(record) { var node = this.getNode(record); Ext.fly(node).removeCls(this.selectedItemCls); }, select: function(records, keepExisting, supressEvents) { console.warn("DataView: select will be removed, please access select through a DataView's SelectionModel, ie: view.getSelectionModel().select()"); var sm = this.getSelectionModel(); return sm.select.apply(sm, arguments); }, clearSelections: function() { console.warn("DataView: clearSelections will be removed, please access deselectAll through DataView's SelectionModel, ie: view.getSelectionModel().deselectAll()"); var sm = this.getSelectionModel(); return sm.deselectAll(); } }); Ext.reg('dataview', Ext.DataView); Ext.DataView.override({ getSelectionCount : function(){ return this.selModel.getSelection().length; }, getSelectedRecords : function(){ return this.selModel.getSelection(); } }); Ext.DataView.override({ scroll: 'vertical', pressedCls : "x-item-pressed", pressedDelay: 100, allowDeselect: true, triggerEvent: 'singletap', triggerCtEvent: 'containertap', addCmpEvents: function() { this.addEvents( 'itemtap', 'itemdoubletap', 'itemswipe', "containertap", "selectionchange", "beforeselect" ); }, afterRender: function() { var me = this; Ext.DataView.superclass.afterRender.call(me); var eventHandlers = { tapstart : me.onTapStart, tapcancel: me.onTapCancel, touchend : me.onTapCancel, doubletap: me.onDoubleTap, swipe : me.onSwipe, scope : me }; eventHandlers[this.triggerEvent] = me.onTap; me.mon(me.getTargetEl(), eventHandlers); if (this.store) { this.bindStore(this.store, true); } }, onTap: function(e) { var item = this.findTargetByEvent(e); if (item) { Ext.fly(item).removeCls(this.pressedCls); var index = this.indexOf(item); if (this.onItemTap(item, index, e) !== false) { this.fireEvent("itemtap", this, index, item, e); } } else { if(this.fireEvent("containertap", this, e) !== false) { this.onContainerTap(e); } } }, onTapStart: function(e, t) { var me = this, item = this.findTargetByEvent(e); if (item) { if (me.pressedDelay) { if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); } me.pressedTimeout = setTimeout(function() { Ext.fly(item).addCls(me.pressedCls); }, Ext.isNumber(me.pressedDelay) ? me.pressedDelay : 100); } else { Ext.fly(item).addCls(me.pressedCls); } } }, onTapCancel: function(e, t) { var me = this, item = this.findTargetByEvent(e); if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); delete me.pressedTimeout; } if (item) { Ext.fly(item).removeCls(me.pressedCls); } }, onContainerTap: function(e) { }, onDoubleTap: function(e) { var item = this.findTargetByEvent(e); if (item) { this.fireEvent("itemdoubletap", this, this.indexOf(item), item, e); } }, onSwipe: function(e) { var item = this.findTargetByEvent(e); if (item) { this.fireEvent("itemswipe", this, this.indexOf(item), item, e); } }, onItemTap: function(item, index, e) { if (this.pressedTimeout) { clearTimeout(this.pressedTimeout); delete this.pressedTimeout; } return true; } }); Ext.List = Ext.extend(Ext.DataView, { componentCls: 'x-list', pinHeaders: Ext.is.iOS || Ext.is.Desktop, indexBar: false, grouped: false, clearSelectionOnDeactivate: true, renderTpl: [ '<tpl if="grouped"><h3 class="x-list-header x-list-header-swap x-hidden-display"></h3></tpl>' ], groupTpl : [ '<tpl for=".">', '<div class="x-list-group x-group-{id}">', '<h3 class="x-list-header">{group}</h3>', '<div class="x-list-group-items">', '{items}', '</div>', '</div>', '</tpl>' ], itemSelector: '.x-list-item', onItemDisclosure: false, preventSelectionOnDisclose: true, initComponent : function() { var memberFnsCombo = {}; if (Ext.isArray(this.itemTpl)) { this.itemTpl = this.itemTpl.join(''); } else if (this.itemTpl && this.itemTpl.html) { Ext.apply(memberFnsCombo, this.itemTpl.initialConfig); this.itemTpl = this.itemTpl.html; } if (!Ext.isDefined(this.itemTpl)) { throw new Error("Ext.List: itemTpl is a required configuration."); } if (this.itemTpl && this.itemTpl.indexOf("\"x-list-item\"") !== -1) { throw new Error("Ext.List: Using a CSS class of x-list-item within your own tpl will break Ext.Lists. Remove the x-list-item from the tpl/itemTpl"); } this.tpl = '<tpl for="."><div class="x-list-item"><div class="x-list-item-body">' + this.itemTpl + '</div>'; if (this.onItemDisclosure) { this.tpl += '<div class="x-list-disclosure"></div>'; } this.tpl += '</div></tpl>'; this.tpl = new Ext.XTemplate(this.tpl, memberFnsCombo); if (this.grouped) { this.listItemTpl = this.tpl; if (Ext.isString(this.listItemTpl) || Ext.isArray(this.listItemTpl)) { this.listItemTpl = new Ext.XTemplate(this.listItemTpl, memberFnsCombo); } if (Ext.isString(this.groupTpl) || Ext.isArray(this.groupTpl)) { this.tpl = new Ext.XTemplate(this.groupTpl); } } else { this.indexBar = false; } if (this.scroll !== false) { this.scroll = { direction: 'vertical', useIndicators: !this.indexBar }; } Ext.List.superclass.initComponent.call(this); if (this.onItemDisclosure) { if (Ext.isFunction(this.onItemDisclosure)) { this.onItemDisclosure = { scope: this, handler: this.onItemDisclosure }; } } this.on('deactivate', this.onDeactivate, this); this.addEvents( 'disclose' ); }, onRender : function() { if (this.grouped) { Ext.applyIf(this.renderData, { grouped: true }); if (this.scroll) { Ext.applyIf(this.renderSelectors, { header: '.x-list-header-swap' }); } } Ext.List.superclass.onRender.apply(this, arguments); }, onDeactivate : function() { if (this.clearSelectionOnDeactivate) { this.getSelectionModel().deselectAll(); } }, afterRender : function() { if (!this.grouped) { this.el.addCls('x-list-flat'); } this.getTargetEl().addCls('x-list-parent'); if (this.indexBar) { this.indexBar = new Ext.IndexBar(Ext.apply({}, Ext.isObject(this.indexBar) ? this.indexBar : {}, { xtype: 'indexbar', alphabet: true, renderTo: this.el })); this.addCls('x-list-indexed'); } Ext.List.superclass.afterRender.call(this); if (this.onItemDisclosure) { this.mon(this.getTargetEl(), 'singletap', this.handleItemDisclosure, this, {delegate: '.x-list-disclosure'}); } }, initEvents : function() { Ext.List.superclass.initEvents.call(this); if (this.grouped) { if (this.pinHeaders && this.scroll) { this.mon(this.scroller, { scrollstart: this.onScrollStart, scroll: this.onScroll, scope: this }); } if (this.indexBar) { this.mon(this.indexBar, { index: this.onIndex, scope: this }); } } }, //@private handleItemDisclosure : function(e, t) { var node = this.findItemByChild(t), record, index; if (node) { record = this.getRecord(node); index = this.indexOf(node); if (this.preventSelectionOnDisclose) { e.stopEvent(); } this.fireEvent('disclose', record, node, index, e); if (Ext.isObject(this.onItemDisclosure) && this.onItemDisclosure.handler) { this.onItemDisclosure.handler.call(this, record, node, index); } } }, setActiveGroup : function(group) { var me = this; if (group) { if (!me.activeGroup || me.activeGroup.header != group.header) { me.header.setHTML(group.header.getHTML()); me.header.show(); } } else { me.header.hide(); } this.activeGroup = group; }, getClosestGroups : function(pos) { if (!this.groupOffsets) { this.updateOffsets(); } var groups = this.groupOffsets, ln = groups.length, group, i, current, next; for (i = 0; i < ln; i++) { group = groups[i]; if (group.offset > pos.y) { next = group; break; } current = group; } return { current: current, next: next }; }, updateIndexes : function() { Ext.List.superclass.updateIndexes.apply(this, arguments); this.updateOffsets(); }, afterComponentLayout : function() { Ext.List.superclass.afterComponentLayout.apply(this, arguments); this.updateOffsets(); }, updateOffsets : function() { if (this.grouped) { this.groupOffsets = []; var headers = this.getTargetEl().query('h3.x-list-header'), ln = headers.length, header, i; for (i = 0; i < ln; i++) { header = Ext.get(headers[i]); header.setDisplayMode(Ext.Element.VISIBILITY); this.groupOffsets.push({ header: header, offset: header.dom.offsetTop }); } } }, onScrollStart : function() { var offset = this.scroller.getOffset(); this.closest = this.getClosestGroups(offset); this.setActiveGroup(this.closest.current); }, onScroll : function(scroller, pos, options) { if (!this.closest) { this.closest = this.getClosestGroups(pos); } if (!this.headerHeight) { this.headerHeight = this.header.getHeight(); } if (pos.y <= 0) { if (this.activeGroup) { this.setActiveGroup(false); this.closest.next = this.closest.current; } return; } else if ( (this.closest.next && pos.y > this.closest.next.offset) || (pos.y < this.closest.current.offset) ) { this.closest = this.getClosestGroups(pos); this.setActiveGroup(this.closest.current); } if (this.closest.next && pos.y > 0 && this.closest.next.offset - pos.y <= this.headerHeight) { var transform = this.headerHeight - (this.closest.next.offset - pos.y); Ext.Element.cssTranslate(this.header, {x: 0, y: -transform}); this.transformed = true; } else if (this.transformed) { this.header.setStyle('-webkit-transform', null); this.transformed = false; } }, onIndex : function(record, target, index) { var key = record.get('key').toLowerCase(), groups = this.store.getGroups(), ln = groups.length, group, i, closest, id; for (i = 0; i < ln; i++) { group = groups[i]; id = this.getGroupId(group); if (id == key || id > key) { closest = id; break; } else { closest = id; } } closest = this.getTargetEl().down('.x-group-' + id); if (closest) { this.scroller.scrollTo({x: 0, y: closest.getOffsetsTo(this.scrollEl)[1]}, false, null, true); } }, getGroupId : function(group) { return group.name.toLowerCase(); }, collectData : function(records, startIndex) { if (!this.grouped) { return Ext.List.superclass.collectData.call(this, records, startIndex); } var results = [], groups = this.store.getGroups(), ln = groups.length, children, cln, c, group, i; for (i = 0, ln = groups.length; i < ln; i++) { group = groups[i]; children = group.children; for (c = 0, cln = children.length; c < cln; c++) { children[c] = children[c].data; } results.push({ group: group.name, id: this.getGroupId(group), items: this.listItemTpl.apply(children) }); } return results; }, onUpdate : function(store, record) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onUpdate.apply(this, arguments); } }, onAdd : function(ds, records, index) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onAdd.apply(this, arguments); } }, onRemove : function(ds, record, index) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onRemove.apply(this, arguments); } } }); Ext.reg('list', Ext.List); Ext.IndexBar = Ext.extend(Ext.DataView, { componentCls: 'x-indexbar', direction: 'vertical', tpl: '<tpl for="."><div class="x-indexbar-item">{value}</div></tpl>', itemSelector: 'div.x-indexbar-item', letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], listPrefix: '', componentLayout: 'autocomponent', scroll: false, initComponent : function() { this.componentLayout = this.getComponentLayout(); if (!this.store) { this.store = new Ext.data.Store({ model: 'IndexBarModel' }); } if (this.alphabet == true) { this.ui = this.ui || 'alphabet'; } if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } this.addEvents( 'index' ); Ext.apply(this.renderData, { componentCls: this.componentCls }); Ext.apply(this.renderSelectors, { body: '.' + this.componentCls + '-body' }); Ext.IndexBar.superclass.initComponent.call(this); }, renderTpl : ['<div class="{componentCls}-body"></div>'], getTargetEl : function() { return this.body; }, afterRender : function() { Ext.IndexBar.superclass.afterRender.call(this); if (this.alphabet === true) { this.loadAlphabet(); } if (this.vertical) { this.el.addCls(this.componentCls + '-vertical'); } else if (this.horizontal) { this.el.addCls(this.componentCls + '-horizontal'); } }, loadAlphabet : function() { var letters = this.letters, len = letters.length, data = [], i, letter; for (i = 0; i < len; i++) { letter = letters[i]; data.push({key: letter.toLowerCase(), value: letter}); } this.store.loadData(data); }, refresh: function() { var el = this.getTargetEl(), records = this.store.getRange(); el.update(''); if (records.length < 1) { if (!this.deferEmptyText || this.hasSkippedEmptyText) { el.update(this.emptyText); } this.all.clear(); } else { this.tpl.overwrite(el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, el.dom)); this.updateIndexes(0); } this.hasSkippedEmptyText = true; this.fireEvent('refresh'); }, collectData : function() { var data = Ext.IndexBar.superclass.collectData.apply(this, arguments); if (this.listPrefix.length > 0) { data.unshift({ key: '', value: this.listPrefix }); } return data; }, initEvents : function() { Ext.IndexBar.superclass.initEvents.call(this); this.mon(this.el, { touchstart: this.onTouchStart, touchend: this.onTouchEnd, touchmove: this.onTouchMove, scope: this }); }, onTouchStart : function(e, t) { e.stopEvent(); this.el.addCls(this.componentCls + '-pressed'); this.pageBox = this.el.getPageBox(); this.onTouchMove(e); }, onTouchEnd : function(e, t) { e.stopEvent(); this.el.removeCls(this.componentCls + '-pressed'); }, onTouchMove : function(e) { e.stopPropagation(); var point = Ext.util.Point.fromEvent(e), target, record, pageBox = this.pageBox; if (!pageBox) { pageBox = this.pageBox = this.el.getPageBox(); } if (this.vertical) { if (point.y > pageBox.bottom || point.y < pageBox.top) { return; } target = Ext.Element.fromPoint(pageBox.left + (pageBox.width / 2), point.y); } else if (this.horizontal) { if (point.x > pageBox.right || point.x < pageBox.left) { return; } target = Ext.Element.fromPoint(point.x, pageBox.top + (pageBox.height / 2)); } if (target) { record = this.getRecord(target.dom); if (record) { this.fireEvent('index', record, target, this.indexOf(target)); } } }, isVertical : function() { return this.vertical; }, isHorizontal : function() { return this.horizontal; } }); Ext.reg('indexbar', Ext.IndexBar); Ext.regModel('IndexBarModel', { fields: ['key', 'value'] }); Ext.Toolbar = Ext.extend(Ext.Container, { isToolbar: true, defaultType: 'button', baseCls: 'x-toolbar', titleCls: 'x-toolbar-title', ui: 'dark', layout: null, titleEl: null, initComponent : function() { this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'center' }); Ext.Toolbar.superclass.initComponent.call(this); }, afterRender : function() { Ext.Toolbar.superclass.afterRender.call(this); if (this.title) { this.titleEl = this.el.createChild({ cls: this.titleCls, html: this.title }); } }, setTitle : function(title) { this.title = title; if (this.rendered) { if (!this.titleEl) { this.titleEl = this.el.createChild({ cls: this.titleCls, html: this.title }); } this.titleEl.setHTML(title); } }, showTitle : function() { if (this.titleEl) { this.titleEl.show(); } }, hideTitle : function() { if (this.titleEl) { this.titleEl.hide(); } } }); Ext.reg('toolbar', Ext.Toolbar); Ext.Spacer = Ext.extend(Ext.Component, { initComponent : function() { if (!this.width) { this.flex = 1; } Ext.Spacer.superclass.initComponent.call(this); }, onRender : function() { Ext.Spacer.superclass.onRender.apply(this, arguments); if (this.flex) { this.el.setStyle('-webkit-box-flex', this.flex); } } }); Ext.reg('spacer', Ext.Spacer); Ext.Sheet = Ext.extend(Ext.Panel, { baseCls : 'x-sheet', centered : false, floating : true, modal : true, draggable : false, monitorOrientation : true, hidden : true, hideOnMaskTap : false, enter : 'bottom', exit : 'bottom', enterAnimation : 'slide', exitAnimation : 'slide', transitions : { bottom : 'up', top : 'down', right : 'left', left : 'right' }, //@private animSheet : function(animate) { var anim = null, me = this, tr = me.transitions, opposites = Ext.Anim.prototype.opposites || {}; if (animate && this[animate]) { if (animate == 'enter') { anim = (typeof me.enterAnimation == 'string') ? { type : me.enterAnimation || 'slide', direction : tr[me.enter] || 'up' } : me.enterAnimation; } else if (animate == 'exit') { anim = (typeof me.exitAnimation == 'string') ? { type : me.exitAnimation || 'slide', direction : tr[me.exit] || 'down' } : me.exitAnimation; } } return anim; }, orient : function(orientation, w, h) { if(!this.container || this.centered || !this.floating){ return this; } var me = this, cfg = me.initialConfig || {}, size = {width : cfg.width, height : cfg.height}, pos = {x : cfg.x, y : cfg.y}, box = me.el.getPageBox(), pageBox, scrollTop = 0; if (me.container.dom == document.body) { pageBox = { width: window.innerWidth, height: window.innerHeight }; scrollTop = document.body.scrollTop; } else { pageBox = me.container.getPageBox(); } pageBox.centerY = pageBox.height / 2; pageBox.centerX = pageBox.width / 2; if(pos.x != undefined || pos.y != undefined){ pos.x = pos.x || 0; pos.y = pos.y || 0; } else { if (/^(bottom|top)/i.test(me.enter)) { size.width = me.stretchX ? pageBox.width : Math.min(200,Math.max(size.width || box.width || pageBox.width, pageBox.width)); size.height = Math.min(size.height || 0, pageBox.height) || undefined; size = me.setSize(size).getSize(); pos.x = pageBox.centerX - size.width / 2; pos.y = me.enter == 'top' ? 0 : pageBox.height - size.height + scrollTop; } else if (/^(left|right)/i.test(me.enter)) { size.height = me.stretchY ? pageBox.height : Math.min(200, Math.max(size.height || box.height || pageBox.height, pageBox.height)); size.width = Math.min(size.width || 0, pageBox.width) || undefined; size = me.setSize(size).getSize(); pos.y = 0; pos.x = me.enter == 'left' ? 0 : pageBox.width - size.width; } } me.setPosition(pos); return this; }, afterRender : function() { Ext.Sheet.superclass.afterRender.apply(this, arguments); this.el.setDisplayMode(Ext.Element.OFFSETS); }, onShow : function(animation) { this.orient(); return Ext.Sheet.superclass.onShow.call(this, animation || this.animSheet('enter')); }, onOrientationChange : function(orientation, w, h) { this.orient(); Ext.Sheet.superclass.onOrientationChange.apply(this, arguments); }, beforeDestroy : function() { delete this.showAnimation; this.hide(false); Ext.Sheet.superclass.beforeDestroy.call(this); } }); Ext.reg('sheet', Ext.Sheet); Ext.ActionSheet = Ext.extend(Ext.Sheet, { componentCls: 'x-sheet-action', stretchY: true, stretchX: true, defaultType: 'button', constructor : function(config) { config = config || {}; Ext.ActionSheet.superclass.constructor.call(this, Ext.applyIf({ floating : true }, config)); } }); Ext.reg('actionsheet', Ext.ActionSheet); Ext.TabBar = Ext.extend(Ext.Panel, { componentCls: 'x-tabbar', activeTab: null, defaultType: 'tab', sortable: false, sortHoldThreshold: 350, initComponent : function() { this.addEvents('change'); this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'middle' }); Ext.TabBar.superclass.initComponent.call(this); }, initEvents : function() { if (this.sortable) { this.sortable = new Ext.util.Sortable(this.el, { itemSelector: '.x-tab', direction: 'horizontal', delay: this.sortHoldThreshold, constrain: true }); this.mon(this.sortable, 'sortchange', this.onSortChange, this); } this.mon(this.el, { touchstart: this.onTouchStart, scope: this }); Ext.TabBar.superclass.initEvents.call(this); }, onTouchStart : function(e, t) { t = e.getTarget('.x-tab'); if (t) { this.onTabTap(Ext.getCmp(t.id)); } }, onSortChange : function(sortable, el, index) { }, onTabTap : function(tab) { if (!tab.disabled) { if (this.cardLayout) { if (this.cardSwitchAnimation) { var animConfig = { reverse: (this.items.indexOf(tab) < this.items.indexOf(this.activeTab)) ? true : false }; if (Ext.isObject(this.cardSwitchAnimation)) { Ext.apply(animConfig, this.cardSwitchAnimation); } else { Ext.apply(animConfig, { type: this.cardSwitchAnimation }); } } this.cardLayout.setActiveItem(tab.card, animConfig || this.cardSwitchAnimation); } this.activeTab = tab; this.fireEvent('change', this, tab, tab.card); } }, getCardLayout : function() { return this.cardLayout; } }); Ext.reg('tabbar', Ext.TabBar); Ext.Tab = Ext.extend(Ext.Button, { isTab: true, baseCls: 'x-tab', pressedCls: 'x-tab-pressed', activeCls: 'x-tab-active', active: false, initComponent : function() { this.addEvents( 'activate', 'deactivate' ); Ext.Tab.superclass.initComponent.call(this); var card = this.card; if (card) { this.card = null; this.setCard(card); } }, setCard : function(card) { if (this.card) { this.mun(this.card, { activate: this.activate, deactivate: this.deactivate, scope: this }); } this.card = card; if (card) { Ext.apply(this, card.tab || {}); this.setText(this.title || card.title || this.text ); this.setIconClass(this.iconCls || card.iconCls); this.setBadge(this.badgeText || card.badgeText); this.mon(card, { beforeactivate: this.activate, beforedeactivate: this.deactivate, scope: this }); } }, onRender: function() { Ext.Tab.superclass.onRender.apply(this, arguments); if (this.active) { this.el.addCls(this.activeCls); } }, getCard : function() { return this.card; }, activate : function() { this.active = true; if (this.el) { this.el.addCls(this.activeCls); } this.fireEvent('activate', this); }, deactivate : function() { this.active = false; if (this.el) { this.el.removeCls(this.activeCls); } this.fireEvent('deactivate', this); } }); Ext.reg('tab', Ext.Tab); Ext.TabPanel = Ext.extend(Ext.Panel, { cardSwitchAnimation: 'slide', tabBarDock: 'top', componentCls: 'x-tabpanel', ui: 'dark', initComponent : function() { var layout = new Ext.layout.CardLayout(this.layout || {}); this.layout = null; this.setLayout(layout); this.tabBar = new Ext.TabBar(Ext.apply({}, this.tabBar || {}, { cardLayout: layout, cardSwitchAnimation: this.cardSwitchAnimation, dock: this.tabBarDock, ui: this.ui, sortable: this.sortable })); if (this.dockedItems && !Ext.isArray(this.dockedItems)) { this.dockedItems = [this.dockedItems]; } else if (!this.dockedItems) { this.dockedItems = []; } this.dockedItems.push(this.tabBar); Ext.TabPanel.superclass.initComponent.call(this); }, getTabBar : function() { return this.tabBar; }, onAdd: function(cmp, idx) { var tabBar = this.tabBar; cmp.tab = tabBar.insert(idx, { xtype: 'tab', card: cmp }); tabBar.doLayout(); }, onRemove: function(cmp, autoDestroy) { this.tabBar.remove(cmp.tab, autoDestroy); this.tabBar.doLayout(); } }); Ext.reg('tabpanel', Ext.TabPanel); Ext.Carousel = Ext.extend(Ext.Panel, { baseCls: 'x-carousel', indicator: true, ui: 'dark', direction: 'horizontal', horizontal: false, vertical: false, initComponent: function() { this.layout = { type: 'card', sizeAllCards: true, hideInactive: false, itemCls: 'x-carousel-item', targetCls: 'x-carousel-body', setOwner : function(owner) { Ext.layout.CardLayout.superclass.setOwner.call(this, owner); } }; if (this.indicator) { var cfg = Ext.isObject(this.indicator) ? this.indicator : {}; this.indicator = new Ext.Carousel.Indicator(Ext.apply({}, cfg, { direction: this.direction, carousel: this, ui: this.ui })); } if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } Ext.Carousel.superclass.initComponent.call(this); }, afterRender: function() { Ext.Carousel.superclass.afterRender.call(this); this.mon(this.body, { drag: this.onDrag, dragThreshold: 5, dragend: this.onDragEnd, direction: this.direction, scope: this }); this.el.addCls(this.baseCls + '-' + this.direction); }, onAdd: function(){ Ext.Carousel.superclass.onAdd.apply(this, arguments); var indicator = this.indicator; if (indicator) { indicator.onCardAdd(); } }, onRemove: function(){ Ext.Carousel.superclass.onRemove.apply(this, arguments); var indicator = this.indicator; if (indicator) { indicator.onCardRemove(); } }, afterLayout : function() { Ext.Carousel.superclass.afterLayout.apply(this, arguments); this.currentSize = this.body.getSize(); this.currentScroll = {x: 0, y: 0}; this.updateCardPositions(); var activeItem = this.layout.getActiveItem(); if (activeItem && this.indicator) { this.indicator.onBeforeCardSwitch(this, activeItem, null, this.items.indexOf(activeItem)); } }, onDrag : function(e) { this.currentScroll = { x: e.deltaX, y: e.deltaY }; var activeIndex = this.items.items.indexOf(this.layout.activeItem); if (this.horizontal) { if ( (activeIndex == 0 && e.deltaX > 0) || (activeIndex == this.items.length - 1 && e.deltaX < 0) ) { this.currentScroll.x = e.deltaX / 2; } } else if (this.vertical) { if ( (activeIndex == 0 && e.deltaY > 0) || (activeIndex == this.items.length - 1 && e.deltaY < 0) ) { this.currentScroll.y = e.deltaY / 2; } } this.updateCardPositions(); }, updateCardPositions : function(animate) { var cards = this.items.items, ln = cards.length, cardOffset, i, card, el, style; for (i = 0; i < ln; i++) { card = cards[i]; if (this.isCardInRange(card)) { if (card.hidden) { card.show(); } el = card.el; style = el.dom.style; if (animate) { if (card === this.layout.activeItem) { el.on('webkitTransitionEnd', this.onTransitionEnd, this, {single: true}); } style.webkitTransitionDuration = '300ms'; } else { style.webkitTransitionDuration = '0ms'; } cardOffset = this.getCardOffset(card); if (this.horizontal) { Ext.Element.cssTransform(el, {translate: [cardOffset, 0]}); } else { Ext.Element.cssTransform(el, {translate: [0, cardOffset]}); } } else if (!card.hidden) { card.hide(); } } }, getCardOffset : function(card) { var cardOffset = this.getCardIndexOffset(card), currentSize = this.currentSize, currentScroll = this.currentScroll; return this.horizontal ? (cardOffset * currentSize.width) + currentScroll.x : (cardOffset * currentSize.height) + currentScroll.y; }, getCardIndexOffset : function(card) { return this.items.items.indexOf(card) - this.getActiveIndex(); }, isCardInRange : function(card) { return Math.abs(this.getCardIndexOffset(card)) <= 2; }, getActiveIndex : function() { return this.items.indexOf(this.layout.activeItem); }, onDragEnd : function(e, t) { var previousDelta, deltaOffset; if (this.horizontal) { deltaOffset = e.deltaX; previousDelta = e.previousDeltaX; } else { deltaOffset = e.deltaY; previousDelta = e.previousDeltaY; } if (deltaOffset < 0 && Math.abs(deltaOffset) > 3 && previousDelta <= 0 && this.layout.getNext()) { this.next(); } else if (deltaOffset > 0 && Math.abs(deltaOffset) > 3 && previousDelta >= 0 && this.layout.getPrev()) { this.prev(); } else { this.scrollToCard(this.layout.activeItem); } }, onBeforeCardSwitch : function(newCard) { if (!this.customDrag && this.items.indexOf(newCard) != -1) { var style = newCard.el.dom.style; style.webkitTransitionDuration = null; style.webkitTransform = null; } return Ext.Carousel.superclass.onBeforeCardSwitch.apply(this, arguments); }, scrollToCard : function(newCard) { this.currentScroll = {x: 0, y: 0}; this.oldCard = this.layout.activeItem; if (newCard != this.oldCard && this.isCardInRange(newCard) && this.onBeforeCardSwitch(newCard, this.oldCard, this.items.indexOf(newCard), true) !== false) { this.layout.activeItem = newCard; if (this.horizontal) { this.currentScroll.x = -this.getCardOffset(newCard); } else { this.currentScroll.y = -this.getCardOffset(newCard); } } this.updateCardPositions(true); }, onTransitionEnd : function(e, t) { this.customDrag = false; this.currentScroll = {x: 0, y: 0}; if (this.oldCard && this.layout.activeItem != this.oldCard) { this.onCardSwitch(this.layout.activeItem, this.oldCard, this.items.indexOf(this.layout.activeItem), true); } delete this.oldCard; }, onCardSwitch : function(newCard, oldCard, index, animated) { this.currentScroll = {x: 0, y: 0}; this.updateCardPositions(); Ext.Carousel.superclass.onCardSwitch.apply(this, arguments); newCard.fireEvent('activate', newCard); }, next: function() { var next = this.layout.getNext(); if (next) { this.customDrag = true; this.scrollToCard(next); } return this; }, prev: function() { var prev = this.layout.getPrev(); if (prev) { this.customDrag = true; this.scrollToCard(prev); } return this; }, isVertical : function() { return this.vertical; }, isHorizontal : function() { return this.horizontal; }, beforeDestroy: function(){ Ext.destroy(this.indicator); Ext.Carousel.superclass.beforeDestroy.call(this); } }); Ext.reg('carousel', Ext.Carousel); Ext.Carousel.Indicator = Ext.extend(Ext.Component, { baseCls: 'x-carousel-indicator', initComponent: function() { if (this.carousel.rendered) { this.render(this.carousel.body); this.onBeforeCardSwitch(null, null, this.carousel.items.indexOf(this.carousel.layout.getActiveItem())); } else { this.carousel.on('render', function() { this.render(this.carousel.body); }, this, {single: true}); } Ext.Carousel.Indicator.superclass.initComponent.call(this); }, onRender: function() { Ext.Carousel.Indicator.superclass.onRender.apply(this, arguments); for (var i = 0, ln = this.carousel.items.length; i < ln; i++) { this.createIndicator(); } this.mon(this.carousel, { beforecardswitch: this.onBeforeCardSwitch, scope: this }); this.mon(this.el, { tap: this.onTap, scope: this }); this.el.addCls(this.baseCls + '-' + this.direction); }, onTap: function(e, t) { var box = this.el.getPageBox(), centerX = box.left + (box.width / 2), centerY = box.top + (box.height / 2), carousel = this.carousel; if ((carousel.isHorizontal() && e.pageX > centerX) || (carousel.isVertical() && e.pageY > centerY)) { this.carousel.next(); } else { this.carousel.prev(); } }, createIndicator: function() { this.indicators = this.indicators || []; this.indicators.push(this.el.createChild({ tag: 'span' })); }, onBeforeCardSwitch: function(carousel, card, old, index) { if (Ext.isNumber(index) && index != -1 && this.indicators[index]) { this.indicators[index].radioCls('x-carousel-indicator-active'); } }, onCardAdd: function() { if (this.rendered) { this.createIndicator(); } }, onCardRemove: function() { if (this.rendered) { this.indicators.pop().remove(); } } }); Ext.reg('carouselindicator', Ext.Carousel.Indicator); Ext.Map = Ext.extend(Ext.Component, { baseCls: 'x-map', useCurrentLocation: false, monitorResize : true, map: null, geo: null, maskMap: false, maskMapCls: 'x-mask-map', initComponent : function() { this.mapOptions = this.mapOptions || {}; this.scroll = false; if(!(window.google || {}).maps){ this.html = 'Google Maps API is required'; } else if (this.useCurrentLocation) { this.geo = this.geo || new Ext.util.GeoLocation({autoLoad: false}); this.geo.on({ locationupdate : this.onGeoUpdate, locationerror : this.onGeoError, scope : this }); } Ext.Map.superclass.initComponent.call(this); this.addEvents ( 'maprender', 'centerchange', 'typechange', 'zoomchange' ); if (this.geo){ this.on({ activate: this.onUpdate, scope: this, single: true }); this.geo.updateLocation(); } }, onRender : function(container, position) { Ext.Map.superclass.onRender.apply(this, arguments); this.el.setDisplayMode(Ext.Element.OFFSETS); }, afterRender : function() { Ext.Map.superclass.afterRender.apply(this, arguments); this.renderMap(); }, onResize : function( w, h) { Ext.Map.superclass.onResize.apply(this, arguments); if (this.map) { google.maps.event.trigger(this.map, 'resize'); } }, afterComponentLayout : function() { if (this.maskMap && !this.mask) { this.el.mask(null, this.maskMapCls); this.mask = true; } }, renderMap : function(){ var me = this, gm = (window.google || {}).maps; if (gm) { if (Ext.is.iPad) { Ext.applyIf(me.mapOptions, { navigationControlOptions: { style: gm.NavigationControlStyle.ZOOM_PAN } }); } Ext.applyIf(me.mapOptions, { center: new gm.LatLng(37.381592, -122.135672), zoom: 12, mapTypeId: gm.MapTypeId.ROADMAP }); if (me.maskMap && !me.mask) { me.el.mask(null, this.maskMapCls); me.mask = true; } if (me.el && me.el.dom && me.el.dom.firstChild) { Ext.fly(me.el.dom.firstChild).remove(); } if (me.map) { gm.event.clearInstanceListeners(me.map); } me.map = new gm.Map(me.el.dom, me.mapOptions); var event = gm.event; event.addListener(me.map, 'zoom_changed', Ext.createDelegate(me.onZoom, me)); event.addListener(me.map, 'maptypeid_changed', Ext.createDelegate(me.onTypeChange, me)); event.addListener(me.map, 'center_changed', Ext.createDelegate(me.onCenterChange, me)); me.fireEvent('maprender', me, me.map); } }, onGeoUpdate : function(coords) { var center; if (coords) { center = this.mapOptions.center = new google.maps.LatLng(coords.latitude, coords.longitude); } if (this.rendered) { this.update(center); } else { this.on('activate', this.onUpdate, this, {single: true, data: center}); } }, onGeoError : function(geo){ }, onUpdate : function(map, e, options) { this.update((options || {}).data); }, update : function(coordinates) { var me = this, gm = (window.google || {}).maps; if (gm) { coordinates = coordinates || me.coords || new gm.LatLng(37.381592, -122.135672); if (coordinates && !(coordinates instanceof gm.LatLng) && 'longitude' in coordinates) { coordinates = new gm.LatLng(coordinates.latitude, coordinates.longitude); } if (!me.hidden && me.rendered) { me.map || me.renderMap(); if (me.map && coordinates instanceof gm.LatLng) { me.map.panTo(coordinates); } } else { me.on('activate', me.onUpdate, me, {single: true, data: coordinates}); } } }, onZoom : function() { this.mapOptions.zoom = (this.map && this.map.getZoom ? this.map.getZoom() : this.mapOptions.zoom) || 10 ; this.fireEvent('zoomchange', this, this.map, this.mapOptions.zoom); }, onTypeChange : function() { this.mapOptions.mapTypeId = this.map && this.map.getMapTypeId ? this.map.getMapTypeId() : this.mapOptions.mapTypeId; this.fireEvent('typechange', this, this.map, this.mapOptions.mapTypeId); }, onCenterChange : function(){ this.mapOptions.center = this.map && this.map.getCenter ? this.map.getCenter() : this.mapOptions.center; this.fireEvent('centerchange', this, this.map, this.mapOptions.center); }, getState : function(){ return this.mapOptions; }, onDestroy : function() { Ext.destroy(this.geo); if (this.maskMap && this.mask) { this.el.unmask(); } if (this.map && (window.google || {}).maps) { google.maps.event.clearInstanceListeners(this.map); } Ext.Map.superclass.onDestroy.call(this); } }); Ext.reg('map', Ext.Map); Ext.NestedList = Ext.extend(Ext.Panel, { componentCls: 'x-nested-list', layout: 'card', cardSwitchAnimation: 'slide', backButton: null, backText: 'Back', useTitleAsBackText: true, updateTitleText: true, displayField: 'text', loadingText: 'Loading...', emptyText: 'No items available.', onItemDisclosure: false, clearSelectionDelay: 200, allowDeselect: false, getItemTextTpl: function(node) { return '{' + this.displayField + '}'; }, getTitleTextTpl: function(node) { return '{' + this.displayField + '}'; }, renderTitleText: function(node) { if (!node.titleTpl) { node.titleTpl = new Ext.XTemplate(this.getTitleTextTpl(node)); } var record = node.getRecord(); if (record) { return node.titleTpl.applyTemplate(record.data); } else if (node.isRoot) { return this.title || this.backText; } else { throw new Error("No RecordNode passed into renderTitleText"); } }, useToolbar: true, getDetailCard: function(recordNode, parentNode) { return false; }, initComponent : function() { var store = Ext.StoreMgr.lookup(this.store), rootNode = store.getRootNode(), title = rootNode.getRecord() ? this.renderTitleText(rootNode) : this.title || ''; this.store = store; if (this.useToolbar) { this.backButton = new Ext.Button({ text: this.backText, ui: 'back', handler: this.onBackTap, scope: this, hidden: true }); if (!this.toolbar || !this.toolbar.isComponent) { this.toolbar = Ext.apply({}, this.toolbar || {}, { dock: 'top', xtype: 'toolbar', ui: 'light', title: title, items: [] }); this.toolbar.items.unshift(this.backButton); this.toolbar = new Ext.Toolbar(this.toolbar); this.dockedItems = this.dockedItems || []; this.dockedItems.push(this.toolbar); } else { this.toolbar.insert(0, this.backButton); } } this.items = [this.getSubList(rootNode)]; Ext.NestedList.superclass.initComponent.call(this); this.on('itemtap', this.onItemTap, this); this.addEvents( 'listchange', 'leafitemtap' ); }, getListConfig: function(node) { var itemId = node.internalId, emptyText = this.emptyText; return { itemId: itemId, xtype: 'list', autoDestroy: true, recordNode: node, store: this.store.getSubStore(node), loadingText: this.loadingText, onItemDisclosure: this.onItemDisclosure, displayField: this.displayField, singleSelect: true, clearSelectionOnDeactivate: false, bubbleEvents: [ 'itemtap', 'containertap', 'beforeselect', 'itemdoubletap', 'selectionchange' ], itemTpl: '<span<tpl if="leaf == true"> class="x-list-item-leaf"</tpl>>' + this.getItemTextTpl(node) + '</span>', deferEmptyText: true, allowDeselect: this.allowDeselect, refresh: function() { if (this.hasSkippedEmptyText) { this.emptyText = emptyText; } Ext.List.prototype.refresh.apply(this, arguments); } }; }, getSubList: function(node) { var items = this.items, list, itemId = node.internalId; if (items && items.get) { list = items.get(itemId); } if (list) { return list; } else { return this.getListConfig(node); } }, addNextCard: function(recordNode, swapTo) { var nextList, parentNode = recordNode ? recordNode.parentNode : null, card; if (recordNode.leaf) { card = this.getDetailCard(recordNode, parentNode); if (card) { nextList = this.add(card); } } else { nextList = this.getSubList(recordNode); nextList = this.add(nextList); } return nextList; }, setActivePath: function(path) { var gotoRoot = path.substr(0, 1) === "/", j = 0, ds = this.store, tree = ds.tree, node, card, lastCard, pathArr, pathLn; if (gotoRoot) { path = path.substr(1); } pathArr = Ext.toArray(path.split('/')); pathLn = pathArr.length; if (gotoRoot) { var items = this.items, itemsArray = this.items.items, i = items.length; for (; i > 1; i--) { this.remove(itemsArray[i - 1], true); } var rootNode = itemsArray[0].recordNode; if (rootNode.id !== pathArr[0]) { throw new Error("rootNode doesn't match!"); } j = 1; } for (; j < pathLn; j++) { if (pathArr[j] !== "") { node = tree.getNodeById(pathArr[j]); card = this.addNextCard(node); if (card) { lastCard = card; } } } if (!lastCard) { throw new Error("Card was not found when trying to add to NestedList."); } this.setActiveItem(lastCard, false); this.fireEvent('listchange', this, lastCard); this.syncToolbar(); }, syncToolbar: function(card) { var list = card || this.getActiveItem(), depth = this.items.indexOf(list), recordNode = list.recordNode, parentNode = recordNode ? recordNode.parentNode : null, backBtn = this.backButton, backBtnText = this.useTitleAsBackText && parentNode ? this.renderTitleText(parentNode) : this.backText, backToggleMth = (depth !== 0) ? 'show' : 'hide'; if (backBtn) { backBtn[backToggleMth](); if (parentNode) { backBtn.setText(backBtnText); } } if (this.toolbar && this.updateTitleText) { this.toolbar.setTitle(recordNode && recordNode.getRecord() ? this.renderTitleText(recordNode) : this.title || ''); this.toolbar.doLayout(); } }, onItemTap: function(subList, subIdx, el, e) { var store = subList.getStore(), record = store.getAt(subIdx), recordNode = record.node, parentNode = recordNode ? recordNode.parentNode : null, displayField = this.displayField, backToggleMth, nextDepth, nextList; nextList = this.addNextCard(recordNode); if (recordNode.leaf) { this.fireEvent("leafitemtap", subList, subIdx, el, e, nextList); } if (nextList) { nextDepth = this.items.indexOf(nextList); this.setActiveItem(nextList, { type: this.cardSwitchAnimation }); this.syncToolbar(nextList); } }, onBackTap: function() { var currList = this.getActiveItem(), currIdx = this.items.indexOf(currList); if (currIdx != 0) { var prevDepth = currIdx - 1, prevList = this.items.getAt(prevDepth), recordNode = prevList.recordNode, record = recordNode.getRecord(), parentNode = recordNode ? recordNode.parentNode : null, backBtn = this.backButton, backToggleMth = (prevDepth !== 0) ? 'show' : 'hide', backBtnText; this.on('cardswitch', function(newCard, oldCard) { var selModel = prevList.getSelectionModel(); this.remove(currList); if (this.clearSelectionDelay) { Ext.defer(selModel.deselectAll, this.clearSelectionDelay, selModel); } }, this, {single: true}); this.setActiveItem(prevList, { type: this.cardSwitchAnimation, reverse: true, scope: this }); this.syncToolbar(prevList); } } }); Ext.reg('nestedlist', Ext.NestedList); Ext.Picker = Ext.extend(Ext.Sheet, { componentCls: 'x-picker', stretchX: true, stretchY: true, hideOnMaskTap: false, doneButton: 'Done', cancelButton: 'Cancel', height: 220, useTitles: false, defaultType: 'pickerslot', initComponent : function() { this.addEvents( 'pick', 'change', 'cancel' ); this.layout = { type: 'hbox', align: 'stretch' }; if (this.slots) { this.items = this.items ? (Ext.isArray(this.items) ? this.items : [this.items]) : []; this.items = this.items.concat(this.slots); } if (this.useTitles) { this.defaults = Ext.applyIf(this.defaults || {}, { title: '' }); } this.on('slotpick', this.onSlotPick, this); if (this.doneButton || this.cancelButton) { var toolbarItems = []; if (this.cancelButton) { toolbarItems.push( Ext.apply( { ui: 'decline', handler: this.onCancelButtonTap, scope: this }, ((Ext.isObject(this.cancelButton) ? this.cancelButton : { text: String(this.cancelButton) })) ) ); } toolbarItems.push({xtype: 'spacer'}); if (this.doneButton) { toolbarItems.push( Ext.apply( { ui: 'action', handler: this.onDoneButtonTap, scope: this }, ((Ext.isObject(this.doneButton) ? this.doneButton : { text: String(this.doneButton) })) ) ); } this.toolbar = new Ext.Toolbar(Ext.applyIf(this.buttonBar || { dock: 'top', items: toolbarItems, defaults: { xtype: 'button' } })); this.dockedItems = this.dockedItems ? (Ext.isArray(this.dockedItems) ? this.dockedItems : [this.dockedItems]) : []; this.dockedItems.push(this.toolbar); } Ext.Picker.superclass.initComponent.call(this); }, afterRender: function() { Ext.Picker.superclass.afterRender.apply(this, arguments); if (this.value) { this.setValue(this.value, false); } }, onDoneButtonTap : function() { var anim = this.animSheet('exit'); Ext.apply(anim, { after: function() { this.fireEvent('change', this, this.getValue()); }, scope: this }); this.hide(anim); }, onCancelButtonTap : function() { var anim = this.animSheet('exit'); Ext.apply(anim, { after: function() { this.setValue(this.values); this.fireEvent('cancel', this); }, scope: this }); this.hide(anim); }, onSlotPick: function(slot, value, node) { this.fireEvent('pick', this, this.getValue(), slot); return false; }, setValue: function(values, animated) { var slot, items = this.items.items, ln = items.length; if (!values) { for (var i = 0; i < ln; i++) { items[i].setSelectedNode(0); } return this; } Ext.iterate(values, function(key, value) { slot = this.child('[name=' + key + ']'); if (slot) { slot.setValue(value, animated); } }, this); this.values = values; return this; }, getValue: function() { var values = {}, items = this.items.items, ln = items.length, item, i; for (i = 0; i < ln; i++) { item = items[i]; values[item.name] = item.getValue(); } return values; } }); Ext.regModel('x-textvalue', { fields: ['text', 'value'] }); Ext.Picker.Slot = Ext.extend(Ext.DataView, { isSlot: true, flex: 1, name: null, displayField: 'text', valueField: 'value', align: 'center', itemSelector: 'div.x-picker-item', componentCls: 'x-picker-slot', renderTpl : [ '<div class="x-picker-mask">', '<div class="x-picker-bar"></div>', '</div>' ], selectedIndex: 0, getElConfig: function() { return { tag: 'div', id: this.id, cls: 'x-picker-' + this.align }; }, initComponent : function() { if (!this.name) { throw new Error('Each picker slot is required to have a name.'); } Ext.apply(this.renderSelectors, { mask: '.x-picker-mask', bar: '.x-picker-bar' }); this.scroll = { direction: 'vertical', useIndicators: false, friction: 0.7, acceleration: 25, snapDuration: 200, animationDuration: 200 }; this.tpl = new Ext.XTemplate([ '<tpl for=".">', '<div class="x-picker-item {cls} <tpl if="extra">x-picker-invalid</tpl>">{' + this.displayField + '}</div>', '</tpl>' ]); var data = this.data, parsedData = [], ln = data && data.length, i, item, obj; if (data && Ext.isArray(data) && ln) { for (i = 0; i < ln; i++) { item = data[i]; obj = {}; if (Ext.isArray(item)) { obj[this.valueField] = item[0]; obj[this.displayField] = item[1]; } else if (Ext.isString(item)) { obj[this.valueField] = item; obj[this.displayField] = item; } else if (Ext.isObject(item)) { obj = item; } parsedData.push(obj); } this.store = new Ext.data.Store({ model: 'x-textvalue', data: parsedData }); this.tempStore = true; } else if (this.store) { this.store = Ext.StoreMgr.lookup(this.store); } this.enableBubble('slotpick'); if (this.title) { this.title = new Ext.Component({ dock: 'top', componentCls: 'x-picker-slot-title', html: this.title }); this.dockedItems = this.title; } Ext.Picker.Slot.superclass.initComponent.call(this); if (this.value !== undefined) { this.setValue(this.value, false); } }, setupBar: function() { this.el.setStyle({padding: ''}); var padding = this.bar.getY() - this.el.getY(); this.barHeight = this.bar.getHeight(); this.el.setStyle({ padding: padding + 'px 0' }); this.slotPadding = padding; this.scroller.updateBoundary(); this.scroller.setSnap(this.barHeight); this.setSelectedNode(this.selectedIndex, false); }, afterComponentLayout: function() { Ext.defer(this.setupBar, 200, this); }, initEvents: function() { this.mon(this.scroller, { scrollend: this.onScrollEnd, scope: this }); }, onScrollEnd: function(scroller, offset) { this.selectedNode = this.getNode(Math.round(offset.y / this.barHeight)); this.selectedIndex = this.indexOf(this.selectedNode); this.fireEvent('slotpick', this, this.getValue(), this.selectedNode); }, scrollToNode: function(node, animate) { var offsetsToBody = Ext.fly(node).getOffsetsTo(this.scrollEl)[1]; this.scroller.scrollTo({ y: offsetsToBody }, animate !== false ? true : false); }, onItemTap: function(node) { Ext.Picker.Slot.superclass.onItemTap.apply(this, arguments); this.setSelectedNode(node); }, getSelectedNode: function() { return this.selectedNode; }, setSelectedNode: function(selected, animate) { if (Ext.isNumber(selected)) { selected = this.getNode(selected); } else if (selected.isModel) { selected = this.getNode(this.store.indexOf(selected)); } if (selected) { this.selectedNode = selected; this.selectedIndex = this.indexOf(selected); this.scrollToNode(selected, animate); } }, getValue: function() { var record = this.store.getAt(this.selectedIndex); return record ? record.get(this.valueField) : null; }, setValue: function(value, animate) { var index = this.store.find(this.valueField, value); if (index != -1) { if (!this.rendered) { this.selectedIndex = index; return; } this.setSelectedNode(index, animate); } }, onDestroy: function() { if (this.tempStore) { this.store.destroyStore(); this.store = null; } Ext.Picker.Slot.superclass.onDestroy.call(this); } }); Ext.reg('pickerslot', Ext.Picker.Slot); Ext.DatePicker = Ext.extend(Ext.Picker, { yearFrom: 1980, yearTo: new Date().getFullYear(), monthText: 'Month', dayText: 'Day', yearText: 'Year', slotOrder: ['month', 'day', 'year'], initComponent: function() { var yearsFrom = this.yearFrom, yearsTo = this.yearTo, years = [], days = [], months = [], ln, tmp, i, daysInMonth; if (yearsFrom > yearsTo) { tmp = yearsFrom; yearsFrom = yearsTo; yearsTo = tmp; } for (i = yearsFrom; i <= yearsTo; i++) { years.push({ text: i, value: i }); } daysInMonth = this.getDaysInMonth(1, new Date().getFullYear()); for (i = 0; i < daysInMonth; i++) { days.push({ text: i + 1, value: i + 1 }); } for (i = 0, ln = Date.monthNames.length; i < ln; i++) { months.push({ text: Date.monthNames[i], value: i + 1 }); } this.slots = []; this.slotOrder.forEach(function(item){ this.slots.push(this.createSlot(item, days, months, years)); }, this); Ext.DatePicker.superclass.initComponent.call(this); }, afterRender: function() { Ext.DatePicker.superclass.afterRender.apply(this, arguments); this.setValue(this.value); }, createSlot: function(name, days, months, years){ switch (name) { case 'year': return { name: 'year', align: 'center', data: years, title: this.useTitles ? this.yearText : false, flex: 3 }; case 'month': return { name: name, align: 'right', data: months, title: this.useTitles ? this.monthText : false, flex: 4 }; case 'day': return { name: 'day', align: 'center', data: days, title: this.useTitles ? this.dayText : false, flex: 2 }; } }, onSlotPick: function(slot, value) { var name = slot.name, date, daysInMonth, daySlot; if (name === "month" || name === "year") { daySlot = this.child('[name=day]'); date = this.getValue(); daysInMonth = this.getDaysInMonth(date.getMonth()+1, date.getFullYear()); daySlot.store.clearFilter(); daySlot.store.filter({ fn: function(r) { return r.get('extra') === true || r.get('value') <= daysInMonth; } }); daySlot.scroller.updateBoundary(true); } Ext.DatePicker.superclass.onSlotPick.apply(this, arguments); }, getValue: function() { var value = Ext.DatePicker.superclass.getValue.call(this), daysInMonth = this.getDaysInMonth(value.month, value.year), day = Math.min(value.day, daysInMonth); return new Date(value.year, value.month-1, day); }, setValue: function(value, animated) { if (!Ext.isDate(value) && !Ext.isObject(value)) { value = null; } if (Ext.isDate(value)) { this.value = { day : value.getDate(), year: value.getFullYear(), month: value.getMonth() + 1 }; } else { this.value = value; } return Ext.DatePicker.superclass.setValue.call(this, this.value, animated); }, getDaysInMonth: function(month, year) { var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return month == 2 && this.isLeapYear(year) ? 29 : daysInMonth[month-1]; }, isLeapYear: function(year) { return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year))); } }); Ext.reg('datepicker', Ext.DatePicker); Ext.Media = Ext.extend(Ext.Component, { url: '', enableControls: true, autoResume: false, autoPause: true, preload: true, playing: false, afterRender : function() { var cfg = this.getConfiguration(); Ext.apply(cfg, { src: this.url, preload: this.preload ? 'auto' : 'none' }); if(this.enableControls){ cfg.controls = 'controls'; } if(this.loop){ cfg.loop = 'loop'; } this.media = this.el.createChild(cfg); Ext.Media.superclass.afterRender.call(this); this.on({ scope: this, activate: this.onActivate, beforedeactivate: this.onDeactivate }); }, onActivate: function(){ if (this.autoResume && !this.playing) { this.play(); } }, onDeactivate: function(){ if (this.autoPause && this.playing) { this.pause(); } }, play : function() { this.media.dom.play(); this.playing = true; }, pause : function() { this.media.dom.pause(); this.playing = false; }, toggle : function() { if(this.playing){ this.pause(); } else { this.play(); } } }); Ext.reg('media', Ext.Media); Ext.Video = Ext.extend(Ext.Media, { posterUrl: '', componentCls: 'x-video', afterRender : function() { Ext.Video.superclass.afterRender.call(this); if (this.posterUrl) { this.media.hide(); this.ghost = this.el.createChild({ cls: 'x-video-ghost', style: 'width: 100%; height: 100%; background: #000 url(' + this.posterUrl + ') center center no-repeat; -webkit-background-size: 100% auto;' }); this.ghost.on('tap', this.onGhostTap, this, {single: true}); } }, onGhostTap: function(){ this.media.show(); this.ghost.hide(); this.play(); }, getConfiguration: function(){ return { tag: 'video', width: '100%', height: '100%' }; } }); Ext.reg('video', Ext.Video); Ext.Audio = Ext.extend(Ext.Media, { componentCls: 'x-audio', onActivate: function(){ Ext.Audio.superclass.onActivate.call(this); if (Ext.is.Phone) { this.media.show(); } }, onDeactivate: function(){ Ext.Audio.superclass.onDeactivate.call(this); if (Ext.is.Phone) { this.media.hide(); } }, getConfiguration: function(){ var hidden = !this.enableControls; if (!Ext.supports.AudioTag) { return { tag: 'embed', type: 'audio/mpeg', target: 'myself', controls: 'true', hidden: hidden }; } else { return { tag: 'audio', hidden: hidden }; } } }); Ext.reg('audio', Ext.Audio); Ext.MessageBox = Ext.extend(Ext.Sheet, { centered: true, renderHidden: true, ui: 'dark', componentCls: 'x-msgbox', enterAnimation: 'pop', exitAnimation: 'pop', defaultTextHeight : 75, constructor : function(config) { config = config || {}; var ui = config.ui || this.ui || '', baseCls = config.componentCls || this.componentCls; delete config.html; this.titleBar = Ext.create({ xtype : 'toolbar', ui : ui, dock : 'top', cls : baseCls + '-title', title : '&#160;' }); this.buttonBar = Ext.create({ xtype : 'toolbar', ui : ui, dock : 'bottom', layout: { pack: 'center' }, cls : baseCls + '-buttons' }); config = Ext.apply({ ui : ui, dockedItems : [this.titleBar, this.buttonBar], renderSelectors : { body : '.' + baseCls + '-body', iconEl : '.' + baseCls + '-icon', msgContentEl : '.' + baseCls + '-content', msgEl : '.' + baseCls + '-text', inputsEl : '.' + baseCls + '-inputs', inputEl : '.' + baseCls + '-input-single', multiLineEl : '.' + baseCls + '-input-textarea' } }, config || {}); Ext.MessageBox.superclass.constructor.call(this, config); }, renderTpl: [ '<div class="{componentCls}-body"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>>', '<div class="{componentCls}-icon x-hidden-display"></div>', '<div class="{componentCls}-content">', '<div class="{componentCls}-text"></div>', '<div class="{componentCls}-inputs x-hidden-display">', '<input type="text" class="{componentCls}-input {componentCls}-input-single" />', '<textarea class="{componentCls}-input {componentCls}-input-textarea"></textarea>', '</div>', '</div>', '</div>' ], onClick : function(button) { if (button) { var config = button.config || {}; if (typeof config.fn == 'function') { config.fn.call( config.scope || null, button.itemId || button.text, config.input ? config.input.dom.value : null, config ); } if (config.cls) { this.el.removeCls(config.cls); } if (config.input) { config.input.dom.blur(); } } this.hide(); }, show : function(config) { var attrib, attrName, attribs = { autocomplete : 'off', autocapitalize : 'off', autocorrect : 'off', maxlength : 0, autofocus : true, placeholder : '', type : 'text' }, assert = /true|on/i; this.rendered || this.render(document.body); config = Ext.applyIf( config || {}, { multiLine : false, prompt : false, value : '', modal : true } ); if (config.title) { this.titleBar.setTitle(config.title); this.titleBar.show(); } else { this.titleBar.hide(); } if (this.inputsEl && (config.multiLine || config.prompt)) { this.inputsEl.show(); if (this.multiLineEl && config.multiLine) { this.inputEl && this.inputEl.hide(); this.multiLineEl.show().setHeight(Ext.isNumber(config.multiLine) ? parseFloat(config.multiLine) : this.defaultTextHeight); config.input = this.multiLineEl; } else if (this.inputEl) { this.inputEl.show(); this.multiLineEl && this.multiLineEl.hide(); config.input = this.inputEl; } if (Ext.isObject(config.prompt)) { Ext.apply(attribs, config.prompt); } for (attrName in attribs) { if (attribs.hasOwnProperty(attrName)) { attrib = attribs[attrName]; config.input.dom.setAttribute( attrName.toLowerCase(), /^auto/i.test(attrName) ? (assert.test(attrib+'') ? 'on' : 'off' ) : attrib ); } } } else { this.inputsEl && this.inputsEl.hide(); } this.setIcon(config.icon || '', false); this.updateText(config.msg, false); if (config.cls) { this.el.addCls(config.cls); } this.modal = !!config.modal; var bbar = this.buttonBar, bs = []; bbar.removeAll(); Ext.each([].concat(config.buttons || Ext.MessageBox.OK), function(button) { if (button) { bs.push( Ext.applyIf({ config : config, scope : this, handler : this.onClick }, button) ); } }, this); bbar.add(bs); if (bbar.rendered) { bbar.doLayout(); } Ext.MessageBox.superclass.show.call(this, config.animate); if (config.input) { config.input.dom.value = config.value || ''; if (assert.test(attribs.autofocus+'') && !('autofocus' in config.input.dom)) { config.input.dom.focus(); } } return this; }, onOrientationChange : function() { this.doComponentLayout(); Ext.MessageBox.superclass.onOrientationChange.apply(this, arguments); }, adjustScale : function(){ Ext.apply(this,{ maxWidth : window.innerWidth, maxHeight : window.innerHeight, minWidth : window.innerWidth * .5, minHeight : window.innerHeight * .5 }); }, doComponentLayout : function() { this.adjustScale(); return Ext.MessageBox.superclass.doComponentLayout.apply(this, arguments); }, alert : function(title, msg, fn, scope) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.OK, fn : fn, scope : scope, icon : Ext.MessageBox.INFO }); }, confirm : function(title, msg, fn, scope) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.YESNO, fn: function(button) { fn.call(scope, button); }, scope : scope, icon: Ext.MessageBox.QUESTION }); }, prompt : function(title, msg, fn, scope, multiLine, value, promptConfig) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.OKCANCEL, fn: function(button, inputValue) { fn.call(scope, button, inputValue); }, scope : scope, icon : Ext.MessageBox.QUESTION, prompt: promptConfig || true, multiLine: multiLine, value: value }); }, updateText : function(text, doLayout) { if(this.msgEl) { this.msgEl.update(text ? String(text) : '&#160;'); if(doLayout !== false) { this.doComponentLayout(); } } return this; }, setIcon : function(icon, doLayout) { if (icon) { this.iconEl.show(); this.iconEl.replaceCls(this.iconCls, icon); } else { this.iconEl.replaceCls(this.iconCls, 'x-hidden-display'); } if (doLayout !== false) { this.doComponentLayout(); } this.iconCls = icon; return this; } }); (function(){ var B = Ext.MessageBox; Ext.apply(B, { OK : {text : 'OK', itemId : 'ok', ui : 'action' }, CANCEL : {text : 'Cancel', itemId : 'cancel'}, YES : {text : 'Yes', itemId : 'yes', ui : 'action' }, NO : {text : 'No', itemId : 'no'}, INFO : 'x-msgbox-info', WARNING : 'x-msgbox-warning', QUESTION : 'x-msgbox-question', ERROR : 'x-msgbox-error' }); Ext.apply(B, { OKCANCEL : [B.CANCEL, B.OK], YESNOCANCEL : [B.CANCEL, B.NO, B.YES], YESNO : [B.NO, B.YES] }); })(); Ext.reg('messagebox', Ext.MessageBox); Ext.reg('msgbox', Ext.MessageBox); Ext.Msg = new Ext.MessageBox(); Ext.form.FormPanel = Ext.extend(Ext.Panel, { standardSubmit: false, componentCls: 'x-form', url: undefined, baseParams : undefined, waitTpl: new Ext.XTemplate( '<div class="{cls}">{message}&hellip;</div>' ), submitOnAction : true, getElConfig: function() { return Ext.apply(Ext.form.FormPanel.superclass.getElConfig.call(this), { tag: 'form' }); }, initComponent : function() { this.addEvents( 'submit', 'beforesubmit', 'exception' ); Ext.form.FormPanel.superclass.initComponent.call(this); this.on('action', this.onFieldAction, this); }, afterRender : function() { Ext.form.FormPanel.superclass.afterRender.call(this); this.el.on('submit', this.onSubmit, this); }, onSubmit : function(e, t) { if (!this.standardSubmit || this.fireEvent('beforesubmit', this, this.getValues(true)) === false) { if (e) { e.stopEvent(); } } }, onFieldAction : function(field) { if (this.submitOnAction) { field.blur(); this.submit(); } }, submit: function(options) { var form = this.el.dom || {}, formValues options = Ext.apply({ url : this.url || form.action, submitDisabled : false, method : form.method || 'post', autoAbort : false, params : null, waitMsg : null, headers : null, success : null, failure : null }, options || {}); formValues = this.getValues(this.standardSubmit || !options.submitDisabled); if (this.standardSubmit) { if (form) { if (options.url && Ext.isEmpty(form.action)) { form.action = options.url; } form.method = (options.method || form.method).toLowerCase(); if (this.fireEvent('beforesubmit', this, formValues, options) !== false) { form.submit(); } } return null; } if (this.fireEvent('beforesubmit', this, formValues, options ) !== false) { if (options.waitMsg) { this.showMask(options.waitMsg); } return Ext.Ajax.request({ url : options.url, method : options.method, rawData : Ext.urlEncode(Ext.apply( Ext.apply({}, this.baseParams || {}), options.params || {}, formValues )), autoAbort : options.autoAbort, headers : Ext.apply( {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, options.headers || {}), scope : this, callback : function(callbackOptions, success, response) { var responseText = response.responseText; this.hideMask(); if (success) { response = Ext.decode(responseText); success = !!response.success; if (success) { if (Ext.isFunction(options.success)) { options.success.call(options.scope || this, this, response, responseText); } this.fireEvent('submit', this, response); return; } } if (Ext.isFunction(options.failure)) { options.failure.call(options.scope || this, this, response, responseText); } this.fireEvent('exception', this, response); } }); } }, loadRecord: function(instance) { if (instance && instance.data) { this.setValues(instance.data); this.record = instance; } return this; }, loadModel: function() { return this.loadRecord.apply(this, arguments); }, getRecord: function() { return this.record; }, updateRecord: function(instance, enabled) { var fields, values, name; if(instance && (fields = instance.fields)){ values = this.getValues(enabled); for (name in values) { if(values.hasOwnProperty(name) && fields.containsKey(name)){ instance.set(name, values[name]); } } } return this; }, setValues: function(values) { var fields = this.getFields(), name, field, value; values = values || {}; for (name in values) { if (values.hasOwnProperty(name)) { field = fields[name]; value = values[name]; if (field) { if (Ext.isArray(field)) { field.forEach(function(field){ if (Ext.isArray(values[name])) { field.setChecked((value.indexOf(field.getValue()) != -1)); } else { field.setChecked((value == field.getValue())); } }); } else { if (field.setChecked) { field.setChecked(value); } else { field.setValue(value); } } } } } return this; }, getValues: function(enabled) { var fields = this.getFields(), field, values = {}, name; for (name in fields) { if (fields.hasOwnProperty(name)) { if (Ext.isArray(fields[name])) { values[name] = []; fields[name].forEach(function(field) { if (field.isChecked() && !(enabled && field.disabled)) { if (field instanceof Ext.form.Radio) { values[name] = field.getValue(); } else { values[name].push(field.getValue()); } } }); } else { field = fields[name]; if (!(enabled && field.disabled)) { if (field instanceof Ext.form.Checkbox) { values[name] = (field.isChecked()) ? field.getValue() : null; } else { values[name] = field.getValue(); } } } } } return values; }, reset: function() { this.getFieldsAsArray().forEach(function(field) { field.reset(); }); return this; }, enable: function() { this.getFieldsAsArray().forEach(function(field) { field.enable(); }); return this; }, disable: function() { this.getFieldsAsArray().forEach(function(field) { field.disable(); }); return this; }, getFieldsAsArray: function() { var fields = []; var getFieldsFrom = function(item) { if (item.isField) { fields.push(item); } if (item.isContainer) { item.items.each(getFieldsFrom); } }; this.items.each(getFieldsFrom); return fields; }, getFields: function(byName) { var fields = {}, itemName; var getFieldsFrom = function(item) { if (item.isField) { itemName = item.getName(); if ((byName && itemName == byName) || typeof byName == 'undefined') { if (fields.hasOwnProperty(itemName)) { if (!Ext.isArray(fields[itemName])) { fields[itemName] = [fields[itemName]]; } fields[itemName].push(item); } else { fields[itemName] = item; } } } if (item.isContainer) { item.items.each(getFieldsFrom); } }; this.items.each(getFieldsFrom); return (byName) ? (fields[byName] || []) : fields; }, getFieldsFromItem: function() { }, showMask : function(cfg, target) { cfg = Ext.isString(cfg) ? {message : cfg} : cfg; if (cfg && this.waitTpl) { this.maskTarget = target = Ext.get(target || cfg.target) || this.el; target && target.mask(this.waitTpl.apply(cfg)); } return this; }, hideMask : function(){ if(this.maskTarget){ this.maskTarget.unmask(); delete this.maskTarget; } return this; } }); Ext.form.FormPanel.prototype.load = Ext.form.FormPanel.prototype.loadModel; Ext.reg('formpanel', Ext.form.FormPanel); Ext.reg('form', Ext.form.FormPanel); Ext.form.FieldSet = Ext.extend(Ext.Panel, { componentCls: 'x-form-fieldset', initComponent : function() { this.componentLayout = this.getLayout(); Ext.form.FieldSet.superclass.initComponent.call(this); }, afterLayout : function(layout) { Ext.form.FieldSet.superclass.afterLayout.call(this, layout); if (this.title && !this.titleEl) { this.setTitle(this.title); } else if (this.titleEl) { this.el.insertFirst(this.titleEl); } if (this.instructions && !this.instructionsEl) { this.setInstructions(this.instructions); } else if (this.instructionsEl) { this.el.appendChild(this.instructionsEl); } }, setTitle: function(title){ if (this.rendered) { if (!this.titleEl) { this.titleEl = this.el.insertFirst({ cls: this.componentCls + '-title' }); } this.titleEl.setHTML(title); } else { this.title = title; } return this; }, setInstructions: function(instructions){ if (this.rendered) { if (!this.instructionsEl) { this.instructionsEl = this.el.createChild({ cls: this.componentCls + '-instructions' }); } this.instructionsEl.setHTML(instructions); } else { this.instructions = instructions; } return this; } }); Ext.reg('fieldset', Ext.form.FieldSet); Ext.form.Field = Ext.extend(Ext.Component, { isField: true, fieldCls: 'x-form-field', baseCls: 'x-field', inputCls: undefined, disabled: false, renderTpl: [ '<tpl if="label">', '<div class="x-form-label"><span>{label}</span></div>', '</tpl>', '<tpl if="fieldEl">', '<div class="x-form-field-container"><input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="maxlength">maxlength="{maxlength}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoCorrect">autocorrect="{autoCorrect}" </tpl> />', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div>', '<tpl if="useClearIcon"><div class="x-field-clear-container"><div class="x-field-clear x-hidden-visibility">&#215;</div></div></tpl>', '</tpl>' ], isFormField: true, autoCreateField: true, inputType: 'text', label: null, labelWidth: '30%', labelAlign: 'left', required: false, useMask: false, initComponent: function() { Ext.form.Field.superclass.initComponent.call(this); }, getName: function() { return this.name || this.id || ''; }, applyRenderSelectors: function() { this.renderSelectors = Ext.applyIf(this.renderSelectors || {}, { mask: '.x-field-mask', labelEl: '.x-form-label', fieldEl: '.' + Ext.util.Format.trim(this.renderData.fieldCls).replace(/ /g, '.') }); Ext.form.Field.superclass.applyRenderSelectors.call(this); }, initRenderData: function() { Ext.form.Field.superclass.initRenderData.apply(this, arguments); Ext.applyIf(this.renderData, { disabled : this.disabled, fieldCls : 'x-input-' + this.inputType + (this.inputCls ? ' ' + this.inputCls: ''), fieldEl : !this.fieldEl && this.autoCreateField, inputId : Ext.id(), label : this.label, labelAlign : 'x-label-align-' + this.labelAlign, name : this.getName(), required : this.required, style : this.style, tabIndex : this.tabIndex, inputType : this.inputType, useMask : this.useMask }); return this.renderData; }, initEvents: function() { Ext.form.Field.superclass.initEvents.apply(this, arguments); if (this.fieldEl) { if (this.useMask && this.mask) { this.mon(this.mask, { tap: this.onMaskTap, scope: this }); } } }, onRender: function() { Ext.form.Field.superclass.onRender.apply(this, arguments); var cls = []; if (this.required) { cls.push('x-field-required'); } if (this.label) { cls.push('x-label-align-' + this.labelAlign); } this.el.addCls(cls); }, afterRender: function() { Ext.form.Field.superclass.afterRender.apply(this, arguments); if (this.label) { this.setLabelWidth(this.labelWidth); } this.initValue(); }, isDisabled: function() { return this.disabled; }, onEnable: function() { this.fieldEl.dom.disabled = false; }, onDisable: function() { this.fieldEl.dom.disabled = true; }, initValue: function() { this.setValue(this.value || '', true); this.originalValue = this.getValue(); }, isDirty: function() { if (this.disabled || !this.rendered) { return false; } return String(this.getValue()) !== String(this.originalValue); }, onMaskTap: function(e) { if (this.disabled) { return false; } if (Ext.is.iOS && e.browserEvent && !e.browserEvent.isSimulated && !e.browserEvent.isSimulated) { console.log('onMaskTap prevented'); e.preventDefault(); e.stopPropagation(); return false; } return true; }, showMask: function(e) { if (this.mask) { this.mask.setStyle('display', 'block'); } }, hideMask: function(e) { if (this.mask) { this.mask.setStyle('display', 'none'); } }, reset: function() { this.setValue(this.originalValue); }, getValue: function(){ if (!this.rendered || !this.fieldEl) { return this.value; } return this.fieldEl.getValue(); }, setValue: function(value){ this.value = value; if (this.rendered && this.fieldEl) { this.fieldEl.dom.value = (Ext.isEmpty(value) ? '' : value); } return this; }, setLabelWidth: function(width) { if (this.labelEl) { this.labelEl.setWidth(width); } return this; } }); Ext.reg('field', Ext.form.Field); Ext.form.Slider = Ext.extend(Ext.form.Field, { ui: 'slider', inputCls: 'x-slider', inputType: 'slider', minValue: 0, maxValue: 100, animationDuration: 200, value: 0, trackWidth: null, monitorOrientation: true, renderTpl: [ '<tpl if="label">', '<div class="x-form-label"><span>{label}</span></div>', '</tpl>', '<tpl if="fieldEl">', '<div id="{inputId}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}"</tpl>', '<tpl if="style">style="{style}" </tpl>', '/></tpl>' ], increment: 1, constructor: function(config) { this.addEvents( 'beforechange', 'change', 'drag', 'dragend' ); Ext.form.Slider.superclass.constructor.call(this, config); }, initComponent: function() { this.tabIndex = -1; if (this.increment == 0) { this.increment = 1; } this.increment = Math.abs(this.increment); this.values = [this.value]; Ext.form.Slider.superclass.initComponent.apply(this, arguments); if (this.thumbs == undefined) { var thumbs = [], values = this.values, length = values.length, i, Thumb = this.getThumbClass(); for (i = 0; i < length; i++) { thumbs[thumbs.length] = new Thumb({ value: values[i], slider: this, listeners: { scope : this, drag : this.onDrag, dragend: this.onThumbDragEnd } }); } this.thumbs = thumbs; } }, initValue: function() { var thumb = this.getThumb(); if (thumb.dragObj) { thumb.dragObj.updateBoundary(); } Ext.form.Slider.superclass.initValue.apply(this, arguments); }, onOrientationChange: function() { Ext.form.Slider.superclass.onOrientationChange.apply(this, arguments); var thumb = this.getThumb(); if (thumb.dragObj) { thumb.dragObj.updateBoundary(); this.moveThumb(thumb, this.getPixelValue(thumb.getValue(), thumb), 0); } }, getThumbClass: function() { return Ext.form.Slider.Thumb; }, setValue: function(value, animationDuration, moveThumb) { if (typeof moveThumb == 'undefined') { moveThumb = true; } moveThumb = !!moveThumb; var thumb = this.getThumb(), oldValue = thumb.getValue(), newValue = this.constrain(value); if (this.fireEvent('beforechange', this, thumb, newValue, oldValue) !== false) { if (moveThumb) { this.moveThumb(thumb, this.getPixelValue(newValue, thumb), animationDuration); } thumb.setValue(newValue); this.doComponentLayout(); this.fireEvent('change', this, thumb, newValue, oldValue); } return this; }, constrain: function(value) { var remainder = value % this.increment; value -= remainder; if (Math.abs(remainder) >= (this.increment / 2)) { value += (remainder > 0) ? this.increment : -this.increment; } value = Math.max(this.minValue, value); value = Math.min(this.maxValue, value); return value; }, getValue: function() { return this.getThumb().getValue(); }, getThumb: function() { return this.thumbs[0]; }, getSliderValue: function(pixelValue, thumb) { var trackWidth = thumb.dragObj.offsetBoundary.right, range = this.maxValue - this.minValue, ratio; this.trackWidth = (trackWidth > 0) ? trackWidth : this.trackWidth; ratio = range / this.trackWidth; return this.minValue + (ratio * (pixelValue)); }, getPixelValue: function(value, thumb) { var trackWidth = thumb.dragObj.offsetBoundary.right, range = this.maxValue - this.minValue, ratio; this.trackWidth = (trackWidth > 0) ? trackWidth : this.trackWidth; ratio = this.trackWidth / range; return (ratio * (value - this.minValue)); }, renderThumbs: function() { var thumbs = this.thumbs, length = thumbs.length, i; for (i = 0; i < length; i++) { thumbs[i].render(this.fieldEl); } }, onThumbDragEnd: function(draggable) { var value = this.getThumbValue(draggable); this.setValue(value); this.fireEvent('dragend', this, draggable.thumb, this.constrain(value)); }, getThumbValue: function(draggable) { var thumb = draggable.thumb; return this.getSliderValue(-draggable.getOffset().x, thumb); }, onDrag: function(draggable){ var value = this.getThumbValue(draggable); this.fireEvent('drag', this, draggable.thumb, this.constrain(value)); }, onTap: function(e) { if (!this.disabled) { var sliderBox = this.fieldEl.getPageBox(), leftOffset = e.pageX - sliderBox.left, thumb = this.getNearest(leftOffset), halfThumbWidth = thumb.dragObj.size.width / 2; this.setValue(this.getSliderValue(leftOffset - halfThumbWidth, thumb), this.animationDuration, true); } }, moveThumb: function(thumb, pixel, animationDuration) { thumb.dragObj.setOffset(new Ext.util.Offset(pixel, 0), animationDuration); }, afterRender: function(ct) { var me = this; me.renderThumbs(); Ext.form.Slider.superclass.afterRender.apply(me, arguments); me.fieldEl.on({ scope: me, tap : me.onTap }); }, getNearest: function(value) { return this.thumbs[0]; }, setThumbsDisabled: function(disable) { var thumbs = this.thumbs, ln = thumbs.length, i = 0; for (; i < ln; i++) { thumbs[i].dragObj[disable ? 'disable' : 'enable'](); } }, disable: function() { Ext.form.Slider.superclass.disable.call(this); this.setThumbsDisabled(true); }, enable: function() { Ext.form.Slider.superclass.enable.call(this); this.setThumbsDisabled(false); } }); Ext.reg('sliderfield', Ext.form.Slider); Ext.form.Slider.Thumb = Ext.extend(Ext.form.Field, { isField: false, baseCls: 'x-thumb', autoCreateField: false, draggable: true, value: 0, onRender: function() { this.draggable = { direction: 'horizontal', constrain: this.slider.fieldEl, revert: false, thumb: this }; Ext.form.Slider.Thumb.superclass.onRender.apply(this, arguments); }, setValue: function(newValue) { this.value = newValue; return this; }, getValue: function() { return this.value; } }); Ext.reg('sliderthumb', Ext.form.Slider.Thumb); Ext.form.Toggle = Ext.extend(Ext.form.Slider, { minValue: 0, maxValue: 1, ui: 'toggle', inputType: 'toggle', minValueCls: 'x-toggle-off', maxValueCls: 'x-toggle-on', animationDuration: 70, toggle: function() { var thumb = this.thumbs[0], value = thumb.getValue(); this.setValue(value == this.minValue ? this.maxValue : this.minValue, this.animationDuration); }, setValue: function(value) { Ext.form.Toggle.superclass.setValue.call(this, value, this.animationDuration); var fieldEl = this.fieldEl; if (this.constrain(value) === this.minValue) { fieldEl.addCls(this.minValueCls); fieldEl.removeCls(this.maxValueCls); } else { fieldEl.addCls(this.maxValueCls); fieldEl.removeCls(this.minValueCls); } }, onTap: function() { if (!this.disabled) { this.toggle(); } }, getThumbClass: function() { return Ext.form.Toggle.Thumb; } }); Ext.reg('togglefield', Ext.form.Toggle); Ext.form.Toggle.Thumb = Ext.extend(Ext.form.Slider.Thumb, { onRender: function() { Ext.form.Toggle.Thumb.superclass.onRender.apply(this, arguments); Ext.DomHelper.append(this.el, [{ cls: 'x-toggle-thumb-off', html: '<span>OFF</span>' },{ cls: 'x-toggle-thumb-on', html: '<span>ON</span>' },{ cls: 'x-toggle-thumb-thumb' }]); } }); Ext.form.Text = Ext.extend(Ext.form.Field, { ui: 'text', focusCls: 'x-field-focus', maxLength: 0, placeHolder: undefined, autoComplete: undefined, autoCapitalize: undefined, autoCorrect: undefined, isFocused: false, isClearIconVisible: false, useMask: Ext.is.iOS, initComponent: function() { this.addEvents( 'focus', 'blur', 'keyup', 'change', 'action' ); this.enableBubble('action'); Ext.form.Text.superclass.initComponent.apply(this, arguments); }, applyRenderSelectors: function() { this.renderSelectors = Ext.applyIf(this.renderSelectors || {}, { clearIconEl: '.x-field-clear', clearIconContainerEl: '.x-field-clear-container' }); Ext.form.Text.superclass.applyRenderSelectors.call(this); }, initRenderData: function() { var renderData = Ext.form.Text.superclass.initRenderData.call(this), autoComplete = this.autoComplete, autoCapitalize = this.autoCapitalize, autoCorrect = this.autoCorrect; Ext.applyIf(renderData, { placeHolder : this.placeHolder, maxlength : this.maxLength, useClearIcon : this.useClearIcon }); var testArray = [true, 'on']; if (autoComplete !== undefined) { renderData.autoComplete = (testArray.indexOf(autoComplete) !== -1) ? 'on': 'off'; } if (autoCapitalize !== undefined) { renderData.autoCapitalize = (testArray.indexOf(autoCapitalize) !== -1) ? 'on': 'off'; } if (autoCorrect !== undefined) { renderData.autoCorrect = (testArray.indexOf(autoCorrect) !== -1) ? 'on': 'off'; } this.renderData = renderData; return renderData; }, initEvents: function() { Ext.form.Text.superclass.initEvents.call(this); if (this.fieldEl) { this.mon(this.fieldEl, { focus: this.onFocus, blur: this.onBlur, keyup: this.onKeyUp, paste: this.updateClearIconVisibility, mousedown: this.onBeforeFocus, scope: this }); if (this.clearIconEl){ this.mon(this.clearIconContainerEl, { scope: this, tap: this.onClearIconTap }); } } }, onEnable: function() { Ext.form.Text.superclass.onEnable.apply(this, arguments); this.disabled = false; this.updateClearIconVisibility(); }, onDisable: function() { Ext.form.Text.superclass.onDisable.apply(this, arguments); this.blur(); this.hideClearIcon(); }, onClearIconTap: function() { if (!this.disabled) { this.setValue(''); } }, updateClearIconVisibility: function() { var value = this.getValue(); if (!value) { value = ''; } if (value.length < 1){ this.hideClearIcon(); } else { this.showClearIcon(); } return this; }, showClearIcon: function() { if (!this.disabled && this.fieldEl && this.clearIconEl && !this.isClearIconVisible) { this.isClearIconVisible = true; this.fieldEl.addCls('x-field-clearable'); this.clearIconEl.removeCls('x-hidden-visibility'); } return this; }, hideClearIcon: function() { if (this.fieldEl && this.clearIconEl && this.isClearIconVisible) { this.isClearIconVisible = false; this.fieldEl.removeCls('x-field-clearable'); this.clearIconEl.addCls('x-hidden-visibility'); } return this; }, afterRender: function() { Ext.form.Text.superclass.afterRender.call(this); this.updateClearIconVisibility(); }, onBeforeFocus: function(e) { this.fireEvent('beforefocus', e); }, beforeFocus: Ext.emptyFn, onMaskTap: function(e) { if (Ext.form.Text.superclass.onMaskTap.apply(this, arguments) !== true) { return false; } this.maskCorrectionTimer = Ext.defer(this.showMask, 1000, this); this.hideMask(); }, onFocus: function(e) { if (this.mask) { if (this.maskCorrectionTimer) { clearTimeout(this.maskCorrectionTimer); } this.hideMask(); } this.beforeFocus(); if (this.focusCls) { this.el.addCls(this.focusCls); } if (!this.isFocused) { this.isFocused = true; this.startValue = this.getValue(); this.fireEvent('focus', this, e); } Ext.currentlyFocusedField = this; }, beforeBlur: Ext.emptyFn, onBlur: function(e) { this.beforeBlur(); if (this.focusCls) { this.el.removeCls(this.focusCls); } this.isFocused = false; var value = this.getValue(); if (String(value) != String(this.startValue)){ this.fireEvent('change', this, value, this.startValue); } this.fireEvent('blur', this, e); this.updateClearIconVisibility(); this.showMask(); this.afterBlur(); Ext.currentlyFocusedField = null; }, afterBlur: Ext.emptyFn, focus: function(){ if (this.rendered && this.fieldEl && this.fieldEl.dom.focus) { this.fieldEl.dom.focus(); } return this; }, blur: function(){ if(this.rendered && this.fieldEl && this.fieldEl.dom.blur) { this.fieldEl.dom.blur(); } return this; }, setValue: function() { Ext.form.Text.superclass.setValue.apply(this, arguments); this.updateClearIconVisibility(); }, onKeyUp: function(e) { this.updateClearIconVisibility(); this.fireEvent('keyup', this, e); if (e.browserEvent.keyCode === 13) { this.blur(); this.fireEvent('action', this, e); } } }); Ext.reg('textfield', Ext.form.Text); Ext.form.TextField = Ext.extend(Ext.form.Text, { constructor: function() { console.warn("Ext.form.TextField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Text instead"); Ext.form.TextField.superclass.constructor.apply(this, arguments); } }); Ext.form.Password = Ext.extend(Ext.form.Text, { inputType: 'password', autoCapitalize : false }); Ext.reg('passwordfield', Ext.form.Password); Ext.form.Email = Ext.extend(Ext.form.Text, { inputType: 'email', autoCapitalize: false }); Ext.reg('emailfield', Ext.form.Email); Ext.form.Url = Ext.extend(Ext.form.Text, { inputType: 'url', autoCapitalize: false }); Ext.reg('urlfield', Ext.form.Url); Ext.form.Search = Ext.extend(Ext.form.Text, { inputType: 'search' }); Ext.reg('searchfield', Ext.form.Search); Ext.form.Number = Ext.extend(Ext.form.Text, { ui: 'number', inputType: 'number', minValue : undefined, maxValue : undefined, stepValue : undefined, renderTpl: [ '<tpl if="label"><div class="x-form-label"><span>{label}</span></div></tpl>', '<tpl if="fieldEl"><div class="x-form-field-container">', '<input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="minValue != undefined">min="{minValue}" </tpl>', '<tpl if="maxValue != undefined">max="{maxValue}" </tpl>', '<tpl if="stepValue != undefined">step="{stepValue}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '/>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div></tpl>', '<tpl if="useClearIcon"><div class="x-field-clear-container"><div class="x-field-clear x-hidden-visibility">&#215;</div><div></tpl>' ], onRender : function() { Ext.apply(this.renderData, { maxValue : this.maxValue, minValue : this.minValue, stepValue : this.stepValue }); Ext.form.Number.superclass.onRender.apply(this, arguments); } }); Ext.reg('numberfield', Ext.form.Number); Ext.form.Spinner = Ext.extend(Ext.form.Number, { componentCls: 'x-spinner', minValue: Number.NEGATIVE_INFINITY, maxValue: Number.MAX_VALUE, incrementValue: 1, accelerateOnTapHold: true, defaultValue: 0, cycle: false, disableInput: false, useClearIcon: false, autoCapitalize: false, renderTpl: [ '<tpl if="label"><div class="x-form-label"><span>{label}</span></div></tpl>', '<tpl if="fieldEl">', '<div class="{componentCls}-body">', '<div class="{componentCls}-down"><span>-</span></div>', '<div class="x-form-field-container">', '<input id="{inputId}" type="{type}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="minValue != undefined">min="{minValue}" </tpl>', '<tpl if="maxValue != undefined">max="{maxValue}" </tpl>', '<tpl if="stepValue != undefined">step="{stepValue}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '/>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div>', '<div class="{componentCls}-up"><span>+</span></div>', '</div>', '</tpl>' ], initComponent: function() { this.addEvents( 'spin', 'spindown', 'spinup' ); Ext.form.Spinner.superclass.initComponent.call(this); }, onRender: function() { this.renderData.disableInput = this.disableInput; Ext.applyIf(this.renderSelectors, { spinUpEl: '.x-spinner-up', spinDownEl: '.x-spinner-down' }); Ext.form.Spinner.superclass.onRender.apply(this, arguments); this.downRepeater = this.createRepeater(this.spinDownEl, this.onSpinDown); this.upRepeater = this.createRepeater(this.spinUpEl, this.onSpinUp); }, initValue: function() { if (isNaN(this.defaultValue)) { this.defaultValue = 0; } if (!this.value) { this.value = this.defaultValue; } Ext.form.Spinner.superclass.initValue.apply(this, arguments); }, createRepeater: function(el, fn){ var repeat = new Ext.util.TapRepeater(el, { accelerate: this.accelerateOnTapHold }); this.mon(repeat, { tap: fn, touchstart: this.onTouchStart, touchend: this.onTouchEnd, preventDefault: true, scope: this }); return repeat; }, onSpinDown: function() { if (!this.disabled) { this.spin(true); } }, onSpinUp: function() { if (!this.disabled) { this.spin(false); } }, onKeyUp: function(e) { Ext.form.Spinner.superclass.onKeyUp.apply(this, arguments); }, onTouchStart: function(btn) { if (!this.disabled) { btn.el.addCls('x-button-pressed'); } }, onTouchEnd: function(btn) { btn.el.removeCls('x-button-pressed'); }, setValue: function(value) { value = parseFloat(value); if (isNaN(value)) { value = this.defaultValue; } Ext.form.Spinner.superclass.setValue.call(this, value); }, spin: function(down) { var value = parseFloat(this.getValue()), increment = this.incrementValue, cycle = this.cycle, min = this.minValue, max = this.maxValue, direction = down ? 'down': 'up'; if (down){ value -= increment; } else{ value += increment; } value = (isNaN(value)) ? this.defaultValue: value; if (value < min) { value = cycle ? max: min; } else if (value > max) { value = cycle ? min: max; } this.setValue(value); this.fireEvent('spin' + direction, this, value); this.fireEvent('spin', this, value, direction); }, destroy: function() { Ext.destroy(this.downRepeater, this.upRepeater); Ext.form.Spinner.superclass.destroy.call(this, arguments); } }); Ext.reg('spinnerfield', Ext.form.Spinner); Ext.form.Hidden = Ext.extend(Ext.form.Field, { ui: 'hidden', inputType: 'hidden', tabIndex: -1 }); Ext.reg('hiddenfield', Ext.form.Hidden); Ext.form.HiddenField = Ext.extend(Ext.form.Hidden, { constructor: function() { console.warn("Ext.form.HiddenField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Hidden instead"); Ext.form.HiddenField.superclass.constructor.apply(this, arguments); } }); Ext.form.Checkbox = Ext.extend(Ext.form.Field, { ui: 'checkbox', inputType: 'checkbox', checked: false, value: '', constructor: function(config) { this.addEvents( 'check', 'uncheck' ); Ext.form.Checkbox.superclass.constructor.call(this, config); }, renderTpl: [ '<tpl if="label"><div class="x-form-label"><span>{label}</span></div></tpl>', '<tpl if="fieldEl"><input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}" tabIndex="-1" ', '<tpl if="checked"> checked </tpl>', '<tpl if="style">style="{style}" </tpl> value="{inputValue}" />', '</tpl>' ], onRender: function() { var isChecked = this.getBooleanIsChecked(this.checked); Ext.apply(this.renderData, { inputValue : String(this.value), checked : isChecked }); Ext.form.Checkbox.superclass.onRender.apply(this, arguments); if (this.fieldEl) { this.mon(this.fieldEl, { click: this.onChange, scope: this }); this.setChecked(isChecked); this.originalState = this.isChecked(); } }, onChange: function(e) { if (e) { if (e.browserEvent) { e = e.browserEvent; } if (!e.isSimulated) { e.preventDefault(); e.stopPropagation(); return; } } if (this.isChecked()) { this.fireEvent('check', this); } else { this.fireEvent('uncheck', this); } }, isChecked: function() { if (this.rendered) { return this.fieldEl.dom.checked || false; } else { return !!this.checked; } }, setChecked: function(checked) { var newState = this.getBooleanIsChecked(checked), rendered = this.rendered, currentState, field; if (rendered) { field = this.fieldEl.dom; currentState = field.checked; } else { currentState = !!this.checked; } if (currentState != newState) { if (rendered) { field.checked = newState; } else { this.checked = newState; } this.onChange(); } return this; }, check: function() { return this.setChecked(true); }, uncheck: function() { return this.setChecked(false); }, reset: function() { Ext.form.Checkbox.superclass.reset.apply(this, arguments); this.setChecked(this.originalState); return this; }, //@private getBooleanIsChecked: function(value) { return /^(true|1|on)/i.test(String(value)); }, getSameGroupFields: function() { var parent = this.el.up('form'), formComponent = Ext.getCmp(parent.id), fields = []; if (formComponent) { fields = formComponent.getFields(this.getName()); } return fields; }, getGroupValues: function() { var values = []; this.getSameGroupFields().forEach(function(field) { if (field.isChecked()) { values.push(field.getValue()); } }); return values; }, setGroupValues: function(values) { this.getSameGroupFields().forEach(function(field) { field.setChecked((values.indexOf(field.getValue()) !== -1)); }); return this; }, setValue: function(value) { value = String(value); Ext.form.Checkbox.superclass.setValue.call(this, value); } }); Ext.reg('checkboxfield', Ext.form.Checkbox); Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { inputType: 'radio', ui: 'radio', getGroupValue: function() { var field, fields = this.getSameGroupFields(); for (var i=0; i<fields.length; i++) { field = fields[i]; if (field.isChecked()) { return field.getValue(); } } return null; }, setGroupValue: function(value) { var field, fields = this.getSameGroupFields(), i = 0, len = fields.length; for (; i < len; i++) { field = fields[i]; if (field.getValue() == value) { field.check(); return; } } } }); Ext.reg('radiofield', Ext.form.Radio); Ext.form.Select = Ext.extend(Ext.form.Text, { ui: 'select', valueField: 'value', displayField: 'text', tabIndex: -1, useMask: true, monitorOrientation: true, initComponent: function() { var options = this.options; if (this.store) { this.store = Ext.StoreMgr.lookup(this.store); } else { this.store = new Ext.data.Store({ fields: [this.valueField, this.displayField] }); if (options && Ext.isArray(options) && options.length > 0) { this.setOptions(this.options); } } Ext.form.Select.superclass.initComponent.call(this); this.addEvents( 'change' ); }, onRender: function(){ Ext.form.Select.superclass.onRender.apply(this, arguments); var name = this.hiddenName; if (name) { this.hiddenField = this.el.insertSibling({ name: name, tag: 'input', type: 'hidden' }, 'after'); } }, getPicker: function() { if (!this.picker) { this.picker = new Ext.Picker({ slots: [{ align : 'center', name : this.name, valueField : this.valueField, displayField: this.displayField, value : this.getValue(), store : this.store }], listeners: { change: this.onPickerChange, scope: this } }); } return this.picker; }, getListPanel: function() { if (!this.listPanel) { this.listPanel = new Ext.Panel({ floating : true, stopMaskTapEvent : false, hideOnMaskTap : true, cls : 'x-select-overlay', scroll : 'vertical', items: { xtype: 'list', store: this.store, itemId: 'list', scroll: false, itemTpl : [ '<span class="x-list-label">{' + this.displayField + '}</span>', '<span class="x-list-selected"></span>' ], listeners: { select : this.onListSelect, scope : this } } }); } return this.listPanel; }, onOrientationChange: function() { if (this.isActive && !Ext.is.Phone) { this.listPanel.showBy(this.el, false, false); } }, onMaskTap: function() { if (this.disabled) { return; } this.showComponent(); }, showComponent: function() { if (Ext.is.Phone) { this.getPicker().show(); } else { var listPanel = this.getListPanel(), index = this.store.findExact(this.valueField, this.value); listPanel.showBy(this.el, 'fade', false); listPanel.down('#list').getSelectionModel().select(index != -1 ? index: 0, false, true); } this.isActive = true; }, onListSelect: function(selModel, selected) { if (selected) { this.setValue(selected.get(this.valueField)); this.fireEvent('change', this, this.getValue()); } this.listPanel.hide({ type: 'fade', out: true, scope: this }); this.isActive = false; }, onPickerChange: function(picker, value) { var currentValue = this.getValue(), newValue = value[this.name]; if (newValue != currentValue) { this.setValue(newValue); this.fireEvent('change', this, newValue); } this.isActive = false; }, setValue: function(value) { var idx = 0, hiddenField = this.hiddenField, record; if (value) { idx = this.store.findExact(this.valueField, value) } record = this.store.getAt(idx); if (record && this.rendered) { this.fieldEl.dom.value = record.get(this.displayField); this.value = record.get(this.valueField); if (hiddenField) { hiddenField.dom.value = this.value; } } else { if (this.rendered) { this.fieldEl.dom.value = value; } this.value = value; } if (this.picker) { var pickerValue = {}; pickerValue[this.name] = this.value; this.picker.setValue(pickerValue); } return this; }, getValue: function(){ return this.value; }, setOptions: function(options, append) { if (!options) { this.store.clearData(); this.setValue(null); } else { this.store.loadData(options, append); } }, destroy: function() { Ext.form.Select.superclass.destroy.apply(this, arguments); Ext.destroy(this.listPanel, this.picker, this.hiddenField); } }); Ext.reg('selectfield', Ext.form.Select); Ext.form.TextArea = Ext.extend(Ext.form.Text, { ui: 'textarea', maxRows: undefined, autoCapitalize: false, renderTpl: [ '<tpl if="label"><div class="x-form-label"><span>{label}</span></div></tpl>', '<tpl if="fieldEl"><div class="x-form-field-container">', '<textarea id="{inputId}" type="{type}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="maxRows != undefined">rows="{maxRows}" </tpl>', '<tpl if="maxlength">maxlength="{maxlength}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '></textarea>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div></tpl>' ], onRender: function() { this.renderData.maxRows = this.maxRows; Ext.form.TextArea.superclass.onRender.apply(this, arguments); }, onKeyUp: function(e) { this.fireEvent('keyup', this, e); } }); Ext.reg('textareafield', Ext.form.TextArea); Ext.form.DatePicker = Ext.extend(Ext.form.Field, { ui: 'select', picker: null, destroyPickerOnHide: false, initComponent: function() { this.addEvents( 'select' ); this.tabIndex = -1; this.useMask = true; Ext.form.Text.superclass.initComponent.apply(this, arguments); }, getDatePicker: function() { if (!this.datePicker) { if (this.picker instanceof Ext.DatePicker) { this.datePicker = this.picker; } else { this.datePicker = new Ext.DatePicker(Ext.apply(this.picker || {})); } this.datePicker.setValue(this.value || null); this.datePicker.on({ scope : this, change: this.onPickerChange, hide : this.onPickerHide }); } return this.datePicker; }, onMaskTap: function() { if (Ext.form.DatePicker.superclass.onMaskTap.apply(this, arguments) !== true) { return false; } this.getDatePicker().show(); }, onPickerChange : function(picker, value) { this.setValue(value); this.fireEvent('select', this, this.getValue()); }, onPickerHide: function() { if (this.destroyPickerOnHide && this.datePicker) { this.datePicker.destroy(); } }, setValue: function(value, animated) { if (this.datePicker) { this.datePicker.setValue(value, animated); this.value = (value != null) ? this.datePicker.getValue() : null; } else { if (!Ext.isDate(value) && !Ext.isObject(value)) { value = null; } if (Ext.isObject(value)) { this.value = new Date(value.year, value.month-1, value.day); } else { this.value = value; } } if (this.rendered) { this.fieldEl.dom.value = this.getValue(true); } return this; }, getValue: function(format) { var value = this.value || null; return (format && Ext.isDate(value)) ? value.format(Ext.util.Format.defaultDateFormat) : value; }, onDestroy: function() { if (this.datePicker) { this.datePicker.destroy(); } Ext.form.DatePicker.superclass.onDestroy.call(this); } }); Ext.reg('datepickerfield', Ext.form.DatePicker); Ext.layout.LayoutManager = new Ext.AbstractManager({ create : function(config, defaultType) { if (!config) { config = defaultType; } if (Ext.isString(config)) { return new this.types[config || defaultType]; } else if (Ext.isObject(config)) { if (config.isLayout) { return config; } else { return new this.types[config.type || defaultType](config); } } } }); Ext.regLayout = function() { return Ext.layout.LayoutManager.registerType.apply(Ext.layout.LayoutManager, arguments); }; Ext.layout.Layout = Ext.extend(Object, { isLayout: true, initialized: false, constructor : function(config) { this.id = Ext.id(null, 'ext-layout-' + this.type + '-'); Ext.apply(this, config); }, layout : function() { var me = this; me.layoutBusy = true; me.initLayout(); if (me.beforeLayout.apply(me, arguments) !== false) { me.onLayout.apply(me, arguments); me.afterLayout(); me.owner.needsLayout = false; me.layoutBusy = false; } }, beforeLayout : function() { this.renderItems(this.getLayoutItems(), this.getTarget()); return true; }, renderItems : function(items, target) { var ln = items.length, i = 0, item; for (; i < ln; i++) { item = items[i]; if (item && !item.rendered) { this.renderItem(item, i, target); } else if (!this.isValidParent(item, target)) { this.moveItem(item, i, target); } } }, renderItem : function(item, position, target) { if (!item.rendered) { item.render(target, position); this.configureItem(item, position); this.childrenChanged = true; } }, moveItem : function(item, position, target) { if (typeof position == 'number') { position = target.dom.childNodes[position]; } target = target.dom || target; target.insertBefore(item.el.dom, position || null); item.container = target; this.configureItem(item, position); this.childrenChanged = true; }, initLayout : function() { if (!this.initialized && !Ext.isEmpty(this.targetCls)) { this.getTarget().addCls(this.targetCls); } this.initialized = true; }, setOwner : function(owner) { this.owner = owner; }, getLayoutItems : function() { return []; }, isValidParent : function(item, target) { var dom = item.el ? item.el.dom : Ext.getDom(item); return target && (dom.parentNode == (target.dom || target)); }, configureItem: function(item, position) { if (this.itemCls) { item.el.addCls(this.itemCls); } }, onLayout : Ext.emptyFn, afterLayout : Ext.emptyFn, onRemove : Ext.emptyFn, onDestroy : Ext.emptyFn, afterRemove : function(item) { if (this.itemCls && item.rendered) { item.el.removeCls(this.itemCls); } }, destroy : function() { if (!Ext.isEmpty(this.targetCls)) { var target = this.getTarget(); if (target) { target.removeCls(this.targetCls); } } this.onDestroy(); } }); Ext.layout.ComponentLayout = Ext.extend(Ext.layout.Layout, { type: 'component', monitorChildren: true, beforeLayout : function(width, height) { Ext.layout.ComponentLayout.superclass.beforeLayout.call(this); var owner = this.owner, isVisible = owner.isVisible(), layoutCollection; if (!isVisible && owner.hiddenOwnerCt) { layoutCollection = owner.hiddenOwnerCt.layoutOnShow; layoutCollection.remove(owner); layoutCollection.add(owner); owner.needsLayout = { width: width, height: height, isSetSize: false }; } return isVisible && this.needsLayout(width, height); }, needsLayout : function(width, height) { this.lastComponentSize = this.lastComponentSize || { width: -Infinity, height: -Infinity }; var childrenChanged = this.childrenChanged; this.childrenChanged = false; return (childrenChanged || this.lastComponentSize.width !== width || this.lastComponentSize.height !== height); }, setElementSize: function(el, width, height) { if (width !== undefined && height !== undefined) { el.setSize(width, height); } else if (height !== undefined) { el.setHeight(height); } else if (width !== undefined) { el.setWidth(width); } }, getTarget : function() { return this.owner.el; }, setTargetSize : function(width, height) { this.setElementSize(this.owner.el, width, height); this.lastComponentSize = { width: width, height: height }; }, afterLayout : function() { var owner = this.owner, layout = owner.layout, ownerCt = owner.ownerCt, ownerCtSize, activeSize, ownerSize, width, height; owner.afterComponentLayout(this); if (layout && layout.isLayout) { layout.layout(); } if (ownerCt && ownerCt.componentLayout && ownerCt.componentLayout.monitorChildren && !ownerCt.componentLayout.layoutBusy) { ownerCt.componentLayout.childrenChanged = true; if (ownerCt.layout && !ownerCt.layout.layoutBusy) { if (ownerCt.layout.type == 'autocontainer') { ownerCt.doComponentLayout(width, height); } else { ownerCt.layout.layout(); } } } } }); Ext.layout.AutoComponentLayout = Ext.extend(Ext.layout.ComponentLayout, { type: 'autocomponent', onLayout : function(width, height) { this.setTargetSize(width, height); } }); Ext.regLayout('autocomponent', Ext.layout.AutoComponentLayout); Ext.layout.DockLayout = Ext.extend(Ext.layout.ComponentLayout, { type: 'dock', itemCls: 'x-docked', onLayout: function(width, height) { var me = this, owner = me.owner, body = owner.body, ownerCt = owner.ownerCt, layout = owner.layout, collapsed = owner.collapsed, contracted = owner.contracted, expanded = owner.expanded, headerItem = me.headerItem, target = me.getTarget(), autoWidth = false, autoHeight = false, animTo; var info = me.info = { boxes: [], size: { width: width, height: height }, padding: { top: target.getPadding('t'), right: target.getPadding('r'), bottom: target.getPadding('b'), left: target.getPadding('l') }, border: { top: target.getBorderWidth('t'), right: target.getBorderWidth('r'), bottom: target.getBorderWidth('b'), left: target.getBorderWidth('l') }, bodyMargin: { top: body.getMargin('t'), right: body.getMargin('r'), bottom: body.getMargin('b'), left: body.getMargin('l') }, bodyBox: {} }; if (height === undefined || height === null || width === undefined || width === null || contracted) { if ((height === undefined || height === null) && (width === undefined || width === null)) { autoHeight = true; autoWidth = true; if (!owner.animCollapse || (!expanded && !contracted)) { me.setTargetSize(null, null); } me.setBodyBox({width: null, height: null}); } else if (height === undefined || height === null) { autoHeight = true; if (!owner.animCollapse || (!expanded && !contracted)) { me.setTargetSize(width, null); } me.setBodyBox({width: width, height: null}); } else { autoWidth = true; if (!owner.animCollapse || (!expanded && !contracted)) { me.setTargetSize(null, height); } me.setBodyBox({width: null, height: height}); } if (!collapsed && layout && layout.isLayout) { layout.layout(); } me.dockItems(autoWidth, autoHeight); if (collapsed) { if (headerItem) { if (headerItem.dock == 'top' || headerItem.dock == 'bottom') { info.size.height = headerItem.getHeight(); } else { info.size.width = headerItem.getWidths(); } } else { info.size.height = 0; } } if (expanded || contracted) { if (owner.animCollapse) { Ext.createDelegate(owner.animCollapseFn, owner, [info.size.width, info.size.height])(); } else { Ext.createDelegate(owner['after' + (expanded ? 'Expand' : 'Collapse')], owner)(); me.setTargetSize(info.size.width, info.size.height); } } else { me.setTargetSize(info.size.width, info.size.height); } } else { if (expanded || contracted) { if (owner.animCollapse) { Ext.createDelegate(owner.animCollapseFn, owner, [width, height])(); } else { Ext.createDelegate(owner['after' + (expanded ? 'Expand' : 'Collapse')], owner)(); me.setTargetSize(width, height); } } else { me.setTargetSize(width, height); me.dockItems(); } } Ext.layout.DockLayout.superclass.onLayout.call(me, width, height); }, afterLayout : function() { Ext.layout.DockLayout.superclass.afterLayout.call(this); }, dockItems : function(autoWidth, autoHeight) { this.calculateDockBoxes(autoWidth, autoHeight); var info = this.info, collapsed = this.owner.collapsed, boxes = info.boxes, ln = boxes.length, dock, i; for (i = 0; i < ln; i++) { dock = boxes[i]; if (collapsed === true && !dock.isHeader) { continue; } dock.item.setPosition(dock.x, dock.y); } if (autoWidth) { info.bodyBox.width = null; } if (autoHeight) { info.bodyBox.height = null; } this.setBodyBox(info.bodyBox); }, calculateDockBoxes : function(autoWidth, autoHeight) { var me = this, target = me.getTarget(), items = me.getLayoutItems(), owner = me.owner, contracted = owner.contracted, expanded = owner.expanded, bodyEl = owner.body, info = me.info, size = info.size, ln = items.length, padding = info.padding, border = info.border, item, i, box, w, h, itemEl, vis; if (autoHeight) { size.height = bodyEl.getHeight() + padding.top + border.top + padding.bottom + border.bottom; } else { size.height = target.getHeight() - target.getMargin('tb'); } if (autoWidth) { size.width = bodyEl.getWidth() + padding.left + border.left + padding.right + border.right; } else { size.width = target.getWidth() - target.getMargin('lr'); } info.bodyBox = { x: border.left + padding.left, y: border.top + padding.top, width: size.width - padding.left - border.left - padding.right - border.right, height: size.height - border.top - padding.top - border.bottom - padding.bottom }; for (i = 0; i < ln; i++) { item = items[i]; if (item.isHeader) { me.headerItem = item; } box = me.initBox(item); if (autoHeight === true) { box = me.adjustAutoBox(box, i); } else { box = me.adjustSizedBox(box, i); } info.boxes.push(box); } }, adjustSizedBox : function(box, index) { var bodyBox = this.info.bodyBox; switch (box.type) { case 'top': box.y = bodyBox.y; break; case 'left': box.x = bodyBox.x; break; case 'bottom': box.y = (bodyBox.y + bodyBox.height) - box.height; break; case 'right': box.x = (bodyBox.x + bodyBox.width) - box.width; break; } if (!box.overlay) { switch (box.type) { case 'top': bodyBox.y += box.height; bodyBox.height -= box.height; break; case 'left': bodyBox.x += box.width; bodyBox.width -= box.width; break; case 'bottom': bodyBox.height -= box.height; break; case 'right': bodyBox.width -= box.width; break; } } return box; }, adjustAutoBox : function (box, index) { var info = this.info, bodyBox = info.bodyBox, size = info.size, boxes = info.boxes, pos = box.type, i, adjustBox; if (pos == 'top' || pos == 'bottom') { for (i = 0; i < index; i++) { adjustBox = boxes[i]; if (adjustBox.stretched && adjustBox.type == 'left' || adjustBox.type == 'right') { adjustBox.height += box.height; } else if (adjustBox.type == 'bottom') { adjustBox.y += box.height; } } } switch (pos) { case 'top': box.y = bodyBox.y; if (!box.overlay) { bodyBox.y += box.height; } size.height += box.height; break; case 'bottom': box.y = (bodyBox.y + bodyBox.height); size.height += box.height; break; case 'left': box.x = bodyBox.x; if (!box.overlay) { bodyBox.x += box.width; bodyBox.width -= box.width; } break; case 'right': if (!box.overlay) { bodyBox.width -= box.width; } box.x = (bodyBox.x + bodyBox.width); break; } return box; }, initBox : function(item) { var bodyBox = this.info.bodyBox, horizontal = (item.dock == 'top' || item.dock == 'bottom'), box = { item: item, overlay: item.overlay, type: item.dock }; if (item.stretch !== false) { box.stretched = true; if (horizontal) { box.x = bodyBox.x; box.width = bodyBox.width; item.doComponentLayout(box.width - item.el.getMargin('lr')); } else { box.y = bodyBox.y; box.height = bodyBox.height; item.doComponentLayout(undefined, box.height - item.el.getMargin('tb')); } } else { item.doComponentLayout(); box.width = item.getWidth(); box.height = item.getHeight(); if (horizontal) { box.x = (item.align == 'right') ? bodyBox.width - box.width : bodyBox.x; } } if (box.width == undefined) { box.width = item.getWidth() + item.el.getMargin('lr'); } if (box.height == undefined) { box.height = item.getHeight() + item.el.getMargin('tb'); } return box; }, getLayoutItems : function() { return this.owner.getDockedItems(); }, setBodyBox : function(box) { var me = this, owner = me.owner, body = owner.body, contracted = owner.contracted, expanded = owner.expanded, info = me.info, bodyMargin = info.bodyMargin, padding = info.padding, border = info.border; if (Ext.isNumber(box.width)) { box.width -= bodyMargin.left + bodyMargin.right; } if (Ext.isNumber(box.height)) { box.height -= bodyMargin.top + bodyMargin.bottom; } me.setElementSize(body, box.width, box.height); body.setLeft(box.x - padding.left - border.left); body.setTop(box.y - padding.top - border.top); }, configureItem : function(item, pos) { Ext.layout.DockLayout.superclass.configureItem.call(this, item, pos); var el = item.el || Ext.get(item); if (this.itemCls) { el.addCls(this.itemCls + '-' + item.dock); } }, afterRemove : function(item) { Ext.layout.DockLayout.superclass.afterRemove.call(this, item); if (this.itemCls) { item.el.removeCls(this.itemCls + '-' + item.dock); } var dom = item.el.dom; if (dom) { dom.parentNode.removeChild(dom); } this.childrenChanged = true; } }); Ext.regLayout('dock', Ext.layout.DockLayout); Ext.layout.FieldLayout = Ext.extend(Ext.layout.ComponentLayout, { type: 'field', onLayout: function(width, height) { Ext.layout.FieldLayout.superclass.onLayout.call(this, owner, target); this.setTargetSize(width, height); }, handleLabel : function() { this.owner.labelEl.setWidth(this.owner.labelWidth); } }); Ext.regLayout('field', Ext.layout.FieldLayout); Ext.layout.ContainerLayout = Ext.extend(Ext.layout.Layout, { type: 'container', getLayoutItems : function() { return this.owner && this.owner.items && this.owner.items.items || []; }, afterLayout : function() { this.owner.afterLayout(this); }, getTarget : function() { return this.owner.getTargetEl(); } }); Ext.layout.AutoContainerLayout = Ext.extend(Ext.layout.ContainerLayout, { type: 'autocontainer', onLayout : function(owner, target) { var items = this.getLayoutItems(), ln = items.length, i; for (i = 0; i < ln; i++) { items[i].doComponentLayout(); } } }); Ext.regLayout('auto', Ext.layout.AutoContainerLayout); Ext.regLayout('autocontainer', Ext.layout.AutoContainerLayout); Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, { itemCls: 'x-fit-item', targetCls: 'x-layout-fit', type: 'fit', onLayout : function() { Ext.layout.FitLayout.superclass.onLayout.call(this); if (this.owner.items.length) { var box = this.getTargetBox(), item = this.owner.items.get(0); this.setItemBox(item, box); item.cancelAutoSize = true; } }, getTargetBox : function() { var target = this.getTarget(), size = target.getSize(), padding = { left: target.getPadding('l'), right: target.getPadding('r'), top: target.getPadding('t'), bottom: target.getPadding('b') }, border = { left: target.getBorderWidth('l'), right: target.getBorderWidth('r'), top: target.getBorderWidth('t'), bottom: target.getBorderWidth('b') }; return { width: size.width- padding.left - padding.right - border.left - border.right, height: size.height - padding.top - padding.bottom - border.top - border.bottom, x: padding.left + border.left, y: padding.top + border.top }; }, setItemBox : function(item, box) { if (item && box.height > 0) { box.width -= item.el.getMargin('lr'); box.height -= item.el.getMargin('tb'); item.setCalculatedSize(box); item.setPosition(box); } } }); Ext.regLayout('fit', Ext.layout.FitLayout); Ext.layout.CardLayout = Ext.extend(Ext.layout.FitLayout, { type: 'card', sizeAllCards: false, hideInactive: true, beforeLayout: function() { this.activeItem = this.getActiveItem(); return Ext.layout.CardLayout.superclass.beforeLayout.apply(this, arguments); }, onLayout: function() { Ext.layout.FitLayout.superclass.onLayout.apply(this, arguments); var activeItem = this.activeItem, items = this.getLayoutItems(), ln = items.length, targetBox = this.getTargetBox(), i, item; for (i = 0; i < ln; i++) { item = items[i]; this.setItemBox(item, targetBox); } if (!this.firstActivated && activeItem) { if (activeItem.fireEvent('beforeactivate', activeItem) !== false) { activeItem.fireEvent('activate', activeItem); } this.firstActivated = true; } }, getActiveItem: function() { if (!this.activeItem && this.owner) { this.activeItem = this.parseActiveItem(this.owner.activeItem); } if (this.activeItem && this.owner.items.items.indexOf(this.activeItem) != -1) { return this.activeItem; } return null; }, parseActiveItem: function(item) { if (item && item.isComponent) { return item; } else if (typeof item == 'number' || item == undefined) { return this.getLayoutItems()[item || 0]; } else { return this.owner.getComponent(item); } }, configureItem: function(item, position) { Ext.layout.FitLayout.superclass.configureItem.call(this, item, position); if (this.hideInactive && this.activeItem !== item) { item.hide(); } else { item.show(); } }, onRemove: function(component) { if (component === this.activeItem) { this.activeItem = null; if (this.owner.items.getCount() == 0) { this.firstActivated = false; } } }, getAnimation: function(newCard, owner) { var newAnim = (newCard || {}).cardSwitchAnimation; if (newAnim === false) { return false; } return newAnim || owner.cardSwitchAnimation; }, setActiveItem: function(newCard, animation) { var me = this, owner = me.owner, doc = Ext.getDoc(), oldCard = me.activeItem, newIndex; animation = (animation == undefined) ? this.getAnimation(newCard, owner) : animation; newCard = me.parseActiveItem(newCard); newIndex = owner.items.indexOf(newCard); if (newIndex == -1) { owner.add(newCard); } if (newCard && oldCard != newCard && owner.onBeforeCardSwitch(newCard, oldCard, newIndex, !!animation) !== false) { if (!newCard.rendered) { this.layout(); } if (newCard.fireEvent('beforeactivate', newCard, oldCard) === false) { return false; } if (oldCard && oldCard.fireEvent('beforedeactivate', oldCard, newCard) === false) { return false; } if (newCard.hidden) { newCard.show(); } me.activeItem = newCard; if (animation) { doc.on('click', Ext.emptyFn, me, { single: true, preventDefault: true }); Ext.Anim.run(newCard, animation, { out: false, autoClear: true, scope: me, after: function() { Ext.defer(function() { doc.un('click', Ext.emptyFn, me); }, 50, me); newCard.fireEvent('activate', newCard, oldCard); if (!oldCard) { owner.onCardSwitch(newCard, oldCard, newIndex, true); } } }); if (oldCard) { Ext.Anim.run(oldCard, animation, { out: true, autoClear: true, after: function() { oldCard.fireEvent('deactivate', oldCard, newCard); if (me.hideInactive && me.activeItem != oldCard) { oldCard.hide(); } owner.onCardSwitch(newCard, oldCard, newIndex, true); } }); } } else { newCard.fireEvent('activate', newCard, oldCard); if (oldCard) { oldCard.fireEvent('deactivate', oldCard, newCard); if (me.hideInactive) { oldCard.hide(); } } owner.onCardSwitch(newCard, oldCard, newIndex, false); } return newCard; } return false; }, getNext: function(wrap) { var items = this.getLayoutItems(), index = items.indexOf(this.activeItem); return items[index + 1] || (wrap ? items[0] : false); }, next: function(anim, wrap) { return this.setActiveItem(this.getNext(wrap), anim); }, getPrev: function(wrap) { var items = this.getLayoutItems(), index = items.indexOf(this.activeItem); return items[index - 1] || (wrap ? items[items.length - 1] : false); }, prev: function(anim, wrap) { return this.setActiveItem(this.getPrev(wrap), anim); } }); Ext.regLayout('card', Ext.layout.CardLayout); Ext.layout.BoxLayout = Ext.extend(Ext.layout.ContainerLayout, { type: 'box', targetCls: 'x-layout-box', innerCls: 'x-layout-box-inner', pack : 'start', align: 'center', direction: 'normal', onLayout: function() { Ext.layout.BoxLayout.superclass.onLayout.call(this); if (this.pack === 'left' || this.pack === 'top') { this.pack = 'start'; } else if (this.pack === 'right' || this.pack === 'bottom') { this.pack = 'end'; } var target = this.getTarget(), ct = target.parent(), targetWidth = (ct.getWidth() - ct.getPadding('lr') - ct.getBorderWidth('lr')) + 'px', targetHeight = (ct.getHeight() - ct.getPadding('tb') - ct.getBorderWidth('tb')) + 'px'; target.setStyle({ '-webkit-box-orient': this.orientation, '-webkit-box-direction': this.direction, '-webkit-box-pack': this.pack, '-webkit-box-align': this.align }); if (this.orientation == 'horizontal') { target.setStyle({ 'min-width': targetWidth, 'height': targetHeight }); } else { target.setStyle({ 'min-height': targetHeight, 'width': targetWidth }); } this.prepareFlexedItems(); this.setFlexedItems(); }, prepareFlexedItems : function() { var items = this.getLayoutItems(), ln = items.length, item, i; for (i = 0; i < ln; i++) { item = items[i]; if (item.flex != undefined) { item.el.setStyle('position', 'absolute'); item.boxEl = this.createBoxEl(item); } else { item.doComponentLayout(); } } }, setFlexedItems : function() { var items = this.getLayoutItems(), ln = items.length, item, i; for (i = 0; i < ln; i++) { item = items[i]; if (item.flex != undefined) { item.boxSize = item.boxEl.getSize(); } } for (i = 0; i < ln; i++) { item = items[i]; if (item.flex != undefined) { item.el.setStyle('position', ''); if (this.align == 'stretch') { item.setSize(item.boxSize); } else { if (this.orientation == 'horizontal') { item.setWidth(item.boxSize.width); } else { item.setHeight(item.boxSize.height); } } item.boxEl.remove(); delete item.boxEl; delete item.boxSize; } } }, getTarget : function() { var owner = this.owner, innerCt = this.innerCt; if (!innerCt) { if (owner.scrollEl) { innerCt = owner.scrollEl.addCls(this.innerCls); } else { innerCt = owner.getTargetEl().createChild({cls: this.innerCls}); } this.innerCt = innerCt; } return innerCt; }, createBoxEl : function(item) { var el = item.el; return el.insertSibling({ style: 'margin-top: ' + el.getMargin('tb') + 'px; margin-left: ' + el.getMargin('lr') + 'px; -webkit-box-flex: ' + item.flex }); } }); Ext.layout.HBoxLayout = Ext.extend(Ext.layout.BoxLayout, { orientation: 'horizontal' }); Ext.regLayout('hbox', Ext.layout.HBoxLayout); Ext.layout.VBoxLayout = Ext.extend(Ext.layout.BoxLayout, { orientation: 'vertical' }); Ext.regLayout('vbox', Ext.layout.VBoxLayout);
JavaScript
/* * jTweetsAnywhere V1.2.1 * http://thomasbillenstein.com/jTweetsAnywhere/ * * Copyright 2010, Thomas Billenstein * Licensed under the MIT license. * http://thomasbillenstein.com/jTweetsAnywhere/license.txt */ (function($) { $.fn.jTweetsAnywhere = function(options) { // setup the default options var options = $.extend( { /** * The user's name who's tweet feed or list feed is displayed. This * param is also used when a Twitter "Follow Button" is displayed. Usually * this param is a string, but can also be an array of strings. If an array * is supplied (and the params 'list' and 'searchParams' are null), a * combined feed of all users is displayed. * * Sample: 'tbillenstein' or ['twitterapi', '...', '...'] */ username: 'tbillenstein', /** * The name of a user's list where the tweet feed is generated from */ list: null, /** * A single search param string or an array of search params, to be used in * a Twitter search call. All Twitter Search Params are supported * See here for the details: * http://apiwiki.twitter.com/Twitter-Search-API-Method%3A-search * * Sample: 'q=twitter' or ['q=twitter', 'geocode=48.856667,2.350833,30km'] */ searchParams: null, /** * The number of tweets shown in the tweet feed. If this param is 0, no feed * is displayed. For user or list feeds the maximum count is 20, for search * results the maximum count is 100. * * Unlike in previous releases, since 1.2.0 jTweetsAnywhere is based on a * tweets caching algorithm that will always deliver the requested count of * tweets accepting that this request can only be fullfilled by calling Twitter * more than once. * * IMPORTANT: Please always keep in mind, that the use of the Twitter API is * rate limited. Non-authenticated users are rated IP-based and you have only * 150 calls per hour available. Every retrieval of tweets counts and so does * for example hovering over a profile image to show the hovercard. * jTweetsAnywhere will always check the remaining count of free API calls before * actually calling Twitter to avoid black listing your visitor's IP. */ count: 0, /** * A flag (true/false) that specifies whether to display a profile image in * tweets. If the param is set to null (the default value), a profile image * is displayed only if the feed represents a user's list or the result of a * Twitter search. * * THIS OPTION IS DEPRECATED. You should use showTweetFeed.showProfileImages * instead. */ tweetProfileImagePresent: null, /** * Each tweet that is loaded from Twitter will pass the tweetFilter. if * the filter returns true, the tweet will be added to the tweets cache * otherwise it is ignored. The defaultTweetFilter alsways retruns true * but you can supply your own tweet filter to customize the tweet feed. */ tweetFilter: defaultTweetFilter, /** * A flag (true/false) that specifies whether to display a Tweet Feed * or an object literal representing the configuration options for the * Tweet Feed. This flag works in conjunction with the count parameter: * - if count equals 0, no feed is displayed, ignoring showTweetFeed * - if count not equals 0 and showTweetFeed equals false, no feed * is displayed * { * expandHovercards: false, // Boolean - Show Hovercards in expanded mode. * * showTimestamp: true, // A flag (true/false) that specifies whether to display a tweet's timestamp * // or an object literal representing the configuration options for the * // timestamp. * // { * // refreshInterval: 0, // Time in seconds to be waited until the * // // timestamps of the displayed tweets get refreshed * // // 0 means no refreshing. * // } * * showSource: false, // Boolean - Show info about the source of the tweet. * * showGeoLocation: true, // Boolean - Show geolocation info and link to Google maps. * * showInReplyTo: true, // Boolean - Show link to the "replied to" tweet (if available). * * showProfileImages: null, // A flag (true/false) that specifies whether to display a profile image in * // tweets. If the param is set to null (the default value), a profile image * // is displayed only if the feed represents a user's list or the result of a * // Twitter search. * * showUserScreenNames: null, // A flag (true/false/null) that specifies whether to display a username in * // tweets. If the param is set to null (the default value), a username * // is displayed only if the feed represents a user's list or the result of a * // Twitter search. * * showUserFullNames: false, // A flag (true/false/null) that specifies whether to display a user's full name * // in tweets. If the param is set to null, a user's full name * // is displayed only if the feed represents a user's list or the result of a * // Twitter search. * * includeRetweets: true, // Boolean - Include native retweets in a user's tweet feed * * paging: // An object literal representing the configuration options for the * { // paging support, that specifies how more/earlier tweets can be loaded * mode: "none" // by using the supplied UI controls (more/next buttons, scrollbar). * }, // Accepted values for mode are: "none" | "more" | "prev-next" | "endless-scroll" * // if mode equals "endless-scroll" you have to set the height of the tweet feed * // element (.jta-tweet-list) in your CSS to get a scrollbar! You should also set * // the "overflow" attribute to "auto". * * autorefresh: // An object literal representing the configuration options for the * { // autorefresh behaviour. * * // IMPORTANT: Please always keep in mind, that using the Twitter API is rate * // limited. Non-authenticated users are rated IP-based and you have only 150 * // calls per hour available. Every retrieval of tweets counts and so does for * // example hovering over a profile image to show the hovercard. jTweetsAnywhere will * // always check the remaining count of free API calls before actually calling * // Twitter to avoid black listing your visitor's IP. * * // However - choose your settings wisely to keep your visitors happy. An update * // interval of 30 seconds on a feed that is updated averaged once per hour * // does not make sense and is a total waste of remaining API calls! * * mode: "none", // Accepted values for mode are: "none" | "auto-insert" | "trigger-insert" * // "none" (the default value) - disables the autorefresh feature * // "auto-insert" - automatically insert the new tweets on top of the tweet feed * // "trigger-insert" - if new tweets arrived, show or update a button that displays * // the number of new tweets. These new tweets are inserted on top of the tweet * // feed, if the user clicks on the button. * * interval: 60, // Time in seconds to be waited until the next request for new tweets. Minimum * // value is 30. * * duration: 3600 // Time in seconds for how long the autorefresh will be active. After * // this period of time, autorefreshing will stop. A value of -1 means * // autorefresh for ever. * } * } */ showTweetFeed: true, /** * A flag (true/false) that specifies whether to display a Twitter "Follow * Button". */ showFollowButton: false, /** * A flag (true/false) that specifies whether to display a Twitter "Connect * Button" or an object literal representing the configuration options for * the "Tweet Box". * { * size: 'medium' // String - The size of the Connect Button. Valid values are: small, medium, large, xlarge * } */ showConnectButton: false, /** * A flag (true/false) that specifies whether to display Login Infos. */ showLoginInfo: false, /** * A flag (true/false) that specifies whether to display a Twitter "Tweet * Box" or an object literal representing the configuration options for * the "Tweet Box". * { * counter: true, // Boolean - Display a counter in the Tweet Box for counting characters * width: 515, // Number - The width of the Tweet Box in pixels * height: 65, // Number - The height of the Tweet Box in pixels * label: "What's happening", // String - The text above the Tweet Box, a call to action * defaultContent: <none>, // String - Pre-populated text in the Tweet Box. Useful for an @mention, a #hashtag, a link, etc. * onTweet: <none> // Function - Specify a listener for when a tweet is sent from the Tweet Box. The listener receives two arguments: a plaintext tweet and an HTML tweet * } */ showTweetBox: false, /** * A decorator is a function that is responsible for constructing a certain * element of the widget. Most of the decorators return a HTML string. * Exceptions are the mainDecorator, which defines the basic sequence of * the widget's components, plus the linkDecorator, the usernameDecorator * and the hashtagDecorator which return the string that is supplied as a * function param, enriched with the HTML tags. * * For details, see the implementations of the default decorators. Each * default decorator can be overwritten by your own implementation. */ mainDecorator: defaultMainDecorator, tweetFeedDecorator: defaultTweetFeedDecorator, tweetDecorator: defaultTweetDecorator, tweetProfileImageDecorator: defaultTweetProfileImageDecorator, tweetBodyDecorator: defaultTweetBodyDecorator, tweetUsernameDecorator: defaultTweetUsernameDecorator, tweetTextDecorator: defaultTweetTextDecorator, tweetAttributesDecorator: defaultTweetAttributesDecorator, tweetTimestampDecorator: defaultTweetTimestampDecorator, tweetSourceDecorator: defaultTweetSourceDecorator, tweetGeoLocationDecorator: defaultTweetGeoLocationDecorator, tweetInReplyToDecorator: defaultTweetInReplyToDecorator, tweetRetweeterDecorator: defaultTweetRetweeterDecorator, tweetFeedControlsDecorator: defaultTweetFeedControlsDecorator, tweetFeedControlsMoreBtnDecorator: defaultTweetFeedControlsMoreBtnDecorator, tweetFeedControlsPrevBtnDecorator: defaultTweetFeedControlsPrevBtnDecorator, tweetFeedControlsNextBtnDecorator: defaultTweetFeedControlsNextBtnDecorator, tweetFeedAutorefreshTriggerDecorator: defaultTweetFeedAutorefreshTriggerDecorator, tweetFeedAutorefreshTriggerContentDecorator: defaultTweetFeedAutorefreshTriggerContentDecorator, connectButtonDecorator: defaultConnectButtonDecorator, loginInfoDecorator: defaultLoginInfoDecorator, loginInfoContentDecorator: defaultLoginInfoContentDecorator, followButtonDecorator: defaultFollowButtonDecorator, tweetBoxDecorator: defaultTweetBoxDecorator, linkDecorator: defaultLinkDecorator, usernameDecorator: defaultUsernameDecorator, hashtagDecorator: defaultHashtagDecorator, loadingDecorator: defaultLoadingDecorator, errorDecorator: defaultErrorDecorator, noDataDecorator: defaultNoDataDecorator, /** * Formatters are currently used for date format processing only. * * The tweetTimestampFormatter formats the tweet's timestamp to be shown * in the tweet attributes section * * For details, see the implementation of the defaultTweetTimestampFormatter. */ tweetTimestampFormatter : defaultTweetTimestampFormatter, /** * The tweetTimestampTooltipFormatter formats the tweet's timestamp to be shown * in the tooltip when hovering over the timestamp link. */ tweetTimestampTooltipFormatter : defaultTweetTimestampTooltipFormatter, /** * A visualizer is a function that is responsible for adding one or more * elements to the DOM and thereby making them visible to the user. * A visualizer might also be responsible to do the opposite effect: * To remove one or more elements from the DOM. * * The tweetVisualizer gets called each time a tweet element should be * appended or prepended to the tweet feed element. * * For details, see the implementation of the defaultTweetVisualizer. * * Each default visualizer can be overwritten by your own implementation. */ tweetVisualizer: defaultTweetVisualizer, /** * The loadingIndicatorVisualizer gets called each time data is retrieved * from Twitter to visualize the loading indicator. This visualizer is also * used to hide the loading indicator. * * For details, see the implementation of the defaultLoadingIndicatorVisualizer. */ loadingIndicatorVisualizer: defaultLoadingIndicatorVisualizer, /** * The autorefreshTriggerVisualizer will be called if the autorefresh * trigger should be visualized or hidden. * * For details, see the implementation of the autorefreshTriggerVisualizer. */ autorefreshTriggerVisualizer: defaultAutorefreshTriggerVisualizer, /** * An event handler is a function that gets called whenever the event you * are interested in, occurs. * * The onDataRequest event handler will be called immediatly before calling * Twitter to retrieve new data and gives you the opportunity to deny * the call by returning false from the function. * * This feature might be used in conjunction with the paging feature, * especially when using the "endless-scroll" paging mode, to avoid the * exhaustion of remaining Twitter API calls, before the rate limit is * reached. The stats parameter contains statistical infos and counters * that you can examine to base your decision whether to return true or * false. */ onDataRequestHandler: defaultOnDataRequestHandler, /** * The onRateLimitData event handler is called each time * jTweetsAnywhere retrieved the rate limit data from Twitter. The actual * rate limit data is contained in the stats object. */ onRateLimitDataHandler: defaultOnRateLimitDataHandler, _tweetFeedConfig: { expandHovercards: false, showTimestamp: { refreshInterval: 0 }, showSource: false, showGeoLocation: true, showInReplyTo: true, showProfileImages: null, showUserScreenNames: null, showUserFullNames: false, includeRetweets: true, paging: { mode: "none", _limit: 0, _offset: 0 }, autorefresh: { mode: "none", interval: 60, duration: 3600, _startTime: null, _triggerElement: null }, _pageParam: 0, _maxId: null, _recLevel: 0, _noData: false, _clearBeforePopulate: false }, _tweetBoxConfig: { counter: true, width: 515, height: 65, label: "What's happening?", defaultContent: '', onTweet: function(textTweet, htmlTweet) {} }, _connectButtonConfig: { size: "medium" }, _baseSelector: null, _baseElement: null, _tweetFeedElement: null, _tweetFeedControlsElement: null, _followButtonElement: null, _loginInfoElement: null, _connectButtonElement: null, _tweetBoxElement: null, _loadingIndicatorElement: null, _noDataElement: null, _tweetsCache: [], _autorefreshTweetsCache: [], _stats: { dataRequestCount: 0, rateLimitPreventionCount: 0, rateLimit: { remaining_hits: 150, hourly_limit: 150 } } }, options); // no main decorator? nothing to do! if (!options.mainDecorator) { return; } options._baseSelector = this.selector; // if username is an array, create the search query and flatten username if (typeof(options.username) != 'string') { if (!options.searchParams) { options.searchParams = ['q=from:' + options.username.join(" OR from:")]; } options.username = options.username[0]; } // if showTweetFeed is not set to a boolean value, we expect the configuration of // the tweet feed if (typeof(options.showTweetFeed) == 'object') { $.extend(true, options._tweetFeedConfig, options.showTweetFeed); } // if showTweetBox is not set to a boolean value, we expect the configuration of // the TweetBox if (typeof(options.showTweetBox) == 'object') { options._tweetBoxConfig = options.showTweetBox; options.showTweetBox = true; } // if showConnectButton is not set to a boolean value, we expect the // configuration of the Connect Button if (typeof(options.showConnectButton) == 'object') { options._connectButtonConfig = options.showConnectButton; options.showConnectButton = true; } // to be compatible, check the deprecated option 'tweetProfileImagePresent' if (options._tweetFeedConfig.showProfileImages == null) { options._tweetFeedConfig.showProfileImages = options.tweetProfileImagePresent; } // if _tweetFeedConfig.showProfileImages is not set to a boolean value, // we decide to show a profile image if the feed represents a user's // list or the results of a Twitter search if (options._tweetFeedConfig.showProfileImages == null) { options._tweetFeedConfig.showProfileImages = (options.list || options.searchParams) && options.tweetProfileImageDecorator; } // if _tweetFeedConfig.showUserScreenNames is not set to a boolean value, // we decide to show a username if the feed represents a user's // list or the results of a Twitter search or a tweet is a native retweet if (options._tweetFeedConfig.showUserScreenNames == null) { if (options.list || options.searchParams) { options._tweetFeedConfig.showUserScreenNames = true; } if (!options.tweetUsernameDecorator) { options._tweetFeedConfig.showUserScreenNames = false; } } // if _tweetFeedConfig.showUserFullNames is not set to a boolean value, // we decide to show a user's full name if the feed represents a user's // list or the results of a Twitter search or a tweet is a native retweet if (options._tweetFeedConfig.showUserFullNames == null) { if (options.list || options.searchParams) { options._tweetFeedConfig.showUserFullNames = true; } if (!options.tweetUsernameDecorator) { options._tweetFeedConfig.showUserFullNames = false; } } options.count = validateRange(options.count, 0, options.searchParams ? 100 : 20); options._tweetFeedConfig.autorefresh.interval = Math.max(30, options._tweetFeedConfig.autorefresh.interval); options._tweetFeedConfig.paging._offset = 0; options._tweetFeedConfig.paging._limit = options.count; // internally, the decision of what parts of a widget are to be // displayed is based on the existence of the decorators if (options.count == 0 || !options.showTweetFeed) { options.tweetFeedDecorator = null; options.tweetFeedControlsDecorator = null; } if (options._tweetFeedConfig.paging.mode == 'none') { options.tweetFeedControlsDecorator = null; } if (!options.showFollowButton) { options.followButtonDecorator = null; } if (!options.showTweetBox) { options.tweetBoxDecorator = null; } if (!options.showConnectButton) { options.connectButtonDecorator = null; } if (!options.showLoginInfo) { options.loginInfoDecorator = null; } if (!options._tweetFeedConfig.showTimestamp) { options.tweetTimestampDecorator = null; } if (!options._tweetFeedConfig.showSource) { options.tweetSourceDecorator = null; } if (!options._tweetFeedConfig.showGeoLocation) { options.tweetGeoLocationDecorator = null; } if (!options._tweetFeedConfig.showInReplyTo) { options.tweetInReplyToDecorator = null; } // setup ajax $.ajaxSetup({ cache: true }); return this.each(function() { // the DOM element, where to display the widget options._baseElement = $(this); // create the widget's necessary sub DOM elements options._tweetFeedElement = options.tweetFeedDecorator ? $(options.tweetFeedDecorator(options)) : null; options._tweetFeedControlsElement = options.tweetFeedControlsDecorator ? $(options.tweetFeedControlsDecorator(options)) : null; options._followButtonElement = options.followButtonDecorator ? $(options.followButtonDecorator(options)) : null; options._tweetBoxElement = options.tweetBoxDecorator ? $(options.tweetBoxDecorator(options)) : null; options._connectButtonElement = options.connectButtonDecorator ? $(options.connectButtonDecorator(options)): null; options._loginInfoElement = options.loginInfoDecorator ? $(options.loginInfoDecorator(options)) : null; // add the widget to the DOM options.mainDecorator(options); populateTweetFeed(options); populateAnywhereControls(options); // bind event handlers to support paging bindEventHandlers(options); // install autorefresh support options._tweetFeedConfig.autorefresh._startTime = new Date().getTime(); startAutorefresh(options); startTimestampRefresh(options); }); }; defaultMainDecorator = function(options) { // defines the default sequence of the widget's elements if (options._tweetFeedElement) { options._baseElement.append(options._tweetFeedElement); } if (options._tweetFeedControlsElement) { options._baseElement.append(options._tweetFeedControlsElement); } if (options._connectButtonElement) { options._baseElement.append(options._connectButtonElement); } if (options._loginInfoElement) { options._baseElement.append(options._loginInfoElement); } if (options._followButtonElement) { options._baseElement.append(options._followButtonElement); } if (options._tweetBoxElement) { options._baseElement.append(options._tweetBoxElement); } }; defaultTweetFeedControlsDecorator = function(options) { // the default tweet feed's paging controls var html = ''; if (options._tweetFeedConfig.paging.mode == 'prev-next') { if (options.tweetFeedControlsPrevBtnDecorator) { html += options.tweetFeedControlsPrevBtnDecorator(options); } if (options.tweetFeedControlsNextBtnDecorator) { html += options.tweetFeedControlsNextBtnDecorator(options); } } else if (options._tweetFeedConfig.paging.mode == 'endless-scroll') { // nothing to do here atm } else { if (options.tweetFeedControlsMoreBtnDecorator) { html += options.tweetFeedControlsMoreBtnDecorator(options); } } return '<div class="jta-tweet-list-controls">' + html + '</div>'; }; defaultTweetFeedControlsMoreBtnDecorator = function(options) { return '<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-more">' + 'More' + '</span>'; }; defaultTweetFeedControlsPrevBtnDecorator = function(options) { return '<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-prev">' + 'Prev' + '</span>'; }; defaultTweetFeedControlsNextBtnDecorator = function(options) { return '<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-next">' + 'Next' + '</span>'; }; defaultTweetFeedAutorefreshTriggerDecorator = function(count, options) { var html = ''; if (options.tweetFeedAutorefreshTriggerContentDecorator) { html = options.tweetFeedAutorefreshTriggerContentDecorator(count, options); } return '<li class="jta-tweet-list-autorefresh-trigger">' + html + '</li>'; }; defaultTweetFeedAutorefreshTriggerContentDecorator = function(count, options) { var content = '' + count + ' new ' + (count > 1 ? ' tweets' : ' tweet'); return '<span class="jta-tweet-list-autorefresh-trigger-content">' + content + '</span>'; }; defaultTweetFeedDecorator = function(options) { // the default placeholder for the tweet feed is an unordered list return '<ul class="jta-tweet-list"></ul>'; }; defaultTweetDecorator = function(tweet, options) { // the default tweet is made of the optional user's profile image and the // tweet body inside a list item element var html = ''; if (options._tweetFeedConfig.showProfileImages) { html += options.tweetProfileImageDecorator(tweet, options); } if (options.tweetBodyDecorator) { html += options.tweetBodyDecorator(tweet, options); } html += '<div class="jta-clear">&nbsp;</div>'; return '<li class="jta-tweet-list-item">' + html + '</li>'; }; defaultTweetProfileImageDecorator = function(tweet, options) { // if tweet is a native retweet, use the retweet's profile var t = tweet.retweeted_status || tweet; // the default profile image decorator simply adds a link to the user's Twitter profile var screenName = t.user ? t.user.screen_name : false || t.from_user; var imageUrl = t.user ? t.user.profile_image_url : false || t.profile_image_url; var html = '<a class="jta-tweet-profile-image-link" href="http://twitter.com/' + screenName + '" target="_blank">' + '<img src="' + imageUrl + '" alt="' + screenName + '"' + (isAnywherePresent() ? '' : (' title="' + screenName + '"')) + '/>' + '</a>'; return '<div class="jta-tweet-profile-image">' + html + '</div>'; }; defaultTweetBodyDecorator = function(tweet, options) { // the default tweet body contains the tweet text and the tweet's creation date var html = ''; if (options.tweetTextDecorator) { html += options.tweetTextDecorator(tweet, options); } if (options.tweetAttributesDecorator) { html += options.tweetAttributesDecorator(tweet, options); } return '<div class="jta-tweet-body ' + (options._tweetFeedConfig.showProfileImages ? 'jta-tweet-body-list-profile-image-present' : '') + '">' + html + '</div>'; }; defaultTweetTextDecorator = function(tweet, options) { var tweetText = tweet.text; // if usernames should be visible and tweet is a native retweet, use // the original tweet text if (tweet.retweeted_status && ( options._tweetFeedConfig.showUserScreenNames || options._tweetFeedConfig.showUserScreenNames == null || options._tweetFeedConfig.showUserFullNames || options._tweetFeedConfig.showUserFullNames == null ) ) { tweetText = tweet.retweeted_status.text; } // the default tweet text decorator optionally marks links, @usernames, // and #hashtags if (options.linkDecorator) { tweetText = options.linkDecorator(tweetText, options); } if (options.usernameDecorator) { tweetText = options.usernameDecorator(tweetText, options); } if (options.hashtagDecorator) { tweetText = options.hashtagDecorator(tweetText, options); } if (options._tweetFeedConfig.showUserScreenNames || options._tweetFeedConfig.showUserFullNames || tweet.retweeted_status && ( options._tweetFeedConfig.showUserScreenNames == null || options._tweetFeedConfig.showUserFullNames == null ) ) { tweetText = options.tweetUsernameDecorator(tweet, options) + ' ' + tweetText; } return '<span class="jta-tweet-text">' + tweetText + '</span>'; }; defaultTweetUsernameDecorator = function(tweet, options) { // if tweet is a native retweet, use the retweet's profile var t = tweet.retweeted_status || tweet; var screenName = t.user ? t.user.screen_name : false || t.from_user; var fullName = t.user ? t.user.name : null; var htmlScreenName; if (screenName && (options._tweetFeedConfig.showUserScreenNames || (options._tweetFeedConfig.showUserScreenNames == null && tweet.retweeted_status))) { htmlScreenName = '<span class="jta-tweet-user-screen-name">' + '<a class="jta-tweet-user-screen-name-link" href="http://twitter.com/' + screenName + '" target="_blank">' + screenName + '</a>' + '</span>'; } var htmlFullName; if (fullName && (options._tweetFeedConfig.showUserFullNames || (options._tweetFeedConfig.showUserFullNames == null && tweet.retweeted_status))) { htmlFullName = '<span class="jta-tweet-user-full-name">' + (htmlScreenName ? ' (' : '') + '<a class="jta-tweet-user-full-name-link" href="http://twitter.com/' + screenName + '" name="' + screenName + '" target="_blank">' + fullName + '</a>' + (htmlScreenName ? ')' : '') + '</span>'; } var html = ""; if (htmlScreenName) { html += htmlScreenName; } if (htmlFullName) { if (htmlScreenName) { html += ' '; } html += htmlFullName; } if (htmlScreenName || htmlFullName) { html = '<span class="jta-tweet-user-name">' + (tweet.retweeted_status ? 'RT ' : '') + html + '</span>'; } return html; }; defaultTweetAttributesDecorator = function(tweet, options) { var html = ''; if (options.tweetTimestampDecorator || options.tweetSourceDecorator || options.tweetGeoLocationDecorator || options.tweetInReplyToDecorator || (tweet.retweeted_status && options.tweetRetweeterDecorator) ) { html += '<span class="jta-tweet-attributes">'; if (options.tweetTimestampDecorator) { html += options.tweetTimestampDecorator(tweet, options); } if (options.tweetSourceDecorator) { html += options.tweetSourceDecorator(tweet, options); } if (options.tweetGeoLocationDecorator) { html += options.tweetGeoLocationDecorator(tweet, options); } if (options.tweetInReplyToDecorator) { html += options.tweetInReplyToDecorator(tweet, options); } if (tweet.retweeted_status && options.tweetRetweeterDecorator) { html += options.tweetRetweeterDecorator(tweet, options); } html += '</span>'; } return html; }; defaultTweetTimestampDecorator = function(tweet, options) { // the default tweet timestamp decorator does a little bit of Twitter like formatting. // if tweet is a native retweet, use the retweet's timestamp var tw = tweet.retweeted_status || tweet; // reformat timestamp from Twitter, so IE is happy var createdAt = formatDate(tw.created_at); // format the timestamp by the tweetTimestampFormatter var tweetTimestamp = options.tweetTimestampFormatter(createdAt); var tweetTimestampTooltip = options.tweetTimestampTooltipFormatter(createdAt); var screenName = tw.user ? tw.user.screen_name : false || tw.from_user; var html = '<span class="jta-tweet-timestamp">' + '<a class="jta-tweet-timestamp-link" data-timestamp="' + createdAt + '" href="http://twitter.com/' + screenName + '/status/' + tw.id + '" target="_blank" title="' + tweetTimestampTooltip + '">' + tweetTimestamp + '</a>' + '</span>'; return html; }; defaultTweetTimestampTooltipFormatter = function(timeStamp) { var d = new Date(timeStamp); return d.toLocaleString(); }; defaultTweetTimestampFormatter = function(timeStamp) { var now = new Date(); var diff = parseInt((now.getTime() - Date.parse(timeStamp)) / 1000); var tweetTimestamp = ''; if (diff < 60) { tweetTimestamp += diff + ' second' + (diff == 1 ? '' : 's') + ' ago'; } else if (diff < 3600) { var t = parseInt((diff + 30) / 60); tweetTimestamp += t + ' minute' + (t == 1 ? '' : 's') + ' ago'; } else if (diff < 86400) { var t = parseInt((diff + 1800) / 3600); tweetTimestamp += t + ' hour' + (t == 1 ? '' : 's') + ' ago'; } else { var d = new Date(timeStamp); var period = 'AM'; var hours = d.getHours(); if (hours > 12) { hours -= 12; period = 'PM'; } var mins = d.getMinutes(); var minutes = (mins < 10 ? '0' : '') + mins; var monthName = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; tweetTimestamp += monthName[d.getMonth()] + ' ' + d.getDate(); if (d.getFullYear() < now.getFullYear()) { tweetTimestamp += ', ' + d.getFullYear(); } var t = parseInt((diff + 43200) / 86400); tweetTimestamp += ' (' + t + ' day' + (t == 1 ? '' : 's') + ' ago)'; } return tweetTimestamp; }; exTimestampFormatter = function(timeStamp) { var diff = parseInt((new Date().getTime() - Date.parse(timeStamp)) / 1000); var tweetTimestamp = ''; if (diff < 60) { tweetTimestamp += 'less than a minute ago'; } else if (diff < 3600) { var t = parseInt((diff + 30) / 60); tweetTimestamp += t + ' minute' + (t == 1 ? '' : 's') + ' ago'; } else if (diff < 86400) { var t = parseInt((diff + 1800) / 3600); tweetTimestamp += 'about ' + t + ' hour' + (t == 1 ? '' : 's') + ' ago'; } else { var t = parseInt((diff + 43200) / 86400); tweetTimestamp += 'about ' + t + ' day' + (t == 1 ? '' : 's') + ' ago'; var d = new Date(timeStamp); var period = 'AM'; var hours = d.getHours(); if (hours > 12) { hours -= 12; period = 'PM'; } var mins = d.getMinutes(); var minutes = (mins < 10 ? '0' : '') + mins; tweetTimestamp += ' (' + hours + ':' + minutes + ' ' + period + ' ' + (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear() + ')'; } return tweetTimestamp; }; defaultTweetSourceDecorator = function(tweet, options) { // if tweet is a native retweet, use the retweet's source var tw = tweet.retweeted_status || tweet; var source = tw.source.replace(/\&lt\;/gi,'<').replace(/\&gt\;/gi,'>').replace(/\&quot\;/gi,'"'); var html = '<span class="jta-tweet-source">' + ' via ' + '<span class="jta-tweet-source-link">' + source + '</span>' + '</span>'; return html; }; defaultTweetGeoLocationDecorator = function(tweet, options) { var html = ''; // if tweet is a native retweet, use the retweet's source var tw = tweet.retweeted_status || tweet; var q; if (tw.geo && tw.geo.coordinates) { q = tw.geo.coordinates.join(); } else if (tw.place && tw.place.full_name) { q = tw.place.full_name; } if (q) { var location = 'here'; if (tw.place && tw.place.full_name) { location = tw.place.full_name; } var link = 'http://maps.google.com/maps?q=' + q; html = '<span class="jta-tweet-location">' + ' from ' + '<a class="jta-tweet-location-link" href="' + link + '" target="_blank">' + location + '</a>' + '</span>'; } return html; }; defaultTweetInReplyToDecorator = function(tweet, options) { // if tweet is a native retweet, use the retweet's source var tw = tweet.retweeted_status || tweet; var html = ''; if (tw.in_reply_to_status_id && tw.in_reply_to_screen_name) { html = '<span class="jta-tweet-inreplyto">' + ' ' + '<a class="jta-tweet-inreplyto-link" href="http://twitter.com/' + tw.in_reply_to_screen_name + '/status/' + tw.in_reply_to_status_id + '" target="_blank">' + 'in reply to ' + tw.in_reply_to_screen_name + '</a>' + '</span>'; } return html; }; defaultTweetRetweeterDecorator = function(tweet, options) { var html = ''; if (tweet.retweeted_status) { var screenName = tweet.user ? tweet.user.screen_name : false || tweet.from_user; var rtc = (tweet.retweeted_status.retweet_count || 0) - 1; var link = '<a class="jta-tweet-retweeter-link" href="http://twitter.com/' + screenName + '" target="_blank">' + screenName + '</a>'; var rtcount = ' and ' + rtc + (rtc > 1 ? ' others' : ' other'); html = '<br/>' + '<span class="jta-tweet-retweeter">' + 'Retweeted by ' + link + (rtc > 0 ? rtcount : '') + '</span>'; } return html; }; defaultConnectButtonDecorator = function(options) { // the default placeholder for the @Anywhere ConnectButton return '<div class="jta-connect-button"></div>'; }; defaultLoginInfoDecorator = function(options) { // the default placeholder for the LoginInfo return '<div class="jta-login-info"></div>'; }; defaultLoginInfoContentDecorator = function(options, T) { // the default markup of the LoginInfo content: the user's profile image, the // user's screen_name and a "button" to sign out var html = ''; if (T.isConnected()) { var screenName = T.currentUser.data('screen_name'); var imageUrl = T.currentUser.data('profile_image_url'); html = '<div class="jta-login-info-profile-image">' + '<a href="http://twitter.com/' + screenName + '" target="_blank">' + '<img src="' + imageUrl + '" alt="' + screenName + '" title="' + screenName + '"/>' + '</a>' + '</div>' + '<div class="jta-login-info-block">' + '<div class="jta-login-info-screen-name">' + '<a href="http://twitter.com/' + screenName + '" target="_blank">' + screenName + '</a>' + '</div>' + '<div class="jta-login-info-sign-out">' + 'Sign out' + '</div>' + '</div>' + '<div class="jta-clear">&nbsp;</div>' ; } return html; }; defaultFollowButtonDecorator = function(options) { // the default placeholder for the @Anywhere FollowButton return '<div class="jta-follow-button"></div>'; }; defaultTweetBoxDecorator = function(options) { // the default placeholder for the @Anywhere TweetBox return '<div class="jta-tweet-box"></div>'; }; defaultLinkDecorator = function(text, options) { // the regex to markup links return text.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1" class="jta-tweet-a jta-tweet-link" target="_blank" rel="nofollow">$1<\/a>'); }; defaultUsernameDecorator = function(text, options) { // the regex to markup @usernames. if @Anywhere is present the task is left to // them return isAnywherePresent() ? text : text.replace(/@([a-zA-Z0-9_]+)/gi,'@<a href="http://twitter.com/$1" class="jta-tweet-a twitter-anywhere-user" target="_blank" rel="nofollow">$1<\/a>'); }; defaultHashtagDecorator = function(text, options) { // the regex to markup #hashtags return text.replace(/#([a-zA-Z0-9_]+)/gi,'<a href="http://search.twitter.com/search?q=%23$1" class="jta-tweet-a jta-tweet-hashtag" title="#$1" target="_blank" rel="nofollow">#$1<\/a>'); }; defaultLoadingDecorator = function(options) { // the default loading decorator simply says: loading ... return '<li class="jta-loading">loading ...</li>'; }; defaultErrorDecorator = function(errorText, options) { // the default error decorator shows the error message return '<li class="jta-error">ERROR: ' + errorText + '</li>'; }; defaultNoDataDecorator = function(options) { // the default no-data decorator simply says: No more data return '<li class="jta-nodata">No more data</li>'; }; defaultTweetFilter = function(tweet, options) { return true; }; defaultTweetVisualizer = function(tweetFeedElement, tweetElement, inserter, options) { // insert (append/prepend) the tweetElement to the tweetFeedElement tweetFeedElement[inserter](tweetElement); }; defaultLoadingIndicatorVisualizer = function(tweetFeedElement, loadingIndicatorElement, options, callback) { defaultVisualizer(tweetFeedElement, loadingIndicatorElement, 'append', 'fadeIn', 600, 'fadeOut', 200, callback); }; defaultAutorefreshTriggerVisualizer = function(tweetFeedElement, triggerElement, options, callback) { defaultVisualizer(tweetFeedElement, triggerElement, 'prepend', 'slideDown', 600, 'fadeOut', 200, callback); }; defaultVisualizer = function(container, element, inserter, effectIn, durationIn, effectOut, durationOut, callback) { // if param container is null element has to be removed from // the DOM, else element has to be inserted in container // if param callback is not null, the callback function must be called // in any case, if the visualizer is done var cb = function() { if (callback) { callback(); } }; if (container) { element.hide(); container[inserter](element); element[effectIn](durationIn, cb); } else { element[effectOut](durationOut, function() { element.remove(); cb(); }); } }; defaultOnDataRequestHandler = function(stats, options) { return true; }; defaultOnRateLimitDataHandler = function(stats, options) { }; updateLoginInfoElement = function(options, T) { // update the content of the LoginInfo element if (options._loginInfoElement && options.loginInfoContentDecorator) { options._loginInfoElement.children().remove(); options._loginInfoElement.append(options.loginInfoContentDecorator(options, T)); $(options._baseSelector + ' .jta-login-info-sign-out').bind('click', function() { twttr.anywhere.signOut(); }); } }; getFeedUrl = function(options, flPaging) { // create the Twitter API URL based on the configuration options var url = ('https:' == document.location.protocol ? 'https:' : 'http:'); if (options.searchParams) { url += '//search.twitter.com/search.json?' + ((options.searchParams instanceof Array) ? options.searchParams.join('&') : options.searchParams) + '&rpp=100'; } else if (options.list) { url += '//api.twitter.com/1/' + options.username + '/lists/' + options.list + '/statuses.json?per_page=20'; } else { url += '//api.twitter.com/1/statuses/user_timeline.json?screen_name=' + options.username + '&count=20'; if (options._tweetFeedConfig.includeRetweets) url += '&include_rts=true'; } if (flPaging) { url += (options._tweetFeedConfig._maxId ? '&max_id=' + options._tweetFeedConfig._maxId : '') + '&page=' + options._tweetFeedConfig._pageParam; } url += '&callback=?'; return url; }; isAnywherePresent = function() { // check, if @Anywhere is present return typeof(twttr) != 'undefined'; }; clearTweetFeed = function(options) { if (options._tweetFeedElement) { options._tweetFeedElement.empty(); } }; populateTweetFeed = function(options) { // if a tweet feed is to be displayed, get the tweets and show them if (options.tweetDecorator && options._tweetFeedElement) { getPagedTweets(options, function(tweets, options) { if (options._tweetFeedConfig._clearBeforePopulate) { clearTweetFeed(options); } hideLoadingIndicator(options, function() { // process the tweets $.each(tweets, function(idx, tweet) { // decorate the tweet and give it to the tweet visualizer options.tweetVisualizer( options._tweetFeedElement, $(options.tweetDecorator(tweet, options)), 'append', options ); }); if (options._tweetFeedConfig._noData && options.noDataDecorator && !options._tweetFeedConfig._noDataElement) { options._tweetFeedConfig._noDataElement = $(options.noDataDecorator(options)); options._tweetFeedElement.append(options._tweetFeedConfig._noDataElement); } if (options._tweetFeedConfig._clearBeforePopulate) { options._tweetFeedElement.scrollTop(0); } addHovercards(options); }); }); } }; populateTweetFeed2 = function(options) { if (options._tweetFeedElement && options._autorefreshTweetsCache.length > 0) { if (options._tweetFeedConfig.autorefresh.mode == 'trigger-insert') { if (options._tweetFeedConfig.autorefresh._triggerElement) { if (options.tweetFeedAutorefreshTriggerContentDecorator) { options._tweetFeedConfig.autorefresh._triggerElement.html( options.tweetFeedAutorefreshTriggerContentDecorator(options._autorefreshTweetsCache.length, options) ); } } else { if (options.tweetFeedAutorefreshTriggerDecorator) { options._tweetFeedConfig.autorefresh._triggerElement = $(options.tweetFeedAutorefreshTriggerDecorator(options._autorefreshTweetsCache.length, options)); options._tweetFeedConfig.autorefresh._triggerElement.bind('click', function() { options.autorefreshTriggerVisualizer( null, options._tweetFeedConfig.autorefresh._triggerElement, options, function() { insertTriggerTweets(options); } ); options._tweetFeedConfig.autorefresh._triggerElement = null; }); options.autorefreshTriggerVisualizer(options._tweetFeedElement, options._tweetFeedConfig.autorefresh._triggerElement, options); } } } else { insertTriggerTweets(options); } } }; insertTriggerTweets = function(options) { // populate the tweet feed with tweets from the autorefresh cache if (options.tweetDecorator && options._autorefreshTweetsCache.length > 0) { // process the autorefresh cache while (options._autorefreshTweetsCache.length > 0) { // get the last tweet and remove it from the autorefresh cache var tweet = options._autorefreshTweetsCache.pop(); // put that tweet on top of the tweets cache options._tweetsCache.unshift(tweet); // adjust paging offset options._tweetFeedConfig.paging._offset++; // decorate the tweet and give it to the tweet visualizer options.tweetVisualizer( options._tweetFeedElement, $(options.tweetDecorator(tweet, options)), 'prepend', options ); } addHovercards(options); } }; addHovercards = function(options) { if (isAnywherePresent()) { // if @Anywhere is present, append Hovercards to @username and // profile images twttr.anywhere(function(T) { T(options._baseSelector + ' .jta-tweet-list').hovercards({expanded: options._tweetFeedConfig.expandHovercards}); T(options._baseSelector + ' .jta-tweet-profile-image img').hovercards( { expanded: options._tweetFeedConfig.expandHovercards, username: function(node) { return node.alt; } }); T(options._baseSelector + ' .jta-tweet-retweeter-link').hovercards( { expanded: options._tweetFeedConfig.expandHovercards, username: function(node) { return node.text; } }); T(options._baseSelector + ' .jta-tweet-user-screen-name-link').hovercards( { expanded: options._tweetFeedConfig.expandHovercards, username: function(node) { return node.text; } }); T(options._baseSelector + ' .jta-tweet-user-full-name-link').hovercards( { expanded: options._tweetFeedConfig.expandHovercards, username: function(node) { return node.name; } }); }); } }; populateAnywhereControls = function(options) { if (isAnywherePresent()) { twttr.anywhere(function(T) { // optionally add an @Anywhere TweetBox if (options.tweetBoxDecorator) { T(options._baseSelector + ' .jta-tweet-box').tweetBox(options._tweetBoxConfig); } // optionally add an @Anywhere FollowButton if (options.followButtonDecorator) { T(options._baseSelector + ' .jta-follow-button').followButton(options.username); } // optionally add an @Anywhere ConnectButton if (options.connectButtonDecorator) { var o = $.extend( { authComplete: function(user) { // display/update login infos on connect/signin event updateLoginInfoElement(options, T); }, signOut: function() { // display/update login infos on signout event updateLoginInfoElement(options, T); } }, options._connectButtonConfig); T(options._baseSelector + ' .jta-connect-button').connectButton(o); // display/update login infos updateLoginInfoElement(options, T); } }); } }; bindEventHandlers = function(options) { if (options.tweetFeedControlsDecorator) { if (options._tweetFeedConfig.paging.mode == 'prev-next') { $(options._baseSelector + ' .jta-tweet-list-controls-button-prev').bind('click', function() { if (!isLoading(options) && options._tweetFeedConfig.paging._offset > 0) { prevPage(options, true); } }); $(options._baseSelector + ' .jta-tweet-list-controls-button-next').bind('click', function() { if (!isLoading(options)) { nextPage(options, true); } }); } else if (options._tweetFeedConfig.paging.mode == 'endless-scroll') { options._tweetFeedElement.bind("scroll", function() { if (!isLoading(options) && ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight())) { nextPage(options, false); } }); } else { $(options._baseSelector + ' .jta-tweet-list-controls-button-more').bind('click', function() { if (!isLoading(options)) { nextPage(options, false); } }); } } }; nextPage = function(options, flClear) { doPage(options, flClear, Math.min(options._tweetFeedConfig.paging._offset + options._tweetFeedConfig.paging._limit, options._tweetsCache.length)); }; prevPage = function(options, flClear) { doPage(options, flClear, Math.max(0, options._tweetFeedConfig.paging._offset - options._tweetFeedConfig.paging._limit)); }; doPage = function(options, flClear, newOffset) { options._tweetFeedConfig.paging._offset = newOffset; options._tweetFeedConfig._clearBeforePopulate = flClear; populateTweetFeed(options); }; startAutorefresh = function(options) { if (options._tweetFeedConfig.autorefresh.mode != 'none' && options._tweetFeedConfig.paging.mode != 'prev-next' && options._tweetFeedConfig.autorefresh.duration != 0 && ( options._tweetFeedConfig.autorefresh.duration < 0 || (new Date().getTime() - options._tweetFeedConfig.autorefresh._startTime) <= options._tweetFeedConfig.autorefresh.duration * 1000 ) ) { window.setTimeout(function() { processAutorefresh(options); }, options._tweetFeedConfig.autorefresh.interval * 1000); } }; stopAutorefresh = function(options) { options._tweetFeedConfig.autorefresh.duration = 0; }; processAutorefresh = function(options) { if (options._tweetFeedConfig.autorefresh.duration != 0) { // load the data ... getRateLimitedData(options, true, getFeedUrl(options, false), function(data, options) { // reverse the sequence of the autorefresh tweets ... var tweets = (data.results || data).slice(0); tweets.reverse(); // ...then process them $.each(tweets, function(idx, tweet) { // if this tweet is already in the standard tweets cache, ignore if (!isTweetInCache(tweet, options)) { // optionally filter tweet ... if (options.tweetFilter(tweet, options)) { // ... then put it to the top of the autorefresh cache options._autorefreshTweetsCache.unshift(tweet); } } }); populateTweetFeed2(options); }); // restart autorefresh startAutorefresh(options); } }; startTimestampRefresh = function(options) { if ( options.tweetTimestampDecorator && typeof(options._tweetFeedConfig.showTimestamp) == 'object' && options._tweetFeedConfig.showTimestamp.refreshInterval > 0 ) { window.setTimeout(function() { processTimestampRefresh(options); }, options._tweetFeedConfig.showTimestamp.refreshInterval * 1000); } }; processTimestampRefresh = function(options) { $.each(options._tweetFeedElement.find('.jta-tweet-timestamp-link'), function(idx, element) { var dataTimestamp = $(element).attr('data-timestamp'); $(element).html(options.tweetTimestampFormatter(dataTimestamp)); }); startTimestampRefresh(options); }; isTweetInCache = function(tweet, options) { var l = options._tweetsCache.length; for (var i = 0; i < l; i++) { if (tweet.id == options._tweetsCache[i].id) { return true; } } return false; }; showLoadingIndicator = function(options) { if (options._tweetFeedElement && options.loadingDecorator && !options._loadingIndicatorElement) { options._loadingIndicatorElement = $(options.loadingDecorator(options)); options.loadingIndicatorVisualizer(options._tweetFeedElement, options._loadingIndicatorElement, options, null); options._tweetFeedElement.scrollTop(1000000); } }; hideLoadingIndicator = function(options, callback) { if (options._loadingIndicatorElement) { options.loadingIndicatorVisualizer(null, options._loadingIndicatorElement, options, callback); options._loadingIndicatorElement = null; } else { if (callback) { callback(); } } }; isLoading = function(options) { return options._loadingIndicatorElement != null; }; formatDate = function(dateStr) { return dateStr.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'); }; validateRange = function(num, lo, hi) { if (num < lo) num = lo; if (num > hi) num = hi; return num; }; showError = function(options, errorText) { if (options.errorDecorator && options._tweetFeedElement) { options._tweetFeedElement.append(options.errorDecorator(errorText, options)); } }; getPagedTweets = function(options, callback) { options._tweetFeedConfig._recLevel = 0; getRecPagedTweets(options, options._tweetFeedConfig.paging._offset, options._tweetFeedConfig.paging._limit, callback); }; getRecPagedTweets = function(options, offset, limit, callback) { ++options._tweetFeedConfig._recLevel; if (offset + limit <= options._tweetsCache.length || options._tweetFeedConfig._recLevel > 3 || options._tweetFeedConfig._noData ) { // if the requested data is already cached or the max. no. of // consecutive API calls is reached, use the records if (offset + limit > options._tweetsCache.length) { limit = Math.max(0, options._tweetsCache.length - offset); } var tweets = []; for (var i = 0; i < limit; i++) { tweets[i] = options._tweetsCache[offset + i]; } callback(tweets, options); } else { // ... if not, load the data, fill the cache and try again ++options._tweetFeedConfig._pageParam; getRateLimitedData(options, false, getFeedUrl(options, true), function(data, options) { var tweets = data.results || data; if (tweets.length == 0) { options._tweetFeedConfig._noData = true; } else { $.each(tweets, function(idx, tweet) { // Snowflake support: just update ids that are currently used if (tweet.id_str) { tweet.id = tweet.id_str; } if (tweet.in_reply_to_status_id_str) { tweet.in_reply_to_status_id = tweet.in_reply_to_status_id_str; } // save the first tweet id for subsequent paging requests if (!options._tweetFeedConfig._maxId) { options._tweetFeedConfig._maxId = tweet.id; } // optionally filter tweet ... if (options.tweetFilter(tweet, options)) { // then put it into the cache options._tweetsCache.push(tweet); } }); } getRecPagedTweets(options, offset, limit, callback); }); } }; getRateLimitedData = function(options, flAutorefresh, url, callback) { getRateLimit(options, function(rateLimit) { if (rateLimit && rateLimit.remaining_hits <= 0) { options._stats.rateLimitPreventionCount++; hideLoadingIndicator(options, null); return; } getData(options, flAutorefresh, url, callback); }); }; getData = function(options, flAutorefresh, url, callback) { options._stats.dataRequestCount++; if (!options.onDataRequestHandler(options._stats, options)) { hideLoadingIndicator(options, null); return; } if (!flAutorefresh) { showLoadingIndicator(options); } $.getJSON(url, function(data) { if (data.error) { // in case of an error, display the error message showError(options, data.error); } else { callback(data, options); } }); }; getRateLimit = function(options, callback) { $.getJSON("http://api.twitter.com/1/account/rate_limit_status.json?callback=?", function(rateLimit) { options._stats.rateLimit = rateLimit; options.onRateLimitDataHandler(options._stats, options); callback(rateLimit); }); }; })(jQuery);
JavaScript
// ここにメインエンジン /* グローバル変数 */ // Twitter関連 var consumerKey = "uVQoMFwJuwSNJ7s4IECwA"; var consumerSecret = "Q6puiy2c3PLjQVs7qCrR0CahHcESXqzeTjgHl4E"; var accessToken = undefined; var accessTokenSecret = undefined; var T = undefined; function init() { twttr.anywhere(onAnywhereLoad); function onAnywhereLoad(twitter) { //twitter.linkifyUsers(); T = twitter; if (twitter.isConnected()) { //sencha_init(); $("#debug").append('<button id="signout" onclick="twttr.anywhere.signOut();" type="button">Sign out of Twitter</button>'); //screenName = twitter.currentUser.data("screen_name"); //$("#debug").append($("<p>").text("ScreenName: "+screenName)); //T("#debug").tweetBox({ height: 100, width: 400, defaultContent: "<YOUR DEFAULT TWEETBOX CONTENT HERE>" }); }else { T("#debug").connectButton({ authComplete: function(user) { // triggered when auth completed successfully location.reload(); }, signOut: function() { // triggered when user logs out } }); } }; } function sencha_init() { Ext.setup({ icon: 'img/icon.png', glossOnIcon: false }); var timeline = new Ext.Component({ title: 'Twitter', cls: 'twitter_tl', scroll: 'vertical', tpl: [ '<tpl for=".">', '<div class="tweet">', '<div class="avatar"><img src="{profile_image_url}" /></div>', '<div class="tweet-content">', '<h2>{from_user}</h2>', '<p>{text}</p>', '</div>', '</div>', '</tpl>' ] }); /*var map = new Ext.Map({ title: 'Map', getLocation: true, mapOptions: { zoom: 12 } });*/ var panel = new Ext.TabPanel({ fullscreen: true, animation: 'slide', items: [timeline] }); var refresh = function() { ; } /*var refresh = function() { var coords = map.geo.coords; Ext.util.JSONP.request({ url: 'http://search.twitter.com/search.json', callbackKey: 'callback', params: { geocode: coords.latitude + ',' + coords.longitude + ',' + '5mi', rpp: 30 }, callback: function(data) { data = data.results; // タイムラインのツイートを更新 timeline.update(data); // 地図にマーカーを追加 for (var i = 0, ln = data.length; i < ln; i++) { var tweet = data[i]; // If the tweet is geo-tagged, use that to display marker if (tweet.geo && tweet.geo.coordinates) { var position = new google.maps.LatLng(tweet.geo.coordinates[0], tweet.geo.coordinates[1]); addMarker(tweet, position); } } } }); };*/ // 以下は全てGoogle MapsのAPI /*var addMarker = function(tweet, position) { var marker = new google.maps.Marker({ map: map.map, position: position }); };*/ //map.geo.on('update', refresh); /*var tabBar = panel.getTabBar(); tabBar.addDocked({ xtype: 'button', ui: 'mask', iconCls: 'refresh', dock: 'right', stretch: false, align: 'center', handler: refresh });*/ }
JavaScript
(function(root) { var $ = root.jQuery; var BlockCookieName = 'azk-blocks'; var VoteEvent = { upvote: 10, downvote: 11, uninteresting: 12, misleading: 13, offensive: 14, repetitive: 15, other: 16, close: 17 }; var VotingMode = { downUp: 1, closeAd: 2 } root.azRegisterExtension('adFeedback', function(divName, pixels, mode) { if ($ === undefined) return; var ad = $('#' + divName); var voteInProgress = false; var voteComplete = false; var castVoteForThisCreative = function(type) { if (pixels[type] !== undefined) { $('body').append("<img src='" + pixels[type] + "' height=0 width=0 />"); } }; $(function() { switch(mode){ case VotingMode.closeAd: /* Custom "close button" elements are possible, in 2 ways: 1. Include an element on the page template with a class of '.adzerk-custom-close-button' -- this will be cloned and placed in the top-right corner in lieu of the 'X'. 2. Include an element in the HTML of the ad itself with a class of '.adzerk-custom-close-button' -- this will become the close button itself, regardless of where it is on the ad and mouse hover status. If no custom close button is found, the default behavior is an 'X' that fades in on mouse hover. */ // tries 8 times, spaced apart 250ms, to find a custom button; // defaults to the 'X' if no custom button is found var tries = 8; findCustomButton(); function findCustomButton() { if (tries > 0) { var searchIFrame = $('iframe').contents().find('.adzerk-custom-close-button'); if (searchIFrame.length) { useCustomButton(searchIFrame); return; } var searchPage = $('.adzerk-custom-close-button'); if (searchPage.length) { searchPage.hide(); var buttonHtml = $('<div>').append(searchPage.clone().show()).html(); showCloseControl(buttonHtml); return; } tries--; window.setTimeout(findCustomButton, 250); } else { showDefaultCloseControl(); } } function useCustomButton(button) { ad.addClass('adzerk-vote'); useAsCloseControl(button); } function showCloseControl(buttonHtml) { ad.addClass('adzerk-vote').append( "<div class='adzerk-close-control' style='display:none;'>" + buttonHtml + "</div>"); control = $('.adzerk-close-control'); showOnHover(control); useAsCloseControl(control); } function showDefaultCloseControl() { showCloseControl("<div class='adzerk-close-button'></div>"); } function showOnHover(control) { ad.hover( function() { if (!voteInProgress) { control.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { control.stop(true, true).fadeOut(250); } } ); } function useAsCloseControl(control) { // When clicked, downvote the ad and collapse the div control.click(function() { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(VoteEvent.close); ad.fadeOut(); }); } break; case VotingMode.downUp: default: ad.addClass('adzerk-vote').append( "<div class='adzerk-vote-controls' style='display:none;'>" + "<div class='adzerk-vote-option adzerk-vote-up'><div class='adzerk-vote-icon'></div></div>" + "<div class='adzerk-vote-option adzerk-vote-down'><div class='adzerk-vote-icon'></div></div>" + "</div>" + "<div class='adzerk-vote-survey' style='display:none;'>" + "<form>" + "<span>No problem. We won't show you that ad again. Why didn't you like it?</span>" + "<ul>" + "<li><label><input type='radio' value='" + VoteEvent.uninteresting + "' name='downvoteReason' />Uninteresting</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.misleading + "' name='downvoteReason' />Misleading</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.offensive + "' name='downvoteReason' />Offensive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.repetitive + "' name='downvoteReason' />Repetitive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.other + "' name='downvoteReason' />Other</label></li>" + "</ul>" + "<a href='#' class='adzerk-vote-cancel'>Oops! I didn't mean to do this.</a>" + "</form>" + "</div>"); var controls = ad.find(".adzerk-vote-controls"); var survey = ad.find(".adzerk-vote-survey"); var showResponse = function() { voteInProgress = false; voteComplete = true; survey.hide(); var thanks = $("<div class='adzerk-vote-response'>Thanks!</div>"); thanks.appendTo(controls).hide().fadeIn(250).delay(3000).fadeOut(250, function() { $(this).remove(); }); }; // Show vote controls when hovering over ad ad.hover( function() { if (!voteInProgress) { controls.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { controls.stop(true, true).fadeOut(250); } } ); // When up arrow is clicked, display a thank you message controls.find(".adzerk-vote-up").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); castVoteForThisCreative(VoteEvent.upvote); showResponse(); } return false; }); // When down arrow is clicked, display the survey to ask why the user didn't like the ad controls.find(".adzerk-vote-down").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); voteInProgress = true; survey.fadeIn(250); } return false; }); survey.find(".adzerk-vote-cancel").click(function() { controls.children("div").removeClass("selected"); voteInProgress = false; survey.fadeOut(250); return false; }); // When a survey option is selected, show a brief thank you and then hide it survey.find("li").click(function() { var vote = survey.find("input:checked").val() if (vote) { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(vote); showResponse(); } }); } }); }); })(this);
JavaScript
(function(root) { var $ = root.jQuery; var BlockCookieName = 'azk-blocks'; var VoteEvent = { upvote: 10, downvote: 11, uninteresting: 12, misleading: 13, offensive: 14, repetitive: 15, other: 16, close: 17 }; var VotingMode = { downUp: 1, closeAd: 2 } root.azRegisterExtension('adFeedback', function(divName, pixels, mode) { if ($ === undefined) return; var ad = $('#' + divName); var voteInProgress = false; var voteComplete = false; var castVoteForThisCreative = function(type) { if (pixels[type] !== undefined) { $('body').append("<img src='" + pixels[type] + "' height=0 width=0 />"); } }; $(function() { switch(mode){ case VotingMode.closeAd: /* Custom "close button" elements are possible, in 2 ways: 1. Include an element on the page template with a class of '.adzerk-custom-close-button' -- this will be cloned and placed in the top-right corner in lieu of the 'X'. 2. Include an element in the HTML of the ad itself with a class of '.adzerk-custom-close-button' -- this will become the close button itself, regardless of where it is on the ad and mouse hover status. If no custom close button is found, the default behavior is an 'X' that fades in on mouse hover. */ // tries 8 times, spaced apart 250ms, to find a custom button; // defaults to the 'X' if no custom button is found var tries = 8; findCustomButton(); function findCustomButton() { if (tries > 0) { var searchIFrame = $('iframe').contents().find('.adzerk-custom-close-button'); if (searchIFrame.length) { useCustomButton(searchIFrame); return; } var searchPage = $('.adzerk-custom-close-button'); if (searchPage.length) { searchPage.hide(); var buttonHtml = $('<div>').append(searchPage.clone().show()).html(); showCloseControl(buttonHtml); return; } tries--; window.setTimeout(findCustomButton, 250); } else { showDefaultCloseControl(); } } function useCustomButton(button) { ad.addClass('adzerk-vote'); useAsCloseControl(button); } function showCloseControl(buttonHtml) { ad.addClass('adzerk-vote').append( "<div class='adzerk-close-control' style='display:none;'>" + buttonHtml + "</div>"); control = $('.adzerk-close-control'); showOnHover(control); useAsCloseControl(control); } function showDefaultCloseControl() { showCloseControl("<div class='adzerk-close-button'></div>"); } function showOnHover(control) { ad.hover( function() { if (!voteInProgress) { control.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { control.stop(true, true).fadeOut(250); } } ); } function useAsCloseControl(control) { // When clicked, downvote the ad and collapse the div control.click(function() { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(VoteEvent.close); ad.fadeOut(); }); } break; case VotingMode.downUp: default: ad.addClass('adzerk-vote').append( "<div class='adzerk-vote-controls' style='display:none;'>" + "<div class='adzerk-vote-option adzerk-vote-up'><div class='adzerk-vote-icon'></div></div>" + "<div class='adzerk-vote-option adzerk-vote-down'><div class='adzerk-vote-icon'></div></div>" + "</div>" + "<div class='adzerk-vote-survey' style='display:none;'>" + "<form>" + "<span>No problem. We won't show you that ad again. Why didn't you like it?</span>" + "<ul>" + "<li><label><input type='radio' value='" + VoteEvent.uninteresting + "' name='downvoteReason' />Uninteresting</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.misleading + "' name='downvoteReason' />Misleading</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.offensive + "' name='downvoteReason' />Offensive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.repetitive + "' name='downvoteReason' />Repetitive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.other + "' name='downvoteReason' />Other</label></li>" + "</ul>" + "<a href='#' class='adzerk-vote-cancel'>Oops! I didn't mean to do this.</a>" + "</form>" + "</div>"); var controls = ad.find(".adzerk-vote-controls"); var survey = ad.find(".adzerk-vote-survey"); var showResponse = function() { voteInProgress = false; voteComplete = true; survey.hide(); var thanks = $("<div class='adzerk-vote-response'>Thanks!</div>"); thanks.appendTo(controls).hide().fadeIn(250).delay(3000).fadeOut(250, function() { $(this).remove(); }); }; // Show vote controls when hovering over ad ad.hover( function() { if (!voteInProgress) { controls.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { controls.stop(true, true).fadeOut(250); } } ); // When up arrow is clicked, display a thank you message controls.find(".adzerk-vote-up").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); castVoteForThisCreative(VoteEvent.upvote); showResponse(); } return false; }); // When down arrow is clicked, display the survey to ask why the user didn't like the ad controls.find(".adzerk-vote-down").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); voteInProgress = true; survey.fadeIn(250); } return false; }); survey.find(".adzerk-vote-cancel").click(function() { controls.children("div").removeClass("selected"); voteInProgress = false; survey.fadeOut(250); return false; }); // When a survey option is selected, show a brief thank you and then hide it survey.find("li").click(function() { var vote = survey.find("input:checked").val() if (vote) { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(vote); showResponse(); } }); } }); }); })(this);
JavaScript
(function(root) { var $ = root.jQuery; var BlockCookieName = 'azk-blocks'; var VoteEvent = { upvote: 10, downvote: 11, uninteresting: 12, misleading: 13, offensive: 14, repetitive: 15, other: 16, close: 17 }; var VotingMode = { downUp: 1, closeAd: 2 } root.azRegisterExtension('adFeedback', function(divName, pixels, mode) { if ($ === undefined) return; var ad = $('#' + divName); var voteInProgress = false; var voteComplete = false; var castVoteForThisCreative = function(type) { if (pixels[type] !== undefined) { $('body').append("<img src='" + pixels[type] + "' height=0 width=0 />"); } }; $(function() { switch(mode){ case VotingMode.closeAd: /* Custom "close button" elements are possible, in 2 ways: 1. Include an element on the page template with a class of '.adzerk-custom-close-button' -- this will be cloned and placed in the top-right corner in lieu of the 'X'. 2. Include an element in the HTML of the ad itself with a class of '.adzerk-custom-close-button' -- this will become the close button itself, regardless of where it is on the ad and mouse hover status. If no custom close button is found, the default behavior is an 'X' that fades in on mouse hover. */ // tries 8 times, spaced apart 250ms, to find a custom button; // defaults to the 'X' if no custom button is found var tries = 8; findCustomButton(); function findCustomButton() { if (tries > 0) { var searchIFrame = $('iframe').contents().find('.adzerk-custom-close-button'); if (searchIFrame.length) { useCustomButton(searchIFrame); return; } var searchPage = $('.adzerk-custom-close-button'); if (searchPage.length) { searchPage.hide(); var buttonHtml = $('<div>').append(searchPage.clone().show()).html(); showCloseControl(buttonHtml); return; } tries--; window.setTimeout(findCustomButton, 250); } else { showDefaultCloseControl(); } } function useCustomButton(button) { ad.addClass('adzerk-vote'); useAsCloseControl(button); } function showCloseControl(buttonHtml) { ad.addClass('adzerk-vote').append( "<div class='adzerk-close-control' style='display:none;'>" + buttonHtml + "</div>"); control = $('.adzerk-close-control'); showOnHover(control); useAsCloseControl(control); } function showDefaultCloseControl() { showCloseControl("<div class='adzerk-close-button'></div>"); } function showOnHover(control) { ad.hover( function() { if (!voteInProgress) { control.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { control.stop(true, true).fadeOut(250); } } ); } function useAsCloseControl(control) { // When clicked, downvote the ad and collapse the div control.click(function() { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(VoteEvent.close); ad.fadeOut(); }); } break; case VotingMode.downUp: default: ad.addClass('adzerk-vote').append( "<div class='adzerk-vote-controls' style='display:none;'>" + "<div class='adzerk-vote-option adzerk-vote-up'><div class='adzerk-vote-icon'></div></div>" + "<div class='adzerk-vote-option adzerk-vote-down'><div class='adzerk-vote-icon'></div></div>" + "</div>" + "<div class='adzerk-vote-survey' style='display:none;'>" + "<form>" + "<span>No problem. We won't show you that ad again. Why didn't you like it?</span>" + "<ul>" + "<li><label><input type='radio' value='" + VoteEvent.uninteresting + "' name='downvoteReason' />Uninteresting</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.misleading + "' name='downvoteReason' />Misleading</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.offensive + "' name='downvoteReason' />Offensive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.repetitive + "' name='downvoteReason' />Repetitive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.other + "' name='downvoteReason' />Other</label></li>" + "</ul>" + "<a href='#' class='adzerk-vote-cancel'>Oops! I didn't mean to do this.</a>" + "</form>" + "</div>"); var controls = ad.find(".adzerk-vote-controls"); var survey = ad.find(".adzerk-vote-survey"); var showResponse = function() { voteInProgress = false; voteComplete = true; survey.hide(); var thanks = $("<div class='adzerk-vote-response'>Thanks!</div>"); thanks.appendTo(controls).hide().fadeIn(250).delay(3000).fadeOut(250, function() { $(this).remove(); }); }; // Show vote controls when hovering over ad ad.hover( function() { if (!voteInProgress) { controls.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { controls.stop(true, true).fadeOut(250); } } ); // When up arrow is clicked, display a thank you message controls.find(".adzerk-vote-up").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); castVoteForThisCreative(VoteEvent.upvote); showResponse(); } return false; }); // When down arrow is clicked, display the survey to ask why the user didn't like the ad controls.find(".adzerk-vote-down").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); voteInProgress = true; survey.fadeIn(250); } return false; }); survey.find(".adzerk-vote-cancel").click(function() { controls.children("div").removeClass("selected"); voteInProgress = false; survey.fadeOut(250); return false; }); // When a survey option is selected, show a brief thank you and then hide it survey.find("li").click(function() { var vote = survey.find("input:checked").val() if (vote) { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(vote); showResponse(); } }); } }); }); })(this);
JavaScript
/*! AutoResize v1.18.4 - 2014-01-11 Automatically adjust textarea height based on user input. (c) 2014 Jack Moore - http://www.jacklmoore.com/autosize Originally altered by mdawaffe. Current version altered by pento. license: http://www.opensource.org/licenses/mit-license.php */ (function ($) { var defaults = { className: 'autosizejs', append: '', callback: false, resizeDelay: 10, placeholder: true, animate: true, animateDuration: 150, animateCallback: function(){}, extraSpace: 20 }, // border:0 is unnecessary, but avoids a bug in Firefox on OSX copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box; word-wrap:break-word; height:0 !important; min-height:0 !important; overflow:hidden; transition:none; -webkit-transition:none; -moz-transition:none;"/>', // line-height is conditionally included because IE7/IE8/old Opera do not return the correct value. typographyStyles = [ 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'letterSpacing', 'textTransform', 'textDecoration', 'wordSpacing', 'textIndent' ], // to keep track which textarea is being mirrored when adjust() is called. mirrored, // the mirror element, which is used to calculate what size the mirrored element should be. mirror = $(copy).data('autosize', true)[0]; // test that line-height can be accurately copied. mirror.style.lineHeight = '99px'; if ($(mirror).css('lineHeight') === '99px') { typographyStyles.push('lineHeight'); } mirror.style.lineHeight = ''; $.fn.autoResize = function (options) { if (!this.length) { return this; } options = $.extend({}, defaults, options || {}); if (mirror.parentNode !== this.parentNode) { $(mirror).insertBefore(this); } return this.each(function () { var ta = this, $ta = $(ta), maxHeight, minHeight, boxOffset = 0, callback = $.isFunction(options.callback), originalStyles = { height: ta.style.height, overflow: ta.style.overflow, overflowY: ta.style.overflowY, wordWrap: ta.style.wordWrap, resize: ta.style.resize }, timeout, width = $ta.width(); if ($ta.data('autosize')) { // exit if autosize has already been applied, or if the textarea is the mirror element. return; } $ta.data('autosize', true); if ($ta.css('box-sizing') === 'border-box' || $ta.css('-moz-box-sizing') === 'border-box' || $ta.css('-webkit-box-sizing') === 'border-box'){ boxOffset = $ta.outerHeight() - $ta.height(); } // IE8 and lower return 'auto', which parses to NaN, if no min-height is set. minHeight = Math.max(parseInt($ta.css('minHeight'), 10) - boxOffset || 0, $ta.height()); $ta.css({ overflow: 'hidden', overflowY: 'hidden', wordWrap: 'break-word', // horizontal overflow is hidden, so break-word is necessary for handling words longer than the textarea width resize: ($ta.css('resize') === 'none' || $ta.css('resize') === 'vertical') ? 'none' : 'horizontal' }); // The mirror width must exactly match the textarea width, so using getBoundingClientRect because it doesn't round the sub-pixel value. // window.getComputedStyle, getBoundingClientRect returning a width are unsupported, but also unneeded in IE8 and lower. function setWidth() { var width; var style = window.getComputedStyle ? window.getComputedStyle(ta, null) : false; if (style) { width = ta.getBoundingClientRect().width; if (width === 0) { width = parseInt(style.width,10); } $.each(['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'], function(i,val){ width -= parseInt(style[val],10); }); } else { width = Math.max($ta.width(), 0); } mirror.style.width = width + 'px'; } function initMirror() { var styles = {}; mirrored = ta; mirror.className = options.className + " " + ta.className; maxHeight = parseInt($ta.css('maxHeight'), 10); // mirror is a duplicate textarea located off-screen that // is automatically updated to contain the same text as the // original textarea. mirror always has a height of 0. // This gives a cross-browser supported way getting the actual // height of the text, through the scrollTop property. $.each(typographyStyles, function(i,val){ styles[val] = $ta.css(val); }); $(mirror).css(styles); setWidth(); // Chrome-specific fix: // When the textarea y-overflow is hidden, Chrome doesn't reflow the text to account for the space // made available by removing the scrollbar. This workaround triggers the reflow for Chrome. if (window.chrome) { var width = ta.style.width; ta.style.width = '0px'; var ignore = ta.offsetWidth; ta.style.width = width; } } // Using mainly bare JS in this function because it is going // to fire very often while typing, and needs to very efficient. function adjust() { var height, original; if (mirrored !== ta) { initMirror(); } else { setWidth(); } if (!ta.value && options.placeholder) { // If the textarea is empty, copy the placeholder text into // the mirror control and use that for sizing so that we // don't end up with placeholder getting trimmed. mirror.value = ($ta.attr("placeholder") || '') + options.append; } else { mirror.value = ta.value + options.append; } mirror.style.overflowY = ta.style.overflowY; original = parseInt(ta.style.height,10); // Setting scrollTop to zero is needed in IE8 and lower for the next step to be accurately applied mirror.scrollTop = 0; mirror.scrollTop = 9e4; // Using scrollTop rather than scrollHeight because scrollHeight is non-standard and includes padding. height = mirror.scrollTop + options.extraSpace; if (maxHeight && height > maxHeight) { ta.style.overflowY = 'scroll'; height = maxHeight; } else { ta.style.overflowY = 'hidden'; if (height < minHeight) { height = minHeight; } } height += boxOffset; height = Math.floor( height ); if (original !== height) { if ( options.animate && $ta.css( 'display' ) === 'block' ) { $ta.stop().animate( {height: height}, options.animateDuration, options.animateCallback ); } else { ta.style.height = height + 'px'; options.animateCallback.call( this ); } if (callback) { options.callback.call(ta,ta); } } } function resize () { clearTimeout(timeout); timeout = setTimeout(function(){ var newWidth = $ta.width(); if (newWidth !== width) { width = newWidth; adjust(); } }, parseInt(options.resizeDelay,10)); } if ('onpropertychange' in ta) { if ('oninput' in ta) { // Detects IE9. IE9 does not fire onpropertychange or oninput for deletions, // so binding to onkeyup to catch most of those occasions. There is no way that I // know of to detect something like 'cut' in IE9. $ta.on('input.autosize keyup.autosize', adjust); } else { // IE7 / IE8 $ta.on('propertychange.autosize', function(){ if(event.propertyName === 'value'){ adjust(); } }); } } else { // Modern Browsers $ta.on('input.autosize', adjust); } // Set options.resizeDelay to false if using fixed-width textarea elements. // Uses a timeout and width check to reduce the amount of times adjust needs to be called after window resize. if (options.resizeDelay !== false) { $(window).on('resize.autosize', resize); } // Event for manual triggering if needed. // Should only be needed when the value of the textarea is changed through JavaScript rather than user input. $ta.on('autosize.resize', adjust); // Event for manual triggering that also forces the styles to update as well. // Should only be needed if one of typography styles of the textarea change, and the textarea is already the target of the adjust method. $ta.on('autosize.resizeIncludeStyle', function() { mirrored = null; adjust(); }); $ta.on('autosize.destroy', function(){ mirrored = null; clearTimeout(timeout); $(window).off('resize', resize); $ta .off('autosize') .off('.autosize') .css(originalStyles) .removeData('autosize'); }); // Call adjust in case the textarea already contains text. adjust(); }); }; }(window.jQuery || window.$)); // jQuery or jQuery-like library, such as Zepto ; var HighlanderComments = jQuery.extend( HighlanderComments, { autosaveInterval: false, commentList: null, initialHeight: 70, cookies: { facebook: 'wpc_fbc', twitter: 'wpc_tc', wordpress: 'wpc_wpc', googleplus: 'wpc_gpc' }, popups: { facebook: ',height=400,width=600', twitter: ',height=515,width=600', wordpress: ',height=500,width=500' }, temp_cookie_data: '', currentParent: false, currentParentId: false, currentParentMargins: {}, resizeCallback: function() {}, init : function() { jQuery( '#respond' ).addClass( 'js' ); HighlanderComments.commentList = jQuery( '#thecomments, .thecomments, #commentlist, #comment-list, #comments-list, .commentlist, .comment-list, .comments-list, .com-list, #comments' ).last(); jQuery( '#comment-form-nascar a' ).click( HighlanderComments.clickService ); jQuery( '#postas-wordpress' ).click( HighlanderComments.clickExternalTab ); jQuery( '#postas-facebook, #labelto-facebook' ).click( HighlanderComments.clickExternalTab ); jQuery( '#postas-twitter, #labelto-twitter' ).click( HighlanderComments.clickExternalTab ); pm.bind( 'googlePlusButtonClick', HighlanderComments.onGooglePlusButtonClick, 'https://public-api.wordpress.com' ); pm.bind( 'googlePlusSignIn', HighlanderComments.onGooglePlusSignIn, 'https://public-api.wordpress.com' ); jQuery( '#labelto-wordpress' ).click( HighlanderComments.checkPostToWordPress ); jQuery( '#comment-form-post-to-edit a' ).click( HighlanderComments.editShareText ); jQuery( window ).resize( HighlanderComments.toggleShareLabels ); HighlanderComments.toggleShareLabels(); HighlanderComments.restoreComment(); // HighlanderComments.autosaveInterval = setInterval( HighlanderComments.autosaveComment, 10000 ); jQuery.each( jQuery( '.comment-form-field input, textarea#comment' ), function() { if ( jQuery(this).val() !== '' ) { HighlanderComments.hideLabels( jQuery(this) ); } } ); jQuery( 'div.comment-form-fields input' ).change( function() { HighlanderComments.toggleLabel( jQuery(this) ); } ).focus( function() { HighlanderComments.hideLabels( jQuery(this) ); } ).blur( function() { HighlanderComments.showLabels( jQuery(this) ); } ); jQuery( 'div.comment-form-fields label' ).click( function() { HighlanderComments.hideLabels( jQuery(this).parent().children( '.comment-form-input input' ) ); } ); // Identity auto-fill from Gravatar Profiles jQuery( '#email' ).blur( function() { HighlanderComments.updateAvatarWithGravatar( '#email' ); if ( !jQuery( '#author' ).val() ) { Gravatar.autofill( jQuery( this ).val(), { 'displayName':'author', 'url':'url' // Their first available link, or profile URL if none } ); var afd = Gravatar.autofill_data; Gravatar.autofill_data = function( hash ) { afd.call( Gravatar, hash ); jQuery( 'input#url' ).change(); jQuery( 'input#author' ).change().click(); }; } } ); // Comment area auto-sizing and tab handling jQuery( 'textarea#comment' ) .autoResize({ animate: false, animateCallback: HighlanderComments.resizeCallback }) .css( 'resize', 'none' ) .trigger('change.dynSiz') .focus( function() { HighlanderComments.hideLabels( jQuery(this) ); } ) .blur( function() { HighlanderComments.showLabels( jQuery(this) ); } ) .keydown( function( e ) { if ( 'undefined' != typeof e.keyCode && 9 == e.keyCode ) { // TAB key e.preventDefault(); if ( 'guest' == jQuery( '#hc_post_as' ).val() ) { if ( 1 == HighlanderComments.comment_registration ) { jQuery( '#postas-wordpress' ).focus(); } else { jQuery( '#email' ).focus(); } } else { jQuery( '#comment-submit' ).focus(); } } } ) .keyup( function( e ) { HighlanderComments.fillShareText( jQuery(this) ); } ) .one( 'focus', function() { pm( { target: jQuery( '#googleplus-sign-in' )[0].contentWindow, type: 'googlePlusLoadJS', data: 0, url: 'https://public-api.wordpress.com' } ); }); // Client-side form validation jQuery( '#commentform' ).submit( function() { var verified = true, email, author; // Comment text required if ( '' === jQuery( 'textarea#comment' ).val() ) { jQuery( 'label[for="comment"]' ).fadeOut( 'fast', function() { jQuery(this).text( HighlanderComments.enterACommentError ).fadeIn( 'fast').addClass('error'); } ); jQuery( '#comment-form-comment' ).addClass('error'); jQuery( 'textarea#comment' ).focus( function() { jQuery(this).parent( '#comment-form-comment' ).removeClass('error'); } ); verified = false; } // Only exists if email/name are required if ( 'guest' == jQuery( '#hc_post_as' ).val() && ( jQuery( '#comment-form-guest label span[class="required"]' ).size() || jQuery( '#comment-form-guest label[class="error"]' ).size() ) ) { email = jQuery( '#email' ).val(); if ( '' === email || !email.match( /^.*@.*\..*$/ ) ) { jQuery( 'label[for="email"]' ).fadeOut( 'fast', function() { var error; if ( '' == email ) { error = HighlanderComments.enterEmailError; } else { error = '<span class="nopublish">' + HighlanderComments.invalidEmailError + '</span>'; } jQuery(this).html( error ).css( 'opacity', 1 ).fadeIn( 'fast' ).addClass( 'error' ); }); jQuery( 'div.comment-form-email .comment-form-input' ).addClass('error'); jQuery( 'input#email' ).focus( function() { jQuery(this).parent().removeClass( 'error' ); } ); verified = false; } author = jQuery( '#author' ).val(); if ( '' === author ) { jQuery( 'label[for="author"]' ).fadeOut( 'fast', function() { jQuery(this).text( HighlanderComments.enterAuthorError ).fadeIn('fast').addClass( 'error' ); } ); jQuery( 'div.comment-form-author .comment-form-input' ).addClass('error'); jQuery( 'input#author' ).focus( function() { jQuery(this).parent().removeClass( 'error' ); } ); verified = false; } } // Don't allow "guest" comments if auth is required if ( '1' == HighlanderComments.comment_registration && 'guest' == jQuery( '#hc_post_as' ).val() ) { jQuery( '#comment-form-nascar > p' ).addClass( 'error' ).fadeOut( 'fast', function() { jQuery( this ).fadeIn( 'fast' ); } ); verified = false; } // Set a cookie to remember which was the last used tab HighlanderComments.writeCookie( 'hc_post_as', jQuery( '#hc_post_as' ).val(), 7, '.wordpress.com' ); if ( !verified ) { return false; } HighlanderComments.clickSubmit(); return true; } ); // Set up the identity block based on WP options, logged in state, etc if ( '1' == HighlanderComments.comment_registration ) { // Must be logged in to comment (guest commenting not allowed) jQuery('#comment-form-guest').hide(); if ( !HighlanderComments.isJetpack && !HighlanderComments.userIsLoggedIn ) { // Force to guest posting if they're not logged in, which should actually not allow itself HighlanderComments.clickGuestTab(); jQuery( '#comment-form-wordpress' ).removeClass( 'selected' ); jQuery( '#hc_post_as' ).val( 'guest' ); } } else { // Guest commenting is allowed if ( HighlanderComments.userIsLoggedIn && jQuery( '#comment-form-wordpress.selected' ).length ) { // User is logged in and we're looking at the WP UI already, get rid of guest commenting jQuery( '#comment-form-guest' ).slideUp( 'fast' ); } } if ( jQuery( '.comment-form-service.selected' ).not( '#comment-form-guest.selected' ).length ) { // Something other than Guest is selected, hide the auth strip jQuery( '#comment-form-nascar' ).hide(); } if ( 'undefined' !== typeof addComment ) { HighlanderComments._moveForm = addComment.moveForm; addComment.moveForm = HighlanderComments.moveForm; } // Hover Tooltips jQuery( '#comment-form-guest .comment-form-avatar' ).hover( function() { pos = jQuery( this ).offset(); if ( 'rtl' === HighlanderComments.text_direction ) { style = 'top:' + ( pos.top - 10 ) + 'px;left:' + ( pos.left - 130 ) + 'px;'; } else { style = 'top:' + ( pos.top - 10 ) + 'px;left:' + ( pos.left + 35 ) + 'px;'; } jQuery( 'body' ).append( '<div id="hltt-grav" class="highlander-tooltip" style="' + style + '">' + HighlanderComments.gravatarFromEmail + '</div>' ); }, function() { jQuery( '#hltt-grav' ).fadeOut( 'fast', function() { jQuery( this ).remove(); jQuery( '.highlander-tooltip' ).remove(); } ); } ); jQuery( '#comment-form-nascar ul' ).hover( function() { pos = jQuery( this ).offset(); if ( 'rtl' === HighlanderComments.text_direction ) { style = 'top:' + ( pos.top - 12 ) + 'px;left:' + ( pos.left + 125 ) + 'px;'; } else { style = 'top:' + ( pos.top - 12 ) + 'px;left:' + ( pos.left - 125 ) + 'px;'; } jQuery( 'body' ).append( '<div id="hltt-auth" class="highlander-tooltip" style="' + style + '">' + HighlanderComments.logInToExternalAccount + '</div>' ); }, function() { jQuery( '#hltt-auth' ).fadeOut( 'fast', function() { jQuery( this ).remove(); jQuery( '.highlander-tooltip' ).remove(); } ); } ); }, _moveForm: null, moveForm: function( commId, parentId, respondId, postId ) { if ( null === HighlanderComments._moveForm ) { return; } var t = this, r = false, respond = jQuery( '#' + respondId ).css( { marginLeft: 0, marginRight: 0 } ), w, wTop, commElement, rHeight, cTop, rTop; if ( HighlanderComments.currentParent ) { if ( parentId === HighlanderComments.currentParentId ) { return false; } w = jQuery(window); wTop = w.scrollTop(); commElement = jQuery( '#' + commId ); cTop = commElement.offset().top; rTop = respond.offset().top; if ( rTop <= cTop ) { rHeight = respond.outerHeight( true ); respond.before( jQuery( '<div id="highlander-placeholder" />' ).css( { margin: 0, padding: 0, border: 0, height: rHeight, visibility: 'hidden', position: respond.css( 'position' ) } ) ); } r = HighlanderComments._moveForm.call( t, commId, parentId, respondId, postId ); if ( false !== r ) { return r; } HighlanderComments.currentParent.stop( true, true ).css( HighlanderComments.currentParentMargins ); jQuery( '#highlander-placeholder' ).remove(); if ( rTop <= cTop ) { jQuery( window ).scrollTop( wTop - rHeight ); } HighlanderComments.moveFormNow.call( t, commId, parentId, respondId ); } else { r = HighlanderComments._moveForm.call( t, commId, parentId, respondId, postId ); if ( false === r ) { HighlanderComments.moveFormNow.call( t, commId, parentId, respondId ); } } return r; }, moveFormNow: function( commId, parentId, respondId ) { HighlanderComments.currentParent = jQuery( '#comment-' + parentId ).parents( '.highlander-comment' ).andSelf().filter( '.highlander-comment' ).last(); if ( !HighlanderComments.currentParent.size() ) { HighlanderComments.currentParent = jQuery( '#comment-' + parentId ).parents( '.comment' ).andSelf().filter( '.comment' ).last(); } HighlanderComments.currentParentId = parentId; var respond = jQuery( '#' + respondId ); if ( !HighlanderComments.currentParent.find( respond ).size() ) { var betterParent = HighlanderComments.currentParent.parents( '.children:first' ); if ( !betterParent.size() ) { betterParent = HighlanderComments.currentParent.parents( '.highlander-comment:first' ); if ( !betterParent.size() ) { betterParent = HighlanderComments.currentParent.parents( '.comment:first' ); } } if ( betterParent.size() ) { HighlanderComments.currentParent = betterParent; } } HighlanderComments.currentParentMargins = { backgroundColor: HighlanderComments.currentParent.css( 'backgroundColor' ), marginLeft: HighlanderComments.currentParent.css( 'marginLeft' ), marginRight: HighlanderComments.currentParent.css( 'marginRight' ) }; var oldOff, newOff, offOrder, autoWidth = false; if ( 'rtl' === HighlanderComments.text_direction ) { offOrder = [ 'Left', 'Right' ]; } else { offOrder = [ 'Right', 'Left' ]; } jQuery.each( offOrder, function( i, v ) { if ( '0px' === HighlanderComments.currentParentMargins['margin' + v] ) { oldOff = HighlanderComments.currentParent.offset().left; if ( 'Right' === v ) { oldOff += HighlanderComments.currentParent.outerWidth(); } HighlanderComments.currentParent.css( 'margin' + v, 0 ); newOff = HighlanderComments.currentParent.offset().left; if ( 'Right' === v ) { newOff += HighlanderComments.currentParent.outerWidth(); } if ( oldOff !== newOff ) { newOff = 'Right' === v ? newOff - oldOff : oldOff - newOff; HighlanderComments.currentParent.css( 'margin' + v, newOff ); HighlanderComments.currentParentMargins['margin' + v] = newOff; autoWidth = true; } } } ); if ( autoWidth ) { HighlanderComments.currentParent.css( 'width', 'auto' ); HighlanderComments.currentParentMargins.width = 'auto'; } var rgbaTransparent = /rgba.*,\s*0\s*\)/, cp, bg, bgi; if ( 'transparent' === HighlanderComments.currentParentMargins.backgroundColor || HighlanderComments.currentParentMargins.backgroundColor.match( rgbaTransparent ) ) { cp = HighlanderComments.currentParent.get( 0 ); bg = 'transparent'; bgi = HighlanderComments.currentParent.css( 'backgroundImage' ); while ( 'none' === bgi && cp.parentNode && cp.parentNode != document && ( 'transparent' === bg || bg.match( rgbaTransparent ) ) ) { cp = cp.parentNode; bg = jQuery( cp ); bgi = bg.css( 'backgroundImage' ); bg = bg.css( 'backgroundColor' ); } HighlanderComments.currentParent.css( 'backgroundColor', bg ); } var cancel = document.getElementById( 'cancel-comment-reply-link' ), listOffsetSource = HighlanderComments.commentList, listOffset, parentOffset = HighlanderComments.currentParent.offset(), currentParentMargins = HighlanderComments.currentParentMargins, redoMargins = false, grandWidth; cp = HighlanderComments.currentParent; while ( !cp.is( HighlanderComments.commentList ) && !cp.is( document ) ) { if ( 'hidden' === cp.css( 'overflow' ) || 'hidden' === cp.css( 'overflow-x' ) ) { listOffsetSource = cp; break; } cp = cp.parent(); } listOffset = listOffsetSource.offset(); HighlanderComments._unmoveForm = cancel.onclick; cancel.onclick = function() { return HighlanderComments.unmoveForm.call( this ); }; if ( -1 < currentParentMargins.marginLeft.toString().indexOf( '%' ) ) { grandWidth = HighlanderComments.currentParent.parent().width(); currentParentMargins.marginLeft = parseFloat( currentParentMargins.marginLeft ) / 100 * grandWidth; redoMargins = true; } if ( -1 < currentParentMargins.marginRight.toString().indexOf( '%' ) ) { grandWidth = HighlanderComments.currentParent.parent().width(); currentParentMargins.marginRight = parseFloat( currentParentMargins.marginRight ) / 100 * grandWidth; redoMargins = true; } if ( redoMargins ) { HighlanderComments.currentParent.css( currentParentMargins ); } listOffset.right = listOffset.left + listOffsetSource.outerWidth(); parentOffset.left -= parseInt( HighlanderComments.currentParent.css( 'margin-left' ), 10 ); parentOffset.right = parentOffset.left + HighlanderComments.currentParent.outerWidth( true ); respond.hide(); HighlanderComments.currentParent.animate( { marginLeft: '-=' + ( parentOffset.left - listOffset.left ).toString(), marginRight: '-=' + ( listOffset.right - parentOffset.right ).toString() }, 350, function() { respond.slideDown( 350, function() { jQuery( '#' + commId + ' .comment-reply-link:first' ).focus(); jQuery( '#comment' ).focus(); HighlanderComments.resizeCallback(); } ); respond.children('form').after('<div class="clear" id="threaded-clear"></div>'); } ); }, _unmoveForm: null, unmoveForm: function() { var r = HighlanderComments._unmoveForm.call( this ); if ( false !== r ) { return r; } HighlanderComments.currentParent.stop( true, true ).animate( HighlanderComments.currentParentMargins, 350, function() { HighlanderComments.currentParent.css( HighlanderComments.currentParentMargins ); HighlanderComments.currentParent = HighlanderComments.currentParentId = false; } ); jQuery( '#respond' ).stop( true, true ).show(); jQuery( '#respond div#threaded-clear' ).remove(); HighlanderComments.resizeCallback(); return r; }, HTMLToText : function( string ) { return jQuery( '<span />' ).text( string ).html(); }, autosaveComment : function() { var oneDay = new Date(); oneDay.setTime( oneDay.getTime() + 86400000 ); document.cookie = 'comment-' + HighlanderComments.postID + '=' + encodeURIComponent( jQuery( '#comment' ).val() ) + '; expires=' + oneDay.toGMTString() + '; path=/'; }, unsaveComment : function() { var oneDay = new Date(); oneDay.setTime( oneDay.getTime() - 86400000 ); document.cookie = 'comment-' + HighlanderComments.postID + '= ; expires=' + oneDay.toGMTString() + '; path=/'; }, restoreComment : function() { var parts = document.cookie.split( ';' ), part; jQuery.each( parts, function(i) { part = parts[i].split( '=' ); if ( 'comment-' + HighlanderComments.postID === jQuery.trim( part[0] ) ) { if ( 'undefined' !== typeof part[1] && 'undefined' !== part[1] && '' !== decodeURIComponent( part[1] ) ) { jQuery( '#comment' ).val( decodeURIComponent( part[1] ) ); } return; } } ); }, switchAccount : function() { jQuery( '.comment-form-service' ).removeClass( 'selected' ).hide(); jQuery( '#hc_post_as' ).val( 'guest' ); jQuery( '#comment-form-nascar > p' ).removeClass( 'error' ); if ( '1' == HighlanderComments.comment_registration ) { jQuery( '#comment-form-nascar' ).show(); jQuery( '#comment-form-guest' ).hide(); // Guest commenting not allowed HighlanderComments.resizeCallback(); } else { jQuery( '#comment-form-nascar' ).show(); jQuery( '#comment-form-guest' ).slideDown( 'fast', HighlanderComments.resizeCallback ); HighlanderComments.clickGuestTab(); } }, setConnectingToText : function( serviceFriendlyName ) { jQuery( '#comment-form-load-service p' ).text( HighlanderComments.connectingToText.replace( '%s', serviceFriendlyName ) ); }, updateLoadServiceVisibility : function( tab ) { jQuery( '.comment-form-service' ) .css( 'visibility', 'hidden' ) .show() .removeClass( 'selected' ) .filter( tab ) .css( 'visibility', 'visible' ) .fadeIn( 'fast' ) .end() .not( tab ) .hide() .css( 'visibility', 'visible' ); }, clickService : function(e) { e.preventDefault(); // HighlanderComments.autosaveComment(); var tab = this.href.replace( /^.*#/, '#' ).split( ':' ); if ( '#comment-form-load-service' === tab[0] && tab[1] ) { HighlanderComments.setConnectingToText( tab[1] ); } else { jQuery( '#hc_post_as' ).val( tab[0].split( '-' ).pop() ); } HighlanderComments.updateLoadServiceVisibility( '#comment-form-load-service' ); jQuery( '#comment-form-nascar li.selected' ).removeClass( 'selected' ); jQuery( this ).parent().addClass( 'selected' ); HighlanderComments.resizeCallback(); }, clickGuestTab : function(e) { if ( '1' == HighlanderComments.comment_registration ) { jQuery( '#comment-form-guest' ).hide(); } if ( jQuery( '#email' ).length && -1 < jQuery( '#email' ).val().indexOf( '@twitter.example.com' ) ) { jQuery( '#email' ).val( '' ).blur(); } HighlanderComments.updateAvatarWithGravatar( '#email' ); // Reenable subscription options jQuery( '#comment-form-subscribe' ).css( 'opacity', '1' ).find( 'input' ).removeAttr( 'disabled' ); HighlanderComments.resizeCallback(); }, checkPostToWordPress: function(e) { HighlanderComments.clickExternalTab( 'wordpress' ); jQuery( '#wordpress-login-first' ).show(); }, updateAvatarWithGravatar : function(e) { var grav_base = ( 'https:' === location.protocol ? 'https://secure' : 'http://www' ) + '.gravatar.com/avatar/'; if ( jQuery( e ).length ) { jQuery( '#comment-form-guest .comment-form-avatar img' ).attr( 'src', grav_base + Gravatar.md5( jQuery.trim( jQuery( e ).val().toLowerCase() ) ) + '?s=25&d=' + encodeURIComponent( HighlanderComments.gravDefault ) ); } else { jQuery( '#comment-form-guest .comment-form-avatar img' ).attr( 'src', grav_base + 'ad516503a11cd5ca435acc9bb6523536?s=25&forcedefault=1&d=' + encodeURIComponent( HighlanderComments.gravDefault ) ); // unknown@gravatar.com } }, getServiceData : function( service ) { var data = HighlanderComments.readCookie( HighlanderComments.cookies[service] ); if ( null === data || 'undefined' === typeof data.access_token || !data.access_token ) { return false; } return data; }, ext_win : false, ext_win_check : false, pollExternalWindow : function( service, from_tab ) { if ( !HighlanderComments.ext_win || HighlanderComments.ext_win.closed ) { // If the cookie is available, then we must have auth'd successfully if ( HighlanderComments.getServiceData( service ) ) { HighlanderComments.doExternalLoggedIn( service ); return; } HighlanderComments.doExternalCanceled( service, from_tab ); HighlanderComments.ext_win = false; clearInterval( HighlanderComments.ext_win_check ); } }, cancelExternalWindow : function() { if ( HighlanderComments.ext_win ) { HighlanderComments.ext_win.close(); } HighlanderComments.doExternalCanceled( jQuery( '#hc_post_as' ).val(), true ); }, clickExternalTab : function( e ) { if ( 'undefined' == typeof e ) { return; } jQuery( '#comment-form-guest' ).slideUp( 'fast', function() { jQuery( '#comment-form-nascar' ).hide(); HighlanderComments.resizeCallback(); clearInterval( HighlanderComments.ext_win_check ); jQuery( '.highlander-tooltip' ).remove(); var from_tab = 1; if ( 'string' == typeof e ) { var service = e; } else { var service = e.currentTarget.id.split( '-' )[1]; if ( e.currentTarget.nodeName != 'A' ) { from_tab = 0; } } if ( // Found commenting cookies null != HighlanderComments.readCookie( HighlanderComments.cookies[service] ) && ( // WordPress tab, and we're logged in 'wordpress' == service && HighlanderComments.userIsLoggedIn || // Not WordPress tab 'wordpress' != service ) ) { if ( from_tab ) { HighlanderComments.doExternalLoggedIn( service ); } } else if ( 'googleplus' == service ) { // Nothing to do - we're already logged in at this point } else { HighlanderComments.ext_win = window.open( HighlanderComments.connectURL + '&service=' + service, 'highconn', 'status=0,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=0' + HighlanderComments.popups[service] ); HighlanderComments.ext_win_check = setInterval( "HighlanderComments.pollExternalWindow( '" + service + "', " + from_tab + " )", 100 ); } } ); }, doExternalLoggedIn : function( service ) { clearInterval( HighlanderComments.ext_win_check ); var data = HighlanderComments.getServiceData( service ); if ( 'object' !== typeof data ) { return; } if ( 'wordpress' == service ) { // Allow subscription options jQuery( '#comment-form-subscribe' ).css( 'opacity', '1' ).find( 'input' ).removeAttr( 'disabled' ); // Set up Gravatar and flag as logged in. Load a page to trigger cookies etc jQuery( '#comment-form-' + service + ' .comment-form-avatar img' ).attr( 'src', data.avatar ); HighlanderComments.userIsLoggedIn = true; if ( !HighlanderComments.isJetpack ) { jQuery( 'body' ).append( '<iframe class="highlander-auth-init" height="1" width="1" style="display:none;" src="' + HighlanderComments.homeURL + 'highlander.login/" />' ); } } else { if ( 'twitter' == service ) { // Disable subscription options for Twitter since we don't have an email jQuery( '#comment-form-subscribe' ).css( 'opacity', '0.5' ).find( 'input' ).attr( 'disabled', 'disabled' ).removeAttr( 'checked' ); } // Run all external avatars through ImgPress to resize them jQuery( '#comment-form-' + service + ' .comment-form-avatar img' ) .attr( 'src', function() { var split, host, path, query, url; try { if ( data.avatar.match( /^(https?:)?\/\/i[012]\.wp\.com\// ) ) { return data.avatar.replace( /^https?:/, location.protocol ); } if ( data.avatar.match( /^(https?:)?\/\/(.*?\.)gravatar\.com\// ) ) { return data.avatar.replace( /^https?:/, location.protocol ); } split = data.avatar.split( '#' ); // Ignore fragment split = split[0].split( '?' ); query = split[1]; split = split[0].split( '//' ); // Ignore scheme split = split[1].split( '/' ); host = split[0]; path = split.slice( 1 ).join( '/' ); url = location.protocol + '//i0.wp.com/' + host + '/' + path + '?'; if ( 'graph.facebook.com' === host && query.length ) { url += 'q=' + encodeURIComponent( query ) + '&'; } return url + 'resize=25%2C25'; } catch ( error ) { return data.avatar; } } ); } jQuery( '#email' ).val( data.email ).change(); jQuery( '#author' ).val( data.name ).change(); jQuery( '#url' ).val( data.link ).change().click(); jQuery( '#' + service + '-avatar' ).val( data.avatar ); jQuery( '#' + service + '-user_id' ).val( data.uid ); jQuery( '#' + service + '-access_token' ).val( data.access_token ); jQuery( '#hc_post_as' ).val( service ); // The child of the li.selected can be a <A> (WP, FB, Twitter) or an <IFRAME> (Google+) var selectedLink = jQuery( '#comment-form-nascar li.selected a' ); if ( selectedLink.length && service == selectedLink.attr( 'id' ).replace( 'postas-', '' ) ) { jQuery( '#comment-form-load-service' ).hide(); jQuery( '#comment-form-' + service ).show(); jQuery( '#comment-form-' + service + ' .comment-form-posting-as strong' ).text( data.name + ':' ); HighlanderComments.resizeCallback(); } var selectedIFrame = jQuery( '#comment-form-nascar li.selected iframe' ); if ( selectedIFrame.length && service == "googleplus" ) { jQuery( '#comment-form-load-service' ).hide(); jQuery( '#comment-form-' + service ).show(); jQuery( '#comment-form-' + service + ' .comment-form-posting-as strong' ).text( data.name + ':' ); HighlanderComments.resizeCallback(); } }, doExternalCanceled : function( service, from_tab ) { if ( from_tab ) { jQuery( '#comment-form-' + service + ' .comment-form-avatar img' ).attr( 'src', ( 'https:' === location.protocol ? 'https://secure' : 'http://www' ) + '.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=25&d=' + encodeURIComponent( HighlanderComments.gravDefault ) ); jQuery( '.comment-meta-' + service ).val( '' ); jQuery( '#postas-' + service + ' span' ).html( '&nbsp; &nbsp; &nbsp;' ); jQuery( '#comment-form-' + service ).hide(); HighlanderComments.switchAccount(); } jQuery( '#postto-' + service ).prop( 'checked', false ); }, doExternalLogout : function( service ) { var hostname; if ( -1 !== document.location.hostname.indexOf( '.wordpress.com' ) ) { hostname = 'wordpress.com'; } else { hostname = document.location.hostname; } HighlanderComments.writeCookie( HighlanderComments.cookies[service], '', -10, hostname ); HighlanderComments.doExternalCanceled( service, true ); if ( 'wordpress' == service ) { HighlanderComments.userIsLoggedIn = false; jQuery( 'body' ).append( '<iframe height="1" width="1" style="display:none;" src="' + HighlanderComments.logoutURL + '" />' ); } if ( 'googleplus' == service ) { jQuery( 'body' ).append( '<iframe height="1" width="1" style="display:none;" src="https://accounts.google.com/logout" />' ); } }, clickSubmit : function(e) { HighlanderComments.unsaveComment(); jQuery( '#respond input#comment-submit' ).val( HighlanderComments.HTMLToText( HighlanderComments.submittingText ) ).addClass( 'disabled' ).attr( 'disabled', 'disabled' ).wrap( '<p id="comment-form-submitting" />' ); }, toggleLabel : function( input ) { if ( jQuery( window ).width() && jQuery( window ).width() <= 450 ) { return; } if ( !input.val().length ) { input.parents('div.comment-form-field').children('label').css( { opacity: 1 } ); } else { input.parents('div.comment-form-field').children('label').css( { opacity: 0.05 } ); } }, hideLabels: function( input ) { if ( jQuery( window ).width() == 0 || jQuery( window ).width() > 450 && !input.attr( 'placeholder' ) ) { input.parents('div.comment-form-field').children('label').animate( { opacity: 0 }, 150, function() { jQuery(this).hide(); } ); } input.parent().addClass('active'); }, showLabels: function( input ) { if ( jQuery( window ).width() == 0 || jQuery( window ).width() > 450 && !input.attr( 'placeholder' ) ) { if ( !input.val().length ) { input.parents('div.comment-form-field').children('label').show().animate( { opacity: 1 }, 150 ); } } input.parent().removeClass('active'); }, editShareText: function(e) { e.preventDefault(); if ( jQuery( '#comment-form-edit-share-text' ).is( ':hidden' ) ) { jQuery( '#comment-form-edit-share-text' ).slideDown( 'fast', HighlanderComments.resizeCallback ); } else { jQuery( '#comment-form-edit-share-text' ).slideUp( 'fast', HighlanderComments.resizeCallback ); } }, toggleShareLabels: function() { if ( jQuery( '#respond' ).outerWidth() > 450 ) { jQuery( '#comment-form-post-to label span' ).show().parent().css( { 'padding-right': 0 } ); } else { jQuery( '#comment-form-post-to label span' ).hide().parent().css( { 'padding-right': '20px' } ); } HighlanderComments.resizeCallback(); }, fillShareText: function( textarea ) { if ( !jQuery( '#comment-form-share-text-textarea' ).length ) { return; } var current = jQuery( '#comment-form-share-text-textarea' ).val().split( '": ' ); var shareComment = current[0] + '": ' + jQuery(textarea).val(); if ( shareComment.length > 140 ) { shareComment = shareComment.substr( 0, 136 ) + '...'; } jQuery( '#comment-form-share-text-textarea' ).val( shareComment ); }, // Google+ Sign-in is a little different than the other services // It uses its own JavaScript API loaded in its own iframe // (public.api/connect/?googleplus-sign-in=1) // We listen for messages from that iframe here onGooglePlusSignIn: function( message ) { var hostname; if ( -1 !== document.location.hostname.indexOf( '.wordpress.com' ) ) { hostname = 'wordpress.com'; } else { hostname = document.location.hostname; } if ( 'undefined' == typeof message.error) { var value = jQuery.param( message ).replace( /\+/g, '%20' ); value.name = encodeURIComponent( value.name ); HighlanderComments.writeCookie( 'wpc_gpc', value, 1, hostname ); jQuery( '#comment-form-nascar li.selected' ).removeClass( 'selected' ); jQuery( "#googleplus-sign-in" ).parent().addClass( 'selected' ); HighlanderComments.doExternalLoggedIn( 'googleplus' ); } else { HighlanderComments.doExternalLogout( 'googleplus' ); } }, onGooglePlusButtonClick: function( message ) { HighlanderComments.setConnectingToText( 'Google+' ); HighlanderComments.updateLoadServiceVisibility( '#comment-form-load-service' ); HighlanderComments.clickExternalTab( 'googleplus' ); }, /* Read the contents of a named cookie, assuming they are query-string-style delimited, and return them as a JS hash. */ readCookie : function(c) { var nameEQ = c + "=", cookieStrings = document.cookie.split( ';' ), i, cookieString, num, chunk, pairs, pair, cookie_data; if( 'wpc_gpc' == c && !document.cookie ) { // Needed for IE because it doesn’t allow setting cookies in iframes from another domain, unless we send P3P headers cookieStrings = HighlanderComments.temp_cookie_data.split( ';' ); } for ( i = 0; i < cookieStrings.length; i++ ) { cookieString = cookieStrings[ i ]; while ( cookieString.charAt( 0 ) === ' ' ) { cookieString = cookieString.substring( 1, cookieString.length ); } if ( cookieString.indexOf( nameEQ ) === 0 ) { chunk = cookieString.substring( nameEQ.length, cookieString.length ); pairs = chunk.split( '&' ); cookie_data = {}; for ( num = pairs.length - 1; num >= 0; num-- ) { pair = pairs[ num ].split( '=' ); cookie_data[ pair[0] ] = decodeURIComponent( pair[1] ); } return cookie_data; } } return null; }, writeCookie : function( name, value, days, domain ) { var expires; if ( days ) { var date = new Date(); date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) ); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } if ( domain ) { domain = "; domain=" + domain; } else { domain = ''; } HighlanderComments.temp_cookie_data = document.cookie = name + "=" + value + expires + "; path=/" + domain; } } ); jQuery( HighlanderComments.init ); ;
JavaScript
var wpcom_mobile_user_agent_info = { PLATFORM_WINDOWS : 'windows', PLATFORM_IPHONE : 'iphone', PLATFORM_IPOD : 'ipod', PLATFORM_IPAD : 'ipad', PLATFORM_BLACKBERRY : 'blackberry', PLATFORM_BLACKBERRY_10 : 'blackberry_10', PLATFORM_SYMBIAN : 'symbian_series60', PLATFORM_SYMBIAN_S40 : 'symbian_series40', PLATFORM_J2ME_MIDP : 'j2me_midp', PLATFORM_ANDROID : 'android', PLATFORM_ANDROID_TABLET : 'android_tablet', PLATFORM_FIREFOX_OS : 'firefoxOS', PLATFORM_MOBILE_GENERIC : 'mobile_generic', userAgent : false, //Shortcut to the browser User Agent String matchedPlatformName : false, //Matched platform name. False otherwise. matchedUserAgentName : false, //Matched UA String. False otherwise. init: function() { var t = this; try{ t.userAgent = navigator.userAgent.toLowerCase(); t.getPlatformName(); t.getMobileUserAgentName(); } catch(e){ console.error(e); } }, initForTest: function(userAgent) { var t = this; t.matchedPlatformName = false; t.matchedUserAgentName = false; try{ t.userAgent = userAgent.toLowerCase(); t.getPlatformName(); t.getMobileUserAgentName(); } catch(e){ console.error(e); } }, /** * This method detects the mobile User Agent name. * * @return string The matched User Agent name, false otherwise. */ getMobileUserAgentName : function() { var t = this; if ( false !== t.matchedUserAgentName ) return t.matchedUserAgentName; if ( false === t.userAgent ) return false; if( t.isChromeForIOS() ) t.matchedUserAgentName = 'chrome-for-ios'; else if( t.isTwitterForIpad() ) t.matchedUserAgentName = 'twitter-for-ipad'; else if( t.isTwitterForIphone() ) t.matchedUserAgentName = 'twitter-for-iphone'; else if( t.isIPhoneOrIPod() ) t.matchedUserAgentName = 'iphone'; else if ( t.isIPad() ) t.matchedUserAgentName = 'ipad'; else if( t.isAndroidTablet() ) t.matchedUserAgentName = 'android_tablet'; else if( t.isAndroid() ) t.matchedUserAgentName = 'android'; else if( t.isBlackberry10() ) t.matchedUserAgentName = 'blackberry_10'; else if( t.userAgent.indexOf('blackberry') != -1 ) t.matchedUserAgentName = 'blackberry'; else if( t.isBlackberryTablet() ) t.matchedUserAgentName = 'blackberry_tablet'; else if( t.isWindowsPhone7() ) t.matchedUserAgentName = 'win7'; else if( t.isWindowsPhone8() ) t.matchedUserAgentName = 'winphone8'; else if( t.isOperaMini() ) t.matchedUserAgentName = 'opera-mini'; else if( t.isOperaMobile() ) t.matchedUserAgentName = 'opera-mobi'; else if( t.isKindleFire() ) t.matchedUserAgentName = 'kindle-fire'; else if( t.isSymbianPlatform() ) t.matchedUserAgentName = 'series60'; else if( t.isFirefoxMobile() ) t.matchedUserAgentName = 'firefox_mobile'; else if( t.isFirefoxOS() ) t.matchedUserAgentName = 'firefoxOS'; else if( t.isFacebookForIphone() ) t.matchedUserAgentName = 'facebook-for-iphone'; else if( t.isFacebookForIpad() ) t.matchedUserAgentName = 'facebook-for-ipad'; else if( t.isWordPressForIos()) t.matchedUserAgentName = 'ios-app'; else if( t.userAgent.indexOf('iphone') != -1 ) t.matchedUserAgentName = 'iphone-unknown'; else if( t.userAgent.indexOf('ipad') != -1 ) t.matchedUserAgentName = 'ipad-unknown'; return t.matchedUserAgentName ; }, getPlatformName : function() { var t = this; if ( false !== t.matchedPlatformName ) return t.matchedPlatformName; if ( false === t.userAgent ) return false; if( t.userAgent.indexOf('windows ce') != -1 || t.userAgent.indexOf('windows phone') != -1) { t.matchedPlatformName = t.PLATFORM_WINDOWS; } else if( t.userAgent.indexOf('ipad') != -1 ) { t.matchedPlatformName = t.PLATFORM_IPAD; } else if( t.userAgent.indexOf('ipod') != -1 ) { t.matchedPlatformName = t.PLATFORM_IPOD; } else if( t.userAgent.indexOf('iphone') != -1 ) { t.matchedPlatformName = t.PLATFORM_IPHONE; } else if( t.userAgent.indexOf('android') != -1 ) { if ( t.isAndroidTablet() ) t.matchedPlatformName = t.PLATFORM_ANDROID_TABLET; else t.matchedPlatformName = t.PLATFORM_ANDROID; } else if( t.isKindleFire() ) { t.matchedPlatformName = t.PLATFORM_ANDROID_TABLET; } else if( t.isBlackberry10() ) { t.matchedPlatformName = t.PLATFORM_BLACKBERRY_10; } else if( t.userAgent.indexOf('blackberry') != -1 ) { t.matchedPlatformName = t.PLATFORM_BLACKBERRY; } else if( t.isBlackberryTablet() ) { t.matchedPlatformName = t.PLATFORM_BLACKBERRY; } else if( t.isSymbianPlatform() ) { t.matchedPlatformName = t.PLATFORM_SYMBIAN; } else if( t.isSymbianS40Platform() ) { t.matchedPlatformName = t.PLATFORM_SYMBIAN_S40; } else if( t.isJ2MEPlatform() ) { t.matchedPlatformName = t.PLATFORM_J2ME_MIDP; } else if (t.isFirefoxOS()) { t.matchedPlatformName = t.PLATFORM_FIREFOX_OS; } else if (t.isFirefoxMobile()) { t.matchedPlatformName = t.PLATFORM_MOBILE_GENERIC; } return t.matchedPlatformName; }, /** * Detect the blackBerry OS version. * * Note: This is for smartphones only. Do not work on BB tablets. * */ getBlackBerryOSVersion : function() { var t = this; if ( false === t.userAgent ) return false; if( t.isBlackberry10() ) return '10'; if( t.userAgent.indexOf('blackberry') == -1) return false; var rv = -1; // Return value assumes failure. if ( t.userAgent.indexOf('webkit') != -1 ) { //detecting the BB OS version for devices running OS 6.0 or higher var re = new RegExp(/Version\/([\d\.]+)/i); } else { //blackberry devices <= 5.XX //BlackBerry9000/5.0.0.93 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/179 var re = new RegExp(/BlackBerry\w+\/([\d\.]+)/i); } if (re.exec(t.userAgent) != null) rv = RegExp.$1.toString(); if( -1 == rv ) return false; return rv; }, /** * Detects if the current UA is iPhone Mobile Safari or another iPhone or iPod Touch Browser. */ isIPhoneOrIPod : function() { var t = this; if ( false === t.userAgent ) return false; var isIphone = ( t.userAgent.indexOf('iphone') != -1 || t.userAgent.indexOf('ipod') != -1 ); var isSafari = ( t.userAgent.indexOf('safari') != -1 ); return( isIphone && isSafari ); }, /** * Detects if the current device is an iPad. */ isIPad : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('ipad') != -1 && t.userAgent.indexOf('safari') != -1); }, /** * Detects if the current UA is Chrome for iOS * */ isChromeForIOS : function() { var t = this; if ( false === t.userAgent ) return false; return( t.isIPhoneOrIPod() && t.userAgent.indexOf('crios/') != -1); }, /** * Detects if the current browser is the Native Android browser. * @return boolean true if the browser is Android otherwise false */ isAndroid : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('android') != -1 ) { if ( t.isOperaMini() || t.isOperaMobile() || t.isFirefoxMobile() ) return false; else return true; } return false; }, /** * Detects if the current browser is the Native Android Tablet browser. * Assumes 'Android' should be in the user agent, but not 'mobile' * * @return boolean true if the browser is Android and not 'mobile' otherwise false */ isAndroidTablet : function() { var t = this; if ( false === t.userAgent ) return false; if( t.userAgent.indexOf('android') != -1 && t.userAgent.indexOf('mobile') == -1) { if ( t.isOperaMini() || t.isOperaMobile() || t.isFirefoxMobile() ) return false; else return true; } return false; }, /** * Detects if the current browser is Opera Mobile * * What is the difference between Opera Mobile and Opera Mini? * - Opera Mobile is a full Internet browser for mobile devices. * - Opera Mini always uses a transcoder to convert the page for a small display. * (it uses Opera advanced server compression technology to compress web content before it gets to a device. * The rendering engine is on Opera's server.) * * Opera/9.80 (Windows NT 6.1; Opera Mobi/14316; U; en) Presto/2.7.81 Version/11.00" */ isOperaMobile : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('opera') != -1 && t.userAgent.indexOf('mobi') != -1); }, /** * Detects if the current browser is Opera Mini * * Opera/8.01 (J2ME/MIDP; Opera Mini/3.0.6306/1528; en; U; ssr) * Opera/9.80 (Android;Opera Mini/6.0.24212/24.746 U;en) Presto/2.5.25 Version/10.5454 * Opera/9.80 (iPhone; Opera Mini/5.0.019802/18.738; U; en) Presto/2.4.15 * Opera/9.80 (J2ME/iPhone;Opera Mini/5.0.019802/886; U; ja) Presto/2.4.15 * Opera/9.80 (J2ME/iPhone;Opera Mini/5.0.019802/886; U; ja) Presto/2.4.15 * Opera/9.80 (Series 60; Opera Mini/5.1.22783/23.334; U; en) Presto/2.5.25 Version/10.54 * Opera/9.80 (BlackBerry; Opera Mini/5.1.22303/22.387; U; en) Presto/2.5.25 Version/10.54 * */ isOperaMini : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('opera') != -1 && t.userAgent.indexOf('mini') != -1); }, /** * isBlackberry10() can be used to check the User Agent for a BlackBerry 10 device. */ isBlackberry10 : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('bb10') != -1 && t.userAgent.indexOf('mobile') != -1); }, /** * isBlackberryTablet() can be used to check the User Agent for a RIM blackberry tablet * The user agent of the BlackBerry® Tablet OS follows a format similar to the following: * Mozilla/5.0 (PlayBook; U; RIM Tablet OS 1.0.0; en-US) AppleWebKit/534.8+ (KHTML, like Gecko) Version/0.0.1 Safari/534.8+ * */ isBlackberryTablet : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('playbook') != -1 && t.userAgent.indexOf('rim tablet') != -1); }, /** * Detects if the current browser is a Windows Phone 7 device. * ex: Mozilla/4.0 (compatible; MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; LG; GW910) */ isWindowsPhone7 : function () { var t = this; if ( false === t.userAgent ) return false; return ( t.userAgent.indexOf('windows phone os 7') != -1 ); }, /** * Detects if the current browser is a Windows Phone 8 device. * ex: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; ARM; Touch; IEMobile/10.0; <Manufacturer>; <Device> [;<Operator>]) */ isWindowsPhone8 : function () { var t = this; if ( false === t.userAgent ) return false; return ( t.userAgent.indexOf('windows phone 8') != -1 ); }, /** * * Detects if the device platform is J2ME. * */ isJ2MEPlatform : function () { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('j2me/midp') != -1 ) return true; if ( t.userAgent.indexOf('midp') != -1 && t.userAgent.indexOf('cldc') != -1 ) return true; return false; }, /** * * Detects if the device platform is the Symbian Series 40. * Nokia Browser for Series 40 is a proxy based browser, previously known as Ovi Browser. * This browser will report 'NokiaBrowser' in the header, however some older version will also report 'OviBrowser'. * */ isSymbianS40Platform : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('series40') != -1 ) { if ( t.userAgent.indexOf('nokia') != -1 || t.userAgent.indexOf('ovibrowser') != -1 || t.userAgent.indexOf('nokiabrowser') != -1) return true; } return false; }, /** * * Detects if the device platform is the Symbian Series 60. * */ isSymbianPlatform : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('webkit') != -1 ) { //First, test for WebKit, then make sure it's either Symbian or S60. if ( t.userAgent.indexOf('symbian') != -1 || t.userAgent.indexOf('series60') != -1 ) return true; else return false; } else if ( t.userAgent.indexOf('symbianos') != -1 && t.userAgent.indexOf('series60') != -1 ) { return true; } else if ( t.userAgent.indexOf('nokia') != -1 && t.userAgent.indexOf('series60') != -1 ) { return true; } else if ( t.userAgent.indexOf('opera mini') != -1) { if( t.userAgent.indexOf('symbianos') != -1 || t.userAgent.indexOf('symbos') != -1 || t.userAgent.indexOf('series 60') != -1 ) return true; } return false; }, /** * Detects if the current browser is the Kindle Fire Native browser. * * Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-84) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true * Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-84) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=false * * @return boolean true if the browser is Kindle Fire Native browser otherwise false */ isKindleFire : function() { var t = this; if ( false === t.userAgent ) return false; return( t.userAgent.indexOf('silk/') != -1 && t.userAgent.indexOf('silk-accelerated=') != -1); }, /** * Detects if the current browser is Firefox Mobile (Fennec) * * http://www.userAgentstring.com/pages/Fennec/ * Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.1.1) Gecko/20110415 Firefox/4.0.2pre Fennec/4.0.1 * Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1b2pre) Gecko/20081015 Fennec/1.0a1 */ isFirefoxMobile : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('fennec') != -1 ) return true; return false; }, /** * Detects if the current browser is the native FirefoxOS browser * * Mozilla/5.0 (Mobile; rv:14.0) Gecko/14.0 Firefox/14.0 * */ isFirefoxOS : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('mozilla') != -1 && t.userAgent.indexOf('mobile') != -1 && t.userAgent.indexOf('gecko') != -1 && t.userAgent.indexOf('firefox') != -1 ) return true; return false; }, /** * Detects if the current UA is Facebook for iPad * - Facebook 4020.0 (iPad; iPhone OS 5.0.1; en_US) * - Mozilla/5.0 (iPad; U; CPU iPhone OS 5_0 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.0.2;FBBV/4020.0;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/5.0;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US;FBSF/1.0] * - Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10A403 [FBAN/FBIOS;FBAV/5.0;FBBV/47423;FBDV/iPad2,1;FBMD/iPad;FBSN/iPhone OS;FBSV/6.0;FBSS/1; FBCR/;FBID/tablet;FBLC/en_US] */ isFacebookForIpad : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('ipad') == -1 ) return false; if ( t.userAgent.indexOf('facebook') != -1 || t.userAgent.indexOf('fbforiphone') != -1 || t.userAgent.indexOf('fban/fbios;') != -1 ) return true; return false; }, /** * Detects if the current UA is Facebook for iPhone * - Facebook 4020.0 (iPhone; iPhone OS 5.0.1; fr_FR) * - Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_0 like Mac OS X; en_US) AppleWebKit (KHTML, like Gecko) Mobile [FBAN/FBForIPhone;FBAV/4.0.2;FBBV/4020.0;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.0;FBSS/2; FBCR/O2;FBID/phone;FBLC/en_US;FBSF/2.0] * - Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 [FBAN/FBIOS;FBAV/5.0;FBBV/47423;FBDV/iPhone3,1;FBMD/iPhone;FBSN/iPhone OS;FBSV/5.1.1;FBSS/2; FBCR/3ITA;FBID/phone;FBLC/en_US] */ isFacebookForIphone : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('iphone') == -1 ) return false; if ( t.userAgent.indexOf('facebook') != -1 && t.userAgent.indexOf('ipad') == -1 ) return true; else if ( t.userAgent.indexOf('fbforiphone') != -1 && t.userAgent.indexOf('tablet') == -1 ) return true; else if ( t.userAgent.indexOf('fban/fbios;') != -1 && t.userAgent.indexOf('tablet') == -1 ) //FB app v5.0 or higher return true; return false; }, /** * Detects if the current UA is Twitter for iPhone * * Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_5 like Mac OS X; nb-no) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8L1 Twitter for iPhone * Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 Twitter for iPhone */ isTwitterForIphone : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('ipad') != -1 ) return false; if ( t.userAgent.indexOf('twitter for iphone') != -1 ) return true; return false; }, /** * Detects if the current UA is Twitter for iPad * * Old version 4.X - Mozilla/5.0 (iPad; U; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8L1 Twitter for iPad * Ver 5.0 or Higher - Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B206 Twitter for iPhone */ isTwitterForIpad : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('twitter for ipad') != -1 ) return true; if ( t.userAgent.indexOf('ipad') != -1 && t.userAgent.indexOf('twitter for iphone') != -1 ) return true; return false; }, /** * Detects if the current UA is WordPress for iOS */ isWordPressForIos : function() { var t = this; if ( false === t.userAgent ) return false; if ( t.userAgent.indexOf('wp-iphone') != -1 ) return true; return false; } };; /*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); jQuery.noConflict(); ; /*! jQuery Migrate v1.2.1 | (c) 2005, 2013 jQuery Foundation, Inc. and other contributors | jquery.org/license */ jQuery.migrateMute===void 0&&(jQuery.migrateMute=!0),function(e,t,n){function r(n){var r=t.console;i[n]||(i[n]=!0,e.migrateWarnings.push(n),r&&r.warn&&!e.migrateMute&&(r.warn("JQMIGRATE: "+n),e.migrateTrace&&r.trace&&r.trace()))}function a(t,a,i,o){if(Object.defineProperty)try{return Object.defineProperty(t,a,{configurable:!0,enumerable:!0,get:function(){return r(o),i},set:function(e){r(o),i=e}}),n}catch(s){}e._definePropertyBroken=!0,t[a]=i}var i={};e.migrateWarnings=[],!e.migrateMute&&t.console&&t.console.log&&t.console.log("JQMIGRATE: Logging is active"),e.migrateTrace===n&&(e.migrateTrace=!0),e.migrateReset=function(){i={},e.migrateWarnings.length=0},"BackCompat"===document.compatMode&&r("jQuery is not compatible with Quirks Mode");var o=e("<input/>",{size:1}).attr("size")&&e.attrFn,s=e.attr,u=e.attrHooks.value&&e.attrHooks.value.get||function(){return null},c=e.attrHooks.value&&e.attrHooks.value.set||function(){return n},l=/^(?:input|button)$/i,d=/^[238]$/,p=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,f=/^(?:checked|selected)$/i;a(e,"attrFn",o||{},"jQuery.attrFn is deprecated"),e.attr=function(t,a,i,u){var c=a.toLowerCase(),g=t&&t.nodeType;return u&&(4>s.length&&r("jQuery.fn.attr( props, pass ) is deprecated"),t&&!d.test(g)&&(o?a in o:e.isFunction(e.fn[a])))?e(t)[a](i):("type"===a&&i!==n&&l.test(t.nodeName)&&t.parentNode&&r("Can't change the 'type' of an input or button in IE 6/7/8"),!e.attrHooks[c]&&p.test(c)&&(e.attrHooks[c]={get:function(t,r){var a,i=e.prop(t,r);return i===!0||"boolean"!=typeof i&&(a=t.getAttributeNode(r))&&a.nodeValue!==!1?r.toLowerCase():n},set:function(t,n,r){var a;return n===!1?e.removeAttr(t,r):(a=e.propFix[r]||r,a in t&&(t[a]=!0),t.setAttribute(r,r.toLowerCase())),r}},f.test(c)&&r("jQuery.fn.attr('"+c+"') may use property instead of attribute")),s.call(e,t,a,i))},e.attrHooks.value={get:function(e,t){var n=(e.nodeName||"").toLowerCase();return"button"===n?u.apply(this,arguments):("input"!==n&&"option"!==n&&r("jQuery.fn.attr('value') no longer gets properties"),t in e?e.value:null)},set:function(e,t){var a=(e.nodeName||"").toLowerCase();return"button"===a?c.apply(this,arguments):("input"!==a&&"option"!==a&&r("jQuery.fn.attr('value', val) no longer sets properties"),e.value=t,n)}};var g,h,v=e.fn.init,m=e.parseJSON,y=/^([^<]*)(<[\w\W]+>)([^>]*)$/;e.fn.init=function(t,n,a){var i;return t&&"string"==typeof t&&!e.isPlainObject(n)&&(i=y.exec(e.trim(t)))&&i[0]&&("<"!==t.charAt(0)&&r("$(html) HTML strings must start with '<' character"),i[3]&&r("$(html) HTML text after last tag is ignored"),"#"===i[0].charAt(0)&&(r("HTML string cannot start with a '#' character"),e.error("JQMIGRATE: Invalid selector string (XSS)")),n&&n.context&&(n=n.context),e.parseHTML)?v.call(this,e.parseHTML(i[2],n,!0),n,a):v.apply(this,arguments)},e.fn.init.prototype=e.fn,e.parseJSON=function(e){return e||null===e?m.apply(this,arguments):(r("jQuery.parseJSON requires a valid JSON string"),null)},e.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||0>e.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e.browser||(g=e.uaMatch(navigator.userAgent),h={},g.browser&&(h[g.browser]=!0,h.version=g.version),h.chrome?h.webkit=!0:h.webkit&&(h.safari=!0),e.browser=h),a(e,"browser",e.browser,"jQuery.browser is deprecated"),e.sub=function(){function t(e,n){return new t.fn.init(e,n)}e.extend(!0,t,this),t.superclass=this,t.fn=t.prototype=this(),t.fn.constructor=t,t.sub=this.sub,t.fn.init=function(r,a){return a&&a instanceof e&&!(a instanceof t)&&(a=t(a)),e.fn.init.call(this,r,a,n)},t.fn.init.prototype=t.fn;var n=t(document);return r("jQuery.sub() is deprecated"),t},e.ajaxSetup({converters:{"text json":e.parseJSON}});var b=e.fn.data;e.fn.data=function(t){var a,i,o=this[0];return!o||"events"!==t||1!==arguments.length||(a=e.data(o,t),i=e._data(o,t),a!==n&&a!==i||i===n)?b.apply(this,arguments):(r("Use of jQuery.fn.data('events') is deprecated"),i)};var j=/\/(java|ecma)script/i,w=e.fn.andSelf||e.fn.addBack;e.fn.andSelf=function(){return r("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"),w.apply(this,arguments)},e.clean||(e.clean=function(t,a,i,o){a=a||document,a=!a.nodeType&&a[0]||a,a=a.ownerDocument||a,r("jQuery.clean() is deprecated");var s,u,c,l,d=[];if(e.merge(d,e.buildFragment(t,a).childNodes),i)for(c=function(e){return!e.type||j.test(e.type)?o?o.push(e.parentNode?e.parentNode.removeChild(e):e):i.appendChild(e):n},s=0;null!=(u=d[s]);s++)e.nodeName(u,"script")&&c(u)||(i.appendChild(u),u.getElementsByTagName!==n&&(l=e.grep(e.merge([],u.getElementsByTagName("script")),c),d.splice.apply(d,[s+1,0].concat(l)),s+=l.length));return d});var Q=e.event.add,x=e.event.remove,k=e.event.trigger,N=e.fn.toggle,T=e.fn.live,M=e.fn.die,S="ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",C=RegExp("\\b(?:"+S+")\\b"),H=/(?:^|\s)hover(\.\S+|)\b/,A=function(t){return"string"!=typeof t||e.event.special.hover?t:(H.test(t)&&r("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"),t&&t.replace(H,"mouseenter$1 mouseleave$1"))};e.event.props&&"attrChange"!==e.event.props[0]&&e.event.props.unshift("attrChange","attrName","relatedNode","srcElement"),e.event.dispatch&&a(e.event,"handle",e.event.dispatch,"jQuery.event.handle is undocumented and deprecated"),e.event.add=function(e,t,n,a,i){e!==document&&C.test(t)&&r("AJAX events should be attached to document: "+t),Q.call(this,e,A(t||""),n,a,i)},e.event.remove=function(e,t,n,r,a){x.call(this,e,A(t)||"",n,r,a)},e.fn.error=function(){var e=Array.prototype.slice.call(arguments,0);return r("jQuery.fn.error() is deprecated"),e.splice(0,0,"error"),arguments.length?this.bind.apply(this,e):(this.triggerHandler.apply(this,e),this)},e.fn.toggle=function(t,n){if(!e.isFunction(t)||!e.isFunction(n))return N.apply(this,arguments);r("jQuery.fn.toggle(handler, handler...) is deprecated");var a=arguments,i=t.guid||e.guid++,o=0,s=function(n){var r=(e._data(this,"lastToggle"+t.guid)||0)%o;return e._data(this,"lastToggle"+t.guid,r+1),n.preventDefault(),a[r].apply(this,arguments)||!1};for(s.guid=i;a.length>o;)a[o++].guid=i;return this.click(s)},e.fn.live=function(t,n,a){return r("jQuery.fn.live() is deprecated"),T?T.apply(this,arguments):(e(this.context).on(t,this.selector,n,a),this)},e.fn.die=function(t,n){return r("jQuery.fn.die() is deprecated"),M?M.apply(this,arguments):(e(this.context).off(t,this.selector||"**",n),this)},e.event.trigger=function(e,t,n,a){return n||C.test(e)||r("Global events are undocumented and deprecated"),k.call(this,e,t,n||document,a)},e.each(S.split("|"),function(t,n){e.event.special[n]={setup:function(){var t=this;return t!==document&&(e.event.add(document,n+"."+e.guid,function(){e.event.trigger(n,null,t,!0)}),e._data(this,n,e.guid++)),!1},teardown:function(){return this!==document&&e.event.remove(document,n+"."+e._data(this,n)),!1}}})}(jQuery,window);; /** The MIT License Copyright (c) 2010 Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ var NO_JQUERY = {}; (function(window, $, undefined) { if (!("console" in window)) { var c = window.console = {}; c.log = c.warn = c.error = c.debug = function(){}; } if ($ === NO_JQUERY) { // jQuery is optional $ = { fn: {}, extend: function() { var a = arguments[0]; for (var i=1,len=arguments.length; i<len; i++) { var b = arguments[i]; for (var prop in b) { a[prop] = b[prop]; } } return a; } }; } $.fn.pm = function() { console.log("usage: \nto send: $.pm(options)\nto receive: $.pm.bind(type, fn, [origin])"); return this; }; // send postmessage $.pm = window.pm = function(options) { pm.send(options); }; // bind postmessage handler $.pm.bind = window.pm.bind = function(type, fn, origin, hash, async_reply) { pm.bind(type, fn, origin, hash, async_reply === true); }; // unbind postmessage handler $.pm.unbind = window.pm.unbind = function(type, fn) { pm.unbind(type, fn); }; // default postmessage origin on bind $.pm.origin = window.pm.origin = null; // default postmessage polling if using location hash to pass postmessages $.pm.poll = window.pm.poll = 200; var pm = { send: function(options) { var o = $.extend({}, pm.defaults, options), target = o.target; if (!o.target) { console.warn("postmessage target window required"); return; } if (!o.type) { console.warn("postmessage type required"); return; } var msg = {data:o.data, type:o.type}; if (o.success) { msg.callback = pm._callback(o.success); } if (o.error) { msg.errback = pm._callback(o.error); } if (("postMessage" in target) && !o.hash) { pm._bind(); target.postMessage(JSON.stringify(msg), o.origin || '*'); } else { pm.hash._bind(); pm.hash.send(o, msg); } }, bind: function(type, fn, origin, hash, async_reply) { pm._replyBind ( type, fn, origin, hash, async_reply ); }, _replyBind: function(type, fn, origin, hash, isCallback) { if (("postMessage" in window) && !hash) { pm._bind(); } else { pm.hash._bind(); } var l = pm.data("listeners.postmessage"); if (!l) { l = {}; pm.data("listeners.postmessage", l); } var fns = l[type]; if (!fns) { fns = []; l[type] = fns; } fns.push({fn:fn, callback: isCallback, origin:origin || $.pm.origin}); }, unbind: function(type, fn) { var l = pm.data("listeners.postmessage"); if (l) { if (type) { if (fn) { // remove specific listener var fns = l[type]; if (fns) { var m = []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.fn !== fn) { m.push(o); } } l[type] = m; } } else { // remove all listeners by type delete l[type]; } } else { // unbind all listeners of all type for (var i in l) { delete l[i]; } } } }, data: function(k, v) { if (v === undefined) { return pm._data[k]; } pm._data[k] = v; return v; }, _data: {}, _CHARS: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), _random: function() { var r = []; for (var i=0; i<32; i++) { r[i] = pm._CHARS[0 | Math.random() * 32]; }; return r.join(""); }, _callback: function(fn) { var cbs = pm.data("callbacks.postmessage"); if (!cbs) { cbs = {}; pm.data("callbacks.postmessage", cbs); } var r = pm._random(); cbs[r] = fn; return r; }, _bind: function() { // are we already listening to message events on this w? if (!pm.data("listening.postmessage")) { if (window.addEventListener) { window.addEventListener("message", pm._dispatch, false); } else if (window.attachEvent) { window.attachEvent("onmessage", pm._dispatch); } pm.data("listening.postmessage", 1); } }, _dispatch: function(e) { //console.log("$.pm.dispatch", e, this); try { var msg = JSON.parse(e.data); } catch (ex) { //console.warn("postmessage data invalid json: ", ex); //message wasn't meant for pm return; } if (!msg.type) { //console.warn("postmessage message type required"); //message wasn't meant for pm return; } var cbs = pm.data("callbacks.postmessage") || {}, cb = cbs[msg.type]; if (cb) { cb(msg.data); } else { var l = pm.data("listeners.postmessage") || {}; var fns = l[msg.type] || []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.origin && o.origin !== '*' && e.origin !== o.origin) { console.warn("postmessage message origin mismatch", e.origin, o.origin); if (msg.errback) { // notify post message errback var error = { message: "postmessage origin mismatch", origin: [e.origin, o.origin] }; pm.send({target:e.source, data:error, type:msg.errback}); } continue; } function sendReply ( data ) { if (msg.callback) { pm.send({target:e.source, data:data, type:msg.callback}); } } try { if ( o.callback ) { o.fn(msg.data, sendReply, e); } else { sendReply ( o.fn(msg.data, e) ); } } catch (ex) { if (msg.errback) { // notify post message errback pm.send({target:e.source, data:ex, type:msg.errback}); } else { throw ex; } } }; } } }; // location hash polling pm.hash = { send: function(options, msg) { //console.log("hash.send", target_window, options, msg); var target_window = options.target, target_url = options.url; if (!target_url) { console.warn("postmessage target window url is required"); return; } target_url = pm.hash._url(target_url); var source_window, source_url = pm.hash._url(window.location.href); if (window == target_window.parent) { source_window = "parent"; } else { try { for (var i=0,len=parent.frames.length; i<len; i++) { var f = parent.frames[i]; if (f == window) { source_window = i; break; } }; } catch(ex) { // Opera: security error trying to access parent.frames x-origin // juse use window.name source_window = window.name; } } if (source_window == null) { console.warn("postmessage windows must be direct parent/child windows and the child must be available through the parent window.frames list"); return; } var hashmessage = { "x-requested-with": "postmessage", source: { name: source_window, url: source_url }, postmessage: msg }; var hash_id = "#x-postmessage-id=" + pm._random(); target_window.location = target_url + hash_id + encodeURIComponent(JSON.stringify(hashmessage)); }, _regex: /^\#x\-postmessage\-id\=(\w{32})/, _regex_len: "#x-postmessage-id=".length + 32, _bind: function() { // are we already listening to message events on this w? if (!pm.data("polling.postmessage")) { setInterval(function() { var hash = "" + window.location.hash, m = pm.hash._regex.exec(hash); if (m) { var id = m[1]; if (pm.hash._last !== id) { pm.hash._last = id; pm.hash._dispatch(hash.substring(pm.hash._regex_len)); } } }, $.pm.poll || 200); pm.data("polling.postmessage", 1); } }, _dispatch: function(hash) { if (!hash) { return; } try { hash = JSON.parse(decodeURIComponent(hash)); if (!(hash['x-requested-with'] === 'postmessage' && hash.source && hash.source.name != null && hash.source.url && hash.postmessage)) { // ignore since hash could've come from somewhere else return; } } catch (ex) { // ignore since hash could've come from somewhere else return; } var msg = hash.postmessage, cbs = pm.data("callbacks.postmessage") || {}, cb = cbs[msg.type]; if (cb) { cb(msg.data); } else { var source_window; if (hash.source.name === "parent") { source_window = window.parent; } else { source_window = window.frames[hash.source.name]; } var l = pm.data("listeners.postmessage") || {}; var fns = l[msg.type] || []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.origin) { var origin = /https?\:\/\/[^\/]*/.exec(hash.source.url)[0]; if (o.origin !== '*' && origin !== o.origin) { console.warn("postmessage message origin mismatch", origin, o.origin); if (msg.errback) { // notify post message errback var error = { message: "postmessage origin mismatch", origin: [origin, o.origin] }; pm.send({target:source_window, data:error, type:msg.errback, hash:true, url:hash.source.url}); } continue; } } function sendReply ( data ) { if (msg.callback) { pm.send({target:source_window, data:data, type:msg.callback, hash:true, url:hash.source.url}); } } try { if ( o.callback ) { o.fn(msg.data, sendReply); } else { sendReply ( o.fn(msg.data) ); } } catch (ex) { if (msg.errback) { // notify post message errback pm.send({target:source_window, data:ex, type:msg.errback, hash:true, url:hash.source.url}); } else { throw ex; } } }; } }, _url: function(url) { // url minus hash part return (""+url).replace(/#.*$/, ""); } }; $.extend(pm, { defaults: { target: null, /* target window (required) */ url: null, /* target window url (required if no window.postMessage or hash == true) */ type: null, /* message type (required) */ data: null, /* message data (required) */ success: null, /* success callback (optional) */ error: null, /* error callback (optional) */ origin: "*", /* postmessage origin (optional) */ hash: false /* use location hash for message passing (optional) */ } }); })(this, typeof jQuery === "undefined" ? NO_JQUERY : jQuery); /** * http://www.JSON.org/json2.js **/ if (! ("JSON" in window && window.JSON)){JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z"};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}()); ; /** * author Christopher Blum * - based on the idea of Remy Sharp, http://remysharp.com/2009/01/26/element-in-view-event-plugin/ * - forked from http://github.com/zuk/jquery.inview/ */ (function ($) { var inviewObjects = {}, viewportSize, viewportOffset, d = document, w = window, documentElement = d.documentElement, expando = $.expando; $.event.special.inview = { add: function(data) { inviewObjects[data.guid + "-" + this[expando]] = { data: data, $element: $(this) }; }, remove: function(data) { try { delete inviewObjects[data.guid + "-" + this[expando]]; } catch(e) {} } }; function getViewportSize() { var mode, domObject, size = { height: w.innerHeight, width: w.innerWidth }; // if this is correct then return it. iPad has compat Mode, so will // go into check clientHeight/clientWidth (which has the wrong value). if (!size.height) { mode = d.compatMode; if (mode || !$.support.boxModel) { // IE, Gecko domObject = mode === 'CSS1Compat' ? documentElement : // Standards d.body; // Quirks size = { height: domObject.clientHeight, width: domObject.clientWidth }; } } return size; } function getViewportOffset() { return { top: w.pageYOffset || documentElement.scrollTop || d.body.scrollTop, left: w.pageXOffset || documentElement.scrollLeft || d.body.scrollLeft }; } function checkInView() { var $elements = $(), elementsLength, i = 0; $.each(inviewObjects, function(i, inviewObject) { var selector = inviewObject.data.selector, $element = inviewObject.$element; $elements = $elements.add(selector ? $element.find(selector) : $element); }); elementsLength = $elements.length; if (elementsLength) { viewportSize = viewportSize || getViewportSize(); viewportOffset = viewportOffset || getViewportOffset(); for (; i<elementsLength; i++) { // Ignore elements that are not in the DOM tree if (!$.contains(documentElement, $elements[i])) { continue; } var element = $elements[i], $element = $(element), elementSize = {}, elementOffset = {}, inView = $element.data('inview'), visiblePartX, visiblePartY, visiblePartsMerged; // for the case where 'display:none' is used in place of 'visibility:hidden' // count and sum the above items to get and move closer to the correct values // IMPORTANT :: insert element into container empty if($element.css('display') == 'none') { var parentElement = $element.parent(); elementOffset.top = parentElement.offset().top; elementOffset.left = parentElement.offset().left; elementSize.height = parentElement.height(); elementSize.width = parentElement.width(); } else { elementSize = { height: $element.height(), width: $element.width() } elementOffset = $element.offset(); } // Don't ask me why because I haven't figured out yet: // viewportOffset and viewportSize are sometimes suddenly null in Firefox 5. // Even though it sounds weird: // It seems that the execution of this function is interferred by the onresize/onscroll event // where viewportOffset and viewportSize are unset if (!viewportOffset || !viewportSize) { return; } if (element.offsetWidth >= 0 && element.offsetHeight >= 0 && element.style.display != "none" && elementOffset.top + elementSize.height > viewportOffset.top && elementOffset.top < viewportOffset.top + viewportSize.height && elementOffset.left + elementSize.width > viewportOffset.left && elementOffset.left < viewportOffset.left + viewportSize.width) { visiblePartX = (viewportOffset.left > elementOffset.left ? 'right' : (viewportOffset.left + viewportSize.width) < (elementOffset.left + elementSize.width) ? 'left' : 'both'); visiblePartY = (viewportOffset.top > elementOffset.top ? 'bottom' : (viewportOffset.top + viewportSize.height) < (elementOffset.top + elementSize.height) ? 'top' : 'both'); visiblePartsMerged = visiblePartX + "-" + visiblePartY; if (!inView || inView !== visiblePartsMerged) { $element.data('inview', visiblePartsMerged).trigger('inview', [true, visiblePartX, visiblePartY]); } } else if (inView) { $element.data('inview', false).trigger('inview', [false]); } } } } $(w).bind("scroll resize", function() { viewportSize = viewportOffset = null; }); // IE < 9 scrolls to focused elements without firing the "scroll" event if (!documentElement.addEventListener && documentElement.attachEvent) { documentElement.attachEvent("onfocusin", function() { viewportOffset = null; }); } // Use setInterval in order to also make sure this captures elements within // "overflow:scroll" elements or elements that appeared in the dom tree due to // dom manipulation and reflow // old: $(window).scroll(checkInView); // // By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays // intervals while the user scrolls. Therefore the inview event might fire a bit late there setInterval(checkInView, 250); })(jQuery);; /* global Jetpack */ /** * Resizeable Iframes. * * Start listening to resize postMessage events for selected iframes: * $( selector ).Jetpack( 'resizeable' ); * - OR - * Jetpack.resizeable( 'on', context ); * * Resize selected iframes: * $( selector ).Jetpack( 'resizeable', 'resize', { width: 100, height: 200 } ); * - OR - * Jetpack.resizeable( 'resize', { width: 100, height: 200 }, context ); * * Stop listening to resize postMessage events for selected iframes: * $( selector ).Jetpack( 'resizeable', 'off' ); * - OR - * Jetpack.resizeable( 'off', context ); * * Stop listening to all resize postMessage events: * Jetpack.resizeable( 'off' ); */ (function($) { var listening = false, // Are we listening for resize postMessage events sourceOrigins = [], // What origins are allowed to send resize postMessage events $sources = false, // What iframe elements are we tracking resize postMessage events from URLtoOrigin, // Utility to convert URLs into origins setupListener, // Binds global resize postMessage event handler destroyListener, // Unbinds global resize postMessage event handler methods; // Jetpack.resizeable methods // Setup the Jetpack global if ( 'undefined' === typeof window.Jetpack ) { window.Jetpack = { /** * Handles the two different calling methods: * $( selector ).Jetpack( 'namespace', 'method', context ) // here, context is optional and is used to filter the collection * - vs. - * Jetpack.namespace( 'method', context ) // here context defines the collection * * @internal * * Call as: Jetpack.getTarget.call( this, context ) * * @param string context: jQuery selector * @return jQuery|undefined object on which to perform operations or undefined when context cannot be determined */ getTarget: function( context ) { if ( this instanceof jQuery ) { return context ? this.filter( context ) : this; } return context ? $( context ) : context; } }; } // Setup the Jetpack jQuery method if ( 'undefined' === typeof $.fn.Jetpack ) { /** * Dispatches calls to the correct namespace * * @param string namespace * @param ... * @return mixed|jQuery (chainable) */ $.fn.Jetpack = function( namespace ) { if ( 'function' === typeof Jetpack[namespace] ) { // Send the call to the correct Jetpack.namespace return Jetpack[namespace].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } else { $.error( 'Namespace "' + namespace + '" does not exist on jQuery.Jetpack' ); } }; } // Define Jetpack.resizeable() namespace to just always bail if no postMessage if ( 'function' !== typeof window.postMessage ) { $.extend( window.Jetpack, { /** * Defines the Jetpack.resizeable() namespace. * See below for non-trivial definition for browsers with postMessage. */ resizeable: function() { $.error( 'Browser does not support window.postMessage' ); } } ); return; } /** * Utility to convert URLs into origins * * http://example.com:port/path?query#fragment -> http://example.com:port * * @param string URL * @return string origin */ URLtoOrigin = function( URL ) { if ( ! URL.match( /^https?:\/\// ) ) { URL = document.location.href; } return URL.split( '/' ).slice( 0, 3 ).join( '/' ); }; /** * Binds global resize postMessage event handler */ setupListener = function() { listening = true; $( window ).on( 'message.JetpackResizeableIframe', function( e ) { var event = e.originalEvent, data; // Ensure origin is allowed if ( -1 === $.inArray( event.origin, sourceOrigins ) ) { return; } // Some browsers send structured data, some send JSON strings if ( 'object' === typeof event.data ) { data = event.data.data; } else { try { data = JSON.parse( event.data ); } catch ( err ) { data = false; } } if ( !data.data ) { return; } // Un-nest data = data.data; // Is it a resize event? if ( 'undefined' === typeof data.action || 'resize' !== data.action ) { return; } // Find the correct iframe and resize it $sources.filter( function() { if ( 'undefined' !== typeof data.name ) { return this.name === data.name; } else { return event.source === this.contentWindow; } } ).first().Jetpack( 'resizeable', 'resize', data ); } ); }; /** * Unbinds global resize postMessage event handler */ destroyListener = function() { listening = false; $( window ).off( 'message.JetpackResizeableIframe' ); sourceOrigins = []; $( '.jetpack-resizeable' ).removeClass( 'jetpack-resizeable' ); $sources = false; }; // Methods for Jetpack.resizeable() namespace methods = { /** * Start listening for resize postMessage events on the given iframes * * Call statically as: Jetpack.resizeable( 'on', context ) * Call as: $( selector ).Jetpack( 'resizeable', 'on', context ) // context optional: used to filter the collectino * * @param string context jQuery selector. * @return jQuery (chainable) */ on: function( context ) { var target = Jetpack.getTarget.call( this, context ); if ( ! listening ) { setupListener(); } target.each( function() { sourceOrigins.push( URLtoOrigin( $( this ).attr( 'src' ) ) ); } ).addClass( 'jetpack-resizeable' ); $sources = $( '.jetpack-resizeable' ); return target; }, /** * Stop listening for resize postMessage events on the given iframes * * Call statically as: Jetpack.resizeable( 'off', context ) * Call as: $( selector ).Jetpack( 'resizeable', 'off', context ) // context optional: used to filter the collectino * * @param string context jQuery selector * @return jQuery (chainable) */ off: function( context ) { var target = Jetpack.getTarget.call( this, context ); if ( 'undefined' === typeof target ) { destroyListener(); return target; } target.each( function() { var origin = URLtoOrigin( $( this ).attr( 'src' ) ), pos = $.inArray( origin, sourceOrigins ); if ( -1 !== pos ) { sourceOrigins.splice( pos, 1 ); } } ).removeClass( 'jetpack-resizeable' ); $sources = $( '.jetpack-resizeable' ); return target; }, /** * Resize the given iframes * * Call statically as: Jetpack.resizeable( 'resize', dimensions, context ) * Call as: $( selector ).Jetpack( 'resizeable', 'resize', dimensions, context ) // context optional: used to filter the collectino * * @param object dimensions in pixels: { width: (int), height: (int) } * @param string context jQuery selector * @return jQuery (chainable) */ resize: function( dimensions, context ) { var target = Jetpack.getTarget.call( this, context ); $.each( [ 'width', 'height' ], function( i, variable ) { var value = 0, container; if ( 'undefined' !== typeof dimensions[variable] ) { value = parseInt( dimensions[variable], 10 ); } if ( 0 !== value ) { target[variable]( value ); container = target.parent(); if ( container.hasClass( 'slim-likes-widget' ) ) { container[variable]( value ); } } } ); return target; } }; // Define Jetpack.resizeable() namespace $.extend( window.Jetpack, { /** * Defines the Jetpack.resizeable() namespace. * See above for trivial definition for browsers with no postMessage. * * @param string method * @param ... * @return mixed|jQuery (chainable) */ resizeable: function( method ) { if ( methods[method] ) { // Send the call to the correct Jetpack.resizeable() method return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ) ); } else if ( ! method ) { // By default, send to Jetpack.resizeable( 'on' ), which isn't useful in that form but is when called as // jQuery( selector ).Jetpack( 'resizeable' ) return methods.on.apply( this ); } else { $.error( 'Method ' + method + ' does not exist on Jetpack.resizeable' ); } } } ); })(jQuery); ; jQuery.extend(jQuery.easing, { easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; } }); jQuery(document).ready(function($) { var isopen = false, bitHeight = $('#bitsubscribe').height(), $bit = $('#bit'); setTimeout(function () { $bit.animate({ bottom: '-' + bitHeight - 30 + 'px' }, 200); if (document.location.href.indexOf('blogsub=') !== -1) { open(); } }, 300); var open = function() { if (isopen) return; isopen = true; $('a.bsub', $bit).addClass('open'); $('#bitsubscribe', $bit).addClass('open') $bit.stop(); $bit.animate({ bottom: '0px' },{duration:400, easing:"easeOutCubic"}); } var close = function() { if (!isopen) return; isopen = false; $bit.stop(); $bit.animate({ bottom: '-' + bitHeight - 30 + 'px' }, 200, function() { $('a.bsub', $bit).removeClass('open'); $('#bitsubscribe', $bit).removeClass('open'); }); } $('a.bsub', $bit).click(function () { if ( !isopen ) open(); else close(); }); var target = $bit.has('form').length? $bit : $(document); target.keyup(function(e) { if (27 == e.keyCode) close(); }); $( '#loggedout-follow' ).submit( function() { email = $( '#loggedout-follow-field' ).val(); if ( '' === email || !email.match( /^.*@.*\..*$/ ) ) { var error = LoggedOutFollow.invalid_email; $( '#loggedout-follow-error' ).text( error ).css( 'opacity', 1 ).fadeIn( 'slow' ); $( '#loggedout-follow-field' ).focus( function() { $('#loggedout-follow-error').fadeOut(); } ); return false; } return true; }); });; /** * Load related posts */ (function($) { var jprp = { response: null, /** * Utility get related posts JSON endpoint from URLs * * @param string URL (optional) * @return string endpoint URL */ getEndpointURL: function( URL ) { var locationObject = document.location; if ( 'string' == typeof( URL ) && URL.match( /^https?:\/\// ) ) { locationObject = document.createElement( 'a' ); locationObject.href = URL; } var args = 'relatedposts=1'; if ( undefined != $( '#jp-relatedposts' ).data( 'exclude' ) ) { args += '&relatedposts_exclude=' + $( '#jp-relatedposts' ).data( 'exclude' ); } if ( '' == locationObject.search ) { return locationObject.pathname + '?' + args; } else { return locationObject.pathname + locationObject.search + '&' + args; } }, getAnchor: function( post, classNames ) { var self = this; var anchor_title = post.title; if ( '' != post.excerpt ) { anchor_title += "\n\n" + post.excerpt; } var anchor = $( '<a>' ); anchor.attr({ 'class': classNames, 'href': post.url, 'title': anchor_title, 'rel': 'nofollow', 'data-origin': post.url_meta.origin, 'data-position': post.url_meta.position }); var anchor_html = $( '<div>' ).append( anchor ).html(); return [ anchor_html.substring( 0, anchor_html.length-4 ), '</a>' ]; }, generateMinimalHtml: function( posts ) { var self = this; var html = ''; $.each( posts, function( index, post ) { var anchor = self.getAnchor( post, 'jp-relatedposts-post-a' ); var classes = 'jp-relatedposts-post jp-relatedposts-post' + index; html += '<p class="' + classes + '" data-post-id="' + post.id + '" data-post-format="' + post.format + '">'; html += '<span class="jp-relatedposts-post-title">' + anchor[0] + post.title + anchor[1] + '</span>'; html += '<span class="jp-relatedposts-post-context">' + post.context + '</span>'; html += '</p>'; } ); return '<div class="jp-relatedposts-items jp-relatedposts-items-minimal">' + html + '</div>'; }, generateVisualHtml: function( posts ) { var self = this; var html = ''; $.each( posts, function( index, post ) { var anchor = self.getAnchor( post, 'jp-relatedposts-post-a' ); var classes = 'jp-relatedposts-post jp-relatedposts-post' + index; if ( '' == post.img.src ) classes += ' jp-relatedposts-post-nothumbs'; else classes += ' jp-relatedposts-post-thumbs'; html += '<div class="' + classes + '" data-post-id="' + post.id + '" data-post-format="' + post.format + '">'; if ( '' != post.img.src ) { html += anchor[0] + '<img class="jp-relatedposts-post-img" src="' + post.img.src + '" width="' + post.img.width + '" alt="' + post.title + '" />' + anchor[1]; } else { var anchor_overlay = self.getAnchor( post, 'jp-relatedposts-post-a jp-relatedposts-post-aoverlay' ); html += anchor_overlay[0] + anchor_overlay[1]; } html += '<h4 class="jp-relatedposts-post-title">' + anchor[0] + post.title + anchor[1] + '</h4>'; html += '<p class="jp-relatedposts-post-excerpt">' + post.excerpt + '</p>'; html += '<p class="jp-relatedposts-post-context">' + post.context + '</p>'; html += '</div>'; } ); return '<div class="jp-relatedposts-items jp-relatedposts-items-visual">' + html + '</div>'; }, /** * We want to set a max height on the excerpt however we want to set * this according to the natual pacing of the page as we never want to * cut off a line of text in the middle so we need to do some detective * work. */ setVisualExcerptHeights: function() { var elements = $( '#jp-relatedposts .jp-relatedposts-post-nothumbs .jp-relatedposts-post-excerpt' ); if ( 0 >= elements.length ) return; var fontSize = parseInt( elements.first().css( 'font-size' ) ), lineHeight = parseInt( elements.first().css( 'line-height' ) ); // Show 5 lines of text elements.css( 'max-height', ( 5 * lineHeight / fontSize ) + 'em' ); }, getTrackedUrl: function( anchor ) { var args = 'relatedposts_hit=1'; args += '&relatedposts_origin=' + $( anchor ).data( 'origin' ); args += '&relatedposts_position=' + $( anchor ).data( 'position' ); if ( '' == anchor.search ) { return anchor.pathname + '?' + args; } else { return anchor.pathname + anchor.search + '&' + args; } }, cleanupTrackedUrl: function() { if ( 'function' != typeof history.replaceState ) { return; } var cleaned_search = document.location.search.replace( /\brelatedposts_[a-z]+=[0-9]*&?\b/gi, '' ); if ( '?' == cleaned_search ) { cleaned_search = ''; } if ( document.location.search != cleaned_search ) { history.replaceState( {}, document.title, document.location.pathname + cleaned_search ); } } }; $( function() { jprp.cleanupTrackedUrl(); $.getJSON( jprp.getEndpointURL(), function( response ) { if ( 0 == response.items.length || 0 == $( '#jp-relatedposts' ).length ) { return; } jprp.response = response; var html = ''; if ( !response.show_thumbnails ) { html = jprp.generateMinimalHtml( response.items ); } else { html = jprp.generateVisualHtml( response.items ); } $( '#jp-relatedposts' ).append( html ); jprp.setVisualExcerptHeights(); $( '#jp-relatedposts' ).show(); $( '#jp-relatedposts a.jp-relatedposts-post-a' ).click(function() { this.href = jprp.getTrackedUrl( this ); }); } ); } ); })(jQuery); ;
JavaScript
/* Detect-zoom * ----------- * Cross Browser Zoom and Pixel Ratio Detector * Version 1.0.4 | Apr 1 2013 * dual-licensed under the WTFPL and MIT license * Maintained by https://github/tombigel * Original developer https://github.com/yonran */ //AMD and CommonJS initialization copied from https://github.com/zohararad/audio5js (function (root, ns, factory) { "use strict"; if (typeof (module) !== 'undefined' && module.exports) { // CommonJS module.exports = factory(ns, root); } else if (typeof (define) === 'function' && define.amd) { // AMD define("factory", function () { return factory(ns, root); }); } else { root[ns] = factory(ns, root); } }(window, 'detectZoom', function () { /** * Use devicePixelRatio if supported by the browser * @return {Number} * @private */ var devicePixelRatio = function () { return window.devicePixelRatio || 1; }; /** * Fallback function to set default values * @return {Object} * @private */ var fallback = function () { return { zoom: 1, devicePxPerCssPx: 1 }; }; /** * IE 8 and 9: no trick needed! * TODO: Test on IE10 and Windows 8 RT * @return {Object} * @private **/ var ie8 = function () { var zoom = Math.round((screen.deviceXDPI / screen.logicalXDPI) * 100) / 100; return { zoom: zoom, devicePxPerCssPx: zoom * devicePixelRatio() }; }; /** * For IE10 we need to change our technique again... * thanks https://github.com/stefanvanburen * @return {Object} * @private */ var ie10 = function () { var zoom = Math.round((document.documentElement.offsetHeight / window.innerHeight) * 100) / 100; return { zoom: zoom, devicePxPerCssPx: zoom * devicePixelRatio() }; }; /** * Mobile WebKit * the trick: window.innerWIdth is in CSS pixels, while * screen.width and screen.height are in system pixels. * And there are no scrollbars to mess up the measurement. * @return {Object} * @private */ var webkitMobile = function () { var deviceWidth = (Math.abs(window.orientation) == 90) ? screen.height : screen.width; var zoom = deviceWidth / window.innerWidth; return { zoom: zoom, devicePxPerCssPx: zoom * devicePixelRatio() }; }; /** * Desktop Webkit * the trick: an element's clientHeight is in CSS pixels, while you can * set its line-height in system pixels using font-size and * -webkit-text-size-adjust:none. * device-pixel-ratio: http://www.webkit.org/blog/55/high-dpi-web-sites/ * * Previous trick (used before http://trac.webkit.org/changeset/100847): * documentElement.scrollWidth is in CSS pixels, while * document.width was in system pixels. Note that this is the * layout width of the document, which is slightly different from viewport * because document width does not include scrollbars and might be wider * due to big elements. * @return {Object} * @private */ var webkit = function () { var important = function (str) { return str.replace(/;/g, " !important;"); }; var div = document.createElement('div'); div.innerHTML = "1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0"; div.setAttribute('style', important('font: 100px/1em sans-serif; -webkit-text-size-adjust: none; text-size-adjust: none; height: auto; width: 1em; padding: 0; overflow: visible;')); // The container exists so that the div will be laid out in its own flow // while not impacting the layout, viewport size, or display of the // webpage as a whole. // Add !important and relevant CSS rule resets // so that other rules cannot affect the results. var container = document.createElement('div'); container.setAttribute('style', important('width:0; height:0; overflow:hidden; visibility:hidden; position: absolute;')); container.appendChild(div); document.body.appendChild(container); var zoom = 1000 / div.clientHeight; zoom = Math.round(zoom * 100) / 100; document.body.removeChild(container); return{ zoom: zoom, devicePxPerCssPx: zoom * devicePixelRatio() }; }; /** * no real trick; device-pixel-ratio is the ratio of device dpi / css dpi. * (Note that this is a different interpretation than Webkit's device * pixel ratio, which is the ratio device dpi / system dpi). * * Also, for Mozilla, there is no difference between the zoom factor and the device ratio. * * @return {Object} * @private */ var firefox4 = function () { var zoom = mediaQueryBinarySearch('min--moz-device-pixel-ratio', '', 0, 10, 20, 0.0001); zoom = Math.round(zoom * 100) / 100; return { zoom: zoom, devicePxPerCssPx: zoom }; }; /** * Firefox 18.x * Mozilla added support for devicePixelRatio to Firefox 18, * but it is affected by the zoom level, so, like in older * Firefox we can't tell if we are in zoom mode or in a device * with a different pixel ratio * @return {Object} * @private */ var firefox18 = function () { return { zoom: firefox4().zoom, devicePxPerCssPx: devicePixelRatio() }; }; /** * works starting Opera 11.11 * the trick: outerWidth is the viewport width including scrollbars in * system px, while innerWidth is the viewport width including scrollbars * in CSS px * @return {Object} * @private */ var opera11 = function () { var zoom = window.top.outerWidth / window.top.innerWidth; zoom = Math.round(zoom * 100) / 100; return { zoom: zoom, devicePxPerCssPx: zoom * devicePixelRatio() }; }; /** * Use a binary search through media queries to find zoom level in Firefox * @param property * @param unit * @param a * @param b * @param maxIter * @param epsilon * @return {Number} */ var mediaQueryBinarySearch = function (property, unit, a, b, maxIter, epsilon) { var matchMedia; var head, style, div; if (window.matchMedia) { matchMedia = window.matchMedia; } else { head = document.getElementsByTagName('head')[0]; style = document.createElement('style'); head.appendChild(style); div = document.createElement('div'); div.className = 'mediaQueryBinarySearch'; div.style.display = 'none'; document.body.appendChild(div); matchMedia = function (query) { style.sheet.insertRule('@media ' + query + '{.mediaQueryBinarySearch ' + '{text-decoration: underline} }', 0); var matched = getComputedStyle(div, null).textDecoration == 'underline'; style.sheet.deleteRule(0); return {matches: matched}; }; } var ratio = binarySearch(a, b, maxIter); if (div) { head.removeChild(style); document.body.removeChild(div); } return ratio; function binarySearch(a, b, maxIter) { var mid = (a + b) / 2; if (maxIter <= 0 || b - a < epsilon) { return mid; } var query = "(" + property + ":" + mid + unit + ")"; if (matchMedia(query).matches) { return binarySearch(mid, b, maxIter - 1); } else { return binarySearch(a, mid, maxIter - 1); } } }; /** * Generate detection function * @private */ var detectFunction = (function () { var func = fallback; //IE8+ if (!isNaN(screen.logicalXDPI) && !isNaN(screen.systemXDPI)) { func = ie8; } // IE10+ / Touch else if (window.navigator.msMaxTouchPoints) { func = ie10; } //Mobile Webkit else if ('orientation' in window && typeof document.body.style.webkitMarquee === 'string') { func = webkitMobile; } //WebKit else if (typeof document.body.style.webkitMarquee === 'string') { func = webkit; } //Opera else if (navigator.userAgent.indexOf('Opera') >= 0) { func = opera11; } //Last one is Firefox //FF 18.x else if (window.devicePixelRatio) { func = firefox18; } //FF 4.0 - 17.x else if (firefox4().zoom > 0.001) { func = firefox4; } return func; }()); return ({ /** * Ratios.zoom shorthand * @return {Number} Zoom level */ zoom: function () { return detectFunction().zoom; }, /** * Ratios.devicePxPerCssPx shorthand * @return {Number} devicePxPerCssPx level */ device: function () { return detectFunction().devicePxPerCssPx; } }); })); var wpcom_img_zoomer = { zoomed: false, timer: null, interval: 1000, // zoom polling interval in millisecond // Should we apply width/height attributes to control the image size? imgNeedsSizeAtts: function( img ) { // Do not overwrite existing width/height attributes. if ( img.getAttribute('width') !== null || img.getAttribute('height') !== null ) return false; // Do not apply the attributes if the image is already constrained by a parent element. if ( img.width < img.naturalWidth || img.height < img.naturalHeight ) return false; return true; }, init: function() { var t = this; try{ t.zoomImages(); t.timer = setInterval( function() { t.zoomImages(); }, t.interval ); } catch(e){ } }, stop: function() { if ( this.timer ) clearInterval( this.timer ); }, getScale: function() { var scale = detectZoom.device(); // Round up to 1.5 or the next integer below the cap. if ( scale <= 1.0 ) scale = 1.0; else if ( scale <= 1.5 ) scale = 1.5; else if ( scale <= 2.0 ) scale = 2.0; else if ( scale <= 3.0 ) scale = 3.0; else if ( scale <= 4.0 ) scale = 4.0; else scale = 5.0; return scale; }, shouldZoom: function( scale ) { var t = this; // Do not operate on hidden frames. if ( "innerWidth" in window && !window.innerWidth ) return false; // Don't do anything until scale > 1 if ( scale == 1.0 && t.zoomed == false ) return false; return true; }, zoomImages: function() { var t = this; var scale = t.getScale(); if ( ! t.shouldZoom( scale ) ){ return; } t.zoomed = true; // Loop through all the <img> elements on the page. var imgs = document.getElementsByTagName("img"); for ( var i = 0; i < imgs.length; i++ ) { // Wait for original images to load if ( "complete" in imgs[i] && ! imgs[i].complete ) continue; // Skip images that don't need processing. var imgScale = imgs[i].getAttribute("scale"); if ( imgScale == scale || imgScale == "0" ) continue; // Skip images that have already failed at this scale var scaleFail = imgs[i].getAttribute("scale-fail"); if ( scaleFail && scaleFail <= scale ) continue; // Skip images that have no dimensions yet. if ( ! ( imgs[i].width && imgs[i].height ) ) continue; // Skip images from Lazy Load plugins if ( ! imgScale && imgs[i].getAttribute("data-lazy-src") && (imgs[i].getAttribute("data-lazy-src") !== imgs[i].getAttribute("src"))) continue; if ( t.scaleImage( imgs[i], scale ) ) { // Mark the img as having been processed at this scale. imgs[i].setAttribute("scale", scale); } else { // Set the flag to skip this image. imgs[i].setAttribute("scale", "0"); } } }, scaleImage: function( img, scale ) { var t = this; var newSrc = img.src; // Skip slideshow images if ( img.parentNode.className.match(/slideshow-slide/) ) return false; // Scale gravatars that have ?s= or ?size= if ( img.src.match( /^https?:\/\/([^\/]*\.)?gravatar\.com\/.+[?&](s|size)=/ ) ) { newSrc = img.src.replace( /([?&](s|size)=)(\d+)/, function( $0, $1, $2, $3 ) { // Stash the original size var originalAtt = "originals", originalSize = img.getAttribute(originalAtt); if ( originalSize === null ) { originalSize = $3; img.setAttribute(originalAtt, originalSize); if ( t.imgNeedsSizeAtts( img ) ) { // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; } } // Get the width/height of the image in CSS pixels var size = img.clientWidth; // Convert CSS pixels to device pixels var targetSize = Math.ceil(img.clientWidth * scale); // Don't go smaller than the original size targetSize = Math.max( targetSize, originalSize ); // Don't go larger than the service supports targetSize = Math.min( targetSize, 512 ); return $1 + targetSize; }); } // Scale resize queries (*.files.wordpress.com) that have ?w= or ?h= else if ( img.src.match( /^https?:\/\/([^\/]+)\.files\.wordpress\.com\/.+[?&][wh]=/ ) ) { if ( img.src.match( /[?&]crop/ ) ) return false; var changedAttrs = {}; var matches = img.src.match( /([?&]([wh])=)(\d+)/g ); for ( var i = 0; i < matches.length; i++ ) { var lr = matches[i].split( '=' ); var thisAttr = lr[0].replace(/[?&]/g, '' ); var thisVal = lr[1]; // Stash the original size var originalAtt = 'original' + thisAttr, originalSize = img.getAttribute( originalAtt ); if ( originalSize === null ) { originalSize = thisVal; img.setAttribute(originalAtt, originalSize); if ( t.imgNeedsSizeAtts( img ) ) { // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; } } // Get the width/height of the image in CSS pixels var size = thisAttr == 'w' ? img.clientWidth : img.clientHeight; var naturalSize = ( thisAttr == 'w' ? img.naturalWidth : img.naturalHeight ); // Convert CSS pixels to device pixels var targetSize = Math.ceil(size * scale); // Don't go smaller than the original size targetSize = Math.max( targetSize, originalSize ); // Don't go bigger unless the current one is actually lacking if ( scale > img.getAttribute("scale") && targetSize <= naturalSize ) targetSize = thisVal; // Don't try to go bigger if the image is already smaller than was requested if ( naturalSize < thisVal ) targetSize = thisVal; if ( targetSize != thisVal ) changedAttrs[ thisAttr ] = targetSize; } var w = changedAttrs.w || false; var h = changedAttrs.h || false; if ( w ) { newSrc = img.src.replace(/([?&])w=\d+/g, function( $0, $1 ) { return $1 + 'w=' + w; }); } if ( h ) { newSrc = newSrc.replace(/([?&])h=\d+/g, function( $0, $1 ) { return $1 + 'h=' + h; }); } } // Scale mshots that have width else if ( img.src.match(/^https?:\/\/([^\/]+\.)*(wordpress|wp)\.com\/mshots\/.+[?&]w=\d+/) ) { newSrc = img.src.replace( /([?&]w=)(\d+)/, function($0, $1, $2) { // Stash the original size var originalAtt = 'originalw', originalSize = img.getAttribute(originalAtt); if ( originalSize === null ) { originalSize = $2; img.setAttribute(originalAtt, originalSize); if ( t.imgNeedsSizeAtts( img ) ) { // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; } } // Get the width of the image in CSS pixels var size = img.clientWidth; // Convert CSS pixels to device pixels var targetSize = Math.ceil(size * scale); // Don't go smaller than the original size targetSize = Math.max( targetSize, originalSize ); // Don't go bigger unless the current one is actually lacking if ( scale > img.getAttribute("scale") && targetSize <= img.naturalWidth ) targetSize = $2; if ( $2 != targetSize ) return $1 + targetSize; return $0; }); } // Scale simple imgpress queries (s0.wp.com) that only specify w/h/fit else if ( img.src.match(/^https?:\/\/([^\/.]+\.)*(wp|wordpress)\.com\/imgpress\?(.+)/) ) { var imgpressSafeFunctions = ["zoom", "url", "h", "w", "fit", "filter", "brightness", "contrast", "colorize", "smooth", "unsharpmask"]; // Search the query string for unsupported functions. var qs = RegExp.$3.split('&'); for ( var q in qs ) { q = qs[q].split('=')[0]; if ( imgpressSafeFunctions.indexOf(q) == -1 ) { return false; } } // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; // Compute new src if ( scale == 1 ) newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?'); else newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?zoom=' + scale + '&'); } // Scale LaTeX images or Photon queries (i#.wp.com) else if ( img.src.match(/^https?:\/\/([^\/.]+\.)*(wp|wordpress)\.com\/latex\.php\?(latex|zoom)=(.+)/) || img.src.match(/^https?:\/\/i[\d]{1}\.wp\.com\/(.+)/) ) { // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; // Compute new src if ( scale == 1 ) newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?'); else newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?zoom=' + scale + '&'); } // Scale static assets that have a name matching *-1x.png or *@1x.png else if ( img.src.match(/^https?:\/\/[^\/]+\/.*[-@]([12])x\.(gif|jpeg|jpg|png)(\?|$)/) ) { // Fix width and height attributes to rendered dimensions. img.width = img.width; img.height = img.height; var currentSize = RegExp.$1, newSize = currentSize; if ( scale <= 1 ) newSize = 1; else newSize = 2; if ( currentSize != newSize ) newSrc = img.src.replace(/([-@])[12]x\.(gif|jpeg|jpg|png)(\?|$)/, '$1'+newSize+'x.$2$3'); } else { return false; } // Don't set img.src unless it has changed. This avoids unnecessary reloads. if ( newSrc != img.src ) { // Store the original img.src var prevSrc, origSrc = img.getAttribute("src-orig"); if ( !origSrc ) { origSrc = img.src; img.setAttribute("src-orig", origSrc); } // In case of error, revert img.src prevSrc = img.src; img.onerror = function(){ img.src = prevSrc; if ( img.getAttribute("scale-fail") < scale ) img.setAttribute("scale-fail", scale); img.onerror = null; }; // Finally load the new image img.src = newSrc; } return true; } }; wpcom_img_zoomer.init(); ; var addComment={moveForm:function(a,b,c,d){var e,f=this,g=f.I(a),h=f.I(c),i=f.I("cancel-comment-reply-link"),j=f.I("comment_parent"),k=f.I("comment_post_ID");if(g&&h&&i&&j){f.respondId=c,d=d||!1,f.I("wp-temp-form-div")||(e=document.createElement("div"),e.id="wp-temp-form-div",e.style.display="none",h.parentNode.insertBefore(e,h)),g.parentNode.insertBefore(h,g.nextSibling),k&&d&&(k.value=d),j.value=b,i.style.display="",i.onclick=function(){var a=addComment,b=a.I("wp-temp-form-div"),c=a.I(a.respondId);if(b&&c)return a.I("comment_parent").value="0",b.parentNode.insertBefore(c,b),b.parentNode.removeChild(b),this.style.display="none",this.onclick=null,!1};try{f.I("comment").focus()}catch(l){}return!1}},I:function(a){return document.getElementById(a)}};; /*jslint indent: 2, browser: true, bitwise: true, plusplus: true */ /*! Copyright Twitter Inc. and other contributors. Licensed under MIT *//* https://github.com/twitter/twemoji/blob/gh-pages/LICENSE */ // WARNING: this file is generated automatically via // `node twemoji-generator.js` // please update its `createTwemoji` function // at the bottom of the same file instead. var twemoji = (function ( ) { 'use strict'; /*jshint maxparams:4 */ var // the exported module object twemoji = { ///////////////////////// // properties // ///////////////////////// // default assets url, by default will be Twitter Inc. CDN base: (location.protocol === 'https:' ? 'https:' : 'http:') + '//twemoji.maxcdn.com/', // default assets file extensions, by default '.png' ext: '.svg', // default assets/folder size, by default "36x36" // available via Twitter CDN: 16, 36, 72 size: 'svg', // basic utilities / helpers to convert code points // to JavaScript surrogates and vice versa convert: { /** * Given an HEX codepoint, returns UTF16 surrogate pairs. * * @param string generic codepoint, i.e. '1F4A9' * @return string codepoint transformed into utf16 surrogates pair, * i.e. \uD83D\uDCA9 * * @example * twemoji.convert.fromCodePoint('1f1e8'); * // "\ud83c\udde8" * * '1f1e8-1f1f3'.split('-').map(twemoji.convert.fromCodePoint).join('') * // "\ud83c\udde8\ud83c\uddf3" */ fromCodePoint: fromCodePoint, /** * Given UTF16 surrogate pairs, returns the equivalent HEX codepoint. * * @param string generic utf16 surrogates pair, i.e. \uD83D\uDCA9 * @param string optional separator for double code points, default='-' * @return string utf16 transformed into codepoint, i.e. '1F4A9' * * @example * twemoji.convert.toCodePoint('\ud83c\udde8\ud83c\uddf3'); * // "1f1e8-1f1f3" * * twemoji.convert.toCodePoint('\ud83c\udde8\ud83c\uddf3', '~'); * // "1f1e8~1f1f3" */ toCodePoint: toCodePoint }, ///////////////////////// // methods // ///////////////////////// /** * User first: used to remove missing images * preserving the original text intent when * a fallback for network problems is desired. * Automatically added to Image nodes via DOM * It could be recycled for string operations via: * $('img.emoji').on('error', twemoji.onerror) */ onerror: function onerror() { if (this.parentNode) { this.parentNode.replaceChild(createText(this.alt), this); } }, /** * Main method/logic to generate either <img> tags or HTMLImage nodes. * "emojify" a generic text or DOM Element. * * @overloads * * String replacement for `innerHTML` or server side operations * twemoji.parse(string); * twemoji.parse(string, Function); * twemoji.parse(string, Object); * * HTMLElement tree parsing for safer operations over existing DOM * twemoji.parse(HTMLElement); * twemoji.parse(HTMLElement, Function); * twemoji.parse(HTMLElement, Object); * * @param string|HTMLElement the source to parse and enrich with emoji. * * string replace emoji matches with <img> tags. * Mainly used to inject emoji via `innerHTML` * It does **not** parse the string or validate it, * it simply replaces found emoji with a tag. * NOTE: be sure this won't affect security. * * HTMLElement walk through the DOM tree and find emoji * that are inside **text node only** (nodeType === 3) * Mainly used to put emoji in already generated DOM * without compromising surrounding nodes and * **avoiding** the usage of `innerHTML`. * NOTE: Using DOM elements instead of strings should * improve security without compromising too much * performance compared with a less safe `innerHTML`. * * @param Function|Object [optional] * either the callback that will be invoked or an object * with all properties to use per each found emoji. * * Function if specified, this will be invoked per each emoji * that has been found through the RegExp except * those follwed by the invariant \uFE0E ("as text"). * Once invoked, parameters will be: * * codePoint:string the lower case HEX code point * i.e. "1f4a9" * * options:Object all info for this parsing operation * * variant:char the optional \uFE0F ("as image") * variant, in case this info * is anyhow meaningful. * By default this is ignored. * * If such callback will return a falsy value instead * of a valid `src` to use for the image, nothing will * actually change for that specific emoji. * * * Object if specified, an object containing the following properties * * callback Function the callback to invoke per each found emoji. * base string the base url, by default twemoji.base * ext string the image extension, by default twemoji.ext * size string the assets size, by default twemoji.size * * @example * * twemoji.parse("I \u2764\uFE0F emoji!"); * // I <img class="emoji" draggable="false" alt="❤️" src="/assets/2764.gif"> emoji! * * * twemoji.parse("I \u2764\uFE0F emoji!", function(icon, options, variant) { * return '/assets/' + icon + '.gif'; * }); * // I <img class="emoji" draggable="false" alt="❤️" src="/assets/2764.gif"> emoji! * * * twemoji.parse("I \u2764\uFE0F emoji!", { * size: 72, * callback: function(icon, options, variant) { * return '/assets/' + options.size + '/' + icon + options.ext; * } * }); * // I <img class="emoji" draggable="false" alt="❤️" src="/assets/72x72/2764.png"> emoji! * */ parse: parse, /** * Given a string, invokes the callback argument * per each emoji found in such string. * This is the most raw version used by * the .parse(string) method itself. * * @param string generic string to parse * @param Function a generic callback that will be * invoked to replace the content. * This calback wil receive standard * String.prototype.replace(str, callback) * arguments such: * callback( * match, // the emoji match * icon, // the emoji text (same as text) * variant // either '\uFE0E' or '\uFE0F', if present * ); * * and others commonly received via replace. * * NOTE: When the variant \uFE0E is found, remember this is an explicit intent * from the user: the emoji should **not** be replaced with an image. * In \uFE0F case one, it's the opposite, it should be graphic. * This utility convetion is that only \uFE0E are not translated into images. */ replace: replace, /** * Simplify string tests against emoji. * * @param string some text that might contain emoji * @return boolean true if any emoji was found, false otherwise. * * @example * * if (twemoji.test(someContent)) { * console.log("emoji All The Things!"); * } */ test: test }, // RegExp based on emoji's official Unicode standards // http://www.unicode.org/Public/UNIDATA/EmojiSources.txt re = /((?:\ud83c\udde8\ud83c\uddf3|\ud83c\uddfa\ud83c\uddf8|\ud83c\uddf7\ud83c\uddfa|\ud83c\uddf0\ud83c\uddf7|\ud83c\uddef\ud83c\uddf5|\ud83c\uddee\ud83c\uddf9|\ud83c\uddec\ud83c\udde7|\ud83c\uddeb\ud83c\uddf7|\ud83c\uddea\ud83c\uddf8|\ud83c\udde9\ud83c\uddea|\u0039\u20e3|\u0038\u20e3|\u0037\u20e3|\u0036\u20e3|\u0035\u20e3|\u0034\u20e3|\u0033\u20e3|\u0032\u20e3|\u0031\u20e3|\u0030\u20e3|\u0023\u20e3|\ud83d\udeb3|\ud83d\udeb1|\ud83d\udeb0|\ud83d\udeaf|\ud83d\udeae|\ud83d\udea6|\ud83d\udea3|\ud83d\udea1|\ud83d\udea0|\ud83d\ude9f|\ud83d\ude9e|\ud83d\ude9d|\ud83d\ude9c|\ud83d\ude9b|\ud83d\ude98|\ud83d\ude96|\ud83d\ude94|\ud83d\ude90|\ud83d\ude8e|\ud83d\ude8d|\ud83d\ude8b|\ud83d\ude8a|\ud83d\ude88|\ud83d\ude86|\ud83d\ude82|\ud83d\ude81|\ud83d\ude36|\ud83d\ude34|\ud83d\ude2f|\ud83d\ude2e|\ud83d\ude2c|\ud83d\ude27|\ud83d\ude26|\ud83d\ude1f|\ud83d\ude1b|\ud83d\ude19|\ud83d\ude17|\ud83d\ude15|\ud83d\ude11|\ud83d\ude10|\ud83d\ude0e|\ud83d\ude08|\ud83d\ude07|\ud83d\ude00|\ud83d\udd67|\ud83d\udd66|\ud83d\udd65|\ud83d\udd64|\ud83d\udd63|\ud83d\udd62|\ud83d\udd61|\ud83d\udd60|\ud83d\udd5f|\ud83d\udd5e|\ud83d\udd5d|\ud83d\udd5c|\ud83d\udd2d|\ud83d\udd2c|\ud83d\udd15|\ud83d\udd09|\ud83d\udd08|\ud83d\udd07|\ud83d\udd06|\ud83d\udd05|\ud83d\udd04|\ud83d\udd02|\ud83d\udd01|\ud83d\udd00|\ud83d\udcf5|\ud83d\udcef|\ud83d\udced|\ud83d\udcec|\ud83d\udcb7|\ud83d\udcb6|\ud83d\udcad|\ud83d\udc6d|\ud83d\udc6c|\ud83d\udc65|\ud83d\udc2a|\ud83d\udc16|\ud83d\udc15|\ud83d\udc13|\ud83d\udc10|\ud83d\udc0f|\ud83d\udc0b|\ud83d\udc0a|\ud83d\udc09|\ud83d\udc08|\ud83d\udc07|\ud83d\udc06|\ud83d\udc05|\ud83d\udc04|\ud83d\udc03|\ud83d\udc02|\ud83d\udc01|\ud83d\udc00|\ud83c\udfe4|\ud83c\udfc9|\ud83c\udfc7|\ud83c\udf7c|\ud83c\udf50|\ud83c\udf4b|\ud83c\udf33|\ud83c\udf32|\ud83c\udf1e|\ud83c\udf1d|\ud83c\udf1c|\ud83c\udf1a|\ud83c\udf18|\ud83c\udccf|\ud83c\udd70|\ud83c\udd71|\ud83c\udd7e|\ud83c\udd8e|\ud83c\udd91|\ud83c\udd92|\ud83c\udd93|\ud83c\udd94|\ud83c\udd95|\ud83c\udd96|\ud83c\udd97|\ud83c\udd98|\ud83c\udd99|\ud83c\udd9a|\ud83d\ude0d|\ud83d\udec5|\ud83d\udec4|\ud83d\udec3|\ud83d\udec2|\ud83d\udec1|\ud83d\udebf|\ud83d\udeb8|\ud83d\udeb7|\ud83d\udeb5|\ud83c\ude01|\ud83c\ude02|\ud83c\ude32|\ud83c\ude33|\ud83c\ude34|\ud83c\ude35|\ud83c\ude36|\ud83c\ude37|\ud83c\ude38|\ud83c\ude39|\ud83c\ude3a|\ud83c\ude50|\ud83c\ude51|\ud83c\udf00|\ud83c\udf01|\ud83c\udf02|\ud83c\udf03|\ud83c\udf04|\ud83c\udf05|\ud83c\udf06|\ud83c\udf07|\ud83c\udf08|\ud83c\udf09|\ud83c\udf0a|\ud83c\udf0b|\ud83c\udf0c|\ud83c\udf0f|\ud83c\udf11|\ud83c\udf13|\ud83c\udf14|\ud83c\udf15|\ud83c\udf19|\ud83c\udf1b|\ud83c\udf1f|\ud83c\udf20|\ud83c\udf30|\ud83c\udf31|\ud83c\udf34|\ud83c\udf35|\ud83c\udf37|\ud83c\udf38|\ud83c\udf39|\ud83c\udf3a|\ud83c\udf3b|\ud83c\udf3c|\ud83c\udf3d|\ud83c\udf3e|\ud83c\udf3f|\ud83c\udf40|\ud83c\udf41|\ud83c\udf42|\ud83c\udf43|\ud83c\udf44|\ud83c\udf45|\ud83c\udf46|\ud83c\udf47|\ud83c\udf48|\ud83c\udf49|\ud83c\udf4a|\ud83c\udf4c|\ud83c\udf4d|\ud83c\udf4e|\ud83c\udf4f|\ud83c\udf51|\ud83c\udf52|\ud83c\udf53|\ud83c\udf54|\ud83c\udf55|\ud83c\udf56|\ud83c\udf57|\ud83c\udf58|\ud83c\udf59|\ud83c\udf5a|\ud83c\udf5b|\ud83c\udf5c|\ud83c\udf5d|\ud83c\udf5e|\ud83c\udf5f|\ud83c\udf60|\ud83c\udf61|\ud83c\udf62|\ud83c\udf63|\ud83c\udf64|\ud83c\udf65|\ud83c\udf66|\ud83c\udf67|\ud83c\udf68|\ud83c\udf69|\ud83c\udf6a|\ud83c\udf6b|\ud83c\udf6c|\ud83c\udf6d|\ud83c\udf6e|\ud83c\udf6f|\ud83c\udf70|\ud83c\udf71|\ud83c\udf72|\ud83c\udf73|\ud83c\udf74|\ud83c\udf75|\ud83c\udf76|\ud83c\udf77|\ud83c\udf78|\ud83c\udf79|\ud83c\udf7a|\ud83c\udf7b|\ud83c\udf80|\ud83c\udf81|\ud83c\udf82|\ud83c\udf83|\ud83c\udf84|\ud83c\udf85|\ud83c\udf86|\ud83c\udf87|\ud83c\udf88|\ud83c\udf89|\ud83c\udf8a|\ud83c\udf8b|\ud83c\udf8c|\ud83c\udf8d|\ud83c\udf8e|\ud83c\udf8f|\ud83c\udf90|\ud83c\udf91|\ud83c\udf92|\ud83c\udf93|\ud83c\udfa0|\ud83c\udfa1|\ud83c\udfa2|\ud83c\udfa3|\ud83c\udfa4|\ud83c\udfa5|\ud83c\udfa6|\ud83c\udfa7|\ud83c\udfa8|\ud83c\udfa9|\ud83c\udfaa|\ud83c\udfab|\ud83c\udfac|\ud83c\udfad|\ud83c\udfae|\ud83c\udfaf|\ud83c\udfb0|\ud83c\udfb1|\ud83c\udfb2|\ud83c\udfb3|\ud83c\udfb4|\ud83c\udfb5|\ud83c\udfb6|\ud83c\udfb7|\ud83c\udfb8|\ud83c\udfb9|\ud83c\udfba|\ud83c\udfbb|\ud83c\udfbc|\ud83c\udfbd|\ud83c\udfbe|\ud83c\udfbf|\ud83c\udfc0|\ud83c\udfc1|\ud83c\udfc2|\ud83c\udfc3|\ud83c\udfc4|\ud83c\udfc6|\ud83c\udfc8|\ud83c\udfca|\ud83c\udfe0|\ud83c\udfe1|\ud83c\udfe2|\ud83c\udfe3|\ud83c\udfe5|\ud83c\udfe6|\ud83c\udfe7|\ud83c\udfe8|\ud83c\udfe9|\ud83c\udfea|\ud83c\udfeb|\ud83c\udfec|\ud83c\udfed|\ud83c\udfee|\ud83c\udfef|\ud83c\udff0|\ud83d\udc0c|\ud83d\udc0d|\ud83d\udc0e|\ud83d\udc11|\ud83d\udc12|\ud83d\udc14|\ud83d\udc17|\ud83d\udc18|\ud83d\udc19|\ud83d\udc1a|\ud83d\udc1b|\ud83d\udc1c|\ud83d\udc1d|\ud83d\udc1e|\ud83d\udc1f|\ud83d\udc20|\ud83d\udc21|\ud83d\udc22|\ud83d\udc23|\ud83d\udc24|\ud83d\udc25|\ud83d\udc26|\ud83d\udc27|\ud83d\udc28|\ud83d\udc29|\ud83d\udc2b|\ud83d\udc2c|\ud83d\udc2d|\ud83d\udc2e|\ud83d\udc2f|\ud83d\udc30|\ud83d\udc31|\ud83d\udc32|\ud83d\udc33|\ud83d\udc34|\ud83d\udc35|\ud83d\udc36|\ud83d\udc37|\ud83d\udc38|\ud83d\udc39|\ud83d\udc3a|\ud83d\udc3b|\ud83d\udc3c|\ud83d\udc3d|\ud83d\udc3e|\ud83d\udc40|\ud83d\udc42|\ud83d\udc43|\ud83d\udc44|\ud83d\udc45|\ud83d\udc46|\ud83d\udc47|\ud83d\udc48|\ud83d\udc49|\ud83d\udc4a|\ud83d\udc4b|\ud83d\udc4c|\ud83d\udc4d|\ud83d\udc4e|\ud83d\udc4f|\ud83d\udc50|\ud83d\udc51|\ud83d\udc52|\ud83d\udc53|\ud83d\udc54|\ud83d\udc55|\ud83d\udc56|\ud83d\udc57|\ud83d\udc58|\ud83d\udc59|\ud83d\udc5a|\ud83d\udc5b|\ud83d\udc5c|\ud83d\udc5d|\ud83d\udc5e|\ud83d\udc5f|\ud83d\udc60|\ud83d\udc61|\ud83d\udc62|\ud83d\udc63|\ud83d\udc64|\ud83d\udc66|\ud83d\udc67|\ud83d\udc68|\ud83d\udc69|\ud83d\udc6a|\ud83d\udc6b|\ud83d\udc6e|\ud83d\udc6f|\ud83d\udc70|\ud83d\udc71|\ud83d\udc72|\ud83d\udc73|\ud83d\udc74|\ud83d\udc75|\ud83d\udc76|\ud83d\udc77|\ud83d\udc78|\ud83d\udc79|\ud83d\udc7a|\ud83d\udc7b|\ud83d\udc7c|\ud83d\udc7d|\ud83d\udc7e|\ud83d\udc7f|\ud83d\udc80|\ud83d\udc81|\ud83d\udc82|\ud83d\udc83|\ud83d\udc84|\ud83d\udc85|\ud83d\udc86|\ud83d\udc87|\ud83d\udc88|\ud83d\udc89|\ud83d\udc8a|\ud83d\udc8b|\ud83d\udc8c|\ud83d\udc8d|\ud83d\udc8e|\ud83d\udc8f|\ud83d\udc90|\ud83d\udc91|\ud83d\udc92|\ud83d\udc93|\ud83d\udc94|\ud83d\udc95|\ud83d\udc96|\ud83d\udc97|\ud83d\udc98|\ud83d\udc99|\ud83d\udc9a|\ud83d\udc9b|\ud83d\udc9c|\ud83d\udc9d|\ud83d\udc9e|\ud83d\udc9f|\ud83d\udca0|\ud83d\udca1|\ud83d\udca2|\ud83d\udca3|\ud83d\udca4|\ud83d\udca5|\ud83d\udca6|\ud83d\udca7|\ud83d\udca8|\ud83d\udca9|\ud83d\udcaa|\ud83d\udcab|\ud83d\udcac|\ud83d\udcae|\ud83d\udcaf|\ud83d\udcb0|\ud83d\udcb1|\ud83d\udcb2|\ud83d\udcb3|\ud83d\udcb4|\ud83d\udcb5|\ud83d\udcb8|\ud83d\udcb9|\ud83d\udcba|\ud83d\udcbb|\ud83d\udcbc|\ud83d\udcbd|\ud83d\udcbe|\ud83d\udcbf|\ud83d\udcc0|\ud83d\udcc1|\ud83d\udcc2|\ud83d\udcc3|\ud83d\udcc4|\ud83d\udcc5|\ud83d\udcc6|\ud83d\udcc7|\ud83d\udcc8|\ud83d\udcc9|\ud83d\udcca|\ud83d\udccb|\ud83d\udccc|\ud83d\udccd|\ud83d\udcce|\ud83d\udccf|\ud83d\udcd0|\ud83d\udcd1|\ud83d\udcd2|\ud83d\udcd3|\ud83d\udcd4|\ud83d\udcd5|\ud83d\udcd6|\ud83d\udcd7|\ud83d\udcd8|\ud83d\udcd9|\ud83d\udcda|\ud83d\udcdb|\ud83d\udcdc|\ud83d\udcdd|\ud83d\udcde|\ud83d\udcdf|\ud83d\udce0|\ud83d\udce1|\ud83d\udce2|\ud83d\udce3|\ud83d\udce4|\ud83d\udce5|\ud83d\udce6|\ud83d\udce7|\ud83d\udce8|\ud83d\udce9|\ud83d\udcea|\ud83d\udceb|\ud83d\udcee|\ud83d\udcf0|\ud83d\udcf1|\ud83d\udcf2|\ud83d\udcf3|\ud83d\udcf4|\ud83d\udcf6|\ud83d\udcf7|\ud83d\udcf9|\ud83d\udcfa|\ud83d\udcfb|\ud83d\udcfc|\ud83d\udd03|\ud83d\udd0a|\ud83d\udd0b|\ud83d\udd0c|\ud83d\udd0d|\ud83d\udd0e|\ud83d\udd0f|\ud83d\udd10|\ud83d\udd11|\ud83d\udd12|\ud83d\udd13|\ud83d\udd14|\ud83d\udd16|\ud83d\udd17|\ud83d\udd18|\ud83d\udd19|\ud83d\udd1a|\ud83d\udd1b|\ud83d\udd1c|\ud83d\udd1d|\ud83d\udd1e|\ud83d\udd1f|\ud83d\udd20|\ud83d\udd21|\ud83d\udd22|\ud83d\udd23|\ud83d\udd24|\ud83d\udd25|\ud83d\udd26|\ud83d\udd27|\ud83d\udd28|\ud83d\udd29|\ud83d\udd2a|\ud83d\udd2b|\ud83d\udd2e|\ud83d\udd2f|\ud83d\udd30|\ud83d\udd31|\ud83d\udd32|\ud83d\udd33|\ud83d\udd34|\ud83d\udd35|\ud83d\udd36|\ud83d\udd37|\ud83d\udd38|\ud83d\udd39|\ud83d\udd3a|\ud83d\udd3b|\ud83d\udd3c|\ud83d\udd3d|\ud83d\udd50|\ud83d\udd51|\ud83d\udd52|\ud83d\udd53|\ud83d\udd54|\ud83d\udd55|\ud83d\udd56|\ud83d\udd57|\ud83d\udd58|\ud83d\udd59|\ud83d\udd5a|\ud83d\udd5b|\ud83d\uddfb|\ud83d\uddfc|\ud83d\uddfd|\ud83d\uddfe|\ud83d\uddff|\ud83d\ude01|\ud83d\ude02|\ud83d\ude03|\ud83d\ude04|\ud83d\ude05|\ud83d\ude06|\ud83d\ude09|\ud83d\ude0a|\ud83d\ude0b|\ud83d\ude0c|\ud83d\udeb4|\ud83d\ude0f|\ud83d\ude12|\ud83d\ude13|\ud83d\ude14|\ud83d\ude16|\ud83d\ude18|\ud83d\ude1a|\ud83d\ude1c|\ud83d\ude1d|\ud83d\ude1e|\ud83d\ude20|\ud83d\ude21|\ud83d\ude22|\ud83d\ude23|\ud83d\ude24|\ud83d\ude25|\ud83d\ude28|\ud83d\ude29|\ud83d\ude2a|\ud83d\ude2b|\ud83d\ude2d|\ud83d\ude30|\ud83d\ude31|\ud83d\ude32|\ud83d\ude33|\ud83d\ude35|\ud83d\ude37|\ud83d\ude38|\ud83d\ude39|\ud83d\ude3a|\ud83d\ude3b|\ud83d\ude3c|\ud83d\ude3d|\ud83d\ude3e|\ud83d\ude3f|\ud83d\ude40|\ud83d\ude45|\ud83d\ude46|\ud83d\ude47|\ud83d\ude48|\ud83d\ude49|\ud83d\ude4a|\ud83d\ude4b|\ud83d\ude4c|\ud83d\ude4d|\ud83d\ude4e|\ud83d\ude4f|\ud83d\ude80|\ud83d\ude83|\ud83d\ude84|\ud83d\ude85|\ud83d\ude87|\ud83d\ude89|\ud83d\ude8c|\ud83d\ude8f|\ud83d\ude91|\ud83d\ude92|\ud83d\ude93|\ud83d\ude95|\ud83d\ude97|\ud83d\ude99|\ud83d\ude9a|\ud83d\udea2|\ud83d\udea4|\ud83d\udea5|\ud83d\udea7|\ud83d\udea8|\ud83d\udea9|\ud83d\udeaa|\ud83d\udeab|\ud83d\udeac|\ud83d\udead|\ud83d\udeb2|\ud83d\udeb6|\ud83d\udeb9|\ud83d\udeba|\ud83d\udebb|\ud83d\udebc|\ud83d\udebd|\ud83d\udebe|\ud83d\udec0|\ud83c\udde6|\ud83c\udde7|\ud83c\udde8|\ud83c\udde9|\ud83c\uddea|\ud83c\uddeb|\ud83c\uddec|\ud83c\udded|\ud83c\uddee|\ud83c\uddef|\ud83c\uddf0|\ud83c\uddf1|\ud83c\uddf2|\ud83c\uddf3|\ud83c\uddf4|\ud83c\uddf5|\ud83c\uddf6|\ud83c\uddf7|\ud83c\uddf8|\ud83c\uddf9|\ud83c\uddfa|\ud83c\uddfb|\ud83c\uddfc|\ud83c\uddfd|\ud83c\uddfe|\ud83c\uddff|\ud83c\udf0d|\ud83c\udf0e|\ud83c\udf10|\ud83c\udf12|\ud83c\udf16|\ud83c\udf17|\ud83c\udf18|\ud83c\udf1a|\ud83c\udf1c|\ud83c\udf1d|\ud83c\udf1e|\ud83c\udf32|\ud83c\udf33|\ud83c\udf4b|\ud83c\udf50|\ud83c\udf7c|\ud83c\udfc7|\ud83c\udfc9|\ud83c\udfe4|\ud83d\udc00|\ud83d\udc01|\ud83d\udc02|\ud83d\udc03|\ud83d\udc04|\ud83d\udc05|\ud83d\udc06|\ud83d\udc07|\ud83d\udc08|\ud83d\udc09|\ud83d\udc0a|\ud83d\udc0b|\ud83d\udc0f|\ud83d\udc10|\ud83d\udc13|\ud83d\udc15|\ud83d\udc16|\ud83d\udc2a|\ud83d\udc65|\ud83d\udc6c|\ud83d\udc6d|\ud83d\udcad|\ud83d\udcb6|\ud83d\udcb7|\ud83d\udcec|\ud83d\udced|\ud83d\udcef|\ud83d\udcf5|\ud83d\udd00|\ud83d\udd01|\ud83d\udd02|\ud83d\udd04|\ud83d\udd05|\ud83d\udd06|\ud83d\udd07|\ud83d\udd08|\ud83d\udd09|\ud83d\udd15|\ud83d\udd2c|\ud83d\udd2d|\ud83d\udd5c|\ud83d\udd5d|\ud83d\udd5e|\ud83d\udd5f|\ud83d\udd60|\ud83d\udd61|\ud83d\udd62|\ud83d\udd63|\ud83d\udd64|\ud83d\udd65|\ud83d\udd66|\ud83d\udd67|\ud83d\ude00|\ud83d\ude07|\ud83d\ude08|\ud83d\ude0e|\ud83d\ude10|\ud83d\ude11|\ud83d\ude15|\ud83d\ude17|\ud83d\ude19|\ud83d\ude1b|\ud83d\ude1f|\ud83d\ude26|\ud83d\ude27|\ud83d\ude2c|\ud83d\ude2e|\ud83d\ude2f|\ud83d\ude34|\ud83d\ude36|\ud83d\ude81|\ud83d\ude82|\ud83d\ude86|\ud83d\ude88|\ud83d\ude8a|\ud83d\ude8b|\ud83d\ude8d|\ud83d\ude8e|\ud83d\ude90|\ud83d\ude94|\ud83d\ude96|\ud83d\ude98|\ud83d\ude9b|\ud83d\ude9c|\ud83d\ude9d|\ud83d\ude9e|\ud83d\ude9f|\ud83d\udea0|\ud83d\udea1|\ud83d\udea3|\ud83d\udea6|\ud83d\udeae|\ud83d\udeaf|\ud83d\udeb0|\ud83d\udeb1|\ud83d\udeb3|\ud83d\udeb4|\ud83d\udeb5|\ud83d\udeb7|\ud83d\udeb8|\ud83d\udebf|\ud83d\udec1|\ud83d\udec2|\ud83d\udec3|\ud83d\udec4|\ud83d\udec5|\ud83c\udf17|\ud83c\udf16|\ud83c\udde6|\ud83c\udde7|\ud83c\udde8|\ud83c\udde9|\ud83c\uddea|\ud83c\uddeb|\ud83c\uddec|\ud83c\udded|\ud83c\uddee|\ud83c\uddef|\ud83c\uddf0|\ud83c\uddf1|\ud83c\uddf2|\ud83c\uddf3|\ud83c\uddf4|\ud83c\uddf5|\ud83c\uddf6|\ud83c\uddf7|\ud83c\uddf8|\ud83c\uddf9|\ud83c\uddfa|\ud83c\uddfb|\ud83c\uddfc|\ud83c\uddfd|\ud83c\uddfe|\ud83c\uddff|\ud83c\udf0d|\ud83c\udf0e|\ud83c\udf10|\ud83c\udf12|\ud83c\udf16|\ud83c\udf17|\ud83c\udf18|\ud83c\udf1a|\ud83c\udf1c|\ud83c\udf1d|\ud83c\udf1e|\ud83c\udf32|\ud83c\udf33|\ud83c\udf4b|\ud83c\udf50|\ud83c\udf7c|\ud83c\udfc7|\ud83c\udfc9|\ud83c\udfe4|\ud83d\udc00|\ud83d\udc01|\ud83d\udc02|\ud83d\udc03|\ud83d\udc04|\ud83d\udc05|\ud83d\udc06|\ud83d\udc07|\ud83d\udc08|\ud83d\udc09|\ud83d\udc0a|\ud83d\udc0b|\ud83d\udc0f|\ud83d\udc10|\ud83d\udc13|\ud83d\udc15|\ud83d\udc16|\ud83d\udc2a|\ud83d\udc65|\ud83d\udc6c|\ud83d\udc6d|\ud83d\udcad|\ud83d\udcb6|\ud83d\udcb7|\ud83d\udcec|\ud83d\udced|\ud83d\udcef|\ud83d\udcf5|\ud83d\udd00|\ud83d\udd01|\ud83d\udd02|\ud83d\udd04|\ud83d\udd05|\ud83d\udd06|\ud83d\udd07|\ud83d\udd08|\ud83d\udd09|\ud83d\udd15|\ud83d\udd2c|\ud83d\udd2d|\ud83d\udd5c|\ud83d\udd5d|\ud83d\udd5e|\ud83d\udd5f|\ud83d\udd60|\ud83d\udd61|\ud83d\udd62|\ud83d\udd63|\ud83d\udd64|\ud83d\udd65|\ud83d\udd66|\ud83d\udd67|\ud83d\ude00|\ud83d\ude07|\ud83d\ude08|\ud83d\ude0e|\ud83d\ude10|\ud83d\ude11|\ud83d\ude15|\ud83d\ude17|\ud83d\ude19|\ud83d\ude1b|\ud83d\ude1f|\ud83d\ude26|\ud83d\ude27|\ud83d\ude2c|\ud83d\ude2e|\ud83d\ude2f|\ud83d\ude34|\ud83d\ude36|\ud83d\ude81|\ud83d\ude82|\ud83d\ude86|\ud83d\ude88|\ud83d\ude8a|\ud83d\ude8b|\ud83d\ude8d|\ud83d\ude8e|\ud83d\ude90|\ud83d\ude94|\ud83d\ude96|\ud83d\ude98|\ud83d\ude9b|\ud83d\ude9c|\ud83d\ude9d|\ud83d\ude9e|\ud83d\ude9f|\ud83d\udea0|\ud83d\udea1|\ud83d\udea3|\ud83d\udea6|\ud83d\udeae|\ud83d\udeaf|\ud83d\udeb0|\ud83d\udeb1|\ud83d\udeb3|\ud83d\udeb4|\ud83d\udeb5|\ud83d\udeb7|\ud83d\udeb8|\ud83d\udebf|\ud83d\udec1|\ud83d\udec2|\ud83d\udec3|\ud83d\udec4|\ud83d\udec5|\ud83c\udf12|\ud83c\udf10|\ud83c\udde6|\ud83c\udde7|\ud83c\udde8|\ud83c\udde9|\ud83c\uddea|\ud83c\uddeb|\ud83c\uddec|\ud83c\udded|\ud83c\uddee|\ud83c\uddef|\ud83c\uddf0|\ud83c\uddf1|\ud83c\uddf2|\ud83c\uddf3|\ud83c\uddf4|\ud83c\uddf5|\ud83c\uddf6|\ud83c\uddf7|\ud83c\uddf8|\ud83c\uddf9|\ud83c\uddfa|\ud83c\uddfb|\ud83c\uddfc|\ud83c\uddfd|\ud83c\uddfe|\ud83c\uddff|\ud83c\udf0d|\ud83c\udf0e|\ue50a|\ue50a|\ue50a|\u27bf|\u3030|\u27b0|\u2797|\u2796|\u2795|\u2755|\u2754|\u2753|\u274e|\u274c|\u2728|\u270b|\u270a|\u2705|\u26ce|\u27bf|\u23f3|\u23f0|\u23ec|\u23eb|\u23ea|\u23e9|\u2122|\u27bf|\u00a9|\u00ae)|(?:(?:\ud83c\udc04|\ud83c\udd7f|\ud83c\ude1a|\ud83c\ude2f|\u3299|\u3297|\u303d|\u2b55|\u2b50|\u2b1c|\u2b1b|\u2b07|\u2b06|\u2b05|\u2935|\u2934|\u27a1|\u2764|\u2757|\u2747|\u2744|\u2734|\u2733|\u2716|\u2714|\u2712|\u270f|\u270c|\u2709|\u2708|\u2702|\u26fd|\u26fa|\u26f5|\u26f3|\u26f2|\u26ea|\u26d4|\u26c5|\u26c4|\u26be|\u26bd|\u26ab|\u26aa|\u26a1|\u26a0|\u2693|\u267b|\u2668|\u2666|\u2665|\u2663|\u2660|\u2653|\u2652|\u2651|\u2650|\u264f|\u264e|\u264d|\u264c|\u264b|\u264a|\u2649|\u2648|\u263a|\u261d|\u2615|\u2614|\u2611|\u260e|\u2601|\u2600|\u25fe|\u25fd|\u25fc|\u25fb|\u25c0|\u25b6|\u25ab|\u25aa|\u24c2|\u231b|\u231a|\u21aa|\u21a9|\u2199|\u2198|\u2197|\u2196|\u2195|\u2194|\u2139|\u2049|\u203c|\u267f)([\uFE0E\uFE0F]?)))/g, // nodes with type 1 which should **not** be parsed shouldntBeParsed = /IFRAME|NOFRAMES|NOSCRIPT|SCRIPT|STYLE/, // just a private shortcut fromCharCode = String.fromCharCode; return twemoji; ///////////////////////// // private functions // // declaration // ///////////////////////// /** * Shortcut to create text nodes * @param string text used to create DOM text node * @return Node a DOM node with that text */ function createText(text) { return document.createTextNode(text); } /** * Default callback used to generate emoji src * based on Twitter CDN * @param string the emoji codepoint string * @param string the default size to use, i.e. "36x36" * @param string optional "\uFE0F" variant char, ignored by default * @return string the image source to use */ function defaultImageSrcGenerator(icon, options) { return ''.concat(options.base, options.size, '/', icon, options.ext); } /** * Given a generic DOM nodeType 1, walk through all children * and store every nodeType 3 (#text) found in the tree. * @param Element a DOM Element with probably some text in it * @param Array the list of previously discovered text nodes * @return Array same list with new discovered nodes, if any */ function grabAllTextNodes(node, allText) { var childNodes = node.childNodes, length = childNodes.length, subnode, nodeType; while (length--) { subnode = childNodes[length]; nodeType = subnode.nodeType; // parse emoji only in text nodes if (nodeType === 3) { // collect them to process emoji later allText.push(subnode); } // ignore all nodes that are not type 1 or that // should not be parsed as script, style, and others else if (nodeType === 1 && !shouldntBeParsed.test(subnode.nodeName)) { grabAllTextNodes(subnode, allText); } } return allText; } /** * Used to both remove the possible variant * and to convert utf16 into code points * @param string the emoji surrogate pair * @param string the optional variant char, if any */ function grabTheRightIcon(icon, variant) { // if variant is present as \uFE0F return toCodePoint( variant === '\uFE0F' ? // the icon should not contain it icon.slice(0, -1) : icon ); } /** * DOM version of the same logic / parser: * emojify all found sub-text nodes placing images node instead. * @param Element generic DOM node with some text in some child node * @param Object options containing info about how to parse * * .callback Function the callback to invoke per each found emoji. * .base string the base url, by default twemoji.base * .ext string the image extension, by default twemoji.ext * .size string the assets size, by default twemoji.size * * @return Element same generic node with emoji in place, if any. */ function parseNode(node, options) { var allText = grabAllTextNodes(node, []), length = allText.length, fragment, subnode, text, match, i, index, img, alt, icon, variant, src; while (length--) { fragment = document.createDocumentFragment(); subnode = allText[length]; text = subnode.nodeValue; i = 0; while ((match = re.exec(text))) { index = match.index; if (index !== i) { fragment.appendChild( createText(text.slice(i, index)) ); } alt = match[0]; icon = match[1]; variant = match[2]; i = index + alt.length; if (variant !== '\uFE0E') { src = options.callback( grabTheRightIcon(icon, variant), options, variant ); if (src) { img = new Image(); img.onerror = twemoji.onerror; img.className = 'emoji'; img.setAttribute('draggable', 'false'); img.alt = alt; img.src = src; } } fragment.appendChild(img || createText(alt)); img = null; } // is there actually anything to replace in here ? if (0 < i) { // any text left to be added ? if (i < text.length) { fragment.appendChild( createText(text.slice(i)) ); } // replace the text node only, leave intact // anything else surrounding such text subnode.parentNode.replaceChild(fragment, subnode); } } return node; } /** * String/HTML version of the same logic / parser: * emojify a generic text placing images tags instead of surrogates pair. * @param string generic string with possibly some emoji in it * @param Object options containing info about how to parse * * .callback Function the callback to invoke per each found emoji. * .base string the base url, by default twemoji.base * .ext string the image extension, by default twemoji.ext * .size string the assets size, by default twemoji.size * * @return the string with <img tags> replacing all found and parsed emoji */ function parseString(str, options) { return replace(str, function (match, icon, variant) { var src; // verify the variant is not the FE0E one // this variant means "emoji as text" and should not // require any action/replacement // http://unicode.org/Public/UNIDATA/StandardizedVariants.html if (variant !== '\uFE0E') { src = options.callback( grabTheRightIcon(icon, variant), options, variant ); if (src) { // recycle the match string replacing the emoji // with its image counter part match = '<img '.concat( 'class="emoji" ', 'draggable="false" ', // needs to preserve user original intent // when variants should be copied and pasted too 'alt="', match, '" ', 'src="', src, '"', '>' ); } } return match; }); } /** * Given a generic value, creates its squared counterpart if it's a number. * As example, number 36 will return '36x36'. * @param any a generic value. * @return any a string representing asset size, i.e. "36x36" * only in case the value was a number. * Returns initial value otherwise. */ function toSizeSquaredAsset(value) { return typeof value === 'number' ? value + 'x' + value : value; } ///////////////////////// // exported functions // // declaration // ///////////////////////// function fromCodePoint(codepoint) { var code = typeof codepoint === 'string' ? parseInt(codepoint, 16) : codepoint; if (code < 0x10000) { return fromCharCode(code); } code -= 0x10000; return fromCharCode( 0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF) ); } function parse(what, how) { if (!how || typeof how === 'function') { how = {callback: how}; } // if first argument is string, inject html <img> tags // otherwise use the DOM tree and parse text nodes only return (typeof what === 'string' ? parseString : parseNode)(what, { callback: how.callback || defaultImageSrcGenerator, base: typeof how.base === 'string' ? how.base : twemoji.base, ext: how.ext || twemoji.ext, size: "svg" // toSizeSquaredAsset(how.size || twemoji.size) }); } function replace(text, callback) { return String(text).replace(re, callback); } function test(text) { // IE6 needs a reset before too re.lastIndex = 0; var result = re.test(text); re.lastIndex = 0; return result; } function toCodePoint(unicodeSurrogates, sep) { var r = [], c = 0, p = 0, i = 0; while (i < unicodeSurrogates.length) { c = unicodeSurrogates.charCodeAt(i++); if (p) { r.push((0x10000 + ((p - 0xD800) << 10) + (c - 0xDC00)).toString(16)); p = 0; } else if (0xD800 <= c && c <= 0xDBFF) { p = c; } else { r.push(c.toString(16)); } } return r.join(sep || '-'); } }()); ; var JetpackEmoji = { EMOJI_SIZE: 72, BASE_URL: '//s0.wp.com/wp-content/mu-plugins/emoji/twemoji/', parse: function( element, size, base_url ) { twemoji.parse( element, { size: size || this.EMOJI_SIZE, base: base_url || this.BASE_URL, callback: function(icon, options, variant) { // Ignore some standard characters that TinyMCE recommends in its character map. // https://teamtinker.wordpress.com/2014/10/29/emoji-launch-week/#comment-2103 switch ( icon ) { case 'a9': case 'ae': case '2122': case '2194': case '2660': case '2663': case '2665': case '2666': return false; } // directly from twemoji return ''.concat(options.base, options.size, '/', icon, options.ext); } } ); } } ; (function() { var emoji = { init: function() { if ( typeof JetpackEmoji === 'undefined' ) { console.error( 'JetpackEmoji not found.' ); return; } var size, base_url; if ( typeof JetpackEmojiSettings !== 'undefined' ) { size = JetpackEmojiSettings.size || null; base_url = JetpackEmojiSettings.base_url || null; } JetpackEmoji.parse( document.body, size, base_url ); if ( typeof infiniteScroll !== 'undefined' ) { jQuery( document.body ).on( 'post-load', function( response ) { // TODO: ideally, we should only target the newly added elements JetpackEmoji.parse( document.body, size, base_url ); } ); } } }; if ( window.addEventListener ) { window.addEventListener( 'load', emoji.init, false ); } else if ( window.attachEvent ) { window.attachEvent( 'onload', emoji.init ); } })(); ;
JavaScript
/** The MIT License Copyright (c) 2010 Daniel Park (http://metaweb.com, http://postmessage.freebaseapps.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ var NO_JQUERY = {}; (function(window, $, undefined) { if (!("console" in window)) { var c = window.console = {}; c.log = c.warn = c.error = c.debug = function(){}; } if ($ === NO_JQUERY) { // jQuery is optional $ = { fn: {}, extend: function() { var a = arguments[0]; for (var i=1,len=arguments.length; i<len; i++) { var b = arguments[i]; for (var prop in b) { a[prop] = b[prop]; } } return a; } }; } $.fn.pm = function() { console.log("usage: \nto send: $.pm(options)\nto receive: $.pm.bind(type, fn, [origin])"); return this; }; // send postmessage $.pm = window.pm = function(options) { pm.send(options); }; // bind postmessage handler $.pm.bind = window.pm.bind = function(type, fn, origin, hash, async_reply) { pm.bind(type, fn, origin, hash, async_reply === true); }; // unbind postmessage handler $.pm.unbind = window.pm.unbind = function(type, fn) { pm.unbind(type, fn); }; // default postmessage origin on bind $.pm.origin = window.pm.origin = null; // default postmessage polling if using location hash to pass postmessages $.pm.poll = window.pm.poll = 200; var pm = { send: function(options) { var o = $.extend({}, pm.defaults, options), target = o.target; if (!o.target) { console.warn("postmessage target window required"); return; } if (!o.type) { console.warn("postmessage type required"); return; } var msg = {data:o.data, type:o.type}; if (o.success) { msg.callback = pm._callback(o.success); } if (o.error) { msg.errback = pm._callback(o.error); } if (("postMessage" in target) && !o.hash) { pm._bind(); target.postMessage(JSON.stringify(msg), o.origin || '*'); } else { pm.hash._bind(); pm.hash.send(o, msg); } }, bind: function(type, fn, origin, hash, async_reply) { pm._replyBind ( type, fn, origin, hash, async_reply ); }, _replyBind: function(type, fn, origin, hash, isCallback) { if (("postMessage" in window) && !hash) { pm._bind(); } else { pm.hash._bind(); } var l = pm.data("listeners.postmessage"); if (!l) { l = {}; pm.data("listeners.postmessage", l); } var fns = l[type]; if (!fns) { fns = []; l[type] = fns; } fns.push({fn:fn, callback: isCallback, origin:origin || $.pm.origin}); }, unbind: function(type, fn) { var l = pm.data("listeners.postmessage"); if (l) { if (type) { if (fn) { // remove specific listener var fns = l[type]; if (fns) { var m = []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.fn !== fn) { m.push(o); } } l[type] = m; } } else { // remove all listeners by type delete l[type]; } } else { // unbind all listeners of all type for (var i in l) { delete l[i]; } } } }, data: function(k, v) { if (v === undefined) { return pm._data[k]; } pm._data[k] = v; return v; }, _data: {}, _CHARS: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), _random: function() { var r = []; for (var i=0; i<32; i++) { r[i] = pm._CHARS[0 | Math.random() * 32]; }; return r.join(""); }, _callback: function(fn) { var cbs = pm.data("callbacks.postmessage"); if (!cbs) { cbs = {}; pm.data("callbacks.postmessage", cbs); } var r = pm._random(); cbs[r] = fn; return r; }, _bind: function() { // are we already listening to message events on this w? if (!pm.data("listening.postmessage")) { if (window.addEventListener) { window.addEventListener("message", pm._dispatch, false); } else if (window.attachEvent) { window.attachEvent("onmessage", pm._dispatch); } pm.data("listening.postmessage", 1); } }, _dispatch: function(e) { //console.log("$.pm.dispatch", e, this); try { var msg = JSON.parse(e.data); } catch (ex) { //console.warn("postmessage data invalid json: ", ex); //message wasn't meant for pm return; } if (!msg.type) { //console.warn("postmessage message type required"); //message wasn't meant for pm return; } var cbs = pm.data("callbacks.postmessage") || {}, cb = cbs[msg.type]; if (cb) { cb(msg.data); } else { var l = pm.data("listeners.postmessage") || {}; var fns = l[msg.type] || []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.origin && o.origin !== '*' && e.origin !== o.origin) { console.warn("postmessage message origin mismatch", e.origin, o.origin); if (msg.errback) { // notify post message errback var error = { message: "postmessage origin mismatch", origin: [e.origin, o.origin] }; pm.send({target:e.source, data:error, type:msg.errback}); } continue; } function sendReply ( data ) { if (msg.callback) { pm.send({target:e.source, data:data, type:msg.callback}); } } try { if ( o.callback ) { o.fn(msg.data, sendReply, e); } else { sendReply ( o.fn(msg.data, e) ); } } catch (ex) { if (msg.errback) { // notify post message errback pm.send({target:e.source, data:ex, type:msg.errback}); } else { throw ex; } } }; } } }; // location hash polling pm.hash = { send: function(options, msg) { //console.log("hash.send", target_window, options, msg); var target_window = options.target, target_url = options.url; if (!target_url) { console.warn("postmessage target window url is required"); return; } target_url = pm.hash._url(target_url); var source_window, source_url = pm.hash._url(window.location.href); if (window == target_window.parent) { source_window = "parent"; } else { try { for (var i=0,len=parent.frames.length; i<len; i++) { var f = parent.frames[i]; if (f == window) { source_window = i; break; } }; } catch(ex) { // Opera: security error trying to access parent.frames x-origin // juse use window.name source_window = window.name; } } if (source_window == null) { console.warn("postmessage windows must be direct parent/child windows and the child must be available through the parent window.frames list"); return; } var hashmessage = { "x-requested-with": "postmessage", source: { name: source_window, url: source_url }, postmessage: msg }; var hash_id = "#x-postmessage-id=" + pm._random(); target_window.location = target_url + hash_id + encodeURIComponent(JSON.stringify(hashmessage)); }, _regex: /^\#x\-postmessage\-id\=(\w{32})/, _regex_len: "#x-postmessage-id=".length + 32, _bind: function() { // are we already listening to message events on this w? if (!pm.data("polling.postmessage")) { setInterval(function() { var hash = "" + window.location.hash, m = pm.hash._regex.exec(hash); if (m) { var id = m[1]; if (pm.hash._last !== id) { pm.hash._last = id; pm.hash._dispatch(hash.substring(pm.hash._regex_len)); } } }, $.pm.poll || 200); pm.data("polling.postmessage", 1); } }, _dispatch: function(hash) { if (!hash) { return; } try { hash = JSON.parse(decodeURIComponent(hash)); if (!(hash['x-requested-with'] === 'postmessage' && hash.source && hash.source.name != null && hash.source.url && hash.postmessage)) { // ignore since hash could've come from somewhere else return; } } catch (ex) { // ignore since hash could've come from somewhere else return; } var msg = hash.postmessage, cbs = pm.data("callbacks.postmessage") || {}, cb = cbs[msg.type]; if (cb) { cb(msg.data); } else { var source_window; if (hash.source.name === "parent") { source_window = window.parent; } else { source_window = window.frames[hash.source.name]; } var l = pm.data("listeners.postmessage") || {}; var fns = l[msg.type] || []; for (var i=0,len=fns.length; i<len; i++) { var o = fns[i]; if (o.origin) { var origin = /https?\:\/\/[^\/]*/.exec(hash.source.url)[0]; if (o.origin !== '*' && origin !== o.origin) { console.warn("postmessage message origin mismatch", origin, o.origin); if (msg.errback) { // notify post message errback var error = { message: "postmessage origin mismatch", origin: [origin, o.origin] }; pm.send({target:source_window, data:error, type:msg.errback, hash:true, url:hash.source.url}); } continue; } } function sendReply ( data ) { if (msg.callback) { pm.send({target:source_window, data:data, type:msg.callback, hash:true, url:hash.source.url}); } } try { if ( o.callback ) { o.fn(msg.data, sendReply); } else { sendReply ( o.fn(msg.data) ); } } catch (ex) { if (msg.errback) { // notify post message errback pm.send({target:source_window, data:ex, type:msg.errback, hash:true, url:hash.source.url}); } else { throw ex; } } }; } }, _url: function(url) { // url minus hash part return (""+url).replace(/#.*$/, ""); } }; $.extend(pm, { defaults: { target: null, /* target window (required) */ url: null, /* target window url (required if no window.postMessage or hash == true) */ type: null, /* message type (required) */ data: null, /* message data (required) */ success: null, /* success callback (optional) */ error: null, /* error callback (optional) */ origin: "*", /* postmessage origin (optional) */ hash: false /* use location hash for message passing (optional) */ } }); })(this, typeof jQuery === "undefined" ? NO_JQUERY : jQuery); /** * http://www.JSON.org/json2.js **/ if (! ("JSON" in window && window.JSON)){JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z"};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}()); /** * Basic event handeler helper */ function on(el, eventName, handler) { if (el.addEventListener) { el.addEventListener(eventName, handler); } else { el.attachEvent('on' + eventName, function(){ handler.call(el); }); } } var googlePlusButtonHasBeenClicked = false; /** * On ready, bind a click handler to our custom button - this click handler will * not be the only one - google will add their own in googlePlusButtonRender too * But this way we can know when the user has initiated a Google+ login * so we can display the loading graphic in the highlander comment form */ on( document.getElementById('customButton') , 'click', googlePlusOnClickCustomButton ); /** * Let our parent know the user clicked on the Google+ button */ function googlePlusOnClickCustomButton() { googlePlusButtonHasBeenClicked = true; pm( { target: window.parent, type: 'googlePlusButtonClick', data: 0, origin: originUrl // defined on the page } ); } /** * This callback is hit 1) when the Google library has rendered the custom button * and completed an initial autonomous check for auth and 2) when the user completes * a login * * At this point, we only want to notify the parent in case #2 - and this avoids * us firing up a userinfo.get on every page load by an auth'd user */ function googlePlusSignInCallback( authResult ) { if ( googlePlusButtonHasBeenClicked ) { if ( 'undefined' != typeof authResult.error ) { googlePlusSignInEvent( { error: authResult.error } ); } else { googlePlusGetProfile(function( profileArgs ) { var data = {}; data.code = authResult.code; data.access_token = authResult.access_token; data.name = profileArgs.displayName; data.avatar = profileArgs.image.url; data.link = profileArgs.url; data.uid = profileArgs.id; data.email = profileArgs['emails'].filter( function( v ) { return v.type === 'account'; // Filter out the primary email } )[0].value; googlePlusSignInEvent( data ); } ); } } } /** * Fetch the user's profile */ function googlePlusGetProfile( callback ) { gapi.client.load( 'plus', 'v1', function() { var request = gapi.client.plus.people.get( { userId: 'me' } ); request.execute( function( resp ) { callback( resp ); } ); } ); } /** * Utility function to send sign in events to the parent of this iframe */ function googlePlusSignInEvent( data ) { pm( { target: window.parent, type: 'googlePlusSignIn', data: data, origin: originUrl } ); } /** * Render the button (attaches Google+ click and auth callbacks) * We use htmlspecialchars here instead of esc_attr to avoid loading all of WP * for a single function call */ function googlePlusButtonRender() { gapi.signin.render( 'customButton', { 'callback': 'googlePlusSignInCallback', 'clientid': google_api_key, 'cookiepolicy': 'single_host_origin', 'scope': 'profile email', 'accesstype' : 'offline' } ); } function googlePlusLoadJS() { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "//apis.google.com/js/client:plusone.js?onload=googlePlusButtonRender"; document.body.appendChild(script); } pm.bind( 'googlePlusLoadJS', googlePlusLoadJS, originUrl );
JavaScript
window['___jsl'] = window['___jsl'] || {};(window['___jsl']['ci'] = (window['___jsl']['ci'] || [])).push({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}});window['___jsl']=window['___jsl']||{};(window['___jsl']['ci'] = (window['___jsl']['ci'] || [])).push({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}}); /* [start] feature=taming */ var safeJSON=window.safeJSON; var tamings___=window.tamings___||[]; var bridge___; var caja___=window.caja___; var ___=window.___;; /* [end] feature=taming */ /* [start] feature=gapi-globals */ var gapi=window.gapi||{};gapi.client=window.gapi&&window.gapi.client||{}; ; ; /* [end] feature=gapi-globals */ /* [start] feature=globals */ var gadgets=window.gadgets||{},shindig=window.shindig||{},osapi=window.osapi=window.osapi||{},google=window.google||{}; ; ; /* [end] feature=globals */ /* [start] feature=core.config.base */ window['___cfg'] = window['___cfg'] || window['___gcfg'];; if(!window.gadgets["config"]){gadgets.config=function(){var f; var h={}; var b={}; function c(j,l){for(var k in l){if(!l.hasOwnProperty(k)){continue }if(typeof j[k]==="object"&&typeof l[k]==="object"){c(j[k],l[k]) }else{j[k]=l[k] }}}function i(){var j=document.scripts||document.getElementsByTagName("script"); if(!j||j.length==0){return null }var m; if(f.u){for(var k=0; !m&&k<j.length; ++k){var l=j[k]; if(l.src&&l.src.indexOf(f.u)==0){m=l }}}if(!m){m=j[j.length-1] }if(!m.src){return null }return m }function a(j){var k=""; if(j.nodeType==3||j.nodeType==4){k=j.nodeValue }else{if(j.innerText){k=j.innerText }else{if(j.innerHTML){k=j.innerHTML }else{if(j.firstChild){var l=[]; for(var m=j.firstChild; m; m=m.nextSibling){l.push(a(m)) }k=l.join("") }}}}return k }function e(k){if(!k){return{} }var j; while(k.charCodeAt(k.length-1)==0){k=k.substring(0,k.length-1) }try{j=(new Function("return ("+k+"\n)"))() }catch(l){}if(typeof j==="object"){return j }try{j=(new Function("return ({"+k+"\n})"))() }catch(l){}return typeof j==="object"?j:{} }function g(n){var p=window.___cfg; if(p){c(n,p) }var o=i(); if(!o){return }var k=a(o); var j=e(k); if(f.f&&f.f.length==1){var m=f.f[0]; if(!j[m]){var l={}; l[f.f[0]]=j; j=l }}c(n,j) }function d(o){for(var l in h){if(h.hasOwnProperty(l)){var n=h[l]; for(var m=0,k=n.length; m<k; ++m){o(l,n[m]) }}}}return{register:function(l,k,j,m){var n=h[l]; if(!n){n=[]; h[l]=n }n.push({validators:k||{},callback:j,callOnUpdate:m}) },get:function(j){if(j){return b[j]||{} }return b },init:function(k,j){f=window.___jsl||{}; c(b,k); g(b); var l=window.___config||{}; c(b,l); d(function(q,p){var o=b[q]; if(o&&!j){var m=p.validators; for(var n in m){if(m.hasOwnProperty(n)){if(!m[n](o[n])){throw new Error('Invalid config value "'+o[n]+'" for parameter "'+n+'" in component "'+q+'"') }}}}if(p.callback){p.callback(b) }}) },update:function(k,p){var o=(window.gapi&&window.gapi["config"]&&window.gapi["config"]["update"]); if(!p&&o){o(k) }var n=[]; d(function(q,j){if(k.hasOwnProperty(q)||(p&&b&&b[q])){if(j.callback&&j.callOnUpdate){n.push(j.callback) }}}); b=p?{}:b||{}; c(b,k); for(var m=0,l=n.length; m<l; ++m){n[m](b) }}} }() }else{gadgets.config=window.gadgets["config"]; gadgets.config.register=gadgets.config.register; gadgets.config.get=gadgets.config.get; gadgets.config.init=gadgets.config.init; gadgets.config.update=gadgets.config.update };; /* [end] feature=core.config.base */ /* [start] feature=core.log */ gadgets.log=(function(){var e=1; var a=2; var f=3; var c=4; var d=function(i){b(e,i) }; gadgets.warn=function(i){b(a,i) }; gadgets.error=function(i){b(f,i) }; gadgets.debug=function(i){}; gadgets.setLogLevel=function(i){h=i }; function b(k,i){if(k<h||!g){return }if(k===a&&g.warn){g.warn(i) }else{if(k===f&&g.error){try{g.error(i) }catch(j){}}else{if(g.log){g.log(i) }}}}d.INFO=e; d.WARNING=a; d.NONE=c; var h=e; var g=window.console?window.console:window.opera?window.opera.postError:undefined; return d })();; ; /* [end] feature=core.log */ /* [start] feature=core.config */ (function(){gadgets.config.EnumValidator=function(d){var c=[]; if(arguments.length>1){for(var b=0,a; (a=arguments[b]); ++b){c.push(a) }}else{c=d }return function(f){for(var e=0,g; (g=c[e]); ++e){if(f===c[e]){return true }}return false } }; gadgets.config.RegExValidator=function(a){return function(b){return a.test(b) } }; gadgets.config.ExistsValidator=function(a){return typeof a!=="undefined" }; gadgets.config.NonEmptyStringValidator=function(a){return typeof a==="string"&&a.length>0 }; gadgets.config.BooleanValidator=function(a){return typeof a==="boolean" }; gadgets.config.LikeValidator=function(a){return function(c){for(var d in a){if(a.hasOwnProperty(d)){var b=a[d]; if(!b(c[d])){return false }}}return true } } })();; /* [end] feature=core.config */ /* [start] feature=core.util.base */ gadgets.util=gadgets.util||{}; (function(){gadgets.util.makeClosure=function(d,f,e){var c=[]; for(var b=2,a=arguments.length; b<a; ++b){c.push(arguments[b]) }return function(){var g=c.slice(); for(var k=0,h=arguments.length; k<h; ++k){g.push(arguments[k]) }return f.apply(d,g) } }; gadgets.util.makeEnum=function(b){var c,a,d={}; for(c=0; (a=b[c]); ++c){d[a]=a }return d } })();; /* [end] feature=core.util.base */ /* [start] feature=core.util.dom */ gadgets.util=gadgets.util||{}; (function(){var c="http://www.w3.org/1999/xhtml"; function b(f,e){var h=e||{}; for(var g in h){if(h.hasOwnProperty(g)){f[g]=h[g] }}}function d(g,f){var e=["<",g]; var i=f||{}; for(var h in i){if(i.hasOwnProperty(h)){e.push(" "); e.push(h); e.push('="'); e.push(gadgets.util.escapeString(i[h])); e.push('"') }}e.push("></"); e.push(g); e.push(">"); return e.join("") }function a(f){var g=""; if(f.nodeType==3||f.nodeType==4){g=f.nodeValue }else{if(f.innerText){g=f.innerText }else{if(f.innerHTML){g=f.innerHTML }else{if(f.firstChild){var e=[]; for(var h=f.firstChild; h; h=h.nextSibling){e.push(a(h)) }g=e.join("") }}}}return g }gadgets.util.createElement=function(f){var e; if((!document.body)||document.body.namespaceURI){try{e=document.createElementNS(c,f) }catch(g){}}return e||document.createElement(f) }; gadgets.util.createIframeElement=function(g){var i=gadgets.util.createElement("iframe"); try{var e=d("iframe",g); var f=gadgets.util.createElement(e); if(f&&((!i)||((f.tagName==i.tagName)&&(f.namespaceURI==i.namespaceURI)))){i=f }}catch(h){}b(i,g); return i }; gadgets.util.getBodyElement=function(){if(document.body){return document.body }try{var f=document.getElementsByTagNameNS(c,"body"); if(f&&(f.length==1)){return f[0] }}catch(e){}return document.documentElement||document }; gadgets.util.getInnerText=function(e){return a(e) } })();; /* [end] feature=core.util.dom */ /* [start] feature=core.util.event */ gadgets.util=gadgets.util||{}; (function(){gadgets.util.attachBrowserEvent=function(c,b,d,a){if(typeof c.addEventListener!="undefined"){c.addEventListener(b,d,a) }else{if(typeof c.attachEvent!="undefined"){c.attachEvent("on"+b,d) }else{gadgets.warn("cannot attachBrowserEvent: "+b) }}}; gadgets.util.removeBrowserEvent=function(c,b,d,a){if(c.removeEventListener){c.removeEventListener(b,d,a) }else{if(c.detachEvent){c.detachEvent("on"+b,d) }else{gadgets.warn("cannot removeBrowserEvent: "+b) }}} })();; /* [end] feature=core.util.event */ /* [start] feature=core.util.onload */ gadgets.util=gadgets.util||{}; (function(){var a=[]; gadgets.util.registerOnLoadHandler=function(b){a.push(b) }; gadgets.util.runOnLoadHandlers=function(){for(var c=0,b=a.length; c<b; ++c){a[c]() }} })();; /* [end] feature=core.util.onload */ /* [start] feature=core.util.string */ gadgets.util=gadgets.util||{}; (function(){var a={0:false,10:true,13:true,34:true,39:true,60:true,62:true,92:true,8232:true,8233:true,65282:true,65287:true,65308:true,65310:true,65340:true}; function b(c,d){return String.fromCharCode(d) }gadgets.util.escape=function(c,g){if(!c){return c }else{if(typeof c==="string"){return gadgets.util.escapeString(c) }else{if(typeof c==="Array"){for(var f=0,d=c.length; f<d; ++f){c[f]=gadgets.util.escape(c[f]) }}else{if(typeof c==="object"&&g){var e={}; for(var h in c){if(c.hasOwnProperty(h)){e[gadgets.util.escapeString(h)]=gadgets.util.escape(c[h],true) }}return e }}}}return c }; gadgets.util.escapeString=function(g){if(!g){return g }var d=[],f,h; for(var e=0,c=g.length; e<c; ++e){f=g.charCodeAt(e); h=a[f]; if(h===true){d.push("&#",f,";") }else{if(h!==false){d.push(g.charAt(e)) }}}return d.join("") }; gadgets.util.unescapeString=function(c){if(!c){return c }return c.replace(/&#([0-9]+);/g,b) } })();; /* [end] feature=core.util.string */ /* [start] feature=core.util.urlparams */ gadgets.util=gadgets.util||{}; (function(){var a=null; function b(e){var f; var c=e.indexOf("?"); var d=e.indexOf("#"); if(d===-1){f=e.substr(c+1) }else{f=[e.substr(c+1,d-c-1),"&",e.substr(d+1)].join("") }return f.split("&") }gadgets.util.getUrlParameters=function(p){var d=typeof p==="undefined"; if(a!==null&&d){return a }var l={}; var f=b(p||window.location.href); var n=window.decodeURIComponent?decodeURIComponent:unescape; for(var h=0,g=f.length; h<g; ++h){var m=f[h].indexOf("="); if(m===-1){continue }var c=f[h].substring(0,m); var o=f[h].substring(m+1); o=o.replace(/\+/g," "); try{l[c]=n(o) }catch(k){}}if(d){a=l }return l }; gadgets.util.getUrlParameters() })();; /* [end] feature=core.util.urlparams */ /* [start] feature=core.util */ gadgets.util=gadgets.util||{}; (function(){var b={}; var a={}; function c(d){b=d["core.util"]||{} }if(gadgets.config){gadgets.config.register("core.util",null,c) }gadgets.util.getFeatureParameters=function(d){return typeof b[d]==="undefined"?null:b[d] }; gadgets.util.hasFeature=function(d){return typeof b[d]!=="undefined" }; gadgets.util.getServices=function(){return a } })();; /* [end] feature=core.util */ /* [start] feature=shindig.auth */ shindig.Auth=function(){var authToken=null; var trusted=null; function addParamsToToken(urlParams){var args=authToken.split("&"); for(var i=0; i<args.length; i++){var nameAndValue=args[i].split("="); if(nameAndValue.length===2){var name=nameAndValue[0]; var value=nameAndValue[1]; if(value==="$"){value=encodeURIComponent(urlParams[name]); args[i]=name+"="+value }}}authToken=args.join("&") }function init(configuration){var urlParams=gadgets.util.getUrlParameters(); var config=configuration["shindig.auth"]||{}; if(config.authToken){authToken=config.authToken }else{if(urlParams.st){authToken=urlParams.st }}if(authToken!==null){addParamsToToken(urlParams) }if(config.trustedJson){trusted=(eval("("+config.trustedJson+")")) }}gadgets.config.register("shindig.auth",null,init); return{getSecurityToken:function(){return authToken },updateSecurityToken:function(newToken){authToken=newToken },getTrustedData:function(){return trusted }} };; shindig.auth=new shindig.Auth();; /* [end] feature=shindig.auth */ /* [start] feature=core.json */ if(window.JSON&&window.JSON.parse&&window.JSON.stringify){gadgets.json=(function(){var a=/___$/; function b(d,e){var c=this[d]; return c }return{parse:function(d){try{return window.JSON.parse(d) }catch(c){return false }},stringify:function(d){var h=window.JSON.stringify; function f(e){return h.call(this,e,b) }var g=(Array.prototype.toJSON&&h([{x:1}])==='"[{\\"x\\": 1}]"')?f:h; try{return g(d,function(i,e){return !a.test(i)?e:void 0 }) }catch(c){return null }}} })() };; ; if(!(window.JSON&&window.JSON.parse&&window.JSON.stringify)){gadgets.json=function(){function f(n){return n<10?"0"+n:n }Date.prototype.toJSON=function(){return[this.getUTCFullYear(),"-",f(this.getUTCMonth()+1),"-",f(this.getUTCDate()),"T",f(this.getUTCHours()),":",f(this.getUTCMinutes()),":",f(this.getUTCSeconds()),"Z"].join("") }; var m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}; function stringify(value){var a,i,k,l,r=/[\"\\\x00-\x1f\x7f-\x9f]/g,v; switch(typeof value){case"string":return r.test(value)?'"'+value.replace(r,function(a){var c=m[a]; if(c){return c }c=a.charCodeAt(); return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16) })+'"':'"'+value+'"'; case"number":return isFinite(value)?String(value):"null"; case"boolean":case"null":return String(value); case"object":if(!value){return"null" }a=[]; if(typeof value.length==="number"&&!value.propertyIsEnumerable("length")){l=value.length; for(i=0; i<l; i+=1){a.push(stringify(value[i])||"null") }return"["+a.join(",")+"]" }for(k in value){if(/___$/.test(k)){continue }if(value.hasOwnProperty(k)){if(typeof k==="string"){v=stringify(value[k]); if(v){a.push(stringify(k)+":"+v) }}}}return"{"+a.join(",")+"}" }return"" }return{stringify:stringify,parse:function(text){if(/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/b-u]/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return eval("("+text+")") }return false }} }() };; gadgets.json.flatten=function(c){var d={}; if(c===null||c===undefined){return d }for(var a in c){if(c.hasOwnProperty(a)){var b=c[a]; if(null===b||undefined===b){continue }d[a]=(typeof b==="string")?b:gadgets.json.stringify(b) }}return d };; /* [end] feature=core.json */ /* [start] feature=core.io */ gadgets.io=function(){var config={}; var oauthState; function makeXhr(){var x; var wrapperXhr=window.shindig&&window.shindig["xhrwrapper"]&&window.shindig["xhrwrapper"]["createXHR"]; if(wrapperXhr){return wrapperXhr() }else{if(typeof ActiveXObject!="undefined"){x=new ActiveXObject("Msxml2.XMLHTTP"); if(!x){x=new ActiveXObject("Microsoft.XMLHTTP") }return x }else{if(typeof XMLHttpRequest!="undefined"||window.XMLHttpRequest){return new window.XMLHttpRequest() }else{throw ("no xhr available") }}}}function hadError(xobj,callback){if(xobj.readyState!==4){return true }try{if(xobj.status!==200){var error=(""+xobj.status); if(xobj.responseText){error=error+" "+xobj.responseText }callback({errors:[error],rc:xobj.status,text:xobj.responseText}); return true }}catch(e){callback({errors:[e.number+" Error not specified"],rc:e.number,text:e.description}); return true }return false }function processNonProxiedResponse(url,callback,params,xobj){if(hadError(xobj,callback)){return }var data={body:xobj.responseText}; callback(transformResponseData(params,data)) }var UNPARSEABLE_CRUFT="throw 1; < don't be evil' >"; function processResponse(url,callback,params,xobj){if(hadError(xobj,callback)){return }var txt=xobj.responseText; var offset=txt.indexOf(UNPARSEABLE_CRUFT)+UNPARSEABLE_CRUFT.length; if(offset<UNPARSEABLE_CRUFT.length){return }txt=txt.substr(offset); var data=eval("("+txt+")"); data=data[url]; if(data.oauthState){oauthState=data.oauthState }if(data.st){shindig.auth.updateSecurityToken(data.st) }callback(transformResponseData(params,data)) }function transformResponseData(params,data){var resp={text:data.body,rc:data.rc||200,headers:data.headers,oauthApprovalUrl:data.oauthApprovalUrl,oauthError:data.oauthError,oauthErrorText:data.oauthErrorText,errors:[]}; if(resp.rc<200||resp.rc>=400){resp.errors=[resp.rc+" Error"] }else{if(resp.text){if(resp.rc>=300&&resp.rc<400){params.CONTENT_TYPE="TEXT" }switch(params.CONTENT_TYPE){case"JSON":case"FEED":resp.data=gadgets.json.parse(resp.text); if(!resp.data){resp.errors.push("500 Failed to parse JSON"); resp.rc=500; resp.data=null }break; case"DOM":var dom; if(typeof ActiveXObject!="undefined"){dom=new ActiveXObject("Microsoft.XMLDOM"); dom.async=false; dom.validateOnParse=false; dom.resolveExternals=false; if(!dom.loadXML(resp.text)){resp.errors.push("500 Failed to parse XML"); resp.rc=500 }else{resp.data=dom }}else{var parser=new DOMParser(); dom=parser.parseFromString(resp.text,"text/xml"); if("parsererror"===dom.documentElement.nodeName){resp.errors.push("500 Failed to parse XML"); resp.rc=500 }else{resp.data=dom }}break; default:resp.data=resp.text; break }}}return resp }function makeXhrRequest(realUrl,proxyUrl,callback,paramData,method,params,processResponseFunction,opt_headers){var xhr=makeXhr(); if(proxyUrl.indexOf("//")==0){proxyUrl=document.location.protocol+proxyUrl }xhr.open(method,proxyUrl,true); if(callback){xhr.onreadystatechange=gadgets.util.makeClosure(null,processResponseFunction,realUrl,callback,params,xhr) }if(paramData!==null){var contentTypeHeader="Content-Type"; var contentType="application/x-www-form-urlencoded"; if(typeof opt_headers==="string"){contentType=opt_headers; opt_headers={} }var headers=opt_headers||{}; if(!headers[contentTypeHeader]){headers[contentTypeHeader]=contentType }for(var headerName in headers){xhr.setRequestHeader(headerName,headers[headerName]) }}xhr.send(paramData) }function respondWithPreload(postData,params,callback){if(gadgets.io.preloaded_&&postData.httpMethod==="GET"){for(var i=0; i<gadgets.io.preloaded_.length; i++){var preload=gadgets.io.preloaded_[i]; if(preload&&(preload.id===postData.url)){delete gadgets.io.preloaded_[i]; if(preload.rc!==200){callback({rc:preload.rc,errors:[preload.rc+" Error"]}) }else{if(preload.oauthState){oauthState=preload.oauthState }var resp={body:preload.body,rc:preload.rc,headers:preload.headers,oauthApprovalUrl:preload.oauthApprovalUrl,oauthError:preload.oauthError,oauthErrorText:preload.oauthErrorText,errors:[]}; callback(transformResponseData(params,resp)) }return true }}}return false }function init(configuration){config=configuration["core.io"]||{} }gadgets.config.register("core.io",null,init); return{makeRequest:function(url,callback,opt_params){var params=opt_params||{}; var httpMethod=params.METHOD||"GET"; var refreshInterval=params.REFRESH_INTERVAL; var auth,st; if(params.AUTHORIZATION&&params.AUTHORIZATION!=="NONE"){auth=params.AUTHORIZATION.toLowerCase(); st=shindig.auth.getSecurityToken() }else{if(httpMethod==="GET"&&refreshInterval===undefined){refreshInterval=3600 }}var signOwner=true; if(typeof params.OWNER_SIGNED!=="undefined"){signOwner=params.OWNER_SIGNED }var signViewer=true; if(typeof params.VIEWER_SIGNED!=="undefined"){signViewer=params.VIEWER_SIGNED }var headers=params.HEADERS||{}; if(httpMethod==="POST"&&!headers["Content-Type"]){headers["Content-Type"]="application/x-www-form-urlencoded" }var urlParams=gadgets.util.getUrlParameters(); var paramData={url:url,httpMethod:httpMethod,headers:gadgets.io.encodeValues(headers,false),postData:params.POST_DATA||"",authz:auth||"",st:st||"",contentType:params.CONTENT_TYPE||"TEXT",numEntries:params.NUM_ENTRIES||"3",getSummaries:!!params.GET_SUMMARIES,signOwner:signOwner,signViewer:signViewer,gadget:urlParams.url,container:urlParams.container||urlParams.synd||"default",bypassSpecCache:gadgets.util.getUrlParameters()["nocache"]||"",getFullHeaders:!!params.GET_FULL_HEADERS}; if(auth==="oauth"||auth==="signed"){if(gadgets.io.oauthReceivedCallbackUrl_){paramData.OAUTH_RECEIVED_CALLBACK=gadgets.io.oauthReceivedCallbackUrl_; gadgets.io.oauthReceivedCallbackUrl_=null }paramData.oauthState=oauthState||""; for(var opt in params){if(params.hasOwnProperty(opt)){if(opt.indexOf("OAUTH_")===0){paramData[opt]=params[opt] }}}}var proxyUrl=config.jsonProxyUrl.replace("%host%",document.location.host); if(!respondWithPreload(paramData,params,callback)){if(httpMethod==="GET"&&refreshInterval>0){var extraparams="?refresh="+refreshInterval+"&"+gadgets.io.encodeValues(paramData); makeXhrRequest(url,proxyUrl+extraparams,callback,null,"GET",params,processResponse) }else{makeXhrRequest(url,proxyUrl,callback,gadgets.io.encodeValues(paramData),"POST",params,processResponse) }}},makeNonProxiedRequest:function(relativeUrl,callback,opt_params,opt_headers){var params=opt_params||{}; makeXhrRequest(relativeUrl,relativeUrl,callback,params.POST_DATA,params.METHOD,params,processNonProxiedResponse,opt_headers) },clearOAuthState:function(){oauthState=undefined },encodeValues:function(fields,opt_noEscaping){var escape=!opt_noEscaping; var buf=[]; var first=false; for(var i in fields){if(fields.hasOwnProperty(i)&&!/___$/.test(i)){if(!first){first=true }else{buf.push("&") }buf.push(escape?encodeURIComponent(String(i)):i); buf.push("="); buf.push(escape?encodeURIComponent(String(fields[i])):fields[i]) }}return buf.join("") },getProxyUrl:function(url,opt_params){var params=opt_params||{}; var refresh=params.REFRESH_INTERVAL; if(refresh===undefined){refresh="3600" }var urlParams=gadgets.util.getUrlParameters(); var rewriteMimeParam=params.rewriteMime?"&rewriteMime="+encodeURIComponent(String(params.rewriteMime)):""; var ret=config.proxyUrl.replace("%url%",encodeURIComponent(url)).replace("%host%",document.location.host).replace("%rawurl%",url).replace("%refresh%",encodeURIComponent(String(refresh))).replace("%gadget%",encodeURIComponent(urlParams.url)).replace("%container%",encodeURIComponent(urlParams.container||urlParams.synd||"default")).replace("%rewriteMime%",rewriteMimeParam); if(ret.indexOf("//")==0){ret=window.location.protocol+ret }return ret }} }(); gadgets.io.RequestParameters=gadgets.util.makeEnum(["METHOD","CONTENT_TYPE","POST_DATA","HEADERS","AUTHORIZATION","NUM_ENTRIES","GET_SUMMARIES","GET_FULL_HEADERS","REFRESH_INTERVAL","OAUTH_SERVICE_NAME","OAUTH_USE_TOKEN","OAUTH_TOKEN_NAME","OAUTH_REQUEST_TOKEN","OAUTH_REQUEST_TOKEN_SECRET","OAUTH_RECEIVED_CALLBACK"]); gadgets.io.MethodType=gadgets.util.makeEnum(["GET","POST","PUT","DELETE","HEAD"]); gadgets.io.ContentType=gadgets.util.makeEnum(["TEXT","DOM","JSON","FEED"]); gadgets.io.AuthorizationType=gadgets.util.makeEnum(["NONE","SIGNED","OAUTH"]);; /* [end] feature=core.io */ /* [start] feature=core.prefs */ (function(){var i=null; var j={}; var f=gadgets.util.escapeString; var d={}; var h={}; var e="en"; var b="US"; var a=0; function c(){var l=gadgets.util.getUrlParameters(); for(var k in l){if(l.hasOwnProperty(k)){if(k.indexOf("up_")===0&&k.length>3){j[k.substr(3)]=String(l[k]) }else{if(k==="country"){b=l[k] }else{if(k==="lang"){e=l[k] }else{if(k==="mid"){a=l[k] }}}}}}}function g(){for(var k in h){if(typeof j[k]==="undefined"){j[k]=h[k] }}}gadgets.Prefs=function(){if(!i){c(); g(); i=this }return i }; gadgets.Prefs.setInternal_=function(n,p){var o=false; if(typeof n==="string"){if(!j.hasOwnProperty(n)||j[n]!==p){o=true }j[n]=p }else{for(var m in n){if(n.hasOwnProperty(m)){var l=n[m]; if(!j.hasOwnProperty(m)||j[m]!==l){o=true }j[m]=l }}}return o }; gadgets.Prefs.setMessages_=function(k){d=k }; gadgets.Prefs.setDefaultPrefs_=function(k){h=k }; gadgets.Prefs.prototype.getString=function(k){if(k===".lang"){k="lang" }return j[k]?f(j[k]):"" }; gadgets.Prefs.prototype.setDontEscape_=function(){f=function(l){return l } }; gadgets.Prefs.prototype.getInt=function(k){var l=parseInt(j[k],10); return isNaN(l)?0:l }; gadgets.Prefs.prototype.getFloat=function(k){var l=parseFloat(j[k]); return isNaN(l)?0:l }; gadgets.Prefs.prototype.getBool=function(k){var l=j[k]; if(l){return l==="true"||l===true||!!parseInt(l,10) }return false }; gadgets.Prefs.prototype.set=function(k,l){throw new Error("setprefs feature required to make this call.") }; gadgets.Prefs.prototype.getArray=function(n){var o=j[n]; if(o){var k=o.split("|"); for(var m=0,l=k.length; m<l; ++m){k[m]=f(k[m].replace(/%7C/g,"|")) }return k }return[] }; gadgets.Prefs.prototype.setArray=function(k,l){throw new Error("setprefs feature required to make this call.") }; gadgets.Prefs.prototype.getMsg=function(k){return d[k]||"" }; gadgets.Prefs.prototype.getCountry=function(){return b }; gadgets.Prefs.prototype.getLang=function(){return e }; gadgets.Prefs.prototype.getModuleId=function(){return a } })();; /* [end] feature=core.prefs */ /* [start] feature=core.legacy */ var JSON=window.JSON||gadgets.json; var _IG_Prefs=(function(){var a=null; var b=function(){if(!a){a=new gadgets.Prefs(); a.setDontEscape_() }return a }; b._parseURL=gadgets.Prefs.parseUrl; return b })(); function _IG_Fetch_wrapper(b,a){b(a.data?a.data:"") }function _IG_FetchContent(b,g,c){var f=c||{}; if(f.refreshInterval){f.REFRESH_INTERVAL=f.refreshInterval }else{f.REFRESH_INTERVAL=3600 }for(var e in f){var d=f[e]; delete f[e]; f[e.toUpperCase()]=d }var a=gadgets.util.makeClosure(null,_IG_Fetch_wrapper,g); gadgets.io.makeRequest(b,a,f) }function _IG_FetchXmlContent(b,e,c){var d=c||{}; if(d.refreshInterval){d.REFRESH_INTERVAL=d.refreshInterval }else{d.REFRESH_INTERVAL=3600 }d.CONTENT_TYPE="DOM"; var a=gadgets.util.makeClosure(null,_IG_Fetch_wrapper,e); gadgets.io.makeRequest(b,a,d) }function _IG_FetchFeedAsJSON(b,f,c,a,d){var e=d||{}; e.CONTENT_TYPE="FEED"; e.NUM_ENTRIES=c; e.GET_SUMMARIES=a; gadgets.io.makeRequest(b,function(j){j.data=j.data||{}; if(j.errors&&j.errors.length>0){j.data.ErrorMsg=j.errors[0] }if(j.data.link){j.data.URL=b }if(j.data.title){j.data.Title=j.data.title }if(j.data.description){j.data.Description=j.data.description }if(j.data.link){j.data.Link=j.data.link }if(j.data.items&&j.data.items.length>0){j.data.Entry=j.data.items; for(var h=0; h<j.data.Entry.length; ++h){var i=j.data.Entry[h]; i.Title=i.title; i.Link=i.link; i.Summary=i.summary||i.description; i.Date=i.pubDate }}for(var g=0; g<j.data.Entry.length; ++g){var i=j.data.Entry[g]; i.Date=(i.Date/1000) }f(j.data) },e) }function _IG_GetCachedUrl(a,b){var c=b||{}; c.REFRESH_INTERVAL=3600; if(c.refreshInterval){c.REFRESH_INTERVAL=c.refreshInterval }return gadgets.io.getProxyUrl(a,c) }function _IG_GetImageUrl(a,b){return _IG_GetCachedUrl(a,b) }function _IG_GetImage(b){var a=document.createElement("img"); a.src=_IG_GetCachedUrl(b); return a }function _IG_RegisterOnloadHandler(a){gadgets.util.registerOnLoadHandler(a) }function _IG_Callback(b,c){var a=arguments; return function(){var d=Array.prototype.slice.call(arguments); b.apply(null,d.concat(Array.prototype.slice.call(a,1))) } }var _args=gadgets.util.getUrlParameters; function _gel(a){return document.getElementById?document.getElementById(a):null }function _gelstn(a){if(a==="*"&&document.all){return document.all }return document.getElementsByTagName?document.getElementsByTagName(a):[] }function _gelsbyregex(d,f){var c=_gelstn(d); var e=[]; for(var b=0,a=c.length; b<a; ++b){if(f.test(c[b].id)){e.push(c[b]) }}return e }function _esc(a){return window.encodeURIComponent?encodeURIComponent(a):escape(a) }function _unesc(a){return window.decodeURIComponent?decodeURIComponent(a):unescape(a) }function _hesc(a){return gadgets.util.escapeString(a) }function _striptags(a){return a.replace(/<\/?[^>]+>/g,"") }function _trim(a){return a.replace(/^\s+|\s+$/g,"") }function _toggle(a){a=(typeof a==="string")?_gel(a):a; if(a!==null){if(a.style.display.length===0||a.style.display==="block"){a.style.display="none" }else{if(a.style.display==="none"){a.style.display="block" }}}}var _uid=(function(){var a=0; return function(){return a++ } })(); function _min(d,c){return(d<c?d:c) }function _max(d,c){return(d>c?d:c) }function _exportSymbols(a,c){var m=window; var f=a.split("."); for(var h=0,g=f.length; h<g; h++){var b=f[h]; m[b]=m[b]||{}; m=m[b] }for(var e=0,d=c.length; e<d; e+=2){m[c[e]]=c[e+1] }}function _IG_AddDOMEventHandler(c,b,a){gadgets.warn("_IG_AddDOMEventHandler not implemented - see SHINDIG-198") };; /* [end] feature=core.legacy */ /* [start] feature=core.tracking */ (function(){function e(b,c,a){b={msg:b||"",line:a||0,jsUrl:0==window.location.href.indexOf(c)?"-top-":c,fullUrl:window.location};try{if(++window._varz_numerrors,gadgets&&!(3<f)){c={};c[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;a=encodeURIComponent||escape;var d=gadgets.util.getUrlParameters(),e=d.container||d.synd,g=d.gadget||d.url,k=["/gadgets/evthdlr?t=err&gadget=",a(g),"&container=",a(e),"&jsurl=",a(b.jsUrl),"&line=",a(b.line),"&session=",h,"&count=",f,"&msg=",a(b.msg)];gadgets.io.makeNonProxiedRequest(k.join(""), null,c);f++}}catch(l){}}window._varz_numerrors=0;var h=(new Date).getTime(),f=0;-1==window.location.href.indexOf("&debug=1")&&-1==window.location.href.indexOf("?debug=1")&&(window.onerror=e)})(); ; /* [end] feature=core.tracking */ /* [start] feature=core */ (function(){var l=null,p=function(){function e(a){a=(""+a).match(E);return!a?l:new b(q(a[1]),q(a[2]),q(a[3]),q(a[4]),q(a[5]),q(a[6]),q(a[7]))}function z(a,e){return"string"==typeof a?encodeURI(a).replace(e,B):l}function B(a){a=a.charCodeAt(0);return"%"+"0123456789ABCDEF".charAt(a>>4&15)+"0123456789ABCDEF".charAt(a&15)}function y(a){if(a===l)return l;for(var a=a.replace(/(^|\/)\.(?:\/|$)/g,"$1").replace(/\/{2,}/g,"/"),e=m,b;(b=a.replace(e,"$1"))!=a;a=b);return a}function A(a,e){var b=a.R(),g=e.K();g?b.fa(e.j): g=e.V();g?b.ca(e.m):g=e.W();g?b.da(e.k):g=e.Y();var m=e.g,k=y(m);if(g)b.ba(e.T()),k=k&&k.replace(x,"");else if(g=!!m){if(47!==k.charCodeAt(0))var k=y(b.g||"").replace(x,""),s=k.lastIndexOf("/")+1,k=y((s?k.substring(0,s):"")+y(m)).replace(x,"")}else k=k&&k.replace(x,""),k!==m&&b.G(k);g?b.G(k):g=e.Z();g?b.M(e.l):g=e.X();g&&b.ea(e.n);return b}function b(a,e,b,g,m,k,s){this.j=a;this.m=e;this.k=b;this.h=g;this.g=m;this.l=k;this.n=s}function q(a){return"string"==typeof a&&0<a.length?a:l}var m=RegExp(/(\/|^)(?:[^./][^/]*|\.{2,}(?:[^./][^/]*)|\.{3,}[^/]*)\/\.\.(?:\/|$)/), x=/^(?:\.\.\/)*(?:\.\.$)?/;b.prototype.toString=function(){var a=[];l!==this.j&&a.push(this.j,":");l!==this.k&&(a.push("//"),l!==this.m&&a.push(this.m,"@"),a.push(this.k),l!==this.h&&a.push(":",this.h.toString()));l!==this.g&&a.push(this.g);l!==this.l&&a.push("?",this.l);l!==this.n&&a.push("#",this.n);return a.join("")};b.prototype.R=function(){return new b(this.j,this.m,this.k,this.h,this.g,this.l,this.n)};b.prototype.U=function(){return this.j&&decodeURIComponent(this.j).toLowerCase()};b.prototype.fa= function(a){this.j=a?a:l};b.prototype.K=function(){return l!==this.j};b.prototype.ca=function(a){this.m=a?a:l};b.prototype.V=function(){return l!==this.m};b.prototype.da=function(a){this.k=a?a:l;this.G(this.g)};b.prototype.W=function(){return l!==this.k};b.prototype.T=function(){return this.h&&decodeURIComponent(this.h)};b.prototype.ba=function(a){if(a){a=Number(a);if(a!==(a&65535))throw Error("Bad port number "+a);this.h=""+a}else this.h=l};b.prototype.Y=function(){return l!==this.h};b.prototype.S= function(){return this.g&&decodeURIComponent(this.g)};b.prototype.G=function(a){a?(a=""+a,this.g=!this.k||/^\//.test(a)?a:"/"+a):this.g=l};b.prototype.M=function(a){this.l=a?a:l};b.prototype.Z=function(){return l!==this.l};b.prototype.aa=function(a){if("object"===typeof a&&!(a instanceof Array)&&(a instanceof Object||"[object Array]"!==Object.prototype.toString.call(a))){var e=[],b=-1,g;for(g in a){var m=a[g];"string"===typeof m&&(e[++b]=g,e[++b]=m)}a=e}for(var e=[],b="",k=0;k<a.length;)g=a[k++], m=a[k++],e.push(b,encodeURIComponent(g.toString())),b="&",m&&e.push("=",encodeURIComponent(m.toString()));this.l=e.join("")};b.prototype.ea=function(a){this.n=a?a:l};b.prototype.X=function(){return l!==this.n};var E=/^(?:([^:/?#]+):)?(?:\/\/(?:([^/?#]*)@)?([^/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/,D=/[#\/\?@]/g,F=/[\#\?]/g;b.parse=e;b.create=function(a,e,m,g,q,k,s){a=new b(z(a,D),z(e,D),"string"==typeof m?encodeURIComponent(m):l,0<g?g.toString():l,z(q,F),l,"string"==typeof s?encodeURIComponent(s): l);k&&("string"===typeof k?a.M(k.replace(/[^?&=0-9A-Za-z_\-~.%]/g,B)):a.aa(k));return a};b.$=A;b.ja=y;b.ua={oa:function(a){return/\.html$/.test(e(a).S())?"text/html":"application/javascript"},$:function(a,b){return a?A(e(a),e(b)).toString():""+b}};return b}();"undefined"!==typeof window&&(window.URI=p);var L={e:{NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,HTML:12,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10,MEDIA_QUERY:13}};L.atype=L.e; L.w={"*::class":9,"*::dir":0,"*::draggable":0,"*::hidden":0,"*::id":4,"*::inert":0,"*::itemprop":0,"*::itemref":6,"*::itemscope":0,"*::lang":0,"*::onblur":2,"*::onchange":2,"*::onclick":2,"*::ondblclick":2,"*::onerror":2,"*::onfocus":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2,"*::onmouseup":2,"*::onreset":2,"*::onscroll":2,"*::onselect":2,"*::onsubmit":2,"*::ontouchcancel":2,"*::ontouchend":2,"*::ontouchenter":2, "*::ontouchleave":2,"*::ontouchmove":2,"*::ontouchstart":2,"*::onunload":2,"*::spellcheck":0,"*::style":3,"*::title":0,"*::translate":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"audio::controls":0,"audio::loop":0,"audio::mediagroup":5, "audio::muted":0,"audio::preload":0,"audio::src":1,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2,"button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"canvas::height":0,"canvas::width":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0, "colgroup::width":0,"command::checked":0,"command::command":5,"command::disabled":0,"command::icon":1,"command::label":0,"command::radiogroup":0,"command::type":0,"data::value":0,"del::cite":1,"del::datetime":0,"details::open":0,"dir::compact":0,"div::align":0,"dl::compact":0,"fieldset::disabled":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0,"form::method":0,"form::name":7,"form::novalidate":0,"form::onreset":2,"form::onsubmit":2, "form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0,"img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0, "input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::inputmode":0,"input::ismap":0,"input::list":5,"input::max":0,"input::maxlength":0,"input::min":0,"input::multiple":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::placeholder":0,"input::readonly":0,"input::required":0,"input::size":0,"input::src":1,"input::step":0,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0, "label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2,"legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"menu::label":0,"menu::type":0,"meter::high":0,"meter::low":0,"meter::max":0,"meter::min":0,"meter::value":0,"ol::compact":0,"ol::reversed":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"output::for":6,"output::name":8,"p::align":0, "pre::width":0,"progress::max":0,"progress::min":0,"progress::value":0,"q::cite":1,"select::autocomplete":0,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::required":0,"select::size":0,"select::tabindex":0,"source::type":0,"table::align":0,"table::bgcolor":0,"table::border":0,"table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0, "tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::autocomplete":0,"textarea::cols":0,"textarea::disabled":0,"textarea::inputmode":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2,"textarea::onfocus":2,"textarea::onselect":2,"textarea::placeholder":0,"textarea::readonly":0, "textarea::required":0,"textarea::rows":0,"textarea::tabindex":0,"textarea::wrap":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0,"tr::valign":0, "track::default":0,"track::kind":0,"track::label":0,"track::srclang":0,"ul::compact":0,"ul::type":0,"video::controls":0,"video::height":0,"video::loop":0,"video::mediagroup":5,"video::muted":0,"video::poster":1,"video::preload":0,"video::src":1,"video::width":0};L.ATTRIBS=L.w;L.c={OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128,VIRTUALIZED:256};L.eflags=L.c; L.f={a:0,abbr:0,acronym:0,address:0,applet:272,area:2,article:0,aside:0,audio:0,b:0,base:274,basefont:274,bdi:0,bdo:0,big:0,blockquote:0,body:305,br:2,button:0,canvas:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,command:2,data:0,datalist:0,dd:1,del:0,details:0,dfn:0,dialog:272,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,figcaption:0,figure:0,font:0,footer:0,form:0,frame:274,frameset:272,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:305,header:0,hgroup:0,hr:2,html:305,i:0,iframe:4,img:2,input:2,ins:0,isindex:274, kbd:0,keygen:274,label:0,legend:0,li:1,link:274,map:0,mark:0,menu:0,meta:274,meter:0,nav:0,nobr:0,noembed:276,noframes:276,noscript:276,object:272,ol:0,optgroup:0,option:1,output:0,p:1,param:274,pre:0,progress:0,q:0,s:0,samp:0,script:84,section:0,select:0,small:0,source:2,span:0,strike:0,strong:0,style:148,sub:0,summary:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,time:0,title:280,tr:1,track:2,tt:0,u:0,ul:0,"var":0,video:0,wbr:2};L.ELEMENTS=L.f; L.O={a:"HTMLAnchorElement",abbr:"HTMLElement",acronym:"HTMLElement",address:"HTMLElement",applet:"HTMLAppletElement",area:"HTMLAreaElement",article:"HTMLElement",aside:"HTMLElement",audio:"HTMLAudioElement",b:"HTMLElement",base:"HTMLBaseElement",basefont:"HTMLBaseFontElement",bdi:"HTMLElement",bdo:"HTMLElement",big:"HTMLElement",blockquote:"HTMLQuoteElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",center:"HTMLElement", cite:"HTMLElement",code:"HTMLElement",col:"HTMLTableColElement",colgroup:"HTMLTableColElement",command:"HTMLCommandElement",data:"HTMLElement",datalist:"HTMLDataListElement",dd:"HTMLElement",del:"HTMLModElement",details:"HTMLDetailsElement",dfn:"HTMLElement",dialog:"HTMLDialogElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",dt:"HTMLElement",em:"HTMLElement",fieldset:"HTMLFieldSetElement",figcaption:"HTMLElement",figure:"HTMLElement",font:"HTMLFontElement",footer:"HTMLElement", form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",h2:"HTMLHeadingElement",h3:"HTMLHeadingElement",h4:"HTMLHeadingElement",h5:"HTMLHeadingElement",h6:"HTMLHeadingElement",head:"HTMLHeadElement",header:"HTMLElement",hgroup:"HTMLElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",i:"HTMLElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",ins:"HTMLModElement",isindex:"HTMLUnknownElement",kbd:"HTMLElement",keygen:"HTMLKeygenElement", label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",mark:"HTMLElement",menu:"HTMLMenuElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",nav:"HTMLElement",nobr:"HTMLElement",noembed:"HTMLElement",noframes:"HTMLElement",noscript:"HTMLElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement", progress:"HTMLProgressElement",q:"HTMLQuoteElement",s:"HTMLElement",samp:"HTMLElement",script:"HTMLScriptElement",section:"HTMLElement",select:"HTMLSelectElement",small:"HTMLElement",source:"HTMLSourceElement",span:"HTMLSpanElement",strike:"HTMLElement",strong:"HTMLElement",style:"HTMLStyleElement",sub:"HTMLElement",summary:"HTMLElement",sup:"HTMLElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",td:"HTMLTableDataCellElement",textarea:"HTMLTextAreaElement",tfoot:"HTMLTableSectionElement", th:"HTMLTableHeaderCellElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",tt:"HTMLElement",u:"HTMLElement",ul:"HTMLUListElement","var":"HTMLElement",video:"HTMLVideoElement",wbr:"HTMLElement"};L.ELEMENT_DOM_INTERFACES=L.O;L.N={NOT_LOADED:0,SAME_DOCUMENT:1,NEW_DOCUMENT:2};L.ueffects=L.N; L.J={"a::href":2,"area::href":2,"audio::src":1,"blockquote::cite":0,"command::icon":1,"del::cite":0,"form::action":2,"img::src":1,"input::src":1,"ins::cite":0,"q::cite":0,"video::poster":1,"video::src":1};L.URIEFFECTS=L.J;L.L={UNSANDBOXED:2,SANDBOXED:1,DATA:0};L.ltypes=L.L;L.I={"a::href":2,"area::href":2,"audio::src":2,"blockquote::cite":2,"command::icon":1,"del::cite":2,"form::action":2,"img::src":1,"input::src":1,"ins::cite":2,"q::cite":2,"video::poster":1,"video::src":2};L.LOADERTYPES=L.I; "undefined"!==typeof window&&(window.html4=L);var Q=function(e){function z(f){if(G.hasOwnProperty(f))return G[f];var a=f.match(R);return a?String.fromCharCode(parseInt(a[1],10)):(a=f.match(S))?String.fromCharCode(parseInt(a[1],16)):H&&T.test(f)?(H.innerHTML="&"+f+";",a=H.textContent,G[f]=a):"&"+f+";"}function B(f,a){return z(a)}function y(f){return f.replace(U,B)}function A(f){return(""+f).replace(V,"&amp;").replace(M,"&lt;").replace(N,"&gt;").replace(W,"&#34;")}function b(f){return f.replace(X,"&amp;$1").replace(M,"&lt;").replace(N,"&gt;")} function q(f){var a={z:f.z||f.cdata,A:f.A||f.comment,B:f.B||f.endDoc,r:f.r||f.endTag,d:f.d||f.pcdata,F:f.F||f.rcdata,H:f.H||f.startDoc,v:f.v||f.startTag};return function(f,e){var c;var b=/(<\/|<\!--|<[!?]|[&<>])/g;c=f+"";if(Y)c=c.split(b);else{for(var i=[],h=0,n;(n=b.exec(c))!==l;)i.push(c.substring(h,n.index)),i.push(n[0]),h=n.index+n[0].length;i.push(c.substring(h));c=i}x(a,c,0,{o:!1,C:!1},e)}}function m(f,a,d,e,c){return function(){x(f,a,d,e,c)}}function x(f,a,d,j,c){try{f.H&&0==d&&f.H(c);for(var b, i,h,n=a.length;d<n;){var r=a[d++],k=a[d];switch(r){case "&":Z.test(k)?(f.d&&f.d("&"+k,c,t,m(f,a,d,j,c)),d++):f.d&&f.d("&amp;",c,t,m(f,a,d,j,c));break;case "</":if(b=/^([-\w:]+)[^\'\"]*/.exec(k))if(b[0].length===k.length&&">"===a[d+1])d+=2,h=b[1].toLowerCase(),f.r&&f.r(h,c,t,m(f,a,d,j,c));else{var g=a,o=d,q=f,s=c,v=t,y=j,x=D(g,o);x?(q.r&&q.r(x.name,s,v,m(q,g,o,y,s)),d=x.next):d=g.length}else f.d&&f.d("&lt;/",c,t,m(f,a,d,j,c));break;case "<":if(b=/^([-\w:]+)\s*\/?/.exec(k))if(b[0].length===k.length&& ">"===a[d+1]){d+=2;h=b[1].toLowerCase();f.v&&f.v(h,[],c,t,m(f,a,d,j,c));var z=e.f[h];z&O&&(d=E(a,{name:h,next:d,c:z},f,c,t,j))}else{var g=a,o=f,q=c,s=t,v=j,C=D(g,d);C?(o.v&&o.v(C.name,C.P,q,s,m(o,g,C.next,v,q)),d=C.c&O?E(g,C,o,q,s,v):C.next):d=g.length}else f.d&&f.d("&lt;",c,t,m(f,a,d,j,c));break;case "<\!--":if(!j.C){for(i=d+1;i<n&&!(">"===a[i]&&/--$/.test(a[i-1]));i++);if(i<n){if(f.A){var A=a.slice(d,i).join("");f.A(A.substr(0,A.length-2),c,t,m(f,a,i+1,j,c))}d=i+1}else j.C=!0}j.C&&f.d&&f.d("&lt;!--", c,t,m(f,a,d,j,c));break;case "<!":if(/^\w/.test(k)){if(!j.o){for(i=d+1;i<n&&">"!==a[i];i++);i<n?d=i+1:j.o=!0}j.o&&f.d&&f.d("&lt;!",c,t,m(f,a,d,j,c))}else f.d&&f.d("&lt;!",c,t,m(f,a,d,j,c));break;case "<?":if(!j.o){for(i=d+1;i<n&&">"!==a[i];i++);i<n?d=i+1:j.o=!0}j.o&&f.d&&f.d("&lt;?",c,t,m(f,a,d,j,c));break;case ">":f.d&&f.d("&gt;",c,t,m(f,a,d,j,c));break;case "":break;default:f.d&&f.d(r,c,t,m(f,a,d,j,c))}}f.B&&f.B(c)}catch(B){if(B!==t)throw B;}}function E(a,w,d,j,c,u){var i=a.length;I.hasOwnProperty(w.name)|| (I[w.name]=RegExp("^"+w.name+"(?:[\\s\\/]|$)","i"));for(var h=I[w.name],n=w.next,r=w.next+1;r<i&&!("</"===a[r-1]&&h.test(a[r]));r++);r<i&&(r-=1);i=a.slice(n,r).join("");if(w.c&e.c.CDATA)d.z&&d.z(i,j,c,m(d,a,r,u,j));else if(w.c&e.c.RCDATA)d.F&&d.F(b(i),j,c,m(d,a,r,u,j));else throw Error("bug");return r}function D(a,b){var d=/^([-\w:]+)/.exec(a[b]),j={};j.name=d[1].toLowerCase();j.c=e.f[j.name];for(var c=a[b].substr(d[0].length),u=b+1,i=a.length;u<i&&">"!==a[u];u++)c+=a[u];if(!(i<=u)){for(var h=[];""!== c;)if(d=$.exec(c))if(d[4]&&!d[5]||d[6]&&!d[7]){for(var d=d[4]||d[6],n=!1,c=[c,a[u++]];u<i;u++){if(n){if(">"===a[u])break}else 0<=a[u].indexOf(d)&&(n=!0);c.push(a[u])}if(i<=u)break;c=c.join("")}else{var n=d[1].toLowerCase(),r;if(d[2]){r=d[3];var g=r.charCodeAt(0);if(34===g||39===g)r=r.substr(1,r.length-2);r=y(r.replace(aa,""))}else r="";h.push(n,r);c=c.substr(d[0].length)}else c=c.replace(/^[\s\S][^a-z\s]*/,"");j.P=h;j.next=u+1;return j}}function F(a){function b(a,f){j||f.push(a)}var d,j;return q({startDoc:function(){d= [];j=!1},startTag:function(c,b,i){if(!j&&e.f.hasOwnProperty(c)){var h=e.f[c];if(!(h&e.c.FOLDABLE)){var n=a(c,b);if(n){if("object"!==typeof n)throw Error("tagPolicy did not return object (old API?)");if("attribs"in n)b=n.attribs;else throw Error("tagPolicy gave no attribs");var g;"tagName"in n?(g=n.tagName,n=e.f[g]):(g=c,n=h);if(h&e.c.OPTIONAL_ENDTAG){var k=d[d.length-1];k&&k.D===c&&(k.t!==g||c!==g)&&i.push("</",k.t,">")}h&e.c.EMPTY||d.push({D:c,t:g});i.push("<",g);c=0;for(k=b.length;c<k;c+=2){var m= b[c],w=b[c+1];w!==l&&void 0!==w&&i.push(" ",m,'="',A(w),'"')}i.push(">");h&e.c.EMPTY&&!(n&e.c.EMPTY)&&i.push("</",g,">")}else j=!(h&e.c.EMPTY)}}},endTag:function(a,f){if(j)j=!1;else if(e.f.hasOwnProperty(a)){var b=e.f[a];if(!(b&(e.c.EMPTY|e.c.FOLDABLE))){if(b&e.c.OPTIONAL_ENDTAG)for(b=d.length;0<=--b;){var h=d[b].D;if(h===a)break;if(!(e.f[h]&e.c.OPTIONAL_ENDTAG))return}else for(b=d.length;0<=--b&&d[b].D!==a;);if(!(0>b)){for(h=d.length;--h>b;){var g=d[h].t;e.f[g]&e.c.OPTIONAL_ENDTAG||f.push("</",g, ">")}b<d.length&&(a=d[b].t);d.length=b;f.push("</",a,">")}}}},pcdata:b,rcdata:b,cdata:b,endDoc:function(a){for(;d.length;d.length--)a.push("</",d[d.length-1].t,">")}})}function a(a,b,d,e,c){if(!c)return l;try{var g=p.parse(""+a);if(g&&(!g.K()||ba.test(g.U()))){var i=c(g,b,d,e);return i?i.toString():l}}catch(h){}return l}function v(a,b,d,e,c){d||a(b+" removed",{Q:"removed",tagName:b});if(e!==c){var g="changed";e&&!c?g="removed":!e&&c&&(g="added");a(b+"."+d+" "+g,{Q:g,tagName:b,ia:d,oldValue:e,newValue:c})}} function J(a,b,d){b=b+"::"+d;if(a.hasOwnProperty(b))return a[b];b="*::"+d;if(a.hasOwnProperty(b))return a[b]}function g(b,g,d,j,c){for(var k=0;k<g.length;k+=2){var i=g[k],h=g[k+1],n=h,m=l,o;if((o=b+"::"+i,e.w.hasOwnProperty(o))||(o="*::"+i,e.w.hasOwnProperty(o)))m=e.w[o];if(m!==l)switch(m){case e.e.NONE:break;case e.e.SCRIPT:h=l;c&&v(c,b,i,n,h);break;case e.e.STYLE:if("undefined"===typeof s){h=l;c&&v(c,b,i,n,h);break}var q=[];s(h,{declaration:function(b,c){var f=b.toLowerCase();P(f,c,d?function(b){return a(b, e.N.ga,e.L.ha,{TYPE:"CSS",CSS_PROP:f},d)}:l);c.length&&q.push(f+": "+c.join(" "))}});h=0<q.length?q.join(" ; "):l;c&&v(c,b,i,n,h);break;case e.e.ID:case e.e.IDREF:case e.e.IDREFS:case e.e.GLOBAL_NAME:case e.e.LOCAL_NAME:case e.e.CLASSES:h=j?j(h):h;c&&v(c,b,i,n,h);break;case e.e.URI:h=a(h,J(e.J,b,i),J(e.I,b,i),{TYPE:"MARKUP",XML_ATTR:i,XML_TAG:b},d);c&&v(c,b,i,n,h);break;case e.e.URI_FRAGMENT:h&&"#"===h.charAt(0)?(h=h.substring(1),h=j?j(h):h,h!==l&&void 0!==h&&(h="#"+h)):h=l;c&&v(c,b,i,n,h);break; default:h=l,c&&v(c,b,i,n,h)}else h=l,c&&v(c,b,i,n,h);g[k+1]=h}return g}function K(a,b,d){return function(j,c){if(e.f[j]&e.c.UNSAFE)d&&v(d,j,void 0,void 0,void 0);else return{attribs:g(j,c,a,b,d)}}}function k(a,b){var d=[];F(b)(a,d);return d.join("")}var s,P;"undefined"!==typeof window&&(s=window.parseCssDeclarations,P=window.sanitizeCssProperty);var G={lt:"<",LT:"<",gt:">",GT:">",amp:"&",AMP:"&",quot:'"',apos:"'",nbsp:"\u00a0"},R=/^#(\d+)$/,S=/^#x([0-9A-Fa-f]+)$/,T=/^[A-Za-z][A-za-z0-9]+$/,H="undefined"!== typeof window&&window.document?window.document.createElement("textarea"):l,aa=/\0/g,U=/&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g,Z=/^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/,V=/&/g,X=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,M=/[<]/g,N=/>/g,W=/\"/g,$=/^\s*([-.:\w]+)(?:\s*(=)\s*((")[^"]*("|$)|(')[^']*('|$)|(?=[a-z][-\w]*\s*=)|[^"'\s]*))?/i,Y=3==="a,b".split(/(,)/).length,O=e.c.CDATA|e.c.RCDATA,t={},I={},ba=/^(?:https?|mailto)$/i,o={};o.ka=o.escapeAttrib=A;o.la=o.makeHtmlSanitizer=F;o.ma=o.makeSaxParser= q;o.na=o.makeTagPolicy=K;o.pa=o.normalizeRCData=b;o.qa=o.sanitize=function(a,b,d,e){return k(a,K(b,d,e))};o.ra=o.sanitizeAttribs=g;o.sa=o.sanitizeWithPolicy=k;o.ta=o.unescapeEntities=y;return o}(L),ca=Q.sanitize;"undefined"!==typeof window&&(window.html=Q,window.html_sanitize=ca);})(); ; /* [end] feature=core */ /* [start] feature=gapi.util-globals */ gapi.util=window.gapi&&window.gapi.util||{}; ; /* [end] feature=gapi.util-globals */ /* [start] feature=gapi.util.getOrigin */ gapi.util.getOrigin=function(a){if(!a)return"";a=a.split("#")[0].split("?")[0];a=a.toLowerCase();0==a.indexOf("//")&&(a=window.location.protocol+a);/^[\w\-]*:\/\//.test(a)||(a=window.location.href);var b=a.substring(a.indexOf("://")+3),c=b.indexOf("/");-1!=c&&(b=b.substring(0,c));a=a.substring(0,a.indexOf("://"));if("http"!==a&&"https"!==a&&"chrome-extension"!==a&&"file"!==a)throw Error("Invalid URI scheme in origin");var c="",d=b.indexOf(":");if(-1!=d){var e=b.substring(d+1),b=b.substring(0,d);if("http"=== a&&"80"!==e||"https"===a&&"443"!==e)c=":"+e}return a+"://"+b+c}; ; /* [end] feature=gapi.util.getOrigin */ /* [start] feature=rpc */ gadgets.rpctx=gadgets.rpctx||{}; if(!gadgets.rpctx.wpm){gadgets.rpctx.wpm=function(){var e,d; var c=true; function b(h,j,g){if(typeof window.addEventListener!="undefined"){window.addEventListener(h,j,g) }else{if(typeof window.attachEvent!="undefined"){window.attachEvent("on"+h,j) }}if(h==="message"){window.___jsl=window.___jsl||{}; var i=window.___jsl; i.RPMQ=i.RPMQ||[]; i.RPMQ.push(j) }}function a(h,i,g){if(window.removeEventListener){window.removeEventListener(h,i,g) }else{if(window.detachEvent){window.detachEvent("on"+h,i) }}}function f(h){var i=gadgets.json.parse(h.data); if(!i||!i.f){return }gadgets.debug("gadgets.rpc.receive("+window.name+"): "+h.data); var g=gadgets.rpc.getTargetOrigin(i.f); if(c&&(typeof h.origin!=="undefined"?h.origin!==g:h.domain!==/^.+:\/\/([^:]+).*/.exec(g)[1])){gadgets.error("Invalid rpc message origin. "+g+" vs "+(h.origin||"")); return }e(i,h.origin) }return{getCode:function(){return"wpm" },isParentVerifiable:function(){return true },init:function(h,i){function g(k){var j=k&&k.rpc||{}; if(String(j.disableForceSecure)==="true"){c=false }}gadgets.config.register("rpc",null,g); e=h; d=i; b("message",f,false); d("..",true); return true },setup:function(h,g){d(h,true); return true },call:function(h,k,j){var g=gadgets.rpc.getTargetOrigin(h); var i=gadgets.rpc._getTargetWin(h); if(g){window.setTimeout(function(){var l=gadgets.json.stringify(j); gadgets.debug("gadgets.rpc.send("+window.name+"): "+l); i.postMessage(l,g) },0) }else{if(h!=".."){gadgets.error("No relay set (used as window.postMessage targetOrigin), cannot send cross-domain message") }}return true }} }() };; gadgets.rpctx.ifpc = gadgets.rpctx.wpm; ; if(!window.gadgets||!window.gadgets["rpc"]){gadgets.rpc=function(){var M="__cb"; var S=""; var T="__ack"; var f=500; var G=10; var b="|"; var u="callback"; var g="origin"; var r="referer"; var s="legacy__"; var q={}; var W={}; var D={}; var B={}; var z=0; var l={}; var m={}; var d={}; var n={}; var E={}; var e=null; var p=null; var A=(window.top!==window.self); var v=window.name; var J=function(){}; var P=0; var Y=1; var a=2; var x=window.console; var V=x&&x.log&&function(ae){x.log(ae) }||function(){}; var R=(function(){function ae(af){return function(){V(af+": call ignored") } }return{getCode:function(){return"noop" },isParentVerifiable:function(){return true },init:ae("init"),setup:ae("setup"),call:ae("call")} })(); if(gadgets.util){d=gadgets.util.getUrlParameters() }function K(){if(d.rpctx=="flash"){return gadgets.rpctx.flash }if(d.rpctx=="rmr"){return gadgets.rpctx.rmr }var ae=typeof window.postMessage==="function"?gadgets.rpctx.wpm:typeof window.postMessage==="object"?gadgets.rpctx.wpm:window.ActiveXObject?(gadgets.rpctx.flash?gadgets.rpctx.flash:(gadgets.rpctx.nix?gadgets.rpctx.nix:gadgets.rpctx.ifpc)):navigator.userAgent.indexOf("WebKit")>0?gadgets.rpctx.rmr:navigator.product==="Gecko"?gadgets.rpctx.frameElement:gadgets.rpctx.ifpc; if(!ae){ae=R }return ae }function k(aj,ah){if(n[aj]){return }var af=H; if(!ah){af=R }n[aj]=af; var ae=E[aj]||[]; for(var ag=0; ag<ae.length; ++ag){var ai=ae[ag]; ai.t=F(aj); af.call(aj,ai.f,ai) }E[aj]=[] }var I=false,U=false; function N(){if(U){return }function ae(){I=true }if(typeof window.addEventListener!="undefined"){window.addEventListener("unload",ae,false) }else{if(typeof window.attachEvent!="undefined"){window.attachEvent("onunload",ae) }}U=true }function j(ae,ai,af,ah,ag){if(!B[ai]||B[ai]!==af){gadgets.error("Invalid gadgets.rpc token. "+B[ai]+" vs "+af); J(ai,a) }ag.onunload=function(){if(m[ai]&&!I){J(ai,Y); gadgets.rpc.removeReceiver(ai) }}; N(); ah=gadgets.json.parse(decodeURIComponent(ah)) }function Z(ak,af){if(ak&&typeof ak.s==="string"&&typeof ak.f==="string"&&ak.a instanceof Array){if(B[ak.f]){if(B[ak.f]!==ak.t){gadgets.error("Invalid gadgets.rpc token. "+B[ak.f]+" vs "+ak.t); J(ak.f,a) }}if(ak.s===T){window.setTimeout(function(){k(ak.f,true) },0); return }if(ak.c){ak[u]=function(al){var am=ak.g?s:""; gadgets.rpc.call(ak.f,am+M,null,ak.c,al) } }if(af){var ag=t(af); ak[g]=af; var ah=ak.r,aj; try{aj=t(ah) }catch(ai){}if(!ah||aj!=ag){ah=af }ak[r]=ah }var ae=(q[ak.s]||q[S]).apply(ak,ak.a); if(ak.c&&typeof ae!=="undefined"){gadgets.rpc.call(ak.f,M,null,ak.c,ae) }}}function t(ag){if(!ag){return"" }ag=((ag.split("#"))[0].split("?"))[0]; ag=ag.toLowerCase(); if(ag.indexOf("//")==0){ag=window.location.protocol+ag }if(ag.indexOf("://")==-1){ag=window.location.protocol+"//"+ag }var ah=ag.substring(ag.indexOf("://")+3); var ae=ah.indexOf("/"); if(ae!=-1){ah=ah.substring(0,ae) }var aj=ag.substring(0,ag.indexOf("://")); if(aj!=="http"&&aj!=="https"&&aj!=="chrome-extension"&&aj!=="file"){throw Error("Invalid URI scheme in origin") }var ai=""; var ak=ah.indexOf(":"); if(ak!=-1){var af=ah.substring(ak+1); ah=ah.substring(0,ak); if((aj==="http"&&af!=="80")||(aj==="https"&&af!=="443")){ai=":"+af }}return aj+"://"+ah+ai }function C(af,ae){return"/"+af+(ae?b+ae:"") }function y(ah){if(ah.charAt(0)=="/"){var af=ah.indexOf(b); var ag=af>0?ah.substring(1,af):ah.substring(1); var ae=af>0?ah.substring(af+1):null; return{id:ag,origin:ae} }else{return null }}function ad(ag){if(typeof ag==="undefined"||ag===".."){return window.parent }var af=y(ag); if(af){return window.top.frames[af.id] }ag=String(ag); var ae=window.frames[ag]; if(ae){return ae }ae=document.getElementById(ag); if(ae&&ae.contentWindow){return ae.contentWindow }return null }function L(ah){var ag=null; var ae=O(ah); if(ae){ag=ae }else{var af=y(ah); if(af){ag=af.origin }else{if(ah==".."){ag=d.parent }else{ag=document.getElementById(ah).src }}}return t(ag) }var H=K(); q[S]=function(){V("Unknown RPC service: "+this["s"]) }; q[M]=function(af,ae){var ag=l[af]; if(ag){delete l[af]; ag.call(this,ae) }}; function X(ag,ae){if(m[ag]===true){return }if(typeof m[ag]==="undefined"){m[ag]=0 }var af=ad(ag); if(ag===".."||af!=null){if(H.setup(ag,ae)===true){m[ag]=true; return }}if(m[ag]!==true&&m[ag]++<G){window.setTimeout(function(){X(ag,ae) },f) }else{n[ag]=R; m[ag]=true }}function O(af){var ae=W[af]; if(ae&&ae.substring(0,1)==="/"){if(ae.substring(1,2)==="/"){ae=document.location.protocol+ae }else{ae=document.location.protocol+"//"+document.location.host+ae }}return ae }function ac(af,ae,ag){if(ae&&!/http(s)?:\/\/.+/.test(ae)){if(ae.indexOf("//")==0){ae=window.location.protocol+ae }else{if(ae.charAt(0)=="/"){ae=window.location.protocol+"//"+window.location.host+ae }else{if(ae.indexOf("://")==-1){ae=window.location.protocol+"//"+ae }}}}W[af]=ae; if(typeof ag!=="undefined"){D[af]=!!ag }}function F(ae){return B[ae] }function c(ae,af){af=af||""; B[ae]=String(af); X(ae,af) }function ab(af){var ae=af.passReferrer||""; var ag=ae.split(":",2); e=ag[0]||"none"; p=ag[1]||"origin" }function aa(ae){if(Q(ae)){H=gadgets.rpctx.ifpc||R; H.init(Z,k) }}function Q(ae){return String(ae.useLegacyProtocol)==="true" }function h(af,ae){function ag(aj){var ai=aj&&aj.rpc||{}; ab(ai); var ah=ai.parentRelayUrl||""; ah=t(d.parent||ae)+ah; ac("..",ah,Q(ai)); aa(ai); c("..",af) }if(!d.parent&&ae){ag({}); return }gadgets.config.register("rpc",null,ag) }function o(af,aj,al){var ai=null; if(af.charAt(0)!="/"){if(!gadgets.util){return }ai=document.getElementById(af); if(!ai){throw new Error("Cannot set up gadgets.rpc receiver with ID: "+af+", element not found.") }}var ae=ai&&ai.src; var ag=aj||gadgets.rpc.getOrigin(ae); ac(af,ag); var ak=gadgets.util.getUrlParameters(ae); var ah=al||ak.rpctoken; c(af,ah) }function i(ae,ag,ah){if(ae===".."){var af=ah||d.rpctoken||d.ifpctok||""; h(af,ag) }else{o(ae,ag,ah) }}function w(ag){if(e==="bidir"||(e==="c2p"&&ag==="..")||(e==="p2c"&&ag!=="..")){var af=window.location.href; var ah="?"; if(p==="query"){ah="#" }else{if(p==="hash"){return af }}var ae=af.lastIndexOf(ah); ae=ae===-1?af.length:ae; return af.substring(0,ae) }return null }return{config:function(ae){if(typeof ae.securityCallback==="function"){J=ae.securityCallback }},register:function(af,ae){if(af===M||af===T){throw new Error("Cannot overwrite callback/ack service") }if(af===S){throw new Error("Cannot overwrite default service: use registerDefault") }q[af]=ae },unregister:function(ae){if(ae===M||ae===T){throw new Error("Cannot delete callback/ack service") }if(ae===S){throw new Error("Cannot delete default service: use unregisterDefault") }delete q[ae] },registerDefault:function(ae){q[S]=ae },unregisterDefault:function(){delete q[S] },forceParentVerifiable:function(){if(!H.isParentVerifiable()){H=gadgets.rpctx.ifpc }},call:function(ae,ag,al,aj){ae=ae||".."; var ak=".."; if(ae===".."){ak=v }else{if(ae.charAt(0)=="/"){ak=C(v,gadgets.rpc.getOrigin(window.location.href)) }}++z; if(al){l[z]=al }var ai={s:ag,f:ak,c:al?z:0,a:Array.prototype.slice.call(arguments,3),t:B[ae],l:!!D[ae]}; var af=w(ae); if(af){ai.r=af }if(ae!==".."&&y(ae)==null&&!document.getElementById(ae)){return }var ah=n[ae]; if(!ah&&y(ae)!==null){ah=H }if(ag.indexOf(s)===0){ah=H; ai.s=ag.substring(s.length); ai.c=ai.c?ai.c:z }ai.g=true; ai.r=ak; if(!ah){if(!E[ae]){E[ae]=[ai] }else{E[ae].push(ai) }return }if(D[ae]){ah=gadgets.rpctx.ifpc }if(ah.call(ae,ak,ai)===false){n[ae]=R; H.call(ae,ak,ai) }},getRelayUrl:O,setRelayUrl:ac,setAuthToken:c,setupReceiver:i,getAuthToken:F,removeReceiver:function(ae){delete W[ae]; delete D[ae]; delete B[ae]; delete m[ae]; delete n[ae] },getRelayChannel:function(){return H.getCode() },receive:function(af,ae){if(af.length>4){H._receiveMessage(af,Z) }else{j.apply(null,af.concat(ae)) }},receiveSameDomain:function(ae){ae.a=Array.prototype.slice.call(ae.a); window.setTimeout(function(){Z(ae) },0) },getOrigin:t,getTargetOrigin:L,init:function(){if(H.init(Z,k)===false){H=R }if(A){i("..") }else{gadgets.config.register("rpc",null,function(af){var ae=af.rpc||{}; ab(ae); aa(ae) }) }},_getTargetWin:ad,_parseSiblingId:y,ACK:T,RPC_ID:v||"..",SEC_ERROR_LOAD_TIMEOUT:P,SEC_ERROR_FRAME_PHISH:Y,SEC_ERROR_FORGED_MSG:a} }(); gadgets.rpc.init() }else{if(typeof gadgets.rpc=="undefined"||!gadgets.rpc){gadgets.rpc=window.gadgets["rpc"]; gadgets.rpc.config=gadgets.rpc.config; gadgets.rpc.register=gadgets.rpc.register; gadgets.rpc.unregister=gadgets.rpc.unregister; gadgets.rpc.registerDefault=gadgets.rpc.registerDefault; gadgets.rpc.unregisterDefault=gadgets.rpc.unregisterDefault; gadgets.rpc.forceParentVerifiable=gadgets.rpc.forceParentVerifiable; gadgets.rpc.call=gadgets.rpc.call; gadgets.rpc.getRelayUrl=gadgets.rpc.getRelayUrl; gadgets.rpc.setRelayUrl=gadgets.rpc.setRelayUrl; gadgets.rpc.setAuthToken=gadgets.rpc.setAuthToken; gadgets.rpc.setupReceiver=gadgets.rpc.setupReceiver; gadgets.rpc.getAuthToken=gadgets.rpc.getAuthToken; gadgets.rpc.removeReceiver=gadgets.rpc.removeReceiver; gadgets.rpc.getRelayChannel=gadgets.rpc.getRelayChannel; gadgets.rpc.receive=gadgets.rpc.receive; gadgets.rpc.receiveSameDomain=gadgets.rpc.receiveSameDomain; gadgets.rpc.getOrigin=gadgets.rpc.getOrigin; gadgets.rpc.getTargetOrigin=gadgets.rpc.getTargetOrigin; gadgets.rpc._getTargetWin=gadgets.rpc._getTargetWin; gadgets.rpc._parseSiblingId=gadgets.rpc._parseSiblingId }};; /* [end] feature=rpc */ /* [start] feature=config.min */ gapi.config={};gapi.config.GLOBAL_CFG_KEY="___gcfg";gapi.config.GLOBAL_CFG_USED="___gu";gapi.config.JSL_KEY="___jsl";gapi.config.DEFAULT_CFG_KEY="cd";gapi.config.USER_CFG_KEY="cu";gapi.config.INJECTED_CFG_KEY="ci";gapi.config.SAVED_CFG_KEY="cfg";gapi.config.ALL_SOURCES_KEY="us";gapi.config.ATTR_PROCESSED_CONFIG="gapi_processed";gapi.config.jsl=function(){return window[gapi.config.JSL_KEY]=window[gapi.config.JSL_KEY]||{}};gapi.config.jslComponent=function(a){var b=gapi.config.jsl();b[a]=b[a]||[];return b[a]}; gapi.config.cfg=function(a){var b=gapi.config.jsl();b[gapi.config.SAVED_CFG_KEY]=!a&&b[gapi.config.SAVED_CFG_KEY]||{};return b[gapi.config.SAVED_CFG_KEY]};gapi.config.isArray=function(a){return"object"===typeof a&&/\[native code\]/.test(a.push)}; gapi.config.foldConfig=function(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]&&b[c]&&"object"===typeof a[c]&&"object"===typeof b[c]&&!gapi.config.isArray(a[c])&&!gapi.config.isArray(b[c])?gapi.config.foldConfig(a[c],b[c]):b[c]&&"object"===typeof b[c]?(a[c]=gapi.config.isArray(b[c])?[]:{},gapi.config.foldConfig(a[c],b[c])):a[c]=b[c])}; gapi.config.getSelfScriptTags=function(){var a=document.scripts||document.getElementsByTagName("script")||[],b=[],c=[];c.push.apply(c,gapi.config.getAllSourceUrls());for(var d=0;d<a.length;++d)for(var e=a[d],f=0;f<c.length;++f)e.src&&0==e.src.indexOf(c[f])&&b.push(e);0==b.length&&0<a.length&&a[a.length-1].src&&b.push(a[a.length-1]);return b}; gapi.config.appendInlineConfig=function(){for(var a=gapi.config.jslComponent(gapi.config.USER_CFG_KEY),b=gapi.config.getSelfScriptTags(),c=0;c<b.length;++c)if(!b[c].getAttribute(gapi.config.ATTR_PROCESSED_CONFIG)){b[c].setAttribute(gapi.config.ATTR_PROCESSED_CONFIG,!0);var d=gapi.config.getInnerText(b[c]);(d=gapi.config.parseConfig(d))&&a.push(d)}};gapi.config.getAllSourceUrls=function(){return gapi.config.jslComponent(gapi.config.ALL_SOURCES_KEY)}; gapi.config.getInnerText=function(a){if(a){var b=a.nodeType;return 3==b||4==b?a.nodeValue:a.textContent||a.innerText||a.innerHTML||""}}; gapi.config.parseConfig=function(a){if(a&&!/^\s+$/.test(a)){for(;0==a.charCodeAt(a.length-1);)a=a.substring(0,a.length-1);var b;try{b=window.JSON.parse(a)}catch(c){}if("object"===typeof b)return b;try{b=(new Function("return ("+a+"\n)"))()}catch(d){}if("object"===typeof b)return b;try{b=(new Function("return ({"+a+"\n})"))()}catch(e){}return"object"===typeof b?b:{}}}; gapi.config.mergeConfig=function(a){gapi.config.cfg(!0);var b=window[gapi.config.GLOBAL_CFG_KEY],c=gapi.config.jslComponent(gapi.config.USER_CFG_KEY);if(b&&b!==window[gapi.config.GLOBAL_CFG_USED]){var d={};gapi.config.foldConfig(d,b);c.push(d);window[gapi.config.GLOBAL_CFG_USED]=b}gapi.config.appendInlineConfig();a&&(d={},gapi.config.foldConfig(d,a),c.push(d));d=gapi.config.jslComponent(gapi.config.DEFAULT_CFG_KEY);a=0;for(b=d.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),d[a]);d=gapi.config.jslComponent(gapi.config.INJECTED_CFG_KEY); a=0;for(b=d.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),d[a]);a=0;for(b=c.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),c[a])};gapi.config.get=function(a,b){if(!a)return gapi.config.cfg();for(var c=a.split("/"),d=gapi.config.cfg(),e=0,f=c.length;d&&"object"===typeof d&&e<f;++e)d=d[c[e]];return e===c.length&&void 0!==d?d:b};gapi.config.update=function(a,b){var c=a;if("string"===typeof a){for(var d=c={},e=a.split("/"),f=0,g=e.length;f<g-1;++f)var h={},d=d[e[f]]=h;d[e[f]]=b}gapi.config.mergeConfig(c)}; gapi.config.prefixGet=function(a){return function(b){return b?gapi.config.get(a+"/"+b):gapi.config.get(a)}};gapi.config.init_=gapi.config.mergeConfig;gapi.config.legacyInit&&gapi.config.legacyInit();gapi.config.init_(); ; /* [end] feature=config.min */ /* [start] feature=shindig.sha1 */ shindig.sha1=(function(){var d="0123456789ABCDEF"; var h=[]; var e=[]; var l=[]; var o=[]; o[0]=128; for(var g=1; g<64; ++g){o[g]=0 }var n; var b; function j(){h[0]=1732584193; h[1]=4023233417; h[2]=2562383102; h[3]=271733878; h[4]=3285377520; n=0; b=0 }function m(i,p){return((i<<p)|(i>>>(32-p)))&4294967295 }function a(p){var q=l; for(var s=0; s<64; s+=4){var B=(p[s]<<24)|(p[s+1]<<16)|(p[s+2]<<8)|(p[s+3]); q[s/4]=B }for(var s=16; s<80; s++){q[s]=m(q[s-3]^q[s-8]^q[s-14]^q[s-16],1) }var A=h[0]; var z=h[1]; var y=h[2]; var x=h[3]; var v=h[4]; var u,r; for(var s=0; s<80; s++){if(s<40){if(s<20){u=x^(z&(y^x)); r=1518500249 }else{u=z^y^x; r=1859775393 }}else{if(s<60){u=(z&y)|(x&(z|y)); r=2400959708 }else{u=z^y^x; r=3395469782 }}var C=(m(A,5)+u+v+r+q[s])&4294967295; v=x; x=y; y=m(z,30); z=A; A=C }h[0]=(h[0]+A)&4294967295; h[1]=(h[1]+z)&4294967295; h[2]=(h[2]+y)&4294967295; h[3]=(h[3]+x)&4294967295; h[4]=(h[4]+v)&4294967295 }function f(q,s){if(typeof(q)==="string"){q=unescape(encodeURIComponent(q)); var p=[]; for(var t=0,r=q.length; t<r; ++t){p.push(q.charCodeAt(t)) }q=p }if(!s){s=q.length }var u=0; if(n==0){while(u+64<s){a(q.slice(u,u+64)); u+=64; b+=64 }}while(u<s){e[n++]=q[u++]; b++; if(n==64){n=0; a(e); while(u+64<s){a(q.slice(u,u+64)); u+=64; b+=64 }}}}function k(){var s=[]; var r=b*8; if(n<56){f(o,56-n) }else{f(o,64-(n-56)) }for(var q=63; q>=56; q--){e[q]=r&255; r>>>=8 }a(e); var t=0; for(var q=0; q<5; q++){for(var p=24; p>=0; p-=8){s[t++]=(h[q]>>p)&255 }}return s }function c(){var p=k(); var r=""; for(var q=0; q<p.length; q++){r+=d.charAt(Math.floor(p[q]/16))+d.charAt(p[q]%16) }return r }j(); return{reset:j,update:f,digest:k,digestString:c} });; /* [end] feature=shindig.sha1 */ /* [start] feature=shindig.random */ shindig.random=(function(){var a=window.crypto; if(a&&typeof a.getRandomValues=="function"){return function(){var k=new window.Uint32Array(1); a.getRandomValues(k); return Number("0."+k[0]) } }var d=gapi.config.get("random/maxObserveMousemove"); if(d==null){d=-1 }var j=0; var f=Math.random(); var e="0123456789ABCDEF"; var c=1; var g=((screen.width*screen.width)+screen.height)*1000000; var b=function(l){l=l||window.event; var k=(l.screenX+l.clientX)<<16; k+=(l.screenY+l.clientY); k*=new Date().getTime()%1000000; c=(c*k)%g; if(d>0&&++j==d){gadgets.util.removeBrowserEvent(window,"mousemove",b,false) }}; if(d!=0){gadgets.util.attachBrowserEvent(window,"mousemove",b,false) }function i(k){var l=shindig.sha1(); l.update(k); return l.digestString() }var h=i(document.cookie+"|"+document.location+"|"+(new Date()).getTime()+"|"+f); return function(){var k=c; k+=parseInt(h.substr(0,20),16); h=i(h); return k/(g+Math.pow(16,20)) } })();; /* [end] feature=shindig.random */ gadgets.config.init({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}}); (function(){var j=window['___jsl']=window['___jsl']||{};j['l']=(j['l']||[]).concat(['core','rpc','shindig.random','shindig.sha1']);})();(function(){var j=window['___jsl']=window['___jsl']||{};if(j['c']){j['c']();delete j['c'];}})();
JavaScript
var Community = { init: function() { cur.Rpc = new fastXDM.Client({ onInit: function() { setTimeout(function () { Community.resizeWidget(); }, 500); }, authorised: function (args) { var href = location.href; if (href.indexOf('fieldText=') != -1) href = href.replace(/fieldText=.+?(&|$)/, 'fieldText=' + winToUtf(ge('commentFiled').getValue()) + '\1'); else href = href + '&fieldText=' + winToUtf(ge('commentFiled').getValue()); if (href.indexOf('autoLogin=1') != -1) href = href.replace('autoLogin=1', 'autoLogin=0'); location.href = href; return; }, unauthorised: function (args) { var href = location.href; if (href.indexOf('autoLogin=0') != -1) href = href.replace('autoLogin=0', 'autoLogin=1'); else href = href + '&autoLogin=1'; cur.Rpc.callMethod('auth'); location.href = href; return; }, mouseMove: function(screenY) { cur.mouseMove(screenY); }, mouseUp: function() { cur.mouseUp(); } }, {safe: true}); cur.mainDiv = ge('main'); Community.resizeWidget(); if (window.wall) { wall.postTooltip = function() {}; } setTimeout(function () { Community.resizeWidget(); }, 0); }, resizeWidget: function() { onBodyResize(true); if (!cur.mainDiv || !cur.Rpc) return; var size = getSize(cur.mainDiv)[1]; cur.Rpc.callMethod('resize', size); }, sendChangeState: function(state, oid, callback, isEvent) { if (state) { cur.Rpc.callMethod('publish', 'widgets.groups.joined'); } else { cur.Rpc.callMethod('publish', 'widgets.groups.leaved'); } var hiddenDomain = ge('hiddenDomain'); if (hiddenDomain) { domain = hiddenDomain.value; } else { domain = ''; } ajax.post('/widget_community.php', { act: 'a_change_state', state: state, oid: oid, hash: cur.hash, domain: domain, is_event: isEvent ? 1 : 0 }, { onDone: function(result, str) { if (callback) { callback(result, str); } }, onFail: function() {} }); }, changeGroupState: function(state, callback) { if (cur.isAdmin) { if (!confirm(cur.isAdminLang)) { return false; } } if (cur.noAuth) { Community.widgetAuth(); window.gotSession = function(autorzied) { if (autorzied == -1) { setTimeout(function () { location.reload(); }, 1000); location.href = location.href + '&1'; } if (autorzied) { ajax.post('/widget_community.php', {act: 'a_get_info', oid: cur.oid}, { onDone: function(result) { if (result.hash) { cur.noAuth = false; cur.justAuth = true; cur.hash = result.hash; cur.can_subscribe = result.can_subscribe; if (result.subscribed) { addClass(cur.join_community, 'community_checked'); } else { removeClass(cur.join_community, 'community_checked'); } Community.changeGroupState(state, callback); } } }); } else { } } return false; } else { if (!cur.justAuth && ge('community_anim_row')) { if (state) { animate(ge('community_anim_row'), {marginLeft: 0}, 200); ge('members_count').innerHTML = cur.count_in; } else { animate(ge('community_anim_row'), {marginLeft: -cur.mWidth}, 200); ge('members_count').innerHTML = cur.count_out; } } Community.sendChangeState(state, cur.oid); callback(); return true; } }, changeEventState: function(state, oid, btn) { if (cur.noAuth) { Community.widgetAuth(); window.gotSession = function(autorzied) { cur.noAuth = false; ajax.post('/widget_community.php', {act: 'a_get_info', oid: cur.oid}, { onDone: function(result) { if (result.hash) { cur.hash = result.hash; cur.can_subscribe = result.can_subscribe; Community.changeEventState(state, oid, btn); } } }); } return false; } if (state == -1) { cur.linkCont = btn.innerHTML; btn.innerHTML = '<img src="/images/upload.gif" />'; } else { lockButton(btn); } Community.sendChangeState(state, cur.oid, function(html) { if (state == -1) { btn.innerHTML = cur.linkCont; } else { unlockButton(btn); } ge('community_event_join').innerHTML = html; Community.resizeWidget(); }, 1); }, widgetAuth: function() { var screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft, screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop, outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth, outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22), features = 'width=655,height=479,left=' + parseInt(screenX + ((outerWidth - 655) / 2), 10) + ',top=' + parseInt(screenY + ((outerHeight - 479) / 2.5), 10); window.activePopup = window.open(location.protocol + '//oauth.vk.com/authorize?client_id=-1&redirect_uri=close.html&display=widget', 'vk_openapi', features); function checkWnd() { if (window.activePopup.closed) { window.gotSession(true); } else { setTimeout(checkWnd, 1000); } } checkWnd(); }, toggleStat: function(oid, width) { if (cur.statShown) { setStyle(ge('community_groups_main'), {height: 'auto'}); hide('hide_stat'); show('show_stat'); show('community_content'); hide('stat_info'); setTimeout(Community.resizeWidget, 0); } else { cur.oldHeight = getSize('community_groups_main')[1]; show('hide_stat'); hide('show_stat'); hide('community_content'); show('stat_info'); setTimeout(Community.resizeWidget, 0); setTimeout(Community.resizeWidget, 500); if (!cur.statLoaded) { setStyle(ge('community_groups_main'), {height: cur.oldHeight - 8}); setStyle(ge('wcomments_progress'), {marginTop: cur.oldHeight / 2 - 40}); ajax.post('/widget_community.php', {act: 'a_get_stat', width: width, oid: oid}, { onDone: function(text) { setStyle(ge('community_groups_main'), {height: 'auto'}); cur.statLoaded = true; ge('stat_info').innerHTML = text; setTimeout(Community.resizeWidget, 0); setTimeout(Community.resizeWidget, 500); } }); } else { setStyle(ge('community_groups_main'), {height: 'auto'}); } } cur.statShown = !cur.statShown; }, membersBox: function(oid) { cur.Rpc.callMethod('showBox', 'widget_community.php?act=members_box&oid='+oid, {height: 442, width: 498}); }, subscribeGroupState: function(state, oid) { ajax.post('/widget_community.php', {act: 'a_subscribe', state: state, oid: oid, hash: cur.hash}, { onDone: function(t) { }, onFail: function() { return true; } }); return true; }, hideStat: function(oid, width) { hide('hide_stat'); show('show_stat'); show('community_content'); hide('stat_info'); setTimeout(Community.resizeWidget, 0); }, subscribeSimple: function() { Community.changeGroupState(1, function() { hide('subscribe_button'); show('unsubscribe_button'); if (cur.canSwitch) { hide('community_friends'); show('community_like'); } }); }, unsubscribeSimple: function() { Community.changeGroupState(0, function() { show('subscribe_button'); hide('unsubscribe_button'); if (cur.canSwitch) { show('community_friends'); hide('community_like'); } }); }, headerOver: function(ev) { if (cur.nameOutTimeout) { clearTimeout(cur.nameOutTimeout); } if (cur.headTween) { return; } var obj = ge('wcommunity_name_cont'); addClass(obj, 'wcommuinty_name_scrolling'); var anim = ge('wcommunity_name_anim'); var width = getSize(anim)[0] - getSize(obj)[0]; if (width < 0) { return false; } var speed = width * 40; if (cur.headTimeout) { clearTimeout(cur.headTimeout); } cur.headTween = animate(anim, {marginLeft: -width}, {duration: speed, transition: Fx.Transitions.linear, onComplete:function() { cur.headTimeout = setTimeout(function() { cur.headTween = animate(anim, {marginLeft: 0}, {duration: speed, transition: Fx.Transitions.linear, onComplete: function() { cur.headTween = false; cur.headTimeout = setTimeout(Community.headerOver.pbind(ev), 1000); }}); }, 1000); }}); }, headerOut: function(ev) { var obj = ge('wcommunity_name_cont'); if (cur.headTimeout) { clearTimeout(cur.headTimeout); } cur.nameOutTimeout = setTimeout(function() { var anim = ge('wcommunity_name_anim'); cur.headTween = animate(anim, {marginLeft: 0}, 200, function() { removeClass(obj, 'wcommuinty_name_scrolling'); cur.headTween = false; }); if (cur.headTimeout) { clearTimeout(cur.headTimeout); } }, 50); }, _eof: 1};try{stManager.done('api/widgets/al_community.js');}catch(e){} window.gotSession = function(session_data) { //pass } var communityWall = { postTooltip: function(el, post, opts) { if (cur.viewAsBox) return; var poll = geByClass('poll', el); if (poll.length && cur.baseUrl) { el.href = cur.baseUrl + 'wall'+post; } return true; }, showMore: function() { if (cur.wallLoaded) { return false; } if (cur.loadingMore) { cur.meedMore = true; return; } cur.loadingMore = true; hide('wall_more_text'); show('wall_more_progress'); var params = { act: 'load_more', offset: cur.offset, oid: cur.oid, wide: cur.wide, width: cur.width }; if (cur.mode) { params.mode = 1; } ajax.post('/widget_community.php', params, { onDone: function(wallCont, count, limit) { cur.offset += limit; if (cur.offset >= count) { cur.wallLoaded = true; hide('wall_more_cont'); } ge('page_wall_posts').appendChild(ce('div', { innerHTML: wallCont })); Community.resizeWidget(); setTimeout(Community.resizeWidget, 500); show('wall_more_text'); hide('wall_more_progress'); cur.loadingMore = false; if (cur.meedMore) { cur.meedMore = false; setTimeout(function() { communityWall.showMore() }, 0); } if (cur.scrollbar) { cur.scrollbar.update(); } }, onFail: function() { return true; } }) } } function goAway(url) { return true; } function showPhoto (photo, list) { var h = 607, w = 607; cur.Rpc.callMethod('showBox', 'al_photos.php?' + ajx2q({act: 'photo_box', photo: photo, wall_owner: photo.split('_')[0], widget: 1, list: list, widget_width: 654, widget: 1}), {height: window.outerHeight || screen.availHeight || 768, width: window.outerWidth || screen.availWidth || 1028}); return false; } function showVideo(video, list) { cur.Rpc.callMethod('showBox', 'al_video.php?' + ajx2q({act: 'video_box', video: video, list: list, wall_owner: video.split('_')[0], widget_width: 654, widget: 1}), {height: window.outerHeight || screen.availHeight || 768, width: window.outerWidth || screen.availWidth || 1028}); return false; } function showFriends(oid) { if (oid > 0) return true; cur.Rpc.callMethod('showBox', 'al_page.php?' + ajx2q({act: 'show_members_box', gid: -oid, tab: 'friends', widget: 1}), {height: 495, width: 432}); return false; } // Tiny Scrollbars start (from al_community.js) (function(w) { w.Scrollbar = function (obj, options) { this.obj = obj = ge(obj); this.options = options || {}; setTimeout((function() { if (!obj) return; setStyle(obj, { overflow: 'hidden' }); var size = getSize(obj); if (size[0] < 100 && options.width) { size[0] = options.width - 2; } this.scrollHeight = size[1]; this.scrollbar = ce('div', { className: 'scrollbar_cont' }); setStyle(this.scrollbar, { right: '1px', left: 'auto', height: size[1] + 'px' }); this.inner = ce('div', { className: 'scrollbar_inner' }); this.scrollbar.appendChild(this.inner); if (options.shadows) { this.topShadowDiv = ce('div', { className: 'scrollbar_top' }); this.bottomShadowDiv = ce('div', { className: 'scrollbar_bottom', width: size[0]+'px' }); this.bottomShadowDiv.style.width = this.topShadowDiv.style.width = size[0]+'px'; obj.parentNode.insertBefore(this.topShadowDiv, obj); obj.parentNode.insertBefore(this.bottomShadowDiv, obj.nextSibling); } obj.parentNode.insertBefore(this.scrollbar, obj); this.mouseMove = this._mouseMove.bind(this); this.mouseUp = this._mouseUp.bind(this); var self = this; function down(event) { if (self.moveY) return; addEvent(w.document, 'mousemove', self.mouseMove); addEvent(w.document, 'mouseup', self.mouseUp); self.moveY = event.screenY - (parseInt(self.inner.style.marginTop) || 0); w.document.body.style.cursor = 'pointer'; addClass(self.inner, 'scrollbar_hovered'); if (options.startDrag) { options.startDrag(); } self.isDown = true; return cancelEvent(event); } this.mouseDown = down; function keydown(event) { var key = event.keyCode; switch (key) { case 40: self.obj.scrollTop += 20; break; case 38: self.obj.scrollTop -= 20; break; case 34: self.obj.scrollTop += self.scrollHeight; break; case 33: self.obj.scrollTop -= self.scrollHeight; break; default: return true; } self.update(true); return cancelEvent(event); } addEvent(obj, 'mousewheel', this.wheel.bind(this)); addEvent(w, 'DOMMouseScroll', this.wheel.bind(this)); addEvent(this.scrollbar, 'mouseover', this.contOver.bind(this)); addEvent(this.scrollbar, 'mouseout', this.contOut.bind(this)); addEvent(this.scrollbar, 'mousedown', this.contDown.bind(this)); if (browser.safari_mobile) { addEvent(obj, 'touchstart', function(event) { cur.touchY = event.touches[0].pageY; //return cancelEvent(event); }); addEvent(obj, 'touchmove', function(event) { var touchY = event.touches[0].pageY; cur.touchDiff = cur.touchY - touchY; obj.scrollTop += cur.touchDiff; cur.touchY = touchY; if (obj.scrollTop > 0 && self.shown !== false) { self.update(true); return cancelEvent(event); } }); addEvent(obj, 'touchend', function() { cur.animateInt = setInterval(function() { cur.touchDiff = cur.touchDiff * 0.9; if (cur.touchDiff < 1 && cur.touchDiff > -1) { clearInterval(cur.animateInt); } else { obj.scrollTop += cur.touchDiff; self.update(true); } }, 0); }) } addEvent(this.inner, 'mousedown', down); addEvent(w, 'keydown', keydown); if (this.contHeight() <= this.scrollHeight) { hide(this.bottomShadowDiv); } else { this.bottomShadow = true; } this.inited = true; this.update(true); }).bind(this), 0); } Scrollbar.prototype.contOver = function() { this.isOut = false; addClass(this.scrollbar, 'scrollbar_c_overed'); } Scrollbar.prototype.contOut = function() { this.isOut = true; if (this.isDown) return; removeClass(this.scrollbar, 'scrollbar_c_overed'); } Scrollbar.prototype.contDown = function(ev) { var y = ev.offsetY - this.innerHeight / 2 + 5;// - this.innerHeight; var scrH = this.scrollHeight - this.innerHeight; var newScroll = Math.floor((this.contHeight() - this.scrollHeight) * Math.min(1, y / scrH)); this.obj.scrollTop = newScroll; this.update(true); this.mouseDown(ev); } w.Scrollbar.prototype._mouseMove = function(event) { this.obj.scrollTop = Math.floor((this.contHeight() - this.scrollHeight) * Math.min(1, (event.screenY - this.moveY) / (this.scrollHeight - 26))); this.update(true); return false; } w.Scrollbar.prototype._mouseUp = function(event) { this.moveY = false; this.isDown = false; if (this.isOut) { this.contOut(); } removeEvent(w.document, 'mousemove', this.mouseMove); removeEvent(w.document, 'mouseup', this.mouseUp); w.document.body.style.cursor = 'default'; removeClass(this.inner, 'scrollbar_hovered'); if (this.options.stopDrag) { this.options.stopDrag(); } return false; } w.Scrollbar.prototype.wheel = function(event) { if (!event) event = window.event; var delta = 0; if (event.wheelDeltaY || event.wheelDelta) { delta = (event.wheelDeltaY || event.wheelDelta) / 2; } else if (event.detail) { delta = -event.detail * 10 } var stWas = this.obj.scrollTop; this.obj.scrollTop -= delta; if (stWas != this.obj.scrollTop && this.shown !== false) { this.update(true); return false; } } w.Scrollbar.prototype.contHeight = function() { if (this.contHashCash) { return this.contHashCash; } var nodes = this.obj.childNodes; var height = 0; var i = nodes.length; while (i--) { height += nodes[i].offsetHeight || 0; } this.contHashCash = height; return height; } w.Scrollbar.prototype.update = function(noChange, updateScroll) { if (!this.inited) { return; } if (!noChange) { this.contHashCash = false; if (this.moveY) { return true; } } if (updateScroll) { var size = getSize(this.obj); this.scrollHeight = size[1]; } var height = this.contHeight(); if (height <= this.scrollHeight) { hide(this.inner); this.shown = false; return; } else if (!this.shown) { show(this.inner); this.shown = true; } var progress = Math.min(1, this.obj.scrollTop / (height - this.scrollHeight)); if (progress > 0 != this.topShadow && this.topShadowDiv) { (this.topShadow ? hide : show)(this.topShadowDiv); this.topShadow = !this.topShadow; } if (progress < 1 != this.bottomShadow && this.bottomShadowDiv) { (this.bottomShadow ? hide : show)(this.bottomShadowDiv); this.bottomShadow = !this.bottomShadow; } this.innerHeight = Math.max(40, Math.floor(this.scrollHeight * this.scrollHeight / height)); this.inner.style.height = this.innerHeight + 'px'; if (height - this.obj.scrollTop < this.scrollHeight * 2) { this.options.more(); } this.inner.style.marginTop = Math.floor((this.scrollHeight - this.innerHeight - 4) * progress + 2) + 'px'; // console.log(this.scrollHeight, height, progress); } })(window); // Tiny Scrollbars end /* Inline video from common.js */ window._videoLastInlined = false; function showInlineVideo(videoId, listId, options, ev, thumb) { if (checkEvent(ev)) return true; if (window.mvcur && mvcur.mvShown) { return showVideo(videoId, listId, options, ev); } options = options || {}; options.params = options.params || {act: 'show_inline', video: videoId, list: listId, autoplay: (options.autoplay) ? 1 : 0}; var h = thumb.clientHeight, w = thumb.clientWidth, btn = geByClass1('video_play_inline', thumb, 'div'); extend(options.params, {width: w, height: h}); options.onDone = function (title, html, js, opts) { revertLastInlineVideo(); hide(thumb); var videoWrap = ce('div', {id: 'page_video_inline_wrap' + videoId, className: 'page_video_inline_wrap', innerHTML: html}, {width: w, height: h}), videoBg = ge('video_background' + videoId); _videoLastInlined = [videoWrap, thumb] thumb.parentNode.appendChild(videoWrap); videoBg && setStyle(geByTag1('img', videoBg), {width: w, height: h}); try { eval('(function () {' + js + '})();'); } catch (e) { debugLog('video inline error', e.message, e.stack, e, js); } var _n = window.Notifier, _a = window.audioPlayer; if (_n) setTimeout(function() { _n.lcSend('video_start'); }, 0); if (_a && _a.player && !_a.player.paused()) { _a.pauseTrack(); _a.pausedByVideo = 1; } }; options.showProgress = function () { addClass(btn, 'video_play_inline_loading'); }; options.hideProgress = function () { removeClass(btn, 'video_play_inline_loading'); }; ajax.post('al_video.php', options.params, options); return false; } function revertLastInlineVideo() { if (!window._videoLastInlined) { return; } re(_videoLastInlined[0]); show(_videoLastInlined[1]); _videoLastInlined = false; }
JavaScript
(function(w) { if (w.fastXDM) return; var handlers = {}; var onEnvLoad = []; var env = {}; // Key generation function genKey() { var key = ''; for (i=0;i<5;i++) key += Math.ceil(Math.random()*15).toString(16); return key; } function waitFor(obj, prop, func, self, count) { if (obj[prop]) { func.apply(self); } else { count = count || 0; if (count < 1000) setTimeout(function() { waitFor(obj, prop, func, self, count + 1) }, 0); } } function attachScript(url) { setTimeout(function() { var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = url || w.fastXDM.helperUrl; waitFor(document, 'body', function() { document.getElementsByTagName('HEAD')[0].appendChild(newScript); }); }, 0); } function walkVar(value, clean) { switch (typeof value) { case 'string': if (clean) { return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;'); } return value.replace(/&#039;/g, '\'').replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&'); case 'object': if (Object.prototype.toString.apply(value) === '[object Array]') { newValue = []; for (var i = 0; i < value.length; i++) { newValue[i] = walkVar(value[i], clean); } } else { for (var k in value) { newValue = {}; if (Object.hasOwnProperty.call(value, k)) { newValue[k] = walkVar(value[k], clean); } } } default: newValue = value; } return newValue; } // Env functions function getEnv(callback, self) { if (env.loaded) { callback.apply(self, [env]); } else { onEnvLoad.push([self, callback]); } } function envLoaded() { env.loaded = true; var i = onEnvLoad.length; while (i--) { onEnvLoad[i][1].apply(onEnvLoad[i][0], [env]); } } function applyMethod(strData, self) { getEnv(function(env) { var data = env.json.parse(strData); if (data[0]) { if (!data[1]) data[1] = []; var i = data[1].length; while (i--) { if (data[1][i]._func) { var funcNum = data[1][i]._func; data[1][i] = function() { var args = Array.prototype.slice.call(arguments); args.unshift('_func'+funcNum); self.callMethod.apply(self, args); } } else if (self.options.safe) { data[1][i] = walkVar(data[1][i], true); } } setTimeout(function() { if (!self.methods[data[0]]) throw Error('fastXDM: Method ' + data[0] + ' is undefined'); self.methods[data[0]].apply(self, data[1]); }, 0); } }); } // XDM object w.fastXDM = { _id: 0, helperUrl: ((location.protocol === 'https:') ? 'https:' : 'http:') + '//vk.com/js/api/xdmHelper.js', Server: function(methods, filter, options) { this.methods = methods || {}; this.id = w.fastXDM._id++; this.options = options || {}; this.filter = filter; this.key = genKey(); this.methods['%init%'] = this.methods.__fxdm_i = function() { w.fastXDM.run(this.id); if (this.methods.onInit) this.methods.onInit(); }; this.frameName = 'fXD'+this.key; this.server = true; handlers[this.key] = [applyMethod, this]; }, Client: function(methods, options) { this.methods = methods || {}; this.id = w.fastXDM._id++; this.options = options || {}; w.fastXDM.run(this.id); if (window.name.indexOf('fXD') == 0) { this.key = window.name.substr(3); } else { throw Error('Wrong window.name property.'); } this.caller = window.parent; handlers[this.key] = [applyMethod, this]; this.client = true; w.fastXDM.on('helper', function() { w.fastXDM.onClientStart(this); }, this); getEnv(function(env) { env.send(this, env.json.stringify(['%init%'])); var methods = this.methods; setTimeout(function() { if (methods.onInit) methods.onInit(); }, 0); }, this); }, onMessage: function(e) { if (!e.data) return false; var key = e.data.substr(0, 5); if (handlers[key]) { var self = handlers[key][1]; if (self && (!self.filter || self.filter(e.origin))) { handlers[key][0](e.data.substr(6), self); } } }, setJSON: function(json) { env.json = json; }, getJSON: function(callback) { if (!callback) return env.json; getEnv(function(env) { callback(env.json); }); }, setEnv: function(exEnv) { for (i in exEnv) { env[i] = exEnv[i]; } envLoaded(); }, _q: {}, on: function(key, act, self) { if (!this._q[key]) this._q[key] = []; if (this._q[key] == -1) { act.apply(self); } else { this._q[key].push([act, self]); } }, run: function(key) { var len = (this._q[key] || []).length; if (this._q[key] && len > 0) { for (var i = 0; i < len; i++) this._q[key][i][0].apply(this._q[key][i][1]); } this._q[key] = -1; }, waitFor: waitFor } w.fastXDM.Server.prototype.start = function(obj, count) { if (obj.contentWindow) { this.caller = obj.contentWindow; this.frame = obj; w.fastXDM.on('helper', function() { w.fastXDM.onServerStart(this); }, this); } else { // Opera old versions var self = this; count = count || 0; if (count < 50) setTimeout(function() { self.start.apply(self, [obj, count+1]); }, 100); } } w.fastXDM.Server.prototype.destroy = function() { handlers.splice(handlers.indexOf(this.key), 1); } function extend(obj1, obj2){ for (var i in obj2) { if (obj1[i] && typeof(obj1[i]) == 'object') { extend(obj1[i], obj2[i]) } else { obj1[i] = obj2[i]; } } } w.fastXDM.Server.prototype.append = function(obj, options) { var div = document.createElement('DIV'); div.innerHTML = '<iframe name="'+this.frameName+'" ></iframe>'; var frame = div.firstChild; var self = this; setTimeout(function() { frame.frameBorder = '0'; if (options) extend(frame, options); obj.insertBefore(frame, obj.firstChild); self.start(frame); }, 0); return frame; } w.fastXDM.Client.prototype.callMethod = w.fastXDM.Server.prototype.callMethod = function() { var args = Array.prototype.slice.call(arguments); var method = args.shift(); var i = args.length; while (i--) { if (typeof(args[i]) == 'function') { this.funcsCount = (this.funcsCount || 0) + 1; var func = args[i]; var funcName = '_func' + this.funcsCount; this.methods[funcName] = function() { func.apply(this, arguments); delete this.methods[funcName]; } args[i] = {_func: this.funcsCount}; } else if (this.options.safe) { args[i] = walkVar(args[i], false); } } waitFor(this, 'caller', function() { w.fastXDM.on(this.id, function() { getEnv(function(env) { env.send(this, env.json.stringify([method, args])); }, this); }, this); }, this); } if (w.JSON && typeof(w.JSON) == 'object' && w.JSON.parse && w.JSON.stringify && w.JSON.stringify({a:[1,2,3]}).replace(/ /g, '') == '{"a":[1,2,3]}') { env.json = {parse: w.JSON.parse, stringify: w.JSON.stringify}; } else { w.fastXDM._needJSON = true; } // PostMessage cover if (w.postMessage) { env.protocol = 'p'; env.send = function(xdm, strData) { xdm.caller.postMessage(xdm.key+':'+strData, "*"); } if (w.addEventListener) { w.addEventListener("message", w.fastXDM.onMessage, false); } else { w.attachEvent("onmessage", w.fastXDM.onMessage); } if (w.fastXDM._needJSON) { w.fastXDM._onlyJSON = true; attachScript(); } else { envLoaded(); } } else { attachScript(); } })(window);
JavaScript
(function(w) { if (w.fastXDM) return; var handlers = {}; var onEnvLoad = []; var env = {}; // Key generation function genKey() { var key = ''; for (i=0;i<5;i++) key += Math.ceil(Math.random()*15).toString(16); return key; } function waitFor(obj, prop, func, self, count) { if (obj[prop]) { func.apply(self); } else { count = count || 0; if (count < 1000) setTimeout(function() { waitFor(obj, prop, func, self, count + 1) }, 0); } } function attachScript(url) { setTimeout(function() { var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = url || w.fastXDM.helperUrl; waitFor(document, 'body', function() { document.getElementsByTagName('HEAD')[0].appendChild(newScript); }); }, 0); } function walkVar(value, clean) { switch (typeof value) { case 'string': if (clean) { return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;'); } return value.replace(/&#039;/g, '\'').replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&'); case 'object': if (Object.prototype.toString.apply(value) === '[object Array]') { newValue = []; for (var i = 0; i < value.length; i++) { newValue[i] = walkVar(value[i], clean); } } else { for (var k in value) { newValue = {}; if (Object.hasOwnProperty.call(value, k)) { newValue[k] = walkVar(value[k], clean); } } } default: newValue = value; } return newValue; } // Env functions function getEnv(callback, self) { if (env.loaded) { callback.apply(self, [env]); } else { onEnvLoad.push([self, callback]); } } function envLoaded() { env.loaded = true; var i = onEnvLoad.length; while (i--) { onEnvLoad[i][1].apply(onEnvLoad[i][0], [env]); } } function applyMethod(strData, self) { getEnv(function(env) { var data = env.json.parse(strData); if (data[0]) { if (!data[1]) data[1] = []; var i = data[1].length; while (i--) { if (data[1][i]._func) { var funcNum = data[1][i]._func; data[1][i] = function() { var args = Array.prototype.slice.call(arguments); args.unshift('_func'+funcNum); self.callMethod.apply(self, args); } } else if (self.options.safe) { data[1][i] = walkVar(data[1][i], true); } } setTimeout(function() { if (!self.methods[data[0]]) { throw Error('fastXDM: Method ' + data[0] + ' is undefined'); } self.methods[data[0]].apply(self, data[1]); }, 0); } }); } // XDM object w.fastXDM = { _id: 0, helperUrl: ((location.protocol === 'https:') ? 'https:' : 'http:') + '//vk.com/js/api/xdmHelper.js', Server: function(methods, filter, options) { this.methods = methods || {}; this.id = w.fastXDM._id++; this.options = options || {}; this.filter = filter; this.key = genKey(); this.methods['%init%'] = this.methods.__fxdm_i = function() { w.fastXDM.run(this.id); if (this.methods.onInit) this.methods.onInit(); }; this.frameName = 'fXD'+this.key; this.server = true; handlers[this.key] = [applyMethod, this]; }, Client: function(methods, options) { this.methods = methods || {}; this.id = w.fastXDM._id++; this.options = options || {}; w.fastXDM.run(this.id); if (window.name.indexOf('fXD') === 0) { this.key = window.name.substr(3); } else { throw Error('Wrong window.name property.'); } this.caller = window.parent; handlers[this.key] = [applyMethod, this]; this.client = true; w.fastXDM.on('helper', function() { w.fastXDM.onClientStart(this); }, this); getEnv(function(env) { env.send(this, env.json.stringify(['%init%'])); var methods = this.methods; setTimeout(function() { if (methods.onInit) methods.onInit(); }, 0); }, this); }, onMessage: function(e) { if (!e.data) return false; var data = e.data; if (typeof data != 'string' && !(data instanceof String)) return false; var key = data.substr(0, 5); if (handlers[key]) { var self = handlers[key][1]; if (self && (!self.filter || self.filter(e.origin))) { handlers[key][0](e.data.substr(6), self); } } }, setJSON: function(json) { env.json = json; }, getJSON: function(callback) { if (!callback) return env.json; getEnv(function(env) { callback(env.json); }); }, setEnv: function(exEnv) { var i; for (i in exEnv) { env[i] = exEnv[i]; } envLoaded(); }, _q: {}, on: function(key, act, self) { if (!this._q[key]) this._q[key] = []; if (this._q[key] == -1) { act.apply(self); } else { this._q[key].push([act, self]); } }, run: function(key) { var len = (this._q[key] || []).length; if (this._q[key] && len > 0) { for (var i = 0; i < len; i++) this._q[key][i][0].apply(this._q[key][i][1]); } this._q[key] = -1; }, waitFor: waitFor } w.fastXDM.Server.prototype.start = function(obj, count) { if (obj.contentWindow) { this.caller = obj.contentWindow; this.frame = obj; w.fastXDM.on('helper', function() { w.fastXDM.onServerStart(this); }, this); } else { // Opera old versions var self = this; count = count || 0; if (count < 50) setTimeout(function() { self.start.apply(self, [obj, count+1]); }, 100); } } w.fastXDM.Server.prototype.destroy = function() { handlers.splice(handlers.indexOf(this.key), 1); } function extend(obj1, obj2){ for (var i in obj2) { if (obj1[i] && typeof(obj1[i]) == 'object') { extend(obj1[i], obj2[i]) } else { obj1[i] = obj2[i]; } } } w.fastXDM.Server.prototype.append = function(obj, options) { var div = document.createElement('DIV'); div.innerHTML = '<iframe name="'+this.frameName+'" ></iframe>'; var frame = div.firstChild; var self = this; setTimeout(function() { frame.frameBorder = '0'; if (options) extend(frame, options); obj.insertBefore(frame, obj.firstChild); self.start(frame); }, 0); return frame; } w.fastXDM.Client.prototype.callMethod = w.fastXDM.Server.prototype.callMethod = function() { var args = Array.prototype.slice.call(arguments); var method = args.shift(); var i = args.length; while (i--) { if (typeof(args[i]) == 'function') { this.funcsCount = (this.funcsCount || 0) + 1; var func = args[i]; var funcName = '_func' + this.funcsCount; this.methods[funcName] = function() { func.apply(this, arguments); delete this.methods[funcName]; } args[i] = {_func: this.funcsCount}; } else if (this.options.safe) { args[i] = walkVar(args[i], false); } } waitFor(this, 'caller', function() { w.fastXDM.on(this.id, function() { getEnv(function(env) { env.send(this, env.json.stringify([method, args])); }, this); }, this); }, this); } if (w.JSON && typeof(w.JSON) == 'object' && w.JSON.parse && w.JSON.stringify && w.JSON.stringify({a:[1,2,3]}).replace(/ /g, '') == '{"a":[1,2,3]}') { env.json = {parse: w.JSON.parse, stringify: w.JSON.stringify}; } else { w.fastXDM._needJSON = true; } // PostMessage cover if (w.postMessage) { env.protocol = 'p'; env.send = function(xdm, strData) { var win = (xdm.frame ? xdm.frame.contentWindow : xdm.caller); win.postMessage(xdm.key+':'+strData, "*"); } if (w.addEventListener) { w.addEventListener("message", w.fastXDM.onMessage, false); } else { w.attachEvent("onmessage", w.fastXDM.onMessage); } if (w.fastXDM._needJSON) { w.fastXDM._onlyJSON = true; attachScript(); } else { envLoaded(); } } else { attachScript(); } })(window); if (!window.VK) window.VK = {}; /* * Based on JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License */ if(!VK.MD5){VK.MD5=function(n){var j=function(o,r){var q=(o&65535)+(r&65535),p=(o>>16)+(r>>16)+(q>>16);return(p<<16)|(q&65535)},g=function(o,p){return(o<<p)|(o>>>(32-p))},k=function(w,r,p,o,v,u){return j(g(j(j(r,w),j(o,u)),v),p)},a=function(q,p,w,v,o,u,r){return k((p&w)|((~p)&v),q,p,o,u,r)},h=function(q,p,w,v,o,u,r){return k((p&v)|(w&(~v)),q,p,o,u,r)},c=function(q,p,w,v,o,u,r){return k(p^w^v,q,p,o,u,r)},m=function(q,p,w,v,o,u,r){return k(w^(p|(~v)),q,p,o,u,r)},b=function(A,u){var z=1732584193,y=-271733879,w=-1732584194,v=271733878,r,q,p,o;A[u>>5]|=128<<((u)%32);A[(((u+64)>>>9)<<4)+14]=u;for(var t=0,s=A.length;t<s;t+=16){r=z;q=y;p=w;o=v;z=a(z,y,w,v,A[t+0],7,-680876936);v=a(v,z,y,w,A[t+1],12,-389564586);w=a(w,v,z,y,A[t+2],17,606105819);y=a(y,w,v,z,A[t+3],22,-1044525330);z=a(z,y,w,v,A[t+4],7,-176418897);v=a(v,z,y,w,A[t+5],12,1200080426);w=a(w,v,z,y,A[t+6],17,-1473231341);y=a(y,w,v,z,A[t+7],22,-45705983);z=a(z,y,w,v,A[t+8],7,1770035416);v=a(v,z,y,w,A[t+9],12,-1958414417);w=a(w,v,z,y,A[t+10],17,-42063);y=a(y,w,v,z,A[t+11],22,-1990404162);z=a(z,y,w,v,A[t+12],7,1804603682);v=a(v,z,y,w,A[t+13],12,-40341101);w=a(w,v,z,y,A[t+14],17,-1502002290);y=a(y,w,v,z,A[t+15],22,1236535329);z=h(z,y,w,v,A[t+1],5,-165796510);v=h(v,z,y,w,A[t+6],9,-1069501632);w=h(w,v,z,y,A[t+11],14,643717713);y=h(y,w,v,z,A[t+0],20,-373897302);z=h(z,y,w,v,A[t+5],5,-701558691);v=h(v,z,y,w,A[t+10],9,38016083);w=h(w,v,z,y,A[t+15],14,-660478335);y=h(y,w,v,z,A[t+4],20,-405537848);z=h(z,y,w,v,A[t+9],5,568446438);v=h(v,z,y,w,A[t+14],9,-1019803690);w=h(w,v,z,y,A[t+3],14,-187363961);y=h(y,w,v,z,A[t+8],20,1163531501);z=h(z,y,w,v,A[t+13],5,-1444681467);v=h(v,z,y,w,A[t+2],9,-51403784);w=h(w,v,z,y,A[t+7],14,1735328473);y=h(y,w,v,z,A[t+12],20,-1926607734);z=c(z,y,w,v,A[t+5],4,-378558);v=c(v,z,y,w,A[t+8],11,-2022574463);w=c(w,v,z,y,A[t+11],16,1839030562);y=c(y,w,v,z,A[t+14],23,-35309556);z=c(z,y,w,v,A[t+1],4,-1530992060);v=c(v,z,y,w,A[t+4],11,1272893353);w=c(w,v,z,y,A[t+7],16,-155497632);y=c(y,w,v,z,A[t+10],23,-1094730640);z=c(z,y,w,v,A[t+13],4,681279174);v=c(v,z,y,w,A[t+0],11,-358537222);w=c(w,v,z,y,A[t+3],16,-722521979);y=c(y,w,v,z,A[t+6],23,76029189);z=c(z,y,w,v,A[t+9],4,-640364487);v=c(v,z,y,w,A[t+12],11,-421815835);w=c(w,v,z,y,A[t+15],16,530742520);y=c(y,w,v,z,A[t+2],23,-995338651);z=m(z,y,w,v,A[t+0],6,-198630844);v=m(v,z,y,w,A[t+7],10,1126891415);w=m(w,v,z,y,A[t+14],15,-1416354905);y=m(y,w,v,z,A[t+5],21,-57434055);z=m(z,y,w,v,A[t+12],6,1700485571);v=m(v,z,y,w,A[t+3],10,-1894986606);w=m(w,v,z,y,A[t+10],15,-1051523);y=m(y,w,v,z,A[t+1],21,-2054922799);z=m(z,y,w,v,A[t+8],6,1873313359);v=m(v,z,y,w,A[t+15],10,-30611744);w=m(w,v,z,y,A[t+6],15,-1560198380);y=m(y,w,v,z,A[t+13],21,1309151649);z=m(z,y,w,v,A[t+4],6,-145523070);v=m(v,z,y,w,A[t+11],10,-1120210379);w=m(w,v,z,y,A[t+2],15,718787259);y=m(y,w,v,z,A[t+9],21,-343485551);z=j(z,r);y=j(y,q);w=j(w,p);v=j(v,o)}return[z,y,w,v]},f=function(r){var q="",s=-1,p=r.length,o,t;while(++s<p){o=r.charCodeAt(s);t=s+1<p?r.charCodeAt(s+1):0;if(55296<=o&&o<=56319&&56320<=t&&t<=57343){o=65536+((o&1023)<<10)+(t&1023);s++}if(o<=127){q+=String.fromCharCode(o)}else{if(o<=2047){q+=String.fromCharCode(192|((o>>>6)&31),128|(o&63))}else{if(o<=65535){q+=String.fromCharCode(224|((o>>>12)&15),128|((o>>>6)&63),128|(o&63))}else{if(o<=2097151){q+=String.fromCharCode(240|((o>>>18)&7),128|((o>>>12)&63),128|((o>>>6)&63),128|(o&63))}}}}}return q},e=function(p){var o=Array(p.length>>2),r,q;for(r=0,q=o.length;r<q;r++){o[r]=0}for(r=0,q=p.length*8;r<q;r+=8){o[r>>5]|=(p.charCodeAt(r/8)&255)<<(r%32)}return o},l=function(p){var o="";for(var r=0,q=p.length*32;r<q;r+=8){o+=String.fromCharCode((p[r>>5]>>>(r%32))&255)}return o},d=function(o){return l(b(e(o),o.length*8))},i=function(q){var t="0123456789abcdef",p="",o;for(var s=0,r=q.length;s<r;s++){o=q.charCodeAt(s);p+=t.charAt((o>>>4)&15)+t.charAt(o&15)}return p};return i(d(f(n)))}} /* * VKontakte Open API JavaScript library * http://vk.com/ */ VK.extend = function(target, source, overwrite) { for (var key in source) { if (overwrite || typeof target[key] === 'undefined') { target[key] = source[key]; } } return target; }; if (VK._protocol !== 'https:') { VK._protocol = ((location.protocol === 'https:') ? 'https:' : 'http:'); } if (!VK.xdConnectionCallbacks) { VK.extend(VK, { version: 1, _apiId: null, _session: null, _userStatus: 'unknown', _domain: { main: 'https://oauth.vk.com/', api: 'https://api.vk.com/' }, _path: { login: 'authorize', proxy: 'fxdm_oauth_proxy.html' }, _rootId: 'vk_api_transport', _nameTransportPath: '', xdReady: false, access: { FRIENDS: 0x2, PHOTOS: 0x4, AUDIO: 0x8, VIDEO: 0x10, MATCHES: 0x20, QUESTIONS: 0x40, WIKI: 0x80 } }); VK.init = function(options) { var body, root; VK._apiId = null; if (!options.apiId) { throw Error('VK.init() called without an apiId'); } VK._apiId = options.apiId; if (options.onlyWidgets) return true; if (options.nameTransportPath && options.nameTransportPath !== '') { VK._nameTransportPath = options.nameTransportPath; } root = document.getElementById(VK._rootId); if (!root) { root = document.createElement('div'); root.id = VK._rootId; body = document.getElementsByTagName('body')[0]; body.insertBefore(root, body.childNodes[0]); } root.style.position = 'absolute'; root.style.top = '-10000px'; var session = VK.Cookie.load(); if (session) { VK.Auth._loadState = 'loaded'; VK.Auth.setSession(session, session ? 'connected' : 'unknown'); } }; if (!VK.Cookie) { VK.Cookie = { _domain: null, load: function() { var cookie = document.cookie.match('\\bvk_app_' + VK._apiId + '=([^;]*)\\b'), session; if (cookie) { session = this.decode(cookie[1]); if (session.secret != 'oauth') { return false; } session.expire = parseInt(session.expire, 10); VK.Cookie._domain = '.' + window.location.hostname;//session.base_domain; } return session; }, setRaw: function(val, ts, domain, time) { var rawCookie; rawCookie = 'vk_app_' + VK._apiId + '=' + val + ''; var exp = time ? (new Date().getTime() + time * 1000) : ts * 1000; rawCookie += (val && ts === 0 ? '' : '; expires=' + new Date(exp).toGMTString()); rawCookie += '; path=/'; rawCookie += (domain ? '; domain=.' + domain : ''); document.cookie = rawCookie; this._domain = domain; }, set: function(session, resp) { if (session) { this.setRaw(this.encode(session), session.expire, window.location.hostname, (resp || {}).time); } else { this.clear(); } }, clear: function() { this.setRaw('', 0, this._domain, 0); }, encode: function(params) { var pairs = [], key; for (key in params) { if (key != 'user') pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key])); } pairs.sort(); return pairs.join('&'); }, decode: function(str) { var params = {}, parts = str.split('&'), i, pair; for (i=0; i < parts.length; i++) { pair = parts[i].split('=', 2); if (pair && pair[0]) { params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } } return params; } }; } if (!VK.Api) { VK.Api = { _headId: null, _callbacks: {}, ie6_7: function() { if (!VK.Api.ieTested) { VK.Api.isIE6_7 = navigator.userAgent.match(/MSIE [6|7]/i); VK.Api.ieTested = true; } return VK.Api.isIE6_7; }, attachScript: function(url) { if (!VK.Api._headId) VK.Api._headId = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.setAttribute('encoding', 'UTF-8'); newScript.src = url; VK.Api._headId.appendChild(newScript); }, checkMethod: function(method, params, cb, queryTry) { var m = method.toLowerCase(); if (m == 'wall.post' || m == 'activity.set') { var text = (m == 'activity.set') ? params.text : params.message; if (!text) { text = ''; } var query = VK._protocol + '//vk.com/al_apps.php?act=wall_post_box&widget=1&method='+m+'&aid=' + parseInt(VK._apiId, 10) + '&text=' + encodeURIComponent(text); if (m == 'wall.post') { query += '&owner_id=' + parseInt(params.owner_id || 0, 10) + '&attachments=' + (params.attachments || params.attachment || '') + '&publish_date=' + (params.publish_date || ''); } var method_access = '_'+(Math.random()).toString(16).substr(2); query += '&method_access='+method_access; var popup = VK.UI.popup({ url: query, width: 460, height: 249 }); var timer = setInterval(function() { if (VK.UI.active.closed) { clearInterval(timer); params.method_access = method_access; VK.Api.call(method, params, cb, queryTry); } }, 500); return false; } return true; }, call: function(method, params, cb, queryTry) { var query = params || {}, qs, responseCb; if (typeof query != 'object' || typeof cb != 'function') { return false; } if (!params.method_access && !params.method_force && !VK.Api.checkMethod(method, params, cb, queryTry)) { return; } if (!queryTry) queryTry = 0; if (VK.Auth._loadState != 'loaded') { var authFunc = function(result) { if (result && result.session) { VK.Observer.unsubscribe('auth.loginStatus', authFunc); VK.Api.call(method, params, cb); } }; VK.Observer.subscribe('auth.loginStatus', authFunc); VK.Auth.getLoginStatus(); return; } if (VK.Api.queryLength(query) < 1500 && !VK.Api.ie6_7()) { var useXDM = false; var rnd = parseInt(Math.random() * 10000000, 10); while (VK.Api._callbacks[rnd]) { rnd = parseInt(Math.random() * 10000000, 10) } query.callback = 'VK.Api._callbacks['+rnd+']'; } else { var useXDM = true; } if (VK._session && VK._session.sid) { query.access_token = VK._session.sid; } qs = VK.Cookie.encode(query); responseCb = function(response) { if (response.error && (response.error.error_code == 3 || response.error.error_code == 4 || response.error.error_code == 5)) { if (queryTry > 3) return false; var repeatCall = function(resp) { VK.Observer.unsubscribe('auth.sessionChange', repeatCall); delete params.access_token; if (resp.session) VK.Api.call(method, params, cb, queryTry + 1); } VK.Observer.subscribe('auth.sessionChange', repeatCall); VK.Auth.getLoginStatus(); } else { cb(response); } if (!useXDM) delete VK.Api._callbacks[rnd]; }; if (useXDM) { if (VK.xdReady) { VK.XDM.remote.callMethod('apiCall', method, qs, responseCb); } else { VK.Observer.subscribe('xdm.init', function() { VK.XDM.remote.callMethod('apiCall', method, qs, responseCb); }); VK.XDM.init(); } } else { VK.Api._callbacks[rnd] = responseCb; VK.Api.attachScript(VK._domain.api + 'method/' + method +'?' + qs); } }, queryLength: function(query) { var len = 100, i; // sid + sig for (i in query) { len += i.length + encodeURIComponent(query[i]).length + 1; } return len; } }; // Alias VK.api = function(method, params, cb) {VK.Api.call(method, params, cb);} }; if (!VK.Auth) { VK.Auth = { popup: null, lsCb: {}, setSession: function(session, status, settings, resp) { var login = !VK._session && session, logout = VK._session && !session, both = VK._session && session && VK._session.mid != session.mid, sessionChange = login || logout || (VK._session && session && VK._session.sid != session.sid), statusChange = status != VK._userStatus, response = { 'session': session, 'status': status, 'settings': settings }; VK._session = session; VK._userStatus = status; VK.Cookie.set(session, resp); if (sessionChange || statusChange || both) { setTimeout(function() { if (statusChange) { VK.Observer.publish('auth.statusChange', response); } if (logout || both) { VK.Observer.publish('auth.logout', response); } if (login || both) { VK.Observer.publish('auth.login', response); } if (sessionChange) { VK.Observer.publish('auth.sessionChange', response); } }, 0); } return response; }, // Public VK.Auth methods login: function(cb, settings) { var channel, url; if (!VK._apiId) { return false; } channel = window.location.protocol + '//' + window.location.hostname; url = VK._domain.main + VK._path.login + '?client_id='+VK._apiId+'&display=popup&redirect_uri=close.html&response_type=token'; if (settings && parseInt(settings, 10) > 0) { url += '&scope=' + settings; } VK.Observer.unsubscribe('auth.onLogin'); VK.Observer.subscribe('auth.onLogin', cb); VK.UI.popup({ width: 665, height: 370, url: url }); var authCallback = function() { VK.Auth.getLoginStatus(function(resp) { VK.Observer.publish('auth.onLogin', resp); VK.Observer.unsubscribe('auth.onLogin'); }, true); } VK.UI.popupOpened = true; var popupCheck = function() { if (!VK.UI.popupOpened) return false; try { if (!VK.UI.active.top || VK.UI.active.closed) { VK.UI.popupOpened = false; authCallback(); return true; } } catch(e) { VK.UI.popupOpened = false; authCallback(); return true; } setTimeout(popupCheck, 100); }; setTimeout(popupCheck, 100); }, // Logout user from app, vk.com & login.vk.com logout: function(cb) { VK.Auth.revokeGrants(cb); }, revokeGrants: function(cb) { var onLogout = function(resp) { VK.Observer.unsubscribe('auth.statusChange', onLogout); if (cb) cb(resp); } VK.Observer.subscribe('auth.statusChange', onLogout); if (VK._session && VK._session.sid) VK.Api.attachScript('https://login.vk.com/?act=openapi&oauth=1&aid=' + parseInt(VK._apiId, 10) + '&location=' + encodeURIComponent(window.location.hostname)+'&do_logout=1&token='+VK._session.sid); VK.Cookie.clear(); }, // Get current login status from session (sync) (not use on load time) getSession: function() { return VK._session; }, // Get current login status from vk.com (async) getLoginStatus: function(cb, force) { if (!VK._apiId) { return; } if (cb) { if (!force && VK.Auth._loadState == 'loaded') { cb({status: VK._userStatus, session: VK._session}); return; } else { VK.Observer.subscribe('auth.loginStatus', cb); } } if (!force && VK.Auth._loadState == 'loading') { return; } VK.Auth._loadState = 'loading'; var rnd = parseInt(Math.random() * 10000000, 10); while (VK.Auth.lsCb[rnd]) { rnd = parseInt(Math.random() * 10000000, 10) } VK.Auth.lsCb[rnd] = function(response) { delete VK.Auth.lsCb[rnd]; VK.Auth._loadState = 'loaded'; if (response && response.auth) { var session = { mid: response.user.id, sid: response.access_token, sig: response.sig, secret: response.secret, expire: response.expire }; if (force) session.user = response.user; var status = 'connected'; } else { var session = null; var status = response.user ? 'logined' : 'unknown'; VK.Cookie.clear(); } VK.Auth.setSession(session, status, false, response); VK.Observer.publish('auth.loginStatus', {session: session, status: status}); VK.Observer.unsubscribe('auth.loginStatus'); }; // AttachScript here VK.Api.attachScript('https://login.vk.com/?act=openapi&oauth=1&aid=' + parseInt(VK._apiId, 10) + '&location=' + encodeURIComponent(window.location.hostname)+'&rnd='+rnd); } }; } } else { // if VK.xdConnectionCallbacks setTimeout(function() { var callback; while (callback = VK.xdConnectionCallbacks.pop()) { callback(); } }, 0); if (VK.Widgets && !VK.Widgets._constructor) { VK.Widgets = false; } } if (!VK.UI) { VK.UI = { active: null, _buttons: [], popup: function(options) { var screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft, screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop, outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth, outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22), width = options.width, height = options.height, left = parseInt(screenX + ((outerWidth - width) / 2), 10), top = parseInt(screenY + ((outerHeight - height) / 2.5), 10), features = ( 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top ); this.active = window.open(options.url, 'vk_openapi', features); }, button: function(el, handler) { var html = ''; if (typeof el == 'string') { el = document.getElementById(el); } this._buttons.push(el); index = this._buttons.length - 1; html = ( '<table cellspacing="0" cellpadding="0" id="openapi_UI_' + index + '" onmouseover="VK.UI._change(1, ' + index + ');" onmouseout="VK.UI._change(0, ' + index + ');" onmousedown="VK.UI._change(2, ' + index + ');" onmouseup="VK.UI._change(1, ' + index + ');" style="cursor: pointer; border: 0px; font-family: tahoma, arial, verdana, sans-serif, Lucida Sans; font-size: 10px;"><tr style="vertical-align: middle">' + '<td><div style="border: 1px solid #3b6798;border-radius: 2px 0px 0px 2px;-moz-border-radius: 2px 0px 0px 2px;-webkit-border-radius: 2px 0px 0px 2px;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6D8DB1; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px;line-height: 13px;">&#1042;&#1086;&#1081;&#1090;&#1080;</div></div></td>' + '<td><div style="background: url(' + VK._protocol + '//vk.com/images/btns.png) 0px -42px no-repeat; width: 21px; height: 21px"></div></td>' + '<td><div style="border: 1px solid #3b6798;border-radius: 0px 2px 2px 0px;-moz-border-radius: 0px 2px 2px 0px;-webkit-border-radius: 0px 2px 2px 0px;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6D8DB1; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 6px 0px 4px;line-height: 13px;">&#1050;&#1086;&#1085;&#1090;&#1072;&#1082;&#1090;&#1077;</div></div></td>' + '</tr></table>' ); el.innerHTML = html; el.style.width = el.childNodes[0].offsetWidth + 'px'; }, _change: function(state, index) { var row = document.getElementById('openapi_UI_' + index).rows[0]; var elems = [row.cells[0].firstChild.firstChild, row.cells[2].firstChild.firstChild]; for (var i = 0; i < 2; ++i) { var elem = elems[i]; if (state === 0) { elem.style.backgroundColor = '#6D8DB1'; elem.style.borderTopColor = '#7E9CBC'; elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#5C82AB'; } else if (state == 1) { elem.style.backgroundColor = '#7693B6'; elem.style.borderTopColor = '#88A4C4'; elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#6088B4'; } else if (state == 2) { elem.style.backgroundColor = '#6688AD'; elem.style.borderBottomColor = '#7495B8'; elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderTopColor = '#51779F'; } } if (state === 0 || state == 2) { row.cells[2].firstChild.style.backgroundPosition = '0px -42px'; } else if (state == 1) { row.cells[2].firstChild.style.backgroundPosition = '0px -63px'; } } }; } if (!VK.XDM) { VK.XDM = { remote: null, init: function() { if (this.remote) return false; var url = VK._domain.api + VK._path.proxy; this.remote = new fastXDM.Server({ onInit: function() { VK.xdReady = true; VK.Observer.publish('xdm.init'); } }); this.remote.append(document.getElementById(VK._rootId), { src: url }); }, xdHandler: function(code) { try { eval('VK.' + code); } catch(e) {} } }; } if (!VK.Observer) { VK.Observer = { _subscribers: function() { if (!this._subscribersMap) { this._subscribersMap = {}; } return this._subscribersMap; }, publish: function(eventName) { var args = Array.prototype.slice.call(arguments), eventName = args.shift(), subscribers = this._subscribers()[eventName], i, j; if (!subscribers) return; for (i = 0, j = subscribers.length; i < j; i++) { if (subscribers[i] != null) { subscribers[i].apply(this, args); } } }, subscribe: function(eventName, handler) { var subscribers = this._subscribers(); if (typeof handler != 'function') return false; if (!subscribers[eventName]) { subscribers[eventName] = [handler]; } else { subscribers[eventName].push(handler); } }, unsubscribe: function(eventName, handler) { var subscribers = this._subscribers()[eventName], i, j; if (!subscribers) return false; if (typeof handler == 'function') { for (i = 0, j = subscribers.length; i < j; i++) { if (subscribers[i] == handler) { subscribers[i] = null; } } } else { delete this._subscribers()[eventName]; } } }; } if (!VK.Widgets) { VK.Widgets = {}; VK.Widgets.count = 0; VK.Widgets.RPC = {}; VK.Widgets.loading = function(obj, enabled) { obj.style.background = enabled ? 'url("' + VK._protocol + '//vk.com/images/upload.gif") center center no-repeat transparent' : 'none'; }; VK.Widgets.Comments = function(objId, options, page) { var pData = VK.Util.getPageData(); if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); options = options || {}; var params = { limit: options.limit || 10, height: options.height || 0, mini: options.mini === undefined ? 'auto' : options.mini, norealtime: options.norealtime ? 1 : 0 }, mouseup = function() { rpc.callMethod('mouseUp'); return false; }, move = function(event) { rpc.callMethod('mouseMove', {screenY: event.screenY}); }, iframe, rpc; if (options.browse) { // browse all comments params.browse = 1; params.replies = options.replies || 0; } else { // page var url = options.pageUrl || pData.url; if (url.substr(0, 1) == '/') { url = (location.protocol + '//' + location.host) + url; } VK.extend(params, { page: page || 0, status_publish: options.autoPublish === undefined ? 1 : options.autoPublish, attach: options.attach === undefined ? '*' : (options.attach ? options.attach : ''), url: url, title: options.pageTitle || pData.title, description: options.pageDescription || pData.description, image: options.pageImage || pData.image }); } if (options.onChange) { // DEPRECATED VK.Observer.subscribe('widgets.comments.new_comment', options.onChange); VK.Observer.subscribe('widgets.comments.delete_comment', options.onChange); } return VK.Widgets._constructor('widget_comments.php', objId, options, params, { showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com') + '/' + url, [], { proxy: function() { rpc.callMethod.apply(rpc, arguments); } }); box.show(); }, startDrag: function() { cursorBack = window.document.body.style.cursor; window.document.body.style.cursor = 'pointer'; VK.Util.addEvent('mousemove', move); VK.Util.addEvent('mouseup', mouseup); }, stopDrag: function() { window.document.body.style.cursor = cursorBack; VK.Util.removeEvent('mousemove', move); VK.Util.removeEvent('mouseup', mouseup); } }, { startHeight: 133, minWidth: 300, width: '100%' }, function(o, i, r) {iframe = i; rpc = r;}); }; VK.Widgets.CommentsBrowse = function(objId, options) { options = options || {}; options.browse = 1; return VK.Widgets.Comments(objId, options); }; VK.Widgets.Recommended = function(objId, options) { var pData = VK.Util.getPageData(); if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); options = options || {}; var params = { limit: options.limit || 5, max: options.max || 0, sort: options.sort || 'friend_likes', verb: options.verb || 0, period: options.period || 'week', target: options.target || 'parent' }; return VK.Widgets._constructor('widget_recommended.php', objId, options, params, {}, { startHeight: (90 + params.limit * 30), minWidth: 150, width: '100%' }); }; VK.Widgets.Post = function(objId, ownerId, postId, hash, options) { options = options || {}; var params = { owner_id: ownerId, post_id: postId, hash: hash || '', width: options.width || 500 }, iframe, rpc, cursorBack; return VK.Widgets._constructor('widget_post.php', objId, options, params, { showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com') + '/' + url, [], { proxy: function() { rpc.callMethod.apply(rpc, arguments); } }); box.show(); }, startDrag: function() { cursorBack = window.document.body.style.cursor; window.document.body.style.cursor = 'pointer'; }, stopDrag: function() { window.document.body.style.cursor = cursorBack; } }, { startHeight: 90, minWidth: 250, width: '100%' }, function(o, i, r) {iframe = i; rpc = r;}); }; VK.Widgets.Like = function(objId, options, page) { var pData = VK.Util.getPageData(); if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); options = VK.extend(options || {}, {allowTransparency: true}); if (options.type == 'button' || options.type == 'vertical' || options.type == 'mini') delete options.width; var type = (options.type == 'full' || options.type == 'button' || options.type == 'vertical' || options.type == 'mini') ? options.type : 'full', width = type == 'full' ? Math.max(200, options.width || 350) : (type == 'button' ? 180 : (type == 'mini' ? 100 : 41)), btnHeight = parseInt(options.height, 10) || 22, height = type == 'vertical' ? (2 * btnHeight + 7) : (type == 'full' ? btnHeight + 1 : btnHeight), params = { page: page || 0, url: options.pageUrl || pData.url, type: type, verb: options.verb == 1 ? 1 : 0, color: options.color || '', title: options.pageTitle || pData.title, description: options.pageDescription || pData.description, image: options.pageImage || pData.image, text: (options.text || '').substr(0, 140), h: btnHeight }, ttHere = options.ttHere || false, isOver = false, obj, buttonIfr, buttonRpc, tooltipIfr, tooltipRpc, checkTO, statsBox; function showTooltip(force) { if ((!isOver && !force) || !tooltipRpc) return; if (!tooltipIfr || !tooltipRpc || tooltipIfr.style.display != 'none' && tooltipIfr.getAttribute('vkhidden') != 'yes') return; var scrollTop = options.getScrollTop ? options.getScrollTop() : (document.body.scrollTop || document.documentElement.scrollTop || 0); var objPos = VK.Util.getXY(obj, options.fixed); var startY = ttHere ? 0 : objPos[1]; if (scrollTop > objPos[1] - 120 && options.tooltipPos != 'top' || type == 'vertical' || options.tooltipPos == 'bottom') { tooltipIfr.style.top = (startY + height + 2) + 'px'; tooltipRpc.callMethod('show', false); } else { tooltipIfr.style.top = (startY - 125) + 'px'; tooltipRpc.callMethod('show', true); } VK.Util.ss(tooltipIfr, {left: ((ttHere ? 0 : objPos[0]) - (type == 'vertical' || type == 'mini' ? 36 : 2)) + 'px', display: 'block', opacity: 1, filter: 'none'}); tooltipIfr.setAttribute('vkhidden', 'no'); isOver = true; } function hideTooltip(force) { if ((isOver && !force) || !tooltipRpc) return; tooltipRpc.callMethod('hide'); buttonRpc.callMethod('hide'); setTimeout(function() { tooltipIfr.style.display = 'none' }, 400); } function handleStatsBox(act) { hideTooltip(true); statsBox = VK.Util.Box(buttonIfr.src + '&act=a_stats_box&widget_width=620'); statsBox.show(); } return VK.Widgets._constructor('widget_like.php', objId, options, params, { initTooltip: function(counter) { tooltipRpc = new fastXDM.Server({ onInit: counter ? function() {showTooltip(true)} : function() {}, proxy: function() { buttonRpc.callMethod.apply(buttonRpc, arguments); }, showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com/') + url, [props.width, props.height], { proxy: function() { tooltipRpc.callMethod.apply(tooltipRpc, arguments); } }); box.show(); }, statsBox: handleStatsBox }, false, {safe: true}); tooltipIfr = tooltipRpc.append(ttHere ? obj : document.body, { src: buttonIfr.src + '&act=a_like_tooltip', scrolling: 'no', allowTransparency: true, id: buttonIfr.id + '_tt', style: {position: 'absolute', padding: 0, display: 'block', opacity: 0.01, filter: 'alpha(opacity=1)', border: '0', width: '238px', height: '124px', zIndex: 5000, overflow: 'hidden'} }); tooltipIfr.setAttribute('vkhidden', 'yes'); obj.onmouseover = tooltipIfr.onmouseover = function() { clearTimeout(checkTO); isOver = true; }; obj.onmouseout = tooltipIfr.onmouseout = function() { clearTimeout(checkTO); isOver = false; checkTO = setTimeout(function() {hideTooltip(); }, 200); }; }, statsBox: handleStatsBox, showTooltip: showTooltip, hideTooltip: hideTooltip, showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com/') + url, [], { proxy: function() { buttonRpc.callMethod.apply(buttonRpc, arguments); } }); box.show(); }, proxy: function() {if (tooltipRpc) tooltipRpc.callMethod.apply(tooltipRpc, arguments);} }, { startHeight: height, minWidth: width }, function(o, i, r) { buttonRpc = r; VK.Util.ss(obj = o, {height: height + 'px', width: width + 'px', position: 'relative', clear: 'both'}); VK.Util.ss(buttonIfr = i, {height: height + 'px', width: width + 'px', overflow: 'hidden', zIndex: 150}); }); }; VK.Widgets.Poll = function(objId, options, pollId) { var pData = VK.Util.getPageData(); // if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); if (!pollId) throw Error('No poll id passed'); options = options || {}; var params = { poll_id: pollId, url: options.pageUrl || pData.url || location.href, title: options.pageTitle || pData.title, description: options.pageDescription || pData.description }; return VK.Widgets._constructor('widget_poll.php', objId, options, params, {}, { startHeight: 133, minWidth: 300, width: '100%' }); }; VK.Widgets.PagePoll = function(objId, options, page) { var pData = VK.Util.getPageData(); // if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); options = options || {}; var params = { page: page || 0, norealtime: options.norealtime ? 1 : 0, poll_id: options.pollId || '', url: options.pageUrl || pData.url || location.href, title: options.pageTitle || pData.title, description: options.pageDescription || pData.description }; return VK.Widgets._constructor('al_widget_poll.php', objId, options, params, {}, { startHeight: 133, minWidth: 300, width: '100%' }); }; VK.Widgets.Community = VK.Widgets.Group = function(objId, options, gid) { gid = parseInt(gid, 10); var RPC; if (!gid) { throw Error('No group_id passed'); } options.mode = parseInt(options.mode, 10).toString(); var params = { gid: gid, mode: (options.mode) ? options.mode : '0' }; if (!options.width) options.width = 200; if (options.wall) params.wall = options.wall; params.color1 = options.color1 || ''; params.color2 = options.color2 || ''; params.color3 = options.color3 || ''; if (options.no_head) params.no_head = 1; if (!options.height) options.height = 290; if (options.wide) { params.wide = 1; if (options.width < 300) { options.width = 300; } } var cursorBack; function mouseup() { RPC.callMethod('mouseUp'); return false; } function move(event) { RPC.callMethod('mouseMove', {screenY: event.screenY}); return false; } return VK.Widgets._constructor('widget_community.php', objId, options, params, { showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com/') + url, [], { proxy: function() { rpc.callMethod.apply(rpc, arguments); } }); box.show(); }, startDrag: function() { cursorBack = window.document.body.style.cursor; window.document.body.style.cursor = 'pointer'; VK.Util.addEvent('mousemove', move); VK.Util.addEvent('mouseup', mouseup); }, stopDrag: function() { window.document.body.style.cursor = cursorBack; VK.Util.removeEvent('mousemove', move); VK.Util.removeEvent('mouseup', mouseup); }, auth: function() { VK.Auth.login(null, 1); } }, { minWidth: 120, width: '200', height: '290', startHeight: 200 }, function(o, i, r) { RPC = r; }); }; VK.Widgets.Auth = function(objId, options) { var pData = VK.Util.getPageData(); if (!VK._apiId) throw Error('VK not initialized. Please use VK.init'); if (!options.width) { options.width = 200; } if (options.type) { type = 1; } else { type = 0; } return VK.Widgets._constructor('widget_auth.php', objId, options, {}, {makeAuth: function(data) { if (data.session) { VK.Auth._loadState = 'loaded'; VK.Auth.setSession(data.session, 'connected'); VK.Observer.publish('auth.loginStatus', {session: data.session, status: 'connected'}); VK.Observer.unsubscribe('auth.loginStatus'); } if (options.onAuth) { options.onAuth(data); } else { if (options.authUrl) { var href = options.authUrl; } else { var href = window.location.href; } if (href.indexOf('?') == -1) { href+='?'; } else { href+='&'; } var vars = []; for (var i in data) { if (i != 'session') vars.push(i+'='+decodeURIComponent(data[i]).replace(/&/g, '%26').replace(/\?/, '%3F')); } window.location.href = href + vars.join('&'); } }}, {startHeight: 80}); }; VK.Widgets.Subscribe = function(objId, options, oid) { oid = parseInt(oid, 10); var RPC; if (!oid) { throw Error('No owner_id passed'); } var params = { oid: oid }; if (options.mode) { params.mode = options.mode; } if (options.soft) { params.soft = options.soft; } return VK.Widgets._constructor('widget_subscribe.php', objId, options, params, { showBox: function(url, props) { var box = VK.Util.Box((options.base_domain || VK._protocol + '//vk.com/') + url, [], { proxy: function() { rpc.callMethod.apply(rpc, arguments); } }); box.show(); }, auth: function() { VK.Auth.login(null, 1); } }, { minWidth: 220, startHeight: 22, height: options.height || 22 }, function(o, i, r) { RPC = r; }); }; VK.Widgets.Ads = function(objId, options, paramsExtra) { options = options || {}; paramsExtra = paramsExtra || {}; var params = {}; var defaults = {}; var funcs = {}; var obj = document.getElementById(objId); var iframe; var rpc; var adsParams = {}; var adsParamsLocal = {}; var adsParamsDefault = {}; for (var key in paramsExtra) { var keyFix = (inArray(key, ['hash']) ? key : 'ads_' + key); adsParams[keyFix] = paramsExtra[key]; } if (obj && obj.getBoundingClientRect) { obj.style.width = '100%'; obj.style.height = '100%'; var rect = obj.getBoundingClientRect(); obj.style.width = ''; obj.style.height = ''; adsParams.ads_ad_unit_width_auto = Math.floor(rect.right - rect.left); adsParams.ads_ad_unit_height_auto = Math.floor(rect.bottom - rect.top); } adsParamsDefault.ads_ad_unit_width = 100; adsParamsDefault.ads_ad_unit_height = 100; adsParamsLocal.ads_ad_unit_width = (parseInt(adsParams.ads_ad_unit_width) || adsParams.ads_ad_unit_width === 'auto' && adsParams.ads_ad_unit_width_auto || adsParamsDefault.ads_ad_unit_width); adsParamsLocal.ads_ad_unit_height = (parseInt(adsParams.ads_ad_unit_height) || adsParams.ads_ad_unit_height === 'auto' && adsParams.ads_ad_unit_height_auto || adsParamsDefault.ads_ad_unit_height); if (adsParams.ads_handler) { adsParamsLocal.ads_handler = adsParams.ads_handler; } if (adsParams.ads_handler_empty_html) { adsParamsLocal.ads_handler_empty_html = adsParams.ads_handler_empty_html; } delete adsParams.ads_handler; delete adsParams.ads_handler_empty_html; params.act = 'ads_web'; params.url = location.href; VK.extend(params, adsParams); options.noDefaultParams = true; options.width = adsParamsLocal.ads_ad_unit_width; options.allowTransparency = true; defaults.startHeight = adsParamsLocal.ads_ad_unit_height; defaults.minWidth = adsParamsLocal.ads_ad_unit_width; funcs.adsOnInitLoader = adsOnInitLoader; funcs.adsOnInit = adsOnInit; return VK.Widgets._constructor('ads_rotate.php', objId, options, params, funcs, defaults, onDone); function adsOnInitLoader(adsScriptVersion) { VK.Widgets.loading(obj, true); adsAttachScript(adsScriptVersion); } function adsOnInit(errorCode, adsParamsExport) { VK.Widgets.loading(obj, false); adsProcessParams(adsParamsExport); if (options.onAdsReady) options.onAdsReady.apply(options.onAdsReady, Array.prototype.slice.call(arguments)); adsProcessHandler(errorCode); } function adsAttachScript(adsScriptVersion) { if (!('vk__adsLight' in window)) { window.vk__adsLight = false; adsScriptVersion = parseInt(adsScriptVersion); var attachScriptFunc = (VK.Api && VK.Api.attachScript || VK.addScript); var base_domain = (options.base_domain || VK._protocol + '//vk.com'); attachScriptFunc(base_domain + '/js/al/aes_light.js?' + adsScriptVersion); } else if (window.vk__adsLight && vk__adsLight.userHandlers && vk__adsLight.userHandlers.onInit) { vk__adsLight.userHandlers.onInit(false); // false - do not publish initial onInit } } function adsProcessParams(adsParamsExport) { if (!adsParamsExport) { return; } for (var paramName in adsParamsExport) { var paramValue = adsParamsExport[paramName]; if (paramName === 'ads_ad_unit_width' || paramName === 'ads_ad_unit_height') { if (!(paramName in adsParams)) { adsParamsLocal[paramName] = (parseInt(paramValue) || paramValue === 'auto' && adsParams[paramName + '_auto'] || adsParamsDefault[paramName]); } } else { if (!(paramName in adsParamsLocal)) { adsParamsLocal[paramName] = paramValue; } } } } function adsProcessHandler(errorCode) { var handlerResult = adsEvalHandler(adsParamsLocal.ads_handler, errorCode); if (errorCode <= 0 && handlerResult !== true) { try { console.log('VK: ad_unit_id = ' + adsParams.ads_ad_unit_id, ', errorCode = ', errorCode); } catch (e) {} adsInsertHtmlHandler(adsParamsLocal.ads_handler_empty_html, adsParamsLocal.ads_ad_unit_width, adsParamsLocal.ads_ad_unit_height); } } function adsEvalHandler(handler) { var result = false; try { if (!handler) { return false; } var func = false; if (isFunction(handler)) { func = handler; } else if (isString(handler)) { var handlerFuncs = handler.split('.'); func = window; for (var i = 0, len = handlerFuncs.length; i < len; i++) { func = func[handlerFuncs[i]]; if (!func) { break; } } if (!func) { if (handler.substr(0, 8) === 'function') { handler = 'return ' + handler + ';'; } var handlerResult = (new Function(handler))(); if (isFunction(handlerResult)) { func = handlerResult; } else { result = handlerResult; } } } if (func) { var args = Array.prototype.slice.call(arguments, 1); result = func.apply(func, args); } } catch (e) { try { console.error(e); } catch (e2) {} } return result; function isFunction(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } function isString(obj) { return Object.prototype.toString.call(obj) === '[object String]'; } } function adsInsertHtmlHandler(handlerHtml, width, height) { if (!handlerHtml) { return; } if (!obj) { return; } width = (width ? width + 'px' : ''); height = (height ? height + 'px' : ''); var iframeHandlerHtml = '<html><head></head><body style="padding: 0; margin: 0;"><div>' + handlerHtml + '</div></body></html>'; var iframeHandler = document.createElement('iframe'); iframeHandler.onload = fixIframeHeight; iframeHandler.id = (iframe ? iframe.id : ('vkwidget-' + Math.round(Math.random() * 1000000))) + '_ads_html_handler'; iframeHandler.src = 'about:blank'; iframeHandler.width = '100%'; iframeHandler.height = '100%'; iframeHandler.scrolling = 'no'; iframeHandler.frameBorder = '0'; iframeHandler.allowTransparency = true; iframeHandler.style.overflow = 'hidden'; iframeHandler.style.width = width; iframeHandler.style.height = height; obj.style.width = width; obj.style.height = height; obj.appendChild(iframeHandler); iframeHandler.contentWindow.vk_ads_html_handler = iframeHandlerHtml; iframeHandler.src = 'javascript:window["vk_ads_html_handler"]'; function fixIframeHeight() { if (height) { return; } try { var rect = iframeHandler.contentWindow.document.body.firstChild.getBoundingClientRect(); var heightFix = Math.ceil(rect.bottom - rect.top); if (heightFix) { iframeHandler.style.height = heightFix; obj.style.height = heightFix; } } catch (e) {} } } function indexOf(arr, value, from) { for (var i = from || 0, l = (arr || []).length; i < l; i++) { if (arr[i] == value) return i; } return -1; } function inArray(value, arr) { return indexOf(arr, value) != -1; } function onDone(o, i, r) { obj = o; iframe = i; rpc = r; } }; VK.Widgets._constructor = function(widgetUrl, objId, options, params, funcs, defaults, onDone, widgetId, iter) { var obj = document.getElementById(objId); widgetId = widgetId || (++VK.Widgets.count); if (!obj) { iter = iter || 0; if (iter > 10) { throw Error('VK.Widgets: object #' + objId + ' not found.'); } setTimeout(function() { VK.Widgets._constructor(widgetUrl, objId, options, params, funcs, defaults, onDone, widgetId, iter + 1); }, 500); return widgetId; } var ifr, base_domain, width, url, urlQueryString, encodedParam, rpc, iframe, i; options = options || {}; defaults = defaults || {}; funcs = funcs || {}; base_domain = options.base_domain || VK._protocol + '//vk.com'; width = (options.width == 'auto') ? obj.clientWidth || '100%' : parseInt(options.width, 10); if (options.height) { params.height = options.height; obj.style.height = options.height + 'px'; } else { obj.style.height = (defaults.startHeight || 200) + 'px'; } width = width ? (Math.max(defaults.minWidth || 200, Math.min(10000, width)) + 'px') : '100%'; if (!params.url) { params.url = options.pageUrl || location.href.replace(/#.*$/, ''); } url = base_domain + '/' + widgetUrl; urlQueryString = ''; if (!options.noDefaultParams) { urlQueryString += '&app=' + (VK._apiId || '0') + '&width=' + width } urlQueryString += '&_ver=' + VK.version if (VK._iframeAppWidget) { params.iframe_app = 1; } for (i in params) { if (i == 'title' && params[i].length > 80) params[i] = params[i].substr(0, 80)+'...'; if (i == 'description' && params[i].length > 160) params[i] = params[i].substr(0, 160)+'...'; if (typeof(params[i]) == 'number') { encodedParam = params[i]; } else { try { encodedParam = encodeURIComponent(params[i]); } catch (e) { encodedParam = ''; } } urlQueryString += '&' + i + '=' + encodedParam; } urlQueryString += '&' + (+new Date()).toString(16); url += '?' + urlQueryString.substr(1); obj.style.width = width; VK.Widgets.loading(obj, true); funcs.publish = function() { var args = Array.prototype.slice.call(arguments); args.push(widgetId); VK.Observer.publish.apply(VK.Observer, args); }; funcs.onInit = function() { VK.Widgets.loading(obj, false); if (funcs.onReady) funcs.onReady(); if (options.onReady) options.onReady(); } funcs.resize = function(e, cb) { obj.style.height = e + 'px'; var el = document.getElementById('vkwidget' + widgetId); if (el) { el.style.height = e + 'px'; } } funcs.resizeWidget = function(newWidth, newHeight) { newWidth = parseInt(newWidth); newHeight = parseInt(newHeight); var widgetElem = document.getElementById('vkwidget' + widgetId); if (isFinite(newWidth)) { obj.style.width = newWidth + 'px'; if (widgetElem) { widgetElem.style.width = newWidth + 'px'; } } if (isFinite(newHeight)) { obj.style.height = newHeight + 'px'; if (widgetElem) { widgetElem.style.height = newHeight + 'px'; } } if (options.onResizeWidget) options.onResizeWidget(); } funcs.updateVersion = function(ver) { if (ver > 1) { VK.Api.attachScript('//vk.com/js/api/openapi_update.js?'+parseInt(ver)); } } rpc = VK.Widgets.RPC[widgetId] = new fastXDM.Server(funcs, function(origin) { if (!origin) return true; origin = origin.toLowerCase(); return (origin.match(/(\.|\/)vk\.com($|\/|\?)/)); }, {safe: true}); iframe = VK.Widgets.RPC[widgetId].append(obj, { src: url, width: (width.indexOf('%') != -1) ? width : (parseInt(width) || width), height: defaults.startHeight || '100%', scrolling: 'no', id: 'vkwidget' + widgetId, allowTransparency: options.allowTransparency || false, style: { overflow: 'hidden' } }); onDone && setTimeout(function() {onDone(obj, iframe || obj.firstChild, rpc);}, 10); return widgetId; }; } if (!VK.Util) { VK.Util = { getPageData: function() { if (!VK._pData) { var metas = document.getElementsByTagName('meta'), pData = {}, keys = ['description', 'title', 'url', 'image', 'app_id'], metaName; for (var i in metas) { if (!metas[i].getAttribute) continue; if (metas[i].getAttribute && ((metaName = metas[i].getAttribute('name')) || (metaName = metas[i].getAttribute('property')))) { for (var j in keys) { if (metaName == keys[j] || metaName == 'og:'+keys[j] || metaName == 'vk:'+keys[j]) { pData[keys[j]] = metas[i].content; } } } } if (pData.app_id && !VK._apiId) { VK._apiId = pData.app_id; } pData.title = pData.title || document.title || ''; pData.description = pData.description || ''; pData.image = pData.image || ''; if (!pData.url && VK._iframeAppWidget && VK._apiId) { pData.url = '/app' + VK._apiId; if (VK._browserHash) { pData.url += VK._browserHash } } var loc = location.href.replace(/#.*$/, ''); if (!pData.url || !pData.url.indexOf(loc)) { pData.url = loc; } VK._pData = pData; } return VK._pData; }, getStyle: function(elem, name) { var ret, defaultView = document.defaultView || window; if (defaultView.getComputedStyle) { name = name.replace(/([A-Z])/g, '-$1').toLowerCase(); var computedStyle = defaultView.getComputedStyle(elem, null); if (computedStyle) { ret = computedStyle.getPropertyValue(name); } } else if (elem.currentStyle) { var camelCase = name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); }); ret = elem.currentStyle[name] || elem.currentStyle[camelCase]; } return ret; }, getXY: function(obj, fixed) { if (!obj || obj === undefined) return; var left = 0, top = 0; if (obj.getBoundingClientRect !== undefined) { var rect = obj.getBoundingClientRect(); left = rect.left; top = rect.top; fixed = true; } else if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; if (fixed) { left -= obj.scrollLeft; top -= obj.scrollTop; } } while (obj = obj.offsetParent); } if (fixed) { top += window.pageYOffset || window.scrollNode && scrollNode.scrollTop || document.documentElement.scrollTop; left += window.pageXOffset || window.scrollNode && scrollNode.scrollLeft || document.documentElement.scrollLeft; } return [left, top]; }, Box: function(src, sizes, fnc, options) { fnc = fnc || {}; var overflowB = document.body.style.overflow; var loader = document.createElement('DIV'); var rpc = new fastXDM.Server(VK.extend(fnc, { onInit: function() { iframe.style.background = 'transparent'; iframe.style.visibility = 'visible'; document.body.style.overflow = 'hidden'; document.body.removeChild(loader); }, hide: function() { iframe.style.display = 'none'; }, tempHide: function() { iframe.style.left = '-10000px'; iframe.style.top = '-10000px'; iframe.style.width = '10px'; iframe.style.height = '10px'; document.body.style.overflow = overflowB; }, destroy: function() { try { iframe.src = 'about: blank;'; } catch (e) {} iframe.parentNode.removeChild(iframe); document.body.style.overflow = overflowB; }, resize: function(w, h) { } }, true), false, {safe: true}), iframe = rpc.append(document.body, { src: src.replace(/&amp;/g, '&'), scrolling: 'no', allowTransparency: true, style: {position: 'fixed', left: 0, top: 0, zIndex: 1002, background: VK._protocol + '//vk.com/images/upload.gif center center no-repeat transparent', padding: '0', border: '0', width: '100%', height: '100%', overflow: 'hidden', visibility: 'hidden'} }); loader.innerHTML = '<div style="position: fixed;left: 50%;top: 50%;margin: 0px auto 0px -60px;z-index: 1002;width: 100px;"><div style="background: url(//vk.com/images/upload_inv_mono'+(window.devicePixelRatio >= 2 ? '_2x' : '')+'.gif) no-repeat 50% 50%;background-size: 64px 16px;height: 50px;position: absolute;width: 100%;z-index: 100;"></div><div style="background-color: #000;opacity: 0.7;filter: alpha(opacity=70);height: 50px;-webkit-border-radius: 5px;-khtml-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-webkit-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);-moz-box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.35);"></div></div>'; document.body.insertBefore(loader, document.body.firstChild); return { show: function(scrollTop, height) { iframe.style.display = 'block'; document.body.style.overflow = 'hidden'; }, hide: function() { iframe.style.display = 'none'; document.body.style.overflow = overflowB; }, iframe: iframe, rpc: rpc } }, addEvent: function(type, func) { if (window.document.addEventListener) { window.document.addEventListener(type, func, false); } else if (window.document.attachEvent) { window.document.attachEvent('on'+type, func); } }, removeEvent: function(type, func) { if (window.document.removeEventListener) { window.document.removeEventListener(type, func, false); } else if (window.document.detachEvent) { window.document.detachEvent('on'+type, func); } }, ss: function(el, styles) {VK.extend(el.style, styles, true);} }; } // Init asynchronous library loading window.vkAsyncInit && setTimeout(vkAsyncInit, 0); if (window.vkAsyncInitCallbacks && vkAsyncInitCallbacks.length) { setTimeout(function() { var callback; while (callback = vkAsyncInitCallbacks.pop()) { try { callback(); } catch(e) { try { console.error(e); } catch (e2) {} } } }, 0); } try{if (window.stManager) stManager.done('api/openapi.js');}catch(e){}
JavaScript
function fireNetSeerTrigger() { window.netseer_fire_on_trigger = null; netseerMainFunction(window); } function netseerMainFunction (lw) { var netseer_ap = "netseer_carrier_id netseer_lat netseer_long netseer_country netseer_city netseer_zip netseer_region netseer_dma netseer_device_type netseer_platform netseer_handset_id netseer_connection netseer_device_id netseer_site_id netseer_app_id netseer_ext_channel netseer_aud_segment netseer_demo netseer_inv_type netseer_req_id netseer_seller_id netseer_ssl".split(" "); var netseer_ap_keys = "caid lat long cntr city zip rgn metro dvtype plf hsid cnn dvid stid appid extch extaseg demo invtype refid exsid ssl".split(" "); var netseer_ap_encoded = "netseer_site_name netseer_app_name".split(" "); var netseer_ap_encoded_keys = "stname appname".split(" "); var isDOMLoaded = false; //var cacheBuster = new Date().getTime(); var cacheBuster = new Date().getHours(); var exchanges = [10,11,14,16,18,27,31]; var exchange_counter = 0; function loadNextPixel() { var pixel = new Image(); if (exchange_counter + 1 < exchanges.length) { pixel.onload = loadNextPixel; pixel.onerror = loadNextPixel; pixel.onabort = loadNextPixel; } var cookie_status = ''; var ext = ''; var exchangeId = exchanges[exchange_counter++]; if(lw.netseer_cookie){ cookie_status = '&cookie=0'; } if(exchangeId==31){ ext = '&ui=2'; } pixel.src = getProtocol(window)+'cmi.netseer.com/redirect?ex=' + exchangeId + '&t=' + cacheBuster + cookie_status + ext; } function whichBrowser() { var agt=navigator.userAgent.toLowerCase(); if (agt.indexOf("safari") != -1 && agt.indexOf("chrom") == -1) return 'Safari'; if (agt.indexOf("mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko") != -1) return 'IE11NoCookie'; if (agt.indexOf("opera") != -1) return 'Opera'; if (agt.indexOf("staroffice") != -1) return 'Star Office'; if (agt.indexOf("webtv") != -1) return 'WebTV'; if (agt.indexOf("beonex") != -1) return 'Beonex'; if (agt.indexOf("chimera") != -1) return 'Chimera'; if (agt.indexOf("netpositive") != -1) return 'NetPositive'; if (agt.indexOf("phoenix") != -1) return 'Phoenix'; if (agt.indexOf("firefox") != -1) return 'Firefox'; if (agt.indexOf("skipstone") != -1) return 'SkipStone'; if (agt.indexOf("msie") != -1) return 'Internet Explorer'; if (agt.indexOf("netscape") != -1) return 'Netscape'; if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla'; if (agt.indexOf('\/') != -1) { if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') { return navigator.userAgent.substr(0,agt.indexOf('\/'));} else return 'Netscape';} else if (agt.indexOf(' ') != -1) return navigator.userAgent.substr(0,agt.indexOf(' ')); else return navigator.userAgent; } function generateUserId() { var userId = "usr"; for(var i=0;i<16;i++){ var randomnumber=Math.floor(Math.random()*16); userId = userId + randomnumber.toString(16); } return userId; } function checkForSafariCookie(){ var browser = whichBrowser(); var cookieName = "netseer_v3_vi"; var userId = readCookie(cookieName); var ret = null; if( whichBrowser() == "Safari"){ if(userId == null) { var date = new Date(); userId = "0:"+generateUserId()+":"+date.getTime(); createCookie(cookieName, userId, 1000); } ret = userId.replace(/"/g,''); } return ret; } function isCookieBlocked(){ var testCookie ="testcookie"; document.cookie = testCookie; cookieBlocked=(document.cookie.indexOf(testCookie)!=-1)? false : true; document.cookie = testCookie + '; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; var browserType = whichBrowser(); if(cookieBlocked == false && (browserType == 'Safari' || browserType == 'IE11NoCookie')){ cookieBlocked = true; } return cookieBlocked; } /** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } function createCookie(name, value, days) { var expires = ""; if (days) { var exdate=new Date(); exdate.setDate(exdate.getDate() + days); expires = "; expires=" + exdate.toUTCString(); } //document.cookie = name + "=" + value + expires +"; domain=.ns-cdn.com"+ "; path=/"; document.cookie = name + "=" + value + expires +"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(";"); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == " ") { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) == 0) { return c.substring(nameEQ.length, c.length); } } return null; } function removeParamFromURL(URL,param) { URL = String(URL); var regex = new RegExp( "\\?" + param + "=[^&]*&?", "gi"); URL = URL.replace(regex,'?'); regex = new RegExp( "\\&" + param + "=[^&]*&?", "gi"); URL = URL.replace(regex,'&'); URL = URL.replace(/(\?|&)$/,''); regex = null; return URL; } function addParamToURL(URL,param,value) { URL = removeParamFromURL(URL,param); URL = URL + '&' + param + '=' + value if (!(/\?/.test(URL))) URL = URL.replace(/&/,'?'); return URL; } function eraseCookie(name) { createCookie(name, "", -1); } function getQuerystring(key, url, default_, seperator) { if (default_ == null) { default_ = ""; } if (seperator == null) { seperator = "&"; } key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?" + seperator + "]" + key + "=([^" + seperator + "#]*)"); var qs = regex.exec(url); if (qs == null) { return default_; } else { return qs[1]; } } function getProtocol(w) { var protocol = "http://"; if(w && w.location && w.location.protocol && "https:" == w.location.protocol.toString().toLowerCase()){ protocol = "https://"; } else if(w && w.netseer_enforce_protocol && w.netseer_enforce_protocol == "https"){ protocol = "https://"; } else if(w && w.netseer_page_url && w.netseer_page_url.toLowerCase().substring(0, 5) == "https"){ protocol = "https://"; } else if(w && (w.netseer_ssl == "1" || w.netseer_ssl == "true")){ protocol = "https://"; } return protocol; } function getHost(a) { if (a && a["location"] && a["location"].host) return a["location"].host["toString"](); else return "cl.netseer.com"; } function getServerEndPoint(a) { var requestProtocol = getProtocol(a); if(a.netseer_embed_style && a.netseer_embed_style=='inline'){ return ""; } if(a.netseer_endpoint){ if(a.netseer_endpoint =='contextlinks.netseer.com'){ a.netseer_endpoint = 'cl.netseer.com'; } else if(a.netseer_endpoint =='staging.netseer.com'){ a.netseer_endpoint = 'media.netseer.com'; } } else if(a && a.netseer_task=='px'){ a.netseer_endpoint = 'pixel.netseer.com'; } else { a.netseer_endpoint = 'cl.netseer.com'; } return requestProtocol + a.netseer_endpoint; } function getLocationForYahoo(url) { var vars = url.href.split("$,"); return vars[vars.length - 1]; } function RemoveHTML(strText) { var regEx = /<[^>]*>/g; return strText.replace(regEx, ""); } function check(b) { return b != null ? "\"" + b + "\"" : "\"\""; } function encodeUrl(b) { if (b) { try { if (typeof encodeURIComponent == "function") { return encodeURIComponent(b); } else { return escape(b); } } catch (e) { return ""; } } else { return b; } } function decodeUrl(b,replacePlus) { if (b) { if(replacePlus){ b = b.replace(/\+/g," "); } try { if (typeof decodeURIComponent == "function") { return decodeURIComponent(b); } else { return unescape(b); } } catch (e) { return ""; } } else { return b; } } function addToUrl(b, a) { if (a) { var seperator = "&"; if(lw.netseer_global_fparam && lw.netseer_global_fparam == "true") seperator = ""; lw.netseer_ad_url += seperator + b + "=" + a; lw.netseer_global_fparam = "false"; } } function addParam(b, a) { if (a) { lw.netseer_page_params += "&" + b + "=" + a; } } function addExtParam(a) { if (a) { lw.netseer_page_params += "&" + a; } } function addToUrlNoKey(a) { if (a) { lw.netseer_ad_url += "&" + a; } } function addEncodedUrl(b, a) { if (a) { addToUrl(b, encodeUrl(a)); } } function setColor(b, a, d) { if (a && typeof a == "object") { a = a[d % a.length]; } addToUrl("color_" + b, a); } function checkClient(b) { b = b.toLowerCase(); if (b.substring(0, 3) != "ca-") { b = "ca-" + b; } return b; } function decode64(input) { var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { return "invalid base64 url"; } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function setToNull(b) { var a = null; b.netseer_global_fparam = a; b.netseer_query = a; b.netseer_ad_frameborder = a; b.netseer_ad_format = a; b.netseer_page_url = a; b.netseer_output_format = a; b.netseer_language = a; b.netseer_gl = a; b.netseer_hints = a; b.netseer_safe = a; b.netseer_encoding = a; b.netseer_ad_output = a; b.netseer_max_num_ads = a; b.netseer_ad_channel = a; b.netseer_contents = a; b.netseer_adtest = a; b.netseer_kw_type = a; b.netseer_kw = a; b.netseer_num_radlinks = a; b.netseer_max_radlink_len = a; b.netseer_rl_filtering = a; b.netseer_rl_mode = a; b.netseer_rt = a; b.netseer_ad_type = a; b.netseer_image_size = a; b.netseer_skip = a; b.netseer_page_location = a; b.netseer_referrer_url = a; b.netseer_ad_region = a; b.netseer_ad_section = a; b.netseer_bid = a; b.netseer_cpa_choice = a; b.netseer_cust_age = a; b.netseer_cust_gender = a; b.netseer_cust_interests = a; b.netseer_cust_id = a; b.netseer_cust_job = a; b.netseer_cust_u_url = a; b.netseer_sim = a; b.netseer_color_bilboard = a; b.netseer_banner_id = a; b.netseer_network_id = a; b.netseer_tracking_url = a; b.netseer_tracking_url_encoded = a; b.netseer_page_url_key = a; b.netseer_search_current_url = a; b.netseer_page_params = a; b.netseer_page_url_base64 = a; b.netseer_landing_page_type = a; b.netseer_background_color = a; b.netseer_click_target = a; b.netseer_pixel_param1 = a; b.netseer_pixel_param2 = a; b.netseer_pixel_param3 = a; b.netseer_pixel_id = a; b.netseer_tag_id = a; b.netseer_client_id = a; b.netseer_task = a; b.netseer_creative_id = a; b.netseer_auction_id = a; b.netseer_slot_index = a; b.netseer_imp_type = a; b.netseer_ext_vid = a; b.netseer_advs = a; b.netseer_taglink_id = a; b.netseer_segment = a; b.netseer_iframe_buster = a; b.netseer_search_param = a; b.netseer_recirculation_sites = a; b.netseer_fire_on_trigger = a; b.netseer_redundant_params = a; b.netseer_url_pattern = a; b.netseer_theme_id = a; b.netseer_imp_src = a; b.netseer_endpoint = a; b.netseer_ad_height=a; b.netseer_ad_width=a; b.netseer_page_url_key=a; b.netseer_debug=a; b.netseer_pixel_cpa=a; b.netseer_search_term = a; b.netseer_visitor_cookie = a; b.netseer_cookie = a; b.netseer_hints = a; b.netseer_bing_formcode = a ; b.netseer_embed_external_pixels = a; b.netseer_referrer_search_term = a; b.netseer_referrer_domain = a; b.netseer_concept_group_id = a; b.netseer_ext_params = a; b.netseer_url_suffix = a; b.netseer_embed_style = a; b.netseer_append = a; b.netseer_pilot_id = a; b.netseer_rule_id = a; b.netseer_enforce_protocol = a; b.netseer_lead_params = a; b.netseer_ip = a; b.netseer_num_ads = a; b.netseer_ad_position = a; b.netseer_cpc = a; b.netseer_user_tgid = a; b.netseer_page_tgid = a; b.netseer_user_cgid = a; b.netseer_page_cgid = a; b.netseer_image_size = a; b.netseer_image_forced = a; b.netseer_cookie_matching = a; b.netseer_req_id = a; b.netseer_ext_script = a; b.netseer_pixel_trigger_mode = a; b.netseer_back_fill = a; for ( var c = 0; c < netseer_ap.length; c++) b[netseer_ap[c]] = a; for ( var c = 0; c < netseer_ap_encoded.length; c++) b[netseer_ap_encoded[c]] = a; } function makeOutput(netseer_task, netseer_ad_height, netseer_ad_width, netseer_iframe_buster, d, divId,netseer_cookie,netseer_imp_src,pixelId,netseerEndPoint,netseerCookieMatching,netseer_pixel_trigger_mode) { var cacheBuster = Math.random(); d = d.substring(0, 2083); d = d.replace(/%\w?$/, ""); if(d!=null){ d = d+"&t="+cacheBuster; } var outputCode; var finalUrl; if (netseer_task == 'lp') { finalUrl = check(d); outputCode = "<iframe id=\"netseer_landingpage_frame\" name=\"netseer_landingpage_frame\" width=" + check(netseer_ad_width) + " height=" + check(netseer_ad_height) + " src=" + check(d) + " frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" vspace=\"0\" hspace=\"0\" allowtransparency=\"true\" scrolling=\"no\"></iframe>"; document.getElementById(divId).innerHTML=outputCode; // document.write(outputCode); } else if (netseer_task == 'ad') { if (netseer_iframe_buster) { var destUrl = netseer_iframe_buster + "?forward_url=" + encodeUrl(d) + "&height=" + netseer_ad_height + "&width=" + netseer_ad_width; finalUrl = check(destUrl); outputCode = "<iframe name=\"netseer_ads_frame\" width=" + check(netseer_ad_width) + " height=" + check(netseer_ad_height) + " src=" + check(destUrl) + " frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" vspace=\"0\" hspace=\"0\" allowtransparency=\"true\" scrolling=\"no\"></iframe>"; document.getElementById(divId).innerHTML = outputCode; // document.write(outputCode); } else { finalUrl = check(d); outputCode = "<iframe name=\"netseer_ads_frame\" width=" + check(netseer_ad_width) + " height=" + check(netseer_ad_height) + " src=" + check(d) + " frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" vspace=\"0\" hspace=\"0\" allowtransparency=\"true\" scrolling=\"no\"></iframe>"; if(lw.netseer_append){ var nodeToAppend = document.getElementById(lw.netseer_append); if(nodeToAppend){ nodeToAppend.innerHTML = nodeToAppend.innerHTML + outputCode; } } else { // document.open(); document.getElementById(divId).innerHTML = outputCode; // document.write(outputCode); // document.close(); } } // running cookie matching for all impressions var isCookieMatched = readCookie('netseer_cm'); if(netseerCookieMatching!='false' && isCookieMatched!='done' && !netseer_cookie && netseer_imp_src != '10'){ loadNextPixel(); if(netseer_imp_src != '11' && netseer_imp_src != '12' && netseer_imp_src != '13' && netseer_imp_src != '14' && netseer_imp_src != '15' && netseer_imp_src != '16' && netseer_imp_src != '17' && netseer_imp_src != '18' && netseer_imp_src != '20' && netseer_imp_src != '21' && netseer_imp_src != '27'){ createCookie('netseer_cm', 'done', 15); } } } else if (netseer_task == 'px') { if (netseer_pixel_trigger_mode && netseer_pixel_trigger_mode == 'sync') loadPixel(d,pixelId,netseerEndPoint,divId); else bindReady(function () {loadPixel(d,pixelId,netseerEndPoint,divId);}); } } function bindReady(handler){ var called = false; function ready() { if (called) return; called = true; handler(); } if (window.addEventListener){ window.addEventListener('load', ready, false); } else { if ( document.addEventListener ) { // native event document.addEventListener( "DOMContentLoaded", ready, false ); } else if ( document.attachEvent ) { // IE try { var isFrame = window.frameElement != null; } catch(e) {} // IE, the document is not inside a frame if ( document.documentElement.doScroll && !isFrame ) { function tryScroll(){ if (called) return; try { document.documentElement.doScroll("left"); ready(); } catch(e) { setTimeout(tryScroll, 10); } } tryScroll(); } // IE, the document is inside a frame document.attachEvent("onreadystatechange", function(){ if ( document.readyState === "complete" ) { ready(); } }); } } /* // Old browsers if (window.addEventListener) window.addEventListener('load', ready, false); else if (window.attachEvent) window.attachEvent('onload', ready); else { var fn = window.onload; // very old browser, copy old onload window.onload = function() { // replace by new onload and call the old one fn && fn(); ready(); }; } */ } function doLoad() { alert( "The load event is executing" ); } function loadPixel(d,pixelId,netseerEndPoint,divId){ var pixel = new Image(); pixel.onload = loadNextPixel; pixel.onabort = loadNextPixel; pixel.onerror = loadNextPixel; pixel.src = d; if (typeof pixelId != 'undefined') embedPixel(pixelId,netseerEndPoint,divId); } /* function embedPixel(pixelId){ var pixelUrl = getServerEndPoint(window) + "/dsatserving2/servlet/pixel?pxid=" + pixelId; document.write('<scr'+'ipt type="text/javascript" src="'+pixelUrl+'"> </scr'+'ipt>'); } */ function embedPixel(pixelId,netseerEndPoint,divId){ var pixelUrl = netseerEndPoint + "/dsatserving2/servlet/pixel?pxid=" + pixelId; var outputCode = "<iframe name=\"nspx\" width=0 height=0 src=" + check(pixelUrl) + " frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" vspace=\"0\" hspace=\"0\" allowtransparency=\"true\" scrolling=\"no\"></iframe>"; var placeHolder = document.getElementById(divId); if(placeHolder){ placeHolder.innerHTML = outputCode; } else { var elemDiv = document.createElement('ins'); elemDiv.style.cssText = 'display:inline-table;border:none;height:0;width:0;;margin:0;padding:0;position:relative;visibility:hidden'; elemDiv.setAttribute("id", divId); elemDiv.innerHTML = outputCode; document.documentElement.lastChild.appendChild(elemDiv); } } function checkForRedundantParams(a){ if(a.netseer_redundant_params){ var parts = a.netseer_redundant_params.split(","); for (var i = 0; i < parts.length; i++) { var currentUrl = a.netseer_page_url; a.netseer_page_url = removeParamFromURL(currentUrl,parts[i]); } } } function getRealPart(a){ if(a.netseer_url_pattern){ var regex = new RegExp(a.netseer_url_pattern,"gi"); var matches = regex.exec(a.netseer_page_url); if(matches!=null){ a.netseer_page_url = decodeUrl(matches[1]); } } } function Main(lw) { var b = null, a = lw, d = document, g = new Date, e = g.getTime(), j = a.netseer_ad_format, src = d.location; a.netseer_page_params = ""; a.netseer_global_fparam = "true"; checkForRedundantParams(a); getRealPart(a); if (a.netseer_task == "lp") { a.netseer_ad_url = getServerEndPoint(a) + "/dsatserving2/servlet/search?"; // this part is done to make sure many to one mapping of tag to // landing page counts toward the referral tag var queryString = a.location.search.substring(1); if (queryString) { queryString = queryString.replace("tlid=", "tlidr="); } var TagLinkIdRef = getQuerystring("tlid", queryString, null, null); addToUrl("tlid", a.netseer_taglink_id); addToUrlNoKey(queryString); addEncodedUrl("url", a.netseer_page_url); } else if (a.netseer_task == "ad") { // these parameters are used for ads a.netseer_ad_url = getServerEndPoint(a) + "/dsatserving2/servlet/BannerServer?"; addToUrl("tagid", a.netseer_tag_id); addToUrl("tlid", a.netseer_taglink_id); addToUrl("cid", a.netseer_creative_id); addToUrl("cptgid",a.netseer_concept_group_id); addToUrl("plid",a.netseer_pilot_id); addToUrl("rlid",a.netseer_rule_id); addToUrl("utgid",a.netseer_user_tgid); addToUrl("ptgid",a.netseer_page_tgid); addToUrl("ucgid",a.netseer_user_cgid); addToUrl("pcgid",a.netseer_page_cgid); addToUrl("bft",a.netseer_back_fill); if (a.netseer_iframe_buster == null || a.netseer_iframe_buster == "") { addEncodedUrl("url", a.netseer_page_url); } addToUrl("q", a.netseer_query); } else if (a.netseer_task == "px") { a.netseer_ad_url = getServerEndPoint(a) + "/dsatserving2/servlet/log?"; //if (getQuerystring("cid", a.netseer_page_url, "") == "") { // addToUrl("tagid", a.netseer_tag_id); //} addToUrl("tagid", a.netseer_tag_id); addToUrl("tlid", a.netseer_taglink_id); addToUrl("pxid", a.netseer_pixel_id); if(!a.netseer_log_type){ a.netseer_log_type = "ltpx"; } addToUrl("nlt", a.netseer_log_type); // addToUrl("cookie", a.netseer_user_id); addToUrl("cid", a.netseer_creative_id); addToUrl("q", a.netseer_query); addEncodedUrl("url", a.netseer_page_url); addEncodedUrl("pxp1", a.netseer_pixel_param1); addEncodedUrl("pxp2", a.netseer_pixel_param2); addEncodedUrl("pxp3", a.netseer_pixel_param3); addEncodedUrl("pxcpa", a.netseer_pixel_cpa); // addToUrlNoKey(a.location.search.substring(1)); /* if(a.netseer_embed_external_pixels) { embedPixel(a.netseer_pixel_id); } */ } for ( var c = 0; c < netseer_ap.length; c++) { if (a[netseer_ap[c]] != null) addToUrl(netseer_ap_keys[c], a[netseer_ap[c]]); } for ( var c = 0; c < netseer_ap_encoded.length; c++) { if (a[netseer_ap_encoded[c]] != null) addEncodedUrl(netseer_ap_encoded_keys[c], a[netseer_ap_encoded[c]]); } if (a.netseer_segment) { addParam('segment', a.netseer_segment); } if (a.netseer_recirculation_sites) { addParam('sites', a.netseer_recirculation_sites); } if (a.netseer_bing_formcode) { addParam('bingformc', a.netseer_bing_formcode); } if (a.netseer_ext_params) { addExtParam(a.netseer_ext_params); } addEncodedUrl("params", a.netseer_page_params); addEncodedUrl("nslp", decodeUrl(a.netseer_lead_params)); addToUrl("pp", a.netseer_pcpm); addToUrl("bp", a.netseer_bcpm); addToUrl("auid", a.netseer_auction_id); addToUrl("sidx", a.netseer_slot_index); addToUrl("evid", a.netseer_ext_vid); if(a.netseer_cookie){ addToUrl("cookie", '0'); } addToUrl("impt", a.netseer_imp_type); addToUrl("advs", a.netseer_advs); addEncodedUrl("sep", a.netseer_search_param); addEncodedUrl("set", decodeUrl(a.netseer_search_term,true)); addEncodedUrl("trurl", decodeUrl(a.netseer_tracking_url)); addEncodedUrl("rfs", decodeUrl(a.netseer_referrer_search_term,true)); addEncodedUrl("rfd", a.netseer_referrer_domain); addToUrl("thid", a.netseer_theme_id); addToUrl("imps", a.netseer_imp_src); addToUrl("adh", a.netseer_ad_height); addToUrl("adw", a.netseer_ad_width); addToUrl("frd", a.netseer_first_request_date); addToUrl("ip", a.netseer_ip); addToUrl("cnads", a.netseer_num_ads); addToUrl("adpos", a.netseer_ad_position); addToUrl("cpc", a.netseer_cpc); addToUrl("cimg", a.netseer_image_size); addToUrl("cimgfrc", a.netseer_image_forced); addEncodedUrl("hints", a.netseer_hints); addEncodedUrl("extsct", decodeUrl(a.netseer_ext_script)); addEncodedUrl("inimgmv", decodeUrl(a.netseer_image_meta_val)); addEncodedUrl("inimga", decodeUrl(a.netseer_img_alt)); addEncodedUrl("inimgu", decodeUrl(a.netseer_image_src_url)); if (a.netseer_referrer_url && a.netseer_ad_url.length + a.netseer_referrer_url.length < 2000) { addEncodedUrl("ref", decodeUrl(a.netseer_referrer_url)); } makeOutput(a.netseer_task, a.netseer_ad_height, a.netseer_ad_width, a.netseer_iframe_buster, a.netseer_ad_url, lw.netseer_append_location,a.netseer_cookie,a.netseer_imp_src,a.netseer_pixel_id,getServerEndPoint(a),a.netseer_cookie_matching,a.netseer_pixel_trigger_mode); setToNull(a); } /* function onLoadCallBack() { makeOutput(window, document, window.netseer_ad_url); setToNull(window); } */ function getLocation(a, b) { var url_key = b.netseer_page_url_key; if (url_key == null) { try{ return b.top.location.href; }catch(err){ return b.location.href; } } else { var parts = url_key.split(","); var seperator = "&"; if (parts.length > 3) { seperator = parts[3]; } var url = decodeUrl(getQuerystring(parts[0], b.location, null, seperator)); if (parts.length > 1) { url = parts[1] + url; } if (parts.length > 2) { url = url + parts[2]; } return url; } } function markLoaded(){ isDOMLoaded = true; } function getSearchTerm(referrerUrl){ var query = null; if(isSubStr('.google.',referrerUrl)){ query = getQuerystring('q', referrerUrl, null); } else if(isSubStr('.bing.',referrerUrl)){ query = getQuerystring('q', referrerUrl, null); } else if(isSubStr('.yahoo.',referrerUrl)){ var p = getQuerystring('p', referrerUrl, null); if(p) { query = p; } else { var q = getQuerystring('q', referrerUrl, null); if(q) query = q; } } /* if(isSubStr('.aol.',referrerUrl)){ return getQuerystring('q', referrerUrl, null); } if(isSubStr('.ask.',referrerUrl)){ return getQuerystring('q', referrerUrl, null); } if(isSubStr('.hotbot.',referrerUrl)){ return getQuerystring('query', referrerUrl, null); } if(isSubStr('gigablast.',referrerUrl)){ return getQuerystring('q', referrerUrl, null); } if(isSubStr('.lycos.',referrerUrl)){ return getQuerystring('query', referrerUrl, null); } if(isSubStr('.dmoz.',referrerUrl)){ return getQuerystring('q', referrerUrl, null); } if(isSubStr('.yippy.',referrerUrl)){ return getQuerystring('query', referrerUrl, null); } if(isSubStr('dogpile.',referrerUrl)){ var regex = new RegExp("/Web/(.*)/"); var q = regex.exec(referrerUrl); return q; } if(isSubStr('.infospace.',referrerUrl)){ var regex = new RegExp("/Web/(.*)/"); var q = regex.exec(referrerUrl); return q; } */ if(query){ query = query.replace(/\+/g,' '); } return query; } function isSubStr(needle,haystack){ if(haystack && needle){ return haystack.indexOf(needle) != -1; } else { return false; } } function Init(lw) { var b = lw, a = document, d = a.location, g = a.referrer, e = null; if(b.netseer_first_request_date == e){ b.netseer_first_request_date = new Date().getTime(); } b.netseer_search_current_url = d; var referrerToUse = null; if(b.netseer_referrer_url){ referrerToUse = b.netseer_referrer_url; } if(g){ if(b.netseer_tag_id && b.netseer_tag_id==17744){ b.netseer_page_url = g; } if(!referrerToUse){ referrerToUse = g; } } if(referrerToUse){ try{ b.netseer_referrer_domain = referrerToUse.split('/')[2]; b.netseer_referrer_search_term = getSearchTerm(referrerToUse); } catch(err) {} } /* else if (!b.netseer_referrer_url) { b.netseer_referrer_url = ""; } */ //createCookie("netseer_v3_ref", Base64.encode(b.netseer_referrer_url),1000); b.netseer_cookie = isCookieBlocked(); if (b.netseer_page_url == e) { b.netseer_page_url = getLocation(a, b); b.netseer_last_modified_time = Date.parse(a.lastModified) / 1000; } else { b.netseer_page_location = d; b.netseer_page_url = decodeUrl(b.netseer_page_url); } if(b.netseer_url_suffix){ b.netseer_page_url = b.netseer_page_url + b.netseer_url_suffix; } } if(lw.netseer_fire_on_trigger){ return; } Init(lw); Main(lw); }; //netseerMainFunction();
JavaScript
(function(root) { var $ = root.jQuery; var BlockCookieName = 'azk-blocks'; var VoteEvent = { upvote: 10, downvote: 11, uninteresting: 12, misleading: 13, offensive: 14, repetitive: 15 }; root.azRegisterExtension('adFeedback', function(divName, pixels) { if ($ === undefined) return; var ad = $('#' + divName); var voteInProgress = false; var voteComplete = false; var castVoteForThisCreative = function(type) { if (pixels[type] !== undefined) { $('body').append("<img src='" + pixels[type] + "' height=0 width=0 />"); } }; $(function() { ad.addClass('adzerk-vote').append( "<div class='adzerk-vote-controls' style='display:none;'>" + "<div class='adzerk-vote-option adzerk-vote-up'><div class='adzerk-vote-icon'></div></div>" + "<div class='adzerk-vote-option adzerk-vote-down'><div class='adzerk-vote-icon'></div></div>" + "</div>" + "<div class='adzerk-vote-survey' style='display:none;'>" + "<form>" + "<span>No problem. We won't show you that ad again. Why didn't you like it?</span>" + "<ul>" + "<li><label><input type='radio' value='" + VoteEvent.uninteresting + "' name='downvoteReason' />Uninteresting</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.misleading + "' name='downvoteReason' />Misleading</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.offensive + "' name='downvoteReason' />Offensive</label></li>" + "<li><label><input type='radio' value='" + VoteEvent.repetitive + "' name='downvoteReason' />Repetitive</label></li>" + "</ul>" + "<a href='#' class='adzerk-vote-cancel'>Oops! I didn't mean to do this.</a>" + "</form>" + "</div>"); var controls = ad.find(".adzerk-vote-controls"); var survey = ad.find(".adzerk-vote-survey"); var showResponse = function() { voteInProgress = false; voteComplete = true; survey.hide(); var thanks = $("<div class='adzerk-vote-response'>Thanks!</div>"); thanks.appendTo(controls).hide().fadeIn(250).delay(3000).fadeOut(250, function() { $(this).remove(); }); }; // Show vote controls when hovering over ad ad.hover( function() { if (!voteInProgress) { controls.stop(true, true).fadeIn(250); } }, function() { if (!voteInProgress) { controls.stop(true, true).fadeOut(250); } } ); // When up arrow is clicked, display a thank you message controls.find(".adzerk-vote-up").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); castVoteForThisCreative(VoteEvent.upvote); showResponse(); } return false; }); // When down arrow is clicked, display the survey to ask why the user didn't like the ad controls.find(".adzerk-vote-down").click(function() { if (!voteInProgress && !voteComplete) { $(this).addClass("selected"); voteInProgress = true; survey.fadeIn(250); } return false; }); survey.find(".adzerk-vote-cancel").click(function() { controls.children("div").removeClass("selected"); voteInProgress = false; survey.fadeOut(250); return false; }); // When a survey option is selected, show a brief thank you and then hide it survey.find("li").click(function() { var vote = survey.find("input:checked").val() if (vote) { castVoteForThisCreative(VoteEvent.downvote); castVoteForThisCreative(vote); showResponse(); } }); }); }); })(this);
JavaScript
window['___jsl'] = window['___jsl'] || {};(window['___jsl']['ci'] = (window['___jsl']['ci'] || [])).push({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}});window['___jsl']=window['___jsl']||{};(window['___jsl']['ci'] = (window['___jsl']['ci'] || [])).push({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}}); /* [start] feature=taming */ var safeJSON=window.safeJSON; var tamings___=window.tamings___||[]; var bridge___; var caja___=window.caja___; var ___=window.___;; /* [end] feature=taming */ /* [start] feature=gapi-globals */ var gapi=window.gapi||{};gapi.client=window.gapi&&window.gapi.client||{}; ; ; /* [end] feature=gapi-globals */ /* [start] feature=globals */ var gadgets=window.gadgets||{},shindig=window.shindig||{},osapi=window.osapi=window.osapi||{},google=window.google||{}; ; ; /* [end] feature=globals */ /* [start] feature=core.config.base */ window['___cfg'] = window['___cfg'] || window['___gcfg'];; if(!window.gadgets["config"]){gadgets.config=function(){var f; var h={}; var b={}; function c(j,l){for(var k in l){if(!l.hasOwnProperty(k)){continue }if(typeof j[k]==="object"&&typeof l[k]==="object"){c(j[k],l[k]) }else{j[k]=l[k] }}}function i(){var j=document.scripts||document.getElementsByTagName("script"); if(!j||j.length==0){return null }var m; if(f.u){for(var k=0; !m&&k<j.length; ++k){var l=j[k]; if(l.src&&l.src.indexOf(f.u)==0){m=l }}}if(!m){m=j[j.length-1] }if(!m.src){return null }return m }function a(j){var k=""; if(j.nodeType==3||j.nodeType==4){k=j.nodeValue }else{if(j.innerText){k=j.innerText }else{if(j.innerHTML){k=j.innerHTML }else{if(j.firstChild){var l=[]; for(var m=j.firstChild; m; m=m.nextSibling){l.push(a(m)) }k=l.join("") }}}}return k }function e(k){if(!k){return{} }var j; while(k.charCodeAt(k.length-1)==0){k=k.substring(0,k.length-1) }try{j=(new Function("return ("+k+"\n)"))() }catch(l){}if(typeof j==="object"){return j }try{j=(new Function("return ({"+k+"\n})"))() }catch(l){}return typeof j==="object"?j:{} }function g(n){var p=window.___cfg; if(p){c(n,p) }var o=i(); if(!o){return }var k=a(o); var j=e(k); if(f.f&&f.f.length==1){var m=f.f[0]; if(!j[m]){var l={}; l[f.f[0]]=j; j=l }}c(n,j) }function d(o){for(var l in h){if(h.hasOwnProperty(l)){var n=h[l]; for(var m=0,k=n.length; m<k; ++m){o(l,n[m]) }}}}return{register:function(l,k,j,m){var n=h[l]; if(!n){n=[]; h[l]=n }n.push({validators:k||{},callback:j,callOnUpdate:m}) },get:function(j){if(j){return b[j]||{} }return b },init:function(k,j){f=window.___jsl||{}; c(b,k); g(b); var l=window.___config||{}; c(b,l); d(function(q,p){var o=b[q]; if(o&&!j){var m=p.validators; for(var n in m){if(m.hasOwnProperty(n)){if(!m[n](o[n])){throw new Error('Invalid config value "'+o[n]+'" for parameter "'+n+'" in component "'+q+'"') }}}}if(p.callback){p.callback(b) }}) },update:function(k,p){var o=(window.gapi&&window.gapi["config"]&&window.gapi["config"]["update"]); if(!p&&o){o(k) }var n=[]; d(function(q,j){if(k.hasOwnProperty(q)||(p&&b&&b[q])){if(j.callback&&j.callOnUpdate){n.push(j.callback) }}}); b=p?{}:b||{}; c(b,k); for(var m=0,l=n.length; m<l; ++m){n[m](b) }}} }() }else{gadgets.config=window.gadgets["config"]; gadgets.config.register=gadgets.config.register; gadgets.config.get=gadgets.config.get; gadgets.config.init=gadgets.config.init; gadgets.config.update=gadgets.config.update };; /* [end] feature=core.config.base */ /* [start] feature=core.log */ gadgets.log=(function(){var e=1; var a=2; var f=3; var c=4; var d=function(i){b(e,i) }; gadgets.warn=function(i){b(a,i) }; gadgets.error=function(i){b(f,i) }; gadgets.debug=function(i){}; gadgets.setLogLevel=function(i){h=i }; function b(k,i){if(k<h||!g){return }if(k===a&&g.warn){g.warn(i) }else{if(k===f&&g.error){try{g.error(i) }catch(j){}}else{if(g.log){g.log(i) }}}}d.INFO=e; d.WARNING=a; d.NONE=c; var h=e; var g=window.console?window.console:window.opera?window.opera.postError:undefined; return d })();; ; /* [end] feature=core.log */ /* [start] feature=core.config */ (function(){gadgets.config.EnumValidator=function(d){var c=[]; if(arguments.length>1){for(var b=0,a; (a=arguments[b]); ++b){c.push(a) }}else{c=d }return function(f){for(var e=0,g; (g=c[e]); ++e){if(f===c[e]){return true }}return false } }; gadgets.config.RegExValidator=function(a){return function(b){return a.test(b) } }; gadgets.config.ExistsValidator=function(a){return typeof a!=="undefined" }; gadgets.config.NonEmptyStringValidator=function(a){return typeof a==="string"&&a.length>0 }; gadgets.config.BooleanValidator=function(a){return typeof a==="boolean" }; gadgets.config.LikeValidator=function(a){return function(c){for(var d in a){if(a.hasOwnProperty(d)){var b=a[d]; if(!b(c[d])){return false }}}return true } } })();; /* [end] feature=core.config */ /* [start] feature=core.util.base */ gadgets.util=gadgets.util||{}; (function(){gadgets.util.makeClosure=function(d,f,e){var c=[]; for(var b=2,a=arguments.length; b<a; ++b){c.push(arguments[b]) }return function(){var g=c.slice(); for(var k=0,h=arguments.length; k<h; ++k){g.push(arguments[k]) }return f.apply(d,g) } }; gadgets.util.makeEnum=function(b){var c,a,d={}; for(c=0; (a=b[c]); ++c){d[a]=a }return d } })();; /* [end] feature=core.util.base */ /* [start] feature=core.util.dom */ gadgets.util=gadgets.util||{}; (function(){var c="http://www.w3.org/1999/xhtml"; function b(f,e){var h=e||{}; for(var g in h){if(h.hasOwnProperty(g)){f[g]=h[g] }}}function d(g,f){var e=["<",g]; var i=f||{}; for(var h in i){if(i.hasOwnProperty(h)){e.push(" "); e.push(h); e.push('="'); e.push(gadgets.util.escapeString(i[h])); e.push('"') }}e.push("></"); e.push(g); e.push(">"); return e.join("") }function a(f){var g=""; if(f.nodeType==3||f.nodeType==4){g=f.nodeValue }else{if(f.innerText){g=f.innerText }else{if(f.innerHTML){g=f.innerHTML }else{if(f.firstChild){var e=[]; for(var h=f.firstChild; h; h=h.nextSibling){e.push(a(h)) }g=e.join("") }}}}return g }gadgets.util.createElement=function(f){var e; if((!document.body)||document.body.namespaceURI){try{e=document.createElementNS(c,f) }catch(g){}}return e||document.createElement(f) }; gadgets.util.createIframeElement=function(g){var i=gadgets.util.createElement("iframe"); try{var e=d("iframe",g); var f=gadgets.util.createElement(e); if(f&&((!i)||((f.tagName==i.tagName)&&(f.namespaceURI==i.namespaceURI)))){i=f }}catch(h){}b(i,g); return i }; gadgets.util.getBodyElement=function(){if(document.body){return document.body }try{var f=document.getElementsByTagNameNS(c,"body"); if(f&&(f.length==1)){return f[0] }}catch(e){}return document.documentElement||document }; gadgets.util.getInnerText=function(e){return a(e) } })();; /* [end] feature=core.util.dom */ /* [start] feature=core.util.event */ gadgets.util=gadgets.util||{}; (function(){gadgets.util.attachBrowserEvent=function(c,b,d,a){if(typeof c.addEventListener!="undefined"){c.addEventListener(b,d,a) }else{if(typeof c.attachEvent!="undefined"){c.attachEvent("on"+b,d) }else{gadgets.warn("cannot attachBrowserEvent: "+b) }}}; gadgets.util.removeBrowserEvent=function(c,b,d,a){if(c.removeEventListener){c.removeEventListener(b,d,a) }else{if(c.detachEvent){c.detachEvent("on"+b,d) }else{gadgets.warn("cannot removeBrowserEvent: "+b) }}} })();; /* [end] feature=core.util.event */ /* [start] feature=core.util.onload */ gadgets.util=gadgets.util||{}; (function(){var a=[]; gadgets.util.registerOnLoadHandler=function(b){a.push(b) }; gadgets.util.runOnLoadHandlers=function(){for(var c=0,b=a.length; c<b; ++c){a[c]() }} })();; /* [end] feature=core.util.onload */ /* [start] feature=core.util.string */ gadgets.util=gadgets.util||{}; (function(){var a={0:false,10:true,13:true,34:true,39:true,60:true,62:true,92:true,8232:true,8233:true,65282:true,65287:true,65308:true,65310:true,65340:true}; function b(c,d){return String.fromCharCode(d) }gadgets.util.escape=function(c,g){if(!c){return c }else{if(typeof c==="string"){return gadgets.util.escapeString(c) }else{if(typeof c==="Array"){for(var f=0,d=c.length; f<d; ++f){c[f]=gadgets.util.escape(c[f]) }}else{if(typeof c==="object"&&g){var e={}; for(var h in c){if(c.hasOwnProperty(h)){e[gadgets.util.escapeString(h)]=gadgets.util.escape(c[h],true) }}return e }}}}return c }; gadgets.util.escapeString=function(g){if(!g){return g }var d=[],f,h; for(var e=0,c=g.length; e<c; ++e){f=g.charCodeAt(e); h=a[f]; if(h===true){d.push("&#",f,";") }else{if(h!==false){d.push(g.charAt(e)) }}}return d.join("") }; gadgets.util.unescapeString=function(c){if(!c){return c }return c.replace(/&#([0-9]+);/g,b) } })();; /* [end] feature=core.util.string */ /* [start] feature=core.util.urlparams */ gadgets.util=gadgets.util||{}; (function(){var a=null; function b(e){var f; var c=e.indexOf("?"); var d=e.indexOf("#"); if(d===-1){f=e.substr(c+1) }else{f=[e.substr(c+1,d-c-1),"&",e.substr(d+1)].join("") }return f.split("&") }gadgets.util.getUrlParameters=function(p){var d=typeof p==="undefined"; if(a!==null&&d){return a }var l={}; var f=b(p||window.location.href); var n=window.decodeURIComponent?decodeURIComponent:unescape; for(var h=0,g=f.length; h<g; ++h){var m=f[h].indexOf("="); if(m===-1){continue }var c=f[h].substring(0,m); var o=f[h].substring(m+1); o=o.replace(/\+/g," "); try{l[c]=n(o) }catch(k){}}if(d){a=l }return l }; gadgets.util.getUrlParameters() })();; /* [end] feature=core.util.urlparams */ /* [start] feature=core.util */ gadgets.util=gadgets.util||{}; (function(){var b={}; var a={}; function c(d){b=d["core.util"]||{} }if(gadgets.config){gadgets.config.register("core.util",null,c) }gadgets.util.getFeatureParameters=function(d){return typeof b[d]==="undefined"?null:b[d] }; gadgets.util.hasFeature=function(d){return typeof b[d]!=="undefined" }; gadgets.util.getServices=function(){return a } })();; /* [end] feature=core.util */ /* [start] feature=shindig.auth */ shindig.Auth=function(){var authToken=null; var trusted=null; function addParamsToToken(urlParams){var args=authToken.split("&"); for(var i=0; i<args.length; i++){var nameAndValue=args[i].split("="); if(nameAndValue.length===2){var name=nameAndValue[0]; var value=nameAndValue[1]; if(value==="$"){value=encodeURIComponent(urlParams[name]); args[i]=name+"="+value }}}authToken=args.join("&") }function init(configuration){var urlParams=gadgets.util.getUrlParameters(); var config=configuration["shindig.auth"]||{}; if(config.authToken){authToken=config.authToken }else{if(urlParams.st){authToken=urlParams.st }}if(authToken!==null){addParamsToToken(urlParams) }if(config.trustedJson){trusted=(eval("("+config.trustedJson+")")) }}gadgets.config.register("shindig.auth",null,init); return{getSecurityToken:function(){return authToken },updateSecurityToken:function(newToken){authToken=newToken },getTrustedData:function(){return trusted }} };; shindig.auth=new shindig.Auth();; /* [end] feature=shindig.auth */ /* [start] feature=core.json */ if(window.JSON&&window.JSON.parse&&window.JSON.stringify){gadgets.json=(function(){var a=/___$/; function b(d,e){var c=this[d]; return c }return{parse:function(d){try{return window.JSON.parse(d) }catch(c){return false }},stringify:function(d){var h=window.JSON.stringify; function f(e){return h.call(this,e,b) }var g=(Array.prototype.toJSON&&h([{x:1}])==='"[{\\"x\\": 1}]"')?f:h; try{return g(d,function(i,e){return !a.test(i)?e:void 0 }) }catch(c){return null }}} })() };; ; if(!(window.JSON&&window.JSON.parse&&window.JSON.stringify)){gadgets.json=function(){function f(n){return n<10?"0"+n:n }Date.prototype.toJSON=function(){return[this.getUTCFullYear(),"-",f(this.getUTCMonth()+1),"-",f(this.getUTCDate()),"T",f(this.getUTCHours()),":",f(this.getUTCMinutes()),":",f(this.getUTCSeconds()),"Z"].join("") }; var m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"}; function stringify(value){var a,i,k,l,r=/[\"\\\x00-\x1f\x7f-\x9f]/g,v; switch(typeof value){case"string":return r.test(value)?'"'+value.replace(r,function(a){var c=m[a]; if(c){return c }c=a.charCodeAt(); return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16) })+'"':'"'+value+'"'; case"number":return isFinite(value)?String(value):"null"; case"boolean":case"null":return String(value); case"object":if(!value){return"null" }a=[]; if(typeof value.length==="number"&&!value.propertyIsEnumerable("length")){l=value.length; for(i=0; i<l; i+=1){a.push(stringify(value[i])||"null") }return"["+a.join(",")+"]" }for(k in value){if(/___$/.test(k)){continue }if(value.hasOwnProperty(k)){if(typeof k==="string"){v=stringify(value[k]); if(v){a.push(stringify(k)+":"+v) }}}}return"{"+a.join(",")+"}" }return"" }return{stringify:stringify,parse:function(text){if(/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/b-u]/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){return eval("("+text+")") }return false }} }() };; gadgets.json.flatten=function(c){var d={}; if(c===null||c===undefined){return d }for(var a in c){if(c.hasOwnProperty(a)){var b=c[a]; if(null===b||undefined===b){continue }d[a]=(typeof b==="string")?b:gadgets.json.stringify(b) }}return d };; /* [end] feature=core.json */ /* [start] feature=core.io */ gadgets.io=function(){var config={}; var oauthState; function makeXhr(){var x; var wrapperXhr=window.shindig&&window.shindig["xhrwrapper"]&&window.shindig["xhrwrapper"]["createXHR"]; if(wrapperXhr){return wrapperXhr() }else{if(typeof ActiveXObject!="undefined"){x=new ActiveXObject("Msxml2.XMLHTTP"); if(!x){x=new ActiveXObject("Microsoft.XMLHTTP") }return x }else{if(typeof XMLHttpRequest!="undefined"||window.XMLHttpRequest){return new window.XMLHttpRequest() }else{throw ("no xhr available") }}}}function hadError(xobj,callback){if(xobj.readyState!==4){return true }try{if(xobj.status!==200){var error=(""+xobj.status); if(xobj.responseText){error=error+" "+xobj.responseText }callback({errors:[error],rc:xobj.status,text:xobj.responseText}); return true }}catch(e){callback({errors:[e.number+" Error not specified"],rc:e.number,text:e.description}); return true }return false }function processNonProxiedResponse(url,callback,params,xobj){if(hadError(xobj,callback)){return }var data={body:xobj.responseText}; callback(transformResponseData(params,data)) }var UNPARSEABLE_CRUFT="throw 1; < don't be evil' >"; function processResponse(url,callback,params,xobj){if(hadError(xobj,callback)){return }var txt=xobj.responseText; var offset=txt.indexOf(UNPARSEABLE_CRUFT)+UNPARSEABLE_CRUFT.length; if(offset<UNPARSEABLE_CRUFT.length){return }txt=txt.substr(offset); var data=eval("("+txt+")"); data=data[url]; if(data.oauthState){oauthState=data.oauthState }if(data.st){shindig.auth.updateSecurityToken(data.st) }callback(transformResponseData(params,data)) }function transformResponseData(params,data){var resp={text:data.body,rc:data.rc||200,headers:data.headers,oauthApprovalUrl:data.oauthApprovalUrl,oauthError:data.oauthError,oauthErrorText:data.oauthErrorText,errors:[]}; if(resp.rc<200||resp.rc>=400){resp.errors=[resp.rc+" Error"] }else{if(resp.text){if(resp.rc>=300&&resp.rc<400){params.CONTENT_TYPE="TEXT" }switch(params.CONTENT_TYPE){case"JSON":case"FEED":resp.data=gadgets.json.parse(resp.text); if(!resp.data){resp.errors.push("500 Failed to parse JSON"); resp.rc=500; resp.data=null }break; case"DOM":var dom; if(typeof ActiveXObject!="undefined"){dom=new ActiveXObject("Microsoft.XMLDOM"); dom.async=false; dom.validateOnParse=false; dom.resolveExternals=false; if(!dom.loadXML(resp.text)){resp.errors.push("500 Failed to parse XML"); resp.rc=500 }else{resp.data=dom }}else{var parser=new DOMParser(); dom=parser.parseFromString(resp.text,"text/xml"); if("parsererror"===dom.documentElement.nodeName){resp.errors.push("500 Failed to parse XML"); resp.rc=500 }else{resp.data=dom }}break; default:resp.data=resp.text; break }}}return resp }function makeXhrRequest(realUrl,proxyUrl,callback,paramData,method,params,processResponseFunction,opt_headers){var xhr=makeXhr(); if(proxyUrl.indexOf("//")==0){proxyUrl=document.location.protocol+proxyUrl }xhr.open(method,proxyUrl,true); if(callback){xhr.onreadystatechange=gadgets.util.makeClosure(null,processResponseFunction,realUrl,callback,params,xhr) }if(paramData!==null){var contentTypeHeader="Content-Type"; var contentType="application/x-www-form-urlencoded"; if(typeof opt_headers==="string"){contentType=opt_headers; opt_headers={} }var headers=opt_headers||{}; if(!headers[contentTypeHeader]){headers[contentTypeHeader]=contentType }for(var headerName in headers){xhr.setRequestHeader(headerName,headers[headerName]) }}xhr.send(paramData) }function respondWithPreload(postData,params,callback){if(gadgets.io.preloaded_&&postData.httpMethod==="GET"){for(var i=0; i<gadgets.io.preloaded_.length; i++){var preload=gadgets.io.preloaded_[i]; if(preload&&(preload.id===postData.url)){delete gadgets.io.preloaded_[i]; if(preload.rc!==200){callback({rc:preload.rc,errors:[preload.rc+" Error"]}) }else{if(preload.oauthState){oauthState=preload.oauthState }var resp={body:preload.body,rc:preload.rc,headers:preload.headers,oauthApprovalUrl:preload.oauthApprovalUrl,oauthError:preload.oauthError,oauthErrorText:preload.oauthErrorText,errors:[]}; callback(transformResponseData(params,resp)) }return true }}}return false }function init(configuration){config=configuration["core.io"]||{} }gadgets.config.register("core.io",null,init); return{makeRequest:function(url,callback,opt_params){var params=opt_params||{}; var httpMethod=params.METHOD||"GET"; var refreshInterval=params.REFRESH_INTERVAL; var auth,st; if(params.AUTHORIZATION&&params.AUTHORIZATION!=="NONE"){auth=params.AUTHORIZATION.toLowerCase(); st=shindig.auth.getSecurityToken() }else{if(httpMethod==="GET"&&refreshInterval===undefined){refreshInterval=3600 }}var signOwner=true; if(typeof params.OWNER_SIGNED!=="undefined"){signOwner=params.OWNER_SIGNED }var signViewer=true; if(typeof params.VIEWER_SIGNED!=="undefined"){signViewer=params.VIEWER_SIGNED }var headers=params.HEADERS||{}; if(httpMethod==="POST"&&!headers["Content-Type"]){headers["Content-Type"]="application/x-www-form-urlencoded" }var urlParams=gadgets.util.getUrlParameters(); var paramData={url:url,httpMethod:httpMethod,headers:gadgets.io.encodeValues(headers,false),postData:params.POST_DATA||"",authz:auth||"",st:st||"",contentType:params.CONTENT_TYPE||"TEXT",numEntries:params.NUM_ENTRIES||"3",getSummaries:!!params.GET_SUMMARIES,signOwner:signOwner,signViewer:signViewer,gadget:urlParams.url,container:urlParams.container||urlParams.synd||"default",bypassSpecCache:gadgets.util.getUrlParameters()["nocache"]||"",getFullHeaders:!!params.GET_FULL_HEADERS}; if(auth==="oauth"||auth==="signed"){if(gadgets.io.oauthReceivedCallbackUrl_){paramData.OAUTH_RECEIVED_CALLBACK=gadgets.io.oauthReceivedCallbackUrl_; gadgets.io.oauthReceivedCallbackUrl_=null }paramData.oauthState=oauthState||""; for(var opt in params){if(params.hasOwnProperty(opt)){if(opt.indexOf("OAUTH_")===0){paramData[opt]=params[opt] }}}}var proxyUrl=config.jsonProxyUrl.replace("%host%",document.location.host); if(!respondWithPreload(paramData,params,callback)){if(httpMethod==="GET"&&refreshInterval>0){var extraparams="?refresh="+refreshInterval+"&"+gadgets.io.encodeValues(paramData); makeXhrRequest(url,proxyUrl+extraparams,callback,null,"GET",params,processResponse) }else{makeXhrRequest(url,proxyUrl,callback,gadgets.io.encodeValues(paramData),"POST",params,processResponse) }}},makeNonProxiedRequest:function(relativeUrl,callback,opt_params,opt_headers){var params=opt_params||{}; makeXhrRequest(relativeUrl,relativeUrl,callback,params.POST_DATA,params.METHOD,params,processNonProxiedResponse,opt_headers) },clearOAuthState:function(){oauthState=undefined },encodeValues:function(fields,opt_noEscaping){var escape=!opt_noEscaping; var buf=[]; var first=false; for(var i in fields){if(fields.hasOwnProperty(i)&&!/___$/.test(i)){if(!first){first=true }else{buf.push("&") }buf.push(escape?encodeURIComponent(String(i)):i); buf.push("="); buf.push(escape?encodeURIComponent(String(fields[i])):fields[i]) }}return buf.join("") },getProxyUrl:function(url,opt_params){var params=opt_params||{}; var refresh=params.REFRESH_INTERVAL; if(refresh===undefined){refresh="3600" }var urlParams=gadgets.util.getUrlParameters(); var rewriteMimeParam=params.rewriteMime?"&rewriteMime="+encodeURIComponent(String(params.rewriteMime)):""; var ret=config.proxyUrl.replace("%url%",encodeURIComponent(url)).replace("%host%",document.location.host).replace("%rawurl%",url).replace("%refresh%",encodeURIComponent(String(refresh))).replace("%gadget%",encodeURIComponent(urlParams.url)).replace("%container%",encodeURIComponent(urlParams.container||urlParams.synd||"default")).replace("%rewriteMime%",rewriteMimeParam); if(ret.indexOf("//")==0){ret=window.location.protocol+ret }return ret }} }(); gadgets.io.RequestParameters=gadgets.util.makeEnum(["METHOD","CONTENT_TYPE","POST_DATA","HEADERS","AUTHORIZATION","NUM_ENTRIES","GET_SUMMARIES","GET_FULL_HEADERS","REFRESH_INTERVAL","OAUTH_SERVICE_NAME","OAUTH_USE_TOKEN","OAUTH_TOKEN_NAME","OAUTH_REQUEST_TOKEN","OAUTH_REQUEST_TOKEN_SECRET","OAUTH_RECEIVED_CALLBACK"]); gadgets.io.MethodType=gadgets.util.makeEnum(["GET","POST","PUT","DELETE","HEAD"]); gadgets.io.ContentType=gadgets.util.makeEnum(["TEXT","DOM","JSON","FEED"]); gadgets.io.AuthorizationType=gadgets.util.makeEnum(["NONE","SIGNED","OAUTH"]);; /* [end] feature=core.io */ /* [start] feature=core.prefs */ (function(){var i=null; var j={}; var f=gadgets.util.escapeString; var d={}; var h={}; var e="en"; var b="US"; var a=0; function c(){var l=gadgets.util.getUrlParameters(); for(var k in l){if(l.hasOwnProperty(k)){if(k.indexOf("up_")===0&&k.length>3){j[k.substr(3)]=String(l[k]) }else{if(k==="country"){b=l[k] }else{if(k==="lang"){e=l[k] }else{if(k==="mid"){a=l[k] }}}}}}}function g(){for(var k in h){if(typeof j[k]==="undefined"){j[k]=h[k] }}}gadgets.Prefs=function(){if(!i){c(); g(); i=this }return i }; gadgets.Prefs.setInternal_=function(n,p){var o=false; if(typeof n==="string"){if(!j.hasOwnProperty(n)||j[n]!==p){o=true }j[n]=p }else{for(var m in n){if(n.hasOwnProperty(m)){var l=n[m]; if(!j.hasOwnProperty(m)||j[m]!==l){o=true }j[m]=l }}}return o }; gadgets.Prefs.setMessages_=function(k){d=k }; gadgets.Prefs.setDefaultPrefs_=function(k){h=k }; gadgets.Prefs.prototype.getString=function(k){if(k===".lang"){k="lang" }return j[k]?f(j[k]):"" }; gadgets.Prefs.prototype.setDontEscape_=function(){f=function(l){return l } }; gadgets.Prefs.prototype.getInt=function(k){var l=parseInt(j[k],10); return isNaN(l)?0:l }; gadgets.Prefs.prototype.getFloat=function(k){var l=parseFloat(j[k]); return isNaN(l)?0:l }; gadgets.Prefs.prototype.getBool=function(k){var l=j[k]; if(l){return l==="true"||l===true||!!parseInt(l,10) }return false }; gadgets.Prefs.prototype.set=function(k,l){throw new Error("setprefs feature required to make this call.") }; gadgets.Prefs.prototype.getArray=function(n){var o=j[n]; if(o){var k=o.split("|"); for(var m=0,l=k.length; m<l; ++m){k[m]=f(k[m].replace(/%7C/g,"|")) }return k }return[] }; gadgets.Prefs.prototype.setArray=function(k,l){throw new Error("setprefs feature required to make this call.") }; gadgets.Prefs.prototype.getMsg=function(k){return d[k]||"" }; gadgets.Prefs.prototype.getCountry=function(){return b }; gadgets.Prefs.prototype.getLang=function(){return e }; gadgets.Prefs.prototype.getModuleId=function(){return a } })();; /* [end] feature=core.prefs */ /* [start] feature=core.legacy */ var JSON=window.JSON||gadgets.json; var _IG_Prefs=(function(){var a=null; var b=function(){if(!a){a=new gadgets.Prefs(); a.setDontEscape_() }return a }; b._parseURL=gadgets.Prefs.parseUrl; return b })(); function _IG_Fetch_wrapper(b,a){b(a.data?a.data:"") }function _IG_FetchContent(b,g,c){var f=c||{}; if(f.refreshInterval){f.REFRESH_INTERVAL=f.refreshInterval }else{f.REFRESH_INTERVAL=3600 }for(var e in f){var d=f[e]; delete f[e]; f[e.toUpperCase()]=d }var a=gadgets.util.makeClosure(null,_IG_Fetch_wrapper,g); gadgets.io.makeRequest(b,a,f) }function _IG_FetchXmlContent(b,e,c){var d=c||{}; if(d.refreshInterval){d.REFRESH_INTERVAL=d.refreshInterval }else{d.REFRESH_INTERVAL=3600 }d.CONTENT_TYPE="DOM"; var a=gadgets.util.makeClosure(null,_IG_Fetch_wrapper,e); gadgets.io.makeRequest(b,a,d) }function _IG_FetchFeedAsJSON(b,f,c,a,d){var e=d||{}; e.CONTENT_TYPE="FEED"; e.NUM_ENTRIES=c; e.GET_SUMMARIES=a; gadgets.io.makeRequest(b,function(j){j.data=j.data||{}; if(j.errors&&j.errors.length>0){j.data.ErrorMsg=j.errors[0] }if(j.data.link){j.data.URL=b }if(j.data.title){j.data.Title=j.data.title }if(j.data.description){j.data.Description=j.data.description }if(j.data.link){j.data.Link=j.data.link }if(j.data.items&&j.data.items.length>0){j.data.Entry=j.data.items; for(var h=0; h<j.data.Entry.length; ++h){var i=j.data.Entry[h]; i.Title=i.title; i.Link=i.link; i.Summary=i.summary||i.description; i.Date=i.pubDate }}for(var g=0; g<j.data.Entry.length; ++g){var i=j.data.Entry[g]; i.Date=(i.Date/1000) }f(j.data) },e) }function _IG_GetCachedUrl(a,b){var c=b||{}; c.REFRESH_INTERVAL=3600; if(c.refreshInterval){c.REFRESH_INTERVAL=c.refreshInterval }return gadgets.io.getProxyUrl(a,c) }function _IG_GetImageUrl(a,b){return _IG_GetCachedUrl(a,b) }function _IG_GetImage(b){var a=document.createElement("img"); a.src=_IG_GetCachedUrl(b); return a }function _IG_RegisterOnloadHandler(a){gadgets.util.registerOnLoadHandler(a) }function _IG_Callback(b,c){var a=arguments; return function(){var d=Array.prototype.slice.call(arguments); b.apply(null,d.concat(Array.prototype.slice.call(a,1))) } }var _args=gadgets.util.getUrlParameters; function _gel(a){return document.getElementById?document.getElementById(a):null }function _gelstn(a){if(a==="*"&&document.all){return document.all }return document.getElementsByTagName?document.getElementsByTagName(a):[] }function _gelsbyregex(d,f){var c=_gelstn(d); var e=[]; for(var b=0,a=c.length; b<a; ++b){if(f.test(c[b].id)){e.push(c[b]) }}return e }function _esc(a){return window.encodeURIComponent?encodeURIComponent(a):escape(a) }function _unesc(a){return window.decodeURIComponent?decodeURIComponent(a):unescape(a) }function _hesc(a){return gadgets.util.escapeString(a) }function _striptags(a){return a.replace(/<\/?[^>]+>/g,"") }function _trim(a){return a.replace(/^\s+|\s+$/g,"") }function _toggle(a){a=(typeof a==="string")?_gel(a):a; if(a!==null){if(a.style.display.length===0||a.style.display==="block"){a.style.display="none" }else{if(a.style.display==="none"){a.style.display="block" }}}}var _uid=(function(){var a=0; return function(){return a++ } })(); function _min(d,c){return(d<c?d:c) }function _max(d,c){return(d>c?d:c) }function _exportSymbols(a,c){var m=window; var f=a.split("."); for(var h=0,g=f.length; h<g; h++){var b=f[h]; m[b]=m[b]||{}; m=m[b] }for(var e=0,d=c.length; e<d; e+=2){m[c[e]]=c[e+1] }}function _IG_AddDOMEventHandler(c,b,a){gadgets.warn("_IG_AddDOMEventHandler not implemented - see SHINDIG-198") };; /* [end] feature=core.legacy */ /* [start] feature=core.tracking */ (function(){function e(b,c,a){b={msg:b||"",line:a||0,jsUrl:0==window.location.href.indexOf(c)?"-top-":c,fullUrl:window.location};try{if(++window._varz_numerrors,gadgets&&!(3<f)){c={};c[gadgets.io.RequestParameters.METHOD]=gadgets.io.MethodType.GET;a=encodeURIComponent||escape;var d=gadgets.util.getUrlParameters(),e=d.container||d.synd,g=d.gadget||d.url,k=["/gadgets/evthdlr?t=err&gadget=",a(g),"&container=",a(e),"&jsurl=",a(b.jsUrl),"&line=",a(b.line),"&session=",h,"&count=",f,"&msg=",a(b.msg)];gadgets.io.makeNonProxiedRequest(k.join(""), null,c);f++}}catch(l){}}window._varz_numerrors=0;var h=(new Date).getTime(),f=0;-1==window.location.href.indexOf("&debug=1")&&-1==window.location.href.indexOf("?debug=1")&&(window.onerror=e)})(); ; /* [end] feature=core.tracking */ /* [start] feature=core */ (function(){var l=null,p=function(){function e(a){a=(""+a).match(E);return!a?l:new b(q(a[1]),q(a[2]),q(a[3]),q(a[4]),q(a[5]),q(a[6]),q(a[7]))}function z(a,e){return"string"==typeof a?encodeURI(a).replace(e,B):l}function B(a){a=a.charCodeAt(0);return"%"+"0123456789ABCDEF".charAt(a>>4&15)+"0123456789ABCDEF".charAt(a&15)}function y(a){if(a===l)return l;for(var a=a.replace(/(^|\/)\.(?:\/|$)/g,"$1").replace(/\/{2,}/g,"/"),e=m,b;(b=a.replace(e,"$1"))!=a;a=b);return a}function A(a,e){var b=a.R(),g=e.K();g?b.fa(e.j): g=e.V();g?b.ca(e.m):g=e.W();g?b.da(e.k):g=e.Y();var m=e.g,k=y(m);if(g)b.ba(e.T()),k=k&&k.replace(x,"");else if(g=!!m){if(47!==k.charCodeAt(0))var k=y(b.g||"").replace(x,""),s=k.lastIndexOf("/")+1,k=y((s?k.substring(0,s):"")+y(m)).replace(x,"")}else k=k&&k.replace(x,""),k!==m&&b.G(k);g?b.G(k):g=e.Z();g?b.M(e.l):g=e.X();g&&b.ea(e.n);return b}function b(a,e,b,g,m,k,s){this.j=a;this.m=e;this.k=b;this.h=g;this.g=m;this.l=k;this.n=s}function q(a){return"string"==typeof a&&0<a.length?a:l}var m=RegExp(/(\/|^)(?:[^./][^/]*|\.{2,}(?:[^./][^/]*)|\.{3,}[^/]*)\/\.\.(?:\/|$)/), x=/^(?:\.\.\/)*(?:\.\.$)?/;b.prototype.toString=function(){var a=[];l!==this.j&&a.push(this.j,":");l!==this.k&&(a.push("//"),l!==this.m&&a.push(this.m,"@"),a.push(this.k),l!==this.h&&a.push(":",this.h.toString()));l!==this.g&&a.push(this.g);l!==this.l&&a.push("?",this.l);l!==this.n&&a.push("#",this.n);return a.join("")};b.prototype.R=function(){return new b(this.j,this.m,this.k,this.h,this.g,this.l,this.n)};b.prototype.U=function(){return this.j&&decodeURIComponent(this.j).toLowerCase()};b.prototype.fa= function(a){this.j=a?a:l};b.prototype.K=function(){return l!==this.j};b.prototype.ca=function(a){this.m=a?a:l};b.prototype.V=function(){return l!==this.m};b.prototype.da=function(a){this.k=a?a:l;this.G(this.g)};b.prototype.W=function(){return l!==this.k};b.prototype.T=function(){return this.h&&decodeURIComponent(this.h)};b.prototype.ba=function(a){if(a){a=Number(a);if(a!==(a&65535))throw Error("Bad port number "+a);this.h=""+a}else this.h=l};b.prototype.Y=function(){return l!==this.h};b.prototype.S= function(){return this.g&&decodeURIComponent(this.g)};b.prototype.G=function(a){a?(a=""+a,this.g=!this.k||/^\//.test(a)?a:"/"+a):this.g=l};b.prototype.M=function(a){this.l=a?a:l};b.prototype.Z=function(){return l!==this.l};b.prototype.aa=function(a){if("object"===typeof a&&!(a instanceof Array)&&(a instanceof Object||"[object Array]"!==Object.prototype.toString.call(a))){var e=[],b=-1,g;for(g in a){var m=a[g];"string"===typeof m&&(e[++b]=g,e[++b]=m)}a=e}for(var e=[],b="",k=0;k<a.length;)g=a[k++], m=a[k++],e.push(b,encodeURIComponent(g.toString())),b="&",m&&e.push("=",encodeURIComponent(m.toString()));this.l=e.join("")};b.prototype.ea=function(a){this.n=a?a:l};b.prototype.X=function(){return l!==this.n};var E=/^(?:([^:/?#]+):)?(?:\/\/(?:([^/?#]*)@)?([^/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/,D=/[#\/\?@]/g,F=/[\#\?]/g;b.parse=e;b.create=function(a,e,m,g,q,k,s){a=new b(z(a,D),z(e,D),"string"==typeof m?encodeURIComponent(m):l,0<g?g.toString():l,z(q,F),l,"string"==typeof s?encodeURIComponent(s): l);k&&("string"===typeof k?a.M(k.replace(/[^?&=0-9A-Za-z_\-~.%]/g,B)):a.aa(k));return a};b.$=A;b.ja=y;b.ua={oa:function(a){return/\.html$/.test(e(a).S())?"text/html":"application/javascript"},$:function(a,b){return a?A(e(a),e(b)).toString():""+b}};return b}();"undefined"!==typeof window&&(window.URI=p);var L={e:{NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,HTML:12,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10,MEDIA_QUERY:13}};L.atype=L.e; L.w={"*::class":9,"*::dir":0,"*::draggable":0,"*::hidden":0,"*::id":4,"*::inert":0,"*::itemprop":0,"*::itemref":6,"*::itemscope":0,"*::lang":0,"*::onblur":2,"*::onchange":2,"*::onclick":2,"*::ondblclick":2,"*::onerror":2,"*::onfocus":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2,"*::onmouseup":2,"*::onreset":2,"*::onscroll":2,"*::onselect":2,"*::onsubmit":2,"*::ontouchcancel":2,"*::ontouchend":2,"*::ontouchenter":2, "*::ontouchleave":2,"*::ontouchmove":2,"*::ontouchstart":2,"*::onunload":2,"*::spellcheck":0,"*::style":3,"*::title":0,"*::translate":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"audio::controls":0,"audio::loop":0,"audio::mediagroup":5, "audio::muted":0,"audio::preload":0,"audio::src":1,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2,"button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"canvas::height":0,"canvas::width":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0, "colgroup::width":0,"command::checked":0,"command::command":5,"command::disabled":0,"command::icon":1,"command::label":0,"command::radiogroup":0,"command::type":0,"data::value":0,"del::cite":1,"del::datetime":0,"details::open":0,"dir::compact":0,"div::align":0,"dl::compact":0,"fieldset::disabled":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0,"form::method":0,"form::name":7,"form::novalidate":0,"form::onreset":2,"form::onsubmit":2, "form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0,"img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0, "input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::inputmode":0,"input::ismap":0,"input::list":5,"input::max":0,"input::maxlength":0,"input::min":0,"input::multiple":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::placeholder":0,"input::readonly":0,"input::required":0,"input::size":0,"input::src":1,"input::step":0,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0, "label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2,"legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"menu::label":0,"menu::type":0,"meter::high":0,"meter::low":0,"meter::max":0,"meter::min":0,"meter::value":0,"ol::compact":0,"ol::reversed":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"output::for":6,"output::name":8,"p::align":0, "pre::width":0,"progress::max":0,"progress::min":0,"progress::value":0,"q::cite":1,"select::autocomplete":0,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::required":0,"select::size":0,"select::tabindex":0,"source::type":0,"table::align":0,"table::bgcolor":0,"table::border":0,"table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0, "tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::autocomplete":0,"textarea::cols":0,"textarea::disabled":0,"textarea::inputmode":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2,"textarea::onfocus":2,"textarea::onselect":2,"textarea::placeholder":0,"textarea::readonly":0, "textarea::required":0,"textarea::rows":0,"textarea::tabindex":0,"textarea::wrap":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0,"tr::valign":0, "track::default":0,"track::kind":0,"track::label":0,"track::srclang":0,"ul::compact":0,"ul::type":0,"video::controls":0,"video::height":0,"video::loop":0,"video::mediagroup":5,"video::muted":0,"video::poster":1,"video::preload":0,"video::src":1,"video::width":0};L.ATTRIBS=L.w;L.c={OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128,VIRTUALIZED:256};L.eflags=L.c; L.f={a:0,abbr:0,acronym:0,address:0,applet:272,area:2,article:0,aside:0,audio:0,b:0,base:274,basefont:274,bdi:0,bdo:0,big:0,blockquote:0,body:305,br:2,button:0,canvas:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,command:2,data:0,datalist:0,dd:1,del:0,details:0,dfn:0,dialog:272,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,figcaption:0,figure:0,font:0,footer:0,form:0,frame:274,frameset:272,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:305,header:0,hgroup:0,hr:2,html:305,i:0,iframe:4,img:2,input:2,ins:0,isindex:274, kbd:0,keygen:274,label:0,legend:0,li:1,link:274,map:0,mark:0,menu:0,meta:274,meter:0,nav:0,nobr:0,noembed:276,noframes:276,noscript:276,object:272,ol:0,optgroup:0,option:1,output:0,p:1,param:274,pre:0,progress:0,q:0,s:0,samp:0,script:84,section:0,select:0,small:0,source:2,span:0,strike:0,strong:0,style:148,sub:0,summary:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,time:0,title:280,tr:1,track:2,tt:0,u:0,ul:0,"var":0,video:0,wbr:2};L.ELEMENTS=L.f; L.O={a:"HTMLAnchorElement",abbr:"HTMLElement",acronym:"HTMLElement",address:"HTMLElement",applet:"HTMLAppletElement",area:"HTMLAreaElement",article:"HTMLElement",aside:"HTMLElement",audio:"HTMLAudioElement",b:"HTMLElement",base:"HTMLBaseElement",basefont:"HTMLBaseFontElement",bdi:"HTMLElement",bdo:"HTMLElement",big:"HTMLElement",blockquote:"HTMLQuoteElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",center:"HTMLElement", cite:"HTMLElement",code:"HTMLElement",col:"HTMLTableColElement",colgroup:"HTMLTableColElement",command:"HTMLCommandElement",data:"HTMLElement",datalist:"HTMLDataListElement",dd:"HTMLElement",del:"HTMLModElement",details:"HTMLDetailsElement",dfn:"HTMLElement",dialog:"HTMLDialogElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",dt:"HTMLElement",em:"HTMLElement",fieldset:"HTMLFieldSetElement",figcaption:"HTMLElement",figure:"HTMLElement",font:"HTMLFontElement",footer:"HTMLElement", form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",h2:"HTMLHeadingElement",h3:"HTMLHeadingElement",h4:"HTMLHeadingElement",h5:"HTMLHeadingElement",h6:"HTMLHeadingElement",head:"HTMLHeadElement",header:"HTMLElement",hgroup:"HTMLElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",i:"HTMLElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",ins:"HTMLModElement",isindex:"HTMLUnknownElement",kbd:"HTMLElement",keygen:"HTMLKeygenElement", label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",mark:"HTMLElement",menu:"HTMLMenuElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",nav:"HTMLElement",nobr:"HTMLElement",noembed:"HTMLElement",noframes:"HTMLElement",noscript:"HTMLElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement", progress:"HTMLProgressElement",q:"HTMLQuoteElement",s:"HTMLElement",samp:"HTMLElement",script:"HTMLScriptElement",section:"HTMLElement",select:"HTMLSelectElement",small:"HTMLElement",source:"HTMLSourceElement",span:"HTMLSpanElement",strike:"HTMLElement",strong:"HTMLElement",style:"HTMLStyleElement",sub:"HTMLElement",summary:"HTMLElement",sup:"HTMLElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",td:"HTMLTableDataCellElement",textarea:"HTMLTextAreaElement",tfoot:"HTMLTableSectionElement", th:"HTMLTableHeaderCellElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",tt:"HTMLElement",u:"HTMLElement",ul:"HTMLUListElement","var":"HTMLElement",video:"HTMLVideoElement",wbr:"HTMLElement"};L.ELEMENT_DOM_INTERFACES=L.O;L.N={NOT_LOADED:0,SAME_DOCUMENT:1,NEW_DOCUMENT:2};L.ueffects=L.N; L.J={"a::href":2,"area::href":2,"audio::src":1,"blockquote::cite":0,"command::icon":1,"del::cite":0,"form::action":2,"img::src":1,"input::src":1,"ins::cite":0,"q::cite":0,"video::poster":1,"video::src":1};L.URIEFFECTS=L.J;L.L={UNSANDBOXED:2,SANDBOXED:1,DATA:0};L.ltypes=L.L;L.I={"a::href":2,"area::href":2,"audio::src":2,"blockquote::cite":2,"command::icon":1,"del::cite":2,"form::action":2,"img::src":1,"input::src":1,"ins::cite":2,"q::cite":2,"video::poster":1,"video::src":2};L.LOADERTYPES=L.I; "undefined"!==typeof window&&(window.html4=L);var Q=function(e){function z(f){if(G.hasOwnProperty(f))return G[f];var a=f.match(R);return a?String.fromCharCode(parseInt(a[1],10)):(a=f.match(S))?String.fromCharCode(parseInt(a[1],16)):H&&T.test(f)?(H.innerHTML="&"+f+";",a=H.textContent,G[f]=a):"&"+f+";"}function B(f,a){return z(a)}function y(f){return f.replace(U,B)}function A(f){return(""+f).replace(V,"&amp;").replace(M,"&lt;").replace(N,"&gt;").replace(W,"&#34;")}function b(f){return f.replace(X,"&amp;$1").replace(M,"&lt;").replace(N,"&gt;")} function q(f){var a={z:f.z||f.cdata,A:f.A||f.comment,B:f.B||f.endDoc,r:f.r||f.endTag,d:f.d||f.pcdata,F:f.F||f.rcdata,H:f.H||f.startDoc,v:f.v||f.startTag};return function(f,e){var c;var b=/(<\/|<\!--|<[!?]|[&<>])/g;c=f+"";if(Y)c=c.split(b);else{for(var i=[],h=0,n;(n=b.exec(c))!==l;)i.push(c.substring(h,n.index)),i.push(n[0]),h=n.index+n[0].length;i.push(c.substring(h));c=i}x(a,c,0,{o:!1,C:!1},e)}}function m(f,a,d,e,c){return function(){x(f,a,d,e,c)}}function x(f,a,d,j,c){try{f.H&&0==d&&f.H(c);for(var b, i,h,n=a.length;d<n;){var r=a[d++],k=a[d];switch(r){case "&":Z.test(k)?(f.d&&f.d("&"+k,c,t,m(f,a,d,j,c)),d++):f.d&&f.d("&amp;",c,t,m(f,a,d,j,c));break;case "</":if(b=/^([-\w:]+)[^\'\"]*/.exec(k))if(b[0].length===k.length&&">"===a[d+1])d+=2,h=b[1].toLowerCase(),f.r&&f.r(h,c,t,m(f,a,d,j,c));else{var g=a,o=d,q=f,s=c,v=t,y=j,x=D(g,o);x?(q.r&&q.r(x.name,s,v,m(q,g,o,y,s)),d=x.next):d=g.length}else f.d&&f.d("&lt;/",c,t,m(f,a,d,j,c));break;case "<":if(b=/^([-\w:]+)\s*\/?/.exec(k))if(b[0].length===k.length&& ">"===a[d+1]){d+=2;h=b[1].toLowerCase();f.v&&f.v(h,[],c,t,m(f,a,d,j,c));var z=e.f[h];z&O&&(d=E(a,{name:h,next:d,c:z},f,c,t,j))}else{var g=a,o=f,q=c,s=t,v=j,C=D(g,d);C?(o.v&&o.v(C.name,C.P,q,s,m(o,g,C.next,v,q)),d=C.c&O?E(g,C,o,q,s,v):C.next):d=g.length}else f.d&&f.d("&lt;",c,t,m(f,a,d,j,c));break;case "<\!--":if(!j.C){for(i=d+1;i<n&&!(">"===a[i]&&/--$/.test(a[i-1]));i++);if(i<n){if(f.A){var A=a.slice(d,i).join("");f.A(A.substr(0,A.length-2),c,t,m(f,a,i+1,j,c))}d=i+1}else j.C=!0}j.C&&f.d&&f.d("&lt;!--", c,t,m(f,a,d,j,c));break;case "<!":if(/^\w/.test(k)){if(!j.o){for(i=d+1;i<n&&">"!==a[i];i++);i<n?d=i+1:j.o=!0}j.o&&f.d&&f.d("&lt;!",c,t,m(f,a,d,j,c))}else f.d&&f.d("&lt;!",c,t,m(f,a,d,j,c));break;case "<?":if(!j.o){for(i=d+1;i<n&&">"!==a[i];i++);i<n?d=i+1:j.o=!0}j.o&&f.d&&f.d("&lt;?",c,t,m(f,a,d,j,c));break;case ">":f.d&&f.d("&gt;",c,t,m(f,a,d,j,c));break;case "":break;default:f.d&&f.d(r,c,t,m(f,a,d,j,c))}}f.B&&f.B(c)}catch(B){if(B!==t)throw B;}}function E(a,w,d,j,c,u){var i=a.length;I.hasOwnProperty(w.name)|| (I[w.name]=RegExp("^"+w.name+"(?:[\\s\\/]|$)","i"));for(var h=I[w.name],n=w.next,r=w.next+1;r<i&&!("</"===a[r-1]&&h.test(a[r]));r++);r<i&&(r-=1);i=a.slice(n,r).join("");if(w.c&e.c.CDATA)d.z&&d.z(i,j,c,m(d,a,r,u,j));else if(w.c&e.c.RCDATA)d.F&&d.F(b(i),j,c,m(d,a,r,u,j));else throw Error("bug");return r}function D(a,b){var d=/^([-\w:]+)/.exec(a[b]),j={};j.name=d[1].toLowerCase();j.c=e.f[j.name];for(var c=a[b].substr(d[0].length),u=b+1,i=a.length;u<i&&">"!==a[u];u++)c+=a[u];if(!(i<=u)){for(var h=[];""!== c;)if(d=$.exec(c))if(d[4]&&!d[5]||d[6]&&!d[7]){for(var d=d[4]||d[6],n=!1,c=[c,a[u++]];u<i;u++){if(n){if(">"===a[u])break}else 0<=a[u].indexOf(d)&&(n=!0);c.push(a[u])}if(i<=u)break;c=c.join("")}else{var n=d[1].toLowerCase(),r;if(d[2]){r=d[3];var g=r.charCodeAt(0);if(34===g||39===g)r=r.substr(1,r.length-2);r=y(r.replace(aa,""))}else r="";h.push(n,r);c=c.substr(d[0].length)}else c=c.replace(/^[\s\S][^a-z\s]*/,"");j.P=h;j.next=u+1;return j}}function F(a){function b(a,f){j||f.push(a)}var d,j;return q({startDoc:function(){d= [];j=!1},startTag:function(c,b,i){if(!j&&e.f.hasOwnProperty(c)){var h=e.f[c];if(!(h&e.c.FOLDABLE)){var n=a(c,b);if(n){if("object"!==typeof n)throw Error("tagPolicy did not return object (old API?)");if("attribs"in n)b=n.attribs;else throw Error("tagPolicy gave no attribs");var g;"tagName"in n?(g=n.tagName,n=e.f[g]):(g=c,n=h);if(h&e.c.OPTIONAL_ENDTAG){var k=d[d.length-1];k&&k.D===c&&(k.t!==g||c!==g)&&i.push("</",k.t,">")}h&e.c.EMPTY||d.push({D:c,t:g});i.push("<",g);c=0;for(k=b.length;c<k;c+=2){var m= b[c],w=b[c+1];w!==l&&void 0!==w&&i.push(" ",m,'="',A(w),'"')}i.push(">");h&e.c.EMPTY&&!(n&e.c.EMPTY)&&i.push("</",g,">")}else j=!(h&e.c.EMPTY)}}},endTag:function(a,f){if(j)j=!1;else if(e.f.hasOwnProperty(a)){var b=e.f[a];if(!(b&(e.c.EMPTY|e.c.FOLDABLE))){if(b&e.c.OPTIONAL_ENDTAG)for(b=d.length;0<=--b;){var h=d[b].D;if(h===a)break;if(!(e.f[h]&e.c.OPTIONAL_ENDTAG))return}else for(b=d.length;0<=--b&&d[b].D!==a;);if(!(0>b)){for(h=d.length;--h>b;){var g=d[h].t;e.f[g]&e.c.OPTIONAL_ENDTAG||f.push("</",g, ">")}b<d.length&&(a=d[b].t);d.length=b;f.push("</",a,">")}}}},pcdata:b,rcdata:b,cdata:b,endDoc:function(a){for(;d.length;d.length--)a.push("</",d[d.length-1].t,">")}})}function a(a,b,d,e,c){if(!c)return l;try{var g=p.parse(""+a);if(g&&(!g.K()||ba.test(g.U()))){var i=c(g,b,d,e);return i?i.toString():l}}catch(h){}return l}function v(a,b,d,e,c){d||a(b+" removed",{Q:"removed",tagName:b});if(e!==c){var g="changed";e&&!c?g="removed":!e&&c&&(g="added");a(b+"."+d+" "+g,{Q:g,tagName:b,ia:d,oldValue:e,newValue:c})}} function J(a,b,d){b=b+"::"+d;if(a.hasOwnProperty(b))return a[b];b="*::"+d;if(a.hasOwnProperty(b))return a[b]}function g(b,g,d,j,c){for(var k=0;k<g.length;k+=2){var i=g[k],h=g[k+1],n=h,m=l,o;if((o=b+"::"+i,e.w.hasOwnProperty(o))||(o="*::"+i,e.w.hasOwnProperty(o)))m=e.w[o];if(m!==l)switch(m){case e.e.NONE:break;case e.e.SCRIPT:h=l;c&&v(c,b,i,n,h);break;case e.e.STYLE:if("undefined"===typeof s){h=l;c&&v(c,b,i,n,h);break}var q=[];s(h,{declaration:function(b,c){var f=b.toLowerCase();P(f,c,d?function(b){return a(b, e.N.ga,e.L.ha,{TYPE:"CSS",CSS_PROP:f},d)}:l);c.length&&q.push(f+": "+c.join(" "))}});h=0<q.length?q.join(" ; "):l;c&&v(c,b,i,n,h);break;case e.e.ID:case e.e.IDREF:case e.e.IDREFS:case e.e.GLOBAL_NAME:case e.e.LOCAL_NAME:case e.e.CLASSES:h=j?j(h):h;c&&v(c,b,i,n,h);break;case e.e.URI:h=a(h,J(e.J,b,i),J(e.I,b,i),{TYPE:"MARKUP",XML_ATTR:i,XML_TAG:b},d);c&&v(c,b,i,n,h);break;case e.e.URI_FRAGMENT:h&&"#"===h.charAt(0)?(h=h.substring(1),h=j?j(h):h,h!==l&&void 0!==h&&(h="#"+h)):h=l;c&&v(c,b,i,n,h);break; default:h=l,c&&v(c,b,i,n,h)}else h=l,c&&v(c,b,i,n,h);g[k+1]=h}return g}function K(a,b,d){return function(j,c){if(e.f[j]&e.c.UNSAFE)d&&v(d,j,void 0,void 0,void 0);else return{attribs:g(j,c,a,b,d)}}}function k(a,b){var d=[];F(b)(a,d);return d.join("")}var s,P;"undefined"!==typeof window&&(s=window.parseCssDeclarations,P=window.sanitizeCssProperty);var G={lt:"<",LT:"<",gt:">",GT:">",amp:"&",AMP:"&",quot:'"',apos:"'",nbsp:"\u00a0"},R=/^#(\d+)$/,S=/^#x([0-9A-Fa-f]+)$/,T=/^[A-Za-z][A-za-z0-9]+$/,H="undefined"!== typeof window&&window.document?window.document.createElement("textarea"):l,aa=/\0/g,U=/&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g,Z=/^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/,V=/&/g,X=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,M=/[<]/g,N=/>/g,W=/\"/g,$=/^\s*([-.:\w]+)(?:\s*(=)\s*((")[^"]*("|$)|(')[^']*('|$)|(?=[a-z][-\w]*\s*=)|[^"'\s]*))?/i,Y=3==="a,b".split(/(,)/).length,O=e.c.CDATA|e.c.RCDATA,t={},I={},ba=/^(?:https?|mailto)$/i,o={};o.ka=o.escapeAttrib=A;o.la=o.makeHtmlSanitizer=F;o.ma=o.makeSaxParser= q;o.na=o.makeTagPolicy=K;o.pa=o.normalizeRCData=b;o.qa=o.sanitize=function(a,b,d,e){return k(a,K(b,d,e))};o.ra=o.sanitizeAttribs=g;o.sa=o.sanitizeWithPolicy=k;o.ta=o.unescapeEntities=y;return o}(L),ca=Q.sanitize;"undefined"!==typeof window&&(window.html=Q,window.html_sanitize=ca);})(); ; /* [end] feature=core */ /* [start] feature=gapi.util-globals */ gapi.util=window.gapi&&window.gapi.util||{}; ; /* [end] feature=gapi.util-globals */ /* [start] feature=gapi.util.getOrigin */ gapi.util.getOrigin=function(a){if(!a)return"";a=a.split("#")[0].split("?")[0];a=a.toLowerCase();0==a.indexOf("//")&&(a=window.location.protocol+a);/^[\w\-]*:\/\//.test(a)||(a=window.location.href);var b=a.substring(a.indexOf("://")+3),c=b.indexOf("/");-1!=c&&(b=b.substring(0,c));a=a.substring(0,a.indexOf("://"));if("http"!==a&&"https"!==a&&"chrome-extension"!==a&&"file"!==a)throw Error("Invalid URI scheme in origin");var c="",d=b.indexOf(":");if(-1!=d){var e=b.substring(d+1),b=b.substring(0,d);if("http"=== a&&"80"!==e||"https"===a&&"443"!==e)c=":"+e}return a+"://"+b+c}; ; /* [end] feature=gapi.util.getOrigin */ /* [start] feature=rpc */ gadgets.rpctx=gadgets.rpctx||{}; if(!gadgets.rpctx.wpm){gadgets.rpctx.wpm=function(){var e,d; var c=true; function b(h,j,g){if(typeof window.addEventListener!="undefined"){window.addEventListener(h,j,g) }else{if(typeof window.attachEvent!="undefined"){window.attachEvent("on"+h,j) }}if(h==="message"){window.___jsl=window.___jsl||{}; var i=window.___jsl; i.RPMQ=i.RPMQ||[]; i.RPMQ.push(j) }}function a(h,i,g){if(window.removeEventListener){window.removeEventListener(h,i,g) }else{if(window.detachEvent){window.detachEvent("on"+h,i) }}}function f(h){var i=gadgets.json.parse(h.data); if(!i||!i.f){return }gadgets.debug("gadgets.rpc.receive("+window.name+"): "+h.data); var g=gadgets.rpc.getTargetOrigin(i.f); if(c&&(typeof h.origin!=="undefined"?h.origin!==g:h.domain!==/^.+:\/\/([^:]+).*/.exec(g)[1])){gadgets.error("Invalid rpc message origin. "+g+" vs "+(h.origin||"")); return }e(i,h.origin) }return{getCode:function(){return"wpm" },isParentVerifiable:function(){return true },init:function(h,i){function g(k){var j=k&&k.rpc||{}; if(String(j.disableForceSecure)==="true"){c=false }}gadgets.config.register("rpc",null,g); e=h; d=i; b("message",f,false); d("..",true); return true },setup:function(h,g){d(h,true); return true },call:function(h,k,j){var g=gadgets.rpc.getTargetOrigin(h); var i=gadgets.rpc._getTargetWin(h); if(g){window.setTimeout(function(){var l=gadgets.json.stringify(j); gadgets.debug("gadgets.rpc.send("+window.name+"): "+l); i.postMessage(l,g) },0) }else{if(h!=".."){gadgets.error("No relay set (used as window.postMessage targetOrigin), cannot send cross-domain message") }}return true }} }() };; gadgets.rpctx.ifpc = gadgets.rpctx.wpm; ; if(!window.gadgets||!window.gadgets["rpc"]){gadgets.rpc=function(){var M="__cb"; var S=""; var T="__ack"; var f=500; var G=10; var b="|"; var u="callback"; var g="origin"; var r="referer"; var s="legacy__"; var q={}; var W={}; var D={}; var B={}; var z=0; var l={}; var m={}; var d={}; var n={}; var E={}; var e=null; var p=null; var A=(window.top!==window.self); var v=window.name; var J=function(){}; var P=0; var Y=1; var a=2; var x=window.console; var V=x&&x.log&&function(ae){x.log(ae) }||function(){}; var R=(function(){function ae(af){return function(){V(af+": call ignored") } }return{getCode:function(){return"noop" },isParentVerifiable:function(){return true },init:ae("init"),setup:ae("setup"),call:ae("call")} })(); if(gadgets.util){d=gadgets.util.getUrlParameters() }function K(){if(d.rpctx=="flash"){return gadgets.rpctx.flash }if(d.rpctx=="rmr"){return gadgets.rpctx.rmr }var ae=typeof window.postMessage==="function"?gadgets.rpctx.wpm:typeof window.postMessage==="object"?gadgets.rpctx.wpm:window.ActiveXObject?(gadgets.rpctx.flash?gadgets.rpctx.flash:(gadgets.rpctx.nix?gadgets.rpctx.nix:gadgets.rpctx.ifpc)):navigator.userAgent.indexOf("WebKit")>0?gadgets.rpctx.rmr:navigator.product==="Gecko"?gadgets.rpctx.frameElement:gadgets.rpctx.ifpc; if(!ae){ae=R }return ae }function k(aj,ah){if(n[aj]){return }var af=H; if(!ah){af=R }n[aj]=af; var ae=E[aj]||[]; for(var ag=0; ag<ae.length; ++ag){var ai=ae[ag]; ai.t=F(aj); af.call(aj,ai.f,ai) }E[aj]=[] }var I=false,U=false; function N(){if(U){return }function ae(){I=true }if(typeof window.addEventListener!="undefined"){window.addEventListener("unload",ae,false) }else{if(typeof window.attachEvent!="undefined"){window.attachEvent("onunload",ae) }}U=true }function j(ae,ai,af,ah,ag){if(!B[ai]||B[ai]!==af){gadgets.error("Invalid gadgets.rpc token. "+B[ai]+" vs "+af); J(ai,a) }ag.onunload=function(){if(m[ai]&&!I){J(ai,Y); gadgets.rpc.removeReceiver(ai) }}; N(); ah=gadgets.json.parse(decodeURIComponent(ah)) }function Z(ak,af){if(ak&&typeof ak.s==="string"&&typeof ak.f==="string"&&ak.a instanceof Array){if(B[ak.f]){if(B[ak.f]!==ak.t){gadgets.error("Invalid gadgets.rpc token. "+B[ak.f]+" vs "+ak.t); J(ak.f,a) }}if(ak.s===T){window.setTimeout(function(){k(ak.f,true) },0); return }if(ak.c){ak[u]=function(al){var am=ak.g?s:""; gadgets.rpc.call(ak.f,am+M,null,ak.c,al) } }if(af){var ag=t(af); ak[g]=af; var ah=ak.r,aj; try{aj=t(ah) }catch(ai){}if(!ah||aj!=ag){ah=af }ak[r]=ah }var ae=(q[ak.s]||q[S]).apply(ak,ak.a); if(ak.c&&typeof ae!=="undefined"){gadgets.rpc.call(ak.f,M,null,ak.c,ae) }}}function t(ag){if(!ag){return"" }ag=((ag.split("#"))[0].split("?"))[0]; ag=ag.toLowerCase(); if(ag.indexOf("//")==0){ag=window.location.protocol+ag }if(ag.indexOf("://")==-1){ag=window.location.protocol+"//"+ag }var ah=ag.substring(ag.indexOf("://")+3); var ae=ah.indexOf("/"); if(ae!=-1){ah=ah.substring(0,ae) }var aj=ag.substring(0,ag.indexOf("://")); if(aj!=="http"&&aj!=="https"&&aj!=="chrome-extension"&&aj!=="file"){throw Error("Invalid URI scheme in origin") }var ai=""; var ak=ah.indexOf(":"); if(ak!=-1){var af=ah.substring(ak+1); ah=ah.substring(0,ak); if((aj==="http"&&af!=="80")||(aj==="https"&&af!=="443")){ai=":"+af }}return aj+"://"+ah+ai }function C(af,ae){return"/"+af+(ae?b+ae:"") }function y(ah){if(ah.charAt(0)=="/"){var af=ah.indexOf(b); var ag=af>0?ah.substring(1,af):ah.substring(1); var ae=af>0?ah.substring(af+1):null; return{id:ag,origin:ae} }else{return null }}function ad(ag){if(typeof ag==="undefined"||ag===".."){return window.parent }var af=y(ag); if(af){return window.top.frames[af.id] }ag=String(ag); var ae=window.frames[ag]; if(ae){return ae }ae=document.getElementById(ag); if(ae&&ae.contentWindow){return ae.contentWindow }return null }function L(ah){var ag=null; var ae=O(ah); if(ae){ag=ae }else{var af=y(ah); if(af){ag=af.origin }else{if(ah==".."){ag=d.parent }else{ag=document.getElementById(ah).src }}}return t(ag) }var H=K(); q[S]=function(){V("Unknown RPC service: "+this["s"]) }; q[M]=function(af,ae){var ag=l[af]; if(ag){delete l[af]; ag.call(this,ae) }}; function X(ag,ae){if(m[ag]===true){return }if(typeof m[ag]==="undefined"){m[ag]=0 }var af=ad(ag); if(ag===".."||af!=null){if(H.setup(ag,ae)===true){m[ag]=true; return }}if(m[ag]!==true&&m[ag]++<G){window.setTimeout(function(){X(ag,ae) },f) }else{n[ag]=R; m[ag]=true }}function O(af){var ae=W[af]; if(ae&&ae.substring(0,1)==="/"){if(ae.substring(1,2)==="/"){ae=document.location.protocol+ae }else{ae=document.location.protocol+"//"+document.location.host+ae }}return ae }function ac(af,ae,ag){if(ae&&!/http(s)?:\/\/.+/.test(ae)){if(ae.indexOf("//")==0){ae=window.location.protocol+ae }else{if(ae.charAt(0)=="/"){ae=window.location.protocol+"//"+window.location.host+ae }else{if(ae.indexOf("://")==-1){ae=window.location.protocol+"//"+ae }}}}W[af]=ae; if(typeof ag!=="undefined"){D[af]=!!ag }}function F(ae){return B[ae] }function c(ae,af){af=af||""; B[ae]=String(af); X(ae,af) }function ab(af){var ae=af.passReferrer||""; var ag=ae.split(":",2); e=ag[0]||"none"; p=ag[1]||"origin" }function aa(ae){if(Q(ae)){H=gadgets.rpctx.ifpc||R; H.init(Z,k) }}function Q(ae){return String(ae.useLegacyProtocol)==="true" }function h(af,ae){function ag(aj){var ai=aj&&aj.rpc||{}; ab(ai); var ah=ai.parentRelayUrl||""; ah=t(d.parent||ae)+ah; ac("..",ah,Q(ai)); aa(ai); c("..",af) }if(!d.parent&&ae){ag({}); return }gadgets.config.register("rpc",null,ag) }function o(af,aj,al){var ai=null; if(af.charAt(0)!="/"){if(!gadgets.util){return }ai=document.getElementById(af); if(!ai){throw new Error("Cannot set up gadgets.rpc receiver with ID: "+af+", element not found.") }}var ae=ai&&ai.src; var ag=aj||gadgets.rpc.getOrigin(ae); ac(af,ag); var ak=gadgets.util.getUrlParameters(ae); var ah=al||ak.rpctoken; c(af,ah) }function i(ae,ag,ah){if(ae===".."){var af=ah||d.rpctoken||d.ifpctok||""; h(af,ag) }else{o(ae,ag,ah) }}function w(ag){if(e==="bidir"||(e==="c2p"&&ag==="..")||(e==="p2c"&&ag!=="..")){var af=window.location.href; var ah="?"; if(p==="query"){ah="#" }else{if(p==="hash"){return af }}var ae=af.lastIndexOf(ah); ae=ae===-1?af.length:ae; return af.substring(0,ae) }return null }return{config:function(ae){if(typeof ae.securityCallback==="function"){J=ae.securityCallback }},register:function(af,ae){if(af===M||af===T){throw new Error("Cannot overwrite callback/ack service") }if(af===S){throw new Error("Cannot overwrite default service: use registerDefault") }q[af]=ae },unregister:function(ae){if(ae===M||ae===T){throw new Error("Cannot delete callback/ack service") }if(ae===S){throw new Error("Cannot delete default service: use unregisterDefault") }delete q[ae] },registerDefault:function(ae){q[S]=ae },unregisterDefault:function(){delete q[S] },forceParentVerifiable:function(){if(!H.isParentVerifiable()){H=gadgets.rpctx.ifpc }},call:function(ae,ag,al,aj){ae=ae||".."; var ak=".."; if(ae===".."){ak=v }else{if(ae.charAt(0)=="/"){ak=C(v,gadgets.rpc.getOrigin(window.location.href)) }}++z; if(al){l[z]=al }var ai={s:ag,f:ak,c:al?z:0,a:Array.prototype.slice.call(arguments,3),t:B[ae],l:!!D[ae]}; var af=w(ae); if(af){ai.r=af }if(ae!==".."&&y(ae)==null&&!document.getElementById(ae)){return }var ah=n[ae]; if(!ah&&y(ae)!==null){ah=H }if(ag.indexOf(s)===0){ah=H; ai.s=ag.substring(s.length); ai.c=ai.c?ai.c:z }ai.g=true; ai.r=ak; if(!ah){if(!E[ae]){E[ae]=[ai] }else{E[ae].push(ai) }return }if(D[ae]){ah=gadgets.rpctx.ifpc }if(ah.call(ae,ak,ai)===false){n[ae]=R; H.call(ae,ak,ai) }},getRelayUrl:O,setRelayUrl:ac,setAuthToken:c,setupReceiver:i,getAuthToken:F,removeReceiver:function(ae){delete W[ae]; delete D[ae]; delete B[ae]; delete m[ae]; delete n[ae] },getRelayChannel:function(){return H.getCode() },receive:function(af,ae){if(af.length>4){H._receiveMessage(af,Z) }else{j.apply(null,af.concat(ae)) }},receiveSameDomain:function(ae){ae.a=Array.prototype.slice.call(ae.a); window.setTimeout(function(){Z(ae) },0) },getOrigin:t,getTargetOrigin:L,init:function(){if(H.init(Z,k)===false){H=R }if(A){i("..") }else{gadgets.config.register("rpc",null,function(af){var ae=af.rpc||{}; ab(ae); aa(ae) }) }},_getTargetWin:ad,_parseSiblingId:y,ACK:T,RPC_ID:v||"..",SEC_ERROR_LOAD_TIMEOUT:P,SEC_ERROR_FRAME_PHISH:Y,SEC_ERROR_FORGED_MSG:a} }(); gadgets.rpc.init() }else{if(typeof gadgets.rpc=="undefined"||!gadgets.rpc){gadgets.rpc=window.gadgets["rpc"]; gadgets.rpc.config=gadgets.rpc.config; gadgets.rpc.register=gadgets.rpc.register; gadgets.rpc.unregister=gadgets.rpc.unregister; gadgets.rpc.registerDefault=gadgets.rpc.registerDefault; gadgets.rpc.unregisterDefault=gadgets.rpc.unregisterDefault; gadgets.rpc.forceParentVerifiable=gadgets.rpc.forceParentVerifiable; gadgets.rpc.call=gadgets.rpc.call; gadgets.rpc.getRelayUrl=gadgets.rpc.getRelayUrl; gadgets.rpc.setRelayUrl=gadgets.rpc.setRelayUrl; gadgets.rpc.setAuthToken=gadgets.rpc.setAuthToken; gadgets.rpc.setupReceiver=gadgets.rpc.setupReceiver; gadgets.rpc.getAuthToken=gadgets.rpc.getAuthToken; gadgets.rpc.removeReceiver=gadgets.rpc.removeReceiver; gadgets.rpc.getRelayChannel=gadgets.rpc.getRelayChannel; gadgets.rpc.receive=gadgets.rpc.receive; gadgets.rpc.receiveSameDomain=gadgets.rpc.receiveSameDomain; gadgets.rpc.getOrigin=gadgets.rpc.getOrigin; gadgets.rpc.getTargetOrigin=gadgets.rpc.getTargetOrigin; gadgets.rpc._getTargetWin=gadgets.rpc._getTargetWin; gadgets.rpc._parseSiblingId=gadgets.rpc._parseSiblingId }};; /* [end] feature=rpc */ /* [start] feature=config.min */ gapi.config={};gapi.config.GLOBAL_CFG_KEY="___gcfg";gapi.config.GLOBAL_CFG_USED="___gu";gapi.config.JSL_KEY="___jsl";gapi.config.DEFAULT_CFG_KEY="cd";gapi.config.USER_CFG_KEY="cu";gapi.config.INJECTED_CFG_KEY="ci";gapi.config.SAVED_CFG_KEY="cfg";gapi.config.ALL_SOURCES_KEY="us";gapi.config.ATTR_PROCESSED_CONFIG="gapi_processed";gapi.config.jsl=function(){return window[gapi.config.JSL_KEY]=window[gapi.config.JSL_KEY]||{}};gapi.config.jslComponent=function(a){var b=gapi.config.jsl();b[a]=b[a]||[];return b[a]}; gapi.config.cfg=function(a){var b=gapi.config.jsl();b[gapi.config.SAVED_CFG_KEY]=!a&&b[gapi.config.SAVED_CFG_KEY]||{};return b[gapi.config.SAVED_CFG_KEY]};gapi.config.isArray=function(a){return"object"===typeof a&&/\[native code\]/.test(a.push)}; gapi.config.foldConfig=function(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]&&b[c]&&"object"===typeof a[c]&&"object"===typeof b[c]&&!gapi.config.isArray(a[c])&&!gapi.config.isArray(b[c])?gapi.config.foldConfig(a[c],b[c]):b[c]&&"object"===typeof b[c]?(a[c]=gapi.config.isArray(b[c])?[]:{},gapi.config.foldConfig(a[c],b[c])):a[c]=b[c])}; gapi.config.getSelfScriptTags=function(){var a=document.scripts||document.getElementsByTagName("script")||[],b=[],c=[];c.push.apply(c,gapi.config.getAllSourceUrls());for(var d=0;d<a.length;++d)for(var e=a[d],f=0;f<c.length;++f)e.src&&0==e.src.indexOf(c[f])&&b.push(e);0==b.length&&0<a.length&&a[a.length-1].src&&b.push(a[a.length-1]);return b}; gapi.config.appendInlineConfig=function(){for(var a=gapi.config.jslComponent(gapi.config.USER_CFG_KEY),b=gapi.config.getSelfScriptTags(),c=0;c<b.length;++c)if(!b[c].getAttribute(gapi.config.ATTR_PROCESSED_CONFIG)){b[c].setAttribute(gapi.config.ATTR_PROCESSED_CONFIG,!0);var d=gapi.config.getInnerText(b[c]);(d=gapi.config.parseConfig(d))&&a.push(d)}};gapi.config.getAllSourceUrls=function(){return gapi.config.jslComponent(gapi.config.ALL_SOURCES_KEY)}; gapi.config.getInnerText=function(a){if(a){var b=a.nodeType;return 3==b||4==b?a.nodeValue:a.textContent||a.innerText||a.innerHTML||""}}; gapi.config.parseConfig=function(a){if(a&&!/^\s+$/.test(a)){for(;0==a.charCodeAt(a.length-1);)a=a.substring(0,a.length-1);var b;try{b=window.JSON.parse(a)}catch(c){}if("object"===typeof b)return b;try{b=(new Function("return ("+a+"\n)"))()}catch(d){}if("object"===typeof b)return b;try{b=(new Function("return ({"+a+"\n})"))()}catch(e){}return"object"===typeof b?b:{}}}; gapi.config.mergeConfig=function(a){gapi.config.cfg(!0);var b=window[gapi.config.GLOBAL_CFG_KEY],c=gapi.config.jslComponent(gapi.config.USER_CFG_KEY);if(b&&b!==window[gapi.config.GLOBAL_CFG_USED]){var d={};gapi.config.foldConfig(d,b);c.push(d);window[gapi.config.GLOBAL_CFG_USED]=b}gapi.config.appendInlineConfig();a&&(d={},gapi.config.foldConfig(d,a),c.push(d));d=gapi.config.jslComponent(gapi.config.DEFAULT_CFG_KEY);a=0;for(b=d.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),d[a]);d=gapi.config.jslComponent(gapi.config.INJECTED_CFG_KEY); a=0;for(b=d.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),d[a]);a=0;for(b=c.length;a<b;++a)gapi.config.foldConfig(gapi.config.cfg(),c[a])};gapi.config.get=function(a,b){if(!a)return gapi.config.cfg();for(var c=a.split("/"),d=gapi.config.cfg(),e=0,f=c.length;d&&"object"===typeof d&&e<f;++e)d=d[c[e]];return e===c.length&&void 0!==d?d:b};gapi.config.update=function(a,b){var c=a;if("string"===typeof a){for(var d=c={},e=a.split("/"),f=0,g=e.length;f<g-1;++f)var h={},d=d[e[f]]=h;d[e[f]]=b}gapi.config.mergeConfig(c)}; gapi.config.prefixGet=function(a){return function(b){return b?gapi.config.get(a+"/"+b):gapi.config.get(a)}};gapi.config.init_=gapi.config.mergeConfig;gapi.config.legacyInit&&gapi.config.legacyInit();gapi.config.init_(); ; /* [end] feature=config.min */ /* [start] feature=shindig.sha1 */ shindig.sha1=(function(){var d="0123456789ABCDEF"; var h=[]; var e=[]; var l=[]; var o=[]; o[0]=128; for(var g=1; g<64; ++g){o[g]=0 }var n; var b; function j(){h[0]=1732584193; h[1]=4023233417; h[2]=2562383102; h[3]=271733878; h[4]=3285377520; n=0; b=0 }function m(i,p){return((i<<p)|(i>>>(32-p)))&4294967295 }function a(p){var q=l; for(var s=0; s<64; s+=4){var B=(p[s]<<24)|(p[s+1]<<16)|(p[s+2]<<8)|(p[s+3]); q[s/4]=B }for(var s=16; s<80; s++){q[s]=m(q[s-3]^q[s-8]^q[s-14]^q[s-16],1) }var A=h[0]; var z=h[1]; var y=h[2]; var x=h[3]; var v=h[4]; var u,r; for(var s=0; s<80; s++){if(s<40){if(s<20){u=x^(z&(y^x)); r=1518500249 }else{u=z^y^x; r=1859775393 }}else{if(s<60){u=(z&y)|(x&(z|y)); r=2400959708 }else{u=z^y^x; r=3395469782 }}var C=(m(A,5)+u+v+r+q[s])&4294967295; v=x; x=y; y=m(z,30); z=A; A=C }h[0]=(h[0]+A)&4294967295; h[1]=(h[1]+z)&4294967295; h[2]=(h[2]+y)&4294967295; h[3]=(h[3]+x)&4294967295; h[4]=(h[4]+v)&4294967295 }function f(q,s){if(typeof(q)==="string"){q=unescape(encodeURIComponent(q)); var p=[]; for(var t=0,r=q.length; t<r; ++t){p.push(q.charCodeAt(t)) }q=p }if(!s){s=q.length }var u=0; if(n==0){while(u+64<s){a(q.slice(u,u+64)); u+=64; b+=64 }}while(u<s){e[n++]=q[u++]; b++; if(n==64){n=0; a(e); while(u+64<s){a(q.slice(u,u+64)); u+=64; b+=64 }}}}function k(){var s=[]; var r=b*8; if(n<56){f(o,56-n) }else{f(o,64-(n-56)) }for(var q=63; q>=56; q--){e[q]=r&255; r>>>=8 }a(e); var t=0; for(var q=0; q<5; q++){for(var p=24; p>=0; p-=8){s[t++]=(h[q]>>p)&255 }}return s }function c(){var p=k(); var r=""; for(var q=0; q<p.length; q++){r+=d.charAt(Math.floor(p[q]/16))+d.charAt(p[q]%16) }return r }j(); return{reset:j,update:f,digest:k,digestString:c} });; /* [end] feature=shindig.sha1 */ /* [start] feature=shindig.random */ shindig.random=(function(){var a=window.crypto; if(a&&typeof a.getRandomValues=="function"){return function(){var k=new window.Uint32Array(1); a.getRandomValues(k); return Number("0."+k[0]) } }var d=gapi.config.get("random/maxObserveMousemove"); if(d==null){d=-1 }var j=0; var f=Math.random(); var e="0123456789ABCDEF"; var c=1; var g=((screen.width*screen.width)+screen.height)*1000000; var b=function(l){l=l||window.event; var k=(l.screenX+l.clientX)<<16; k+=(l.screenY+l.clientY); k*=new Date().getTime()%1000000; c=(c*k)%g; if(d>0&&++j==d){gadgets.util.removeBrowserEvent(window,"mousemove",b,false) }}; if(d!=0){gadgets.util.attachBrowserEvent(window,"mousemove",b,false) }function i(k){var l=shindig.sha1(); l.update(k); return l.digestString() }var h=i(document.cookie+"|"+document.location+"|"+(new Date()).getTime()+"|"+f); return function(){var k=c; k+=parseInt(h.substr(0,20),16); h=i(h); return k/(g+Math.pow(16,20)) } })();; /* [end] feature=shindig.random */ gadgets.config.init({"rpc":{"commSwf":"//xpc.googleusercontent.com/gadgets/xpc.swf","passReferrer":"p2c:query","parentRelayUrl":"/rpc_relay.html"},"core.io":{"jsonProxyUrl":"//%host%/gadgets/makeRequest","proxyUrl":"//www.gmodules.com/gadgets/proxy/refresh=%refresh%&container=%container%%rewriteMime%&gadget=%gadget%/%rawurl%"}}); (function(){var j=window['___jsl']=window['___jsl']||{};j['l']=(j['l']||[]).concat(['core','rpc','shindig.random','shindig.sha1']);})();(function(){var j=window['___jsl']=window['___jsl']||{};if(j['c']){j['c']();delete j['c'];}})();
JavaScript
(function () { var host = window.location.hostname; var port = window.location.port; var videoPlugin; var videoStream; var audioPlugin; var audioStream; var error; var volume; function stream(object,type,done) { var state = "idle"; return { restart: function () { state = "restarting"; done(); if (object.playlist.isPlaying) { object.playlist.stop(); object.playlist.clear(); object.playlist.items.clear(); setTimeout(function () { this.start(false); }.bind(this),2000); } else { this.start(false); } }, start: function (e) { var req = generateUriParams(type); state = "starting"; if (e!==false) done(); $.ajax({ type: 'GET', url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri, success: function (e) { setTimeout(function () { state = "streaming"; object.playlist.add('http://'+host+':'+port+'/spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri,'',req.params); object.playlist.playItem(0); setTimeout(function () { done(); },600); },1000); }, error: function () { state = "error"; getError(); } }); }, stop: function () { $.ajax({ type: 'GET', url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&stop', success: function (e) { //done(); ?? }, error: function () { state = "error"; getError(); } }); if (object.playlist.isPlaying) { object.playlist.stop(); object.playlist.clear(); object.playlist.items.clear(); } state = "idle"; done(); }, getState: function() { return state; }, isStreaming: function () { return object.playlist.isPlaying; } } } function sendRequest(request,success,error) { var data; if (typeof request === "string") data = {'action':request}; else data = request; $.ajax({type: 'POST', url: 'request.json', data: JSON.stringify(data), success:success, error:error}); } function updatePhoneStatus(data) { if (data.volume !== undefined) { volume = data.volume; $('#sound>#volume').text(volume.current); } $('#battery>#level').text(data.battery); setTimeout(function () { sendRequest( [{"action":"battery"},{"action":"volume"}], function (e) { updatePhoneStatus(e); }, function () { updatePhoneStatus({battery:'??'}); } ); },100000); } function updateTooltip(title) { $('#tooltip>div').hide(); $('#tooltip #'+title).show(); } function loadSettings(config) { $('#resolution,#framerate,#bitrate,#audioEncoder,#videoEncoder').children().each(function (c) { if ($(this).val()===config.videoResolution || $(this).val()===config.videoFramerate || $(this).val()===config.videoBitrate || $(this).val()===config.audioEncoder || $(this).val()===config.videoEncoder ) { $(this).parent().children().prop('selected',false); $(this).prop('selected',true); } }); if (config.streamAudio===false) $('#audioEnabled').prop('checked',false); if (config.streamVideo===false) $('#videoEnabled').prop('checked',false); } function saveSettings() { var res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val()); var videoQuality = /[0-9]+/.exec($('#bitrate').val())[0]+'-'+/[0-9]+/.exec($('#framerate').val())[0]+'-'+res[1]+'-'+res[2]; var settings = { 'stream_video': $('#videoEnabled').prop('checked')===true, 'stream_audio': $('#audioEnabled').prop('checked')===true, 'video_encoder': $('#videoEncoder').val(), 'audio_encoder': $('#audioEncoder').val(), 'video_quality': videoQuality }; sendRequest({'action':'set','settings':settings}); } function loadSoundsList(sounds) { var list = $('#soundslist'), category, name; sounds.forEach(function (e) { category = e.match(/([a-z0-9]+)_/)[1]; name = e.match(/[a-z0-9]+_([a-z0-9_]+)/)[1]; if ($('.category.'+category).length==0) list.append( '<div class="category '+category+'"><span class="category-name">'+category+'</span><div class="category-separator"></div></div>' ); $('.category.'+category).append('<div class="sound" id="'+e+'"><a>'+name.replace(/_/g,' ')+'</a></div>'); }); } function testScreenState(state) { if (state===0) { $('#error-screenoff').fadeIn(1000); $('#glass').fadeIn(1000); } } function testVlcPlugin() { if (videoPlugin[0].VersionInfo === undefined || videoPlugin[0].VersionInfo.indexOf('2.0') === -1) { $('#error-noplugin').fadeIn(); $('#glass').fadeIn(); } } function generateUriParams(type) { var audioEncoder, videoEncoder, cache, rotation, flash, camera, res; // Audio conf if ($('#audioEnabled').prop('checked')) { audioEncoder = $('#audioEncoder').val()=='AMR-NB'?'amr':'aac'; } else { audioEncoder = "nosound"; } // Resolution res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val()); // Video conf if ($('#videoEnabled').prop('checked')) { videoEncoder = ($('#videoEncoder').val()=='H.263'?'h263':'h264')+'='+ /[0-9]+/.exec($('#bitrate').val())[0]+'-'+ /[0-9]+/.exec($('#framerate').val())[0]+'-'; videoEncoder += res[1]+'-'+res[2]; } else { videoEncoder = "novideo"; } // Flash if ($('#flashEnabled').val()==='1') flash = 'on'; else flash = 'off'; // Camera camera = $('#cameraId').val(); // Params cache = /[0-9]+/.exec($('#cache').val())[0]; return { uri:type==='audio'?audioEncoder:(videoEncoder+'&flash='+flash+'&camera='+camera), params:[':network-caching='+cache] } } function getError() { sendRequest( 'state', function (e) { error = e.state.lastError; updateStatus(); }, function () { error = 'Phone unreachable !'; updateStatus(); } ); } function updateStatus() { var status = $('#status'), button = $('#connect>div>h1'), cover = $('#vlc-container #upper-layer'); // STATUS if (videoStream.getState()==='starting' || videoStream.getState()==='restarting' || audioStream.getState()==='starting' || audioStream.getState()==='restarting') { status.html(__('Trying to connect...')) } else { if (!videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('NOT CONNECTED')); else if (videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('Streaming video but not audio')); else if (!videoStream.isStreaming() && audioStream.isStreaming()) status.html(__('Streaming audio but not video')); else status.html(__('Streaming audio and video')); } // BUTTON if ((videoStream.getState()==='idle' || videoStream.getState()==='error') && (audioStream.getState()==='idle' || audioStream.getState()==='error')) { button.html(__('Connect !!')); } else button.text(__('Disconnect ?!')); // WINDOW if (videoStream.getState()==='error' || audioStream.getState()==='error') { videoPlugin.css('visibility','hidden'); cover.html('<div id="wrapper"><h1>'+__('An error occurred')+' :(</h1><p>'+error+'</p></div>'); } else if (videoStream.getState()==='restarting' || audioStream.getState()==='restarting') { videoPlugin.css('visibility','hidden'); cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('UPDATING SETTINGS')+'</h1></div>').show(); } else if (videoStream.getState()==='starting' || audioStream.getState()==='starting') { videoPlugin.css('visibility','hidden'); cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('CONNECTION')+'</h1></div>').show(); } else if (videoStream.getState()==='streaming') { videoPlugin.css('visibility','inherit'); cover.hide(); } if (videoStream.getState()==='idle') { if (audioStream.getState()==='streaming') { videoPlugin.css('visibility','hidden'); cover.html('').css('background','url("images/speaker.png") center no-repeat').show(); } else if (audioStream.getState()==='idle') { videoPlugin.css('visibility','hidden'); cover.html('').css('background','url("images/eye.png") center no-repeat').show(); } } } function disableAndEnable(input) { input.prop('disabled',true); setTimeout(function () { input.prop('disabled',false); },1000); } function setupEvents() { var cover = $('#vlc-container #upper-layer'); var status = $('#status'); var button = $('#connect>div>h1'); $('.popup #close').click(function (){ $('#glass').fadeOut(); $('.popup').fadeOut(); }); $('#connect').click(function () { if ($(this).prop('disabled')===true) return; disableAndEnable($(this)); if ((videoStream.getState()!=='idle' && videoStream.getState()!=='error') || (audioStream.getState()!=='idle' && audioStream.getState()!=='error')) { videoStream.stop(); audioStream.stop(); } else { if (!$('#videoEnabled').prop('checked') && !$('#audioEnabled').prop('checked')) return; if ($('#videoEnabled').prop('checked')) videoStream.start(); if ($('#audioEnabled').prop('checked')) audioStream.start(); } }); $('#torch-button').click(function () { if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return; disableAndEnable($(this)); if ($('#flashEnabled').val()=='0') { $('#flashEnabled').val('1'); $(this).addClass('torch-on'); } else { $('#flashEnabled').val('0'); $(this).removeClass('torch-on'); } if (videoStream.getState()==='streaming') videoStream.restart(); }); $('#buzz-button').click(function () { $(this).animate({'padding-left':'+=10'}, 40, 'linear') .animate({'padding-left':'-=20'}, 80, 'linear') .animate({'padding-left':'+=10'}, 40, 'linear'); sendRequest('buzz'); }); $(document).on('click', '.camera-not-selected', function () { if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return; $('#cameras span').addClass('camera-not-selected'); $(this).removeClass('camera-not-selected'); disableAndEnable($('.camera-not-selected')); $('#cameraId').val($(this).attr('data-id')); if (videoStream.getState()==='streaming') videoStream.restart(); }) $('.audio select').change(function () { if (audioStream.isStreaming()) { audioStream.restart(); } }); $('.audio input').change(function () { if (audioStream.isStreaming() || videoStream.isStreaming()) { if ($('#audioEnabled').prop('checked')) audioStream.restart(); else audioStream.stop(); disableAndEnable($(this)); } }); $('.video select').change(function () { if (videoStream.isStreaming()) { videoStream.restart(); } }); $('.video input').change(function () { if (audioStream.isStreaming() || videoStream.isStreaming()) { if ($('#videoEnabled').prop('checked')) videoStream.restart(); else videoStream.stop(); disableAndEnable($(this)); } }); $('.cache select').change(function () { if (videoStream.isStreaming()) { videoStream.restart(); } if (audioStream.isStreaming()) { audioStream.restart(); } }); $('select,input').change(function () { saveSettings(); }); $('.section').click(function () { $('.section').removeClass('selected'); $(this).addClass('selected'); updateTooltip($(this).attr('id')); }); $(document).on('click', '.sound', function () { sendRequest([{'action':'play','name':$(this).attr('id')}]); }); $('#fullscreen').click(function () { videoPlugin[0].video.toggleFullscreen(); }); $('#hide-tooltip').click(function () { $('body').width($('body').width() - $('#tooltip').width()); $('#tooltip').hide(); $('#need-help').show(); }); $('#need-help').click(function () { $('body').width($('body').width() + $('#tooltip').width()); $('#tooltip').show(); $('#need-help').hide(); }); $('#sound #plus').click(function () { volume.current += 1; if (volume.current > volume.max) volume.current = volume.max; else sendRequest([{'action':'volume','set':volume.current}]); $('#sound>#volume').text(volume.current); }); $('#sound #minus').click(function () { volume.current -= 1; if (volume.current < 0) volume.current = 0; else sendRequest([{'action':'volume','set':volume.current}]); $('#sound>#volume').text(volume.current); }); window.onbeforeunload = function (e) { videoStream.stop(); audioStream.stop(); } }; $(document).ready(function () { videoPlugin = $('#vlcv'); videoStream = stream(videoPlugin[0],'video',updateStatus); audioPlugin = $('#vlca'); audioStream = stream(audioPlugin[0],'audio',updateStatus); testVlcPlugin(); sendRequest([{'action':'sounds'},{'action':'screen'},{'action':'get'},{'action':'battery'},{'action':'volume'}], function (data) { // Verifies that the screen is not turned off testScreenState(data.screen); // Fetches the list of sounds available on the phone loadSoundsList(data.sounds); // Retrieves the configuration of Spydroid on the phone loadSettings(data.get); // Retrieves volume and battery level updatePhoneStatus(data); }); // Translate the interface in the appropriate language $('h1,h2,h3,span,p,a,em').translate(); $('.popup').each(function () { $(this).css({'top':($(window).height()-$(this).height())/2,'left':($(window).width()-$(this).width())/2}); }); $('#tooltip').hide(); $('#need-help').show(); // Bind DOM events setupEvents(); }); }());
JavaScript
(function () { var translations = { en: { 1:"About", 2:"Return", 3:"Change quality settings", 4:"Flash/Vibrator", 5:"Click on the torch to enable or disable the flash", 6:"Play a prerecorded sound", 7:"Connect !!", 8:"Disconnect ?!", 9:"STATUS", 10:"NOT CONNECTED", 11:"ERROR :(", 12:"CONNECTION", 13:"UPDATING SETTINGS", 14:"CONNECTED", 15:"Show some tips", 16:"Hide those tips", 17:"Those buttons will trigger sounds on your phone...", 18:"Use them to surprise your victim.", 19:"Or you could use this to surprise your victim !", 20:"This will simply toggle the led in front of you're phone, so that even in the deepest darkness, you shall not be blind...", 21:"If the stream is choppy, try reducing the bitrate or increasing the cache size.", 22:"Try it instead of H.263 if video streaming is not working at all !", 23:"The H.264 compression algorithm is more efficient but may not work on your phone...", 24:"You need to install or update VLC and the VLC mozilla plugin !", 25:"During the installation make sure to check the firefox plugin !", 26:"Close", 27:"You must leave the screen of your smartphone on !", 28:"Front facing camera", 29:"Back facing camera", 30:"Switch between cameras", 31:"Streaming video but not audio", 32:"Streaming audio but not video", 33:"Streaming audio and video", 34:"Trying to connect...", 35:"Stream sound", 36:"Stream video", 37:"Fullscreen", 38:"Encoder", 39:"Resolution", 40:"Cache size", 41:"This generally happens when you are trying to use settings that are not supported by your phone.", 42:"Retrieving error message...", 43:"An error occurred", 44:"Click on the phone to make your phone buzz" }, fr: { 1:"À propos", 2:"Retour", 3:"Changer la qualité du stream", 4:"Flash/Vibreur", 5:"Clique sur l'ampoule pour activer ou désactiver le flash", 6:"Jouer un son préenregistré", 7:"Connexion !!", 8:"Déconnecter ?!", 9:"STATUT", 10:"DÉCONNECTÉ", 11:"ERREUR :(", 12:"CONNEXION", 13:"M.A.J.", 14:"CONNECTÉ", 15:"Afficher l'aide", 16:"Masquer l'aide", 17:"Clique sur un de ces boutons pour lancer un son préenregistré sur ton smartphone !", 18:"Utilise les pour surprendre ta victime !!", 19:"Ça peut aussi servir à surprendre ta victime !", 20:"Clique sur l'ampoule pour allumer le flash de ton smartphone", 21:"Si le stream est saccadé essaye de réduire le bitrate ou d'augmenter la taille du cache.", 22:"Essaye le à la place du H.263 si le streaming de la vidéo ne marche pas du tout !", 23:"Le H.264 est un algo plus efficace pour compresser la vidéo mais il a moins de chance de marcher sur ton smartphone...", 24:"Tu dois d'abord installer ou mettre à jour VLC et le mozilla plugin !", 25:"Pendant l'installation laisse cochée l'option plugin mozilla !", 26:"Fermer", 27:"Tu dois laisser l'écran de ton smartphone allumé", 28:"Caméra face avant", 29:"Caméra face arrière", 30:"Choisir la caméra", 31:"Streaming de la vidéo", 32:"Streaming de l'audio", 33:"Streaming de l'audio et de la vidéo", 34:"Connexion en cours...", 35:"Streaming du son", 36:"Streaming de la vidéo", 37:"Plein écran", 38:"Encodeur", 39:"Résolution", 40:"Taille cache", 41:"En général, cette erreur se produit quand les paramètres sélectionnés ne sont pas compatibles avec le smartphone.", 42:"Attente du message d'erreur...", 43:"Une erreur s'est produite", 44:"Clique pour faire vibrer ton tel." }, ru: { 1:"Спасибо", 2:"Вернуться", 3:"Изменить настройки качества", 4:"Переключатель вспышки", 5:"Нажмите здесь, чтобы включить или выключить вспышку", 6:"Проиграть звук на телефоне", 7:"Подключиться !!", 8:"Отключиться ?!", 9:"СОСТОЯНИЕ", 10:"НЕТ ПОДКЛЮЧЕНИЯ", 11:"ОШИБКА :(", 12:"ПОДКЛЮЧЕНИЕ", 13:"ОБНОВЛЕНИЕ НАСТРОЕК", 14:"ПОДКЛЮЧЕНО", 15:"Показать поясняющие советы", 16:"Спрятать эти советы", 17:"Эти кнопки будут проигрывать звуки на вашем телефоне...", 18:"Используйте их, чтобы удивить вашу жертву.", 19:"Или вы можете удивить свою жертву!", 20:"Это переключатель режима подсветки на передней части вашего телефона, так что даже в самой кромешной тьме, вы не будете слепы ...", 21:"Если поток прерывается, попробуйте уменьшить битрейт или увеличив размер кэша.", 22:"Если топоковое видео не работает совсем, попробуйте сжатие Н.263", 23:"Алгоритм сжатия H.264, является более эффективным, но может не работать на вашем телефоне ...", 24:"You need to install or update VLC and the VLC mozilla plugin !", 25:"При установке убедитесь в наличии плагина для firefox !", 26:"Закрыть", 27:"Вам надо отойти от вашего смартфона.", 28:"Фронтальная камера", 29:"Камера с обратной стороны", 30:"Переключиться на другую камеру", 31:"Передача видео без звука", 32:"Передача звука без видео", 33:"Передача звука и видео", 34:"Пытаемся подключится", 35:"Аудио поток", 36:"Видео поток", 37:"На весь экран", 38:"Кодек", 39:"Разрешение", 40:"Размер кеша", 41:"Как правило, это происходит, когда вы пытаетесь использовать настройки, не поддерживаемые вашим телефоном.", 42:"Получение сообщения об ошибке ..." }, de : { 1:"Apropos", 2:"Zurück", 3:"Qualität des Streams verändern", 4:"Fotolicht ein/aus", 5:"Klick die Glühbirne an, um das Fotolicht einzuschalten oder azufallen", 6:"Vereinbarten Ton spielen", 7:"Verbindung !!", 8:"Verbinden ?!", 9:"STATUS", 10:"NICHT VERBUNDEN", 11:"FEHLER :(", 12:"VERBINDUNG", 13:"UPDATE", 14:"VERBUNDEN", 15:"Hilfe anzeigen", 16:"Hilfe ausblenden", 17:"Klick diese Tasten an, um Töne auf deinem Smartphone spielen zu lassen !", 18:"Benutz sie, um deine Opfer zu überraschen !!", 19:"Das kann auch dein Opfer erschrecken !", 20:"Es wird die LED hinter deinem Handy anmachen, damit du nie blind bleibst, auch im tiefsten Dunkeln", 21:"Wenn das Stream ruckartig ist, versuch mal die Bitrate zu reduzieren oder die Größe vom Cache zu steigern.", 22:"Probier es ansatt H.263, wenn das Videostream überhaupt nicht funktionert !", 23:"Der H.264 Kompressionalgorithmus ist effizienter aber er wird auf deinem Handy vielleicht nicht funktionieren...", 24:"You need to install or update VLC and the VLC mozilla plugin !", 25:"Während der Installation, prüfe dass das Firefox plugin abgecheckt ist!", 26:"Zumachen", 27:"Du musst den Bildschirm deines Smartphones eingeschaltet lassen !", 28:"Frontkamera", 29:"Rückkamera", 30:"Kamera auswählen", 31:"Videostreaming", 32:"Audiostreaming", 33:"Video- und Audiostreaming", 34:"Ausstehende Verbindung...", 35:"Soundstreaming", 36:"Videostreaming", 37:"Ganzer Bildschirm", 38:"Encoder", 39:"Auflösung", 40:"Cachegröße", 41:"Dieser Fehler gescheht überhaupt, wenn die gewählten Einstellungen mit dem Smartphone nicht kompatibel sind.", 42:"Es wird auf die Fehlermeldung gewartet...", 43:"Ein Fehler ist geschehen..." } }; var lang = window.navigator.userLanguage || window.navigator.language; //var lang = "ru"; var __ = function (text) { var x,y=0,z; if (lang.match(/en/i)!=null) return text; for (x in translations) { if (lang.match(new RegExp(x,"i"))!=null) { for (z in translations.en) { if (text==translations.en[z]) { y = z; break; } } return translations[x][y]==undefined?text:translations[x][y]; } } return text; }; $.fn.extend({ translate: function () { return this.each(function () { $(this).html(__($(this).html())); }); } }); window.__ = __; }());
JavaScript
document.createElement('header'); document.createElement('nav'); document.createElement('section'); document.createElement('article'); document.createElement('aside'); document.createElement('footer'); document.createElement('hgroup'); $(document).ready(function () { $('.section-content,#status-container').addClass('ie8-background'); $('.category-separator').hide(); });
JavaScript
// validate search form to make sure keyword is not empty function validateSearch(form){ // return false if search query is empty if(form.txtKeyword.value == ""){ alert("Search keyword is required"); return false; } return true; } // validate the quantity entered by user function validateQuantity(form){ // return false if quantity is empty if(form.qty.value == ""){ alert("Quantity is required"); return false; } // check if quantity is an not an integer and display an error if(!isInteger(form.qty.value)){ alert("Quantity should be an integrer greater than zero"); return false; } // Check if quantity is not less than 1 if(form.qty.value < 1){ alert("Quantity should be greater than zero"); return false; } return true; } // when user changes sort by selection box or items per page to refresh page function search(){ document.getElementById("frmProducts").submit(); } // check if a radio button in the product list is selected, otherwise display an error function validateSelectProduct(form){ for (i = 0; i <form.radId.length; i++) { if (form.radId[i].checked) { return true; } } alert("Please select a fruit from the list"); return false; } // This function is taken from: http://acmesoffware.com/acme/default.asp function isInteger (s) { var i; if (isEmpty(s)) if (isInteger.arguments.length == 1) return 0; else return (isInteger.arguments[1] == true); for (i = 0; i < s.length; i++) { var c = s.charAt(i); if (!isDigit(c)) return false; } return true; } function isEmpty(s){ return ((s == null) || (s.length == 0)) } function isDigit (c) { return ((c >= "0") && (c <= "9")) } // Validate login form function loginvalidate(form) { // check if username is not blank if(form.txtUsername.value == "") { alert("Username is required!"); form.txtUsername.focus(); return false; } // check if password is not blank if(form.txtPassword.value == "") { alert("Password is required!"); form.txtPassword.focus(); return false; } return true; } // Validate registration form function registerValidate(form) { // regular expression to check name re=/^[a-z A-Z]+$/ // validate username if(!re.test(form.txtUsername.value)) { alert("Username is not valid!"); form.txtUsername.focus(); return false; } // validate password if(form.txtPassword.value == "") { alert("Password is required!"); form.txtPassword.focus(); return false; } // validate password if(form.txtPassword.value != form.txtConfirm.value) { alert("Password and confirm did not match!"); form.txtPassword.focus(); return false; } // return fasle when name contains none characters if(!re.test(form.txtName.value)){ alert("Full name is not valid"); form.txtName.focus(); return false; } // regular expression to check email address re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ // return false if email address is not valid if(!re.test(form.txtEmail.value)) { alert("Email address is not valid!"); form.txtEmail.focus(); return false; } return true; }
JavaScript
/* * This javascript can be used within Firebug to extract values from the weekly pages on www.hundredpushups.com * Requires jQuery on the page. Can be "installed" via bookmarklet @ http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet */ var workout = {'easy':[],'mid':[],'hard':[]}; var week = 1; function cleanMax(value) { if (value.indexOf("max") == -1) { return value;} var len = 1; if (value.indexOf(" ") > -1 && value.length > 16) { len++; } value = value.substring(14); return value.substring(0,value.length-len) } function prettyPrint(workout,week,level) { var set = ""; var values = []; var day = 1; var newline = false; for(var i = 1; i < workout.length; i++) { if (newline) { set += workoutCode(values,week,day,level)+"\r\n"; values=[]; newline = false; day++; } if (i%5 == 0) {newline = true;} values.push(workout[i]); } set += workoutCode(values,week,day,level); return set; } function workoutCode(values,week,day,level) { return "PUSHUPS["+week+"]["+day+"]["+level+"] = new int[]{"+values.join(",")+"};"; } function getWeek() { var path = document.location.pathname; var value = path.substring(5,path.indexOf(".")); return value; } // main week = getWeek(); $('tr [class=specalt],tr [class=spec]').each(function() { var easy = $(this).next(); var mid = easy.next(); var hard = mid.next(); workout['easy'].push(cleanMax(easy.html())); workout['mid'].push(cleanMax(mid.html())); workout['hard'].push(cleanMax(mid.html())); }); console.log(prettyPrint(workout.easy,week,0)+"\r\n"+ prettyPrint(workout.mid,week,1)+"\r\n"+ prettyPrint(workout.hard,week,2));
JavaScript
/* * jQuery Mobile Framework 1.0 * http://jquerymobile.com * * Copyright 2011 (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * */ /*! * jQuery UI Widget @VERSION * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { $( elem ).triggerHandler( "remove" ); } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { $( this ).triggerHandler( "remove" ); }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ); if ( !instance ) { throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'"; } if ( !$.isFunction( instance[options] ) ) { throw "no such method '" + options + "' for " + name + " widget instance"; } var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, this._getCreateOptions(), options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._trigger( "create" ); this._init(); }, _getCreateOptions: function() { var options = {}; if ( $.metadata ) { options = $.metadata.get( element )[ this.widgetName ]; } return options; }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, this.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } this._setOptions( options ); return this; }, _setOptions: function( options ) { var self = this; $.each( options, function( key, value ) { self._setOption( key, value ); }); return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _trigger: function( type, event, data ) { var callback = this.options[ type ]; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); data = data || {}; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( event.originalEvent ) { for ( var i = $.event.props.length, prop; i; ) { prop = $.event.props[ --i ]; event[ prop ] = event.originalEvent[ prop ]; } } this.element.trigger( event, data ); return !( $.isFunction(callback) && callback.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })( jQuery ); /* * widget factory extentions for mobile */ (function( $, undefined ) { $.widget( "mobile.widget", { // decorate the parent _createWidget to trigger `widgetinit` for users // who wish to do post post `widgetcreate` alterations/additions // // TODO create a pull request for jquery ui to trigger this event // in the original _createWidget _createWidget: function() { $.Widget.prototype._createWidget.apply( this, arguments ); this._trigger( 'init' ); }, _getCreateOptions: function() { var elem = this.element, options = {}; $.each( this.options, function( option ) { var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) { return "-" + c.toLowerCase(); }) ); if ( value !== undefined ) { options[ option ] = value; } }); return options; }, enhanceWithin: function( target ) { // TODO remove dependency on the page widget for the keepNative. // Currently the keepNative value is defined on the page prototype so // the method is as well var page = $(target).closest(":jqmData(role='page')").data( "page" ), keepNative = (page && page.keepNativeSelector()) || ""; $( this.options.initSelector, target ).not( keepNative )[ this.widgetName ](); } }); })( jQuery ); /* * a workaround for window.matchMedia */ (function( $, undefined ) { var $window = $( window ), $html = $( "html" ); /* $.mobile.media method: pass a CSS media type or query and get a bool return note: this feature relies on actual media query support for media queries, though types will work most anywhere examples: $.mobile.media('screen') //>> tests for screen media type $.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4) */ $.mobile.media = (function() { // TODO: use window.matchMedia once at least one UA implements it var cache = {}, testDiv = $( "<div id='jquery-mediatest'>" ), fakeBody = $( "<body>" ).append( testDiv ); return function( query ) { if ( !( query in cache ) ) { var styleBlock = document.createElement( "style" ), cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }"; //must set type for IE! styleBlock.type = "text/css"; if ( styleBlock.styleSheet ){ styleBlock.styleSheet.cssText = cssrule; } else { styleBlock.appendChild( document.createTextNode(cssrule) ); } $html.prepend( fakeBody ).prepend( styleBlock ); cache[ query ] = testDiv.css( "position" ) === "absolute"; fakeBody.add( styleBlock ).remove(); } return cache[ query ]; }; })(); })(jQuery); /* * support tests */ (function( $, undefined ) { var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "Webkit", "Moz", "O" ], webos = "palmGetResource" in window, //only used to rule out scrollTop operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]", bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ); for ( var v in props ){ if ( fbCSS[ props[ v ] ] !== undefined ) { return true; } } } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl' />" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href || location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.mobile.browser = {}; $.mobile.browser.ie = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ); return v > 4 ? v : !v; })(); $.extend( $.support, { orientation: "orientation" in window && "onorientationchange" in window, touch: "ontouchend" in document, cssTransitions: "WebKitTransitionEvent" in window, pushState: "pushState" in history && "replaceState" in history, mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), touchOverflow: !!propExists( "overflowScrolling" ), boxShadow: !!propExists( "boxShadow" ) && !bb, scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos && !operamini, dynamicBaseTag: baseTagTest() }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible var nokiaLTE7_3 = (function(){ var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini operamini || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" ); } })( jQuery ); /* * "mouse" plugin */ // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $( document ), nextTouchID = 1, lastTouchID = 0; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j; event = $.Event(event); event.type = eventType; oe = event.originalEvent; props = $.event.props; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } // make sure that if the mouse and click virtual events are generated // without a .which one is defined if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ){ event.which = 1; } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++){ prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout(function(){ resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ){ clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); } return ve; } function mouseEventCallback( event ) { var touchID = $.data(event.target, touchTargetPropertyName); if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){ var ve = triggerVirtualEvent( "v" + event.type, event ); if ( ve ) { if ( ve.isDefaultPrevented() ) { event.preventDefault(); } if ( ve.isPropagationStopped() ) { event.stopPropagation(); } if ( ve.isImmediatePropagationStopped() ) { event.stopImmediatePropagation(); } } } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; var t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold; didScroll = didScroll || ( Math.abs(t.pageX - startX) > moveThreshold || Math.abs(t.pageY - startY) > moveThreshold ), flags = getVirtualBindingFlags( event.target ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { var ve = triggerVirtualEvent( "vclick", event, flags ); if ( ve && ve.isDefaultPrevented() ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler(){} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function( data, namespace ) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {}); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if (activeDocHandlers[ "touchstart" ] === 1) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function( data, namespace ) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( var i = 0; i < virtualEventNames.length; i++ ){ $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ){ var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is syntehsized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); /* * "events" plugin - Handles events */ (function( $, window, undefined ) { // add new event shortcuts $.each( ( "touchstart touchmove touchend orientationchange throttledresize " + "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; $.attrFn[ name ] = true; }); var supportTouch = $.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; function triggerCustomEvent( obj, eventType, event ) { var originalType = event.type; event.type = eventType; $.event.handle.call( obj, event ); event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout(function() { trigger( event, false ); }, 50 ); }); } }; // also handles taphold $.event.special.tap = { setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( "vmousedown", function( event ) { if ( event.which && event.which !== 1 ) { return false; } var origTarget = event.target, origEvent = event.originalEvent, timer; function clearTapTimer() { clearTimeout( timer ); } function clearTapHandlers() { clearTapTimer(); $this.unbind( "vclick", clickHandler ) .unbind( "vmouseup", clearTapTimer ) .unbind( "vmousecancel", clearTapHandlers ); } function clickHandler(event) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( origTarget == event.target ) { triggerCustomEvent( thisObject, "tap", event ); } } $this.bind( "vmousecancel", clearTapHandlers ) .bind( "vmouseup", clearTapTimer ) .bind( "vclick", clickHandler ); timer = setTimeout(function() { triggerCustomEvent( thisObject, "taphold", $.Event( "taphold" ) ); }, 750 ); }); } }; // also handles swipeleft, swiperight $.event.special.swipe = { scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling. durationThreshold: 1000, // More time than this, and it isn't a swipe. horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this. verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this. setup: function() { var thisObject = this, $this = $( thisObject ); $this.bind( touchStartEvent, function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, start = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ], origin: $( event.target ) }, stop; function moveHandler( event ) { if ( !start ) { return; } var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event; stop = { time: ( new Date() ).getTime(), coords: [ data.pageX, data.pageY ] }; // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } } $this.bind( touchMoveEvent, moveHandler ) .one( touchStopEvent, function( event ) { $this.unbind( touchMoveEvent, moveHandler ); if ( start && stop ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { start.origin.trigger( "swipe" ) .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" ); } } start = stop = undefined; }); }); } }; (function( $, window ) { // "Cowboy" Ben Alman var win = $( window ), special_event, get_orientation, last_orientation; $.event.special.orientationchange = special_event = { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation && $.mobile.orientationChangeEnabled ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function(){ // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation && $.mobile.orientationChangeEnabled ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }; // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( "orientationchange" ); } } // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var isPortrait = true, elem = document.documentElement; // prefer window orientation to the calculation based on screensize as // the actual screen resize takes place before or after the orientation change event // has been fired depending on implementation (eg android 2.3 is before, iphone after). // More testing is required to determine if a more reliable method of determining the new screensize // is possible when orientationchange is fired. (eg, use media queries + element + opacity) if ( $.support.orientation ) { // if the window orientation registers as 0 or 180 degrees report // portrait, otherwise landscape isPortrait = window.orientation % 180 == 0; } else { isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1; } return isPortrait ? "portrait" : "landscape"; }; })( jQuery, window ); // throttled resize event (function() { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function(){ $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })(); $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); } }; }); })( jQuery, this ); // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv $.browser.msie && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); /* * "page" plugin */ (function( $, undefined ) { $.widget( "mobile.page", $.mobile.widget, { options: { theme: "c", domCache: false, keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')" }, _create: function() { this._trigger( "beforecreate" ); this.element .attr( "tabindex", "0" ) .addClass( "ui-page ui-body-" + this.options.theme ); }, keepNativeSelector: function() { var options = this.options, keepNativeDefined = options.keepNative && $.trim(options.keepNative); if( keepNativeDefined && options.keepNative !== options.keepNativeDefault ){ return [options.keepNative, options.keepNativeDefault].join(", "); } return options.keepNativeDefault; } }); })( jQuery ); /* * "core" - The base file for jQm */ (function( $, window, undefined ) { var nsNormalizeDict = {}; // jQuery.mobile configurable options $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Define the url parameter used for referencing widget-generated sub-pages. // Translates to to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // disable to prevent jquery from bothering with links linkBindingEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "slide", // Minimum scroll distance that will be remembered when returning to a page minScrollBack: 250, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Show loading message during Ajax requests // if false, message will not appear, but loading classes will still be toggled on html el loadingMessage: "loading", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", //automatically initialize the DOM when it's ready autoInitializePage: true, pushStateEnabled: true, // turn of binding to the native orientationchange due to android orientation behavior orientationChangeEnabled: true, // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ gradeA: function(){ return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7; }, // TODO might be useful upstream in jquery itself ? keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, // COMMAND COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, // COMMAND_RIGHT NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91 // COMMAND }, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $( document ).trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, // Expose our cache for testing purposes. nsNormalizeDict: nsNormalizeDict, // Take a data attribute property, prepend the namespace // and then camel case the attribute string. Add the result // to our nsNormalizeDict so we don't have to do this again. nsNormalize: function( prop ) { if ( !prop ) { return; } return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) ); }, getInheritedTheme: function( el, defaultTheme ) { // Find the closest parent with a theme class on it. Note that // we are not using $.fn.closest() on purpose here because this // method gets called quite a bit and we need it to be as fast // as possible. var e = el[ 0 ], ltr = "", re = /ui-(bar|body)-([a-z])\b/, c, m; while ( e ) { var c = e.className || ""; if ( ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) { // We found a parent with a theme class // on it so bail from this loop. break; } e = e.parentNode; } // Return the theme letter we found, if none, return the // specified default. return ltr || defaultTheme || "a"; } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { var result; if ( typeof prop != "undefined" ) { result = this.data( prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.jqmData = function( elem, prop, value ) { var result; if ( typeof prop != "undefined" ) { result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.fn.removeWithDependents = function() { $.removeWithDependents( this ); }; $.removeWithDependents = function( elem ) { var $elem = $( elem ); ( $elem.jqmData('dependents') || $() ).remove(); $elem.remove(); }; $.fn.addDependents = function( newDependents ) { $.addDependents( $(this), newDependents ); }; $.addDependents = function( elem, newDependents ) { var dependents = $(elem).jqmData( 'dependents' ) || $(); $(elem).jqmData( 'dependents', $.merge(dependents, newDependents) ); }; // note that this helper doesn't attempt to handle the callback // or setting of an html elements text, its only purpose is // to return the html encoded version of the text in all cases. (thus the name) $.fn.getEncodedText = function() { return $( "<div/>" ).text( $(this).text() ).html(); }; // Monkey-patching Sizzle to filter the :jqmData selector var oldFind = $.find, jqmDataRE = /:jqmData\(([^)]*)\)/g; $.find = function( selector, context, ret, extra ) { selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" ); return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /* * core utilities for auto ajax navigation, base tag mgmt, */ ( function( $, undefined ) { //define vars for interal use var $window = $( window ), $html = $( 'html' ), $head = $( 'head' ), //url path helpers for use in relative url management path = { // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: // // [6]: jblas:password@mycompany.com:8080 // [7]: jblas:password // [8]: jblas // [9]: password // [10]: mycompany.com:8080 // [11]: mycompany.com // [12]: 8080 // [13]: /mail/inbox // [14]: /mail/ // [15]: inbox // [16]: ?msg=1234&type=unread // [17]: #msg-content // urlParseRE: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var matches = path.urlParseRE.exec( url || "" ) || []; // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. return { href: matches[ 0 ] || "", hrefNoHash: matches[ 1 ] || "", hrefNoSearch: matches[ 2 ] || "", domain: matches[ 3 ] || "", protocol: matches[ 4 ] || "", doubleSlash: matches[ 5 ] || "", authority: matches[ 6 ] || "", username: matches[ 8 ] || "", password: matches[ 9 ] || "", host: matches[ 10 ] || "", hostname: matches[ 11 ] || "", port: matches[ 12 ] || "", pathname: matches[ 13 ] || "", directory: matches[ 14 ] || "", filename: matches[ 15 ] || "", search: matches[ 16 ] || "", hash: matches[ 17 ] || "" }; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; var absStack = absPath ? absPath.split( "/" ) : [], relStack = relPath.split( "/" ); for ( var i = 0; i < relStack.length; i++ ) { var d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ), authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + doubleSlash + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // otherwise the Data Url won't match the id of the embedded Page. return u.hash.split( dialogHashKey )[0].replace( /^#/, "" ); } else if ( path.isSameDomain( u, documentBase ) ) { return u.hrefNoHash.replace( documentBase.domain, "" ); } return absUrl; }, //get path from current hash, or from a file path get: function( newPath ) { if( newPath === undefined ) { newPath = location.hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' ); }, //return the substring of a filepath before the sub-page key, for making a server request getFilePath: function( path ) { var splitkey = '&' + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, //check if the specified url refers to the first page in the main application document. isFirstPageUrl: function( url ) { // We only deal with absolute paths. var u = path.parseUrl( path.makeUrlAbsolute( url, documentBase ) ), // Does the url have the same path as the document? samePath = u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ), // Get the first page element. fp = $.mobile.firstPage, // Get the id of the first page element if it has one. fpId = fp && fp[0] ? fp[0].id : undefined; // The url refers to the first page if the path matches the document and // it either has no hash value, or the hash is exactly equal to the id of the // first page element. return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) ); } return (/^#/).test( u.href ); } }, //will be defined when a link is clicked and given an active class $activeClickedLink = null, //urlHistory is purely here to make guesses at whether the back or forward button was clicked //and provide an appropriate transition urlHistory = { // Array of pages that are visited during a single page load. // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs) stack: [], //maintain an index number for the active page in the stack activeIndex: 0, //get active getActive: function() { return urlHistory.stack[ urlHistory.activeIndex ]; }, getPrev: function() { return urlHistory.stack[ urlHistory.activeIndex - 1 ]; }, getNext: function() { return urlHistory.stack[ urlHistory.activeIndex + 1 ]; }, // addNew is used whenever a new page is added addNew: function( url, transition, title, pageUrl, role ) { //if there's forward history, wipe it if( urlHistory.getNext() ) { urlHistory.clearForward(); } urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl, role: role } ); urlHistory.activeIndex = urlHistory.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 ); }, directHashChange: function( opts ) { var back , forward, newActiveIndex, prev = this.getActive(); // check if url isp in history and if it's ahead or behind current page $.each( urlHistory.stack, function( i, historyEntry ) { //if the url is in the stack, it's a forward or a back if( opts.currentUrl === historyEntry.url ) { //define back and forward by whether url is older or newer than current page back = i < urlHistory.activeIndex; forward = !back; newActiveIndex = i; } }); // save new page index, null check to prevent falsey 0 result this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex; if( back ) { ( opts.either || opts.isBack )( true ); } else if( forward ) { ( opts.either || opts.isForward )( false ); } }, //disable hashchange event listener internally to ignore one change //toggled internally when location.hash is updated to match the url of a successful page load ignoreNextHashChange: false }, //define first selector to receive focus when a page is shown focusable = "[tabindex],a,button:visible,select:visible,input", //queue to hold simultanious page transitions pageTransitionQueue = [], //indicates whether or not page is in process of transitioning isPageTransitioning = false, //nonsense hash change key for dialogs, so they create a history entry dialogHashKey = "&ui-state=dialog", //existing base tag? $base = $head.children( "base" ), //tuck away the original document URL minus any fragment. documentUrl = path.parseUrl( location.href ), //if the document has an embedded base tag, documentBase is set to its //initial value. If a base tag does not exist, then we default to the documentUrl. documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl, //cache the comparison once. documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ); //base element management, defined depending on dynamic base tag support var base = $.support.dynamicBaseTag ? { //define base element, for use in routing asset urls that are referenced in Ajax-requested markup element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ), //set the generated BASE element's href attribute to a new page's base path set: function( href ) { base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) ); }, //set the generated BASE element's href attribute to a new page's base path reset: function() { base.element.attr( "href", documentBase.hrefNoHash ); } } : undefined; /* internal utility functions --------------------------------------*/ //direct focus to the page title, or otherwise first focusable element function reFocus( page ) { var pageTitle = page.find( ".ui-title:eq(0)" ); if( pageTitle.length ) { pageTitle.focus(); } else{ page.focus(); } } //remove active classes after page transition or error function removeActiveLinkClass( forceRemoval ) { if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) { $activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $activeClickedLink = null; } function releasePageTransitionLock() { isPageTransitioning = false; if( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } } // Save the last scroll distance per page, before it is hidden var setLastScrollEnabled = true, firstScrollElem, getScrollElem, setLastScroll, delayedSetLastScroll; getScrollElem = function() { var scrollElem = $window, activePage, touchOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled; if( touchOverflow ){ activePage = $( ".ui-page-active" ); scrollElem = activePage.is( ".ui-native-fixed" ) ? activePage.find( ".ui-content" ) : activePage; } return scrollElem; }; setLastScroll = function( scrollElem ) { // this barrier prevents setting the scroll value based on the browser // scrolling the window based on a hashchange if( !setLastScrollEnabled ) { return; } var active = $.mobile.urlHistory.getActive(); if( active ) { var lastScroll = scrollElem && scrollElem.scrollTop(); // Set active page's lastScroll prop. // If the location we're scrolling to is less than minScrollBack, let it go. active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll; } }; // bind to scrollstop to gather scroll position. The delay allows for the hashchange // event to fire and disable scroll recording in the case where the browser scrolls // to the hash targets location (sometimes the top of the page). once pagechange fires // getLastScroll is again permitted to operate delayedSetLastScroll = function() { setTimeout( setLastScroll, 100, $(this) ); }; // disable an scroll setting when a hashchange has been fired, this only works // because the recording of the scroll position is delayed for 100ms after // the browser might have changed the position because of the hashchange $window.bind( $.support.pushState ? "popstate" : "hashchange", function() { setLastScrollEnabled = false; }); // handle initial hashchange from chrome :( $window.one( $.support.pushState ? "popstate" : "hashchange", function() { setLastScrollEnabled = true; }); // wait until the mobile page container has been determined to bind to pagechange $window.one( "pagecontainercreate", function(){ // once the page has changed, re-enable the scroll recording $.mobile.pageContainer.bind( "pagechange", function() { var scrollElem = getScrollElem(); setLastScrollEnabled = true; // remove any binding that previously existed on the get scroll // which may or may not be different than the scroll element determined for // this page previously scrollElem.unbind( "scrollstop", delayedSetLastScroll ); // determine and bind to the current scoll element which may be the window // or in the case of touch overflow the element with touch overflow scrollElem.bind( "scrollstop", delayedSetLastScroll ); }); }); // bind to scrollstop for the first page as "pagechange" won't be fired in that case getScrollElem().bind( "scrollstop", delayedSetLastScroll ); // Make the iOS clock quick-scroll work again if we're using native overflow scrolling /* if( $.support.touchOverflow ){ if( $.mobile.touchOverflowEnabled ){ $( window ).bind( "scrollstop", function(){ if( $( this ).scrollTop() === 0 ){ $.mobile.activePage.scrollTop( 0 ); } }); } } */ //function for transitioning between two existing pages function transitionPages( toPage, fromPage, transition, reverse ) { //get current scroll distance var active = $.mobile.urlHistory.getActive(), touchOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled, toScroll = active.lastScroll || ( touchOverflow ? 0 : $.mobile.defaultHomeScroll ), screenHeight = getScreenHeight(); // Scroll to top, hide addr bar window.scrollTo( 0, $.mobile.defaultHomeScroll ); if( fromPage ) { //trigger before show/hide events fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } ); } if( !touchOverflow){ toPage.height( screenHeight + toScroll ); } toPage.data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } ); //clear page loader $.mobile.hidePageLoadingMsg(); if( touchOverflow && toScroll ){ toPage.addClass( "ui-mobile-pre-transition" ); // Send focus to page as it is now display: block reFocus( toPage ); //set page's scrollTop to remembered distance if( toPage.is( ".ui-native-fixed" ) ){ toPage.find( ".ui-content" ).scrollTop( toScroll ); } else{ toPage.scrollTop( toScroll ); } } //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. var th = $.mobile.transitionHandlers[transition || "none"] || $.mobile.defaultTransitionHandler, promise = th( transition, reverse, toPage, fromPage ); promise.done(function() { //reset toPage height back if( !touchOverflow ){ toPage.height( "" ); // Send focus to the newly shown page reFocus( toPage ); } // Jump to top or prev scroll, sometimes on iOS the page has not rendered yet. if( !touchOverflow ){ $.mobile.silentScroll( toScroll ); } //trigger show/hide events if( fromPage ) { if( !touchOverflow ){ fromPage.height( "" ); } fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } ); } //trigger pageshow, define prevPage as either fromPage or empty jQuery obj toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } ); }); return promise; } //simply set the active page's minimum height to screen height, depending on orientation function getScreenHeight(){ var orientation = $.event.special.orientationchange.orientation(), port = orientation === "portrait", winMin = port ? 480 : 320, screenHeight = port ? screen.availHeight : screen.availWidth, winHeight = Math.max( winMin, $( window ).height() ), pageMin = Math.min( screenHeight, winHeight ); return pageMin; } $.mobile.getScreenHeight = getScreenHeight; //simply set the active page's minimum height to screen height, depending on orientation function resetActivePageHeight(){ // Don't apply this height in touch overflow enabled mode if( $.support.touchOverflow && $.mobile.touchOverflowEnabled ){ return; } $( "." + $.mobile.activePageClass ).css( "min-height", getScreenHeight() ); } //shared page enhancements function enhancePage( $page, role ) { // If a role was specified, make sure the data-role attribute // on the page element is in sync. if( role ) { $page.attr( "data-" + $.mobile.ns + "role", role ); } //run page plugin $page.page(); } /* exposed $.mobile methods */ //animation complete callback $.fn.animationComplete = function( callback ) { if( $.support.cssTransitions ) { return $( this ).one( 'webkitAnimationEnd', callback ); } else{ // defer execution for consistency between webkit/non webkit setTimeout( callback, 0 ); return $( this ); } }; //expose path object on $.mobile $.mobile.path = path; //expose base object on $.mobile $.mobile.base = base; //history stack $.mobile.urlHistory = urlHistory; $.mobile.dialogHashKey = dialogHashKey; //default non-animation transition handler $.mobile.noneTransitionHandler = function( name, reverse, $toPage, $fromPage ) { if ( $fromPage ) { $fromPage.removeClass( $.mobile.activePageClass ); } $toPage.addClass( $.mobile.activePageClass ); return $.Deferred().resolve( name, reverse, $toPage, $fromPage ).promise(); }; //default handler for unknown transitions $.mobile.defaultTransitionHandler = $.mobile.noneTransitionHandler; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { none: $.mobile.defaultTransitionHandler }; //enable cross-domain page support $.mobile.allowCrossDomainPages = false; //return the original document url $.mobile.getDocumentUrl = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href; }; //return the original document base url $.mobile.getDocumentBase = function(asParsedObject) { return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href; }; $.mobile._bindPageRemove = function() { var page = $(this); // when dom caching is not enabled or the page is embedded bind to remove the page on hide if( !page.data("page").options.domCache && page.is(":jqmData(external-page='true')") ) { page.bind( 'pagehide.remove', function() { var $this = $( this ), prEvent = new $.Event( "pageremove" ); $this.trigger( prEvent ); if( !prEvent.isDefaultPrevented() ){ $this.removeWithDependents(); } }); } }; // Load a page into the DOM. $.mobile.loadPage = function( url, options ) { // This function uses deferred notifications to let callers // know when the page is done loading, or if an error has occurred. var deferred = $.Deferred(), // The default loadPage options with overrides specified by // the caller. settings = $.extend( {}, $.mobile.loadPage.defaults, options ), // The DOM element for the page after it has been loaded. page = null, // If the reloadPage option is true, and the page is already // in the DOM, dupCachedPage will be set to the page element // so that it can be removed after the new version of the // page is loaded off the network. dupCachedPage = null, // determine the current base url findBaseWithDefault = function(){ var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) ); return closestBase || documentBase.hrefNoHash; }, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subpage params in it. absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() ); // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // If the caller is using a "post" request, reloadPage must be true if( settings.data && settings.type === "post" ){ settings.reloadPage = true; } // The absolute version of the URL minus any dialog/subpage params. // In otherwords the real URL of the page to be loaded. var fileUrl = path.getFilePath( absUrl ), // The version of the Url actually stored in the data-url attribute of // the page. For embedded pages, it is just the id of the page. For pages // within the same domain as the document base, it is the site relative // path. For cross-domain pages (Phone Gap only) the entire absolute Url // used to load the page. dataUrl = path.convertUrlToDataUrl( absUrl ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Check to see if the page already exists in the DOM. page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); // If we failed to find the page, check to see if the url is a // reference to an embedded page. If so, it may have been dynamically // injected by a developer, in which case it would be lacking a data-url // attribute and in need of enhancement. if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) { page = settings.pageContainer.children( "#" + dataUrl ) .attr( "data-" + $.mobile.ns + "url", dataUrl ); } // If we failed to find a page in the DOM, check the URL to see if it // refers to the first page in the application. If it isn't a reference // to the first page and refers to non-existent embedded page, error out. if ( page.length === 0 ) { if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) { // Check to make sure our cached-first-page is actually // in the DOM. Some user deployed apps are pruning the first // page from the DOM for various reasons, we check for this // case here because we don't want a first-page with an id // falling through to the non-existent embedded page error // case. If the first-page is not in the DOM, then we let // things fall through to the ajax loading code below so // that it gets reloaded. if ( $.mobile.firstPage.parent().length ) { page = $( $.mobile.firstPage ); } } else if ( path.isEmbeddedPage( fileUrl ) ) { deferred.reject( absUrl, options ); return deferred.promise(); } } // Reset base to the default document base. if ( base ) { base.reset(); } // If the page we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Otherwise, track the // existing page as a duplicated. if ( page.length ) { if ( !settings.reloadPage ) { enhancePage( page, settings.role ); deferred.resolve( absUrl, options, page ); return deferred.promise(); } dupCachedPage = page; } var mpc = settings.pageContainer, pblEvent = new $.Event( "pagebeforeload" ), triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings }; // Let listeners know we're about to load a page. mpc.trigger( pblEvent, triggerData ); // If the default behavior is prevented, stop here! if( pblEvent.isDefaultPrevented() ){ return deferred.promise(); } if ( settings.showLoadMsg ) { // This configurable timeout allows cached pages a brief delay to load without showing a message var loadMsgDelay = setTimeout(function(){ $.mobile.showPageLoadingMsg(); }, settings.loadMsgDelay ), // Shared logic for clearing timeout and removing message. hideMsg = function(){ // Stop message show timer clearTimeout( loadMsgDelay ); // Hide loading message $.mobile.hidePageLoadingMsg(); }; } if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) { deferred.reject( absUrl, options ); } else { // Load the new page. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, dataType: "html", success: function( html, textStatus, xhr ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var all = $( "<div></div>" ), //page title regexp newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1, // TODO handle dialogs again pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ), dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests can be directed to the // correct url. loading into a temprorary element makes these requests immediately if( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { url = fileUrl = path.getFilePath( RegExp.$1 ); } if ( base ) { base.set( fileUrl ); } //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if( !page.length ){ page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" ); } if ( newPageTitle && !page.jqmData( "title" ) ) { if ( ~newPageTitle.indexOf( "&" ) ) { newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text(); } page.jqmData( "title", newPageTitle ); } //rewrite src and href attrs to use a base url if( !$.support.dynamicBaseTag ) { var newPath = path.get( fileUrl ); page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() { var thisAttr = $( this ).is( '[href]' ) ? 'href' : $(this).is('[src]') ? 'src' : 'action', thisUrl = $( this ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. //if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' ); if( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( this ).attr( thisAttr, newPath + thisUrl ); } }); } //append to page and enhance // TODO taging a page with external to make sure that embedded pages aren't removed // by the various page handling code is bad. Having page handling code in many // places is bad. Solutions post 1.0 page .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) ) .attr( "data-" + $.mobile.ns + "external-page", true ) .appendTo( settings.pageContainer ); // wait for page creation to leverage options defined on widget page.one( 'pagecreate', $.mobile._bindPageRemove ); enhancePage( page, settings.role ); // Enhancing the page may result in new dialogs/sub pages being inserted // into the DOM. If the original absUrl refers to a sub-page, that is the // real page we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" ); } //bind pageHide to removePage after it's hidden, if the page options specify to do so // Remove loading message. if ( settings.showLoadMsg ) { hideMsg(); } // Add the page reference and xhr to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.page = page; // Let listeners know the page loaded successfully. settings.pageContainer.trigger( "pageload", triggerData ); deferred.resolve( absUrl, options, page, dupCachedPage ); }, error: function( xhr, textStatus, errorThrown ) { //set base back to current path if( base ) { base.set( path.get() ); } // Add error info to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.errorThrown = errorThrown; var plfEvent = new $.Event( "pageloadfailed" ); // Let listeners know the page load failed. settings.pageContainer.trigger( plfEvent, triggerData ); // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if( plfEvent.isDefaultPrevented() ){ return; } // Remove loading message. if ( settings.showLoadMsg ) { // Remove loading message. hideMsg(); //show error message $( "<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>"+ $.mobile.pageLoadErrorMessage +"</h1></div>" ) .css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 }) .appendTo( settings.pageContainer ) .delay( 800 ) .fadeOut( 400, function() { $( this ).remove(); }); } deferred.reject( absUrl, options ); } }); } return deferred.promise(); }; $.mobile.loadPage.defaults = { type: "get", data: undefined, reloadPage: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. showLoadMsg: false, pageContainer: undefined, loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message. }; // Show a specific page in the page container. $.mobile.changePage = function( toPage, options ) { // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition to // service the request. if( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } var settings = $.extend( {}, $.mobile.changePage.defaults, options ); // Make sure we have a pageContainer to work with. settings.pageContainer = settings.pageContainer || $.mobile.pageContainer; // Make sure we have a fromPage. settings.fromPage = settings.fromPage || $.mobile.activePage; var mpc = settings.pageContainer, pbcEvent = new $.Event( "pagebeforechange" ), triggerData = { toPage: toPage, options: settings }; // Let listeners know we're about to change the current page. mpc.trigger( pbcEvent, triggerData ); // If the default behavior is prevented, stop here! if( pbcEvent.isDefaultPrevented() ){ return; } // We allow "pagebeforechange" observers to modify the toPage in the trigger // data to allow for redirects. Make sure our toPage is updated. toPage = triggerData.toPage; // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( typeof toPage == "string" ) { $.mobile.loadPage( toPage, settings ) .done(function( url, options, newPage, dupCachedPage ) { isPageTransitioning = false; options.duplicateCachedPage = dupCachedPage; $.mobile.changePage( newPage, options ); }) .fail(function( url, options ) { isPageTransitioning = false; //clear out the active button state removeActiveLinkClass( true ); //release transition lock so navigation is free again releasePageTransitionLock(); settings.pageContainer.trigger( "pagechangefailed", triggerData ); }); return; } // If we are going to the first-page of the application, we need to make // sure settings.dataUrl is set to the application document url. This allows // us to avoid generating a document url with an id hash in the case where the // first-page of the document has an id attribute specified. if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) { settings.dataUrl = documentUrl.hrefNoHash; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. var fromPage = settings.fromPage, url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ), // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path pageUrl = url, fileUrl = path.getFilePath( url ), active = urlHistory.getActive(), activeIsInitialPage = urlHistory.activeIndex === 0, historyDir = 0, pageTitle = document.title, isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog"; // By default, we prevent changePage requests when the fromPage and toPage // are the same element, but folks that generate content manually/dynamically // and reuse pages want to be able to transition to the same page. To allow // this, they will need to change the default value of allowSamePageTransition // to true, *OR*, pass it in as an option when they manually call changePage(). // It should be noted that our default transition animations assume that the // formPage and toPage are different elements, so they may behave unexpectedly. // It is up to the developer that turns on the allowSamePageTransitiona option // to either turn off transition animations, or make sure that an appropriate // animation transition is used. if( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) { isPageTransitioning = false; mpc.trigger( "pagechange", triggerData ); return; } // We need to make sure the page we are given has already been enhanced. enhancePage( toPage, settings.role ); // If the changePage request was sent from a hashChange event, check to see if the // page is already within the urlHistory stack. If so, we'll assume the user hit // the forward/back button and will try to match the transition accordingly. if( settings.fromHashChange ) { urlHistory.directHashChange({ currentUrl: url, isBack: function() { historyDir = -1; }, isForward: function() { historyDir = 1; } }); } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead, // we should be tracking focus with a live() handler so we already have // the element in hand at this point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement // is undefined when we are in an IFrame. try { if(document.activeElement && document.activeElement.nodeName.toLowerCase() != 'body') { $(document.activeElement).blur(); } else { $( "input:focus, textarea:focus, select:focus" ).blur(); } } catch(e) {} // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { // on the initial page load active.url is undefined and in that case should // be an empty string. Moving the undefined -> empty string back into // urlHistory.addNew seemed imprudent given undefined better represents // the url state url = ( active.url || "" ) + dialogHashKey; } // Set the location hash. if( settings.changeHash !== false && url ) { //disable hash listening temporarily urlHistory.ignoreNextHashChange = true; //update hash and history path.set( url ); } // if title element wasn't found, try the page div data attr too // If this is a deep-link or a reload ( active === undefined ) then just use pageTitle var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).getEncodedText(); if( !!newPageTitle && pageTitle == document.title ) { pageTitle = newPageTitle; } if ( !toPage.jqmData( "title" ) ) { toPage.jqmData( "title", pageTitle ); } // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); //add page to history stack if it's not back or forward if( !historyDir ) { urlHistory.addNew( url, settings.transition, pageTitle, pageUrl, settings.role ); } //set page title document.title = urlHistory.getActive().title; //set "toPage" as activePage $.mobile.activePage = toPage; // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function() { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } //remove initial build class (only present on first pageshow) $html.removeClass( "ui-mobile-rendering" ); releasePageTransitionLock(); // Let listeners know we're all done changing the current page. mpc.trigger( "pagechange", triggerData ); }); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage dataUrl: undefined, fromPage: undefined, allowSamePageTransition: false }; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { // Look for the closest element with a nodeName of "a". // Note that we are checking if we have a valid nodeName // before attempting to access it. This is because the // node we get called with could have originated from within // an embedded SVG document where some symbol instance elements // don't have nodeName defined on them, or strings are of type // SVGAnimatedString. if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() == "a" ) { break; } ele = ele.parentNode; } return ele; } // The base URL for any given element depends on the page it resides in. function getClosestBaseUrl( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = documentBase.hrefNoHash; if ( !url || !path.isPath( url ) ) { url = base; } return path.makeUrlAbsolute( url, base); } //The following event bindings should be bound after mobileinit has been triggered //the following function is called in the init file $.mobile._registerInternalEvents = function(){ //bind to form submit events, handle with Ajax $( "form" ).live('submit', function( event ) { var $this = $( this ); if( !$.mobile.ajaxEnabled || $this.is( ":jqmData(ajax='false')" ) ) { return; } var type = $this.attr( "method" ), target = $this.attr( "target" ), url = $this.attr( "action" ); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = getClosestBaseUrl( $this ); if ( url === documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) ); //external submits use regular HTTP if( path.isExternal( url ) || target ) { return; } $.mobile.changePage( url, { type: type && type.length && type.toLowerCase() || "get", data: $this.serialize(), transition: $this.jqmData( "transition" ), direction: $this.jqmData( "direction" ), reloadPage: true } ); event.preventDefault(); }); //add active state on vclick $( document ).bind( "vclick", function( event ) { // if this isn't a left click we don't care. Its important to note // that when the virtual event is generated it will create if ( event.which > 1 || !$.mobile.linkBindingEnabled ){ return; } var link = findClosestLink( event.target ); if ( link ) { if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) { removeActiveLinkClass( true ); $activeClickedLink = $( link ).closest( ".ui-btn" ).not( ".ui-disabled" ); $activeClickedLink.addClass( $.mobile.activeBtnClass ); $( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur(); } } }); // click routing - direct to HTTP or Ajax, accordingly $( document ).bind( "click", function( event ) { if( !$.mobile.linkBindingEnabled ){ return; } var link = findClosestLink( event.target ); // If there is no link associated with the click or its not a left // click we want to ignore the click if ( !link || event.which > 1) { return; } var $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function(){ window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 ); }; //if there's a data-rel=back attr, go back in history if( $link.is( ":jqmData(rel='back')" ) ) { window.history.back(); return false; } var baseUrl = getClosestBaseUrl( $link ), //get href, if defined, otherwise default to empty hash href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); //if ajax is disabled, exit early if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){ httpCleanup(); //use default click handling return; } // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) != -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( path.isPath( href ) ) { //we have apath so make it the href we want to load. href = path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ), // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ), //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad ); if( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax var transition = $link.jqmData( "transition" ), direction = $link.jqmData( "direction" ), reverse = ( direction && direction === "reverse" ) || // deprecated - remove by 1.0 $link.jqmData( "back" ), //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $( ".ui-page" ).live( "pageshow.prefetch", function() { var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function(){ var $link = $(this), url = $link.attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url, {role: $link.attr("data-" + $.mobile.ns + "rel")} ); } }); }); $.mobile._handleHashChange = function( hash ) { //find first page via hash var to = path.stripHash( hash ), //transition is false if it's the first page, undefined otherwise (and may be overridden by default) transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined, // default options for the changPage calls made after examining the current state // of the page and the hash changePageOptions = { transition: transition, changeHash: false, fromHashChange: true }; //if listening is disabled (either globally or temporarily), or it's a dialog hash if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) { urlHistory.ignoreNextHashChange = false; return; } // special case for dialogs if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) { // If current active page is not a dialog skip the dialog and continue // in the same direction if(!$.mobile.activePage.is( ".ui-dialog" )) { //determine if we're heading forward or backward and continue accordingly past //the current dialog urlHistory.directHashChange({ currentUrl: to, isBack: function() { window.history.back(); }, isForward: function() { window.history.forward(); } }); // prevent changePage() return; } else { // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack urlHistory.directHashChange({ currentUrl: to, // regardless of the direction of the history change // do the following either: function( isBack ) { var active = $.mobile.urlHistory.getActive(); to = active.pageUrl; // make sure to set the role, transition and reversal // as most of this is lost by the domCache cleaning $.extend( changePageOptions, { role: active.role, transition: active.transition, reverse: isBack }); } }); } } //if to is defined, load it if ( to ) { // At this point, 'to' can be one of 3 things, a cached page element from // a history stack entry, an id, or site-relative/absolute URL. If 'to' is // an id, we need to resolve it against the documentBase, not the location.href, // since the hashchange could've been the result of a forward/backward navigation // that crosses from an external page/dialog to an internal page/dialog. to = ( typeof to === "string" && !path.isPath( to ) ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to; $.mobile.changePage( to, changePageOptions ); } else { //there's no hash, go to the first page in the dom $.mobile.changePage( $.mobile.firstPage, changePageOptions ); } }; //hashchange event handler $window.bind( "hashchange", function( e, triggered ) { $.mobile._handleHashChange( location.hash ); }); //set page min-heights to be device specific $( document ).bind( "pageshow", resetActivePageHeight ); $( window ).bind( "throttledresize", resetActivePageHeight ); };//_registerInternalEvents callback })( jQuery ); /* * history.pushState support, layered on top of hashchange */ ( function( $, window ) { // For now, let's Monkeypatch this onto the end of $.mobile._registerInternalEvents // Scope self to pushStateHandler so we can reference it sanely within the // methods handed off as event handlers var pushStateHandler = {}, self = pushStateHandler, $win = $( window ), url = $.mobile.path.parseUrl( location.href ); $.extend( pushStateHandler, { // TODO move to a path helper, this is rather common functionality initialFilePath: (function() { return url.pathname + url.search; })(), initialHref: url.hrefNoHash, // Flag for tracking if a Hashchange naturally occurs after each popstate + replace hashchangeFired: false, state: function() { return { hash: location.hash || "#" + self.initialFilePath, title: document.title, // persist across refresh initialHref: self.initialHref }; }, resetUIKeys: function( url ) { var dialog = $.mobile.dialogHashKey, subkey = "&" + $.mobile.subPageUrlKey, dialogIndex = url.indexOf( dialog ); if( dialogIndex > -1 ) { url = url.slice( 0, dialogIndex ) + "#" + url.slice( dialogIndex ); } else if( url.indexOf( subkey ) > -1 ) { url = url.split( subkey ).join( "#" + subkey ); } return url; }, // TODO sort out a single barrier to hashchange functionality nextHashChangePrevented: function( value ) { $.mobile.urlHistory.ignoreNextHashChange = value; self.onHashChangeDisabled = value; }, // on hash change we want to clean up the url // NOTE this takes place *after* the vanilla navigation hash change // handling has taken place and set the state of the DOM onHashChange: function( e ) { // disable this hash change if( self.onHashChangeDisabled ){ return; } var href, state, hash = location.hash, isPath = $.mobile.path.isPath( hash ), resolutionUrl = isPath ? location.href : $.mobile.getDocumentUrl(); hash = isPath ? hash.replace( "#", "" ) : hash; // propulate the hash when its not available state = self.state(); // make the hash abolute with the current href href = $.mobile.path.makeUrlAbsolute( hash, resolutionUrl ); if ( isPath ) { href = self.resetUIKeys( href ); } // replace the current url with the new href and store the state // Note that in some cases we might be replacing an url with the // same url. We do this anyways because we need to make sure that // all of our history entries have a state object associated with // them. This allows us to work around the case where window.history.back() // is called to transition from an external page to an embedded page. // In that particular case, a hashchange event is *NOT* generated by the browser. // Ensuring each history entry has a state object means that onPopState() // will always trigger our hashchange callback even when a hashchange event // is not fired. history.replaceState( state, document.title, href ); }, // on popstate (ie back or forward) we need to replace the hash that was there previously // cleaned up by the additional hash handling onPopState: function( e ) { var poppedState = e.originalEvent.state, holdnexthashchange = false; // if there's no state its not a popstate we care about, ie chrome's initial popstate // or forward popstate if( poppedState ) { // disable any hashchange triggered by the browser self.nextHashChangePrevented( true ); // defer our manual hashchange until after the browser fired // version has come and gone setTimeout(function() { // make sure that the manual hash handling takes place self.nextHashChangePrevented( false ); // change the page based on the hash $.mobile._handleHashChange( poppedState.hash ); }, 100); } }, init: function() { $win.bind( "hashchange", self.onHashChange ); // Handle popstate events the occur through history changes $win.bind( "popstate", self.onPopState ); // if there's no hash, we need to replacestate for returning to home if ( location.hash === "" ) { history.replaceState( self.state(), document.title, location.href ); } } }); $( function() { if( $.mobile.pushStateEnabled && $.support.pushState ){ pushStateHandler.init(); } }); })( jQuery, this ); /* * "transitions" plugin - Page change tranistions */ (function( $, window, undefined ) { function css3TransitionHandler( name, reverse, $to, $from ) { var deferred = new $.Deferred(), reverseClass = reverse ? " reverse" : "", viewportClass = "ui-mobile-viewport-transitioning viewport-" + name, doneFunc = function() { $to.add( $from ).removeClass( "out in reverse " + name ); if ( $from && $from[ 0 ] !== $to[ 0 ] ) { $from.removeClass( $.mobile.activePageClass ); } $to.parent().removeClass( viewportClass ); deferred.resolve( name, reverse, $to, $from ); }; $to.animationComplete( doneFunc ); $to.parent().addClass( viewportClass ); if ( $from ) { $from.addClass( name + " out" + reverseClass ); } $to.addClass( $.mobile.activePageClass + " " + name + " in" + reverseClass ); return deferred.promise(); } // Make our transition handler public. $.mobile.css3TransitionHandler = css3TransitionHandler; // If the default transition handler is the 'none' handler, replace it with our handler. if ( $.mobile.defaultTransitionHandler === $.mobile.noneTransitionHandler ) { $.mobile.defaultTransitionHandler = css3TransitionHandler; } })( jQuery, this ); /* * "degradeInputs" plugin - degrades inputs to another type after custom enhancements are made. */ (function( $, undefined ) { $.mobile.page.prototype.options.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: "text", tel: false, time: false, url: false, week: false }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ var page = $(e.target).closest(':jqmData(role="page")').data("page"), options; if( !page ) { return; } options = page.options; // degrade inputs to avoid poorly implemented native functionality $( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() { var $this = $( this ), type = this.getAttribute( "type" ), optType = options.degradeInputs[ type ] || "text"; if ( options.degradeInputs[ type ] ) { var html = $( "<div>" ).html( $this.clone() ).html(), // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead hasType = html.indexOf( " type=" ) > -1, findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/, repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" ); $this.replaceWith( html.replace( findstr, repstr ) ); } }); }); })( jQuery );/* * "dialog" plugin. */ (function( $, window, undefined ) { $.widget( "mobile.dialog", $.mobile.widget, { options: { closeBtnText : "Close", overlayTheme : "a", initSelector : ":jqmData(role='dialog')" }, _create: function() { var self = this, $el = this.element, headerCloseButton = $( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ); $el.addClass( "ui-overlay-" + this.options.overlayTheme ); // Class the markup for dialog styling // Set aria role $el.attr( "role", "dialog" ) .addClass( "ui-dialog" ) .find( ":jqmData(role='header')" ) .addClass( "ui-corner-top ui-overlay-shadow" ) .prepend( headerCloseButton ) .end() .find( ":jqmData(role='content'),:jqmData(role='footer')" ) .addClass( "ui-overlay-shadow" ) .last() .addClass( "ui-corner-bottom" ); // this must be an anonymous function so that select menu dialogs can replace // the close method. This is a change from previously just defining data-rel=back // on the button and letting nav handle it headerCloseButton.bind( "vclick", function() { self.close(); }); /* bind events - clicks and submits should use the closing transition that the dialog opened with unless a data-transition is specified on the link/form - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally */ $el.bind( "vclick submit", function( event ) { var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ), active; if ( $target.length && !$target.jqmData( "transition" ) ) { active = $.mobile.urlHistory.getActive() || {}; $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) ) .attr( "data-" + $.mobile.ns + "direction", "reverse" ); } }) .bind( "pagehide", function() { $( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass ); }); }, // Close method goes back in history close: function() { window.history.back(); } }); //auto self-init widgets $( $.mobile.dialog.prototype.options.initSelector ).live( "pagecreate", function(){ $( this ).dialog(); }); })( jQuery, this ); /* * This plugin handles theming and layout of headers, footers, and content areas */ (function( $, undefined ) { $.mobile.page.prototype.options.backBtnText = "Back"; $.mobile.page.prototype.options.addBackBtn = false; $.mobile.page.prototype.options.backBtnTheme = null; $.mobile.page.prototype.options.headerTheme = "a"; $.mobile.page.prototype.options.footerTheme = "a"; $.mobile.page.prototype.options.contentTheme = null; $( ":jqmData(role='page'), :jqmData(role='dialog')" ).live( "pagecreate", function( e ) { var $page = $( this ), o = $page.data( "page" ).options, pageRole = $page.jqmData( "role" ), pageTheme = o.theme; $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this ).each(function() { var $this = $( this ), role = $this.jqmData( "role" ), theme = $this.jqmData( "theme" ), contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ), $headeranchors, leftbtn, rightbtn, backBtn; $this.addClass( "ui-" + role ); //apply theming and markup modifications to page,header,content,footer if ( role === "header" || role === "footer" ) { var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme; $this //add theme class .addClass( "ui-bar-" + thisTheme ) // Add ARIA role .attr( "role", role === "header" ? "banner" : "contentinfo" ); // Right,left buttons $headeranchors = $this.children( "a" ); leftbtn = $headeranchors.hasClass( "ui-btn-left" ); rightbtn = $headeranchors.hasClass( "ui-btn-right" ); leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; // Auto-add back btn on pages beyond first view if ( o.addBackBtn && role === "header" && $( ".ui-page" ).length > 1 && $this.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) && !leftbtn ) { backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" ) // If theme is provided, override default inheritance .attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme ) .prependTo( $this ); } // Page title $this.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "tabindex": "0", "role": "heading", "aria-level": "1" }); } else if ( role === "content" ) { if ( contentTheme ) { $this.addClass( "ui-body-" + ( contentTheme ) ); } // Add ARIA role $this.attr( "role", "main" ); } }); }); })( jQuery );/* * "collapsible" plugin */ (function( $, undefined ) { $.widget( "mobile.collapsible", $.mobile.widget, { options: { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", theme: null, contentTheme: null, iconTheme: "d", initSelector: ":jqmData(role='collapsible')" }, _create: function() { var $el = this.element, o = this.options, collapsible = $el.addClass( "ui-collapsible" ), collapsibleHeading = $el.children( o.heading ).first(), collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ), collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ), collapsiblesInSet = collapsibleSet.children( ":jqmData(role='collapsible')" ); // Replace collapsibleHeading if it's a legend if ( collapsibleHeading.is( "legend" ) ) { collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading ); collapsibleHeading.next().remove(); } // If we are in a collapsible set if ( collapsibleSet.length ) { // Inherit the theme from collapsible-set if ( !o.theme ) { o.theme = collapsibleSet.jqmData( "theme" ); } // Inherit the content-theme from collapsible-set if ( !o.contentTheme ) { o.contentTheme = collapsibleSet.jqmData( "content-theme" ); } } collapsibleContent.addClass( ( o.contentTheme ) ? ( "ui-body-" + o.contentTheme ) : ""); collapsibleHeading //drop heading in before content .insertBefore( collapsibleContent ) //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( "<span class='ui-collapsible-heading-status'></span>" ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .buttonMarkup({ shadow: false, corners: false, iconPos: "left", icon: "plus", theme: o.theme }); if ( !collapsibleSet.length ) { collapsibleHeading .find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) ) .addClass( "ui-corner-top ui-corner-bottom" ); } else { // If we are in a collapsible set // Initialize the collapsible set if it's not already initialized if ( !collapsibleSet.jqmData( "collapsiblebound" ) ) { collapsibleSet .jqmData( "collapsiblebound", true ) .bind( "expand", function( event ) { $( event.target ) .closest( ".ui-collapsible" ) .siblings( ".ui-collapsible" ) .trigger( "collapse" ); }); } collapsiblesInSet.first() .find( "a" ) .first() .addClass( "ui-corner-top" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-top" ); collapsiblesInSet.last() .jqmData( "collapsible-last", true ) .find( "a" ) .first() .addClass( "ui-corner-bottom" ) .find( ".ui-btn-inner" ) .addClass( "ui-corner-bottom" ); if ( collapsible.jqmData( "collapsible-last" ) ) { collapsibleHeading .find( "a" ).first().add ( collapsibleHeading.find( ".ui-btn-inner" ) ) .addClass( "ui-corner-bottom" ); } } //events collapsible .bind( "expand collapse", function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); var $this = $( this ), isCollapse = ( event.type === "collapse" ), contentTheme = o.contentTheme; collapsibleHeading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse) .find( ".ui-collapsible-heading-status" ) .text( isCollapse ? o.expandCueText : o.collapseCueText ) .end() .find( ".ui-icon" ) .toggleClass( "ui-icon-minus", !isCollapse ) .toggleClass( "ui-icon-plus", isCollapse ); $this.toggleClass( "ui-collapsible-collapsed", isCollapse ); collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse ); if ( contentTheme && ( !collapsibleSet.length || collapsible.jqmData( "collapsible-last" ) ) ) { collapsibleHeading .find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) ) .toggleClass( "ui-corner-bottom", isCollapse ); collapsibleContent.toggleClass( "ui-corner-bottom", !isCollapse ); } collapsibleContent.trigger( "updatelayout" ); } }) .trigger( o.collapsed ? "collapse" : "expand" ); collapsibleHeading .bind( "click", function( event ) { var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse"; collapsible.trigger( type ); event.preventDefault(); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.collapsible.prototype.options.initSelector, e.target ).collapsible(); }); })( jQuery ); /* * "fieldcontain" plugin - simple class additions to make form row separators */ (function( $, undefined ) { $.fn.fieldcontain = function( options ) { return this.addClass( "ui-field-contain ui-body ui-br" ); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='fieldcontain')", e.target ).fieldcontain(); }); })( jQuery );/* * plugin for creating CSS grids */ (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null },options), $kids = $this.children(), gridCols = {solo:1, a:2, b:3, c:4, d:5}, grid = o.grid, iterator; if ( !grid ) { if ( $kids.length <= 5 ) { for ( var letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery );/* * "navbar" plugin */ (function( $, undefined ) { $.widget( "mobile.navbar", $.mobile.widget, { options: { iconpos: "top", grid: null, initSelector: ":jqmData(role='navbar')" }, _create: function(){ var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role","navigation" ) .find( "ul" ) .grid({ grid: this.options.grid }); if ( !iconpos ) { $navbar.addClass( "ui-navbar-noicons" ); } $navbtns.buttonMarkup({ corners: false, shadow: false, iconpos: iconpos }); $navbar.delegate( "a", "vclick", function( event ) { $navbtns.not( ".ui-state-persist" ).removeClass( $.mobile.activeBtnClass ); $( this ).addClass( $.mobile.activeBtnClass ); }); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.navbar.prototype.options.initSelector, e.target ).navbar(); }); })( jQuery ); /* * "listview" plugin */ (function( $, undefined ) { //Keeps track of the number of lists per page UID //This allows support for multiple nested list in the same page //https://github.com/jquery/jquery-mobile/issues/1617 var listCountPerPage = {}; $.widget( "mobile.listview", $.mobile.widget, { options: { theme: null, countTheme: "c", headerTheme: "b", dividerTheme: "b", splitIcon: "arrow-r", splitTheme: "b", inset: false, initSelector: ":jqmData(role='listview')" }, _create: function() { var t = this; // create listview markup t.element.addClass(function( i, orig ) { return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" ); }); t.refresh( true ); }, _removeCorners: function( li, which ) { var top = "ui-corner-top ui-corner-tr ui-corner-tl", bot = "ui-corner-bottom ui-corner-br ui-corner-bl"; li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) ); if ( which === "top" ) { li.removeClass( top ); } else if ( which === "bottom" ) { li.removeClass( bot ); } else { li.removeClass( top + " " + bot ); } }, _refreshCorners: function( create ) { var $li, $visibleli, $topli, $bottomli; if ( this.options.inset ) { $li = this.element.children( "li" ); // at create time the li are not visible yet so we need to rely on .ui-screen-hidden $visibleli = create?$li.not( ".ui-screen-hidden" ):$li.filter( ":visible" ); this._removeCorners( $li ); // Select the first visible li element $topli = $visibleli.first() .addClass( "ui-corner-top" ); $topli.add( $topli.find( ".ui-btn-inner" ) .not( ".ui-li-link-alt span:first-child" ) ) .addClass( "ui-corner-top" ) .end() .find( ".ui-li-link-alt, .ui-li-link-alt span:first-child" ) .addClass( "ui-corner-tr" ) .end() .find( ".ui-li-thumb" ) .not(".ui-li-icon") .addClass( "ui-corner-tl" ); // Select the last visible li element $bottomli = $visibleli.last() .addClass( "ui-corner-bottom" ); $bottomli.add( $bottomli.find( ".ui-btn-inner" ) ) .find( ".ui-li-link-alt" ) .addClass( "ui-corner-br" ) .end() .find( ".ui-li-thumb" ) .not(".ui-li-icon") .addClass( "ui-corner-bl" ); } if ( !create ) { this.element.trigger( "updatelayout" ); } }, // This is a generic utility method for finding the first // node with a given nodeName. It uses basic DOM traversal // to be fast and is meant to be a substitute for simple // $.fn.closest() and $.fn.children() calls on a single // element. Note that callers must pass both the lowerCase // and upperCase version of the nodeName they are looking for. // The main reason for this is that this function will be // called many times and we want to avoid having to lowercase // the nodeName from the element every time to ensure we have // a match. Note that this function lives here for now, but may // be moved into $.mobile if other components need a similar method. _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) { var dict = {}; dict[ lcName ] = dict[ ucName ] = true; while ( ele ) { if ( dict[ ele.nodeName ] ) { return ele; } ele = ele[ nextProp ]; } return null; }, _getChildrenByTagName: function( ele, lcName, ucName ) { var results = [], dict = {}; dict[ lcName ] = dict[ ucName ] = true; ele = ele.firstChild; while ( ele ) { if ( dict[ ele.nodeName ] ) { results.push( ele ); } ele = ele.nextSibling; } return $( results ); }, _addThumbClasses: function( containers ) { var i, img, len = containers.length; for ( i = 0; i < len; i++ ) { img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) ); if ( img.length ) { img.addClass( "ui-li-thumb" ); $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); } } }, refresh: function( create ) { this.parentPage = this.element.closest( ".ui-page" ); this._createSubPages(); var o = this.options, $list = this.element, self = this, dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme, listsplittheme = $list.jqmData( "splittheme" ), listspliticon = $list.jqmData( "spliticon" ), li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ), counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1, itemClassDict = {}, item, itemClass, itemTheme, a, last, splittheme, countParent, icon, imgParents, img; if ( counter ) { $list.find( ".ui-li-dec" ).remove(); } if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( this.element, "c" ); } for ( var pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = "ui-li"; // If we're creating the element, we update it regardless if ( create || !item.hasClass( "ui-li" ) ) { itemTheme = item.jqmData("theme") || o.theme; a = this._getChildrenByTagName( item[ 0 ], "a", "A" ); if ( a.length ) { icon = item.jqmData("icon"); item.buttonMarkup({ wrapperEls: "div", shadow: false, corners: false, iconpos: "right", icon: a.length > 1 || icon === false ? false : icon || "arrow-r", theme: itemTheme }); if ( ( icon != false ) && ( a.length == 1 ) ) { item.addClass( "ui-li-has-arrow" ); } a.first().addClass( "ui-link-inherit" ); if ( a.length > 1 ) { itemClass += " ui-li-has-alt"; last = a.last(); splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme; last.appendTo(item) .attr( "title", last.getEncodedText() ) .addClass( "ui-li-link-alt" ) .empty() .buttonMarkup({ shadow: false, corners: false, theme: itemTheme, icon: false, iconpos: false }) .find( ".ui-btn-inner" ) .append( $( document.createElement( "span" ) ).buttonMarkup({ shadow: true, corners: true, theme: splittheme, iconpos: "notext", icon: listspliticon || last.jqmData( "icon" ) || o.splitIcon }) ); } } else if ( item.jqmData( "role" ) === "list-divider" ) { itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme; item.attr( "role", "heading" ); //reset counter when a divider heading is encountered if ( counter ) { counter = 1; } } else { itemClass += " ui-li-static ui-body-" + itemTheme; } } if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) { countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" ); countParent.addClass( "ui-li-jsnumbering" ) .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" ); } // Instead of setting item class directly on the list item and its // btn-inner at this point in time, push the item into a dictionary // that tells us what class to set on it so we can do this after this // processing loop is finished. if ( !itemClassDict[ itemClass ] ) { itemClassDict[ itemClass ] = []; } itemClassDict[ itemClass ].push( item[ 0 ] ); } // Set the appropriate listview item classes on each list item // and their btn-inner elements. The main reason we didn't do this // in the for-loop above is because we can eliminate per-item function overhead // by calling addClass() and children() once or twice afterwards. This // can give us a significant boost on platforms like WP7.5. for ( itemClass in itemClassDict ) { $( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass ); } $list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" ) .end() .find( "p, dl" ).addClass( "ui-li-desc" ) .end() .find( ".ui-li-aside" ).each(function() { var $this = $(this); $this.prependTo( $this.parent() ); //shift aside to front for css float }) .end() .find( ".ui-li-count" ).each( function() { $( this ).closest( "li" ).addClass( "ui-li-has-count" ); }).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" ); // The idea here is to look at the first image in the list item // itself, and any .ui-link-inherit element it may contain, so we // can place the appropriate classes on the image and list item. // Note that we used to use something like: // // li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... ); // // But executing a find() like that on Windows Phone 7.5 took a // really long time. Walking things manually with the code below // allows the 400 listview item page to load in about 3 seconds as // opposed to 30 seconds. this._addThumbClasses( li ); this._addThumbClasses( $list.find( ".ui-link-inherit" ) ); this._refreshCorners( create ); }, //create a string for ID/subpage url creation _idStringEscape: function( str ) { return str.replace(/[^a-zA-Z0-9]/g, '-'); }, _createSubPages: function() { var parentList = this.element, parentPage = parentList.closest( ".ui-page" ), parentUrl = parentPage.jqmData( "url" ), parentId = parentUrl || parentPage[ 0 ][ $.expando ], parentListId = parentList.attr( "id" ), o = this.options, dns = "data-" + $.mobile.ns, self = this, persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ), hasSubPages; if ( typeof listCountPerPage[ parentId ] === "undefined" ) { listCountPerPage[ parentId ] = -1; } parentListId = parentListId || ++listCountPerPage[ parentId ]; $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) { var self = this, list = $( this ), listId = list.attr( "id" ) || parentListId + "-" + i, parent = list.parent(), nodeEls = $( list.prevAll().toArray().reverse() ), nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ), title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId, theme = list.jqmData( "theme" ) || o.theme, countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme, newPage, anchor; //define hasSubPages for use in later removal hasSubPages = true; newPage = list.detach() .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" ) .parent() .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" ) .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" ) .parent() .appendTo( $.mobile.pageContainer ); newPage.page(); anchor = parent.find('a:first'); if ( !anchor.length ) { anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() ); } anchor.attr( "href", "#" + id ); }).listview(); // on pagehide, remove any nested pages along with the parent page, as long as they aren't active // and aren't embedded if( hasSubPages && parentPage.is( ":jqmData(external-page='true')" ) && parentPage.data("page").options.domCache === false ) { var newRemove = function( e, ui ){ var nextPage = ui.nextPage, npURL; if( ui.nextPage ){ npURL = nextPage.jqmData( "url" ); if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){ self.childPages().remove(); parentPage.remove(); } } }; // unbind the original page remove and replace with our specialized version parentPage .unbind( "pagehide.remove" ) .bind( "pagehide.remove", newRemove); } }, // TODO sort out a better way to track sub pages of the listview this is brittle childPages: function(){ var parentUrl = this.parentPage.jqmData( "url" ); return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')"); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( $.mobile.listview.prototype.options.initSelector, e.target ).listview(); }); })( jQuery ); /* * "listview" filter extension */ (function( $, undefined ) { $.mobile.listview.prototype.options.filter = false; $.mobile.listview.prototype.options.filterPlaceholder = "Filter items..."; $.mobile.listview.prototype.options.filterTheme = "c"; $.mobile.listview.prototype.options.filterCallback = function( text, searchValue ){ return text.toLowerCase().indexOf( searchValue ) === -1; }; $( ":jqmData(role='listview')" ).live( "listviewcreate", function() { var list = $( this ), listview = list.data( "listview" ); if ( !listview.options.filter ) { return; } var wrapper = $( "<form>", { "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme, "role": "search" }), search = $( "<input>", { placeholder: listview.options.filterPlaceholder }) .attr( "data-" + $.mobile.ns + "type", "search" ) .jqmData( "lastval", "" ) .bind( "keyup change", function() { var $this = $(this), val = this.value.toLowerCase(), listItems = null, lastval = $this.jqmData( "lastval" ) + "", childItems = false, itemtext = "", item, change; // Change val as lastval for next execution $this.jqmData( "lastval" , val ); change = val.substr( 0 , lastval.length - 1 ).replace( lastval , "" ); if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) { // Removed chars or pasted something totally different, check all items listItems = list.children(); } else { // Only chars added, not removed, only use visible subset listItems = list.children( ":not(.ui-screen-hidden)" ); } if ( val ) { // This handles hiding regular rows without the text we search for // and any list dividers without regular rows shown under it for ( var i = listItems.length - 1; i >= 0; i-- ) { item = $( listItems[ i ] ); itemtext = item.jqmData( "filtertext" ) || item.text(); if ( item.is( "li:jqmData(role=list-divider)" ) ) { item.toggleClass( "ui-filter-hidequeue" , !childItems ); // New bucket! childItems = false; } else if ( listview.options.filterCallback( itemtext, val ) ) { //mark to be hidden item.toggleClass( "ui-filter-hidequeue" , true ); } else { // There's a shown item in the bucket childItems = true; } } // Show items, not marked to be hidden listItems .filter( ":not(.ui-filter-hidequeue)" ) .toggleClass( "ui-screen-hidden", false ); // Hide items, marked to be hidden listItems .filter( ".ui-filter-hidequeue" ) .toggleClass( "ui-screen-hidden", true ) .toggleClass( "ui-filter-hidequeue", false ); } else { //filtervalue is empty => show all listItems.toggleClass( "ui-screen-hidden", false ); } listview._refreshCorners(); }) .appendTo( wrapper ) .textinput(); if ( $( this ).jqmData( "inset" ) ) { wrapper.addClass( "ui-listview-filter-inset" ); } wrapper.bind( "submit", function() { return false; }) .insertBefore( list ); }); })( jQuery );/* * "nojs" plugin - class to make elements hidden to A grade browsers */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" ); }); })( jQuery );/* * "checkboxradio" plugin */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.mobile.widget, { options: { theme: null, initSelector: "input[type='checkbox'],input[type='radio']" }, _create: function() { var self = this, input = this.element, // NOTE: Windows Phone could not find the label through a selector // filter works though. label = input.closest( "form,fieldset,:jqmData(role='page')" ).find( "label[for='" + input[ 0 ].id + "']"), inputtype = input.attr( "type" ), checkedState = inputtype + "-on", uncheckedState = inputtype + "-off", icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState, activeBtn = icon ? "" : " " + $.mobile.activeBtnClass, checkedClass = "ui-" + checkedState + activeBtn, uncheckedClass = "ui-" + uncheckedState, checkedicon = "ui-icon-" + checkedState, uncheckedicon = "ui-icon-" + uncheckedState; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } // Expose for other methods $.extend( this, { label: label, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass, checkedicon: checkedicon, uncheckedicon: uncheckedicon }); // If there's no selected theme... if( !this.options.theme ) { this.options.theme = this.element.jqmData( "theme" ); } label.buttonMarkup({ theme: this.options.theme, icon: icon, shadow: false }); // Wrap the input + label in a div input.add( label ) .wrapAll( "<div class='ui-" + inputtype + "'></div>" ); label.bind({ vmouseover: function( event ) { if ( $( this ).parent().is( ".ui-disabled" ) ) { event.stopPropagation(); } }, vclick: function( event ) { if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } self._cacheVals(); input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) ); // trigger click handler's bound directly to the input as a substitute for // how label clicks behave normally in the browsers // TODO: it would be nice to let the browser's handle the clicks and pass them // through to the associate input. we can swallow that click at the parent // wrapper element level input.triggerHandler( 'click' ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly self._getInputSet().not( input ).prop( "checked", false ); self._updateAll(); return false; } }); input .bind({ vmousedown: function() { self._cacheVals(); }, vclick: function() { var $this = $(this); // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); self._getInputSet().not($this).prop( "checked", false ); } else { $this.prop( "checked", false ); } self._updateAll(); }, focus: function() { label.addClass( "ui-focus" ); }, blur: function() { label.removeClass( "ui-focus" ); } }); this.refresh(); }, _cacheVals: function() { this._getInputSet().each(function() { var $this = $(this); $this.jqmData( "cacheVal", $this.is( ":checked" ) ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function(){ if(this.inputtype == "checkbox") { return this.element; } return this.element.closest( "form,fieldset,:jqmData(role='page')" ) .find( "input[name='"+ this.element.attr( "name" ) +"'][type='"+ this.inputtype +"']" ); }, _updateAll: function() { var self = this; this._getInputSet().each(function() { var $this = $(this); if ( $this.is( ":checked" ) || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, refresh: function() { var input = this.element, label = this.label, icon = label.find( ".ui-icon" ); // input[0].checked expando doesn't always report the proper value // for checked='checked' if ( $( input[ 0 ] ).prop( "checked" ) ) { label.addClass( this.checkedClass ).removeClass( this.uncheckedClass ); icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon ); } else { label.removeClass( this.checkedClass ).addClass( this.uncheckedClass ); icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon ); } if ( input.is( ":disabled" ) ) { this.disable(); } else { this.enable(); } }, disable: function() { this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" ); }, enable: function() { this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.checkboxradio.prototype.enhanceWithin( e.target ); }); })( jQuery ); /* * "button" plugin - links that proxy to native input/buttons */ (function( $, undefined ) { $.widget( "mobile.button", $.mobile.widget, { options: { theme: null, icon: null, iconpos: null, inline: null, corners: true, shadow: true, iconshadow: true, initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']" }, _create: function() { var $el = this.element, o = this.options, type, name, $buttonPlaceholder; // Add ARIA role this.button = $( "<div></div>" ) .text( $el.text() || $el.val() ) .insertBefore( $el ) .buttonMarkup({ theme: o.theme, icon: o.icon, iconpos: o.iconpos, inline: o.inline, corners: o.corners, shadow: o.shadow, iconshadow: o.iconshadow }) .append( $el.addClass( "ui-btn-hidden" ) ); type = $el.attr( "type" ); name = $el.attr( "name" ); // Add hidden input during submit if input type="submit" has a name. if ( type !== "button" && type !== "reset" && name ) { $el.bind( "vclick", function() { // Add hidden input if it doesn’t already exist. if( $buttonPlaceholder === undefined ) { $buttonPlaceholder = $( "<input>", { type: "hidden", name: $el.attr( "name" ), value: $el.attr( "value" ) }).insertBefore( $el ); // Bind to doc to remove after submit handling $( document ).one("submit", function(){ $buttonPlaceholder.remove(); // reset the local var so that the hidden input // will be re-added on subsequent clicks $buttonPlaceholder = undefined; }); } }); } this.refresh(); }, enable: function() { this.element.attr( "disabled", false ); this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); }, refresh: function() { var $el = this.element; if ( $el.prop("disabled") ) { this.disable(); } else { this.enable(); } // the textWrapper is stored as a data element on the button object // to prevent referencing by it's implementation details (eg 'class') this.button.data( 'textWrapper' ).text( $el.text() || $el.val() ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.button.prototype.enhanceWithin( e.target ); }); })( jQuery );/* * "slider" plugin */ ( function( $, undefined ) { $.widget( "mobile.slider", $.mobile.widget, { options: { theme: null, trackTheme: null, disabled: false, initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')" }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, parentTheme = $.mobile.getInheritedTheme( control, "c" ), theme = this.options.theme || parentTheme, trackTheme = this.options.trackTheme || parentTheme, cType = control[ 0 ].nodeName.toLowerCase(), selectClass = ( cType == "select" ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), labelID = controlID + "-label", label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ), val = function() { return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex; }, min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), slider = $( "<div class='ui-slider " + selectClass + " ui-btn-down-" + trackTheme + " ui-btn-corner-all' role='application'></div>" ), handle = $( "<a href='#' class='ui-slider-handle'></a>" ) .appendTo( slider ) .buttonMarkup({ corners: true, theme: theme, shadow: true }) .attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": val(), "aria-valuetext": val(), "title": val(), "aria-labelledby": labelID }), options; $.extend( this, { slider: slider, handle: handle, dragging: false, beforeStart: null, userModified: false, mouseMoved: false }); if ( cType == "select" ) { slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); options = control.find( "option" ); control.find( "option" ).each(function( i ) { var side = !i ? "b":"a", corners = !i ? "right" :"left", theme = !i ? " ui-btn-down-" + trackTheme :( " " + $.mobile.activeBtnClass ); $( "<div class='ui-slider-labelbg ui-slider-labelbg-" + side + theme + " ui-btn-corner-" + corners + "'></div>" ) .prependTo( slider ); $( "<span class='ui-slider-label ui-slider-label-" + side + theme + " ui-btn-corner-" + corners + "' role='img'>" + $( this ).getEncodedText() + "</span>" ) .prependTo( handle ); }); } label.addClass( "ui-slider" ); // monitor the input for updated values control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" ) .change( function() { // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again if (!self.mouseMoved) { self.refresh( val(), true ); } }) .keyup( function() { // necessary? self.refresh( val(), true, true ); }) .blur( function() { self.refresh( val(), true ); }); // prevent screen drag when slider activated $( document ).bind( "vmousemove", function( event ) { if ( self.dragging ) { // self.mouseMoved must be updated before refresh() because it will be used in the control "change" event self.mouseMoved = true; if ( cType === "select" ) { // make the handle move in sync with the mouse handle.removeClass( "ui-slider-handle-snapping" ); } self.refresh( event ); // only after refresh() you can calculate self.userModified self.userModified = self.beforeStart !== control[0].selectedIndex; return false; } }); slider.bind( "vmousedown", function( event ) { self.dragging = true; self.userModified = false; self.mouseMoved = false; if ( cType === "select" ) { self.beforeStart = control[0].selectedIndex; } self.refresh( event ); return false; }); slider.add( document ) .bind( "vmouseup", function() { if ( self.dragging ) { self.dragging = false; if ( cType === "select") { // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); if ( self.mouseMoved ) { // this is a drag, change the value only if user dragged enough if ( self.userModified ) { self.refresh( self.beforeStart == 0 ? 1 : 0 ); } else { self.refresh( self.beforeStart ); } } else { // this is just a click, change the value self.refresh( self.beforeStart == 0 ? 1 : 0 ); } } self.mouseMoved = false; return false; } }); slider.insertAfter( control ); // NOTE force focus on handle this.handle .bind( "vmousedown", function() { $( this ).focus(); }) .bind( "vclick", false ); this.handle .bind( "keydown", function( event ) { var index = val(); if ( self.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !self._keySliding ) { self._keySliding = true; $( this ).addClass( "ui-state-active" ); } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: self.refresh( min ); break; case $.mobile.keyCode.END: self.refresh( max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: self.refresh( index + step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: self.refresh( index - step ); break; } }) // remove active mark .keyup( function( event ) { if ( self._keySliding ) { self._keySliding = false; $( this ).removeClass( "ui-state-active" ); } }); this.refresh(undefined, undefined, true); }, refresh: function( val, isfromControl, preventInputUpdate ) { if ( this.options.disabled || this.element.attr('disabled')) { this.disable(); } var control = this.element, percent, cType = control[0].nodeName.toLowerCase(), min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0, max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1; if ( typeof val === "object" ) { var data = val, // a slight tolerance helped get to the ends of the slider tol = 8; if ( !this.dragging || data.pageX < this.slider.offset().left - tol || data.pageX > this.slider.offset().left + this.slider.width() + tol ) { return; } percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 ); } else { if ( val == null ) { val = cType === "input" ? parseFloat( control.val() ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } var newval = Math.round( ( percent / 100 ) * ( max - min ) ) + min; if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } // Flip the stack of the bg colors if ( percent > 60 && cType === "select" ) { // TODO: Dead path? } this.handle.css( "left", percent + "%" ); this.handle.attr( { "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ), "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText(), title: newval }); // add/remove classes for flip toggle switch if ( cType === "select" ) { if ( newval === 0 ) { this.slider.addClass( "ui-slider-switch-a" ) .removeClass( "ui-slider-switch-b" ); } else { this.slider.addClass( "ui-slider-switch-b" ) .removeClass( "ui-slider-switch-a" ); } } if ( !preventInputUpdate ) { var valueChanged = false; // update control"s value if ( cType === "input" ) { valueChanged = control.val() !== newval; control.val( newval ); } else { valueChanged = control[ 0 ].selectedIndex !== newval; control[ 0 ].selectedIndex = newval; } if ( !isfromControl && valueChanged ) { control.trigger( "change" ); } } }, enable: function() { this.element.attr( "disabled", false ); this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false ); return this._setOption( "disabled", false ); }, disable: function() { this.element.attr( "disabled", true ); this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true ); return this._setOption( "disabled", true ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.slider.prototype.enhanceWithin( e.target ); }); })( jQuery ); /* * "textinput" plugin for text inputs, textareas */ (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type])" }, _create: function() { var input = this.element, o = this.options, theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ), themeclass = " ui-body-" + theme, focusedEl, clearbtn; $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); focusedEl = input.addClass("ui-input-text ui-body-"+ theme ); // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" input widget if ( input.is( "[type='search'],:jqmData(type='search')" ) ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent(); clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" ) .tap(function( event ) { input.val( "" ).focus(); input.trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true }); function toggleClear() { setTimeout(function() { clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() ); }, 0); } toggleClear(); input.bind('paste cut keyup focus change blur', toggleClear); } else { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass ); } input.focus(function() { focusedEl.addClass( "ui-focus" ); }) .blur(function(){ focusedEl.removeClass( "ui-focus" ); }); // Autogrow if ( input.is( "textarea" ) ) { var extraLineHeight = 15, keyupTimeoutBuffer = 100, keyup = function() { var scrollHeight = input[ 0 ].scrollHeight, clientHeight = input[ 0 ].clientHeight; if ( clientHeight < scrollHeight ) { input.height(scrollHeight + extraLineHeight); } }, keyupTimeout; input.keyup(function() { clearTimeout( keyupTimeout ); keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer ); }); // Issue 509: the browser is not providing scrollHeight properly until the styles load if ( $.trim( input.val() ) ) { // bind to the window load to make sure the height is calculated based on BOTH // the DOM and CSS $( window ).load( keyup ); // binding to pagechange here ensures that for pages loaded via // ajax the height is recalculated without user input $( document ).one( "pagechange", keyup ); } } }, disable: function(){ ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).addClass( "ui-disabled" ); }, enable: function(){ ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.textinput.prototype.enhanceWithin( e.target ); }); })( jQuery ); /* * custom "selectmenu" plugin */ (function( $, undefined ) { var extendSelect = function( widget ){ var select = widget.select, selectID = widget.selectID, label = widget.label, thisPage = widget.select.closest( ".ui-page" ), screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"} ).appendTo( thisPage ), selectOptions = widget._selectOptions(), isMultiple = widget.isMultiple = widget.select[ 0 ].multiple, buttonId = selectID + "-button", menuId = selectID + "-menu", menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.getEncodedText() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ).appendTo( $.mobile.pageContainer ).page(), listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + widget.options.overlayTheme + " " + $.mobile.defaultDialogTransition } ).insertAfter(screen), list = $( "<ul>", { "class": "ui-selectmenu-list", "id": menuId, "role": "listbox", "aria-labelledby": buttonId }).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ).appendTo( listbox ), header = $( "<div>", { "class": "ui-header ui-bar-" + widget.options.theme }).prependTo( listbox ), headerTitle = $( "<h1>", { "class": "ui-title" }).appendTo( header ), headerClose = $( "<a>", { "text": widget.options.closeText, "href": "#", "class": "ui-btn-left" }).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup(), menuPageContent = menuPage.find( ".ui-content" ), menuPageClose = menuPage.find( ".ui-header a" ); $.extend( widget, { select: widget.select, selectID: selectID, buttonId: buttonId, menuId: menuId, thisPage: thisPage, menuPage: menuPage, label: label, screen: screen, selectOptions: selectOptions, isMultiple: isMultiple, theme: widget.options.theme, listbox: listbox, list: list, header: header, headerTitle: headerTitle, headerClose: headerClose, menuPageContent: menuPageContent, menuPageClose: menuPageClose, placeholder: "", build: function() { var self = this; // Create list from select, update state self.refresh(); self.select.attr( "tabindex", "-1" ).focus(function() { $( this ).blur(); self.button.focus(); }); // Button events self.button.bind( "vclick keydown" , function( event ) { if ( event.type == "vclick" || event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE ) ) { self.open(); event.preventDefault(); } }); // Events for list items self.list.attr( "role", "listbox" ) .delegate( ".ui-li>a", "focusin", function() { $( this ).attr( "tabindex", "0" ); }) .delegate( ".ui-li>a", "focusout", function() { $( this ).attr( "tabindex", "-1" ); }) .delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) { // index of option tag to be selected var oldIndex = self.select[ 0 ].selectedIndex, newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ), option = self._selectOptions().eq( newIndex )[ 0 ]; // toggle selected status on the tag for multi selects option.selected = self.isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( self.isMultiple ) { $( this ).find( ".ui-icon" ) .toggleClass( "ui-icon-checkbox-on", option.selected ) .toggleClass( "ui-icon-checkbox-off", !option.selected ); } // trigger change if value changed if ( self.isMultiple || oldIndex !== newIndex ) { self.select.trigger( "change" ); } //hide custom select for single selects only if ( !self.isMultiple ) { self.close(); } event.preventDefault(); }) .keydown(function( event ) { //keyboard events for menu items var target = $( event.target ), li = target.closest( "li" ), prev, next; // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: prev = li.prev(); // if there's a previous option, focus it if ( prev.length ) { target .blur() .attr( "tabindex", "-1" ); prev.find( "a" ).first().focus(); } return false; break; // down or right arrow keys case 40: next = li.next(); // if there's a next option, focus it if ( next.length ) { target .blur() .attr( "tabindex", "-1" ); next.find( "a" ).first().focus(); } return false; break; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "click" ); return false; break; } }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion self.menuPage.bind( "pagehide", function() { self.list.appendTo( self.listbox ); self._focusButton(); // TODO centralize page removal binding / handling in the page plugin. // Suggestion from @jblas to do refcounting // // TODO extremely confusing dependency on the open method where the pagehide.remove // bindings are stripped to prevent the parent page from disappearing. The way // we're keeping pages in the DOM right now sucks // // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select // // doing this here provides for the back button on the custom select dialog $.mobile._bindPageRemove.call( self.thisPage ); }); // Events on "screen" overlay self.screen.bind( "vclick", function( event ) { self.close(); }); // Close button on small overlays self.headerClose.click( function() { if ( self.menuType == "overlay" ) { self.close(); return false; } }); // track this dependency so that when the parent page // is removed on pagehide it will also remove the menupage self.thisPage.addDependents( this.menuPage ); }, _isRebuildRequired: function() { var list = this.list.find( "li" ), options = this._selectOptions(); // TODO exceedingly naive method to determine difference // ignores value changes etc in favor of a forcedRebuild // from the user in the refresh method return options.text() !== list.text(); }, refresh: function( forceRebuild , foo ){ var self = this, select = this.element, isMultiple = this.isMultiple, options = this._selectOptions(), selected = this.selected(), // return an array of all selected index's indicies = this.selectedIndices(); if ( forceRebuild || this._isRebuildRequired() ) { self._buildList(); } self.setButtonText(); self.setButtonCount(); self.list.find( "li:not(.ui-li-divider)" ) .removeClass( $.mobile.activeBtnClass ) .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indicies ) > -1 ) { var item = $( this ); // Aria selected attr item.attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( self.isMultiple ) { item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" ); } else { item.addClass( $.mobile.activeBtnClass ); } } }); }, close: function() { if ( this.options.disabled || !this.isOpen ) { return; } var self = this; if ( self.menuType == "page" ) { // doesn't solve the possible issue with calling change page // where the objects don't define data urls which prevents dialog key // stripping - changePage has incoming refactor window.history.back(); } else { self.screen.addClass( "ui-screen-hidden" ); self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" ); self.list.appendTo( self.listbox ); self._focusButton(); } // allow the dialog to be closed again self.isOpen = false; }, open: function() { if ( this.options.disabled ) { return; } var self = this, menuHeight = self.list.parent().outerHeight(), menuWidth = self.list.parent().outerWidth(), activePage = $( ".ui-page-active" ), tOverflow = $.support.touchOverflow && $.mobile.touchOverflowEnabled, tScrollElem = activePage.is( ".ui-native-fixed" ) ? activePage.find( ".ui-content" ) : activePage; scrollTop = tOverflow ? tScrollElem.scrollTop() : $( window ).scrollTop(), btnOffset = self.button.offset().top, screenHeight = window.innerHeight, screenWidth = window.innerWidth; //add active class to button self.button.addClass( $.mobile.activeBtnClass ); //remove after delay setTimeout( function() { self.button.removeClass( $.mobile.activeBtnClass ); }, 300); function focusMenuItem() { self.list.find( $.mobile.activeBtnClass ).focus(); } if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for WebOS/Opera Mini (set lastscroll using button offset) if ( scrollTop == 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( "pageshow", function() { // silentScroll() is called whenever a page is shown to restore // any previous scroll position the page may have had. We need to // wait for the "silentscroll" event before setting focus to avoid // the browser"s "feature" which offsets rendering to make sure // whatever has focus is in view. $( window ).one( "silentscroll", function() { focusMenuItem(); }); self.isOpen = true; }); self.menuType = "page"; self.menuPageContent.append( self.list ); self.menuPage.find("div .ui-title").text(self.label.text()); $.mobile.changePage( self.menuPage, { transition: $.mobile.defaultDialogTransition }); } else { self.menuType = "overlay"; self.screen.height( $(document).height() ) .removeClass( "ui-screen-hidden" ); // Try and center the overlay over the button var roomtop = btnOffset - scrollTop, roombot = scrollTop + screenHeight - btnOffset, halfheight = menuHeight / 2, maxwidth = parseFloat( self.list.parent().css( "max-width" ) ), newtop, newleft; if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) { newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight; } else { // 30px tolerance off the edges newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30; } // If the menuwidth is smaller than the screen center is if ( menuWidth < maxwidth ) { newleft = ( screenWidth - menuWidth ) / 2; } else { //otherwise insure a >= 30px offset from the left newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2; // 30px tolerance off the edges if ( newleft < 30 ) { newleft = 30; } else if ( (newleft + menuWidth) > screenWidth ) { newleft = screenWidth - menuWidth - 30; } } self.listbox.append( self.list ) .removeClass( "ui-selectmenu-hidden" ) .css({ top: newtop, left: newleft }) .addClass( "in" ); focusMenuItem(); // duplicate with value set in page show for dialog sized selects self.isOpen = true; } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, optgroups = [], lis = [], dataIcon = self.isMultiple ? "checkbox-off" : "false"; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); // Populate menu with options from select element self.select.find( "option" ).each( function( i ) { var $this = $( this ), $parent = $this.parent(), text = $this.getEncodedText(), anchor = "<a href='#'>"+ text +"</a>", classes = [], extraAttrs = []; // Are we inside an optgroup? if ( $parent.is( "optgroup" ) ) { var optLabel = $parent.attr( "label" ); // has this optgroup already been built yet? if ( $.inArray( optLabel, optgroups ) === -1 ) { lis.push( "<li data-" + $.mobile.ns + "role='list-divider'>"+ optLabel +"</li>" ); optgroups.push( optLabel ); } } // Find placeholder text // TODO: Are you sure you want to use getAttribute? ^RW if ( !this.getAttribute( "value" ) || text.length == 0 || $this.jqmData( "placeholder" ) ) { if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-selectmenu-placeholder" ); } placeholder = self.placeholder = text; } // support disabled option tags if ( this.disabled ) { classes.push( "ui-disabled" ); extraAttrs.push( "aria-disabled='true'" ); } lis.push( "<li data-" + $.mobile.ns + "option-index='" + i + "' data-" + $.mobile.ns + "icon='"+ dataIcon +"' class='"+ classes.join(" ") + "' " + extraAttrs.join(" ") +">"+ anchor +"</li>" ); }); self.list.html( lis.join(" ") ); self.list.find( "li" ) .attr({ "role": "option", "tabindex": "-1" }) .first().attr( "tabindex", "0" ); // Hide header close link for single selects if ( !this.isMultiple ) { this.headerClose.hide(); } // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.hide(); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, _button: function(){ return $( "<a>", { "href": "#", "role": "button", // TODO value is undefined at creation "id": this.buttonId, "aria-haspopup": "true", // TODO value is undefined at creation "aria-owns": this.menuId }); } }); }; $( "select" ).live( "selectmenubeforecreate", function(){ var selectmenuWidget = $( this ).data( "selectmenu" ); if( !selectmenuWidget.options.nativeMenu ){ extendSelect( selectmenuWidget ); } }); })( jQuery ); /* * "selectmenu" plugin */ (function( $, undefined ) { $.widget( "mobile.selectmenu", $.mobile.widget, { options: { theme: null, disabled: false, icon: "arrow-d", iconpos: "right", inline: null, corners: true, shadow: true, iconshadow: true, menuPageTheme: "b", overlayTheme: "a", hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, initSelector: "select:not(:jqmData(role='slider'))" }, _button: function(){ return $( "<div/>" ); }, _setDisabled: function( value ) { this.element.attr( "disabled", value ); this.button.attr( "aria-disabled", value ); return this._setOption( "disabled", value ); }, _focusButton : function() { var self = this; setTimeout( function() { self.button.focus(); }, 40); }, _selectOptions: function() { return this.select.find( "option" ); }, // setup items that are generally necessary for select menu extension _preExtension: function(){ this.select = this.element.wrap( "<div class='ui-select'>" ); this.selectID = this.select.attr( "id" ); this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" ); this.isMultiple = this.select[ 0 ].multiple; if ( !this.options.theme ) { this.options.theme = $.mobile.getInheritedTheme( this.select, "c" ); } }, _create: function() { this._preExtension(); // Allows for extension of the native select for custom selects and other plugins // see select.custom for example extension // TODO explore plugin registration this._trigger( "beforeCreate" ); this.button = this._button(); var self = this, options = this.options, // IE throws an exception at options.item() function when // there is no selected item // select first in this case selectedIndex = this.select[ 0 ].selectedIndex == -1 ? 0 : this.select[ 0 ].selectedIndex, // TODO values buttonId and menuId are undefined here button = this.button .text( $( this.select[ 0 ].options.item( selectedIndex ) ).text() ) .insertBefore( this.select ) .buttonMarkup( { theme: options.theme, icon: options.icon, iconpos: options.iconpos, inline: options.inline, corners: options.corners, shadow: options.shadow, iconshadow: options.iconshadow }); // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( options.nativeMenu && window.opera && window.opera.version ) { this.select.addClass( "ui-select-nativeonly" ); } // Add counter for multi selects if ( this.isMultiple ) { this.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" ) .hide() .appendTo( button.addClass('ui-li-has-count') ); } // Disable if specified if ( options.disabled || this.element.attr('disabled')) { this.disable(); } // Events on native select this.select.change( function() { self.refresh(); }); this.build(); }, build: function() { var self = this; this.select .appendTo( self.button ) .bind( "vmousedown", function() { // Add active class to button self.button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus vmouseover", function() { self.button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove self.button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { self.button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur", function() { self.button.removeClass( "ui-btn-down-" + self.options.theme ); }); }, selected: function() { return this._selectOptions().filter( ":selected" ); }, selectedIndices: function() { var self = this; return this.selected().map( function() { return self._selectOptions().index( this ); }).get(); }, setButtonText: function() { var self = this, selected = this.selected(); this.button.find( ".ui-btn-text" ).text( function() { if ( !self.isMultiple ) { return selected.text(); } return selected.length ? selected.map( function() { return $( this ).text(); }).get().join( ", " ) : self.placeholder; }); }, setButtonCount: function() { var selected = this.selected(); // multiple count inside button if ( this.isMultiple ) { this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } }, refresh: function() { this.setButtonText(); this.setButtonCount(); }, // open and close preserved in native selects // to simplify users code when looping over selects open: $.noop, close: $.noop, disable: function() { this._setDisabled( true ); this.button.addClass( "ui-disabled" ); }, enable: function() { this._setDisabled( false ); this.button.removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.selectmenu.prototype.enhanceWithin( e.target ); }); })( jQuery ); /* * "buttons" plugin - for making button-like links */ ( function( $, undefined ) { $.fn.buttonMarkup = function( options ) { options = options || {}; for ( var i = 0; i < this.length; i++ ) { var el = this.eq( i ), e = el[ 0 ], o = $.extend( {}, $.fn.buttonMarkup.defaults, { icon: options.icon !== undefined ? options.icon : el.jqmData( "icon" ), iconpos: options.iconpos !== undefined ? options.iconpos : el.jqmData( "iconpos" ), theme: options.theme !== undefined ? options.theme : el.jqmData( "theme" ), inline: options.inline !== undefined ? options.inline : el.jqmData( "inline" ), shadow: options.shadow !== undefined ? options.shadow : el.jqmData( "shadow" ), corners: options.corners !== undefined ? options.corners : el.jqmData( "corners" ), iconshadow: options.iconshadow !== undefined ? options.iconshadow : el.jqmData( "iconshadow" ) }, options ), // Classes Defined innerClass = "ui-btn-inner", textClass = "ui-btn-text", buttonClass, iconClass, // Button inner markup buttonInner = document.createElement( o.wrapperEls ), buttonText = document.createElement( o.wrapperEls ), buttonIcon = o.icon ? document.createElement( "span" ) : null; if ( attachEvents ) { attachEvents(); } // if not, try to find closest theme container if ( !o.theme ) { o.theme = $.mobile.getInheritedTheme( el, "c" ); } buttonClass = "ui-btn ui-btn-up-" + o.theme; if ( o.inline ) { buttonClass += " ui-btn-inline"; } if ( o.icon ) { o.icon = "ui-icon-" + o.icon; o.iconpos = o.iconpos || "left"; iconClass = "ui-icon " + o.icon; if ( o.iconshadow ) { iconClass += " ui-icon-shadow"; } } if ( o.iconpos ) { buttonClass += " ui-btn-icon-" + o.iconpos; if ( o.iconpos == "notext" && !el.attr( "title" ) ) { el.attr( "title", el.getEncodedText() ); } } if ( o.corners ) { buttonClass += " ui-btn-corner-all"; innerClass += " ui-btn-corner-all"; } if ( o.shadow ) { buttonClass += " ui-shadow"; } e.setAttribute( "data-" + $.mobile.ns + "theme", o.theme ); el.addClass( buttonClass ); buttonInner.className = innerClass; buttonInner.setAttribute("aria-hidden", "true"); buttonText.className = textClass; buttonInner.appendChild( buttonText ); if ( buttonIcon ) { buttonIcon.className = iconClass; buttonInner.appendChild( buttonIcon ); } while ( e.firstChild ) { buttonText.appendChild( e.firstChild ); } e.appendChild( buttonInner ); // TODO obviously it would be nice to pull this element out instead of // retrieving it from the DOM again, but this change is much less obtrusive // and 1.0 draws nigh $.data( e, 'textWrapper', $( buttonText ) ); } return this; }; $.fn.buttonMarkup.defaults = { corners: true, shadow: true, iconshadow: true, inline: false, wrapperEls: "span" }; function closestEnabledButton( element ) { var cname; while ( element ) { // Note that we check for typeof className below because the element we // handed could be in an SVG DOM where className on SVG elements is defined to // be of a different type (SVGAnimatedString). We only operate on HTML DOM // elements, so we look for plain "string". cname = ( typeof element.className === 'string' ) && element.className.split(' '); if ( cname && $.inArray( "ui-btn", cname ) > -1 && $.inArray( "ui-disabled", cname ) < 0 ) { break; } element = element.parentNode; } return element; } var attachEvents = function() { $( document ).bind( { "vmousedown": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme ); } }, "vmousecancel vmouseup": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme ); } }, "vmouseover focus": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme ); } }, "vmouseout blur": function( event ) { var btn = closestEnabledButton( event.target ), $btn, theme; if ( btn ) { $btn = $( btn ); theme = $btn.attr( "data-" + $.mobile.ns + "theme" ); $btn.removeClass( "ui-btn-hover-" + theme + " ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme ); } } }); attachEvents = null; }; //links in bars, or those with data-role become buttons //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target ) .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .buttonMarkup(); }); })( jQuery ); /* * "controlgroup" plugin - corner-rounding for groups of buttons, checks, radios, etc */ (function( $, undefined ) { $.fn.controlgroup = function( options ) { return this.each(function() { var $el = $( this ), o = $.extend({ direction: $el.jqmData( "type" ) || "vertical", shadow: false, excludeInvisible: true }, options ), groupheading = $el.children( "legend" ), flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ], type = $el.find( "input" ).first().attr( "type" ); // Replace legend with more stylable replacement div if ( groupheading.length ) { $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" ); $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) ); groupheading.remove(); } $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction ); // TODO: This should be moved out to the closure // otherwise it is redefined each time controlgroup() is called function flipClasses( els ) { els.removeClass( "ui-btn-corner-all ui-shadow" ) .eq( 0 ).addClass( flCorners[ 0 ] ) .end() .last().addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" ); } flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ) ); flipClasses( $el.find( ".ui-btn-inner" ) ); if ( o.shadow ) { $el.addClass( "ui-shadow" ); } }); }; //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $( ":jqmData(role='controlgroup')", e.target ).controlgroup({ excludeInvisible: false }); }); })(jQuery);/* * "links" plugin - simple class additions for links */ (function( $, undefined ) { $( document ).bind( "pagecreate create", function( e ){ //links within content areas $( e.target ) .find( "a" ) .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }); })( jQuery );/* * "fixHeaderFooter" plugin - on-demand positioning for headers,footers */ (function( $, undefined ) { var slideDownClass = "ui-header-fixed ui-fixed-inline fade", slideUpClass = "ui-footer-fixed ui-fixed-inline fade", slideDownSelector = ".ui-header:jqmData(position='fixed')", slideUpSelector = ".ui-footer:jqmData(position='fixed')"; $.fn.fixHeaderFooter = function( options ) { if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) { return this; } return this.each(function() { var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }); }; // single controller for all showing,hiding,toggling $.mobile.fixedToolbars = (function() { if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) { return; } var stickyFooter, delayTimer, currentstate = "inline", autoHideMode = false, showDelay = 100, ignoreTargets = "a,input,textarea,select,button,label,.ui-header-fixed,.ui-footer-fixed", toolbarSelector = ".ui-header-fixed:first, .ui-footer-fixed:not(.ui-footer-duplicate):last", // for storing quick references to duplicate footers supportTouch = $.support.touch, touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", stateBefore = null, scrollTriggered = false, touchToggleEnabled = true; function showEventCallback( event ) { // An event that affects the dimensions of the visual viewport has // been triggered. If the header and/or footer for the current page are in overlay // mode, we want to hide them, and then fire off a timer to show them at a later // point. Events like a resize can be triggered continuously during a scroll, on // some platforms, so the timer is used to delay the actual positioning until the // flood of events have subsided. // // If we are in autoHideMode, we don't do anything because we know the scroll // callbacks for the plugin will fire off a show when the scrolling has stopped. if ( !autoHideMode && currentstate === "overlay" ) { if ( !delayTimer ) { $.mobile.fixedToolbars.hide( true ); } $.mobile.fixedToolbars.startShowTimer(); } } $(function() { var $document = $( document ), $window = $( window ); $document .bind( "vmousedown", function( event ) { if ( touchToggleEnabled ) { stateBefore = currentstate; } }) .bind( "vclick", function( event ) { if ( touchToggleEnabled ) { if ( $(event.target).closest( ignoreTargets ).length ) { return; } if ( !scrollTriggered ) { $.mobile.fixedToolbars.toggle( stateBefore ); stateBefore = null; } } }) .bind( "silentscroll", showEventCallback ); // The below checks first for a $(document).scrollTop() value, and if zero, binds scroll events to $(window) instead. // If the scrollTop value is actually zero, both will return zero anyway. // // Works with $(document), not $(window) : Opera Mobile (WinMO phone; kinda broken anyway) // Works with $(window), not $(document) : IE 7/8 // Works with either $(window) or $(document) : Chrome, FF 3.6/4, Android 1.6/2.1, iOS // Needs work either way : BB5, Opera Mobile (iOS) ( ( $document.scrollTop() === 0 ) ? $window : $document ) .bind( "scrollstart", function( event ) { scrollTriggered = true; if ( stateBefore === null ) { stateBefore = currentstate; } // We only enter autoHideMode if the headers/footers are in // an overlay state or the show timer was started. If the // show timer is set, clear it so the headers/footers don't // show up until after we're done scrolling. var isOverlayState = stateBefore == "overlay"; autoHideMode = isOverlayState || !!delayTimer; if ( autoHideMode ) { $.mobile.fixedToolbars.clearShowTimer(); if ( isOverlayState ) { $.mobile.fixedToolbars.hide( true ); } } }) .bind( "scrollstop", function( event ) { if ( $( event.target ).closest( ignoreTargets ).length ) { return; } scrollTriggered = false; if ( autoHideMode ) { $.mobile.fixedToolbars.startShowTimer(); autoHideMode = false; } stateBefore = null; }); $window.bind( "resize updatelayout", showEventCallback ); }); // 1. Before page is shown, check for duplicate footer // 2. After page is shown, append footer to new page $( ".ui-page" ) .live( "pagebeforeshow", function( event, ui ) { var page = $( event.target ), footer = page.find( ":jqmData(role='footer')" ), id = footer.data( "id" ), prevPage = ui.prevPage, prevFooter = prevPage && prevPage.find( ":jqmData(role='footer')" ), prevFooterMatches = prevFooter.length && prevFooter.jqmData( "id" ) === id; if ( id && prevFooterMatches ) { stickyFooter = footer; setTop( stickyFooter.removeClass( "fade in out" ).appendTo( $.mobile.pageContainer ) ); } }) .live( "pageshow", function( event, ui ) { var $this = $( this ); if ( stickyFooter && stickyFooter.length ) { setTimeout(function() { setTop( stickyFooter.appendTo( $this ).addClass( "fade" ) ); stickyFooter = null; }, 500); } $.mobile.fixedToolbars.show( true, this ); }); // When a collapsiable is hidden or shown we need to trigger the fixed toolbar to reposition itself (#1635) $( ".ui-collapsible-contain" ).live( "collapse expand", showEventCallback ); // element.getBoundingClientRect() is broken in iOS 3.2.1 on the iPad. The // coordinates inside of the rect it returns don't have the page scroll position // factored out of it like the other platforms do. To get around this, // we'll just calculate the top offset the old fashioned way until core has // a chance to figure out how to handle this situation. // // TODO: We'll need to get rid of getOffsetTop() once a fix gets folded into core. function getOffsetTop( ele ) { var top = 0, op, body; if ( ele ) { body = document.body; op = ele.offsetParent; top = ele.offsetTop; while ( ele && ele != body ) { top += ele.scrollTop || 0; if ( ele == op ) { top += op.offsetTop; op = ele.offsetParent; } ele = ele.parentNode; } } return top; } function setTop( el ) { var fromTop = $(window).scrollTop(), thisTop = getOffsetTop( el[ 0 ] ), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisCSStop = el.css( "top" ) == "auto" ? 0 : parseFloat(el.css( "top" )), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), useRelative = el.parents( ".ui-page:not(.ui-page-fullscreen)" ).length, relval; if ( el.is( ".ui-header-fixed" ) ) { relval = fromTop - thisTop + thisCSStop; if ( relval < thisTop ) { relval = 0; } return el.css( "top", useRelative ? relval : fromTop ); } else { // relval = -1 * (thisTop - (fromTop + screenHeight) + thisCSStop + thisHeight); // if ( relval > thisTop ) { relval = 0; } relval = fromTop + screenHeight - thisHeight - (thisTop - thisCSStop ); return el.css( "top", useRelative ? relval : fromTop + screenHeight - thisHeight ); } } // Exposed methods return { show: function( immediately, page ) { $.mobile.fixedToolbars.clearShowTimer(); currentstate = "overlay"; var $ap = page ? $( page ) : ( $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ) ); return $ap.children( toolbarSelector ).each(function() { var el = $( this ), fromTop = $( window ).scrollTop(), // el.offset().top returns the wrong value on iPad iOS 3.2.1, call our workaround instead. thisTop = getOffsetTop( el[ 0 ] ), screenHeight = window.innerHeight, thisHeight = el.outerHeight(), alreadyVisible = ( el.is( ".ui-header-fixed" ) && fromTop <= thisTop + thisHeight ) || ( el.is( ".ui-footer-fixed" ) && thisTop <= fromTop + screenHeight ); // Add state class el.addClass( "ui-fixed-overlay" ).removeClass( "ui-fixed-inline" ); if ( !alreadyVisible && !immediately ) { el.animationComplete(function() { el.removeClass( "in" ); }).addClass( "in" ); } setTop(el); }); }, hide: function( immediately ) { currentstate = "inline"; var $ap = $.mobile.activePage ? $.mobile.activePage : $( ".ui-page-active" ); return $ap.children( toolbarSelector ).each(function() { var el = $(this), thisCSStop = el.css( "top" ), classes; thisCSStop = thisCSStop == "auto" ? 0 : parseFloat(thisCSStop); // Add state class el.addClass( "ui-fixed-inline" ).removeClass( "ui-fixed-overlay" ); if ( thisCSStop < 0 || ( el.is( ".ui-header-fixed" ) && thisCSStop !== 0 ) ) { if ( immediately ) { el.css( "top", 0); } else { if ( el.css( "top" ) !== "auto" && parseFloat( el.css( "top" ) ) !== 0 ) { classes = "out reverse"; el.animationComplete(function() { el.removeClass( classes ).css( "top", 0 ); }).addClass( classes ); } } } }); }, startShowTimer: function() { $.mobile.fixedToolbars.clearShowTimer(); var args = [].slice.call( arguments ); delayTimer = setTimeout(function() { delayTimer = undefined; $.mobile.fixedToolbars.show.apply( null, args ); }, showDelay); }, clearShowTimer: function() { if ( delayTimer ) { clearTimeout( delayTimer ); } delayTimer = undefined; }, toggle: function( from ) { if ( from ) { currentstate = from; } return ( currentstate === "overlay" ) ? $.mobile.fixedToolbars.hide() : $.mobile.fixedToolbars.show(); }, setTouchToggleEnabled: function( enabled ) { touchToggleEnabled = enabled; } }; })(); //auto self-init widgets $( document ).bind( "pagecreate create", function( event ) { if ( $( ":jqmData(position='fixed')", event.target ).length ) { $( event.target ).each(function() { if ( !$.support.scrollTop || ( $.support.touchOverflow && $.mobile.touchOverflowEnabled ) ) { return this; } var $this = $( this ); if ( $this.jqmData( "fullscreen" ) ) { $this.addClass( "ui-page-fullscreen" ); } // Should be slidedown $this.find( slideDownSelector ).addClass( slideDownClass ); // Should be slideup $this.find( slideUpSelector ).addClass( slideUpClass ); }) } }); })( jQuery ); /* * "fixHeaderFooter" native plugin - Behavior for "fixed" headers,footers, and scrolling inner content */ (function( $, undefined ) { // Enable touch overflow scrolling when it's natively supported $.mobile.touchOverflowEnabled = false; // Enabled zoom when touch overflow is enabled. Can cause usability issues, unfortunately $.mobile.touchOverflowZoomEnabled = false; $( document ).bind( "pagecreate", function( event ) { if( $.support.touchOverflow && $.mobile.touchOverflowEnabled ){ var $target = $( event.target ), scrollStartY = 0; if( $target.is( ":jqmData(role='page')" ) ){ $target.each(function() { var $page = $( this ), $fixies = $page.find( ":jqmData(role='header'), :jqmData(role='footer')" ).filter( ":jqmData(position='fixed')" ), fullScreen = $page.jqmData( "fullscreen" ), $scrollElem = $fixies.length ? $page.find( ".ui-content" ) : $page; $page.addClass( "ui-mobile-touch-overflow" ); $scrollElem.bind( "scrollstop", function(){ if( $scrollElem.scrollTop() > 0 ){ window.scrollTo( 0, $.mobile.defaultHomeScroll ); } }); if( $fixies.length ){ $page.addClass( "ui-native-fixed" ); if( fullScreen ){ $page.addClass( "ui-native-fullscreen" ); $fixies.addClass( "fade in" ); $( document ).bind( "vclick", function(){ $fixies .removeClass( "ui-native-bars-hidden" ) .toggleClass( "in out" ) .animationComplete(function(){ $(this).not( ".in" ).addClass( "ui-native-bars-hidden" ); }); }); } } }); } } }); })( jQuery ); /* * "init" - Initialize the framework */ (function( $, window, undefined ) { var $html = $( "html" ), $head = $( "head" ), $window = $( window ); // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); // support conditions // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, // otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if ( $.mobile.ajaxBlacklist ) { $.mobile.ajaxEnabled = false; } // add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); // loading div which appears during Ajax requests // will not appear if $.mobile.loadingMessage is false var $loader = $( "<div class='ui-loader ui-body-a ui-corner-all'><span class='ui-icon ui-icon-loading spin'></span><h1></h1></div>" ); $.extend($.mobile, { // turn on/off page loading message. showPageLoadingMsg: function() { if ( $.mobile.loadingMessage ) { var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); $loader .find( "h1" ) .text( $.mobile.loadingMessage ) .end() .appendTo( $.mobile.pageContainer ) // position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top .css({ top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 || activeBtn.length && activeBtn.offset().top || 100 }); } $html.addClass( "ui-loading" ); }, hidePageLoadingMsg: function() { $html.removeClass( "ui-loading" ); }, // find and enhance the pages in the dom and transition to the first page. initializePage: function() { // find present pages var $pages = $( ":jqmData(role='page')" ); // if no pages are found, create one with body's inner html if ( !$pages.length ) { $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } // add dialogs, set data-url attrs $pages.add( ":jqmData(role='dialog')" ).each(function() { var $this = $(this); // unless the data url is already set set it to the pathname if ( !$this.jqmData("url") ) { $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search ); } }); // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); // define page container $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" ); // alert listeners that the pagecontainer has been determined for binding // to events triggered on it $window.trigger( "pagecontainercreate" ); // cue page loading message $.mobile.showPageLoadingMsg(); // if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM if ( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ) { $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } ); } // otherwise, trigger a hashchange to load a deeplink else { $window.trigger( "hashchange", [ true ] ); } } }); // This function injects a meta viewport tag to prevent scaling. Off by default, on by default when touchOverflow scrolling is enabled function disableZoom() { var cont = "user-scalable=no", meta = $( "meta[name='viewport']" ); if( meta.length ){ meta.attr( "content", meta.attr( "content" ) + ", " + cont ); } else{ $( "head" ).prepend( "<meta>", { "name": "viewport", "content": cont } ); } } // if touch-overflow is enabled, disable user scaling, as it creates usability issues if( $.support.touchOverflow && $.mobile.touchOverflowEnabled && !$.mobile.touchOverflowZoomEnabled ){ //disableZoom(); } // initialize events now, after mobileinit has occurred $.mobile._registerInternalEvents(); // check which scrollTop value should be used by scrolling to 1 immediately at domready // then check what the scroll top is. Android will report 0... others 1 // note that this initial scroll won't hide the address bar. It's just for the check. $(function() { window.scrollTo( 0, 1 ); // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) // so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if( $.mobile.autoInitializePage ){ $.mobile.initializePage(); } // window load event // hide iOS browser chrome on load $window.load( $.mobile.silentScroll ); }); })( jQuery, this );
JavaScript