code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * jQuery validation plug-in 1.6 * * http://bassistance.de/jquery-plugins/jquery-plugin-validation/ * http://docs.jquery.com/Plugins/Validation * * Copyright (c) 2006 - 2008 Jörn Zaefferer * * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.zaefferer $ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { $.extend($.fn, { // http://docs.jquery.com/Plugins/Validation/validate validate: function( options ) { // if nothing is selected, return nothing; can't chain anyway if (!this.length) { options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" ); return; } // check if a validator for this form was already created var validator = $.data(this[0], 'validator'); if ( validator ) { return validator; } validator = new $.validator( options, this[0] ); $.data(this[0], 'validator', validator); if ( validator.settings.onsubmit ) { // allow suppresing validation by adding a cancel class to the submit button this.find("input, button").filter(".cancel").click(function() { validator.cancelSubmit = true; }); // when a submitHandler is used, capture the submitting button if (validator.settings.submitHandler) { this.find("input, button").filter(":submit").click(function() { validator.submitButton = this; }); } // validate the form on submit this.submit( function( event ) { if ( validator.settings.debug ) // prevent form submit to be able to see console output event.preventDefault(); function handle() { if ( validator.settings.submitHandler ) { if (validator.submitButton) { // insert a hidden input as a replacement for the missing submit button var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm); } validator.settings.submitHandler.call( validator, validator.currentForm ); if (validator.submitButton) { // and clean up afterwards; thanks to no-block-scope, hidden can be referenced hidden.remove(); } return false; } return true; } // prevent submit for invalid forms or custom submit handlers if ( validator.cancelSubmit ) { validator.cancelSubmit = false; return handle(); } if ( validator.form() ) { if ( validator.pendingRequest ) { validator.formSubmitted = true; return false; } return handle(); } else { validator.focusInvalid(); return false; } }); } return validator; }, // http://docs.jquery.com/Plugins/Validation/valid valid: function() { if ( $(this[0]).is('form')) { return this.validate().form(); } else { var valid = true; var validator = $(this[0].form).validate(); this.each(function() { valid &= validator.element(this); }); return valid; } }, // attributes: space seperated list of attributes to retrieve and remove removeAttrs: function(attributes) { var result = {}, $element = this; $.each(attributes.split(/\s/), function(index, value) { result[value] = $element.attr(value); $element.removeAttr(value); }); return result; }, // http://docs.jquery.com/Plugins/Validation/rules rules: function(command, argument) { var element = this[0]; if (command) { var settings = $.data(element.form, 'validator').settings; var staticRules = settings.rules; var existingRules = $.validator.staticRules(element); switch(command) { case "add": $.extend(existingRules, $.validator.normalizeRule(argument)); staticRules[element.name] = existingRules; if (argument.messages) settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages ); break; case "remove": if (!argument) { delete staticRules[element.name]; return existingRules; } var filtered = {}; $.each(argument.split(/\s/), function(index, method) { filtered[method] = existingRules[method]; delete existingRules[method]; }); return filtered; } } var data = $.validator.normalizeRules( $.extend( {}, $.validator.metadataRules(element), $.validator.classRules(element), $.validator.attributeRules(element), $.validator.staticRules(element) ), element); // make sure required is at front if (data.required) { var param = data.required; delete data.required; data = $.extend({required: param}, data); } return data; } }); // Custom selectors $.extend($.expr[":"], { // http://docs.jquery.com/Plugins/Validation/blank blank: function(a) {return !$.trim("" + a.value);}, // http://docs.jquery.com/Plugins/Validation/filled filled: function(a) {return !!$.trim("" + a.value);}, // http://docs.jquery.com/Plugins/Validation/unchecked unchecked: function(a) {return !a.checked;} }); // constructor for validator $.validator = function( options, form ) { this.settings = $.extend( {}, $.validator.defaults, options ); this.currentForm = form; this.init(); }; $.validator.format = function(source, params) { if ( arguments.length == 1 ) return function() { var args = $.makeArray(arguments); args.unshift(source); return $.validator.format.apply( this, args ); }; if ( arguments.length > 2 && params.constructor != Array ) { params = $.makeArray(arguments).slice(1); } if ( params.constructor != Array ) { params = [ params ]; } $.each(params, function(i, n) { source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); }); return source; }; $.extend($.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", validClass: "valid", errorElement: "label", focusInvalid: true, errorContainer: $( [] ), errorLabelContainer: $( [] ), onsubmit: true, ignore: [], ignoreTitle: false, onfocusin: function(element) { this.lastActive = element; // hide error label and remove error class on focus if enabled if ( this.settings.focusCleanup && !this.blockFocusCleanup ) { this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); this.errorsFor(element).hide(); } }, onfocusout: function(element) { if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) { this.element(element); } }, onkeyup: function(element) { if ( element.name in this.submitted || element == this.lastElement ) { this.element(element); } }, onclick: function(element) { // click on selects, radiobuttons and checkboxes if ( element.name in this.submitted ) this.element(element); // or option elements, check parent select in that case else if (element.parentNode.name in this.submitted) this.element(element.parentNode) }, highlight: function( element, errorClass, validClass ) { $(element).addClass(errorClass).removeClass(validClass); }, unhighlight: function( element, errorClass, validClass ) { $(element).removeClass(errorClass).addClass(validClass); } }, // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults setDefaults: function(settings) { $.extend( $.validator.defaults, settings ); }, messages: { required: nv_required, remote: nv_remote, email: nv_email, url: nv_url, date: nv_date, dateISO: nv_dateISO, number: nv_number, digits: nv_digits, creditcard: nv_creditcard, equalTo: nv_equalTo, accept: nv_accept, maxlength: $.validator.format(nv_maxlength), minlength: $.validator.format(nv_minlength), rangelength: $.validator.format(nv_rangelength), range: $.validator.format(nv_range), max: $.validator.format(nv_max), min: $.validator.format(nv_min) }, autoCreateRanges: false, prototype: { init: function() { this.labelContainer = $(this.settings.errorLabelContainer); this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm); this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer ); this.submitted = {}; this.valueCache = {}; this.pendingRequest = 0; this.pending = {}; this.invalid = {}; this.reset(); var groups = (this.groups = {}); $.each(this.settings.groups, function(key, value) { $.each(value.split(/\s/), function(index, name) { groups[name] = key; }); }); var rules = this.settings.rules; $.each(rules, function(key, value) { rules[key] = $.validator.normalizeRule(value); }); function delegate(event) { var validator = $.data(this[0].form, "validator"); validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] ); } $(this.currentForm) .delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate) .delegate("click", ":radio, :checkbox, select, option", delegate); if (this.settings.invalidHandler) $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler); }, // http://docs.jquery.com/Plugins/Validation/Validator/form form: function() { this.checkForm(); $.extend(this.submitted, this.errorMap); this.invalid = $.extend({}, this.errorMap); if (!this.valid()) $(this.currentForm).triggerHandler("invalid-form", [this]); this.showErrors(); return this.valid(); }, checkForm: function() { this.prepareForm(); for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { this.check( elements[i] ); } return this.valid(); }, // http://docs.jquery.com/Plugins/Validation/Validator/element element: function( element ) { element = this.clean( element ); this.lastElement = element; this.prepareElement( element ); this.currentElements = $(element); var result = this.check( element ); if ( result ) { delete this.invalid[element.name]; } else { this.invalid[element.name] = true; } if ( !this.numberOfInvalids() ) { // Hide error containers on last error this.toHide = this.toHide.add( this.containers ); } this.showErrors(); return result; }, // http://docs.jquery.com/Plugins/Validation/Validator/showErrors showErrors: function(errors) { if(errors) { // add items to error list and map $.extend( this.errorMap, errors ); this.errorList = []; for ( var name in errors ) { this.errorList.push({ message: errors[name], element: this.findByName(name)[0] }); } // remove items from success list this.successList = $.grep( this.successList, function(element) { return !(element.name in errors); }); } this.settings.showErrors ? this.settings.showErrors.call( this, this.errorMap, this.errorList ) : this.defaultShowErrors(); }, // http://docs.jquery.com/Plugins/Validation/Validator/resetForm resetForm: function() { if ( $.fn.resetForm ) $( this.currentForm ).resetForm(); this.submitted = {}; this.prepareForm(); this.hideErrors(); this.elements().removeClass( this.settings.errorClass ); }, numberOfInvalids: function() { return this.objectLength(this.invalid); }, objectLength: function( obj ) { var count = 0; for ( var i in obj ) count++; return count; }, hideErrors: function() { this.addWrapper( this.toHide ).hide(); }, valid: function() { return this.size() == 0; }, size: function() { return this.errorList.length; }, focusInvalid: function() { if( this.settings.focusInvalid ) { try { $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus(); } catch(e) { // ignore IE throwing errors when focusing hidden elements } } }, findLastActive: function() { var lastActive = this.lastActive; return lastActive && $.grep(this.errorList, function(n) { return n.element.name == lastActive.name; }).length == 1 && lastActive; }, elements: function() { var validator = this, rulesCache = {}; // select all valid inputs inside the form (no submit or reset buttons) // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved return $([]).add(this.currentForm.elements) .filter(":input") .not(":submit, :reset, :image, [disabled]") .not( this.settings.ignore ) .filter(function() { !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this); // select only the first element for each name, and only those with rules specified if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) return false; rulesCache[this.name] = true; return true; }); }, clean: function( selector ) { return $( selector )[0]; }, errors: function() { return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext ); }, reset: function() { this.successList = []; this.errorList = []; this.errorMap = {}; this.toShow = $([]); this.toHide = $([]); this.currentElements = $([]); }, prepareForm: function() { this.reset(); this.toHide = this.errors().add( this.containers ); }, prepareElement: function( element ) { this.reset(); this.toHide = this.errorsFor(element); }, check: function( element ) { element = this.clean( element ); // if radio/checkbox, validate first element in group instead if (this.checkable(element)) { element = this.findByName( element.name )[0]; } var rules = $(element).rules(); var dependencyMismatch = false; for( method in rules ) { var rule = { method: method, parameters: rules[method] }; try { var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters ); // if a method indicates that the field is optional and therefore valid, // don't mark it as valid when there are no other rules if ( result == "dependency-mismatch" ) { dependencyMismatch = true; continue; } dependencyMismatch = false; if ( result == "pending" ) { this.toHide = this.toHide.not( this.errorsFor(element) ); return; } if( !result ) { this.formatAndAdd( element, rule ); return false; } } catch(e) { this.settings.debug && window.console && console.log("exception occured when checking element " + element.id + ", check the '" + rule.method + "' method", e); throw e; } } if (dependencyMismatch) return; if ( this.objectLength(rules) ) this.successList.push(element); return true; }, // return the custom message for the given element and validation method // specified in the element's "messages" metadata customMetaMessage: function(element, method) { if (!$.metadata) return; var meta = this.settings.meta ? $(element).metadata()[this.settings.meta] : $(element).metadata(); return meta && meta.messages && meta.messages[method]; }, // return the custom message for the given element name and validation method customMessage: function( name, method ) { var m = this.settings.messages[name]; return m && (m.constructor == String ? m : m[method]); }, // return the first defined argument, allowing empty strings findDefined: function() { for(var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } return undefined; }, defaultMessage: function( element, method) { return this.findDefined( this.customMessage( element.name, method ), this.customMetaMessage( element, method ), // title is never undefined, so handle empty string as undefined !this.settings.ignoreTitle && element.title || undefined, $.validator.messages[method], "<strong>Warning: No message defined for " + element.name + "</strong>" ); }, formatAndAdd: function( element, rule ) { var message = this.defaultMessage( element, rule.method ), theregex = /\$?\{(\d+)\}/g; if ( typeof message == "function" ) { message = message.call(this, rule.parameters, element); } else if (theregex.test(message)) { message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters); } this.errorList.push({ message: message, element: element }); this.errorMap[element.name] = message; this.submitted[element.name] = message; }, addWrapper: function(toToggle) { if ( this.settings.wrapper ) toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); return toToggle; }, defaultShowErrors: function() { for ( var i = 0; this.errorList[i]; i++ ) { var error = this.errorList[i]; this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); this.showLabel( error.element, error.message ); } if( this.errorList.length ) { this.toShow = this.toShow.add( this.containers ); } if (this.settings.success) { for ( var i = 0; this.successList[i]; i++ ) { this.showLabel( this.successList[i] ); } } if (this.settings.unhighlight) { for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) { this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass ); } } this.toHide = this.toHide.not( this.toShow ); this.hideErrors(); this.addWrapper( this.toShow ).show(); }, validElements: function() { return this.currentElements.not(this.invalidElements()); }, invalidElements: function() { return $(this.errorList).map(function() { return this.element; }); }, showLabel: function(element, message) { var label = this.errorsFor( element ); if ( label.length ) { // refresh error/success class label.removeClass().addClass( this.settings.errorClass ); // check if we have a generated label, replace the message then label.attr("generated") && label.html(message); } else { // create label label = $("<" + this.settings.errorElement + "/>") .attr({"for": this.idOrName(element), generated: true}) .addClass(this.settings.errorClass) .html(message || ""); if ( this.settings.wrapper ) { // make sure the element is visible, even in IE // actually showing the wrapped element is handled elsewhere label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); } if ( !this.labelContainer.append(label).length ) this.settings.errorPlacement ? this.settings.errorPlacement(label, $(element) ) : label.insertAfter(element); } if ( !message && this.settings.success ) { label.text(""); typeof this.settings.success == "string" ? label.addClass( this.settings.success ) : this.settings.success( label ); } this.toShow = this.toShow.add(label); }, errorsFor: function(element) { var name = this.idOrName(element); return this.errors().filter(function() { return $(this).attr('for') == name }); }, idOrName: function(element) { return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name); }, checkable: function( element ) { return /radio|checkbox/i.test(element.type); }, findByName: function( name ) { // select by name and filter by form for performance over form.find("[name=...]") var form = this.currentForm; return $(document.getElementsByName(name)).map(function(index, element) { return element.form == form && element.name == name && element || null; }); }, getLength: function(value, element) { switch( element.nodeName.toLowerCase() ) { case 'select': return $("option:selected", element).length; case 'input': if( this.checkable( element) ) return this.findByName(element.name).filter(':checked').length; } return value.length; }, depend: function(param, element) { return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true; }, dependTypes: { "boolean": function(param, element) { return param; }, "string": function(param, element) { return !!$(param, element.form).length; }, "function": function(param, element) { return param(element); } }, optional: function(element) { return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch"; }, startRequest: function(element) { if (!this.pending[element.name]) { this.pendingRequest++; this.pending[element.name] = true; } }, stopRequest: function(element, valid) { this.pendingRequest--; // sometimes synchronization fails, make sure pendingRequest is never < 0 if (this.pendingRequest < 0) this.pendingRequest = 0; delete this.pending[element.name]; if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) { $(this.currentForm).submit(); this.formSubmitted = false; } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) { $(this.currentForm).triggerHandler("invalid-form", [this]); this.formSubmitted = false; } }, previousValue: function(element) { return $.data(element, "previousValue") || $.data(element, "previousValue", { old: null, valid: true, message: this.defaultMessage( element, "remote" ) }); } }, classRuleSettings: { required: {required: true}, email: {email: true}, url: {url: true}, date: {date: true}, dateISO: {dateISO: true}, dateDE: {dateDE: true}, number: {number: true}, numberDE: {numberDE: true}, digits: {digits: true}, creditcard: {creditcard: true} }, addClassRules: function(className, rules) { className.constructor == String ? this.classRuleSettings[className] = rules : $.extend(this.classRuleSettings, className); }, classRules: function(element) { var rules = {}; var classes = $(element).attr('class'); classes && $.each(classes.split(' '), function() { if (this in $.validator.classRuleSettings) { $.extend(rules, $.validator.classRuleSettings[this]); } }); return rules; }, attributeRules: function(element) { var rules = {}; var $element = $(element); for (method in $.validator.methods) { var value = $element.attr(method); if (value) { rules[method] = value; } } // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) { delete rules.maxlength; } return rules; }, metadataRules: function(element) { if (!$.metadata) return {}; var meta = $.data(element.form, 'validator').settings.meta; return meta ? $(element).metadata()[meta] : $(element).metadata(); }, staticRules: function(element) { var rules = {}; var validator = $.data(element.form, 'validator'); if (validator.settings.rules) { rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {}; } return rules; }, normalizeRules: function(rules, element) { // handle dependency check $.each(rules, function(prop, val) { // ignore rule when param is explicitly false, eg. required:false if (val === false) { delete rules[prop]; return; } if (val.param || val.depends) { var keepRule = true; switch (typeof val.depends) { case "string": keepRule = !!$(val.depends, element.form).length; break; case "function": keepRule = val.depends.call(element, element); break; } if (keepRule) { rules[prop] = val.param !== undefined ? val.param : true; } else { delete rules[prop]; } } }); // evaluate parameters $.each(rules, function(rule, parameter) { rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter; }); // clean number parameters $.each(['minlength', 'maxlength', 'min', 'max'], function() { if (rules[this]) { rules[this] = Number(rules[this]); } }); $.each(['rangelength', 'range'], function() { if (rules[this]) { rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; } }); if ($.validator.autoCreateRanges) { // auto-create ranges if (rules.min && rules.max) { rules.range = [rules.min, rules.max]; delete rules.min; delete rules.max; } if (rules.minlength && rules.maxlength) { rules.rangelength = [rules.minlength, rules.maxlength]; delete rules.minlength; delete rules.maxlength; } } // To support custom messages in metadata ignore rule methods titled "messages" if (rules.messages) { delete rules.messages } return rules; }, // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function(data) { if( typeof data == "string" ) { var transformed = {}; $.each(data.split(/\s/), function() { transformed[this] = true; }); data = transformed; } return data; }, // http://docs.jquery.com/Plugins/Validation/Validator/addMethod addMethod: function(name, method, message) { $.validator.methods[name] = method; $.validator.messages[name] = message != undefined ? message : $.validator.messages[name]; if (method.length < 3) { $.validator.addClassRules(name, $.validator.normalizeRule(name)); } }, methods: { // http://docs.jquery.com/Plugins/Validation/Methods/required required: function(value, element, param) { // check if dependency is met if ( !this.depend(param, element) ) return "dependency-mismatch"; switch( element.nodeName.toLowerCase() ) { case 'select': // could be an array for select-multiple or a string, both are fine this way var val = $(element).val(); return val && val.length > 0; case 'input': if ( this.checkable(element) ) return this.getLength(value, element) > 0; default: return $.trim(value).length > 0; } }, // http://docs.jquery.com/Plugins/Validation/Methods/remote remote: function(value, element, param) { if ( this.optional(element) ) return "dependency-mismatch"; var previous = this.previousValue(element); if (!this.settings.messages[element.name] ) this.settings.messages[element.name] = {}; previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param = typeof param == "string" && {url:param} || param; if ( previous.old !== value ) { previous.old = value; var validator = this; this.startRequest(element); var data = {}; data[element.name] = value; $.ajax($.extend(true, { url: param, mode: "abort", port: "validate" + element.name, dataType: "json", data: data, success: function(response) { validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response === true; if ( valid ) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; var message = (previous.message = response || validator.defaultMessage( element, "remote" )); errors[element.name] = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending"; } else if( this.pending[element.name] ) { return "pending"; } return previous.valid; }, // http://docs.jquery.com/Plugins/Validation/Methods/minlength minlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/maxlength maxlength: function(value, element, param) { return this.optional(element) || this.getLength($.trim(value), element) <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/rangelength rangelength: function(value, element, param) { var length = this.getLength($.trim(value), element); return this.optional(element) || ( length >= param[0] && length <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/min min: function( value, element, param ) { return this.optional(element) || value >= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/max max: function( value, element, param ) { return this.optional(element) || value <= param; }, // http://docs.jquery.com/Plugins/Validation/Methods/range range: function( value, element, param ) { return this.optional(element) || ( value >= param[0] && value <= param[1] ); }, // http://docs.jquery.com/Plugins/Validation/Methods/email email: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ return this.optional(element) || /^((([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.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/url url: function(value, element) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/date date: function(value, element) { return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); }, // http://docs.jquery.com/Plugins/Validation/Methods/dateISO dateISO: function(value, element) { return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/number number: function(value, element) { return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/digits digits: function(value, element) { return this.optional(element) || /^\d+$/.test(value); }, // http://docs.jquery.com/Plugins/Validation/Methods/creditcard // based on http://en.wikipedia.org/wiki/Luhn creditcard: function(value, element) { if ( this.optional(element) ) return "dependency-mismatch"; // accept only digits and dashes if (/[^0-9-]+/.test(value)) return false; var nCheck = 0, nDigit = 0, bEven = false; value = value.replace(/\D/g, ""); for (var n = value.length - 1; n >= 0; n--) { var cDigit = value.charAt(n); var nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } return (nCheck % 10) == 0; }, // http://docs.jquery.com/Plugins/Validation/Methods/accept accept: function(value, element, param) { param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif"; return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); }, // http://docs.jquery.com/Plugins/Validation/Methods/equalTo equalTo: function(value, element, param) { // bind to the blur event of the target in order to revalidate whenever the target field is updated // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() { $(element).valid(); }); return value == target.val(); } } }); // deprecated, use $.validator.format instead $.format = $.validator.format; })(jQuery); // ajax mode: abort // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() ;(function($) { var ajax = $.ajax; var pendingRequests = {}; $.ajax = function(settings) { // create settings for compatibility with ajaxSetup settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings)); var port = settings.port; if (settings.mode == "abort") { if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return (pendingRequests[port] = ajax.apply(this, arguments)); } return ajax.apply(this, arguments); }; })(jQuery); // provides cross-browser focusin and focusout events // IE has native support, in other browsers, use event caputuring (neither bubbles) // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation // handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target // provides triggerEvent(type: String, target: Element) to trigger delegated events ;(function($) { $.each({ focus: 'focusin', blur: 'focusout' }, function( original, fix ){ $.event.special[fix] = { setup:function() { if ( $.browser.msie ) return false; this.addEventListener( original, $.event.special[fix].handler, true ); }, teardown:function() { if ( $.browser.msie ) return false; this.removeEventListener( original, $.event.special[fix].handler, true ); }, handler: function(e) { arguments[0] = $.event.fix(e); arguments[0].type = fix; return $.event.handle.apply(this, arguments); } }; }); $.extend($.fn, { delegate: function(type, delegate, handler) { return this.bind(type, function(event) { var target = $(event.target); if (target.is(delegate)) { return handler.apply(target, arguments); } }); }, triggerEvent: function(type, target) { return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]); } }) })(jQuery);
JavaScript
/* Copyright (c) 2009 Dimas Begunoff, http://www.farinspace.com Licensed under the MIT license http://en.wikipedia.org/wiki/MIT_License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function imgpreload(imgs,settings) { // settings = { each:Function, all:Function } if (settings instanceof Function) { settings = {all:settings}; } // use of typeof required // https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description if (typeof imgs == "string") { imgs = [imgs]; } var loaded = []; var t = imgs.length; var i = 0; for (i; i<t; i++) { var img = new Image(); img.onload = function() { loaded.push(this); if (settings.each instanceof Function) { settings.each.call(this); } if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); } }; img.src = imgs[i]; } } if (typeof jQuery != "undefined") { (function($){ // extend jquery (because i love jQuery) $.imgpreload = imgpreload; // public $.fn.imgpreload = function(settings) { settings = $.extend({},$.fn.imgpreload.defaults,(settings instanceof Function)?{all:settings}:settings); this.each(function() { var elem = this; imgpreload($(this).attr('src'),function() { if (settings.each instanceof Function) { settings.each.call(elem); } }); }); // declare urls and loop here (loop a second time) to prevent // pollution of above closure with unnecessary variables var urls = []; this.each(function() { urls.push($(this).attr('src')); }); var selection = this; imgpreload(urls,function() { if (settings.all instanceof Function) { settings.all.call(selection); } }); return this; }; // public $.fn.imgpreload.defaults = { each: null // callback invoked when each image in a group loads , all: null // callback invoked when when the entire group of images has loaded }; })(jQuery); } /* Usage: $('#content img').imgpreload(function() { // this = jQuery image object selection // callback executes when all images are loaded }); $('#content img').imgpreload ({ each: function() { // this = dom image object // callback executes when each image loads }, all: function() { // this = jQuery image object selection // callback executes when all images are loaded } }); $.imgpreload('/images/a.gif',function() { // this = new image object // callback }); $.imgpreload(['/images/a.gif','/images/b.gif'],function() { // this = array of new image objects // callback executes when all images are loaded }); $.imgpreload(['/images/a.gif','/images/b.gif'], { each: function() { // this = new image object // callback executes on every image load }, all: function() { // this = array of new image objects // callback executes when all images are loaded } }); */
JavaScript
/** * @Project NUKEVIET 3.0 * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2010 VINADES.,JSC. All rights reserved * @Createdate 31/05/2010, 9:36 */ function nv_checkForm() { var op_name = document.getElementById('op_name').options[document.getElementById('op_name').selectedIndex].value; var type_name = document.getElementById('type_name'); var ext_name = document.getElementById('ext_name'); if (op_name == 'optimize') { type_name.disabled = true; ext_name.disabled = true; } else { type_name.disabled = false; ext_name.disabled = false; } } function nv_chsubmit(oForm, cbName) { var op_name = document.getElementById('op_name').options[document.getElementById('op_name').selectedIndex].value; if (op_name == 'optimize') { var tabs = ""; for ( var i = 0; i < oForm[cbName].length; i++) { if (oForm[cbName][i].checked) { tabs += (tabs != "") ? "," : ""; tabs += oForm[cbName][i].value; } } var subm_form = document.getElementById('subm_form'); subm_form.disabled = true; nv_ajax("POST", oForm.action, nv_fc_variable + '=' + op_name + '&tables=' + tabs, '', 'nv_submit_res'); } else { oForm.submit(); } return; } function nv_submit_res(res) { alert(res); nv_show_dbtables(); return; } function nv_show_dbtables() { nv_ajax("post", script_name, nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=main&show_tabs=1&num=' + nv_randomPassword(8), 'show_tables'); } function nv_show_highlight(tp) { nv_ajax( "post", window.location.href, 'show_highlight=' + tp, 'my_highlight' ); return false; }
JavaScript
/*---------------------------------------------------------------------------- CHIM - CHuoi's Input Method ---------------------------------------------------------------------------- copyright : (C) 2005, 2006, 2007 by Dao Hai Lam/ website : http://xvnkb.sf.net/chim email : daohailam<at>yahoo<dot>com last modify : Thu, 05 Jul 2007 23:07:22 +0700 version : 0.9.3 ---------------------------------------------------------------------------- Mudim - Mudzot's Input Method (c)2008 by Mudzot http://code.google.com/p/mudim email: mudzot<at>gmail.com version: 0.8 date: 29.05.08 ---------------------------------------------------------------------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. -------------------------------------------------------------------------------*/ // Development environment: Firefox with Firebug extension with console debug if (typeof(console)=='undefined') { //if console doesnt exist, use the annoying alert instead console=function () {return this;}; // console.debug <--- instruct the build script remove this line console.debug = function (a) {alert(a)}; } //---------------------------------------------------------------------------- // Class: CHIM //---------------------------------------------------------------------------- CHIM = function() { return this; }; //---------------------------------------------------------------------------- // Class Mudim //---------------------------------------------------------------------------- Mudim = function() { return this; }; //---------------------------------------------------------------------------- // Constants: //---------------------------------------------------------------------------- Mudim.DISPLAY_ID=['mudim-off','mudim-vni','mudim-telex','mudim-viqr','mudim-mix','mudim-auto']; Mudim.SPELLCHECK_ID='mudim-checkspell'; Mudim.ACCENTRULE_ID='mudim-accentrule'; CHIM.CHAR_A = 'A'; CHIM.CHAR_a = 'a'; CHIM.CHAR_E = 'E'; CHIM.CHAR_e = 'e'; CHIM.CHAR_U = 'U'; CHIM.CHAR_u = 'u'; CHIM.CHAR_G = 'G'; CHIM.CHAR_g = 'g'; CHIM.CHAR_Q = 'Q'; CHIM.CHAR_q = 'q'; CHIM.CHAR_y = 'y'; CHIM.CHAR_Y = 'Y'; CHIM.CHAR_i = 'i'; CHIM.CHAR_I = 'I'; CHIM.CHAR_0x80 = String.fromCharCode(0x80); //---------------------------------------------------------------------------- CHIM.vowels = "AIUEOYaiueoy"; CHIM.separators = " !@#$%^&*()_+=-{}[]|\\:\";'<>?,./~`\r\n\t"; //---------------------------------------------------------------------------- CHIM.off = 0; CHIM.buffer = []; CHIM.dirty = false; //---------------------------------------------------------------------------- // Function: CHIM.CharIsUI // Checking if given character is in U & I set or not // // Parameters: // u - given char // // Returns: // True - if u is in [U,I] //---------------------------------------------------------------------------- CHIM.CharIsUI = function(u) { var n, UI = CHIM.UI; u = u.charCodeAt(0); for ( n = 0; UI[n] != 0 && UI[n] != u; n++ ) {} return UI[n] != 0 ? n : -1; }; //---------------------------------------------------------------------------- // Function: CHIM.CharIsO // Checking if given character is O or not // Parameters: // u: the char //---------------------------------------------------------------------------- CHIM.CharIsO = function(u) { var n, O = CHIM.O; u = u.charCodeAt(0); for ( n = 0; O[n] != 0 && O[n] != u; n++ ){} return O[n] != 0 ? n : -1; }; //---------------------------------------------------------------------------- // Function: CHIM.CharPriorityCompare // Compare 2 chars using VNese priority table //---------------------------------------------------------------------------- CHIM.CharPriorityCompare = function(u1, u2) { var VN = CHIM.VN; var n, i = -1, j = -1, u; for ( n = 0, u = u1.charCodeAt(0); VN[n] != 0 && VN[n] != u; n++ ){} if ( VN[n] != 0 ) {i = n;} for ( n = 0, u = u2.charCodeAt(0); VN[n] != 0 && VN[n] != u; n++ ){} if ( VN[n] ) {j = n;} return i - j; }; //---------------------------------------------------------------------------- // Function: CHIM.SetCharAt //---------------------------------------------------------------------------- CHIM.SetCharAt = function( n, c ) { CHIM.buffer[n] = String.fromCharCode( c ); }; //---------------------------------------------------------------------------- // Class: CHIM.Speller //---------------------------------------------------------------------------- CHIM.Speller = function() { return this; }; //---------------------------------------------------------------------------- CHIM.Speller.enabled = true; CHIM.Speller.position = 0; CHIM.Speller.count = 0; CHIM.Speller.vowels = []; CHIM.Speller.lasts = []; //---------------------------------------------------------------------------- CHIM.Speller.Toggle = function() { CHIM.Speller.enabled = !CHIM.Speller.enabled; Mudim.SetPreference(); }; //---------------------------------------------------------------------------- CHIM.Speller.Set = function(position, key) { CHIM.Speller.vowels[CHIM.Speller.count] = CHIM.Speller.position; CHIM.Speller.lasts[CHIM.Speller.count++] = key; CHIM.Speller.position = position; }; //---------------------------------------------------------------------------- CHIM.Speller.Clear = function() { CHIM.Speller.position = -1; CHIM.Speller.count = 0; }; //---------------------------------------------------------------------------- CHIM.Speller.Last = function() { return CHIM.Speller.lasts[CHIM.Speller.count - 1]; }; Mudim.consonants = "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz"; Mudim.spchk = "AIUEOYaiueoy|BDFJKLQSVWXZbdfjklqsvwxz|'`~?.^*+="; Mudim.vwchk = "|oa|uy|ue|oe|ou|ye|ua|uo|ai|ui|oi|au|iu|ia|eu|ie|ao|eo|ay|uu|io|yu|"; Mudim.nvchk = "FfJjWwZz"; Mudim.separators = "!@#$%^&*()_+=-{}[]|\\:\";'<>?,./~`"; Mudim.tailConsonantsPattern = '|c|ch|p|t|m|n|ng|nh|'; /** * Spell checking (if necessary) * If spelling error detected, assign the error index in buffer to CHIM.off * @param (char) key Current key * @param (int) Accent group, 0 means non-accent key * @return true if spelling error detected */ Mudim.CheckSpell = function(key, grp) { var b = CHIM.buffer; var len = b.length; var n = key.toLowerCase(); if (CHIM.Speller.enabled && !Mudim.tempDisableSpellCheck) { //console.debug('Begin CheckSpell'); // Rule based on the ending consonants if (grp > 0 && CHIM.off == 0) { if (Mudim.tailConsonants.length>0) { var ecIdx=Mudim.tailConsonantsPattern.indexOf('|'+Mudim.tailConsonants+'|'); if (ecIdx<0) { // spelling rule as described in Issue #16 comment #1 CHIM.off = len; Mudim.tailConsonants=''; //console.debug('Tail consonants not in pattern, just append'); return true; } else if (ecIdx<9 && grp==2) { var typeid = Mudim.GetMarkTypeID(n,2); if (typeid !=0 && typeid!=1 && typeid!=5) { CHIM.off = len; Mudim.tailConsonants=''; //console.debug('Tail consonants not in pattern, just append'); return true; } } } if (len == 2 && (b[1]==CHIM.CHAR_u || b[1]==CHIM.CHAR_U) && (b[0]==CHIM.CHAR_q || b[0]==CHIM.CHAR_Q) && (grp==2 || (grp==1 && Mudim.GetMarkTypeID(n,1)==1))) { //spelling rule as described in Issue #16 comment #0 CHIM.off = len; return CHIM.Append(len, c, key); } } else if ( !CHIM.off ) { var kp = Mudim.spchk.indexOf(key); if (len>0) { var lkey = b[len-1].toLowerCase(); } if ( len==0 ) { //console.debug('Buffer empty'); if ( Mudim.nvchk.indexOf(key) >= 0 ) { CHIM.off = -1; } else if ( kp >= 0 && kp < 12 ) { CHIM.Speller.Set(0, key); } else if( kp == 12 || kp > 37 ) { return; } else { CHIM.Speller.Clear(); } } else if( kp == 12 || kp > 37 ) { // | or `~^.? CHIM.ClearBuffer(); return; } else if( kp > 12 ) { // b, d, f,... CHIM.off = len; } else if( kp >= 0 ) { // vowels var i = 0; while (Mudim.consonants.indexOf(b[i])>=0) { i++; } if (i>0) { Mudim.headConsonants = b.slice(0,i).toString().replace(/,/g,'').toLowerCase(); } if ( CHIM.Speller.position < 0 ) { if (Mudim.headConsonants == 'q') { // q must be followed by u if (len==1 && n!='u') { //console.debug('Q not followed by u: spelling error'); CHIM.off = len; } else if (b[1] == 'u' && n == 'u') { //console.debug('QUU: spelling error'); CHIM.off = len; } } else if (lkey == 'p' && n!= 'h') { // p must be followed by h //console.debug('P not followed by h: spelling error'); CHIM.off = len; } else if (lkey == 'k' && n != 'i' && n !='e' && n!='y') { //console.debug('K not followed by [iey]: spelling error'); CHIM.off = len; } else if (Mudim.headConsonants == 'ngh' && n!='i' && n!='e') { //console.debug('NGH not followed by [ie]: spelling error'); CHIM.off = len; } else { CHIM.Speller.Set(len, key); if (n == 'y') { if ('hklmst'.indexOf(lkey) < 0) { //console.debug('Y must follow [hklms]: spelling error'); CHIM.off = len; } } else if (n=='e' || n=='i') { if (len>1 && (lkey=='g')) { //console.debug('xg[ie]: spelling error'); CHIM.off=len; } if (lkey=='c') { //console.debug('c[ie] : spelling error'); CHIM.off=1; } } } } else if( len - CHIM.Speller.position > 1 ) { //console.debug('Spelling error'); CHIM.off = len; } else { var w = "|"+CHIM.Speller.Last().toLowerCase()+key.toLowerCase()+"|"; var idx = Mudim.vwchk.indexOf(w); if ( idx < 0 ) { //console.debug('Vowel composition not found: spelling error'); CHIM.off = len; } else if (idx < 18 && (Mudim.headConsonants == 'c' || Mudim.headConsonants == 'C')){ //console.debug('C doesnt come with this vowel composition'); CHIM.off = len; } else if (lkey == 'y' && Mudim.headConsonants == '' && n != 'e') { //console.debug('y[^e] : spelling error'); CHIM.off = len; } else { CHIM.Speller.Set(len,key); } } } else { // special cases switch( key ) { case 'h': case 'H': // [cgknpt]h if( lkey >= CHIM.CHAR_0x80 || "CGKNPTcgknpt".indexOf(lkey) < 0 ) { CHIM.off = len; } break; case 'g': case 'G': // [n]g if( lkey != 'n' && lkey != 'N' ) { CHIM.off = len; } break; case 'r': case 'R': // [t]r if( lkey != 't' && lkey != 'T' ) { CHIM.off = len; } break; default: if( Mudim.consonants.indexOf(lkey) >= 0 ) { CHIM.off = len; } break; } } } if (CHIM.off != 0) { return true; } } return false; }; //---------------------------------------------------------------------------- // Function: CHIM.Append // Add key to buffer and check spelling // Parameters: // count: current buffer length // lastkey: last key in buffer // key: current key //---------------------------------------------------------------------------- CHIM.Append = function(count, lastkey, key) { //console.debug('|%s| (Begin Append)',CHIM.buffer); if ( Mudim.separators.indexOf(key) >= 0 ) { CHIM.ClearBuffer(); return; } Mudim.my='mu'; CHIM.buffer.push(key); return Mudim.AdjustAccent(CHIM.modes[Mudim.method-1][2].charAt(0)); }; //---------------------------------------------------------------------------- // Function: CHIM.AddKey // Add key to internal buffer // // Parameters: // key - the key to add // // Returns: // -1 - if nothing change in the internal buffer // N >= 0 - indicate the position of internal buffer has been changed // Remarks: // Some spell checking with the consonats at the end occur here //---------------------------------------------------------------------------- CHIM.AddKey = function( key ) { var p = -1; var i, j = -1; var b, c = 0, cc, l; var count = CHIM.buffer.length; var m = CHIM.modes[ Mudim.method-1 ], n; var v = null; var autoModeProbe = false; //console.debug('|%s| (Begin AddKey)',CHIM.buffer); if( !count || CHIM.off != 0 || Mudim.tempOff) { if (Mudim.CheckSpell(key,l)) { return CHIM.Append(count, c, key); } return CHIM.Append(0, 0, key); } b = CHIM.buffer; c = b[p = count - 1]; n = key.toLowerCase(); for( l = 1; l < m.length; l++ ) if( m[l].indexOf(n) >= 0 ) {break;} if( l >= m.length ) { //console.debug('Not mark key, just append to buffer'); Mudim.CheckSpell(key,0); return CHIM.Append(count, c, key); } if (Mudim.method == 5) { //Auto detect Mudim.method = Mudim.AutoDetectMode(n); //console.debug("Method detected: "+Mudim.method); autoModeProbe = true; } if ((p=Mudim.FindAccentPos(n))<0) { //console.debug('Appropriate accent position not found, just append'); if (autoModeProbe) { Mudim.method = 5; autoModeProbe = false; } Mudim.CheckSpell(key,0); return CHIM.Append(count, c, key); } //console.debug('Found mark position: %d',p); Mudim.lord='dz'; if (Mudim.CheckSpell(key,l)) { if (autoModeProbe) { Mudim.method = 5; autoModeProbe = false; } return CHIM.Append(count, c, key); } c=b[p]; var x = c.charCodeAt(0); var found = false; //Actually put the mark on defined position if( l == 1 ) { //group 1 //console.debug('Mark key group 1 detected'); m = m[0]; for( i = 0; !found && i < m.length; i++ ) { var k = m[i]; if( k[0] == n ) { for( i = 1; i < k.length; i++ ) { v = CHIM.vncode_1[k[i]]; Mudim.AdjustAccent(n); x=b[p].charCodeAt(0); if (Mudim.GetMarkTypeID(n,1)==3) { //Exception of dd, replace the first char //console.debug('Receive 2nd d, consider 1st char to put mark'); p=0;c=b[p];x=c.charCodeAt(0); } if (Mudim.PutMark(p,x,1,v,n,true)) { //console.debug('Successfully put mark of group 1'); if (p>0 && Mudim.GetMarkTypeID(n,1)==1 && p<count-1 && CHIM.CharIsO(b[p])>=0 && CHIM.CharIsUI(b[p-1])>=0 && b[0]!=CHIM.CHAR_q && b[0]!=CHIM.CHAR_Q) { // uox+ when x!=i ---> u+o+ //console.debug('uoxw when x!=i : put additional + on u'); Mudim.PutMark(p-1,b[p-1].charCodeAt(0),1,CHIM.vn_UW,n,false); } found=true; break; } } break; } } } else { //and group 2 //console.debug('Mark key group 2 detected'); for( i = 0; i < CHIM.vncode_2.length; i++ ) { v = CHIM.vncode_2[i]; if (Mudim.PutMark(p,x,2,v,n,true)) { //console.debug('Successfully put mark of group 2'); found=true; break; } } } if( !found ) { //console.debug('Mark isnt compatible with this position'); Mudim.CheckSpell(key,0); if (autoModeProbe) { //console.debug("Change back to method 5"); Mudim.method = 5; } autoModeProbe = false; return CHIM.Append(count, c, key); } else { if (autoModeProbe) { CHIM.SetDisplay(); } autoModeProbe = false; } if (CHIM.off!=0) { //console.debug('Push the key into buffer due to double mark'); CHIM.buffer.push(key); } return p>=0; }; //---------------------------------------------------------------------------- // Function: CHIM.BackSpace // Delete the last char in internal buffer and update Speller status //---------------------------------------------------------------------------- CHIM.BackSpace = function() { var count = CHIM.buffer.length; if( count <= 0 ) { CHIM.dirty = true; } else { if (Mudim.accent[0]==count-1) Mudim.ResetAccentInfo(); var i=CHIM.vn_OW.length-1; var code = CHIM.buffer[count-1].charCodeAt(0); while (i>=0 && CHIM.vn_OW[i] != code) { // test if this is o+ i--; } if (i<0) { i=CHIM.vn_UW.length-1; while (i>=0 && CHIM.vn_UW[i] != code) { // is this u+ ? i--; } } if (i>=0 && (i%2) == 1) { //console.debug('Decrease w'); Mudim.w--; } --count; CHIM.buffer.pop(); if( count == CHIM.Speller.position ) { CHIM.Speller.position = CHIM.Speller.vowels[--CHIM.Speller.count]; } if( (CHIM.off < 0 && !count) || (count <= CHIM.off) ) { CHIM.off = 0; } } }; //---------------------------------------------------------------------------- // Function: CHIM.ClearBuffer // Clear internal buffer & Speller status //---------------------------------------------------------------------------- CHIM.ClearBuffer = function() { CHIM.off = 0; Mudim.w=0; CHIM.Speller.Clear(); Mudim.ResetAccentInfo(); Mudim.tailConsonants=''; Mudim.headConsonants=''; Mudim.ctrlSerie = 0; Mudim.shiftSerie = 0; if (CHIM.buffer.length>0) { Mudim.tempOff = false; Mudim.tempDisableSpellCheck = false; } CHIM.buffer = []; }; //---------------------------------------------------------------------------- // Function: CHIM.SetDisplay // Show current status on browser //---------------------------------------------------------------------------- CHIM.SetDisplay = function() { if ( typeof(Mudim.DISPLAY_ID) != "undefined" && Mudim.method < Mudim.DISPLAY_ID.length ) { var r; //Clear all button. This is needed by only the lazy rendering engine of my Konqueror for (var i=0;i<5;i++) { r=document.getElementById(Mudim.DISPLAY_ID[i]); if (r) {r.checked = false;} } //Set the selected method on r = document.getElementById( Mudim.DISPLAY_ID[Mudim.method] ); if ( r ) {r.checked = true;} } if ( typeof(Mudim.SPELLCHECK_ID) != "undefined" ) { var r = document.getElementById( Mudim.SPELLCHECK_ID ); if ( r ) {r.checked = CHIM.Speller.enabled;} } if ( typeof(Mudim.ACCENTRULE_ID) != "undefined" ) { var r = document.getElementById( Mudim.ACCENTRULE_ID ); if ( r ) {r.checked = Mudim.newAccentRule;} } }; //---------------------------------------------------------------------------- // Function: CHIM.SwitchMethod // Switching to next pecking method //---------------------------------------------------------------------------- CHIM.SwitchMethod = function() { CHIM.ClearBuffer(); Mudim.method = (++Mudim.method % 6); CHIM.SetDisplay(); Mudim.SetPreference(); }; //---------------------------------------------------------------------------- // Function: CHIM.SetMethod // Set pecking method :-) // // Parameters: // m - value of pecking method //---------------------------------------------------------------------------- CHIM.SetMethod = function(m) { CHIM.ClearBuffer(); Mudim.method = m; CHIM.SetDisplay(); Mudim.SetPreference(); }; //---------------------------------------------------------------------------- // Function: CHIM.Toggle //---------------------------------------------------------------------------- CHIM.Toggle = function() { var p; if (!(p=Mudim.Panel)) {Mudim.InitPanel();} if (Mudim.method == 0) { CHIM.SetMethod(Mudim.oldMethod); } else { Mudim.oldMethod=Mudim.method; CHIM.SetMethod(0); } Mudim.SetPreference(); }; //---------------------------------------------------------------------------- // Function: CHIM.GetTarget // Get the current target which CHIM's pointing to // // Parameters: // e - the current active event // // Returns: // The current target //---------------------------------------------------------------------------- CHIM.GetTarget = function(e) { var r; if ( e == null ) { e = window.event; } if ( e == null ) { return null; } if ( e.srcElement != null ) { // IE r = e.srcElement; } else { r = e.target; while ( r && r.nodeType != 1 ) // climb up from text nodes on Moz r = r.parentNode; } if (r.tagName == 'BODY') { r = r.parentNode; } CHIM.peckable = r.tagName=='HTML' || r.type=='textarea' || r.type=='text'; return r; }; //---------------------------------------------------------------------------- // Function: CHIM.GetCursorPosition //---------------------------------------------------------------------------- CHIM.GetCursorPosition = function( target ) { if (target == null || target.value == null || target.value.length == 0) { return -1; } // Moz/Opera if (typeof(target.selectionStart) != 'undefined') { if (target.selectionStart < 0 || target.selectionStart > target.length || target.selectionEnd < 0 || target.selectionEnd > target.length || target.selectionEnd < target.selectionStart) { return -1; } return target.selectionStart; } // IE if (document.selection) { var selection = document.selection.createRange(); var textRange = target.createTextRange(); // if the current selection is within the edit control if (textRange == null || selection == null || ((selection.text != "") && textRange.inRange(selection) == false)) { return -1; } if (selection.text == "") { var index = 1; if ( target.tagName == "INPUT" ) { var contents = textRange.text; while (index < contents.length) { textRange.findText(contents.substring(index)); if (textRange.boundingLeft == selection.boundingLeft) {break;} index++; } } // Handle text areas. else if ( target.tagName == "TEXTAREA" ) { var caret = document.selection.createRange().duplicate(); index = target.value.length + 1; while (caret.parentElement() == target && caret.move("character", 1) == 1) { --index; if (target.value.charCodeAt(index) == 10) {index -= 1;} } if (index == target.value.length + 1) {index = -1;} } return index; } return textRange.text.indexOf(selection.text); } }; //---------------------------------------------------------------------------- // Function: CHIM.SetCursorPosition //---------------------------------------------------------------------------- CHIM.SetCursorPosition = function(target, p) { if (p < 0) {return;} if (target.setSelectionRange) { target.setSelectionRange(p, p); } else if (target.createTextRange) { var range = target.createTextRange(); range.collapse(true); // odd behaviour each 4th times when a mark is put at the end of line var i; var dec = 0; for (i = 0; i<p; i++) { if ((target.value.charCodeAt(i) == 10) || (target.value.charCodeAt(i) == 13)) { if (dec == 0) { --p; dec = 1; } } else { dec = 0; } } range.moveStart('character', p); range.moveEnd('character', 0); range.select(); } }; /** * Update buffer content with the word which appears right before the cursor * @param (object) target The target text element */ CHIM.UpdateBuffer = function(target) { CHIM.ClearBuffer(); if (target.tagName != 'HTML') { var separators = CHIM.separators; var c = CHIM.GetCursorPosition( target ) - 1; if ( c > 0 ) { while ( c >= 0 && separators.indexOf(target.value.charAt(c)) < 0 ) { CHIM.buffer.unshift(target.value.charAt(c)); c = c - 1; } } Mudim.startWordOffset = c + 1; } else { CHIM.buffer = CHIM.HTMLEditor.GetCurrentWord(target).split(''); } CHIM.dirty = false; }; //---------------------------------------------------------------------------- CHIM.VK_TAB = 9; CHIM.VK_BACKSPACE = 8; CHIM.VK_ENTER = 13; CHIM.VK_DELETE = 46; CHIM.VK_SPACE = 32; CHIM.VK_LIMIT = 128; CHIM.VK_LEFT_ARROW = 37; CHIM.VK_RIGHT_ARROW = 39; CHIM.VK_HOME = 36; CHIM.VK_END = 35; CHIM.VK_PAGE_UP = 33; CHIM.VK_PAGE_DOWN = 34; CHIM.VK_UP_ARROW = 38; CHIM.VK_DOWN_ARROW = 40; CHIM.VK_ONOFF = 120; //F9 CHIM.VK_ONOFF2 = 121; //F10 CHIM.VK_PANELTOGGLE = 119; //F8 CHIM.VK_CTRL = 17; CHIM.VK_SHIFT = 16; CHIM.VK_ALT = 18; //---------------------------------------------------------------------------- // Function: ProcessControlKey //---------------------------------------------------------------------------- CHIM.ProcessControlKey = function(keyCode, release) { switch ( keyCode ) { case CHIM.VK_TAB: case CHIM.VK_ENTER: CHIM.ClearBuffer(); break; case CHIM.VK_BACKSPACE: if (!release) {CHIM.BackSpace();} break; case CHIM.VK_DELETE: case CHIM.VK_LEFT_ARROW: case CHIM.VK_RIGHT_ARROW: case CHIM.VK_HOME: case CHIM.VK_END: case CHIM.VK_PAGE_UP: case CHIM.VK_PAGE_DOWN: case CHIM.VK_UP_ARROW: case CHIM.VK_DOWN_ARROW: CHIM.dirty = true; break; } }; //---------------------------------------------------------------------------- // Function: IsHotkey // Check if key pressed is a CHIM hotkey or not // // Parameters: // e - the event object // k - the value of key // // Returns: // True - if k is a hotkey // // See also: // <CHIM.SwitchMethod> //---------------------------------------------------------------------------- CHIM.IsHotkey = function(e, k) { if ( k == CHIM.VK_PANELTOGGLE ) { Mudim.TogglePanel();return true; } else if (k == CHIM.VK_ONOFF || k == CHIM.VK_ONOFF2) { CHIM.Toggle(); return true; } return false; }; //---------------------------------------------------------------------------- // Class: CHIM.HTMLEditor //---------------------------------------------------------------------------- CHIM.HTMLEditor = function() { return this; }; //---------------------------------------------------------------------------- // Function: CHIM.HTMLEditor.GetRange //---------------------------------------------------------------------------- CHIM.HTMLEditor.GetRange = function(target) { if (!target.parentNode.iframe) {return;} var win = target.parentNode.iframe.contentWindow; return (!window.opera && document.all) ? win.document.selection.createRange() : win.getSelection().getRangeAt(0); }; //---------------------------------------------------------------------------- // Function: CHIM.HTMLEditor.GetCurrentWord //---------------------------------------------------------------------------- CHIM.HTMLEditor.GetCurrentWord = function(target) { var range = CHIM.HTMLEditor.GetRange(target); if (!range) {return '';} if (!window.opera && document.all) { while (range.moveStart('character', -1) == -1) { if (CHIM.separators.indexOf(range.text.charAt(0)) >= 0) { range.moveStart('character', 1); break; } } return range.text; } var word = ''; var s; if (!(s = range.startContainer.nodeValue)) {return '';} var c = range.startOffset - 1; if (c > 0) { while ( c >= 0 && CHIM.separators.indexOf(s.charAt(c)) < 0 && s.charCodeAt(c)!=160) { //It's so strange that space character appears to have code 160 in iframe. But issue 7 fixed word = s.charAt(c) + word; c = c - 1; } } return word; }; //---------------------------------------------------------------------------- // Function: CHIM.HTMLEditor.Process //---------------------------------------------------------------------------- CHIM.HTMLEditor.Process = function(target, l) { var range = CHIM.HTMLEditor.GetRange(target); if (typeof(range)=='undefined') { return; } var b = CHIM.buffer; if (!window.opera && document.all) { var x = -l; range.moveStart('character', x); range.moveEnd('character', x+b.length); range.pasteHTML(b.toString().replace(/,/g,'')); return; } var container = range.startContainer; var offset = range.startOffset; var start = offset - l; container.nodeValue = container.nodeValue.substring(0, start) + b.toString().replace(/,/g,'') + container.nodeValue.substring(start + l); if (l<b.length) {offset++;} range.setEnd(container, offset); range.setStart(container, offset); }; //---------------------------------------------------------------------------- // Function: CHIM.Freeze //---------------------------------------------------------------------------- CHIM.Freeze = function(target) { /*var ign = Mudim.IGNORE_ID; if (ign.length > 0) { for ( var i = 0; i < ign.length; i++ ) { if( target.id == ign[i] ) {return true;} } } return false;*/ var ign = Mudim.IGNORE_ID; return ( ign.test( target.id ) ) ? true : false; }; //---------------------------------------------------------------------------- // Function: CHIM.KeyHandler // Handle key press event //---------------------------------------------------------------------------- CHIM.KeyHandler = function(e) { if ( e == null ) {e = window.event;} if (e.isHandled==true) {return;} e.isHandled=true; var keyCode = e.keyCode; if ( keyCode == 0 ) { // as it might on Moz keyCode = e.charCode; } if ( keyCode == 0 ) { // unlikely to get here keyCode = e.which; } if ( Mudim.method == 0 ) {return;} var target = null; if ( !(target = CHIM.GetTarget(e)) || !CHIM.peckable || CHIM.Freeze(target) ) {return;} if ( e.ctrlKey || e.ctrlLeft || e.metaKey) { if (keyCode == CHIM.VK_BACKSPACE || keyCode == CHIM.VK_LEFT_ARROW || keyCode == CHIM.VK_RIGHT_ARROW) { CHIM.dirty = true; } return; } if ( e.charCode == null || e.charCode != 0 ) { // process ASCII only var key = String.fromCharCode(keyCode); if ( keyCode == CHIM.VK_SPACE || keyCode == CHIM.VK_ENTER ) { CHIM.ClearBuffer(); } else if ( keyCode > CHIM.VK_SPACE && keyCode < CHIM.VK_LIMIT ) { if ( CHIM.dirty ) { CHIM.UpdateBuffer( target ); } var l = CHIM.buffer.length; if (l==0) { Mudim.startWordOffset=CHIM.GetCursorPosition(target); } if (Mudim.newTempDisableSpellCheckRequest) { CHIM.ClearBuffer(); Mudim.startWordOffset=CHIM.GetCursorPosition(target); Mudim.newTempDisableSpellCheckRequest = false; } if (CHIM.AddKey(key) ) { if (e.stopPropagation) {e.stopPropagation();} if (e.preventDefault) {e.preventDefault();} e.cancelBubble = true; e.returnValue = false; Mudim.UpdateUI(target,l); } } else { CHIM.dirty = true; } } else { // process control key CHIM.ProcessControlKey( keyCode, true ); } }; /** *Catch keyup event to implement escaping Mudim for current word *@param (object) e Event passed by browser */ CHIM.KeyUp = function(e) { if ( e == null ) {e = window.event;} if ( e.keyCode == CHIM.VK_SHIFT ) { if (Mudim.shiftSerie == 1) { //console.debug('Temporarily turn off'); Mudim.tempOff = true; Mudim.shiftSerie = 0; } } if ( e.keyCode == CHIM.VK_CTRL ) { if (Mudim.ctrlSerie == 1) { //console.debug('Temporarily disable spell checking'); Mudim.tempDisableSpellCheck = true; Mudim.ctrlSerie = 0; Mudim.newTempDisableSpellCheckRequest = true; } } //console.debug('ctrl: '+Mudim.ctrlSerie+' || tempDis: '+Mudim.tempDisableSpellCheck); }; //---------------------------------------------------------------------------- // Function: KeyDown // Handle the key down event // // Parameters: // e - event which is passed by some browsers //---------------------------------------------------------------------------- CHIM.KeyDown = function(e) { var target = null; if ( e == null ) {e = window.event;} if (CHIM.IsHotkey(e,e.keyCode)) {return;} if (e.altKey || e.altLeft) { return; } if ( e.shiftKey || e.shiftLeft || e.metaKey ) { Mudim.shiftSerie |= 1; //Shift pressed if (e.keyCode != CHIM.VK_SHIFT) { // Shift-x Mudim.shiftSerie |= 2; } return; } if ( e.ctrlKey || e.ctrlLeft || e.metaKey ) { Mudim.ctrlSerie |= 1; //Ctrl pressed if (e.keyCode != CHIM.VK_CTRL) { // Ctrl-x Mudim.ctrlSerie |= 2; } return; } if ( !(target = CHIM.GetTarget(e)) || !CHIM.peckable || CHIM.Freeze(target) ) {return;} var keyCode = e.keyCode; if ( keyCode == 0 ) { // as it might on Moz keyCode = e.charCode; } if ( keyCode == 0 ) { // unlikely to get here keyCode = e.which; } CHIM.ProcessControlKey( keyCode, false ); }; //---------------------------------------------------------------------------- // Function: MouseDown // Handle the mouse down event //---------------------------------------------------------------------------- CHIM.MouseDown = function(e) { CHIM.Activate(); CHIM.dirty = true; }; //---------------------------------------------------------------------------- // Function: Attach // Attach CHIM to an element // // Parameters: // e - element to attach // r - boolean value indicates that CHIM functions will replace the // default handlers //---------------------------------------------------------------------------- CHIM.Attach = function(e, r) { if (!e) {return;} if (!e.chim) { if (!r) { if (!window.opera && document.all) { // IE e.attachEvent('onkeydown', CHIM.KeyDown); e.attachEvent('onkeyup', CHIM.KeyUp); e.attachEvent('onkeypress', CHIM.KeyHandler); e.attachEvent('onmousedown', CHIM.MouseDown); } else { // Moz & others e.addEventListener('keydown', CHIM.KeyDown, false); e.addEventListener('keyup', CHIM.KeyUp, false); e.addEventListener('keypress', CHIM.KeyHandler, false); e.addEventListener('mousedown', CHIM.MouseDown, false); } } else { e.onkeydown = CHIM.KeyDown; e.onkeyup = CHIM.KeyUp; e.onkeypress = CHIM.KeyHandler; e.onmousedown = CHIM.MouseDown; } e.chim = true; } var f = e.getElementsByTagName('iframe'); for (var i = 0; i < f.length; i++) { var doc = (!window.opera && document.all) ? f[i].contentWindow.document : f[i].contentDocument; try { doc.iframe = f[i]; CHIM.Attach(doc, false); } catch(e) {} } var f = e.getElementsByTagName('frame'); for (var i = 0; i < f.length; i++) { var doc = (!window.opera && document.all) ? f[i].contentWindow.document : f[i].contentDocument; try { doc.iframe = f[i]; CHIM.Attach(doc, false); } catch(e) {} } }; //---------------------------------------------------------------------------- // Function: CHIM.Activate //---------------------------------------------------------------------------- CHIM.Activate = function() { try { CHIM.Attach(document, true); CHIM.SetDisplay(); } catch (exc) { } }; //---------------------------------------------------------------------------- // Code tables //---------------------------------------------------------------------------- CHIM.vn_A0=[65,193,192,7842,195,7840]; CHIM.vn_a0=[97,225,224,7843,227,7841]; CHIM.vn_A6=[194,7844,7846,7848,7850,7852]; CHIM.vn_a6=[226,7845,7847,7849,7851,7853]; CHIM.vn_A8=[258,7854,7856,7858,7860,7862]; CHIM.vn_a8=[259,7855,7857,7859,7861,7863]; CHIM.vn_O0=[79,211,210,7886,213,7884]; CHIM.vn_o0=[111,243,242,7887,245,7885]; CHIM.vn_O6=[212,7888,7890,7892,7894,7896]; CHIM.vn_o6=[244,7889,7891,7893,7895,7897]; CHIM.vn_O7=[416,7898,7900,7902,7904,7906]; CHIM.vn_o7=[417,7899,7901,7903,7905,7907]; CHIM.vn_U0=[85,218,217,7910,360,7908]; CHIM.vn_u0=[117,250,249,7911,361,7909]; CHIM.vn_U7=[431,7912,7914,7916,7918,7920]; CHIM.vn_u7=[432,7913,7915,7917,7919,7921]; CHIM.vn_E0=[69,201,200,7866,7868,7864]; CHIM.vn_e0=[101,233,232,7867,7869,7865]; CHIM.vn_E6=[202,7870,7872,7874,7876,7878]; CHIM.vn_e6=[234,7871,7873,7875,7877,7879]; CHIM.vn_I0=[73,205,204,7880,296,7882]; CHIM.vn_i0=[105,237,236,7881,297,7883]; CHIM.vn_Y0=[89,221,7922,7926,7928,7924]; CHIM.vn_y0=[121,253,7923,7927,7929,7925]; //---------------------------------------------------------------------------- CHIM.vncode_2=[ CHIM.vn_A0,CHIM.vn_a0,CHIM.vn_A6,CHIM.vn_a6,CHIM.vn_A8,CHIM.vn_a8, CHIM.vn_O0,CHIM.vn_o0,CHIM.vn_O6,CHIM.vn_o6,CHIM.vn_O7,CHIM.vn_o7, CHIM.vn_U0,CHIM.vn_u0,CHIM.vn_U7,CHIM.vn_u7, CHIM.vn_E0,CHIM.vn_e0,CHIM.vn_E6,CHIM.vn_e6, CHIM.vn_I0,CHIM.vn_i0,CHIM.vn_Y0,CHIM.vn_y0 ]; //---------------------------------------------------------------------------- CHIM.vn_AA=[ 65,194,193,7844,192,7846,7842,7848,195,7850,7840,7852,258,194,7854,7844, 7856,7846,7858,7848,7860,7850,7862,7852,97,226,225,7845,224,7847,7843, 7849,227,7851,7841,7853,259,226,7855,7845,7857,7847,7859,7849,7861,7851, 7863,7853 ]; CHIM.vn_AW=[ 65,258,193,7854,192,7856,7842,7858,195,7860,7840,7862,194,258,7844,7854, 7846,7856,7848,7858,7850,7860,7852,7862,97,259,225,7855,224,7857,7843, 7859,227,7861,7841,7863,226,259,7845,7855,7847,7857,7849,7859,7851,7861, 7853,7863 ]; //---------------------------------------------------------------------------- CHIM.vn_OO=[ 79,212,211,7888,210,7890,7886,7892,213,7894,7884,7896,416,212,7898,7888, 7900,7900,7902,7892,7904,7894,7906,7896,111,244,243,7889,242,7891,7887, 7893,245,7895,7885,7897,417,244,7899,7889,7901,7891,7903,7893,7905,7895, 7907,7897 ]; CHIM.vn_OW=[ 79,416,211,7898,210,7900,7886,7902,213,7904,7884,7906,212,416,7888,7898, 7890,7900,7892,7902,7894,7904,7896,7906,111,417,243,7899,242,7901,7887, 7903,245,7905,7885,7907,244,417,7889,7899,7891,7901,7893,7903,7895,7905, 7897,7907 ]; CHIM.vn_UW=[ 85,431,218,7912,217,7914,7910,7916,360,7918,7908,7920,117,432,250, 7913,249,7915,7911,7917,361,7919,7909,7921]; CHIM.vn_EE=[ 69,202,201,7870,200,7872,7866,7874,7868,7876,7864,7878,101,234,233,7871, 232,7873,7867,7875,7869,7877,7865,7879 ]; CHIM.vn_DD=[68,272,100,273]; //---------------------------------------------------------------------------- CHIM.vncode_1=[ CHIM.vn_AA,CHIM.vn_EE,CHIM.vn_OO, CHIM.vn_AW,CHIM.vn_OW,CHIM.vn_UW, CHIM.vn_DD ]; //---------------------------------------------------------------------------- CHIM.modes=[ [[['6',0,1,2],['7',4,5],['8',3],['9',6]],'6789','012345'], [[['a',0],['e',1],['o',2],['w',3,4,5],['d',6]],'ewoda','zsfrxj'], [[['^',0,1,2],['+',4,5],['(',3],['d',6]],'^+(d',"='`?~."], [[['6',0,1,2],['7',4,5],['8',3],['9',6],['a',0],['e',1],['o',2],['w',3,4,5],['d',6]],'6789ewoda',"012345zsfrxj"], [[['6',0,1,2],['7',4,5],['8',3],['9',6],['a',0],['e',1],['o',2],['w',3,4,5],['d',6],['^',0,1,2],['+',4,5],['(',3],['d',6]],'6789ewoda^+(d',"012345zsfrxj='`?~."] ]; //---------------------------------------------------------------------------- CHIM.UI=[ 85,218,217,7910,360,7908,117,250,249,7911,361,7909,431,7912,7914,7916, 7918,7920,432,7913,7915,7917,7919,7921,73,205,204,7880,296,7882,105,237, 236,7881,297,7883,0 ]; //---------------------------------------------------------------------------- CHIM.O=[ 79,211,210,7886,213,7884,111,243,242,7887,245,7885,212,7888,7890,7892, 7894,7896, 244,7889,7891,7893,7895,7897,416,7898,7900,7902,7904,7906, 417,7899,7901,7903,7905,7907,0]; //---------------------------------------------------------------------------- CHIM.VN=[ 97,65,225,193,224,192,7843,7842,227,195,7841,7840,226,194,7845,7844,7847, 7846,7849,7848,7851,7850,7853,7852,259,258,7855,7854,7857,7856,7859,7858, 7861,7860,7863,7862,101,69,233,201,232,200,7867,7866,7869,7868,7865,7864, 234,202,7871,7870,7873,7872,7875,7874,7877,7876,7879,7878,111,79,243,211, 242,210,7887,7886,245,213,7885,7884,244,212,7889,7888,7891,7890,7893, 7892,7895,7894,7897,7896,417,416,7899,7898,7901,7900,7903,7902,7905,7904, 7907,7906,121,89,253,221,7923,7922,7927,7926,7929,7928,7925,7924,117,85, 250,218,249,217,7911,7910,361,360,7909,7908,432,431,7913,7912,7915,7914, 7917,7916,7919,7918,7921,7920,105,73,237,205,236,204,7881,7880,297,296, 7883,7882,273,272,0 ]; //--------------------------------------------------------------------------- // Function: UpdateUI // Synchronize text content with internal buffer after adding key // Parameters: // target: the text container (textbox, textarea, ...) // l : buffer length BEFORE adding key //--------------------------------------------------------------------------- Mudim.UpdateUI = function(target,l) { var b=CHIM.buffer; if (target.tagName == 'HTML') { CHIM.HTMLEditor.Process(target, l); if (l < CHIM.buffer.length) {return;} return false; } var start = Mudim.startWordOffset < 0 ? 0 : Mudim.startWordOffset; var end = CHIM.GetCursorPosition(target); var t = target.scrollTop; target.value = target.value.substring( 0, start ) + b.toString().replace(/,/g,'') + target.value.substring( end ); CHIM.SetCursorPosition( target, start + b.length); target.scrollTop = t; }; //--------------------------------------------------------------------------- // Function FindAccentPos // Find position to put accent based on current internal buffer content, provided with the most possible next key // Return: // the position (index in buffer) //--------------------------------------------------------------------------- Mudim.FindAccentPos = function(nKey) { var k=nKey.toLowerCase(); var m=CHIM.modes[Mudim.method-1]; var b=CHIM.buffer; var len=b.length; var i,j,l,p,c; if (!len || CHIM.off!=0) {return -1;} for( i = 1; i < m.length; i++ ) if( m[i].indexOf(k) >= 0 ) {break;} p=len-1; Mudim.is='ot'; switch (l=i) { case 1: if (Mudim.GetMarkTypeID(k,1)==3) {break;} // d in telex case 2: default: i=p; while (i>=0 && b[i] < CHIM.CHAR_0x80 && CHIM.vowels.indexOf(b[i])<0) i--; //Find the last vowel if (i<0) {return -1;} if (i<len-1) { //consonants at the end, copy them to Mudim.tailConsonants for spell checking Mudim.tailConsonants=b.slice(i+1,len).toString().replace(/,/g,'').toLowerCase(); } while( i-1 >= 0 && (CHIM.vowels.indexOf(b[i-1]) >=0 || b[i-1] > CHIM.CHAR_0x80) && CHIM.CharPriorityCompare( b[i-1], b[i] ) < 0 ) i--; if( i == len-1 && i-1 >= 0 && (j = CHIM.CharIsUI(b[i-1])) > 0 ) { switch( b[i] ) { case CHIM.CHAR_a: case CHIM.CHAR_A: //something like lu'a, bu`a, .. BUT only change when deal with mark group 2 or ( of group 1 if ( (i-2 < 0 || (j < 24 && b[i-2] != CHIM.CHAR_q && b[i-2] != CHIM.CHAR_Q) || (j >= 24 && b[i-2] != CHIM.CHAR_g && b[i-2] != CHIM.CHAR_G) ) && (l==2 || (l==1 && Mudim.GetMarkTypeID(k,1)==1))) i--; break; case CHIM.CHAR_u: case CHIM.CHAR_U: if( i-2 < 0 || (b[i-2] != CHIM.CHAR_g && b[i-2] != CHIM.CHAR_G) ) i--; break; case CHIM.CHAR_Y: case CHIM.CHAR_y: //old accent rule : tu`y, hu?y, .... but quy` , quy? if ( (!Mudim.newAccentRule) && i-2>=0 && b[i-2]!=CHIM.CHAR_q && b[i-2]!=CHIM.CHAR_Q ) {i--;} break; } } if ( i == len-1 && i-1 >=0 && CHIM.CharIsO(b[i-1]) > 0) { switch(b[i]) { case CHIM.CHAR_a: case CHIM.CHAR_A: if (!Mudim.newAccentRule && (l==2 || (l==1 && Mudim.GetMarkTypeID(k,1)!=1))) i--; break; case CHIM.CHAR_e: case CHIM.CHAR_E: if (!Mudim.newAccentRule) i--; break; }; } if (i == len-2 && i-1 >= 0) { // qux ---> put mark on x var uipos=CHIM.CharIsUI(b[i]); if (uipos>=0 && uipos<24 & (b[i-1]==CHIM.CHAR_q || b[i-1]==CHIM.CHAR_Q)) { i++; } } p=i; break; }; if (Mudim.GetMarkTypeID(k,1)==3 && b[0]=='d') {return 0;} return p; }; //--------------------------------------------------------------------------- //Function Mudim.PutMark // put diacritical mark //Parameters: // pos: position in buffer to put // charCodeAtPos: code of the character at pos // group: mark group (1 or 2 ), define which table (vncode_1 or vncode_2) // idx: index in the table // key: the key added // checkDouble: raise CHIM.off when delete mark //--------------------------------------------------------------------------- Mudim.PutMark = function(pos,charCodeAtPos,group,subsTab,key,checkDouble) { var v = subsTab; var i; //console.debug('|'+CHIM.buffer+'| (Begin PutMark)'); for (i=0;i<v.length;i++) { if (v[i]==charCodeAtPos) { switch (group) { case 1: if (Mudim.GetMarkTypeID(key,1)==1) {Mudim.w++;} if( i % 2 == 0 ) { CHIM.SetCharAt( pos, v[i+1] ); } else { CHIM.SetCharAt( pos, v[i-1] ); if (checkDouble) { CHIM.off = CHIM.buffer.length + 1; } } break; case 2: var j = Mudim.GetMarkTypeID(key,2); if( j >= 0 ) { if( j != i ) { CHIM.SetCharAt( pos, v[j] ); //console.debug('Mark group 2 added'); Mudim.accent=[pos,(CHIM.buffer[pos]).charCodeAt(0),v,key]; } else { CHIM.SetCharAt(pos, v[0]); Mudim.ResetAccentInfo(); if (checkDouble) { //console.debug('Double mark, clear now'); CHIM.off = CHIM.buffer.length + 1; } } } break; } return true; } } return false; }; //--------------------------------------------------------------------------- // Function ResetAccentInfo // Reset information about current accent //--------------------------------------------------------------------------- Mudim.ResetAccentInfo = function() { Mudim.accent = [-1,0,null,'z']; }; //--------------------------------------------------------------------------- // Function AdjustAccent // Update accent position when it is changed // Return: // true if accent has been updated successfully //--------------------------------------------------------------------------- Mudim.AdjustAccent = function(vk) { //console.debug('|'+CHIM.buffer+'| (Begin AdjustAccent)'); if (CHIM.off!=0) { return false; } var p=Mudim.FindAccentPos(vk); var a = Mudim.accent; var b=CHIM.buffer; var v,i,j,c; if (p<0) { return false;} i = CHIM.vn_OW.length-1; c = b[p].charCodeAt(0); while (i>=0 && CHIM.vn_OW[i]!=c) {i--;} j = CHIM.vn_UW.length-1; if (p>0) { c=b[p-1].charCodeAt(0); while (j>=0 && CHIM.vn_UW[j]!=c) {j--;} } else { j=-1; } //uo if (p<b.length-1 && p>0 && i>=0 && j>=0) { //console.debug('uo detected with w = '+Mudim.w); if (Mudim.w==1) { if (i%2==0) { //u+o Mudim.PutMark(p,b[p].charCodeAt(0),1,CHIM.vn_OW,CHIM.modes[Mudim.method-1][1].charAt(1),false); //u+ o+ if (b[0]==CHIM.CHAR_q || b[0]==CHIM.CHAR_Q) { //if word starts with 'q' then change to uo+ //console.debug('Change to quo+'); Mudim.PutMark(p-1,b[p-1].charCodeAt(0),1,CHIM.vn_UW,CHIM.modes[Mudim.method-1][1].charAt(1),false); } } else { //uo+ if (b[0]!=CHIM.CHAR_q && b[0]!=CHIM.CHAR_Q) { //if word doesnt start with 'q' then change to u+o+ Mudim.PutMark(p-1,b[p-1].charCodeAt(0),1,CHIM.vn_UW,CHIM.modes[Mudim.method-1][1].charAt(1),false); } } return true; } } if (a[0]>=0 && p>0 && a[0]!=p) { // Automatically adjust the accent, when position changes //console.debug('Accent position changed, adjust now'); Mudim.PutMark(a[0],a[1],2,a[2],a[3],false); for( i = 0; i < CHIM.vncode_2.length; i++ ) { v = CHIM.vncode_2[i]; if (Mudim.PutMark(p,b[p].charCodeAt(0),2,v,a[3],true)) { break; } } return true; } return false; }; //---------------------------------------------------------------------------- // Function: GetMarkTypeID // get the index in mark string of each method // Parameters: // key: the key // group: mark group (1 or 2) // Return: // -1 if this key is not a mark key // or the index in mark key string. // Remarks: // Use global variable Mudim.method // For group 1, the return value is stable only for the ones used in implementation (1 and 3) //---------------------------------------------------------------------------- Mudim.GetMarkTypeID = function (key,group) { var m = CHIM.modes[Mudim.method-1]; if (Mudim.method != 4) { return m[group].indexOf(key); } else { var j = -1; for (var i = 0; i < 2; i++) { j = CHIM.modes[i][group].indexOf(key); if (j>=0) { return j; } } return j; } }; /** * Auto detect typing mode based on current character * @param(char) c Current character *@return typing mode */ Mudim.AutoDetectMode = function(c) { var gi; if ((gi = CHIM.modes[4][1].indexOf(c))>=0) { if (gi<4) { return 1; } else if (gi<9) { return 2; } else { return 3; } } else if ((gi = CHIM.modes[4][2].indexOf(c))>=0) { if (gi<6) { return 1; } else if (gi<12) { return 2; } else { return 3; } } else { return 0; } }; //---------------------------------------------------------------------------- // Function: Mudim.SetPreference() //---------------------------------------------------------------------------- Mudim.SetPreference = function() { var d=new Date(); d.setTime(d.getTime()+604800000); var tail=';expires='+d.toGMTString()+';path=/'; var value = Mudim.method; var value= CHIM.Speller.enabled ? value + 8 : value; value = Mudim.newAccentRule ? value + 16 : value; value = Mudim.showPanel ? value + 32 : value; value += Mudim.displayMode * 64; document.cookie='|mudim-settings='+value+tail; //console.debug('Cookie value written : |mudim-settings='+value+tail); }; //---------------------------------------------------------------------------- // Function: Mudim.GetPreference() //---------------------------------------------------------------------------- Mudim.GetPreference = function() { var c=document.cookie.split(';'); for (var i=0;i<c.length && c[i].indexOf('|mudim-settings')<0;i++); if (i==c.length) { CHIM.SetDisplay(); } else { var value=parseInt(c[i].split('=')[1],10); //console.debug('Cookie value read : %d',value); Mudim.method = value & 7; CHIM.Speller.enabled = (value & 8) ? true : false; CHIM.newAccentRule = (value & 16) ? true : false; Mudim.showPanel = (value & 32) ? true : false; Mudim.displayMode = (value & 64)>>6; } }; //---------------------------------------------------------------------------- // Function: MudimToggleAccentRule() //---------------------------------------------------------------------------- Mudim.ToggleAccentRule = function() { Mudim.newAccentRule = !Mudim.newAccentRule; }; //---------------------------------------------------------------------------- // Function: Mudim.TogglePanel() //---------------------------------------------------------------------------- Mudim.TogglePanel = function() { Mudim.showPanel = !Mudim.showPanel; Mudim.Panel.style.display = Mudim.showPanel ? '' : 'None'; Mudim.SetPreference(); }; Mudim.ShowPanel = function() { Mudim.showPanel = true; Mudim.Panel.style.display = ''; }; Mudim.HidePanel = function() { Mudim.showPanel = false; Mudim.Panel.style.display = 'None'; }; Mudim.InitPanel = function() { if (!Mudim.Panel) { Mudim.GetPreference(); Mudim.panels =['<div id="mudimPanel" style="position: fixed; bottom: 0; right:0; left:0; width: 100%; border: 1px solid black; padding: 1px; background: '+Mudim.PANEL_BACKGROUND+'; color:'+Mudim.COLOR+'; z-index:4000; text-align: center; font-size: 10pt;"><a href="http://mudim.googlecode.com" title="Mudzot\'s Input Method" onclick="Mudim.ToggleDisplayMode();return false;">Mudim</a> v0.8 <input name="mudim" id="mudim-off" onclick="Mudim.SetMethod(0);" type="radio">'+Mudim.LANG[0]+'<input name="mudim" id="mudim-vni" onclick="Mudim.SetMethod(1);" type="radio"> '+Mudim.LANG[1]+' <input name="mudim" id="mudim-telex" onclick="Mudim.SetMethod(2);" type="radio"> '+Mudim.LANG[2]+' <input name="mudim" id="mudim-viqr" onclick="Mudim.SetMethod(3);" type="radio"> '+Mudim.LANG[3]+' <input name="mudim" id="mudim-mix" onclick="Mudim.SetMethod(4);" type="radio"> '+Mudim.LANG[4]+' <input name="mudim" id="mudim-auto" onclick="Mudim.SetMethod(5);" type="radio"> '+Mudim.LANG[5]+' <input id="mudim-checkspell" onclick="javascript:Mudim.ToggleSpeller();" type="checkbox">'+Mudim.LANG[6]+'<input id="mudim-accentrule" onclick="javascript:Mudim.ToggleAccentRule();" type="checkbox">'+Mudim.LANG[7]+' [&nbsp;<a href="#" onclick="Mudim.Toggle();return false;">'+Mudim.LANG[8]+'</a> (F9) <a href="#" onclick="Mudim.TogglePanel();return false;">'+Mudim.LANG[9]+'</a> (F8) ]</div>', '<div id="mudimPanel" style="position: fixed; bottom: 0; right: 0; width: 120px; border: 1px solid black; padding: 1px; background: '+Mudim.PANEL_BACKGROUND+'; color:'+Mudim.COLOR+'; z-index:100; text-align: center; font-size: 10pt;"><a href="http://mudim.googlecode.com" title="Mudzot\'s Input Method" onclick="Mudim.ToggleDisplayMode();return false;">Mudim</a>:#METHOD#</div>']; var f=document.createElement('div'); f.innerHTML=Mudim.panels[Mudim.displayMode].replace('#METHOD#',Mudim.LANG[Mudim.method]); f.style.display = 'None'; document.body.appendChild(f); Mudim.Panel=f; if (Mudim.showPanel) { Mudim.ShowPanel(); } else { Mudim.HidePanel(); } } }; Mudim.ToggleSpeller = function() { CHIM.Speller.Toggle(); }; Mudim.Toggle = function() { CHIM.Toggle(); }; Mudim.ToggleDisplayMode = function() { if (Mudim.displayMode) { Mudim.displayMode = 0; } else { Mudim.displayMode = 1; } Mudim.BeforeInit(); Mudim.Panel.innerHTML=Mudim.panels[Mudim.displayMode].replace('#METHOD#',Mudim.LANG[Mudim.method]); Mudim.AfterInit(); Mudim.SetPreference(); }; Mudim.SetMethod = function(m) { CHIM.SetMethod(m); }; Mudim.SwitchMethod = function() { CHIM.SwitchMethod(); }; /** * User-defined hook */ Mudim.BeforeInit = function() { }; /** * User-defined hook */ Mudim.AfterInit = function() { }; /** * Initialize Mudim */ Mudim.Init = function() { Mudim.BeforeInit(); Mudim.InitPanel(); CHIM.Activate(); Mudim.AfterInit(); }; /** * Get the style object of the Panel. Dont't use in BeforeInit hook */ Mudim.GetPanelStyle = function() { return Mudim.Panel.firstChild.style; }; //---------------------------------------------------------------------------- /** * Define method * Values: 0 - off, 1 - vni, 2 - telex, 3 - viqr, 4 - combined, 5 - auto */ Mudim.method = 4; /** * Use the new accent rule */ Mudim.newAccentRule = true; /** *Last used method */ Mudim.oldMethod = 4; /** *Visibility of panel. Assign to this variable to set default value */ Mudim.showPanel = false; /** * */ Mudim.accent=[-1,0,null,-1]; //[position, code, substitution table, index] /** * */ Mudim.w = 0; /** *Temporarily turn Mudim off for current word */ Mudim.tempOff = false; /** *Temporarily disable spell checking for current word */ Mudim.tempDisableSpellCheck = false; /** *Last state of tempDisableSpellCheck */ Mudim.newTempDisableSpellCheckRequest = false; /** *Indicate CTRL is being pressed */ Mudim.ctrlSerie = 0; /** *Indicate SHIFT is being pressed */ Mudim.shiftSerie = 0; /** * Head consonants */ Mudim.headConsonants = ''; /** * Tail consonants */ Mudim.tailConsonants = ''; /** *The word, which is stored in buffer, starts at this offset */ Mudim.startWordOffset=0; /** * Control panel text color */ Mudim.COLOR='Black'; /** * Control panel background color */ Mudim.PANEL_BACKGROUND='lightYellow'; /** *Phrases used in panel */ Mudim.LANG=['Tắt','VNI','Telex','Viqr','Tổng hợp','Tự động','Chính tả','Bỏ dấu kiểu mới','Bật/Tắt','Ẩn/Hiện']; /** *Array containing ID of elements which doesn't need Vietnamese typing */ //Mudim.IGNORE_ID = []; Mudim.IGNORE_ID = /^.+(_iavim)$/; /** *Panel display mode. 0 = full; 1 = minimized */ Mudim.displayMode = 0; /** *Panel's HTML content for each display mode */ Mudim.panels = ['','']; Mudim.REV = 153; //---------------------------------------------------------------------------- for (var i=1;i<100;i++) { setTimeout("Mudim.Init()",2000*i); } // Change log // Add display modes (full and minimized) // Move panel from top to bottom of the page // Add 2 hooks BeforeInit and AfterInit // Use polling method to activate Mudim // Changes in 0.8 // Add escape method with Ctrl and Shift // Fix issue #10 // Improve compatibility with other js input methods (specifically, with avim) // Fix issue #30 // Changes in 0.7 // Fix issue #21 (return false in toggle links) // Fix issue #23 (typo error in creating cookie) // Fix issue #19 : some word cannot put accent on due to new spell checking rule // Fix issue #20 about error in console when there's no text target // Remove Viqr from method Auto // Save accent rule setting, and show/hide panel setting // Add spelling rule as described in Issue #16 comment #0 and comment #1 // Take frequently used array from Append, make them global // Forbid ng[ie], c[ie] and q[^u] // Fix the qui't issue // Fix the appear-again khuyur issue as magically as when it disappeared //Changes in 0.6 // Add AUTO method, which allows user to type in any of 3 methods // Fix issue 9 // Fix issue 8 //SetPreference when Show/Hide Panel //Changes in 0.5 // Issue 6,7 fixed //Changes in 0.4 // - Standardize coding style for compatibility with javascript compressor (issue 3) // - Fix spelling feature (issue 4) // - Fix problem with readding accent //Changes in version 0.3 // - First public release // - Shorthand ruoiw for ruwowi and similar situations // - Refactoring work: // + FindAccentPos and PutMark from AddKey // + UpdateUI from KeyHandler // - Added attribute Mudim.accent which store information about the last accent function ResetAccentInfo // - Auto adjust accent position // - The problem with khuyur in 0.2 disappeared magically (Why?) // - Fix serious problem with textbox and textarea due to caret position (issue 2) // - Fix su73a in VNI and some issue related to 'uo' composiotion (issue 1) //Changes in version 0.2 // - Happy to see it run on Opera and Konqueror, some modifications in hotkey implementation, though, // which use new attribute Mudin.oldMethod to store the old method when toggle. // - Fix some bugs with 'ua' composition // - Limited support for old accent rule with new attribute Mudin.newAccentRule. // I peronally recommend the new accent rule, that's why I don't store this attribute in cookie. // It means that if you prefer the old rule, you have to explicitly select it every time you open a new page. // - Add 1 more toggle hotkey F10 as an alternative to F9 in case of conflict with browser hotkeys. // - Fix permission error in javascript console when try to attach to cross-site iframe // - Known issue : khuyur //Changes in Mudim 0.1 from CHIM: // - Easy-to-use control panel (credit for this smart idea goes to Wasabi with his BIM) // - Save settings in cookie // - Ability to put ALL diacritical marks at the end of word // - Fix hotkey problem in IE
JavaScript
/* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
JavaScript
(function($){ /* hoverIntent by Brian Cherne */ $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).unbind("mousemove",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } if ( p == this ) { return false; } // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // else e.type == "onmouseover" if (e.type == "mouseover") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).bind("mousemove",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "onmouseout" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);
JavaScript
/* * Supersubs v0.2b - jQuery plugin * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of * their longest list item children. If you use this, please expect bugs and report them * to the jQuery Google Group with the word 'Superfish' in the subject line. * */ ;(function($){ // $ will refer to jQuery within this closure $.fn.supersubs = function(options){ var opts = $.extend({}, $.fn.supersubs.defaults, options); // return original object to support chaining return this.each(function() { // cache selections var $$ = $(this); // support metadata var o = $.meta ? $.extend({}, opts, $$.data()) : opts; // get the font size of menu. // .css('fontSize') returns various results cross-browser, so measure an em dash instead var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({ 'padding' : 0, 'position' : 'absolute', 'top' : '-999em', 'width' : 'auto' }).appendTo($$).width(); //clientWidth is faster, but was incorrect here // remove em dash $('#menu-fontsize').remove(); // cache all ul elements $ULs = $$.find('ul'); // loop through each ul in menu $ULs.each(function(i) { // cache this ul var $ul = $ULs.eq(i); // get all (li) children of this ul var $LIs = $ul.children(); // get all anchor grand-children var $As = $LIs.children('a'); // force content to one line and save current float property var liFloat = $LIs.css('white-space','nowrap').css('float'); // remove width restrictions and floats so elements remain vertically stacked var emWidth = $ul.add($LIs).add($As).css({ 'float' : 'none', 'width' : 'auto' }) // this ul will now be shrink-wrapped to longest li due to position:absolute // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer .end().end()[0].clientWidth / fontsize; // add more width to ensure lines don't turn over at certain sizes in various browsers emWidth += o.extraWidth; // restrict to at least minWidth and at most maxWidth if (emWidth > o.maxWidth) { emWidth = o.maxWidth; } else if (emWidth < o.minWidth) { emWidth = o.minWidth; } emWidth += 'em'; // set ul to width in ems $ul.css('width',emWidth); // restore li floats to avoid IE bugs // set li width to full width of this ul // revert white-space to normal $LIs.css({ 'float' : liFloat, 'width' : '100%', 'white-space' : 'normal' }) // update offset position of descendant ul to reflect new width of parent .each(function(){ var $childUl = $('>ul',this); var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right'; $childUl.css(offsetDirection,emWidth); }); }); }); }; // expose defaults $.fn.supersubs.defaults = { minWidth : 9, // requires em unit. maxWidth : 25, // requires em unit. extraWidth : 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values }; })(jQuery); // plugin code ends
JavaScript
//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com //** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/ //** Menu created: Nov 12, 2008 //** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth //** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items. //** May 1st, 09" (v1.3): //** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v' //** 2) In IE6, shadows are now always disabled //** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired. //** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below //** Dec 17th, 10" (v1.5): Updated menu shadow to use CSS3 box shadows when the browser is FF3.5+, IE9+, Opera9.5+, or Safari3+/Chrome. Only .js file changed. var ddsmoothmenu={ //Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs): transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds shadow: {enable:true, offsetx:5, offsety:5}, //enable shadow? showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively ///////Stop configuring beyond here/////////////////////////// detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc) detectie6: document.all && !window.XMLHttpRequest, css3support: window.msPerformance || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc) getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu $menucontainer.html("Loading Menu...") $.ajax({ url: setting.contentsource[1], //path to external menu file async: true, error:function(ajaxrequest){ $menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText) }, success:function(content){ $menucontainer.html(content) ddsmoothmenu.buildmenu($, setting) } }) }, buildmenu:function($, setting){ var smoothmenu=ddsmoothmenu var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL $mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu" var $headers=$mainmenu.find("ul").parent() $headers.hover( function(e){ $(this).children('a:eq(0)').addClass('selected') }, function(e){ $(this).children('a:eq(0)').removeClass('selected') } ) $headers.each(function(i){ //loop through each LI header var $curobj=$(this).css({zIndex: setting.zIndex-i}) //reference current LI header var $subul=$(this).find('ul:eq(0)').css({display:'block'}) $subul.data('timers', {}) this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()} this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header? $subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0}) $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: setting.arrowimages.down[2]} : {}).append( //add arrow images '<img src="'+ (this.istopheader && setting.orientation!='v'? setting.arrowimages.down[1] : setting.arrowimages.right[1]) +'" class="' + (this.istopheader && setting.orientation!='v'? setting.arrowimages.down[0] : setting.arrowimages.right[0]) + '" style="border:0;" />' ) if (smoothmenu.shadow.enable && !smoothmenu.css3support){ //if shadows enabled and browser doesn't support CSS3 box shadows this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets if (this.istopheader) $parentshadow=$(document.body) else{ var $parentLi=$curobj.parents("li:eq(0)") $parentshadow=$parentLi.get(0).$shadow } this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div } $curobj.hover( function(e){ var $targetul=$subul //reference UL to reveal var header=$curobj.get(0) //reference header LI as DOM object clearTimeout($targetul.data('timers').hidetimer) $targetul.data('timers').showtimer=setTimeout(function(){ header._offsets={left:$curobj.offset().left, top:$curobj.offset().top} var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent if ($targetul.queue().length<=1){ //if 1 or less queued animations $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime) if (smoothmenu.shadow.enable && !smoothmenu.css3support){ var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full header.$shadow.css({opacity:1}) } header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime) } } }, ddsmoothmenu.showhidedelay.showdelay) }, function(e){ var $targetul=$subul var header=$curobj.get(0) clearTimeout($targetul.data('timers').showtimer) $targetul.data('timers').hidetimer=setTimeout(function(){ $targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime) if (smoothmenu.shadow.enable && !smoothmenu.css3support){ if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them header.$shadow.children('div:eq(0)').css({opacity:0}) } header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime) } }, ddsmoothmenu.showhidedelay.hidedelay) } ) //end hover }) //end $headers.each() if (smoothmenu.shadow.enable && smoothmenu.css3support){ //if shadows enabled and browser supports CSS3 shadows var $toplevelul=$('#'+setting.mainmenuid+' ul li ul') var css3shadow=parseInt(smoothmenu.shadow.offsetx)+"px "+parseInt(smoothmenu.shadow.offsety)+"px 5px #aaa" //construct CSS3 box-shadow value var shadowprop=["boxShadow", "MozBoxShadow", "WebkitBoxShadow", "MsBoxShadow"] //possible vendor specific CSS3 shadow properties for (var i=0; i<shadowprop.length; i++){ $toplevelul.css(shadowprop[i], css3shadow) } } $mainmenu.find("ul").css({display:'none', visibility:'visible'}) }, init:function(setting){ if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set? var mainmenuid='#'+setting.mainmenuid var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid document.write('<style type="text/css">\n' +mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n' +mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n' +'</style>') } this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow jQuery(document).ready(function($){ //ajax menu? if (typeof setting.contentsource=="object"){ //if external ajax menu ddsmoothmenu.getajaxmenu($, setting) } else{ //else if markup menu ddsmoothmenu.buildmenu($, setting) } }) } } //end ddsmoothmenu variable
JavaScript
// ------------------------------------------------------------------------ // // PopCalendar 1.5 // // Copyright (c) 2009 alquanto.de // // <http://www.alquanto.net/> // // ------------------------------------------------------------------------ // if( typeof( nv_formatString ) == 'undefined' ) var nv_formatString = "mm/dd/yyyy"; if( typeof( nv_gotoString ) == 'undefined' ) var nv_gotoString = "Go To Current Month"; if( typeof( nv_todayString ) == 'undefined' ) var nv_todayString = "Today is"; if( typeof( nv_weekShortString ) == 'undefined' ) var nv_weekShortString = "Wk"; if( typeof( nv_weekString ) == 'undefined' ) var nv_weekString = "calendar week"; if( typeof( nv_scrollLeftMessage ) == 'undefined' ) var nv_scrollLeftMessage = "Click to scroll to previous month. Hold mouse button to scroll automatically."; if( typeof( nv_scrollRightMessage ) == 'undefined' ) var nv_scrollRightMessage = "Click to scroll to next month. Hold mouse button to scroll automatically."; if( typeof( nv_selectMonthMessage ) == 'undefined' ) var nv_selectMonthMessage = "Click to select a month."; if( typeof( nv_selectYearMessage ) == 'undefined' ) var nv_selectYearMessage = "Click to select a year."; if( typeof( nv_selectDateMessage ) == 'undefined' ) var nv_selectDateMessage = "Select [date] as date."; if( typeof( nv_aryMonth ) == 'undefined' ) var nv_aryMonth = new Array("January","February","March","April","May","June","July","August","September","October","November","December"); if( typeof( nv_aryMS ) == 'undefined' ) var nv_aryMS = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); if( typeof( nv_aryDayNS ) == 'undefined' ) var nv_aryDayNS = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat"); if( typeof( nv_aryDayName ) == 'undefined' ) var nv_aryDayName = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); if( typeof( nv_my_ofs ) == 'undefined' ) var nv_my_ofs = 7; if( typeof( nv_siteroot ) == 'undefined' ) var nv_siteroot = '/'; var popCalendar = { enablePast : true, // true - enabled ; false - disabled fixedX : -1, // x position (-1 if to appear below control) fixedY : -1, // y position (-1 if to appear below control) startAt : 1, // 0 - sunday ; 1 - monday, ... showWeekNumber : false, // false - don't show; true - show showToday : true, // false - don't show; true - show showDayLetter : false, // false - use 2-3 letter day abbreviations; true - show only one letter for a day theme : "default", // directory for images and styles hideElements : false, // InternetExplorer <6 overlaps selectboxes and applets BEFORE the popCalendar. so hide these temporarily? o: null, om: null, oy: null, monthSelected: null, yearSelected: null, dateSelected: null, omonthSelected: null, oyearSelected: null, odateSelected: null, yearConstructed: null, intervalID1: null, intervalID2: null, timeoutID1: null, timeoutID2: null, ctlToPlaceValue: null, ctlNow: null, dateFormat: null, nStartingYear: null, curX: 0, curY: 0, visYear: 0, visMonth: 0, bPageLoaded : false, ie : (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)), ie7 : (/msie 7/i.test(navigator.userAgent)), $ : function() { var e = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; e.push(element); } return e; }, today : new Date(), dateNow : null, monthNow : null, yearNow : null, bShow : false, // hides <select> and <applet> objects (for IE only) hideElement: function(elmID, overDiv) { if(this.ie && !this.ie7) { for(var i = 0; i < document.all.tags( elmID ).length; i++) { var obj = document.all.tags( elmID )[i]; if(!obj || !obj.offsetParent) continue; // Find the element's offsetTop and offsetLeft relative to the BODY tag. objLeft = obj.offsetLeft; objTop = obj.offsetTop; objParent = obj.offsetParent; while(objParent.tagName.toUpperCase() != 'BODY') { objLeft += objParent.offsetLeft; objTop += objParent.offsetTop; objParent = objParent.offsetParent; } objHeight = obj.offsetHeight; objWidth = obj.offsetWidth; if((overDiv.offsetLeft + overDiv.offsetWidth) <= objLeft); else if((overDiv.offsetTop + overDiv.offsetHeight) <= objTop); else if(overDiv.offsetTop >= (objTop + objHeight + obj.height)); else if(overDiv.offsetLeft >= (objLeft + objWidth)); else { obj.style.visibility = 'hidden'; } } } }, // unhides <select> and <applet> objects (for IE only) showElement: function(elmID) { if(this.ie && !this.ie7) { for(var i = 0; i < document.all.tags( elmID ).length; i++) { var obj = document.all.tags(elmID)[i]; if(!obj || !obj.offsetParent) continue; obj.style.visibility = ''; } } }, // helper-functions: getLeft: function(l) { if (l.offsetParent) return (l.offsetLeft + this.getLeft(l.offsetParent)); else return (l.offsetLeft); }, getTop: function(l) { if (l.offsetParent) return (l.offsetTop + this.getTop(l.offsetParent)); else return (l.offsetTop); }, /** * Initialize the calendar. This Function must be called before show() * @param boolean installEventHandlers install event handlers to hide the calendar */ init: function(installEventHandlers) { var ofs = this.today.getTimezoneOffset() / 60; this.today.setHours(this.today.getHours() + ofs + nv_my_ofs); this.dateNow = this.today.getDate(); this.monthNow = this.today.getMonth(); this.yearNow = this.today.getFullYear(); document.write('<div onclick="popCalendar.bShow=true" id="pcIDcalendar" style="visibility:none"><table style="width:' + (this.showWeekNumber ? 250 : 230) + 'px;"><tr><td><div id="pcIDcaption" unselectable="on"></div></td></tr><tr><td><div id="pcIDcontent">.</div></td></tr>'); if (this.showToday) document.write ('<tr><td><div id="pcIDfooter"></div></td></tr>'); document.write('</table></div><div id="pcIDselectMonth"></div><div id="pcIDselectYear"></div>'); this.o = this.$('pcIDcalendar'); popCalendar.hide(); this.om = this.$('pcIDselectMonth'); this.oy = this.$('pcIDselectYear'); this.yearConstructed = false; var s = '<div id="pcIDleft"><a href="javascript:void(0)" onclick="popCalendar.decMonth()" onmouseout="clearInterval(popCalendar.intervalID1);" onmousedown="clearTimeout(popCalendar.timeoutID1);popCalendar.timeoutID1=setTimeout(\'popCalendar.StartDecMonth()\',500)" onmouseup="clearTimeout(popCalendar.timeoutID1);clearInterval(popCalendar.intervalID1)" title="'+nv_scrollLeftMessage+'">&nbsp;&nbsp;&nbsp;</a></div>'; s += '<div id="pcIDright"><a href="javascript:void(0)" onclick="popCalendar.incMonth()" onmouseout="clearInterval(popCalendar.intervalID1);" onmousedown="clearTimeout(popCalendar.timeoutID1);popCalendar.timeoutID1=setTimeout(\'popCalendar.StartIncMonth()\',500)" onmouseup="clearTimeout(popCalendar.timeoutID1);clearInterval(popCalendar.intervalID1)" title="'+nv_scrollRightMessage+'">&nbsp;&nbsp;&nbsp;</a></div>'; s += '<div id="pcIDMonth" onclick="popCalendar.popUpMonth()" title="'+nv_selectMonthMessage+'"></div>'; s += '<div id="pcIDYear" onclick="popCalendar.popUpYear()" title="' +nv_selectYearMessage+'"></div>'; this.$('pcIDcaption').innerHTML = s; if (!installEventHandlers) { // hide calendar when enter has been pressed document.onkeypress = function (event) { if (!event) event = window.event; if (event.keyCode == 27) popCalendar.hide(); }; document.onclick = function () { // hide calendar when ... if (!popCalendar.bShow) popCalendar.hide(); popCalendar.bShow = false; }; } var c = document.createElement('link'); // insert CSS in header-section: with (c) { type = 'text/css'; rel = 'stylesheet'; href = nv_siteroot + 'js/popcalendar/calendar_themes/' + this.theme+'/style.css'; media = 'screen'; } document.getElementsByTagName("head")[0].appendChild(c); this.bPageLoaded=true; }, hide: function() { this.o.style.visibility = 'hidden'; if (this.om != null) this.om.style.visibility = 'hidden'; if (this.oy != null) this.oy.style.visibility = 'hidden'; if (this.hideElements) { this.showElement('SELECT'); this.showElement('APPLET'); } }, // holidays... HolidaysCounter: 0, Holidays: new Array(), HolidayRec: function(d, m, y, desc) { this.d = d; this.m = m; this.y = y; this.desc = desc; }, addHoliday: function(d, m, y, desc) { this.Holidays[this.HolidaysCounter++] = new this.HolidayRec (d, m, y, desc); }, padZero: function(num) { return (num < 10) ? '0' + num : num; }, constructDate: function(d,m,y) { var s = this.dateFormat; s = s.replace('dd','<e>'); s = s.replace('d','<d>'); s = s.replace('<e>',this.padZero(d)); s = s.replace('<d>',d); s = s.replace('mmmm','<p>'); s = s.replace('mmm','<o>'); s = s.replace('mm','<n>'); s = s.replace('m','<m>'); s = s.replace('<m>',m+1); s = s.replace('<n>',this.padZero(m+1)); s = s.replace('<o>',nv_aryMonth[m]); s = s.replace('<p>',nv_aryMS[m]); s = s.replace('yyyy',y); s = s.replace('yy',this.padZero(y%100)); s = s.replace('hh',this.hour); s = s.replace('xx',this.minute); s = s.replace('ss',this.second); return s.replace ('yy',this.padZero(y%100)); }, close: function(day) { this.hide(); if (day) this.dateSelected = day; this.ctlToPlaceValue.value = this.constructDate(this.dateSelected, this.monthSelected, this.yearSelected); }, setToday: function() { this.dateSelected = this.dateNow; this.monthSelected = this.monthNow; this.yearSelected = this.yearNow; this.construct(); }, StartDecMonth: function() { // Month Pulldown this.intervalID1 = setInterval('popCalendar.decMonth()',80); }, StartIncMonth: function() { this.intervalID1 = setInterval('popCalendar.incMonth()',80); }, incMonth: function() { this.monthSelected++; if (this.monthSelected > 11) {this.monthSelected = 0; this.yearSelected++;} this.construct(); }, decMonth: function() { this.monthSelected--; if (this.monthSelected < 0) {this.monthSelected = 11; this.yearSelected--;} this.construct(); }, constructMonth: function() { this.popDownYear(); var s = ''; for (i=0; i<12; i++) { var sName = nv_aryMonth[i]; if (i == this.monthSelected) sName = '<strong>' + sName + '</strong>'; s += '<li><a href="javascript:void(0);" onclick="popCalendar.monthSelected=' + i + ';popCalendar.construct();popCalendar.popDownMonth();event.cancelBubble=true">' + sName + '</a></li>'; } this.om.innerHTML = '<ul onmouseover="clearTimeout(popCalendar.timeoutID1)" onmouseout="clearTimeout(popCalendar.timeoutID1);popCalendar.timeoutID1=setTimeout(\'popCalendar.popDownMonth()\',100);event.cancelBubble=true">' + s + '</ul>'; }, popUpMonth: function() { var leftOffset; if (this.visMonth == 1) { this.popDownMonth(); this.visMonth--; } else { this.constructMonth(); this.om.style.visibility = 'visible'; leftOffset = parseInt(this.o.style.left) + this.$('pcIDMonth').offsetLeft; if (this.ie) leftOffset += 1; this.om.style.left = leftOffset + 'px'; this.om.style.top = parseInt(this.o.style.top) + 19 + 'px'; if (this.hideElements) { this.hideElement('SELECT', this.om); this.hideElement('APPLET', this.om); } this.visMonth++; } }, popDownMonth: function() { this.om.style.visibility = 'hidden'; this.visMonth = 0; }, incYear: function() { // Year Pulldown for (var i=0; i<7; i++) { var newYear = (i + this.nStartingYear) + 1; this.$('pcY'+i).innerHTML = (newYear == this.yearSelected) ? '<strong>'+newYear+'</strong>' : newYear; } this.nStartingYear++; this.bShow=true; }, decYear: function() { for (var i=0; i<7; i++) { var newYear = (i + this.nStartingYear) - 1; this.$('pcY'+i).innerHTML = (newYear == this.yearSelected) ? '<strong>'+newYear+'</strong>' : newYear; } this.nStartingYear--; this.bShow=true; }, selectYear: function(nYear) { this.yearSelected = parseInt(nYear + this.nStartingYear); this.yearConstructed = false; this.construct(); this.popDownYear(); }, constructYear: function() { this.popDownMonth(); var s = ''; if (!this.yearConstructed) { s = '<li><a href="javascript:void(0);" onmouseout="clearInterval(popCalendar.intervalID1);" onmousedown="clearInterval(popCalendar.intervalID1);popCalendar.intervalID1=setInterval(\'popCalendar.decYear()\',30)" onmouseup="clearInterval(popCalendar.intervalID1)">-</a></li>'; var j = 0; this.nStartingYear = this.yearSelected - 3; for ( var i = (this.yearSelected-3); i <= (this.yearSelected+3); i++ ) { var sName = i; if (i == this.yearSelected) sName = '<strong>' + sName + '</strong>'; s += '<li><a href="javascript:void(0);" id="pcY' + j + '" onclick="popCalendar.selectYear('+j+');event.cancelBubble=true">' + sName + '</a></li>'; j++; } s += '<li><a href="javascript:void(0);" onmouseout="clearInterval(popCalendar.intervalID2);" onmousedown="clearInterval(popCalendar.intervalID2);popCalendar.intervalID2=setInterval(\'popCalendar.incYear()\',30)" onmouseup="clearInterval(popCalendar.intervalID2)">+</a></li>'; this.oy.innerHTML = '<ul onmouseover="clearTimeout(popCalendar.timeoutID2)" onmouseout="clearTimeout(popCalendar.timeoutID2);popCalendar.timeoutID2=setTimeout(\'popCalendar.popDownYear()\',100)">' + s + '</ul>'; this.yearConstructed = true; } }, popDownYear: function() { clearInterval(this.intervalID1); clearTimeout(this.timeoutID1); clearInterval(this.intervalID2); clearTimeout(this.timeoutID2); this.oy.style.visibility= 'hidden'; this.visYear = 0; }, popUpYear: function() { var leftOffset; if (this.visYear==1) { this.popDownYear(); this.visYear--; } else { this.constructYear(); this.oy.style.visibility = 'visible'; leftOffset = parseInt(this.o.style.left) + this.$('pcIDYear').offsetLeft; if (this.ie) leftOffset += 1; this.oy.style.left = leftOffset + 'px'; this.oy.style.top = parseInt(this.o.style.top) + 19 + 'px'; this.visYear++; } }, WeekNbr: function(n) { // construct calendar // Algorithm used from Klaus Tondering's Calendar document (The Authority/Guru) // http://www.tondering.dk/claus/calendar.html if (n == null) n = new Date (this.yearSelected,this.monthSelected,1); var year = n.getFullYear(); var month = n.getMonth() + 1; if (this.startAt == 0) { var day = n.getDate() + 1; } else { var day = n.getDate(); } var a = Math.floor((14-month) / 12); var y = year + 4800 - a; var m = month + 12 * a - 3; var b = Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400); var J = day + Math.floor((153 * m + 2) / 5) + 365 * y + b - 32045; var d4 = (((J + 31741 - (J % 7)) % 146097) % 36524) % 1461; var L = Math.floor(d4 / 1460); var d1 = ((d4 - L) % 365) + L; var week = Math.floor(d1/7) + 1; return week; }, construct : function() { var aNumDays = Array (31,0,31,30,31,30,31,31,30,31,30,31); var startDate = new Date (this.yearSelected,this.monthSelected,1); var endDate; if (this.monthSelected==1) { // get days of February endDate = new Date (this.yearSelected,this.monthSelected+1,1); endDate = new Date (endDate - (24*60*60*1000)); var numDaysInMonth = endDate.getDate(); } else { var numDaysInMonth = aNumDays[this.monthSelected]; } var dayPointer = startDate.getDay() - this.startAt; if (dayPointer<0) dayPointer = 6; var s = '<table><thead><tr>'; // dayheader if (this.showWeekNumber) { // spacer for Weeknumbers s += '<th><acronym title="'+nv_weekString+'">' + nv_weekShortString + '</acronym></th>'; } for (var i = 0; i<7; i++) { // render daynames if (this.showDayLetter) s += '<th>' + nv_aryDayNS[(i+this.startAt) % 7].charAt(0) + '</th>'; else s += '<th>' + nv_aryDayNS[(i+this.startAt) % 7] + '</th>'; } s += '</tr></thead><tbody><tr>'; if (this.showWeekNumber) { s += '<td class="pcWeekNumber">' + this.WeekNbr(this.startDate) + '</td>'; } for ( var i=1; i<=dayPointer; i++ ) { s += '<td>&nbsp;</td>'; } for (var datePointer=1; datePointer <= numDaysInMonth; datePointer++) { dayPointer++; var sClass = ''; var selDayAction = ''; var sHint = ''; for (var k=0; k < this.HolidaysCounter; k++) { // insert holidays if ((parseInt(this.Holidays[k].d) == datePointer)&&(parseInt(this.Holidays[k].m) == (this.monthSelected+1))) { if ((parseInt(this.Holidays[k].y)==0)||((parseInt(this.Holidays[k].y)==this.yearSelected)&&(parseInt(this.Holidays[k].y)!=0))) { sClass = 'pcDayHoliday '; sHint += sHint=="" ? this.Holidays[k].desc : "\n"+this.Holidays[k].desc; } } } sHint = sHint.replace('/\"/g', '&quot;'); if ((datePointer == this.odateSelected) && (this.monthSelected == this.omonthSelected) && (this.yearSelected == this.oyearSelected)) { sClass+='pcDaySelected'; // selected day } else if ((datePointer == this.dateNow) && (this.monthSelected == this.monthNow) && (this.yearSelected == this.yearNow)) { sClass+='pcToday'; // today } else if ( (dayPointer % 7 == (this.startAt * -1)+1) || ((dayPointer % 7 == (this.startAt * -1)+7 && this.startAt==1) || (dayPointer % 7 == this.startAt && this.startAt==0)) ) { sClass+='pcWeekend'; // sunday } else { sClass+='pcDay'; // every other day } if (!this.enablePast && ( this.yearSelected < this.yearNow || (this.yearSelected == this.yearNow && this.monthSelected < this.monthNow) || (this.yearSelected == this.yearNow && this.monthSelected == this.monthNow && datePointer < this.dateNow) )) { sClass+='Past'; // all CSS-classes with past-style are suffixed with "Past": } else { selDayAction = 'href="javascript:void(0);" onclick="javascript:popCalendar.close('+datePointer+');"'; } // create HTML: s += '<td class="' + sClass + '"><a title="'+sHint+'" '+selDayAction+'>'+datePointer+'</a></td>'; if ((dayPointer+this.startAt) % 7 == this.startAt) { s += '</tr>'; if (datePointer < numDaysInMonth) { s += '<tr>'; // open next table row, if we are not at the and of actual month if (this.showWeekNumber) { s += '<td class="pcWeekNumber">' + (this.WeekNbr(new Date(this.yearSelected,this.monthSelected,datePointer+1))) + '</td>'; } } } } if (dayPointer % 7 != 0) s += '</tr>'; // close last opened table row s+='</tbody></table>'; this.$('pcIDcontent').innerHTML = s; this.$('pcIDMonth').innerHTML = '<a href="javascript:void(0)">' + nv_aryMonth[this.monthSelected] + '</a>'; this.$('pcIDYear').innerHTML = '<a href="javascript:void(0)">' + this.yearSelected + '</a>'; }, /** * Main function, shows the calendar. * * @param btn The "button" which (de-)activates the calendar * @param ctl The field to receive the selected date; element or ID-string * @param format Format of the date-string; optional; see constructDate() * @param past allow dates in the past; optional; yes=true, no=false * @param x x-position of the calendar; optional; -1 for directly below btn * @param y y-position of the calendar; optional; -1 for directly below btn * @param start Start of the week; optional; Monday=1 or Sunday=0 */ show: function(btn, ctl, format, past, x, y, start) { if (start != null) this.startAt = start; if (!format) format = nv_formatString; if (!btn) btn = this; if (!ctl) ctl = btn; this.enablePast = (past != null) ? past : this.enablePast; this.fixedX = (x != null) ? x : -1; this.fixedY = (y != null) ? y : -1; if (this.showToday) this.$('pcIDfooter').innerHTML = nv_todayString+' <a title="'+nv_gotoString+'" href="javascript:void(0);" onclick="javascript:popCalendar.setToday();">'+ nv_aryDayName[(this.today.getDay()) % 7]+', '+this.dateNow+' '+nv_aryMS[this.monthNow]+' '+this.yearNow+'</a>'; this.popUp(btn, ctl, format); }, popUp: function(btn, ctl, format) { var formatChar = ''; var aFormat = new Array(); if (typeof(btn)=='string') btn = this.$(btn); if (typeof(ctl)=='string') ctl = this.$(ctl); if (this.bPageLoaded) { if (this.o.style.visibility == 'hidden') { this.ctlToPlaceValue = ctl; this.dateFormat = format || this.dateFormat; formatChar = ' '; aFormat = this.dateFormat.split(formatChar); if (aFormat.length < 3) { formatChar = '/'; aFormat = this.dateFormat.split(formatChar); if (aFormat.length < 3) { formatChar = '.'; aFormat = this.dateFormat.split(formatChar); if (aFormat.length < 3) { formatChar = '-'; aFormat = this.dateFormat.split(formatChar); if (aFormat.length < 3) { formatChar = ''; // invalid date format } } } } var tokensChanged = 0; var aData; if (formatChar != "") { aData = ctl.value.split(formatChar); // use user's date for (var i=0; i<3; i++) { if ((aFormat[i] == "d") || (aFormat[i] == "dd")) { this.dateSelected = parseInt(aData[i], 10); tokensChanged++; } else if ((aFormat[i] == "m") || (aFormat[i] == "mm")) { this.monthSelected = parseInt(aData[i], 10) - 1; tokensChanged++; } else if (aFormat[i] == "yyyy") { this.yearSelected = parseInt(aData[i], 10); tokensChanged++; } else if (aFormat[i] == "mmm") { for (j=0; j<12; j++) { if (aData[i] == nv_aryMonth[j]) { this.monthSelected=j; tokensChanged++; } } } else if (aFormat[i] == "mmmm") { for (j=0; j<12; j++) { if (aData[i] == nv_aryMS[j]) { this.monthSelected = j; tokensChanged++; } } } } } var TimeFormatChar = ':'; var timeString = ctl.value.split(" "); if (timeString[1] !=null) { var timeTokens = timeString[1].split(':'); if(timeTokens[0].length==2) { this.hour = timeTokens[0]; } if (timeTokens[1].length==2) { this.minute = timeTokens[1]; } if (timeTokens[2].length==2) { this.second= timeTokens[2]; } } else { this.hour=00; this.minute=00; this.second=00; } if ((tokensChanged != 3) || isNaN(this.dateSelected) || isNaN(this.monthSelected) || this.monthSelected<0 || isNaN(this.yearSelected)) { this.dateSelected = this.dateNow; this.monthSelected = this.monthNow; this.yearSelected = this.yearNow; } this.odateSelected = this.dateSelected; this.omonthSelected = this.monthSelected; this.oyearSelected = this.yearSelected; if (typeof jQuery != 'undefined') { // use jQuery if available this.o.style.top = (this.fixedY == -1) ? $(btn).position().top + btn.offsetHeight + 'px' : this.fixedY + 'px' ; this.o.style.left= (this.fixedX == -1) ? $(btn).position().left + 'px' : this.fixedX + 'px'; } else { this.o.style.top = (this.fixedY == -1) ? btn.offsetTop + this.getTop(btn.offsetParent) + btn.offsetHeight + 2 + 'px' : this.fixedY + 'px' ; this.o.style.left= (this.fixedX == -1) ? btn.offsetLeft + this.getLeft(btn.offsetParent) + 'px' : this.fixedX + 'px'; } this.construct (1, this.monthSelected, this.yearSelected); this.o.style.visibility = "visible"; if (this.hideElements) { this.hideElement('SELECT', this.$('pcIDcalendar')); this.hideElement('APPLET', this.$('pcIDcalendar')); } this.bShow = true; } else { popCalendar.hide(); if (this.ctlNow!=btn) this.popUp(btn, ctl, format); } this.ctlNow = btn; } } } popCalendar.init();
JavaScript
//Nested Side Bar Menu (Mar 20th, 09) //By Dynamic Drive: http://www.dynamicdrive.com/style/ var menuids=["sidebarmenu1"] //Enter id(s) of each Side Bar Menu's main UL, separated by commas function initsidebarmenu(){ for (var i=0; i<menuids.length; i++){ var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul") for (var t=0; t<ultags.length; t++){ ultags[t].parentNode.getElementsByTagName("a")[0].className+=" subfolderstyle" if (ultags[t].parentNode.parentNode.id==menuids[i]) //if this is a first level submenu ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px" //dynamically position first level submenus to be width of main menu item else //else if this is a sub level submenu (ul) ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it ultags[t].parentNode.onmouseover=function(){ this.getElementsByTagName("ul")[0].style.display="block" } ultags[t].parentNode.onmouseout=function(){ this.getElementsByTagName("ul")[0].style.display="none" } } for (var t=ultags.length-1; t>-1; t--){ //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars ultags[t].style.visibility="visible" ultags[t].style.display="none" } } } if (window.addEventListener) window.addEventListener("load", initsidebarmenu, false) else if (window.attachEvent) window.attachEvent("onload", initsidebarmenu)
JavaScript
/** * @Project NUKEVIET 3.0 * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2010 VINADES.,JSC. All rights reserved * @Createdate 31/05/2010, 9:36 */ function nv_admin_logout() { if (confirm(nv_admlogout_confirm[0])) { nv_ajax( 'get', nv_siteroot + 'index.php?second=admin_logout', 'js=1', '', 'nv_adminlogout_check' ); } return false; } // --------------------------------------- function nv_adminlogout_check(res) { if(res == 1) { alert(nv_admlogout_confirm[1]); if(nv_area_admin == 1) { window.location.href = nv_siteroot + 'index.php'; } else { window.location.href = strHref; } } return false; } function nv_open_browse_file(theURL,winName,w,h,features) { LeftPosition = (screen.width) ? (screen.width-w)/2 : 0; TopPosition = (screen.height) ? (screen.height-h)/2 : 0; settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition; if(features != '') { settings = settings + ','+features; } window.open(theURL,winName,settings); window.blur(); } //--------------------------------------- function nv_sh(sl_id, div_id){ var new_opt = document.getElementById(sl_id).options[document.getElementById(sl_id).selectedIndex].value; if (new_opt == 3) nv_show_hidden(div_id, 1); else nv_show_hidden(div_id, 0); return false; }
JavaScript
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** May 2nd, 08'- Script rewritten and updated to 2.0. //** June 12th, 08'- Script updated to v 2.3, which adds the following features: //1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later. //2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former). //3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example. //** July 11th, 08'- Script updated to v 2.4: //1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider") //2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads. var featuredcontentslider={ //3 variables below you can customize if desired: ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="loading.gif" /> Fetching slider Contents. Please wait...</div>', bustajaxcache: true, //bust caching of external ajax page after 1st request? enablepersist: true, //persist to last content viewed when returning to page? settingcaches: {}, //object to cache "setting" object of each script instance jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually. this.turnpage(this.settingcaches[fcsid], pagenumber) }, ajaxconnect:function(setting){ var page_request = false if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false var pageurl=setting.contentsource[1] page_request.onreadystatechange=function(){ featuredcontentslider.ajaxpopulate(page_request, setting) } document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcache, true) page_request.send(null) }, ajaxpopulate:function(page_request, setting){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ document.getElementById(setting.id).innerHTML=page_request.responseText this.buildpaginate(setting) } }, buildcontentdivs:function(setting){ var alldivs=document.getElementById(setting.id).getElementsByTagName("div") for (var i=0; i<alldivs.length; i++){ if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv" setting.contentdivs.push(alldivs[i]) alldivs[i].style.display="none" //collapse all content DIVs to begin with } } }, buildpaginate:function(setting){ this.buildcontentdivs(setting) var sliderdiv=document.getElementById(setting.id) var pdiv=document.getElementById("paginate-"+setting.id) var phtml="" var toc=setting.toc var nextprev=setting.nextprev if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){ for (var i=1; i<=setting.contentdivs.length; i++){ phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> ' } phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '') pdiv.innerHTML=phtml } var pdivlinks=pdiv.getElementsByTagName("a") var toclinkscount=0 //var to keep track of actual # of toc links for (var i=0; i<pdivlinks.length; i++){ if (this.css(pdivlinks[i], "toc", "check")){ if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents) pdivlinks[i].style.display="none" //hide this toc link continue } pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link pdivlinks[i][setting.revealtype]=function(){ featuredcontentslider.turnpage(setting, this.getAttribute("rel")) return false } setting.toclinks.push(pdivlinks[i]) } else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next" pdivlinks[i].onclick=function(){ featuredcontentslider.turnpage(setting, this.className) return false } } } this.turnpage(setting, setting.currentpage, true) if (setting.autorotate[0]){ //if auto rotate enabled pdiv[setting.revealtype]=function(){ featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation this.autorotate(setting) } }, urlparamselect:function(fcsid){ var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, turnpage:function(setting, thepage, autocall){ var currentpage=setting.currentpage //current page # before change var totalpages=setting.contentdivs.length var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage) turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly return setting.currentpage=turntopage setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex this.cleartimer(setting, window["fcsfade"+setting.id]) setting.cacheprevpage=setting.prevpage if (setting.enablefade[0]==true){ setting.curopacity=0 this.fadeup(setting) } if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete) setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.prevpage, setting.currentpage) } setting.contentdivs[turntopage-1].style.visibility="visible" setting.contentdivs[turntopage-1].style.display="block" if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[setting.prevpage-1], "selected", "remove") if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[turntopage-1], "selected", "add") setting.prevpage=turntopage if (this.enablepersist) this.setCookie("fcspersist"+setting.id, turntopage) }, setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=setting.contentdivs[setting.currentpage-1] if (targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value setting.curopacity=value }, fadeup:function(setting){ if (setting.curopacity<1){ this.setopacity(setting, setting.curopacity+setting.enablefade[1]) window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50) } else{ //when fade is complete if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run) setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.cacheprevpage, setting.currentpage) } }, cleartimer:function(setting, timervar){ if (typeof timervar!="undefined"){ clearTimeout(timervar) clearInterval(timervar) if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div setting.contentdivs[setting.cacheprevpage-1].style.display="none" } } }, css:function(el, targetclass, action){ var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig") if (action=="check") return needle.test(el.className) else if (action=="remove") el.className=el.className.replace(needle, "") else if (action=="add") el.className+=" "+targetclass }, autorotate:function(setting){ window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1]) }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value){ document.cookie = name+"="+value }, init:function(setting){ var persistedpage=this.getCookie("fcspersist"+setting.id) || 1 var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index this.settingcaches[setting.id]=setting //cache "setting" object setting.contentdivs=[] setting.toclinks=[] setting.topzindex=0 setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1) setting.prevpage=setting.currentpage setting.revealtype="on"+(setting.revealtype || "click") setting.curopacity=0 setting.onChange=setting.onChange || function(){} if (setting.contentsource[0]=="inline") this.buildpaginate(setting) if (setting.contentsource[0]=="ajax") this.ajaxconnect(setting) } }
JavaScript
/** * Styleswitch stylesheet switcher built on jQuery * Under an Attribution, Share Alike License * By Kelvin Luck ( http://www.kelvinluck.com/ ) **/ (function($) { $(document).ready(function() { $('.styleswitch').click(function() { switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('style'); if (c) switchStylestyle(c); }); function switchStylestyle(styleName) { $('link[rel*=style][title]').each(function(i) { this.disabled = true; if (this.getAttribute('title') == styleName) this.disabled = false; }); createCookie('style', styleName, 365); } })(jQuery); // cookie functions http://www.quirksmode.org/js/cookies.html function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; 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 eraseCookie(name) { createCookie(name,"",-1); } // /cookie functions
JavaScript
//** Stay on Top content script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** Script available at usage terms at http://www.dynamicdrive.com //** v1.0 (May 12th, 09') var alwaysOnTop={ dsettings: { targetid: '', orientation: 2, position: [10, 30], externalsource: '', frequency: 1, hideafter: 0, fadeduration: [500, 500], display: 0 //internal setting on whether to display target element at all (based on frequency setting) }, settingscache: {}, positiontarget:function($target, settings){ var fixedsupport=!document.all || document.all && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode var posoptions={position:fixedsupport? 'fixed':'absolute', visibility:'visible'} if (settings.fadeduration[0]>0) //if fade in posoptions.opacity=0 posoptions[(/^[13]$/.test(settings.orientation))? 'left' : 'right']=settings.position[0] posoptions[(/^[12]$/.test(settings.orientation))? 'top' : 'bottom']=settings.position[1] if (document.all && !window.XMLHttpRequest) //loose check for IE6 and below posoptions.width=$target.width() //IE6- seems to require an explicit width on a DIV $target.css(posoptions) if (!fixedsupport){ this.keepfixed($target, settings) var evtstr='scroll.' + settings.targetid + ' resize.'+settings.targetid jQuery(window).bind(evtstr, function(){alwaysOnTop.keepfixed($target, settings)}) } this.revealdiv($target, settings, fixedsupport) if (settings.hideafter>0){ //if hide timer enabled setTimeout(function(){ alwaysOnTop.hidediv(settings.targetid) }, settings.hideafter+settings.fadeduration[0]) } }, keepfixed:function($target, settings){ var $window=jQuery(window) var is1or3=/^[13]$/.test(settings.orientation) var is1or2=/^[12]$/.test(settings.orientation) var x=$window.scrollLeft() + (is1or3? settings.position[0] : $window.width()-$target.outerWidth()-settings.position[0]) var y=$window.scrollTop() + (is1or2? settings.position[1] : $window.height()-$target.outerHeight()-settings.position[1]) $target.css({left:x+'px', top:y+'px'}) }, revealdiv:function($target, settings){ if (settings.fadeduration[0]>0) //if fade in $target.show().animate({opacity:1}, settings.fadeduration[0]) else $target.show() if (settings.frequency=="session") //set session only cookie (name: 'sots' + targetid)? this.setCookie('sots'+settings.targetid, 'shown') else if (/^\d+ day/i.test(settings.frequency)){ //set persistent cookie (name: 'sotp' + targetid)? var persistdays=parseInt(settings.frequency) this.setCookie('sotp'+settings.targetid, persistdays, persistdays) } }, hidediv:function(targetid){ //public function var $target=jQuery('#'+targetid) if ($target.css('display')=='none') //if target hidden already return var settings=this.settingscache[targetid] if (settings.fadeduration[1]>0) //if fade out $target.animate({opacity:0}, settings.fadeduration[1], function(){$target.hide()}) else $target.hide() var evtstr='scroll.' + settings.targetid + ' resize.'+settings.targetid jQuery(window).unbind(evtstr) }, loadajaxcontent:function($, settings){ $.ajax({ url: settings.externalsource, error:function(ajaxrequest){ alert('Error fetching Ajax content.\nServer Response: '+ajaxrequest.responseText) }, success:function(content){ var $target=$(content) if ($target.get(0).id==settings.targetid) alwaysOnTop.positiontarget($target.appendTo('body'), settings) else alert('Error: The value you have entered for "targetid" ('+settings.targetid+') ' + 'doesn\'t match the ID of your remote content\'s DIV container ('+$target.get(0).id+'). This must be corrected' ) } }) }, init:function(options){ var settings={} settings=jQuery.extend(settings, this.dsettings, options) this.settingscache[settings.targetid]=settings if (typeof settings.frequency=="number") //value of 1=show, 0=hide settings.display=(settings.frequency>Math.random())? 1 : 0 else if (settings.frequency=="session") settings.display=(this.getCookie('sots'+settings.targetid)=='shown')? 0 : 1 //session cookie name: 'sots' + targetid else if (/^\d+ day/i.test(settings.frequency)){ //match 'xx days' //If admin has changed number of days to persist from current cookie records, reset persistence by deleting cookie if (parseInt(this.getCookie('sotp'+settings.targetid))!= parseInt(settings.frequency)) this.setCookie('sotp'+settings.targetid, '', -1) settings.display=(this.getCookie('sotp'+settings.targetid)!=null)? 0 : 1 //persistent cookie name: 'sotp' + targetid } jQuery(document).ready(function($){ if (settings.externalsource!='' && settings.display){ //if ajax content alwaysOnTop.loadajaxcontent($, settings) } else if (settings.externalsource==''){ //inline content var $target=$('#'+settings.targetid) if (!settings.display){ //if hide content (based on frequency setting) $target.hide() return false } else{ alwaysOnTop.positiontarget($target, settings) } } }) //end ready }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value, days){ if (typeof days!="undefined"){ //if set persistent cookie var expireDate = new Date() var expstring=expireDate.setDate(expireDate.getDate()+days) document.cookie = name+"="+value+"; expires="+expireDate.toGMTString() } else document.cookie = name+"="+value+"; path=/" } }
JavaScript
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** May 2nd, 08'- Script rewritten and updated to 2.0. //** June 12th, 08'- Script updated to v 2.3, which adds the following features: //1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later. //2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former). //3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example. //** July 11th, 08'- Script updated to v 2.4: //1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider") //2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads. var featuredcontentslider={ //3 variables below you can customize if desired: ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="loading.gif" /> Fetching slider Contents. Please wait...</div>', bustajaxcache: true, //bust caching of external ajax page after 1st request? enablepersist: true, //persist to last content viewed when returning to page? settingcaches: {}, //object to cache "setting" object of each script instance jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually. this.turnpage(this.settingcaches[fcsid], pagenumber) }, ajaxconnect:function(setting){ var page_request = false if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false var pageurl=setting.contentsource[1] page_request.onreadystatechange=function(){ featuredcontentslider.ajaxpopulate(page_request, setting) } document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcache, true) page_request.send(null) }, ajaxpopulate:function(page_request, setting){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ document.getElementById(setting.id).innerHTML=page_request.responseText this.buildpaginate(setting) } }, buildcontentdivs:function(setting){ var alldivs=document.getElementById(setting.id).getElementsByTagName("div") for (var i=0; i<alldivs.length; i++){ if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv" setting.contentdivs.push(alldivs[i]) alldivs[i].style.display="none" //collapse all content DIVs to begin with } } }, buildpaginate:function(setting){ this.buildcontentdivs(setting) var sliderdiv=document.getElementById(setting.id) var pdiv=document.getElementById("paginate-"+setting.id) var phtml="" var toc=setting.toc var nextprev=setting.nextprev if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){ for (var i=1; i<=setting.contentdivs.length; i++){ phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> ' } phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '') pdiv.innerHTML=phtml } var pdivlinks=pdiv.getElementsByTagName("a") var toclinkscount=0 //var to keep track of actual # of toc links for (var i=0; i<pdivlinks.length; i++){ if (this.css(pdivlinks[i], "toc", "check")){ if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents) pdivlinks[i].style.display="none" //hide this toc link continue } pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link pdivlinks[i][setting.revealtype]=function(){ featuredcontentslider.turnpage(setting, this.getAttribute("rel")) return false } setting.toclinks.push(pdivlinks[i]) } else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next" pdivlinks[i].onclick=function(){ featuredcontentslider.turnpage(setting, this.className) return false } } } this.turnpage(setting, setting.currentpage, true) if (setting.autorotate[0]){ //if auto rotate enabled pdiv[setting.revealtype]=function(){ featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation this.autorotate(setting) } }, urlparamselect:function(fcsid){ var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, turnpage:function(setting, thepage, autocall){ var currentpage=setting.currentpage //current page # before change var totalpages=setting.contentdivs.length var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage) turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly return setting.currentpage=turntopage setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex this.cleartimer(setting, window["fcsfade"+setting.id]) setting.cacheprevpage=setting.prevpage if (setting.enablefade[0]==true){ setting.curopacity=0 this.fadeup(setting) } if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete) setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.prevpage, setting.currentpage) } setting.contentdivs[turntopage-1].style.visibility="visible" setting.contentdivs[turntopage-1].style.display="block" if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[setting.prevpage-1], "selected", "remove") if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[turntopage-1], "selected", "add") setting.prevpage=turntopage if (this.enablepersist) this.setCookie("fcspersist"+setting.id, turntopage) }, setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=setting.contentdivs[setting.currentpage-1] if (targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value setting.curopacity=value }, fadeup:function(setting){ if (setting.curopacity<1){ this.setopacity(setting, setting.curopacity+setting.enablefade[1]) window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50) } else{ //when fade is complete if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run) setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.cacheprevpage, setting.currentpage) } }, cleartimer:function(setting, timervar){ if (typeof timervar!="undefined"){ clearTimeout(timervar) clearInterval(timervar) if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div setting.contentdivs[setting.cacheprevpage-1].style.display="none" } } }, css:function(el, targetclass, action){ var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig") if (action=="check") return needle.test(el.className) else if (action=="remove") el.className=el.className.replace(needle, "") else if (action=="add") el.className+=" "+targetclass }, autorotate:function(setting){ window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1]) }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value){ document.cookie = name+"="+value }, init:function(setting){ var persistedpage=this.getCookie("fcspersist"+setting.id) || 1 var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index this.settingcaches[setting.id]=setting //cache "setting" object setting.contentdivs=[] setting.toclinks=[] setting.topzindex=0 setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1) setting.prevpage=setting.currentpage setting.revealtype="on"+(setting.revealtype || "click") setting.curopacity=0 setting.onChange=setting.onChange || function(){} if (setting.contentsource[0]=="inline") this.buildpaginate(setting) if (setting.contentsource[0]=="ajax") this.ajaxconnect(setting) } }
JavaScript
$(function(){ $("ul.nav li").hover(function(){ $(this).addClass("hover"); $('ul:first', this).css('visibility', 'visible'); }, function(){ $(this).removeClass("hover"); $('ul:first', this).css('visibility', 'hidden'); }); $("ul.nav li ul li:has(ul)").find("a:first").append(" &raquo; "); });
JavaScript
var obj = null; function checkHover() { if (obj) { obj.find('ul').fadeOut('fast'); } //if } //checkHover $(document).ready(function() { $('#category_news > li').hover(function() { if (obj) { obj.find('ul').fadeOut('fast'); obj = null; } //if $(this).find('ul').fadeIn('fast'); }, function() { obj = $(this); setTimeout( "checkHover()", 400); }); });
JavaScript
// Copyright 2008 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. // Generic helpers /** * Create a new XMLHttpRequest in a cross-browser-compatible way. * @return XMLHttpRequest object */ function M_getXMLHttpRequest() { try { return new XMLHttpRequest(); } catch (e) { } try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } return null; } /** * Finds the element's parent in the DOM tree. * @param {Element} element The element whose parent we want to find * @return The parent element of the given element */ function M_getParent(element) { if (element.parentNode) { return element.parentNode; } else if (element.parentElement) { // IE compatibility. Why follow standards when you can make up your own? return element.parentElement; } return null; } /** * Finds the event's target in a way that works on all browsers. * @param {Event} e The event object whose target we want to find * @return The element receiving the event */ function M_getEventTarget(e) { var src = e.srcElement ? e.srcElement : e.target; return src; } /** * Function to determine if we are in a KHTML-based browser(Konq/Safari). * @return Boolean of whether we are in a KHTML browser */ function M_isKHTML() { var agt = navigator.userAgent.toLowerCase(); return (agt.indexOf("safari") != -1) || (agt.indexOf("khtml") != -1); } /** * Function to determine if we are running in an IE browser. * @return Boolean of whether we are running in IE */ function M_isIE() { return (navigator.userAgent.toLowerCase().indexOf("msie") != -1) && !window.opera; } /** * Function to determine if we are in a WebKit-based browser (Chrome/Safari). * @return Boolean of whether we are in a WebKit browser */ function M_isWebKit() { return navigator.userAgent.toLowerCase().indexOf("webkit") != -1; } /** * Stop the event bubbling in a browser-independent way. Sometimes required * when it is not easy to return true when an event is handled. * @param {Window} win The window in which this event is happening * @param {Event} e The event that we want to cancel */ function M_stopBubble(win, e) { if (!e) { e = win.event; } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } /** * Return distance in pixels from the top of the document to the given element. * @param {Element} element The element whose offset we want to find * @return Integer value of the height of the element from the top */ function M_getPageOffsetTop(element) { var y = element.offsetTop; if (element.offsetParent != null) { y += M_getPageOffsetTop(element.offsetParent); } return y; } /** * Return distance in pixels of the given element from the left of the document. * @param {Element} element The element whose offset we want to find * @return Integer value of the horizontal position of the element */ function M_getPageOffsetLeft(element) { var x = element.offsetLeft; if (element.offsetParent != null) { x += M_getPageOffsetLeft(element.offsetParent); } return x; } /** * Find the height of the window viewport. * @param {Window} win The window whose viewport we would like to measure * @return Integer value of the height of the given window */ function M_getWindowHeight(win) { return M_getWindowPropertyByBrowser_(win, M_getWindowHeightGetters_); } /** * Find the vertical scroll position of the given window. * @param {Window} win The window whose scroll position we want to find * @return Integer value of the scroll position of the given window */ function M_getScrollTop(win) { return M_getWindowPropertyByBrowser_(win, M_getScrollTopGetters_); } /** * Scroll the target element into view at 1/3rd of the window height only if * the scrolling direction matches the direction that was asked for. * @param {Window} win The window in which the element resides * @param {Element} element The element that we want to bring into view * @param {Integer} direction Positive for scroll down, negative for scroll up */ function M_scrollIntoView(win, element, direction) { var elTop = M_getPageOffsetTop(element); var winHeight = M_getWindowHeight(win); var targetScroll = elTop - winHeight / 3; var scrollTop = M_getScrollTop(win); if ((direction > 0 && scrollTop < targetScroll) || (direction < 0 && scrollTop > targetScroll)) { win.scrollTo(M_getPageOffsetLeft(element), targetScroll); } } /** * Returns whether the element is visible. * @param {Window} win The window that the element resides in * @param {Element} element The element whose visibility we want to determine * @return Boolean of whether the element is visible in the window or not */ function M_isElementVisible(win, element) { var elTop = M_getPageOffsetTop(element); var winHeight = M_getWindowHeight(win); var winTop = M_getScrollTop(win); if (elTop < winTop || elTop > winTop + winHeight) { return false; } return true; } // Cross-browser compatibility quirks and methodology borrowed from // common.js var M_getWindowHeightGetters_ = { ieQuirks_: function(win) { return win.document.body.clientHeight; }, ieStandards_: function(win) { return win.document.documentElement.clientHeight; }, dom_: function(win) { return win.innerHeight; } }; var M_getScrollTopGetters_ = { ieQuirks_: function(win) { return win.document.body.scrollTop; }, ieStandards_: function(win) { return win.document.documentElement.scrollTop; }, dom_: function(win) { return win.pageYOffset; } }; /** * Slightly modified from common.js: Konqueror has the CSS1Compat property * but requires the standard DOM functionlity, not the IE one. */ function M_getWindowPropertyByBrowser_(win, getters) { try { if (!M_isKHTML() && "compatMode" in win.document && win.document.compatMode == "CSS1Compat") { return getters.ieStandards_(win); } else if (M_isIE()) { return getters.ieQuirks_(win); } } catch (e) { // Ignore for now and fall back to DOM method } return getters.dom_(win); } // Global search box magic (global.html) /** * Handle the onblur action of the search box, replacing it with greyed out * instruction text when it is empty. * @param {Element} element The search box element */ function M_onSearchBlur(element) { var defaultMsg = "Enter a changelist#, user, or group"; if (element.value.length == 0 || element.value == defaultMsg) { element.style.color = "gray"; element.value = defaultMsg; } else { element.style.color = ""; } } /** * Handle the onfocus action of the search box, emptying it out if no new text * was entered. * @param {Element} element The search box element */ function M_onSearchFocus(element) { if (element.style.color == "gray") { element.style.color = ""; element.value = ""; } } // Inline diffs (changelist.html) /** * Creates an iframe to load the diff in the background and when that's done, * calls a function to transfer the contents of the iframe into the current DOM. * @param {Integer} suffix The number associated with that diff * @param {String} url The URL that the diff should be fetched from * @return false (for event bubbling purposes) */ function M_showInlineDiff(suffix, url) { var hide = document.getElementById("hide-" + suffix); var show = document.getElementById("show-" + suffix); var frameDiv = document.getElementById("frameDiv-" + suffix); var dumpDiv = document.getElementById("dumpDiv-" + suffix); var diffTR = document.getElementById("diffTR-" + suffix); var hideAll = document.getElementById("hide-alldiffs"); var showAll = document.getElementById("show-alldiffs"); /* Twiddle the "show/hide all diffs" link */ if (hide.style.display != "") { M_CL_hiddenInlineDiffCount -= 1; if (M_CL_hiddenInlineDiffCount == M_CL_maxHiddenInlineDiffCount) { showAll.style.display = "inline"; hideAll.style.display = "none"; } else { showAll.style.display = "none"; hideAll.style.display = "inline"; } } hide.style.display = ""; show.style.display = "none"; dumpDiv.style.display = "block"; // XXX why not ""? diffTR.style.display = ""; if (!frameDiv.innerHTML) { if (M_isKHTML()) { frameDiv.style.display = "block"; // XXX why not ""? } frameDiv.innerHTML = "<iframe src='" + url + "'" + " onload='M_dumpInlineDiffContent(this, \"" + suffix + "\")'"+ "height=1>your browser does not support iframes!</iframe>"; } return false; } /** * Hides the diff that was retrieved with M_showInlineDiff. * @param {Integer} suffix The number associated with the diff we want to hide */ function M_hideInlineDiff(suffix) { var hide = document.getElementById("hide-" + suffix); var show = document.getElementById("show-" + suffix); var dumpDiv = document.getElementById("dumpDiv-" + suffix); var diffTR = document.getElementById("diffTR-" + suffix); var hideAll = document.getElementById("hide-alldiffs"); var showAll = document.getElementById("show-alldiffs"); /* Twiddle the "show/hide all diffs" link */ if (hide.style.display != "none") { M_CL_hiddenInlineDiffCount += 1; if (M_CL_hiddenInlineDiffCount == M_CL_maxHiddenInlineDiffCount) { showAll.style.display = "inline"; hideAll.style.display = "none"; } else { showAll.style.display = "none"; hideAll.style.display = "inline"; } } hide.style.display = "none"; show.style.display = "inline"; diffTR.style.display = "none"; dumpDiv.style.display = "none"; return false; } /** * Dumps the content of the given iframe into the appropriate div in order * for the diff to be displayed. * @param {Element} iframe The IFRAME that contains the diff data * @param {Integer} suffix The number associated with the diff */ function M_dumpInlineDiffContent(iframe, suffix) { var dumpDiv = document.getElementById("dumpDiv-" + suffix); dumpDiv.style.display = "block"; // XXX why not ""? dumpDiv.innerHTML = iframe.contentWindow.document.body.innerHTML; // TODO: The following should work on all browsers instead of the // innerHTML hack above. At this point I don't remember what the exact // problem was, but it didn't work for some reason. // dumpDiv.appendChild(iframe.contentWindow.document.body); if (M_isKHTML()) { var frameDiv = document.getElementById("frameDiv-" + suffix); frameDiv.style.display = "none"; } } /** * Goes through all the diffs and triggers the onclick action on them which * should start the mechanism for displaying them. * @param {Integer} num The number of diffs to display (0-indexed) */ function M_showAllDiffs(num) { for (var i = 0; i < num; i++) { var link = document.getElementById('show-' + i); // Since the user may not have JS, the template only shows the diff inline // for the onclick action, not the href. In order to activate it, we must // call the link's onclick action. if (link.className.indexOf("reverted") == -1) { link.onclick(); } } } /** * Goes through all the diffs and hides them by triggering the hide link. * @param {Integer} num The number of diffs to hide (0-indexed) */ function M_hideAllDiffs(num) { for (var i = 0; i < num; i++) { var link = document.getElementById('hide-' + i); // If the user tries to hide, that means they have JS, which in turn means // that we can just set href in the href of the hide link. link.onclick(); } } // Inline comment submission forms (changelist.html, file.html) /** * Changes the elements display style to "" which renders it visible. * @param {String|Element} elt The id of the element or the element itself */ function M_showElement(elt) { if (typeof elt == "string") { elt = document.getElementById(elt); } if (elt) elt.style.display = ""; } /** * Changes the elements display style to "none" which renders it invisible. * @param {String|Element} elt The id of the element or the element itself */ function M_hideElement(elt) { if (typeof elt == "string") { elt = document.getElementById(elt); } if (elt) elt.style.display = "none"; } /** * Toggle the visibility of a section. The little indicator triangle will also * be toggled. * @param {String} id The id of the target element */ function M_toggleSection(id) { var sectionStyle = document.getElementById(id).style; var pointerStyle = document.getElementById(id + "-pointer").style; if (sectionStyle.display == "none") { sectionStyle.display = ""; pointerStyle.backgroundImage = "url('" + media_url + "opentriangle.gif')"; } else { sectionStyle.display = "none"; pointerStyle.backgroundImage = "url('" + media_url + "closedtriangle.gif')"; } } /** * Callback for XMLHttpRequest. */ function M_PatchSetFetched() { if (http_request.readyState != 4) return; var section = document.getElementById(http_request.div_id); if (http_request.status == 200) { section.innerHTML = http_request.responseText; /* initialize dashboardState again to update cached patch rows */ if (dashboardState) dashboardState.initialize(); } else { section.innerHTML = '<div style="color:red">Could not load the patchset (' + http_request.status + ').</div>'; } } /** * Toggle the visibility of a patchset, and fetches it if necessary. * @param {String} issue The issue key * @param {String} id The patchset key */ function M_toggleSectionForPS(issue, patchset) { var id = 'ps-' + patchset; M_toggleSection(id); var section = document.getElementById(id); if (section.innerHTML.search("<div") != -1) return; section.innerHTML = "<div>Loading...</div>" http_request = M_getXMLHttpRequest(); if (!http_request) return; http_request.open('GET', base_url + issue + "/patchset/" + patchset, true); http_request.onreadystatechange = M_PatchSetFetched; http_request.div_id = id; http_request.send(null); } // Comment expand/collapse /** * Toggles whether the specified changelist comment is expanded/collapsed. * @param {Integer} cid The comment id, 0-indexed */ function M_switchChangelistComment(cid) { M_switchCommentCommon_('cl', String(cid)); } /** * Toggles a comment or patchset. * * If the anchor has the form "#msgNUMBER" a message is toggled. * If the anchor has the form "#psNUMBER" a patchset is toggled. */ function M_toggleIssueOverviewByAnchor() { var href = window.location.href; var idx_hash = href.lastIndexOf('#'); if (idx_hash != -1) { var anchor = href.slice(idx_hash+1, href.length); if (anchor.slice(0, 3) == 'msg') { var elem = document.getElementById(anchor); elem.className += ' referenced'; var num = elem.getAttribute('name'); M_switchChangelistComment(num); } else if (anchor.slice(0, 2) == 'ps') { // hide last patchset which is visible by default. M_toggleSectionForPS(issueId, lastPSId); M_toggleSectionForPS(issueId, anchor.slice(2, anchor.length)); } } } /** * Toggles whether the specified inline comment is expanded/collapsed. * @param {Integer} cid The comment id, 0-indexed * @param {Integer} lineno The lineno associated with the comment * @param {String} side The side (a/b) associated with the comment */ function M_switchInlineComment(cid, lineno, side) { M_switchCommentCommon_('inline', String(cid) + "-" + lineno + "-" + side); } /** * Used to expand all comments, hiding the preview and showing the comment. * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} num_comments The number of comments to show */ function M_showAllComments(prefix, num_comments) { for (var i = 0; i < num_comments; i++) { M_hideElement(prefix + "-preview-" + i); M_showElement(prefix + "-comment-" + i); } } /** * Used to collpase all comments, showing the preview and hiding the comment. * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} num_comments The number of comments to hide */ function M_hideAllComments(prefix, num_comments) { for (var i = 0; i < num_comments; i++) { M_showElement(prefix + "-preview-" + i); M_hideElement(prefix + "-comment-" + i); } } // Common methods for comment handling (changelist.html, file.html, // comment_form.html) /** * Toggles whether the specified comment is expanded/collapsed. Works in * the review form. * @param {String} prefix The prefix of the comment element name. * @param {String} suffix The suffix of the comment element name. */ function M_switchCommentCommon_(prefix, suffix) { prefix && (prefix += '-'); suffix && (suffix = '-' + suffix); var previewSpan = document.getElementById(prefix + 'preview' + suffix); var commentDiv = document.getElementById(prefix + 'comment' + suffix); if (!previewSpan || !commentDiv) { alert('Failed to find comment element: ' + prefix + 'comment' + suffix + '. Please send ' + 'this message with the URL to the app owner'); return; } if (previewSpan.style.display == 'none') { M_showElement(previewSpan); M_hideElement(commentDiv); } else { M_hideElement(previewSpan); M_showElement(commentDiv); } } /** * Expands all inline comments. */ function M_expandAllInlineComments() { M_showAllInlineComments(); var comments = document.getElementsByName("inline-comment"); var commentsLength = comments.length; for (var i = 0; i < commentsLength; i++) { comments[i].style.display = ""; } var previews = document.getElementsByName("inline-preview"); var previewsLength = previews.length; for (var i = 0; i < previewsLength; i++) { previews[i].style.display = "none"; } } /** * Collapses all inline comments. */ function M_collapseAllInlineComments() { M_showAllInlineComments(); var comments = document.getElementsByName("inline-comment"); var commentsLength = comments.length; for (var i = 0; i < commentsLength; i++) { comments[i].style.display = "none"; } var previews = document.getElementsByName("inline-preview"); var previewsLength = previews.length; for (var i = 0; i < previewsLength; i++) { previews[i].style.display = ""; } } // Non-inline comment actions /** * Sets up a reply form for a given comment (non-inline). * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {Integer} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} opt_lineno (optional) The line number the comment should be * attached to * @param {String} opt_snapshot (optional) The snapshot ID of the comment being * replied to */ function M_replyToComment(author, written_time, ccs, cid, prefix, opt_lineno, opt_snapshot) { var form = document.getElementById("comment-form-" + cid); if (!form) { form = document.getElementById("dareplyform"); if (!form) { form = document.getElementById("daform"); // XXX for file.html } form = form.cloneNode(true); form.name = form.id = "comment-form-" + cid; M_createResizer_(form, cid); document.getElementById(prefix + "-comment-" + cid).appendChild(form); } form.style.display = ""; form.reply_to.value = cid; form.ccs.value = ccs; if (typeof opt_lineno != 'undefined' && typeof opt_snapshot != 'undefined') { form.lineno.value = opt_lineno; form.snapshot.value = opt_snapshot; } form.text.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("comment-text-" + cid); M_setValueFromDivs(divs, form.text); form.text.value += "\n"; form.text.focus(); } /** /* TODO(andi): docstring */ function M_replyToMessage(message_id, written_time, author, db_message_object_key) { var form = document.getElementById('message-reply-form'); form = form.cloneNode(true); var container = document.getElementById('message-reply-'+message_id); var replyLink = document.getElementById('message-reply-href-'+message_id); var msgTextarea = replyLink.nextSibling.nextSibling; form.insertBefore(msgTextarea, form.firstChild); M_showElement(msgTextarea); container.appendChild(form); M_showElement(container); form.in_reply_to.value = db_message_object_key; form.discard.onclick = function () { form.message.value = ""; M_getParent(container).insertBefore(msgTextarea, replyLink.nextSibling.nextSibling); M_showElement(replyLink); M_hideElement(msgTextarea); container.innerHTML = ""; } form.send_mail.id = 'message-reply-send-mail-'+message_id; var lbl = document.getElementById(form.send_mail.id).nextSibling.nextSibling; lbl.setAttribute('for', form.send_mail.id); if (!form.message.value) { form.message.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("cl-message-" + message_id); form.message.focus(); M_setValueFromDivs(divs, form.message); form.message.value += "\n"; } M_addTextResizer_(form); M_hideElement(replyLink); } /** * Edits a non-inline draft comment. * @param {Integer} cid The number of the comment to be edited */ function M_editComment(cid) { var suffix = String(cid); var form = document.getElementById("comment-form-" + suffix); if (!form) { alert("Form " + suffix + " does not exist. Please send this message " + "with the URL to the app owner"); return false; } var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = "none"; } M_hideElement("edit-link-" + suffix); M_hideElement("undo-link-" + suffix); form.style.display = ""; form.text.focus(); } /** * Used to cancel comment editing, this will revert the text of the comment * and hide its form. * @param {Element} form The form that contains this comment * @param {Integer} cid The number of the comment being hidden */ function M_resetAndHideComment(form, cid) { form.text.blur(); form.text.value = form.oldtext.value; form.style.display = "none"; var texts = document.getElementsByName("comment-text-" + cid); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = ""; } M_showElement("edit-link-" + cid); } /** * Removing a draft comment is the same as setting its text contents to nothing. * @param {Element} form The form containing the draft comment to be discarded * @return true in order for the form submission to continue */ function M_removeComment(form) { form.text.value = ""; return true; } // Inline comments (file.html) /** * Helper method to assign an onclick handler to an inline 'Cancel' button. * @param {Element} form The form containing the cancel button * @param {Function} cancelHandler A function with one 'form' argument * @param {Array} opt_handlerParams An array whose first three elements are: * {String} cid The number of the comment * {String} lineno The line number of the comment * {String} side 'a' or 'b' */ function M_assignToCancel_(form, cancelHandler, opt_handlerParams) { var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { if (form.elements[i].getAttribute("name") == "cancel") { form.elements[i].onclick = function() { if (typeof opt_handlerParams != "undefined") { var cid = opt_handlerParams[0]; var lineno = opt_handlerParams[1]; var side = opt_handlerParams[2]; cancelHandler(form, cid, lineno, side); } else { cancelHandler(form); } }; return; } } } /** * Helper method to assign an onclick handler to an inline '[+]' link. * @param {Element} form The form containing the resizer * @param {String} suffix The suffix of the comment form id: lineno-side */ function M_createResizer_(form, suffix) { if (!form.hasResizer) { var resizer = document.getElementById("resizer").cloneNode(true); resizer.onclick = function() { var form = document.getElementById("comment-form-" + suffix); if (!form) return; form.text.rows += 5; form.text.focus(); }; var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { var node = form.elements[i]; if (node.nodeName == "TEXTAREA") { var parent = M_getParent(node); parent.insertBefore(resizer, node.nextSibling); resizer.style.display = ""; form.hasResizer = true; } } } } /** * Like M_createResizer_(), but updates the form's first textarea field. * This is assumed not to be the last field. * @param {Element} form The form whose textarea field to update. */ function M_addTextResizer_(form) { if (M_isWebKit()) { return; // WebKit has its own resizer. } var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { var node = form.elements[i]; if (node.nodeName == "TEXTAREA") { var parent = M_getParent(node); var resizer = document.getElementById("resizer").cloneNode(true); var next = node.nextSibling; parent.insertBefore(resizer, next); resizer.onclick = function() { node.rows += 5; node.focus(); }; resizer.style.display = ""; if (next && next.className == "resizer") { // Remove old resizer. parent.removeChild(next); } break; } } } /** * Helper method to assign an onclick handler to an inline 'Save' button. * @param {Element} form The form containing the save button * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_assignToSave_(form, cid, lineno, side) { var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { if (form.elements[i].getAttribute("name") == "save") { form.elements[i].onclick = function() { return M_submitInlineComment(form, cid, lineno, side); }; return; } } } /** * Creates an inline comment at the given line number and side of the diff. * @param {String} lineno The line number of the new comment * @param {String} side Either 'a' or 'b' signifying the side of the diff */ function M_createInlineComment(lineno, side) { // The first field of the suffix is typically the cid, but we choose '-1' // here since the backend has not assigned the new comment a cid yet. var suffix = "-1-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { form = document.getElementById("dainlineform").cloneNode(true); form.name = form.id = "comment-form-" + suffix; M_assignToCancel_(form, M_removeTempInlineComment); M_createResizer_(form, suffix); M_assignToSave_(form, "-1", lineno, side); // There is a "text" node before the "div" node form.childNodes[1].setAttribute("name", "comment-border"); var id = (side == 'a' ? "old" : "new") + "-line-" + lineno; var td = document.getElementById(id); td.appendChild(form); var tr = M_getParent(td); tr.setAttribute("name", "hook"); hookState.updateHooks(); } form.style.display = ""; form.lineno.value = lineno; if (side == 'b') { form.snapshot.value = new_snapshot; } else { form.snapshot.value = old_snapshot; } form.side.value = side; var savedDraftKey = "new-" + form.lineno.value + "-" + form.snapshot.value; M_restoreDraftText_(savedDraftKey, form); form.text.focus(); hookState.gotoHook(0); } /** * Removes a never-submitted 'Reply' inline comment from existence (created via * M_replyToInlineComment). * @param {Element} form The form that contains the comment to be removed * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_removeTempReplyInlineComment(form, cid, lineno, side) { var divInlineComment = M_getParent(form); var divCommentBorder = M_getParent(divInlineComment); var td = M_getParent(divCommentBorder); var tr = M_getParent(td); form.cancel.blur(); // The order of the subsequent lines is sensitive to browser compatibility. var suffix = cid + "-" + lineno + "-" + side; M_saveDraftText_("reply-" + suffix, form.text.value); divInlineComment.removeChild(form); M_updateRowHook(tr); } /** * Removes a never-submitted inline comment from existence (created via * M_createInlineComment). Saves the existing text for the next time a draft is * created on the same line. * @param {Element} form The form that contains the comment to be removed */ function M_removeTempInlineComment(form) { var td = M_getParent(form); var tr = M_getParent(td); // The order of the subsequent lines is sensitive to browser compatibility. var savedDraftKey = "new-" + form.lineno.value + "-" + form.snapshot.value; M_saveDraftText_(savedDraftKey, form.text.value); form.cancel.blur(); td.removeChild(form); M_updateRowHook(tr); } /** * Helper to edit a draft inline comment. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @return {Element} The form that contains the comment */ function M_editInlineCommentCommon_(cid, lineno, side) { var suffix = cid + "-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { alert("Form " + suffix + " does not exist. Please send this message " + "with the URL to the app owner"); return false; } M_createResizer_(form, suffix); var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = "none"; } var hides = document.getElementsByName("comment-hide-" + suffix); var hidesLength = hides.length; for (var i = 0; i < hidesLength; i++) { hides[i].style.display = "none"; var links = hides[i].getElementsByTagName("A"); if (links && links.length > 0) { var link = links[0]; link.innerHTML = "Show quoted text"; } } M_hideElement("edit-link-" + suffix); M_hideElement("undo-link-" + suffix); form.style.display = ""; var parent = document.getElementById("inline-comment-" + suffix); if (parent && parent.style.display == "none") { M_switchInlineComment(cid, lineno, side); } form.text.focus(); hookState.gotoHook(0); return form; } /** * Edits a draft inline comment. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_editInlineComment(cid, lineno, side) { M_editInlineCommentCommon_(cid, lineno, side); } /** * Restores a canceled draft inline comment for editing. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_restoreEditInlineComment(cid, lineno, side) { var form = M_editInlineCommentCommon_(cid, lineno, side); var savedDraftKey = "edit-" + cid + "-" + lineno + "-" + side; M_restoreDraftText_(savedDraftKey, form, false); } /** * Helper to reply to an inline comment. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @param {String} opt_reply The response to pre-fill with. * @param {Boolean} opt_submit This will submit the comment right after * creation. Only makes sense when opt_reply is set * @return {Element} The form that contains the comment */ function M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side, opt_reply, opt_submit) { var suffix = cid + "-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { form = document.getElementById("dainlineform").cloneNode(true); form.name = form.id = "comment-form-" + suffix; M_assignToCancel_(form, M_removeTempReplyInlineComment, [cid, lineno, side]); M_assignToSave_(form, cid, lineno, side); M_createResizer_(form, suffix); var parent = document.getElementById("inline-comment-" + suffix); if (parent.style.display == "none") { M_switchInlineComment(cid, lineno, side); } parent.appendChild(form); } form.style.display = ""; form.lineno.value = lineno; if (side == 'b') { form.snapshot.value = new_snapshot; } else { form.snapshot.value = old_snapshot; } form.side.value = side; if (!M_restoreDraftText_("reply-" + suffix, form, false) || typeof opt_reply != "undefined") { form.text.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("comment-text-" + suffix); M_setValueFromDivs(divs, form.text); form.text.value += "\n"; if (typeof opt_reply != "undefined") { form.text.value += opt_reply; } if (opt_submit) { M_submitInlineComment(form, cid, lineno, side); return; } } form.text.focus(); hookState.gotoHook(0); return form; } /** * Replies to an inline comment. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @param {String} opt_reply The response to pre-fill with. * @param {Boolean} opt_submit This will submit the comment right after * creation. Only makes sense when opt_reply is set */ function M_replyToInlineComment(author, written_time, cid, lineno, side, opt_reply, opt_submit) { M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side, opt_reply, opt_submit); } /** * Restores a canceled draft inline comment for reply. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_restoreReplyInlineComment(author, written_time, cid, lineno, side) { var form = M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side); var savedDraftKey = "reply-" + cid + "-" + lineno + "-" + side; M_restoreDraftText_(savedDraftKey, form, false); } /** * Updates an inline comment td with the given HTML. * @param {Element} td The TD that contains the inline comment * @param {String} html The text to be put into .innerHTML of the td */ function M_updateInlineComment(td, html) { var tr = M_getParent(td); if (!tr) { alert("TD had no parent. Please notify the app owner."); return; } // The server sends back " " to make things empty, for Safari if (html.length <= 1) { td.innerHTML = ""; M_updateRowHook(tr); } else { td.innerHTML = html; tr.name = "hook"; hookState.updateHooks(); } } /** * Updates a comment tr's name, depending on whether there are now comments * in it or not. Also updates the hook cache if required. Assumes that the * given TR already has name == "hook" and only tries to remove it if all * are empty. * @param {Element} tr The TR containing the potential comments */ function M_updateRowHook(tr) { if (!(tr && tr.cells)) return; // If all of the TR's cells are empty, remove the hook name var i = 0; var numCells = tr.cells.length; for (i = 0; i < numCells; i++) { if (tr.cells[i].innerHTML != "") { break; } } if (i == numCells) { tr.setAttribute("name", ""); hookState.updateHooks(); } hookState.gotoHook(0); } /** * Submits an inline comment and updates the DOM in AJAX fashion with the new * comment data for that line. * @param {Element} form The form containing the submitting comment * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @return true if AJAX fails and the form should be submitted the "old" way, * or false if the form is submitted using AJAX, preventing the regular * form submission from proceeding */ function M_submitInlineComment(form, cid, lineno, side) { var td = null; if (form.side.value == 'a') { td = document.getElementById("old-line-" + form.lineno.value); } else { td = document.getElementById("new-line-" + form.lineno.value); } if (!td) { alert("Could not find snapshot " + form.snapshot.value + "! Please let " + "the app owner know."); return true; } if (typeof side == "undefined") { side = form.side.value; } // Clear saved draft state for affected new, edited, and replied comments if (typeof cid != "undefined" && typeof lineno != "undefined" && side) { var suffix = cid + "-" + lineno + "-" + side; M_clearDraftText_("new-" + lineno + "-" + form.snapshot.value); M_clearDraftText_("edit-" + suffix); M_clearDraftText_("reply-" + suffix); M_hideElement("undo-link-" + suffix); } var httpreq = M_getXMLHttpRequest(); if (!httpreq) { // No AJAX. Oh well. Go ahead and submit this the old way. return true; } // Konqueror jumps to a random location for some reason var scrollTop = M_getScrollTop(window); var aborted = false; reenable_form = function() { form.save.disabled = false; form.cancel.disabled = false; if (form.discard != null) { form.discard.disabled = false; } form.text.disabled = false; form.style.cursor = "auto"; }; // This timeout can potentially race with the request coming back OK. In // general, if it hasn't come back for 60 seconds, it won't ever come back. var httpreq_timeout = setTimeout(function() { aborted = true; httpreq.abort(); reenable_form(); alert("Comment could not be submitted for 60 seconds. Please ensure " + "connectivity (and that the server is up) and try again."); }, 60000); httpreq.onreadystatechange = function () { // Firefox 2.0, at least, runs this with readyState = 4 but all other // fields unset when the timeout aborts the request, against all // documentation. if (httpreq.readyState == 4 && !aborted) { clearTimeout(httpreq_timeout); if (httpreq.status == 200) { M_updateInlineComment(td, httpreq.responseText); } else { reenable_form(); alert("An error occurred while trying to submit the comment: " + httpreq.statusText); } if (M_isKHTML()) { window.scrollTo(0, scrollTop); } } } httpreq.open("POST", base_url + "inline_draft", true); httpreq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var req = []; var len = form.elements.length; for (var i = 0; i < len; i++) { var element = form.elements[i]; if (element.type == "hidden" || element.type == "textarea") { req.push(element.name + "=" + encodeURIComponent(element.value)); } } req.push("side=" + side); // Disable forever. If this succeeds, then the form will end up getting // rewritten, and if it fails, the page should get a refresh anyways. form.save.blur(); form.save.disabled = true; form.cancel.blur(); form.cancel.disabled = true; if (form.discard != null) { form.discard.blur(); form.discard.disabled = true; } form.text.blur(); form.text.disabled = true; form.style.cursor = "wait"; // Send the request httpreq.send(req.join("&")); // No need to resubmit this form. return false; } /** * Removes a draft inline comment. * @param {Element} form The form that contains the comment to be removed * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_removeInlineComment(form, cid, lineno, side) { // Update state to save the canceled edit text var snapshot = side == "a" ? old_snapshot : new_snapshot; var savedDraftKey = "new-" + lineno + "-" + snapshot; var savedText = form.text.value; form.text.value = ""; var ret = M_submitInlineComment(form, cid, lineno, side); M_saveDraftText_(savedDraftKey, savedText); return ret; } /** * Combines all the divs from a single comment (generated by multiple buckets) * and undoes the escaping work done by Django filters, and inserts the result * into a given textarea. * @param {Array} divs An array of div elements to be combined * @param {Element} text The textarea whose value needs to be updated */ function M_setValueFromDivs(divs, text) { var lines = []; var divsLength = divs.length; for (var i = 0; i < divsLength; i++) { lines = lines.concat(divs[i].innerHTML.split("\n")); // It's _fairly_ certain that the last line in the div will be // empty, based on how the template works. If the last line in the // array is empty, then ignore it. if (lines.length > 0 && lines[lines.length - 1] == "") { lines.length = lines.length - 1; } } for (var i = 0; i < lines.length; i++) { // Undo the <a> tags added by urlize and urlizetrunc lines[i] = lines[i].replace(/<a (.*?)href=[\'\"]([^\'\"]+?)[\'\"](.*?)>(.*?)<\/a>/ig, '$2'); // Undo the escape Django filter lines[i] = lines[i].replace(/&gt;/ig, ">"); lines[i] = lines[i].replace(/&lt;/ig, "<"); lines[i] = lines[i].replace(/&quot;/ig, "\""); lines[i] = lines[i].replace(/&#39;/ig, "'"); lines[i] = lines[i].replace(/&amp;/ig, "&"); // Must be last text.value += "> " + lines[i] + "\n"; } } /** * Undo an edit of a draft inline comment, i.e. discard changes. * @param {Element} form The form containing the edits * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_resetAndHideInlineComment(form, cid, lineno, side) { // Update canceled edit state var suffix = cid + "-" + lineno + "-" + side; M_saveDraftText_("edit-" + suffix, form.text.value); if (form.text.value != form.oldtext.value) { M_showElement("undo-link-" + suffix); } form.text.blur(); form.text.value = form.oldtext.value; form.style.display = "none"; var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { if (texts[i].className.indexOf("comment-text-quoted") < 0) { texts[i].style.display = ""; } } var hides = document.getElementsByName("comment-hide-" + suffix); var hidesLength = hides.length; for (var i = 0; i < hidesLength; i++) { hides[i].style.display = ""; } M_showElement("edit-link-" + suffix); hookState.gotoHook(0); } /** * Toggles whether we display quoted text or not, both for inline and regular * comments. Inline comments will have lineno and side defined. * @param {String} cid The comment number * @param {String} bid The bucket number in that comment * @param {String} lineno (optional) Line number of the comment * @param {String} side (optional) 'a' or 'b' */ function M_switchQuotedText(cid, bid, lineno, side) { var tmp = "" if (typeof lineno != 'undefined' && typeof side != 'undefined') tmp = "-" + lineno + "-" + side; var extra = cid + tmp + "-" + bid; var div = document.getElementById("comment-text-" + extra); var a = document.getElementById("comment-hide-link-" + extra); if (div.style.display == "none") { div.style.display = ""; a.innerHTML = "Hide quoted text"; } else { div.style.display = "none"; a.innerHTML = "Show quoted text"; } if (tmp != "") { hookState.gotoHook(0); } } /** * Handler for the double click event in the code table element. Creates a new * inline comment for that line of code on the right side of the diff. * @param {Event} evt The event object for this double-click event */ function M_handleTableDblClick(evt) { if (!logged_in) { if (!login_warned) { login_warned = true; alert("Please sign in to enter inline comments."); } return; } var evt = evt ? evt : (event ? event : null); var target = M_getEventTarget(evt); if (target.tagName == 'INPUT' || target.tagName == 'TEXTAREA') { return; } while (target != null && target.tagName != 'TD') { target = M_getParent(target); } if (target == null) { return; } var side = null; if (target.id.substr(0, 7) == "newcode") { side = 'b'; } else if (target.id.substr(0, 7) == "oldcode") { side = 'a'; } if (side != null) { M_createInlineComment(parseInt(target.id.substr(7)), side); } } var M_timerLongTap = null; /** * Resets the long tap timer iff activated. */ function M_clearTableTouchTimeout() { if (M_timerLongTap) { clearTimeout(M_timerLongTap); } M_timerLongTap = null; } /** * Handles long tap events on mobile devices (touchstart). * * This function activates a 1sec timeout that redirects the event to * M_handleTableDblClick(). */ function M_handleTableTouchStart(evt) { if (evt.touches && evt.touches.length == 1) { // 1 finger touch M_clearTableTouchTimeout(); M_timerLongTap = setTimeout(function() { M_clearTableTouchTimeout(); M_handleTableDblClick(evt); }, 1000); } } /** * Handles touchend event for long taps on mobile devices. */ function M_handleTableTouchEnd(evt) { M_clearTableTouchTimeout(); } /** * Makes all inline comments visible. This is the default view. */ function M_showAllInlineComments() { var hide_elements = document.getElementsByName("hide-all-inline"); var show_elements = document.getElementsByName("show-all-inline"); for (var i = 0; i < hide_elements.length; i++) { hide_elements[i].style.display = ""; } var elements = document.getElementsByName("comment-border"); var elementsLength = elements.length; for (var i = 0; i < elementsLength; i++) { var tr = M_getParent(M_getParent(elements[i])); tr.style.display = ""; tr.name = "hook"; } for (var i = 0; i < show_elements.length; i++) { show_elements[i].style.display = "none"; } hookState.updateHooks(); } /** * Hides all inline comments, to make code easier ot read. */ function M_hideAllInlineComments() { var hide_elements = document.getElementsByName("hide-all-inline"); var show_elements = document.getElementsByName("show-all-inline"); for (var i = 0; i < show_elements.length; i++) { show_elements[i].style.display = ""; } var elements = document.getElementsByName("comment-border"); var elementsLength = elements.length; for (var i = 0; i < elementsLength; i++) { var tr = M_getParent(M_getParent(elements[i])); tr.style.display = "none"; tr.name = ""; } for (var i = 0; i < hide_elements.length; i++) { hide_elements[i].style.display = "none"; } hookState.updateHooks(); } /** * Flips between making inline comments visible and invisible. */ function M_toggleAllInlineComments() { var show_elements = document.getElementsByName("show-all-inline"); if (!show_elements) { return; } if (show_elements[0].style.display == "none") { M_hideAllInlineComments(); } else { M_showAllInlineComments(); } } /** * Navigates to the diff with the requested versions on left/right */ function M_navigateDiff(issueid, filename) { var left = document.getElementById('left').value; var right = document.getElementById('right').value; if (left == '-1') { window.location.href = base_url + issueid + '/diff/' + right + '/' + filename; } else { window.location.href = base_url + issueid + '/diff2/' + left + ':' + right + '/' + filename; } } // File view keyboard navigation /** * M_HookState class. Keeps track of the current 'hook' that we are on and * responds to n/p/N/P events. * @param {Window} win The window that the table is in. * @constructor */ function M_HookState(win) { /** * -2 == top of page; -1 == diff; or index into hooks array * @type Integer */ this.hookPos = -2; /** * A cache of visible table rows with tr.name == "hook" * @type Array */ this.visibleHookCache = []; /** * The indicator element that we move around * @type Element */ this.indicator = document.getElementById("hook-sel"); /** * The element the indicator points to * @type Element */ this.indicated_element = null; /** * Caches whether we are in an IE browser * @type Boolean */ this.isIE = M_isIE(); /** * The window that the table with the hooks is in * @type Window */ this.win = win; } /** * Find all the hook locations in a browser-portable fashion, and store them * in a cache. * @return Array of TR elements. */ M_HookState.prototype.computeHooks_ = function() { var allHooks = null; if (this.isIE) { // IE only recognizes the 'name' attribute on tags that are supposed to // have one, such as... not TR. var tmpHooks = document.getElementsByTagName("TR"); var tmpHooksLength = tmpHooks.length; allHooks = []; for (var i = 0; i < tmpHooksLength; i++) { if (tmpHooks[i].name == "hook") { allHooks.push(tmpHooks[i]); } } } else { allHooks = document.getElementsByName("hook"); } var visibleHooks = []; var allHooksLength = allHooks.length; for (var i = 0; i < allHooksLength; i++) { var hook = allHooks[i]; if (hook.style.display == "") { visibleHooks.push(hook); } } this.visibleHookCache = visibleHooks; return visibleHooks; }; /** * Recompute all the hook positions, update the hookPos, and update the * indicator's position if necessary, but do not scroll. */ M_HookState.prototype.updateHooks = function() { var curHook = null; if (this.indicated_element != null) { curHook = this.indicated_element; } else if (this.hookPos >= 0 && this.hookPos < this.visibleHookCache.length) { curHook = this.visibleHookCache[this.hookPos]; } this.computeHooks_(); var newHookPos = -1; if (curHook != null) { for (var i = 0; i < this.visibleHookCache.length; i++) { if (this.visibleHookCache[i] == curHook) { newHookPos = i; break; } } } if (newHookPos != -1) { this.hookPos = newHookPos; } this.gotoHook(0); }; /** * Update the indicator's position to be at the top of the table row. * @param {Element} tr The tr whose top the indicator will be lined up with. */ M_HookState.prototype.updateIndicator_ = function(tr) { // Find out where the table's top is, and add one so that when we align // the position indicator, it takes off 1px from one tr and 1px from another. // This must be computed every time since the top of the table may move due // to window resizing. var tableTop = M_getPageOffsetTop(document.getElementById("table-top")) + 1; this.indicator.style.top = String(M_getPageOffsetTop(tr) - tableTop) + "px"; var totWidth = 0; var numCells = tr.cells.length; for (var i = 0; i < numCells; i++) { totWidth += tr.cells[i].clientWidth; } this.indicator.style.left = "0px"; this.indicator.style.width = totWidth + "px"; this.indicator.style.display = ""; this.indicated_element = tr; }; /** * Update the indicator's position, and potentially scroll to the proper * location. Computes the new position based on current scroll position, and * whether the previously selected hook was visible. * @param {Integer} direction Scroll direction: -1 for up only, 1 for down only, * 0 for no scrolling. */ M_HookState.prototype.gotoHook = function(direction) { var hooks = this.visibleHookCache; // Hide the current selection image this.indicator.style.display = "none"; this.indicated_element = null; // Add a border to all td's in the selected row if (this.hookPos < -1) { if (direction != 0) { window.scrollTo(0, 0); } this.hookPos = -2; } else if (this.hookPos == -1) { var diffs = document.getElementsByName("diffs"); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (diffs && direction != 0) { window.scrollTo(0, M_getPageOffsetTop(diffs)); } this.updateIndicator_(document.getElementById("thecode").rows[0]); } else { if (this.hookPos < hooks.length) { var hook = hooks[this.hookPos]; for (var i = 0; i < hook.cells.length; i++) { var td = hook.cells[i]; if (td.id != null && td.id != "") { if (direction != 0) { M_scrollIntoView(this.win, td, direction); } break; } } // Found one! this.updateIndicator_(hook); } else { if (direction != 0) { window.scrollTo(0, document.body.offsetHeight); } this.hookPos = hooks.length; var thecode = document.getElementById("thecode"); this.updateIndicator_(thecode.rows[thecode.rows.length - 1]); } } }; /** * Update the indicator and hook position by moving to the next/prev line. * If the target line doesn't have a hook marker, the marker is added. * @param {Integer} direction Scroll direction: -1 for up, 1 for down. */ M_HookState.prototype.gotoLine = function(direction) { var thecode = document.getElementById("thecode").rows; // find current hook and store visible code lines var currHook = this.indicated_element; var hookIdx = -1; var codeRows = new Array(); for (var i=0; i < thecode.length; i++) { if (thecode[i].id.substr(0, 4) == "pair") { codeRows.push(thecode[i]); if (currHook && thecode[i].id == currHook.id) { hookIdx = codeRows.length - 1; } } } if (direction > 0) { if (hookIdx == -1 && this.hookPos == -2) { // not on a hook yet this.incrementHook_(false); this.gotoHook(0); return; } else if (hookIdx == -1 && this.indicated_element.id == "codeBottom") { // about to move off the borders return; } else if (hookIdx == codeRows.length - 1) { // last row window.scrollTo(0, document.body.offsetHeight); this.hookPos = this.visibleHookCache.length; this.updateIndicator_(thecode[thecode.length - 1]); return; } else { hookIdx = Math.min(hookIdx + 1, codeRows.length - 1); } } else { if (hookIdx == -1 && this.hookPos < 0) { // going beyond the top return; } else if (hookIdx == -1) { // we are at the bottom line hookIdx = codeRows.length - 1; } else if (hookIdx == 0) { // we are at the top this.hookPos = -1; this.indicated_element = null; this.gotoHook(-1); return; } else { hookIdx = Math.max(hookIdx - 1, 0); } } var tr = codeRows[hookIdx]; if (tr) { this.updateIndicator_(tr); M_scrollIntoView(this.win, tr, direction); } } /** * Updates hookPos relative to indicated line. * @param {Array} hooks Hook array. * @param {Integer} direction Wether to look for the next or prev element. */ M_HookState.prototype.updateHookPosByIndicator_ = function(hooks, direction) { if (this.indicated_element == null) { return; } else if (this.indicated_element.getAttribute("name") == "hook") { // hookPos is alread a hook return; } var indicatorLine = parseInt(this.indicated_element.id.split("-")[1]); for (var i=0; i < hooks.length; i++) { if (hooks[i].id.substr(0, 4) == "pair" && parseInt(hooks[i].id.split("-")[1]) > indicatorLine) { if (direction > 0) { this.hookPos = i - 1; } else { this.hookPos = i; } return; } } } /** * Set this.hookPos to the next desired hook. * @param {Boolean} findComment Whether to look only for comment hooks */ M_HookState.prototype.incrementHook_ = function(findComment) { var hooks = this.visibleHookCache; if (this.indicated_line) { this.hookPos = this.findClosestHookPos_(hooks); } if (findComment) { this.hookPos = Math.max(0, this.hookPos + 1); while (this.hookPos < hooks.length && hooks[this.hookPos].className != "inline-comments") { this.hookPos++; } } else { this.hookPos = Math.min(hooks.length, this.hookPos + 1); } }; /** * Set this.hookPos to the previous desired hook. * @param {Boolean} findComment Whether to look only for comment hooks */ M_HookState.prototype.decrementHook_ = function(findComment) { var hooks = this.visibleHookCache; if (findComment) { this.hookPos = Math.min(hooks.length - 1, this.hookPos - 1); while (this.hookPos >= 0 && hooks[this.hookPos].className != "inline-comments") { this.hookPos--; } } else { this.hookPos = Math.max(-2, this.hookPos - 1); } }; /** * Find the first document element in sorted array elts whose vertical position * is greater than the given height from the top of the document. Optionally * look only for comment elements. * * @param {Integer} height The height in pixels from the top * @param {Array.<Element>} elts Document elements * @param {Boolean} findComment Whether to look only for comment elements * @return {Integer} The index of such an element, or elts.length otherwise */ function M_findElementAfter_(height, elts, findComment) { for (var i = 0; i < elts.length; ++i) { if (M_getPageOffsetTop(elts[i]) > height) { if (!findComment || elts[i].className == "inline-comments") { return i; } } } return elts.length; } /** * Find the last document element in sorted array elts whose vertical position * is less than the given height from the top of the document. Optionally * look only for comment elements. * * @param {Integer} height The height in pixels from the top * @param {Array.<Element>} elts Document elements * @param {Boolean} findComment Whether to look only for comment elements * @return {Integer} The index of such an element, or -1 otherwise */ function M_findElementBefore_(height, elts, findComment) { for (var i = elts.length - 1; i >= 0; --i) { if (M_getPageOffsetTop(elts[i]) < height) { if (!findComment || elts[i].className == "inline-comments") { return i; } } } return -1; } /** * Move to the next hook indicator and scroll. * @param opt_findComment {Boolean} Whether to look only for comment hooks */ M_HookState.prototype.gotoNextHook = function(opt_findComment) { // If the current hook is not on the page, select the first hook that is // either on the screen or below. var hooks = this.visibleHookCache; this.updateHookPosByIndicator_(hooks, 1); var diffs = document.getElementsByName("diffs"); var thecode = document.getElementById("thecode"); var findComment = Boolean(opt_findComment); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { this.incrementHook_(findComment); } else if (this.hookPos == -2 && (M_isElementVisible(this.win, diffs) || M_getScrollTop(this.win) < M_getPageOffsetTop(diffs))) { this.incrementHook_(findComment) } else if (this.hookPos < hooks.length || (this.hookPos >= hooks.length && !M_isElementVisible( this.win, thecode.rows[thecode.rows.length - 1].cells[0]))) { var scrollTop = M_getScrollTop(this.win); this.hookPos = M_findElementAfter_(scrollTop, hooks, findComment); } this.gotoHook(1); }; /** * Move to the previous hook indicator and scroll. * @param opt_findComment {Boolean} Whether to look only for comment hooks */ M_HookState.prototype.gotoPrevHook = function(opt_findComment) { // If the current hook is not on the page, select the last hook that is // above the bottom of the screen window. var hooks = this.visibleHookCache; this.updateHookPosByIndicator_(hooks, -1); var diffs = document.getElementsByName("diffs"); var findComment = Boolean(opt_findComment); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (this.hookPos == 0 && findComment) { this.hookPos = -2; } else if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { this.decrementHook_(findComment); } else if (this.hookPos > hooks.length) { this.hookPos = hooks.length; } else if (this.hookPos == -1 && M_isElementVisible(this.win, diffs)) { this.decrementHook_(findComment); } else if (this.hookPos == -2 && M_getScrollTop(this.win) == 0) { } else { var scrollBot = M_getScrollTop(this.win) + M_getWindowHeight(this.win); this.hookPos = M_findElementBefore_(scrollBot, hooks, findComment); } // The top of the diffs table is irrelevant if we want comment hooks. if (findComment && this.hookPos <= -1) { this.hookPos = -2; } this.gotoHook(-1); }; /** * If the currently selected hook is a comment, either respond to it or edit * the draft if there is one already. Prefer the right side of the table. */ M_HookState.prototype.respond = function() { if (this.indicated_element && ! this.indicated_element.getAttribute("name") != "hook") { // Turn indicated element into a "real" hook so we can add comments. this.indicated_element.setAttribute("name", "hook") } this.updateHooks(); var hooks = this.visibleHookCache; if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { // Go through this tr and try responding to the last comment. The general // hope is that these are returned in DOM order var comments = hooks[this.hookPos].getElementsByTagName("div"); var commentsLength = comments.length; if (comments && commentsLength == 0) { // Don't give up too early and look a bit forward var sibling = hooks[this.hookPos].nextSibling; while (sibling && sibling.tagName != "TR") { sibling = sibling.nextSibling; } comments = sibling.getElementsByTagName("div"); commentsLength = comments.length; } if (comments && commentsLength > 0) { var last = null; for (var i = commentsLength - 1; i >= 0; i--) { if (comments[i].getAttribute("name") == "comment-border") { last = comments[i]; break; } } if (last) { var links = last.getElementsByTagName("a"); if (links) { for (var i = links.length - 1; i >= 0; i--) { if (links[i].getAttribute("name") == "comment-reply" && links[i].style.display != "none") { document.location.href = links[i].href; return; } } } } } else { // Create a comment at this line // TODO: Implement this in a sane fashion, e.g. opens up a comment // at the end of the diff chunk. var tr = hooks[this.hookPos]; for (var i = tr.cells.length - 1; i >= 0; i--) { if (tr.cells[i].id.substr(0, 7) == "newcode") { M_createInlineComment(parseInt(tr.cells[i].id.substr(7)), 'b'); return; } else if (tr.cells[i].id.substr(0, 7) == "oldcode") { M_createInlineComment(parseInt(tr.cells[i].id.substr(7)), 'a'); return; } } } } }; // Intra-line diff handling /** * IntraLineDiff class. Initializes structures to keep track of highlighting * state. * @constructor */ function M_IntraLineDiff() { /** * Whether we are showing intra-line changes or not * @type Boolean */ this.intraLine = true; /** * "oldreplace" css rule * @type CSSStyleRule */ this.oldReplace = null; /** * "oldlight" css rule * @type CSSStyleRule */ this.oldLight = null; /** * "newreplace" css rule * @type CSSStyleRule */ this.newReplace = null; /** * "newlight" css rule * @type CSSStyleRule */ this.newLight = null; /** * backup of the "oldreplace" css rule's background color * @type DOMString */ this.saveOldReplaceBkgClr = null; /** * backup of the "newreplace" css rule's background color * @type DOMString */ this.saveNewReplaceBkgClr = null; /** * "oldreplace1" css rule's background color * @type DOMString */ this.oldIntraBkgClr = null; /** * "newreplace1" css rule's background color * @type DOMString */ this.newIntraBkgClr = null; this.findStyles_(); } /** * Finds the styles in the document and keeps references to them in this class * instance. */ M_IntraLineDiff.prototype.findStyles_ = function() { var ss = document.styleSheets[0]; var rules = []; if (ss.cssRules) { rules = ss.cssRules; } else if (ss.rules) { rules = ss.rules; } for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (rule.selectorText == ".oldreplace1") { this.oldIntraBkgClr = rule.style.backgroundColor; } else if (rule.selectorText == ".newreplace1") { this.newIntraBkgClr = rule.style.backgroundColor; } else if (rule.selectorText == ".oldreplace") { this.oldReplace = rule; this.saveOldReplaceBkgClr = this.oldReplace.style.backgroundColor; } else if (rule.selectorText == ".newreplace") { this.newReplace = rule; this.saveNewReplaceBkgClr = this.newReplace.style.backgroundColor; } else if (rule.selectorText == ".oldlight") { this.oldLight = rule; } else if (rule.selectorText == ".newlight") { this.newLight = rule; } } }; /** * Toggle the highlighting of the intra line diffs, alternatively turning * them on and off. */ M_IntraLineDiff.prototype.toggle = function() { if (this.intraLine) { this.oldReplace.style.backgroundColor = this.oldIntraBkgClr; this.oldLight.style.backgroundColor = this.oldIntraBkgClr; this.newReplace.style.backgroundColor = this.newIntraBkgClr; this.newLight.style.backgroundColor = this.newIntraBkgClr; this.intraLine = false; } else { this.oldReplace.style.backgroundColor = this.saveOldReplaceBkgClr; this.oldLight.style.backgroundColor = this.saveOldReplaceBkgClr; this.newReplace.style.backgroundColor = this.saveNewReplaceBkgClr; this.newLight.style.backgroundColor = this.saveNewReplaceBkgClr; this.intraLine = true; } }; /** * A click handler common to just about every page, set in global.html. * @param {Event} evt The event object that triggered this handler. * @return false if the event was handled. */ function M_clickCommon(evt) { if (helpDisplayed) { var help = document.getElementById("help"); help.style.display = "none"; helpDisplayed = false; return false; } return true; } /** * Get a name for key combination of keydown event. * * See also http://unixpapa.com/js/key.html */ function M_getKeyName(evt) { var name = ""; if (evt.ctrlKey) { name += "Ctrl-" } if (evt.altKey) { name += "Alt-" } if (evt.shiftKey) { name += "Shift-" } if (evt.metaKey) { name += "Meta-" } // Character keys have codes of corresponding ASCII symbols if (evt.keyCode >= 65 && evt.keyCode <= 90) { return name + String.fromCharCode(evt.keyCode); } // Numeric keys seems to have codes of corresponding ASCII symbols too if (evt.keyCode >= 48 && evt.keyCode <= 57) { return name + String.fromCharCode(evt.keyCode); } // Handling special keys switch (evt.keyCode) { case 27: return name + "Esc"; case 13: return name + "Enter"; case 188: return name + ","; // [,<] case 190: return name + "."; // [.>] case 191: return name + "/"; // [/?] case 38: return name + "ArrowUp"; case 40: return name + "ArrowDown"; case 17: // Ctrl case 18: // Alt case 16: // Shift // case ??: Meta ? return name.substr(0, name.lenght-1); default: name += "<"+evt.keyCode+">"; } return name; } /** * Common keydown handler for all pages. * @param {Event} evt The event object that triggered this callback * @param {function(string)} handler Handles the specific key name; * returns false if the key was handled. * @param {function(Event, Node, int, string)} input_handler * Handles the event in case that the event source is an input field. * returns false if the key press was handled. * @return false if the event was handled */ function M_keyDownCommon(evt, handler, input_handler) { if (!evt) var evt = window.event; // for IE var target = M_getEventTarget(evt); var keyName = M_getKeyName(evt); if (target.nodeName == "TEXTAREA" || target.nodeName == "INPUT") { if (input_handler) { return input_handler(target, keyName); } return true; } if (keyName == 'Shift-/' /* '?' */ || keyName == 'Esc') { var help = document.getElementById("help"); if (help) { // Only allow the help to be turned on with the ? key. if (helpDisplayed || keyName == 'Shift-/') { helpDisplayed = !helpDisplayed; help.style.display = helpDisplayed ? "" : "none"; return false; } } return true; } return handler(keyName); } /** * Helper event handler for the keydown event in a comment textarea. * @param {Event} evt The event object that triggered this callback * @param {Node} src The textarea document element * @param {String} key The string with combination name * @return false if the event was handled */ function M_commentTextKeyDown_(src, key) { if (src.nodeName == "TEXTAREA") { if (key == 'Ctrl-S') { // Save the form corresponding to this text area. M_disableCarefulUnload(); if (src.form.save.onclick) { return src.form.save.onclick(); } else { src.form.submit(); return false; } } if (key == 'Esc') { if (src.getAttribute('id') == draftMessage.id_textarea) { draftMessage.dialog_hide(true); src.blur(); return false; } else { // textarea of inline comment return src.form.cancel.onclick(); } } } return true; } /** * Helper to find an item by its elementId and jump to it. If the item * cannot be found this will jump to the changelist instead. * @param {elementId} the id of an element an href */ function M_jumpToHrefOrChangelist(elementId) { var hrefElement = document.getElementById(elementId); if (hrefElement) { document.location.href = hrefElement.href; } else { M_upToChangelist(); } } /** * Event handler for the keydown event in the file view. * @param {Event} evt The event object that triggered this callback * @return false if the event was handled */ function M_keyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'N') { // next diff if (hookState) hookState.gotoNextHook(); } else if (key == 'P') { // previous diff if (hookState) hookState.gotoPrevHook(); } else if (key == 'Shift-N') { // next comment if (hookState) hookState.gotoNextHook(true); } else if (key == 'Shift-P') { // previous comment if (hookState) hookState.gotoPrevHook(true); } else if (key == 'ArrowDown') { if (hookState) hookState.gotoLine(1); } else if (key == 'ArrowUp') { if (hookState) hookState.gotoLine(-1); } else if (key == 'J') { // next file M_jumpToHrefOrChangelist('nextFile') } else if (key == 'K') { // prev file M_jumpToHrefOrChangelist('prevFile') } else if (key == 'Shift-J') { // next file with comment M_jumpToHrefOrChangelist('nextFileWithComment') } else if (key == 'Shift-K') { // prev file with comment M_jumpToHrefOrChangelist('prevFileWithComment') } else if (key == 'M') { document.location.href = publish_link; } else if (key == 'Shift-M') { if (draftMessage) { draftMessage.dialog_show(); } } else if (key == 'U') { // up to CL M_upToChangelist(); } else if (key == 'I') { // toggle intra line diff if (intraLineDiff) intraLineDiff.toggle(); } else if (key == 'S') { // toggle show/hide inline comments M_toggleAllInlineComments(); } else if (key == 'E') { M_expandAllInlineComments(); } else if (key == 'C') { M_collapseAllInlineComments(); } else if (key == 'Enter') { // respond to current comment if (hookState) hookState.respond(); } else { return true; } return false; }, M_commentTextKeyDown_); } /** * Event handler for the keydown event in the changelist (issue) view. * @param {Event} evt The event object that triggered this callback * @return false if the event was handled */ function M_changelistKeyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'O' || key == 'Enter') { if (dashboardState) { var child = dashboardState.curTR.cells[3].firstChild; while (child && child.nextSibling && child.nodeName != "A") { child = child.nextSibling; } if (child && child.nodeName == "A") { location.href = child.href; } } } else if (key == 'I') { if (dashboardState) { var child = dashboardState.curTR.cells[2].firstChild; while (child && child.nextSibling && (child.nodeName != "A" || child.style.display == "none")) { child = child.nextSibling; } if (child && child.nodeName == "A") { location.href = child.href; } } } else if (key == 'K') { if (dashboardState) dashboardState.gotoPrev(); } else if (key == 'J') { if (dashboardState) dashboardState.gotoNext(); } else if (key == 'M') { document.location.href = publish_link; } else if (key == 'U') { // back to dashboard document.location.href = base_url; } else { return true; } return false; }); } /** * Goes from the file view back up to the changelist view. */ function M_upToChangelist() { var upCL = document.getElementById('upCL'); if (upCL) { document.location.href = upCL.href; } } /** * Asynchronously request static analysis warnings as comments. * @param {String} cl The current changelist * @param {String} depot_path The id of the target element * @param {String} a The version number of the left side to be analyzed * @param {String} b The version number of the right side to be analyzed */ function M_getBugbotComments(cl, depot_path, a, b) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return; } // Konqueror jumps to a random location for some reason var scrollTop = M_getScrollTop(window); httpreq.onreadystatechange = function () { // Firefox 2.0, at least, runs this with readyState = 4 but all other // fields unset when the timeout aborts the request, against all // documentation. if (httpreq.readyState == 4) { if (httpreq.status == 200) { M_updateWarningStatus(httpreq.responseText); } if (M_isKHTML()) { window.scrollTo(0, scrollTop); } } } httpreq.open("GET", base_url + "warnings/" + cl + "/" + depot_path + "?a=" + a + "&b=" + b, true); httpreq.send(null); } /** * Updates a warning status td with the given HTML. * @param {String} result The new html to replace the existing content */ function M_updateWarningStatus(result) { var elem = document.getElementById("warnings"); elem.innerHTML = result; if (hookState) hookState.updateHooks(); } /* Ripped off from Caribou */ var M_CONFIRM_DISCARD_NEW_MSG = "Your draft comment has not been saved " + "or sent.\n\nDiscard your comment?"; var M_useCarefulUnload = true; /** * Return an alert if the specified textarea is visible and non-empty. */ function M_carefulUnload(text_area_id) { return function () { var text_area = document.getElementById(text_area_id); if (!text_area) return; var text_parent = M_getParent(text_area); if (M_useCarefulUnload && text_area.style.display != "none" && text_parent.style.display != "none" && goog.string.trim(text_area.value)) { return M_CONFIRM_DISCARD_NEW_MSG; } }; } function M_disableCarefulUnload() { M_useCarefulUnload = false; } // History Table /** * Toggles visibility of the snapshots that belong to the given parent. * @param {String} parent The parent's index * @param {Boolean} opt_show If present, whether to show or hide the group */ function M_toggleGroup(parent, opt_show) { var children = M_historyChildren[parent]; if (children.length == 1) { // No children. return; } var show = (typeof opt_show != "undefined") ? opt_show : (document.getElementById("history-" + children[1]).style.display != ""); for (var i = 1; i < children.length; i++) { var child = document.getElementById("history-" + children[i]); child.style.display = show ? "" : "none"; } var arrow = document.getElementById("triangle-" + parent); if (arrow) { arrow.className = "triangle-" + (show ? "open" : "closed"); } } /** * Makes the given groups visible. * @param {Array.<Number>} parents The indexes of the parents of the groups * to show. */ function M_expandGroups(parents) { for (var i = 0; i < parents.length; i++) { M_toggleGroup(parents[i], true); } document.getElementById("history-expander").style.display = "none"; document.getElementById("history-collapser").style.display = ""; } /** * Hides the given parents, except for groups that contain the * selected radio buttons. * @param {Array.<Number>} parents The indexes of the parents of the groups * to hide. */ function M_collapseGroups(parents) { // Find the selected snapshots var parentsToLeaveOpen = {}; var form = document.getElementById("history-form"); var formLength = form.a.length; for (var i = 0; i < formLength; i++) { if (form.a[i].checked || form.b[i].checked) { var element = "history-" + form.a[i].value; var name = document.getElementById(element).getAttribute("name"); if (name != "parent") { // The name of a child is "parent-%d" % parent_index. var parentIndex = Number(name.match(/parent-(\d+)/)[1]); parentsToLeaveOpen[parentIndex] = true; } } } // Collapse the parents we need to collapse. for (var i = 0; i < parents.length; i++) { if (!(parents[i] in parentsToLeaveOpen)) { M_toggleGroup(parents[i], false); } } document.getElementById("history-expander").style.display = ""; document.getElementById("history-collapser").style.display = "none"; } /** * Expands the reverted files section of the files list in the changelist view. * * @param {String} tableid The id of the table element that contains hidden TR's * @param {String} hide The id of the element to hide after this is completed. */ function M_showRevertedFiles(tableid, hide) { var table = document.getElementById(tableid); if (!table) return; var rowsLength = table.rows.length; for (var i = 0; i < rowsLength; i++) { var row = table.rows[i]; if (row.getAttribute("name") == "afile") row.style.display = ""; } if (dashboardState) dashboardState.initialize(); var h = document.getElementById(hide); if (h) h.style.display = "none"; } // Undo draft cancel /** * An associative array mapping keys that identify inline comments to draft * text values. * New inline comments have keys 'new-lineno-snapshot_id' * Edit inline comments have keys 'edit-cid-lineno-side' * Reply inline comments have keys 'reply-cid-lineno-side' * @type Object */ var M_savedInlineDrafts = new Object(); /** * Saves draft text from a form. * @param {String} draftKey The key identifying the saved draft text * @param {String} text The draft text to be saved */ function M_saveDraftText_(draftKey, text) { M_savedInlineDrafts[draftKey] = text; } /** * Clears saved draft text. Does nothing with an invalid key. * @param {String} draftKey The key identifying the saved draft text */ function M_clearDraftText_(draftKey) { delete M_savedInlineDrafts[draftKey]; } /** * Restores saved draft text to a form. Does nothing with an invalid key. * @param {String} draftKey The key identifying the saved draft text * @param {Element} form The form that contains the comment to be restored * @param {Element} opt_selectAll Whether the restored text should be selected. * True by default. * @return {Boolean} true if we found a saved draft and false otherwise */ function M_restoreDraftText_(draftKey, form, opt_selectAll) { if (M_savedInlineDrafts[draftKey]) { form.text.value = M_savedInlineDrafts[draftKey]; if (typeof opt_selectAll == 'undefined' || opt_selectAll) { form.text.select(); } return true; } return false; } // Dashboard CL navigation /** * M_DashboardState class. Keeps track of the current position of * the selector on the dashboard, and moves it on keydown. * @param {Window} win The window that the dashboard table is in. * @param {String} trName The name of TRs that we will move between. * @param {String} cookieName The cookie name to store the marker position into. * @constructor */ function M_DashboardState(win, trName, cookieName) { /** * The position of the marker, 0-indexed into the trCache array. * @ype Integer */ this.trPos = 0; /** * The current TR object that the marker is pointing at. * @type Element */ this.curTR = null; /** * Array of tr rows that we are moving between. Computed once (updateable). * @type Array */ this.trCache = []; /** * The window that the table is in, used for positioning information. * @type Window */ this.win = win; /** * The expected name of tr's that we are going to cache. * @type String */ this.trName = trName; /** * The name of the cookie value where the marker position is stored. * @type String */ this.cookieName = cookieName; this.initialize(); } /** * Initializes the clCache array, and moves the marker into the first position. */ M_DashboardState.prototype.initialize = function() { var filter = function(arr, lambda) { var ret = []; var arrLength = arr.length; for (var i = 0; i < arrLength; i++) { if (lambda(arr[i])) { ret.push(arr[i]); } } return ret; }; var cache; if (M_isIE()) { // IE does not recognize the 'name' attribute on TR tags cache = filter(document.getElementsByTagName("TR"), function (elem) { return elem.name == this.trName; }); } else { cache = document.getElementsByName(this.trName); } this.trCache = filter(cache, function (elem) { return elem.style.display != "none"; }); if (document.cookie && this.cookieName) { cookie_values = document.cookie.split(";"); for (var i=0; i<cookie_values.length; i++) { name = cookie_values[i].split("=")[0].replace(/ /g, ''); if (name == this.cookieName) { pos = cookie_values[i].split("=")[1]; /* Make sure that the saved position is valid. */ if (pos > this.trCache.length-1) { pos = 0; } this.trPos = pos; } } } this.goto_(0); } /** * Moves the cursor to the curCL position, and potentially scrolls the page to * bring the cursor into view. * @param {Integer} direction Positive for scrolling down, negative for * scrolling up, and 0 for no scrolling. */ M_DashboardState.prototype.goto_ = function(direction) { var oldTR = this.curTR; if (oldTR) { oldTR.cells[0].firstChild.style.visibility = "hidden"; } this.curTR = this.trCache[this.trPos]; this.curTR.cells[0].firstChild.style.visibility = ""; if (this.cookieName) { document.cookie = this.cookieName+'='+this.trPos; } if (!M_isElementVisible(this.win, this.curTR)) { M_scrollIntoView(this.win, this.curTR, direction); } } /** * Moves the cursor up one. */ M_DashboardState.prototype.gotoPrev = function() { if (this.trPos > 0) this.trPos--; this.goto_(-1); } /** * Moves the cursor down one. */ M_DashboardState.prototype.gotoNext = function() { if (this.trPos < this.trCache.length - 1) this.trPos++; this.goto_(1); } /** * Event handler for dashboard hot keys. Dispatches cursor moves, as well as * opening CLs. */ function M_dashboardKeyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'K') { if (dashboardState) dashboardState.gotoPrev(); } else if (key == 'J') { if (dashboardState) dashboardState.gotoNext(); } else if (key == 'Shift-3' /* '#' */) { if (dashboardState) { var child = dashboardState.curTR.cells[1].firstChild; while (child && child.className != "issue-close") { child = child.nextSibling; } if (child) { child = child.firstChild; } while (child && child.nodeName != "A") { child = child.nextSibling; } if (child) { location.href = child.href; } } } else if (key == 'O' || key == 'Enter') { if (dashboardState) { var child = dashboardState.curTR.cells[2].firstChild; while (child && child.nodeName != "A") { child = child.firstChild; } if (child) { location.href = child.href; } } } else { return true; } return false; }); } /** * Helper to fill a table cell element. * @param {Array} attrs An array of attributes to be applied * @param {String} text The content of the table cell * @return {Element} */ function M_fillTableCell_(attrs, text) { var td = document.createElement("td"); for (var j=0; j<attrs.length; j++) { if (attrs[j][0] == "class" && M_isIE()) { td.setAttribute("className", attrs[j][1]); } else { td.setAttribute(attrs[j][0], attrs[j][1]); } } if (!text) text = ""; if (M_isIE()) { td.innerText = text; } else { td.textContent = text; } return td; } /* * Function to request more context between diff chunks. * See _ShortenBuffer() in codereview/engine.py. */ function M_expandSkipped(id_before, id_after, where, id_skip) { links = document.getElementById('skiplinks-'+id_skip).getElementsByTagName('a'); for (var i=0; i<links.length; i++) { links[i].href = '#skiplinks-'+id_skip; } tr = document.getElementById('skip-'+id_skip); var httpreq = M_getXMLHttpRequest(); if (!httpreq) { html = '<td colspan="2" style="text-align: center;">'; html = html + 'Failed to retrieve additional lines. '; html = html + 'Please update your context settings.'; html = html + '</td>'; tr.innerHTML = html; } document.getElementById('skiploading-'+id_skip).style.visibility = 'visible'; var context_select = document.getElementById('id_context'); var context = null; if (context_select) { context = context_select.value; } aborted = false; httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && !aborted) { if (httpreq.status == 200) { response = eval('('+httpreq.responseText+')'); var last_row = null; for (var i=0; i<response.length; i++) { var data = response[i]; var row = document.createElement("tr"); for (var j=0; j<data[0].length; j++) { if (data[0][j][0] == "class" && M_isIE()) { row.setAttribute("className", data[0][j][1]); } else { row.setAttribute(data[0][j][0], data[0][j][1]); } } if ( where == 't' || where == 'a') { tr.parentNode.insertBefore(row, tr); } else { if (last_row) { tr.parentNode.insertBefore(row, last_row.nextSibling); } else { tr.parentNode.insertBefore(row, tr.nextSibling); } } var left = M_fillTableCell_(data[1][0][0], data[1][0][1]); var right = M_fillTableCell_(data[1][1][0], data[1][1][1]); row.appendChild(left); row.appendChild(right); last_row = row; } var curr = document.getElementById('skipcount-'+id_skip); var new_count = parseInt(curr.innerHTML)-response.length/2; if ( new_count > 0 ) { if ( where == 'b' ) { var new_before = id_before; var new_after = id_after-response.length/2; } else { var new_before = id_before+response.length/2; var new_after = id_after; } curr.innerHTML = new_count; html = ''; if ( new_count > 3*context ) { html += '<a href="javascript:M_expandSkipped('+new_before; html += ','+new_after+',\'t\', '+id_skip+');">'; html += 'Expand '+context+' before'; html += '</a> | '; } html += '<a href="javascript:M_expandSkipped('+new_before; html += ','+new_after+',\'a\','+id_skip+');">Expand all</a>'; if ( new_count > 3*context ) { var val = parseInt(new_after); html += ' | <a href="javascript:M_expandSkipped('+new_before; html += ','+val+',\'b\','+id_skip+');">'; html += 'Expand '+context+' after'; html += '</a>'; } document.getElementById('skiplinks-'+(id_skip)).innerHTML = html; var loading_node = document.getElementById('skiploading-'+id_skip); loading_node.style.visibility = 'hidden'; } else { tr.parentNode.removeChild(tr); } hookState.updateHooks(); if (hookState.hookPos != -2 && M_isElementVisible(window, hookState.indicator)) { // Restore indicator position on screen, but only if the indicator // is visible. We don't know if we have to scroll up or down to // make the indicator visible. Therefore the current hook is // internally set to the previous hook and // then gotoNextHook() does everything needed to end up with a // clean hookState and the indicator visible on screen. hookState.hookPos = hookState.hookPos - 1; hookState.gotoNextHook(); } } else { msg = '<td colspan="2" align="center"><span style="color:red;">'; msg += 'An error occurred ['+httpreq.status+']. '; msg += 'Please report.'; msg += '</span></td>'; tr.innerHTML = msg; } } } colwidth = document.getElementById('id_column_width').value; url = skipped_lines_url+id_before+'/'+id_after+'/'+where+'/'+colwidth; if (context) { url += '?context='+context; } httpreq.open('GET', url, true); httpreq.send(''); } /** * Finds the element position. */ function M_getElementPosition(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; } /** * Position the user info popup according to the mouse event coordinates */ function M_positionUserInfoPopup(obj, userPopupDiv) { pos = M_getElementPosition(obj); userPopupDiv.style.left = pos[0] + "px"; userPopupDiv.style.top = pos[1] + 20 + "px"; } /** * Brings up user info popup using ajax */ function M_showUserInfoPopup(obj) { var DIV_ID = "userPopupDiv"; var userPopupDiv = document.getElementById(DIV_ID); var url = obj.getAttribute("href") var index = url.indexOf("/user/"); var user_key = url.substring(index + 6); if (!userPopupDiv) { var userPopupDiv = document.createElement("div"); userPopupDiv.className = "popup"; userPopupDiv.id = DIV_ID; userPopupDiv.filter = 'alpha(opacity=85)'; userPopupDiv.opacity = '0.85'; userPopupDiv.innerHTML = ""; userPopupDiv.onmouseout = function() { userPopupDiv.style.visibility = 'hidden'; } document.body.appendChild(userPopupDiv); } M_positionUserInfoPopup(obj, userPopupDiv); var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } var aborted = false; var httpreq_timeout = setTimeout(function() { aborted = true; httpreq.abort(); }, 5000); httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && !aborted) { clearTimeout(httpreq_timeout); if (httpreq.status == 200) { userPopupDiv = document.getElementById(DIV_ID); userPopupDiv.innerHTML=httpreq.responseText; userPopupDiv.style.visibility = "visible"; } else { //Better fail silently here because it's not //critical functionality } } } httpreq.open("GET", base_url + "user_popup/" + user_key, true); httpreq.send(null); obj.onmouseout = function() { aborted = true; userPopupDiv.style.visibility = 'hidden'; obj.onmouseout = null; } } /** * TODO(jiayao,andi): docstring */ function M_showPopUp(obj, id) { var popup = document.getElementById(id); var pos = M_getElementPosition(obj); popup.style.left = pos[0]+'px'; popup.style.top = pos[1]+20+'px'; popup.style.visibility = 'visible'; obj.onmouseout = function() { popup.style.visibility = 'hidden'; obj.onmouseout = null; } } /** * Jump to a patch in the changelist. * @param {Element} select The select form element. * @param {Integer} issue The issue id. * @param {Integer} patchset The patchset id. * @param {Boolean} unified If True show unified diff else s-b-s view. * @param {String} opt_part The type of diff to jump to -- diff/diff2/patch */ function M_jumpToPatch(select, issue, patchset, unified, opt_part) { var part = opt_part; if (!part) { if (unified) { part = 'patch'; } else { part = 'diff'; } } var url = base_url+issue+'/'+part+'/'+patchset+'/'+select.value; var context = document.getElementById('id_context'); var colwidth = document.getElementById('id_column_width'); if (context && colwidth) { url = url+'?context='+context.value+'&column_width='+colwidth.value; } document.location.href = url; } /** * Add or remove a star to/from the given issue. * @param {Integer} id The issue id. * @param {String} url The url fragment to append: "/star" or "/unstar". */ function M_setIssueStar_(id, url) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status == 200) { var elem = document.getElementById("issue-star-" + id); elem.innerHTML = httpreq.responseText; } } } httpreq.open("POST", base_url + id + url, true); httpreq.send("xsrf_token=" + xsrfToken); } /** * Add a star to the given issue. * @param {Integer} id The issue id. */ function M_addIssueStar(id) { return M_setIssueStar_(id, "/star"); } /** * Remove the star from the given issue. * @param {Integer} id The issue id. */ function M_removeIssueStar(id) { return M_setIssueStar_(id, "/unstar"); } /** * Close a given issue. * @param {Integer} id The issue id. */ function M_closeIssue(id) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status == 200) { var elem = document.getElementById("issue-close-" + id); elem.innerHTML = ''; var elem = document.getElementById("issue-title-" + id); elem.innerHTML += ' (' + httpreq.responseText + ')'; } } } httpreq.open("POST", base_url + id + "/close", true); httpreq.send("xsrf_token=" + xsrfToken); } /** * Generic callback when page is unloaded. */ function M_unloadPage() { if (draftMessage) { draftMessage.save(); } } /** * Draft message dialog class. * @param {Integer} issue_id ID of current issue. * @param {Boolean} headless If true, the dialog is not initialized (default: false). */ var draftMessage = null; function M_draftMessage(issue_id, headless) { this.issue_id = issue_id; this.id_dlg_container = 'reviewmsgdlg'; this.id_textarea = 'reviewmsg'; this.id_hidden = 'reviewmsgorig'; this.id_status = 'reviewmsgstatus'; this.is_modified = false; if (! headless) { this.initialize(); } } /** * Constructor. * Sets keydown callback and loads draft message if any. */ M_draftMessage.prototype.initialize = function() { this.load(); } /** * Shows the dialog and focusses on textarea. */ M_draftMessage.prototype.dialog_show = function() { dlg = this.get_dialog_(); dlg.style.display = ""; this.set_status(''); textarea = document.getElementById(this.id_textarea); textarea.focus(); } /** * Hides the dialog and optionally saves the current content. * @param {Boolean} save If true, the content is saved. */ M_draftMessage.prototype.dialog_hide = function(save) { if (save) { this.save(); } dlg = this.get_dialog_(); dlg.style.display = "none"; } /** * Discards draft message. */ M_draftMessage.prototype.dialog_discard = function() { this.discard(function(response) { draftMessage.set_status('OK'); textarea = document.getElementById(draftMessage.id_textarea); textarea.value = ''; }); return false; } /** * Saves the content without closing the dialog. */ M_draftMessage.prototype.dialog_save = function() { this.set_status(''); textarea = document.getElementById(this.id_textarea); this.save(function(response) { if (response.status != 200) { draftMessage.set_status('An error occurred.'); } else { draftMessage.set_status('Message saved.'); } textarea.focus(); return false; }); return false; } /** * Sets a status message in the dialog. * Additionally a timeout function is created to hide the message again. * @param {String} msg The message to display. */ M_draftMessage.prototype.set_status = function(msg) { var statusSpan = document.getElementById(this.id_status); if (statusSpan) { statusSpan.innerHTML = msg; if (msg) { this.status_timeout = setTimeout(function() { draftMessage.set_status(''); }, 3000); } } } /** * Saves the content of the draft message. * @param {Function} cb A function called with the response object. */ M_draftMessage.prototype.save = function(cb) { textarea = document.getElementById(this.id_textarea); hidden = document.getElementById(this.id_hidden); if (textarea == null || textarea.value == hidden.value || textarea.value == "") { return; } text = textarea.value; var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && cb) { /* XXX set hidden before cb */ hidden = document.getElementById(draftMessage.id_hidden); hidden.value = text; cb(httpreq); } } httpreq.open("POST", base_url + this.issue_id + "/draft_message", true); httpreq.send("reviewmsg="+encodeURIComponent(text)); } /** * Loads the content of the draft message from the datastore. */ M_draftMessage.prototype.load = function() { elem = document.getElementById(this.id_textarea); elem.disabled = "disabled"; this.set_status("Loading..."); if (elem) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status != 200) { draftMessage.set_status('An error occurred.'); } else { if (elem) { elem.value = httpreq.responseText; hidden = document.getElementById(draftMessage.id_hidden); hidden.value = elem.value; } } elem.removeAttribute("disabled"); draftMessage.set_status(''); elem.focus(); } } httpreq.open("GET", base_url + this.issue_id + "/draft_message", true); httpreq.send(""); } } /** * Discards the draft message. * @param {Function} cb A function called with response object. */ M_draftMessage.prototype.discard = function(cb) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && cb) { elem = document.getElementById(this.id_textarea); if (elem) { elem.value = ""; hidden = document.getElementById(this.id_hidden); hidden.value = elem.value; } cb(httpreq); } } httpreq.open("DELETE", base_url + this.issue_id + "/draft_message", true); httpreq.send(""); } /** * Helper function that returns the dialog's HTML container. */ M_draftMessage.prototype.get_dialog_ = function() { return document.getElementById(this.id_dlg_container); }
JavaScript
/* * Autocomplete - jQuery plugin 1.0.2 * * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ * */ ;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v; } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if ( !value ) { return [""]; } var words = value.split( options.multipleSeparator ); var result = []; $.each(words, function(i, value) { if ( $.trim(value) ) result[i] = $.trim(value); }); return result; } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else $input.val( "" ); } } ); } if (wasVisible) // position cursor at end of input field $.Autocompleter.Selection(input, input.value.length, input.value.length); }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.Autocompleter.Selection = function(field, start, end) { if( field.createTextRange ){ var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } else if( field.setSelectionRange ){ field.setSelectionRange(start, end); } else { if( field.selectionStart ){ field.selectionStart = start; field.selectionEnd = end; } } field.focus(); }; })(jQuery);
JavaScript
/** * Ajax Queue Plugin * * Homepage: http://jquery.com/plugins/project/ajaxqueue * Documentation: http://docs.jquery.com/AjaxQueue */ /** <script> $(function(){ jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); }); </script> <ul style="position: absolute; top: 5px; right: 5px;"></ul> */ /* * Queued Ajax requests. * A new Ajax request won't be started until the previous queued * request has finished. */ /* * Synced Ajax requests. * The Ajax request will happen as soon as you call this method, but * the callbacks (success/error/complete) won't fire until all previous * synced requests have been completed. */ (function($) { var ajax = $.ajax; var pendingRequests = {}; var synced = []; var syncedData = []; $.ajax = function(settings) { // create settings for compatibility with ajaxSetup settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); var port = settings.port; switch(settings.mode) { case "abort": if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return pendingRequests[port] = ajax.apply(this, arguments); case "queue": var _old = settings.complete; settings.complete = function(){ if ( _old ) _old.apply( this, arguments ); jQuery([ajax]).dequeue("ajax" + port );; }; jQuery([ ajax ]).queue("ajax" + port, function(){ ajax( settings ); }); return; case "sync": var pos = synced.length; synced[ pos ] = { error: settings.error, success: settings.success, complete: settings.complete, done: false }; syncedData[ pos ] = { error: [], success: [], complete: [] }; settings.error = function(){ syncedData[ pos ].error = arguments; }; settings.success = function(){ syncedData[ pos ].success = arguments; }; settings.complete = function(){ syncedData[ pos ].complete = arguments; synced[ pos ].done = true; if ( pos == 0 || !synced[ pos-1 ] ) for ( var i = pos; i < synced.length && synced[i].done; i++ ) { if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); synced[i] = null; syncedData[i] = null; } }; } return ajax.apply(this, arguments); }; })(jQuery);
JavaScript
/************************************************************************** ****************** SF MENU ********************************** ***************************************************************************/ /* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show',height:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery); /* * Supersubs v0.2b - jQuery plugin * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of * their longest list item children. If you use this, please expect bugs and report them * to the jQuery Google Group with the word 'Superfish' in the subject line. * */ ;(function($){ // $ will refer to jQuery within this closure $.fn.supersubs = function(options){ var opts = $.extend({}, $.fn.supersubs.defaults, options); // return original object to support chaining return this.each(function() { // cache selections var $$ = $(this); // support metadata var o = $.meta ? $.extend({}, opts, $$.data()) : opts; // get the font size of menu. // .css('fontSize') returns various results cross-browser, so measure an em dash instead var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({ 'padding' : 0, 'position' : 'absolute', 'top' : '-999em', 'width' : 'auto' }).appendTo($$).width(); //clientWidth is faster, but was incorrect here // remove em dash $('#menu-fontsize').remove(); // cache all ul elements $ULs = $$.find('ul'); // loop through each ul in menu $ULs.each(function(i) { // cache this ul var $ul = $ULs.eq(i); // get all (li) children of this ul var $LIs = $ul.children(); // get all anchor grand-children var $As = $LIs.children('a'); // force content to one line and save current float property var liFloat = $LIs.css('white-space','nowrap').css('float'); // remove width restrictions and floats so elements remain vertically stacked var emWidth = $ul.add($LIs).add($As).css({ 'float' : 'none', 'width' : 'auto' }) // this ul will now be shrink-wrapped to longest li due to position:absolute // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer .end().end()[0].clientWidth / fontsize; // add more width to ensure lines don't turn over at certain sizes in various browsers emWidth += o.extraWidth; // restrict to at least minWidth and at most maxWidth if (emWidth > o.maxWidth) { emWidth = o.maxWidth; } else if (emWidth < o.minWidth) { emWidth = o.minWidth; } emWidth += 'em'; // set ul to width in ems $ul.css('width',emWidth); // restore li floats to avoid IE bugs // set li width to full width of this ul // revert white-space to normal $LIs.css({ 'float' : liFloat, 'width' : '100%', 'white-space' : 'normal' }) // update offset position of descendant ul to reflect new width of parent .each(function(){ var $childUl = $('>ul',this); var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right'; $childUl.css(offsetDirection,emWidth); }); }); }); }; // expose defaults $.fn.supersubs.defaults = { minWidth : 9, // requires em unit. maxWidth : 25, // requires em unit. extraWidth : 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values }; })(jQuery); // plugin code ends jQuery(document).ready(function(){ jQuery("ul.sf-menu").supersubs({ minWidth: 10, // minimum width of sub-menus in em units maxWidth: 45, // maximum width of sub-menus in em units extraWidth: 1 // extra width can ensure lines don't sometimes turn over // due to slight rounding differences and font-family }).superfish(); // call supersubs first, then superfish, so that subs are // not display:none when measuring. Call before initialising // containing tabs for same reason. });
JavaScript
(function($){ /* hoverIntent by Brian Cherne */ $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).unbind("mousemove",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } if ( p == this ) { return false; } // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // else e.type == "onmouseover" if (e.type == "mouseover") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).bind("mousemove",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "onmouseout" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/*************************************************** TABBED AREA ***************************************************/ jQuery(document).ready(function() { //When page loads... jQuery(".tab_content").hide(); //Hide all content jQuery("ul.tabs li:first").addClass("active").show(); //Activate first tab jQuery(".tab_content:first").show(); //Show first tab content //On Click Event jQuery("ul.tabs li").click(function() { jQuery("ul.tabs li").removeClass("active"); //Remove any "active" class jQuery(this).addClass("active"); //Add "active" class to selected tab jQuery(".tab_content").hide(); //Hide all tab content var activeTab = jQuery(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content jQuery(activeTab).fadeIn(); //Fade in the active ID content return false; }); }); /*********************************************************************************************************************** DOCUMENT: includes/javascript.js DEVELOPED BY: Ryan Stemkoski COMPANY: Zipline Interactive EMAIL: ryan@gozipline.com PHONE: 509-321-2849 DATE: 3/26/2009 UPDATED: 3/25/2010 DESCRIPTION: This is the JavaScript required to create the accordion style menu. Requires jQuery library NOTE: Because of a bug in jQuery with IE8 we had to add an IE stylesheet hack to get the system to work in all browsers. I hate hacks but had no choice :(. ************************************************************************************************************************/ jQuery(document).ready(function() { //ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING) jQuery('.accordionButton').click(function() { //REMOVE THE ON CLASS FROM ALL BUTTONS jQuery('.accordionButton').removeClass('on'); //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES jQuery('.accordionContent').slideUp(200); //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT if(jQuery(this).next().is(':hidden') == true) { //ADD THE ON CLASS TO THE BUTTON jQuery(this).addClass('on'); //OPEN THE SLIDE jQuery(this).next().slideDown(200); } }); /*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ //ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER jQuery('.accordionButton').mouseover(function() { jQuery(this).addClass('over'); //ON MOUSEOUT REMOVE THE OVER CLASS }).mouseout(function() { jQuery(this).removeClass('over'); }); /*** END REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ /******************************************************************************************************************** CLOSES ALL S ON PAGE LOAD ********************************************************************************************************************/ jQuery('.accordionContent').hide(); jQuery("#open").trigger('click'); });
JavaScript
/*************************************************** TABBED AREA ***************************************************/ jQuery(document).ready(function() { //When page loads... jQuery(".tab_content").hide(); //Hide all content jQuery("ul.tabs li:first").addClass("active").show(); //Activate first tab jQuery(".tab_content:first").show(); //Show first tab content //On Click Event jQuery("ul.tabs li").click(function() { jQuery("ul.tabs li").removeClass("active"); //Remove any "active" class jQuery(this).addClass("active"); //Add "active" class to selected tab jQuery(".tab_content").hide(); //Hide all tab content var activeTab = jQuery(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content jQuery(activeTab).fadeIn(); //Fade in the active ID content return false; }); }); /*********************************************************************************************************************** DOCUMENT: includes/javascript.js DEVELOPED BY: Ryan Stemkoski COMPANY: Zipline Interactive EMAIL: ryan@gozipline.com PHONE: 509-321-2849 DATE: 3/26/2009 UPDATED: 3/25/2010 DESCRIPTION: This is the JavaScript required to create the accordion style menu. Requires jQuery library NOTE: Because of a bug in jQuery with IE8 we had to add an IE stylesheet hack to get the system to work in all browsers. I hate hacks but had no choice :(. ************************************************************************************************************************/ jQuery(document).ready(function() { //ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING) jQuery('.accordionButton').click(function() { //REMOVE THE ON CLASS FROM ALL BUTTONS jQuery('.accordionButton').removeClass('on'); //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES jQuery('.accordionContent').slideUp(200); //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT if(jQuery(this).next().is(':hidden') == true) { //ADD THE ON CLASS TO THE BUTTON jQuery(this).addClass('on'); //OPEN THE SLIDE jQuery(this).next().slideDown(200); } }); /*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ //ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER jQuery('.accordionButton').mouseover(function() { jQuery(this).addClass('over'); //ON MOUSEOUT REMOVE THE OVER CLASS }).mouseout(function() { jQuery(this).removeClass('over'); }); /*** END REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ /******************************************************************************************************************** CLOSES ALL S ON PAGE LOAD ********************************************************************************************************************/ jQuery('.accordionContent').hide(); jQuery("#open").trigger('click'); });
JavaScript
(function($) { // Compliant with jquery.noConflict() $.fn.jCarouselLite = function(o) { o = $.extend({ btnPrev: null, btnNext: null, btnGo: null, mouseWheel: false, auto: null, speed: 200, easing: null, vertical: false, circular: true, visible: 3, start: 0, scroll: 1, beforeStart: null, afterEnd: null }, o || {}); return this.each(function() { // Returns the element collection. Chainable. var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; var div = $(this), ul = $("ul:first", div), tLi = $(".car", ul), tl = tLi.size(), v = o.visible; if(o.circular) { ul.prepend(tLi.slice(tl-v-1+1).clone()) .append(tLi.slice(0,v).clone()); o.start += v; } var li = $(".car", ul), itemLength = li.size(), curr = o.start; div.css("visibility", "visible"); li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); ul.css({ padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); //div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "29px"}); div.css({overflow: "hidden", "z-index": "2"}); var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) li.css({width: li.width()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images if(o.btnPrev) $(o.btnPrev).click(function() { return go(curr-o.scroll); }); if(o.btnNext) $(o.btnNext).click(function() { return go(curr+o.scroll); }); if(o.btnGo) $.each(o.btnGo, function(i, val) { $(val).click(function() { return go(o.circular ? o.visible+i : i); }); }); if(o.mouseWheel && div.mousewheel) div.mousewheel(function(e, d) { return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); }); if(o.auto) setInterval(function() { go(curr+o.scroll); }, o.auto+o.speed); function vis() { return li.slice(curr).slice(0,v); }; function go(to) { if(!running) { if(o.beforeStart) o.beforeStart.call(this, vis()); if(o.circular) { // If circular we are in first or last, then goto the other end if(to<=o.start-v-1) { // If first, then goto last ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; } else if(to>=itemLength-v+1) { // If last, then goto first ul.css(animCss, -( (v) * liSize ) + "px" ); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. curr = to==itemLength-v+1 ? v+1 : v+o.scroll; } else curr = to; } else { // If non-circular and to points to first or last, we just return. if(to<0 || to>itemLength-v) return; else curr = to; } // If neither overrides it, the curr will still be "to" and we can proceed. running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { if(o.afterEnd) o.afterEnd.call(this, vis()); running = false; } ); // Disable buttons when the carousel reaches the last/first, and enable when not if(!o.circular) { $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength-v && o.btnNext) || [] ).addClass("disabled"); } } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery);
JavaScript
function BcClient(socket) { this.socket = socket; // todo rename to serverInterface? this.users = new TList().bindSource(socket, 'users'); this.currentUser = new User(); // do not replace this.users.bindSlave(this.currentUser); this.premades = new TList().bindSource(socket, 'premades'); this.currentPremade = new Premade(); // do not replace this.premades.bindSlave(this.currentPremade); this.goals = new TList().bindSource(socket, 'goals'); this.courses = new TList().bindSource(socket, 'courses'); this.exercises = new TList().bindSource(socket, 'exercises'); this.messages = new TList().bindSource(socket, 'messages'); this.premadeUsers = new TList().bindSource(socket, 'premade.users'); this.premadeMessages = new TList().bindSource(socket, 'premade.messages'); // todo move to premade object? this.tankStack = new TList().bindSource(socket, 'game.botStack'); this.field = new Field(13 * 32, 13 * 32); TList.prototype.bindSource.call(this.field, socket, 'f'); this.vmRunner = new VmRunner(this); var self = this; this.socket.on('logged', function(data) { self.currentUser.unserialize(data.user); }); this.socket.on('joined', function(data) { // do not replace this.currentPremade self.currentPremade.unserialize(data.premade); }); this.socket.on('unjoined', function() { // do not replace this.currentPremade self.currentPremade.unserialize([]); }); }; Eventable(BcClient.prototype); //===== actions ================================================================ BcClient.prototype.connect = function() { this.socket.socket.connect(); }; BcClient.prototype.login = function(nick) { this.socket.emit('login', { nick : nick }); }; BcClient.prototype.setCourse = function(id) { this.socket.emit('set-course', { id: id }); }; BcClient.prototype.say = function(text) { this.socket.emit('say', { text : text }); }; BcClient.prototype.join = function(name, gameType) { this.socket.emit('join', { name : name, gameType : gameType }); }; BcClient.prototype.unjoin = function() { this.socket.emit('unjoin'); }; BcClient.prototype.startGame = function(level) { var self = this; this.socket.emit('start', { level: level }); }; BcClient.prototype.stopGame = function() { if (this.currentPremade.type == 'createbot') { this.socket.emit('stop-game'); } }; BcClient.prototype.executeCode = function(code) { if (this.currentPremade.gameRun) { this.socket.emit('execute', { code: code }); this.vmRunner.executeCode(code); } }; BcClient.prototype.control = function(commands) { this.socket.emit('control', commands); }; BcClient.prototype.turn = function(direction) { this.control({ turn: direction }); }; BcClient.prototype.move = function(distance) { this.control({ move: distance }); }; BcClient.prototype.startMove = function() { this.control({ startMove: 1 }); }; BcClient.prototype.stopMove = function() { this.control({ stopMove: 1 }); }; BcClient.prototype.fire = function() { this.control({ fire: 1 }); }; //===== events ================================================================= BcClient.prototype.onConnect = function(handler) { this.socket.on('connect', handler); }; BcClient.prototype.onConnectFail = function(handler) { this.socket.on('connect_failed', handler).on('error', handler); };
JavaScript
TankController = function TankController(tank) { this.tank = tank; var controller = this; $(window.document).keydown(this.controlEvent.bind(this)); $(window.document).keyup (this.controlEvent.bind(this)); }; TankController.prototype.controlEvent = function(e) { if ($('.CodeMirror textarea').get(0) == window.document.activeElement) { return; } if ($('#game').hasClass('create-bot')) { return; } // console.log(e.keyCode); // console.log(e.type); if (e.keyCode == 38 /*up*/) { if (e.type == 'keydown') { this.tank.turn('north'); this.tank.startMove(); } else if (e.type == 'keyup') { this.tank.stopMove(); } } if (e.keyCode == 39 /*right*/) { if (e.type == 'keydown') { this.tank.turn('east'); this.tank.startMove(); } else if (e.type == 'keyup') { this.tank.stopMove(); } } if (e.keyCode == 40 /*down*/) { if (e.type == 'keydown') { this.tank.turn('south'); this.tank.startMove(); } else if (e.type == 'keyup') { this.tank.stopMove(); } } if (e.keyCode == 37 /*left*/) { if (e.type == 'keydown') { this.tank.turn('west'); this.tank.startMove(); } else if (e.type == 'keyup') { this.tank.stopMove(); } } if (e.keyCode == 70 /*f*/ || e.keyCode == 32) { this.tank.fire(); } };
JavaScript
// there are all existing global vars below var bcClient, uiManager; var codeMirror = null; // todo better place? $(function() { new WidgetLangSelector(); if (typeof WebSocket == 'undefined' && typeof MozWebSocket == 'undefined') { $('.ui-block').hide().filter('#nowebsocket').show(); } else { // hack to substitute ws. var wsDomain = 'ws.' + location.hostname + (location.port ? ':' + location.port : ''); var src = 'http://' + wsDomain + '/socket.io/socket.io.js'; $.getScript(src, function(){ var socket = io.connect(wsDomain, { 'auto connect' : false, 'reconnect' : false // todo learn reconnection abilities }); bcClient = new BcClient(socket); uiManager = new UiManager(bcClient); bcClient.connect(); }); } $(window).resize(); });
JavaScript
isArray = Array.isArray; ServerUser = function ServerUser(course) { User.call(this, arguments); this.collections = {}; this.updateCollector = {}; this.messages = 0; this.countMessageFrom = Date.now(); this.setCurrentCourse(course); }; ServerUser.maxMessages = 10; // per minute ServerUser._eventTypeMap = {'add': 'a', 'change': 'c', 'remove': 'r'}; ServerUser.prototype = new User(); ServerUser.prototype.constructor = ServerUser; ServerUser.prototype.setCurrentCourse = function(course) { this.unwatchCollection('exercises'); this.currentCourse = course; this.watchCollection(course.execises, 'exercises'); this.emit('change'); }; ServerUser.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name] // 0 , this.id // 1 , this.nick // 2 , this.lives // 3 , this.points // 4 , this.clan ? this.clan.n : 0 // 5 , this.premade ? this.premade.id : 0 // 6 , this.positionId // 7 , this.tank ? this.tank.id : 0 // 8 , this.currentCourse ? this.currentCourse.id : 0 // 9 ]; }; ServerUser.prototype.sendUpdatesToClient = function() { if ((this.countMessageFrom + 60*1000) < Date.now()) { this.countMessageFrom = Date.now(); this.messages = 0; } var lastSync = this.lastSync, data = {}, itemData; // events may occur is this milliseconds, so do not record it as synced, and "- 1" this.lastSync = Date.now() - 1; var collections = 0; for (var key in this.updateCollector) { data[key] = []; for (var i in this.updateCollector[key]) { data[key].push(this.updateCollector[key][i]); delete this.updateCollector[key][i]; } if (data[key].length == 0) { delete data[key]; } else { collections++; } } if (collections) { this.clientMessage('sync', data); } }; ServerUser.prototype.control = function(event) { // if have tank and tank is on the field if (this.tank && this.tank.field) { if (event.turn) { this.tank.turn(event.turn); } if (event.startMove) { this.tank.startMove(); } if (event.stopMove) { this.tank.stopMove(); } if (event.fire) { this.tank.fire(); } if (event.move) { this.tank.move(event.move); } } }; ServerUser.prototype.say = function(text) { if (this.messages < ServerUser.maxMessages) { var message = new Message(text); message.user = this; if (this.premade) { this.premade.say(message); } else { registry.messages.say(message); } this.messages++; return true; } else { return false; } }; ServerUser.prototype.hit = function() { if (this.premade) { this.lives -= 1; if (this.lives < 0) { this.tank.field.remove(this.tank); } else { this.tank.lives = 1; this.tank.resetPosition(); } this.emit('change'); } }; ServerUser.prototype.addReward = function(reward) { this.points += reward; this.emit('change'); }; ServerUser.prototype.clientMessage = function(type, data) { if (this.socket) { this.socket.emit(type, data); } else { console.log('Trying to send data to disconnected client.'); // todo bug? // console.trace(); } }; ServerUser.prototype.onCollectionUpdate = function(syncKey, item, type /*, fields*/) { var data = item.serialize(); this.updateCollector[syncKey][item.id] = [ServerUser._eventTypeMap[type], data]; }; /** * @param collection * @param syncKey ключ, по которому клиент узнает к какой группе относятся объекты */ ServerUser.prototype.watchCollection = function(collection, syncKey) { this.unwatchCollection(syncKey); // сюда будут складываться объновления объектов this.updateCollector[syncKey] = []; var user = this; var addCallback = function(item) { user.onCollectionUpdate(syncKey, item, 'add'); }; var changeCallback = function(item) { user.onCollectionUpdate(syncKey, item, 'change'); }; var removeCallback = function(item) { user.onCollectionUpdate(syncKey, item, 'remove'); }; // подписываемся на обновления collection.on('add', addCallback); collection.on('change', changeCallback); collection.on('remove', removeCallback); // запоминаем callback, чтобы при отключении от группы, можно было удалить обработчик this.collections[syncKey] = { 'addCallback': addCallback, 'changeCallback': changeCallback, 'removeCallback': removeCallback, 'collection': collection }; // отправляем клиенту все объекты группы, как вновь созданные collection.traversal(function(item){ this.onCollectionUpdate(syncKey, item, 'add'); }, this); }; ServerUser.prototype.unwatchCollection = function(syncKey) { if (this.collections[syncKey]) { // удаляем обработчик this.collections[syncKey].collection.removeListener('add', this.collections[syncKey].addCallback); this.collections[syncKey].collection.removeListener('change', this.collections[syncKey].changeCallback); this.collections[syncKey].collection.removeListener('remove', this.collections[syncKey].removeCallback); // сообщаем клиенту, чтобы он удалил у себя эту группу this.clientMessage('clearCollection', syncKey); delete this.collections[syncKey]; delete this.updateCollector[syncKey]; } }; ServerUser.prototype.unwatchAll = function() { for (var syncKey in this.collections) { this.unwatchCollection(syncKey); } };
JavaScript
TMessageList = function TMessageList() { TList.apply(this, arguments); }; TMessageList.prototype = new TList(); TMessageList.prototype.constructor = TMessageList; TMessageList.prototype.say = function(message) { this.add(message); for (var i in this.items) { if (this.items[i].time + 5 * 60 * 1000 < Date.now()) { this.remove(this.items[i]); } } };
JavaScript
TPremadeList = function TPremadeList() { TList.apply(this, arguments); }; TPremadeList.prototype = new TList(); TPremadeList.prototype.constructor = TPremadeList; TPremadeList.prototype.join = function(event, user) { var gameName = event.name && event.name.substr(0,20); if (!user.premade) { var premade; for (var i in this.items) { if (this.items[i].name == gameName) { premade = this.items[i]; break; } } if (!premade) { if (this.count() >= 100) { // games limit throw {message: "Не получается создать игру. Достигнут максимум одновременных игр на сервере."}; } else { premade = new Premade(gameName, event.gameType); this.add(premade); } } premade.join(user); } else { throw {message: "User already in premade - " + user.premade.id + " (bug?)"}; } };
JavaScript
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"); // todo globals registry = {}; require('../common/event'); require('../common/list'); require('../common/game'); require('../common/premade'); require('../server/premadelist'); require('../common/user'); require('../server/user'); require('../common/message'); require('../server/messagelist'); require('../common/func'); require('../common/map_tiled'); require('../battle-city/field'); require('../battle-city/bot-emitter'); require('../battle-city/objects/abstract'); require('../battle-city/objects/animation'); require('../battle-city/objects/bullet'); require('../battle-city/objects/tank'); require('../battle-city/objects/tankbot'); require('../battle-city/objects/wall'); require('../battle-city/objects/delimiter'); require('../battle-city/objects/base'); require('../battle-city/objects/bonus'); require('../battle-city/objects/trees'); require('../battle-city/objects/water'); require('../battle-city/objects/ice'); require('../battle-city/objects/checkpoint'); require('../battle-city/goals'); require('../battle-city/clan'); require('../edu/course'); require('../edu/courselist'); require('../edu/exercise'); require('../edu/exerciselist'); require('../common/server'); registry.users = new TList(); registry.premades = new TPremadeList(); registry.messages = new TMessageList(); registry.courses = new CoursesList(); process.on('uncaughtException', function(ex) { if (ex.stack) { console.log(ex.stack); } else { console.log(ex); console.trace(); } }); /** * Server is responsible for accepting user connections. */ var server = require('http').createServer(function(request, response) { if (process.argv.indexOf('serve-static') == -1) { // static served with haproxy + nginx response.writeHead(301, {'Location':'http://'+request.headers.host.replace(/:\d+$/, '')}); response.end(); } else { var uri = url.parse(request.url).pathname; if (uri == '/') { uri = '/index.html'; } var filename = path.join(process.cwd(), uri); path.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } var exts = { '.html': 'text/html', '.js': 'application/x-javascript', '.png': 'image/png', '.css': 'text/css' }; response.writeHead(200, { 'Content-Type': exts[path.extname(filename)] }); response.write(file, "binary"); response.end(); }); }); } }); server.listen(8124); var io = require('socket.io'); var config = { 'browser client minification': true, 'browser client etag': true, 'browser client gzip': true, 'transports': ['websocket'], 'log level': 1 }; io.listen(server, config).sockets.on('connection', function(socket) { new BcServerInterface(socket); });
JavaScript
ExerciseList = function ExerciseList() { TList.apply(this, arguments); }; ExerciseList.prototype = new TList(); ExerciseList.prototype.constructor = ExerciseList;
JavaScript
CoursesList = function CoursesList() { TList.apply(this, arguments); this.add(new CoursePascalBasics()); this.add(new CourseAlgoritms()); }; CoursesList.prototype = new TList(); CoursesList.prototype.constructor = CoursesList;
JavaScript
Course = function Course(id, name) { this.id = id; this.name = name; // this.execises = new TList(); }; Course.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.name // 2 ]; // z is constant }; Course.prototype.unserialize = function(data) { this.id = data[1]; this.name = data[2]; }; CoursePascalBasics = function CoursePascalBasics() { this.execises = new TList(); this.execises.add(new Exercise('pascal-algoritm1', 1)); this.execises.add(new Exercise('pascal-algoritm2', 2)); this.execises.add(new Exercise('pascal-if-statement', 3)); this.execises.add(new Exercise('pascal-for-statement', 4)); }; CoursePascalBasics.prototype = new Course(1, 'course-pascal-basics'); CourseAlgoritms = function CourseAlgoritms() { this.execises = new TList(); this.execises.add(new Exercise('algoritms-wayfinder', 1)); }; CourseAlgoritms.prototype = new Course(2, 'course-algoritms');
JavaScript
Exercise = function Exercise(name, level) { this.name = name; this.level = level; }; Exercise.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.name, // 2 this.level // 3 ]; // z is constant }; Exercise.prototype.unserialize = function(data) { this.id = data[1]; this.name = data[2]; this.level = data[3]; };
JavaScript
if (!window.availableLangs['/src/edu/course-pascal-basics/ex1']) { window.availableLangs['/src/edu/course-pascal-basics/ex1'] = {}; } window.availableLangs['/src/edu/course-pascal-basics/ex1']['en'] = { 'exercise-help-content': '<h1>Exercise 1</h1>\ \ <p>In this exercise you goal is to write a program which will lead a tank towards\ checkpoint. Program is a sequence of instructons perfoming consequently step by step.\ One example of insctuction is a procedure call:</p>\ \ <pre class="code">move(steps);</pre>\ \ <p>With this instruction you can make tank to move given steps forward. In this\ example \'move\' is a procedure name. Next after a procedure name are argument list\ encolsed with round brackets. There are only one argument in the example above,\ and this argument are number of step to move forward.</p>\ \ <p>Another procedure call can be this:</p>\ \ <pre class="code">turn(direction);</pre>\ \ <p>This instruction make tank to turn to gived direction. \'direction\' arugument\ of \'turn\' procedure should be a string. Strings in the Pascal language should be\ enclosed with single quoted. This is need by a compiler to split strings and\ keywords or procedure\'s names. So to turn tank to the east, you\ should write this:</p>\ \ <pre class="code">turn(\'east\');</pre>\ \ <p>other appropriate values are \'west\' - turn westward, \'north\' -\ turn northward and \'south\' - turn southward.</p>\ \ <p>In this exercise tank should move 11 steps forward, then turn to the right\ and move another 10 step forward.</p>\ \ <p>Here is a final program source code:</p>\ \ <pre class="code">\ Program Level1;\n\ begin\n\ move(11);\n\ turn(\'east\');\n\ move(10);\n\ end.\n\ </pre>\ \ <p>After you finish writing program, click "Execute code" button to run a program.</p>' };
JavaScript
if (!window.availableLangs['/src/edu/course-pascal-basics/ex2']) { window.availableLangs['/src/edu/course-pascal-basics/ex2'] = {}; } window.availableLangs['/src/edu/course-pascal-basics/ex2']['ru'] = { 'exercise-help-content': '<h1>Задача</h1>\ \ <p>Во втором упражнении вам необходимо проехать через две контрольные точки.</p>\ \ <p>Вот готовый вариант решения задания:</p>\ \ <pre class="code">\ Program Program2;\n\ begin\n\ move(11);\n\ turn(\'east\');\n\ move(10);\n\ turn(\'north\');\n\ move(4);\n\ turn(\'west\');\n\ move(12);\n\ end.\n\ </pre>\ ' };
JavaScript
if (!window.availableLangs['/src/edu/course-pascal-basics/ex3']) { window.availableLangs['/src/edu/course-pascal-basics/ex3'] = {}; } window.availableLangs['/src/edu/course-pascal-basics/ex3']['ru'] = { 'exercise-help-content': '<h1>Задача</h1>\ \ <p>В третьем упражнении цель появляется в одном из двух мест. Но заранее неизвестно в каком именно. \ Чтобы стало понятно о чем речь, нажмите несколько раз кнопку "Начать заново", и вы увидете, что иногда цель \ перемещается на новое место. То есть танку нужно будет проехать 11 шагов вверх, \ затем повернуть вправо или влево, и проехать еще 5 шагов.</p>\ \ <p>Чтобы узнать в какую именно сторону нужно повернуть танк, в этом упражнении будут доступны \ две переменные с именами "x" и "checkpointx". Сравнив какая их этих переменных больше, \ вы сможете решить в какую сторону поворачивать танк. Для этого вам нужно будет использовать \ следующую конструкцию:</p>\ \ <pre class="code">\ if условие then\n\ оператор1\n\ else\n\ оператор2;\n\ </pre>\ \ <p>Во ходе выполнения программы будет вычислено <b>условие</b>, и, если условие верно, \ будет выполнен <b>оператор1</b>, а если условие не верно, то будет выполнен <b>оператор2</b>. \ Обратите внимание, что перед ключевым словом <b>else</b> нет запятой.</p>\ \ <p>Вот готовый вариант решения задания:</p>\ \ <pre class="code">\ Program Program3;\n\ begin\n\ move(11);\n\ if x>checkpointx then\n\ turn(\'west\')\n\ else\n\ turn(\'east\');\n\ move(5);\n\ end.\n\ </pre>\ ' };
JavaScript
if (!window.availableLangs['/src/edu/course-pascal-basics/ex4']) { window.availableLangs['/src/edu/course-pascal-basics/ex4'] = {}; } window.availableLangs['/src/edu/course-pascal-basics/ex4']['ru'] = { 'exercise-help-content': '<h1>Задача</h1>\ \ <p>В четвертом упражнении вам нужно объехать 3 цели. Но, как вы можете заметить, \ цели расположенны не хаотично и объехать их можно повторив три раза подряд одни и \ теже действия. Для этого существует оператор цикла:</p>\ \ <pre class="code">\n\ for переменная := значение1 to значение2 do\n\ оператор;\n\ </pre>\n\ \ <p>Оператор for будет увеличивать значение переменной <b>переменная</b> на еденицу, \ начиная со значения1 и заканчивая значением2, каждый раз выполняя <b>оператор</b>, следующий за <b>do</b>. \ То есть, чтобы выполнить <b>оператор</b> 3 раза, нужно будет написать:</p>\ \ <pre class="code">\n\ for переменная := 1 to 3 do\n\ оператор;\n\ </pre>\n\ \ <p>Но переменная <b>переменная</b> должна быть сначала объявлена, для этого сразу после \ строки <b>Program Program4;</b> нужно написать:</p>\ \ <pre class="code">\n\ var a: integer;\n\ </pre>\n\ <p>Тем самым мы определили переменную <b>a</b> и сам цикл можем записать в следующем виде:</p>\ \ <pre class="code">\n\ for a := 1 to 3 do\n\ оператор;\n\ </pre>\n\ \ <p>Но нам в цикле нужно выполнить не один оператор, а несколько. Для этого можно объеденить \ группу операторов операторными скобками <b>begin</b> и <b>end</b>. В результате получим \ например такой вариант решения задания:</p>\ \ <pre class="code">\n\ Program Program4;\n\ var a: integer;\n\ begin\n\ for a:=1 to 3 do begin\n\ move(5);\n\ turn(\'left\');\n\ move(5);\n\ turn(\'left\');\n\ turn(\'left\');\n\ end\n\ end.\n\ </pre>\n\ ' };
JavaScript
if (!window.availableLangs['/src/edu/course-pascal-basics/ex1']) { window.availableLangs['/src/edu/course-pascal-basics/ex1'] = {}; } window.availableLangs['/src/edu/course-pascal-basics/ex1']['ru'] = { 'exercise-help-content': '<h1>Задача</h1>\ \ <p>В первом упражнении вам необходимо написать программу управления танком, которая \ приведет его в точку назначения. Программа представляет собой набор инструкций, \ выполняемых последовательно, одна за другой. Одним из примеров иструкции, может \ быть вызов процедуры:</p>\ \ <pre class="code">move(steps);</pre>\ \ <p>С помощью этого вызова можно указать танку двигаться вперед на заданное \ количество шагов. В данном случае, move - это имя процедуры. После имени \ процедуры может идти заключенный в круглые скобки список аргументов. Тут у нас \ только один аргумент steps - целое число, указывающее количество шагов, которые \ должен совершить танк.</p>\ \ <p>Другой полезной процедурой будет:</p>\ \ <pre class="code">turn(direction);</pre>\ \ <p>Эта процедура указывает танку повернуться в указанную сторону. Параметром \ direction должна быть строка. Cтроки в Pascal заключаются в одинарные \ кавычки, чтобы компилятор не путал строки с названием процедур или переменных. \ Например чтобы танк повернулся вправо (на восток), нужно написать:</p>\ \ <pre class="code">turn(\'east\');</pre>\ \ <p>остальными вариантами будут: \'west\' - налево (на запад), \'north\' - вверх (на \ север) и \'south\' - вниз (на юг).</p>\ \ <p>В данном задании, танк должен проехать вверх на 11 шагов, затем повернуться \ направо, и проехать еще 10 шагов.</p>\ \ <p>Вот готовый вариант решения задания:</p>\ \ <pre class="code">\ Program Level1;\n\ begin\n\ move(11);\n\ turn(\'east\');\n\ move(10);\n\ end.\n\ </pre>\ \ <p>Скопируйте код на вкладку "Редактор кода", после чего нажмите кнопку "Выполнить код".</p>' };
JavaScript
BotEmitter = function BotEmitter(x, y) { this.x = x; this.y = y; };
JavaScript
(function(){ window.images = {}; var sprites = [ 'img/tank1-down-s1.png' , 'img/tank1-down-s2.png' , 'img/tank1-up-s1.png' , 'img/tank1-up-s2.png' , 'img/tank1-right-s1.png' , 'img/tank1-right-s2.png' , 'img/tank1-left-s1.png' , 'img/tank1-left-s2.png' , 'img/tank2-down-s1.png' , 'img/tank2-down-s2.png' , 'img/tank2-up-s1.png' , 'img/tank2-up-s2.png' , 'img/tank2-right-s1.png' , 'img/tank2-right-s2.png' , 'img/tank2-left-s1.png' , 'img/tank2-left-s2.png' , 'img/normal-bot-down-s1.png' , 'img/normal-bot-down-s2.png' , 'img/normal-bot-down-s1-blink.png' , 'img/normal-bot-down-s2-blink.png' , 'img/normal-bot-up-s1.png' , 'img/normal-bot-up-s2.png' , 'img/normal-bot-up-s1-blink.png' , 'img/normal-bot-up-s2-blink.png' , 'img/normal-bot-right-s1.png' , 'img/normal-bot-right-s2.png' , 'img/normal-bot-right-s1-blink.png' , 'img/normal-bot-right-s2-blink.png' , 'img/normal-bot-left-s1.png' , 'img/normal-bot-left-s2.png' , 'img/normal-bot-left-s1-blink.png' , 'img/normal-bot-left-s2-blink.png' , 'img/fast-bullet-bot-down-s1.png' , 'img/fast-bullet-bot-down-s2.png' , 'img/fast-bullet-bot-down-s1-blink.png' , 'img/fast-bullet-bot-down-s2-blink.png' , 'img/fast-bullet-bot-up-s1.png' , 'img/fast-bullet-bot-up-s2.png' , 'img/fast-bullet-bot-up-s1-blink.png' , 'img/fast-bullet-bot-up-s2-blink.png' , 'img/fast-bullet-bot-right-s1.png' , 'img/fast-bullet-bot-right-s2.png' , 'img/fast-bullet-bot-right-s1-blink.png' , 'img/fast-bullet-bot-right-s2-blink.png' , 'img/fast-bullet-bot-left-s1.png' , 'img/fast-bullet-bot-left-s2.png' , 'img/fast-bullet-bot-left-s1-blink.png' , 'img/fast-bullet-bot-left-s2-blink.png' , 'img/fast-bot-down-s1.png' , 'img/fast-bot-down-s2.png' , 'img/fast-bot-down-s1-blink.png' , 'img/fast-bot-down-s2-blink.png' , 'img/fast-bot-up-s1.png' , 'img/fast-bot-up-s2.png' , 'img/fast-bot-up-s1-blink.png' , 'img/fast-bot-up-s2-blink.png' , 'img/fast-bot-right-s1.png' , 'img/fast-bot-right-s2.png' , 'img/fast-bot-right-s1-blink.png' , 'img/fast-bot-right-s2-blink.png' , 'img/fast-bot-left-s1.png' , 'img/fast-bot-left-s2.png' , 'img/fast-bot-left-s1-blink.png' , 'img/fast-bot-left-s2-blink.png' , 'img/heavy-bot-down-s1.png' , 'img/heavy-bot-down-s2.png' , 'img/heavy-bot-down-s1-blink.png' , 'img/heavy-bot-down-s2-blink.png' , 'img/heavy-bot-up-s1.png' , 'img/heavy-bot-up-s2.png' , 'img/heavy-bot-up-s1-blink.png' , 'img/heavy-bot-up-s2-blink.png' , 'img/heavy-bot-right-s1.png' , 'img/heavy-bot-right-s2.png' , 'img/heavy-bot-right-s1-blink.png' , 'img/heavy-bot-right-s2-blink.png' , 'img/heavy-bot-left-s1.png' , 'img/heavy-bot-left-s2.png' , 'img/heavy-bot-left-s1-blink.png' , 'img/heavy-bot-left-s2-blink.png' , 'img/bullet-up.png' , 'img/bullet-down.png' , 'img/bullet-left.png' , 'img/bullet-right.png' , 'img/brick-wall.png' , 'img/black.png' , 'img/base.png' , 'img/base-hit.png' , 'img/birth1.png' , 'img/birth2.png' , 'img/steel-wall.png' , 'img/star.png' , 'img/grenade.png' , 'img/shovel.png' , 'img/trees.png' , 'img/water1.png' , 'img/water2.png' , 'img/hit1.png' , 'img/hit2.png' , 'img/hit3.png' , 'img/helmet.png' , 'img/live.png' , 'img/timer.png' , 'img/armored1.png' , 'img/armored2.png' , 'img/ice.png' , 'img/checkpoint.png' ]; for (var i in sprites) { window.images[sprites[i]] = new Image(); window.images[sprites[i]].src = sprites[i]; } })();
JavaScript
Goal = function Goal(clan) { this.clan = clan; this.status = 0; // 0 - active, 1 - done }; Eventable(Goal.prototype); Goal.prototype.check = function() { throw new Error('subclass responsibility'); }; Goal.prototype.reset = function(field) { this.status = 0; }; GoalCheckPoint = function GoalCheckPoint(clan, x, y) { Goal.call(this, clan); this.checkpoint = new Checkpoint(x, y); }; GoalCheckPoint.prototype = new Goal(); GoalCheckPoint.prototype.constructor = GoalCheckPoint; GoalCheckPoint.prototype.check = function() { var res = this.clan.game.field.intersect(this.checkpoint); var clan = this.clan; for (var i in res) { if (res[i] instanceof Tank && res[i].clan == clan.enemiesClan) { clan.game.field.remove(this.checkpoint); this.status = 1; this.emit('change'); } } }; GoalCheckPoint.prototype.reset = function() { this.status = 0; this.clan.game.field.add(this.checkpoint); }; GoalCheckPoint.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.status, // 2 this.checkpoint.x, // 3 this.checkpoint.y // 4 ]; }; GoalCheckPoint.prototype.unserialize = function(data) { this.id = data[1]; this.status = data[2]; this.checkpoint = new Checkpoint(data[3], data[4]); };
JavaScript
/** * drawable * coordinates */ Bonus = function Bonus(x, y) { AbstractGameObject.call(this, 16, 16); this.x = x; this.y = y; this.z = 2; }; Bonus.prototype = new AbstractGameObject(); Bonus.prototype.constructor = Bonus; Eventable(Bonus.prototype); Bonus.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], this.id, this.x, this.y ]; // z is constant }; Bonus.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Bonus.prototype.hit = function(bullet) { return false; }; BonusStar = function BonusStar(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/star.png'; }; BonusStar.prototype = new Bonus(); BonusStar.prototype.constructor = BonusStar; BonusStar.prototype.applyTo = function(tank) { if (tank.maxBullets == 1) { tank.maxBullets = 2; } else if (tank.bulletPower == 1) { tank.bulletPower = 2; } }; BonusGrenade = function BonusGrenade(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/grenade.png'; }; BonusGrenade.prototype = new Bonus(); BonusGrenade.prototype.constructor = BonusGrenade; BonusGrenade.prototype.applyTo = function(tank) { // hit() cause splice tank.clan.enemiesClan.users, so collect tanks first var tanks = []; for (var i in tank.clan.enemiesClan.users) { tanks.push(tank.clan.enemiesClan.users[i].tank); } for (var i in tanks) { tanks[i].hit(); } }; BonusShovel = function BonusShovel(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/shovel.png'; }; BonusShovel.prototype = new Bonus(); BonusShovel.prototype.constructor = BonusShovel; BonusShovel.prototype.applyTo = function(tank) { if (!tank.clan.isBots()) { tank.clan.base.armor(); } }; BonusHelmet = function BonusHelmet(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/helmet.png'; }; BonusHelmet.prototype = new Bonus(); BonusHelmet.prototype.constructor = BonusHelmet; BonusHelmet.prototype.applyTo = function(tank) { tank.armoredTimer = tank.clan.defaultArmoredTimer; }; BonusLive = function BonusLive(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/live.png'; }; BonusLive.prototype = new Bonus(); BonusLive.prototype.constructor = BonusLive; BonusLive.prototype.applyTo = function(tank) { tank.user.lives++; tank.user.emit('change'); }; BonusTimer = function BonusTimer(x, y) { Bonus.apply(this, arguments); this.img[0] = 'img/timer.png'; }; BonusTimer.prototype = new Bonus(); BonusTimer.prototype.constructor = BonusTimer; BonusTimer.prototype.applyTo = function(tank) { tank.clan.enemiesClan.pauseTanks(); };
JavaScript
AbstractGameObject = function AbstractGameObject(hw, hh) { // for intersection (when speedX > hw) this.hw = this.boundX = hw; //for intersection (when speedY > hh) this.hh = this.boundY = hh; this.speedX; // set only through setSpeedX() this.speedY; // set only through setSpeedY() this.img = []; }; AbstractGameObject.prototype.z = 1; AbstractGameObject.prototype.setSpeedX = function(value) { this.speedX = value; this.boundX = this.speedX ? Math.max(this.hw, Math.abs(this.speedX)) : this.hw; }; AbstractGameObject.prototype.setSpeedY = function(value) { this.speedY = value; this.boundY = this.speedY ? Math.max(this.hh, Math.abs(this.speedY)) : this.hh; }; // sample AbstractGameObject.prototype.serialize = function() { // zero element is always type, first - id return [ serializeTypeMatches['AbstractGameObject'], this.id // ... ]; }; //sample AbstractGameObject.prototype.unserialize = function(data) { this.id = data[1]; // ... };
JavaScript
Delimiter = function Delimiter(x, y, hw, hh) { AbstractGameObject.call(this, hw, hh); this.x = x; this.y = y; this.z = 1; this.hw = hw; // half width this.hh = hh; // half height this.img[0] = 'img/black.png'; }; Delimiter.prototype = new AbstractGameObject(); Delimiter.prototype.constructor = Delimiter; Eventable(Delimiter.prototype); Delimiter.prototype.serialize = function() { return [ serializeTypeMatches['Delimiter'], // 0 this.id, // 1 this.x, this.y, this.hw, this.hh ]; }; Delimiter.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } this.hw = data[4]; this.hh = data[5]; }; Delimiter.prototype.hit = function() { return true; };
JavaScript
/** * drawable * coordinates */ Water = function Water(x, y) { AbstractGameObject.call(this, 8, 8); this.x = x; this.y = y; this.z = 1; this.img[0] = 'img/water1.png'; }; Water.prototype = new AbstractGameObject(); Water.prototype.constructor = Water; Eventable(Water.prototype); Water.prototype.serialize = function() { return [ serializeTypeMatches['Water'], // 0 this.id, // 1 this.x, this.y ]; // z is constant }; Water.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Water.prototype.hit = function(bullet) { return false; }; Water.prototype.animateStep = function(step) { if (step % 10 == 0) { if (step % 20 >= 10) { this.img[0] = 'img/water2.png'; } else { this.img[0] = 'img/water1.png'; } } };
JavaScript
/** * drawable * coordinates */ Bullet = function Bullet(speedX, speedY) { AbstractGameObject.call(this, 4, 4); this.x = 0; this.y = 0; this.z = 1; // bullet is rectangle step of bullet this.setSpeedX(speedX); this.setSpeedY(speedY); this.finalX = 0; // for proper hit animation (todo ugly) this.finalY = 0; // for proper hit animation (todo ugly) this.power = 1; this.setDirectionImage(); }; Bullet.prototype = new AbstractGameObject(); Bullet.prototype.constructor = Bullet; Eventable(Bullet.prototype); Bullet.prototype.setDirectionImage = function() { var dir = 'up'; if (this.speedY > 0) { dir = 'down'; } else if (this.speedY < 0) { dir = 'up'; } else if (this.speedX > 0) { dir = 'right'; } else if (this.speedX < 0) { dir = 'left'; } this.img[0] = 'img/bullet-' + dir + '.png'; }; Bullet.prototype.step = function() { if (this.field.move(this, this.x + this.speedX, this.y + this.speedY)) { this.emit('change'); } }; Bullet.prototype.hit = function() { this.field.remove(this); return true; }; Bullet.prototype.onIntersect = function(items) { var canMoveThrowItems = true; for (var i in items) { if (items[i] == this.tank) continue; // todo neiberhood wall can be already removed if (items[i].hit && items[i].hit(this)) { if (this.speedX) this.finalX = items[i].x - items[i].hw * vector(this.speedX); else this.finalX = this.x; if (this.speedY) this.finalY = items[i].y - items[i].hh * vector(this.speedY); else this.finalY = this.y; canMoveThrowItems = false; } } if (!canMoveThrowItems) { this.field.remove(this); } return canMoveThrowItems; }; Bullet.prototype.serialize = function() { return [ serializeTypeMatches['Bullet'], // 0 this.id, // 1 this.x, // 2 this.y, // 3 this.speedX, // 4 this.speedY, // 5 this.finalX, // 6 todo remove this.finalY // 7 todo remove ]; }; Bullet.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } this.setSpeedX(data[4]); this.setSpeedY(data[5]); this.finalX = data[6]; this.finalY = data[7]; this.setDirectionImage(); };
JavaScript
/** * drawable * coordinates * * interface: * fire() * turn(direction) * startMove() * stopMove() * * В этом классе перемешанны: * - сама сущность * - отрисовка (setDirectionImage(), imgBase, clanN, trackStep, blink) * - пуле устанавливаются координаты напрямую, а для этого надо знать, * что можно задавать x и y напрямую, только до добавления объекта * в map_tiled (можно переделать map_tiled чтобы он слушал gameBus, * а объекты просто кидали событие move). * - distanceLeft и this.emit('task-done') - знание о том что vm на клиенте * ждет этого события, чтобы продолжить выполнять код (можно выделить * в tankController). * - не понятно куда пристроить обработку бонусов, толи this.onBonus толи в * bonus.onIntersect. А может вообще в отдельный класс? * - сериализация * * Этот класс знает о: * - о своих пулях (bullets) * - об игровом поле (field) * - бонусах (onBonus) * - о льде (Ice) * - о кланах (clan) * - о виртуальной машине на клиенте (this.emit('task-done')) * - о спрайтах для отрисовки * - serializeTypeMatches * - о пользователях (bullet.tank.user.addReward(this.reward)) * */ Tank = function Tank(x, y) { AbstractGameObject.call(this, 16, 16); this.initialPosition = { x: x, y: y }; this.x = x; this.y = y; this.z = 1; this.moveOn = 0; // flag used in Tank.step() this.distanceLeft = null; this.setSpeedX(0); this.setSpeedY(-this.speed); this.direction = null; this.setDirectionImage(); this.maxBullets = 1; this.bulletPower = 1; this.bullets = new Array(); // can move to current direction? this.stuck = false; this.lives = 1; this.bonus = false; this.clan = null; this.armoredTimer = Tank.defaultArmoredTimer; // 30ms step this.trackStep = 1; // 1 or 2 this.birthTimer = 1 * 1000/30; // 30ms step this.fireTimer = 0; this.onIce = false; this.glidingTimer = 0; this.blink = false; }; Tank.defaultArmoredTimer = 10 * 1000/30; // 30ms step Tank.prototype = new AbstractGameObject(); Tank.prototype.constructor = Tank; Tank.prototype.imgBase = 'img/tank'; Tank.prototype.reward = 100; Tank.prototype.speed = 2; // default speed Tank.prototype.bulletSpeed = 5; // default speed Eventable(Tank.prototype); Tank.prototype.onAddToField = function() { var self = this; this.field.on('remove', function(object) { for (var i in self.bullets) { if (self.bullets[i] == object) { self.bullets.splice(i, 1); } } }); }; Tank.prototype.fire = function() { if (this.birthTimer <= 0 && this.bullets.length < this.maxBullets && !(this.bullets.length > 0 && this.fireTimer > 0)) { if (this.bullets.length > 0) { // to not second fire too fast this.fireTimer = 0.5 * 1000/30; // 30ms step } var bullet = new Bullet(); bullet.tank = this; bullet.clan = this.clan; bullet.setSpeedX(vector(this.speedX) * this.bulletSpeed); bullet.setSpeedY(vector(this.speedY) * this.bulletSpeed); // before adding to field (may set x, y directly) bullet.x = this.x + (this.hw - 2) * vector(this.speedX); bullet.y = this.y + (this.hh - 2) * vector(this.speedY); bullet.power = this.bulletPower; this.bullets.push(bullet); this.field.add(bullet); } this.emit('task-done'); }; Tank.prototype.step = function(paused) { if (this.fireTimer > 0) this.fireTimer--; if ((this.birthTimer > 0)) { this.birthTimer--; this.emit('change'); return; } if (this.armoredTimer > 0) { this.armoredTimer--; if (this.armoredTimer <= 0) { this.emit('change'); } } if (paused) return; var onIce = false; if (this.moveOn || this.glidingTimer > 0) { // todo field.move()? var sx = this.distanceLeft && this.distanceLeft < this.speedX ? vector(this.speedX) * this.distanceLeft : this.speedX; var sy = this.distanceLeft && this.distanceLeft < this.speedY ? vector(this.speedY) * this.distanceLeft : this.speedY; this.stuck = false; var intersect = this.field.intersect(this, this.x + sx, this.y + sy); if (intersect.length > 0) { for (var i in intersect) { switch (true) { case intersect[i] instanceof Bonus: this.onBonus(intersect[i]); break; case intersect[i] instanceof Ice: onIce = true; // no break! before default! default: // power === undefined is a hack for fast bullet detection if (intersect[i].z == this.z && intersect[i].power === undefined) { this.stuck = true; this.glidingTimer = 0; } } } } if (!this.stuck) { this.field.setXY(this, this.x + sx, this.y + sy); if (this.distanceLeft) { this.distanceLeft -= Math.abs(sx + sy); // sx == 0 || sy == 0 if (this.distanceLeft == 0) { this.emit('task-done'); this.distanceLeft = null; this.moveOn = false; } } } this.onIce = onIce; if (this.glidingTimer > 0) { if (onIce) { this.glidingTimer--; } else { this.glidingTimer = 0; } } this.emit('change'); } }; Tank.prototype.onBonus = function(bonus) { bonus.applyTo(this); this.field.remove(bonus); }; //function for override for different sprites Tank.prototype.setDirectionImage = function() { var dir = 'up'; if (this.speedY > 0) { dir = 'down'; } else if (this.speedY < 0) { dir = 'up'; } else if (this.speedX > 0) { dir = 'right'; } else if (this.speedX < 0) { dir = 'left'; } this.img[0] = (((this.imgBase == 'img/tank') ? this.imgBase + this.clanN : this.imgBase) // todo clanN hack + '-' + dir + '-s' + this.trackStep + (this.blink ? '-blink' : '') + '.png'); }; Tank.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.x, // 2 this.y, // 3 this.speedX, // 4 this.speedY, // 5 this.bonus, // 6 Math.round(this.armoredTimer), // 7 Math.round(this.birthTimer), // 8 this.clan.n // 9 ]; }; Tank.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } this.setSpeedX(data[4]); this.setSpeedY(data[5]); this.bonus = data[6]; this.armoredTimer = data[7]; this.birthTimer = data[8]; this.clanN = data[9]; }; Tank.prototype.animateStep = function(step) { if (this.birthTimer > 0) { this.img[0] = 'img/birth' + ((step % 6) > 3 ? 1 : 2) + '.png'; delete this.img[1]; } else { if (this.moveOn) { this.trackStep = step % 2 + 1; } if (this.bonus) { this.blink = (step % 10) > 5; } else if(this.blink) { this.blink = false; } this.setDirectionImage(); if (this.armoredTimer > 0) { this.img[1] = step % 2 ? 'img/armored1.png' : 'img/armored2.png'; } else { delete this.img[1]; } } }; /** * There are circumstances when turning is impossible, so return bool * * @todo too long function * @param direction * @return bool */ Tank.prototype.turn = function(direction) { var canTurn = true; if (direction == 'right') { switch (true) { case this.speedX > 0: direction = 'south'; break; case this.speedX < 0: direction = 'north'; break; case this.speedY > 0: direction = 'west'; break; case this.speedY < 0: direction = 'east'; break; } } if (direction == 'left') { switch (true) { case this.speedX > 0: direction = 'north'; break; case this.speedX < 0: direction = 'south'; break; case this.speedY > 0: direction = 'east'; break; case this.speedY < 0: direction = 'west'; break; } } if (this.direction != direction) { // emulate move back tank for 1 pixel // doto this may be a bug, if tank just change direction to opposite var vx = this.speedX > 0 ? 1 : -1; var vy = this.speedY > 0 ? 1 : -1; // 1, 2 - first try turn with backward adjust, second try turn with forward adjust var newX1, newY1, newX2, newY2, newSpeedX, newSpeedY; switch (direction) { case 'north': newSpeedX = 0; newSpeedY = -this.speed; if (this.x % 16 > 8 + vx) { newX1 = this.x + 16 - this.x % 16; newX2 = this.x - this.x % 16; } else { newX1 = this.x - this.x % 16; newX2 = this.x + 16 - this.x % 16; } newY1 = newY2 = this.y; break; case 'east': newSpeedX = this.speed; newSpeedY = 0; newX1 = newX2 = this.x; if (this.y % 16 > 8 + vy) { newY1 = this.y + 16 - this.y % 16; newY2 = this.y - this.y % 16; } else { newY1 = this.y - this.y % 16; newY2 = this.y + 16 - this.y % 16; } break; case 'south': newSpeedX = 0; newSpeedY = this.speed; if (this.x % 16 > 8 + vx) { newX1 = this.x + 16 - this.x % 16; newX2 = this.x - this.x % 16; } else { newX1 = this.x - this.x % 16; newX2 = this.x + 16 - this.x % 16; } newY1 = newY2 = this.y; break; case 'west': newSpeedX = -this.speed; newSpeedY = 0; newX1 = newX2 = this.x; if (this.y % 16 > 8 + vy) { newY1 = this.y + 16 - this.y % 16; newY2 = this.y - this.y % 16; } else { newY1 = this.y - this.y % 16; newY2 = this.y + 16 - this.y % 16; } break; default: this.emit('task-done', 'Unknown direction "' + direction + '"'); throw new Error('Unknown direction "' + direction + '"'); } var intersects = this.field.intersect(this, newX1, newY1); for (var i in intersects) { if (intersects[i].z == this.z) { canTurn = false; } } if (canTurn) { // new place is clear, turn: this.field.setXY(this, newX1, newY1); this.setSpeedX(newSpeedX); this.setSpeedY(newSpeedY); this.direction = direction; this.emit('change'); } else { canTurn = true; var intersects = this.field.intersect(this, newX2, newY2); for (var i in intersects) { if (intersects[i].z == this.z) { canTurn = false; } } if (canTurn) { // new place is clear, turn: this.field.setXY(this, newX2, newY2); this.setSpeedX(newSpeedX); this.setSpeedY(newSpeedY); this.direction = direction; this.emit('change'); }; } } this.emit('task-done'); return canTurn; }; Tank.prototype.move = function(distance) { this.distanceLeft = distance; this.moveOn = true; }; Tank.prototype.startMove = function() { this.distanceLeft = null; this.moveOn = true; }; Tank.prototype.stopMove = function() { this.distanceLeft = null; this.moveOn = false; if (this.onIce) { this.glidingTimer = 1000/30; // 30ms step } }; /** * Bullet may be undefined (see BonusGrenade) */ Tank.prototype.hit = function(bullet) { if (this.armoredTimer > 0) { return true; } // do not hit your confederates (or yourself) if (!bullet || this.clan != bullet.clan) { if (bullet) { this.lives--; } else { this.lives = 0; } if (this.lives <= 0) { if (bullet && bullet.tank.user) { bullet.tank.user.addReward(this.reward); } if (this.user) { this.user.hit(); } else { this.field.remove(this); } } if (bullet && (this.bonus || (this.user && !this.clan.enemiesClan.isBots()))) { this.bonus = false; var bonuses = [BonusStar, BonusGrenade, BonusShovel, BonusHelmet, BonusLive, BonusTimer]; this.field.add(new (bonuses[Math.floor(Math.random()*(bonuses.length-0.0001))])( Math.round((Math.random() * (this.field.width / 16 - 2))) * 16 + 16, Math.round((Math.random() * (this.field.height / 16 - 2))) * 16 + 16 )); } } return true; }; Tank.prototype.resetPosition = function() { this.maxBullets = 1; this.bulletPower = 1; this.distanceLeft = null; this.direction = null; this.moveOn = 0; this.setSpeedX(0); this.setSpeedY(-this.speed); this.bullets = []; this.armoredTimer = this.clan ? this.clan.defaultArmoredTimer : Tank.defaultArmoredTimer; this.birthTimer = 1 * 1000/30; // 30ms step if (this.field) { this.field.setXY(this, this.initialPosition.x, this.initialPosition.y); } this.emit('change'); };
JavaScript
/** * drawable * coordinates */ Trees = function Trees(x, y) { AbstractGameObject.call(this, 8, 8); this.x = x; this.y = y; this.z = 2; this.img[0] = 'img/trees.png'; }; Trees.prototype = new AbstractGameObject(); Trees.prototype.constructor = Trees; Eventable(Trees.prototype); Trees.prototype.serialize = function() { return [ serializeTypeMatches['Trees'], // 0 this.id, // 1 this.x, this.y ]; // z is constant }; Trees.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Trees.prototype.hit = function(bullet) { return false; };
JavaScript
Base = function Base(x, y) { AbstractGameObject.call(this, 16, 16); this.x = x; this.y = y; this.img[0] = 'img/base.png'; this.shootDown = false; }; Base.prototype = new AbstractGameObject(); Base.prototype.constructor = Base; Base.prototype.baseEdge = { 1: [ {x: 11, y: 23} , {x: 11, y: 24} , {x: 11, y: 25} , {x: 12, y: 23} , {x: 13, y: 23} , {x: 14, y: 23} , {x: 14, y: 24} , {x: 14, y: 25}], 2: [ {x: 11, y: 0} , {x: 11, y: 1} , {x: 11, y: 2} , {x: 12, y: 2} , {x: 13, y: 2} , {x: 14, y: 2} , {x: 14, y: 1} , {x: 14, y: 0}] }; Eventable(Base.prototype); Base.prototype.serialize = function() { return [ serializeTypeMatches['Base'], this.id, this.x, this.y, this.shootDown ]; // z is constant }; Base.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } this.shootDown = data[4]; }; Base.prototype.hit = function() { this.shootDown = true; this.clan.premade.gameOver(this.clan.enemiesClan, 2000); this.emit('change'); return true; }; Base.prototype.armor = function() { this.armoredTimer = 10 * 1000/30; // 30ms step var edge = this.baseEdge[this.clan.n]; for (var i in edge) { var walls = this.field.intersect(this, edge[i].x*16+8, edge[i].y*16+8, 8, 8); var convert = true; for (var j in walls) { if (!(walls[j] instanceof Wall)) { convert = false; } } if (convert) { for (var j in walls) { this.field.remove(walls[j]); } this.field.add(new SteelWall(edge[i].x*16+8, edge[i].y*16+8)); } } }; Base.prototype.disarm = function() { var edge = this.baseEdge[this.clan.n]; for (var i in edge) { var walls = this.field.intersect(this, edge[i].x*16+8, edge[i].y*16+8, 8, 8); var convert = true; for (var j in walls) { if (!(walls[j] instanceof Wall)) { convert = false; } } if (convert) { for (var j in walls) { this.field.remove(walls[j]); } this.field.add(new Wall(edge[i].x*16+ 4, edge[i].y*16+ 4)); this.field.add(new Wall(edge[i].x*16+ 4, edge[i].y*16+12)); this.field.add(new Wall(edge[i].x*16+12, edge[i].y*16+ 4)); this.field.add(new Wall(edge[i].x*16+12, edge[i].y*16+12)); } } }; Base.prototype.step = function() { if (this.armoredTimer > 0) { if (--this.armoredTimer <= 0) { this.disarm(); } } }; Base.prototype.animateStep = function(step) { if (this.shootDown) { this.img[0] = 'img/base-hit.png'; } };
JavaScript
OnFieldAnimation = function OnFieldAnimation(step, hw, hh) { AbstractGameObject.call(this, hw, hh); this.firstStep = step; }; OnFieldAnimation.prototype = new AbstractGameObject(); OnFieldAnimation.prototype.constructor = OnFieldAnimation; BulletHitAnimation = function BulletHitAnimation(step, x, y) { OnFieldAnimation.call(this, step, 16, 16); this.x = x; this.y = y; this.img[0] = 'img/hit1.png'; }; BulletHitAnimation.prototype = new OnFieldAnimation(); BulletHitAnimation.prototype.constructor = BulletHitAnimation; BulletHitAnimation.prototype.animateStep = function(step) { if (step - this.firstStep > 2) { this.field.remove(this); } else if (step - this.firstStep > 1) { this.img[0] = 'img/hit2.png'; } }; TankHitAnimation = function TankHitAnimation(step, x, y) { OnFieldAnimation.call(this, step, 16, 16); this.x = x; this.y = y; this.img[0] = 'img/hit1.png'; }; TankHitAnimation.prototype = new OnFieldAnimation(); TankHitAnimation.prototype.constructor = TankHitAnimation; TankHitAnimation.prototype.animateStep = function(step) { if (step - this.firstStep > 5) { this.field.remove(this); } else if (step - this.firstStep > 3) { this.hw = this.hh = 32; // don't care about intersections this.img[0] = 'img/hit3.png'; } else if (step - this.firstStep > 1) { this.img[0] = 'img/hit2.png'; } };
JavaScript
TankBot = function TankBot(x, y, bonus) { Tank.apply(this, arguments); // call parent constructor this.setSpeedY(this.speed); this.moveOn = true; this.bonus = bonus; this.clan = null; this.armoredTimer = 0; this.fireTimer = 0; // do not fire too fast }; TankBot.prototype = new Tank(); TankBot.prototype.constructor = TankBot; TankBot.prototype.reward = 100; TankBot.prototype.imgBase = 'img/normal-bot'; TankBot.prototype.step = function(paused) { if ((this.birthTimer <= 0) && !paused) { if ((this.stuck || Math.random() < 0.03) && this.fireTimer <= 0) { this.fire(); this.fireTimer = 0.5 * 1000/30; // 30ms step } if (this.stuck || Math.random() < 0.007) { // move percents var mp = { 'north': this.y / 500, 'east': (416 - this.x) / 416, 'south': (500 - this.y) / 500, 'west': this.x / 416 }; var percent = Math.random() * (mp['north'] + mp['east'] + mp['south'] + mp['west']); for (var i in mp) { percent -= mp[i]; if (percent < 0) { this.turn(i); break; } } } } Tank.prototype.step.call(this, paused); }; TankBot.prototype.onBonus = function(bonus) { }; FastBulletTankBot = function FastBulletTankBot(x, y, bonus) { TankBot.apply(this, arguments); // call parent constructor }; FastBulletTankBot.prototype = new TankBot(); FastBulletTankBot.prototype.constructor = FastBulletTankBot; FastBulletTankBot.prototype.reward = 200; FastBulletTankBot.prototype.imgBase = 'img/fast-bullet-bot'; FastBulletTankBot.prototype.bulletSpeed = 8; // default speed FastTankBot = function FastTankBot(x, y, bonus) { TankBot.apply(this, arguments); // call parent constructor }; FastTankBot.prototype = new TankBot(); FastTankBot.prototype.constructor = FastTankBot; FastTankBot.prototype.reward = 300; FastTankBot.prototype.imgBase = 'img/fast-bot'; FastTankBot.prototype.speed = 3; // default speed HeavyTankBot = function HeavyTankBot(x, y, bonus) { TankBot.apply(this, arguments); // call parent constructor this.lives = 3; }; HeavyTankBot.prototype = new TankBot(); HeavyTankBot.prototype.constructor = HeavyTankBot; HeavyTankBot.prototype.reward = 400; HeavyTankBot.prototype.imgBase = 'img/heavy-bot';
JavaScript
/** * drawable * coordinates */ Wall = function Wall(x, y, hw, hh) { AbstractGameObject.call(this, hw ? hw : 4, hh ? hh : 4); this.x = x; this.y = y; this.z = 1; this.img[0] = 'img/brick-wall.png'; }; Wall.prototype = new AbstractGameObject(); Wall.prototype.constructor = Wall; Eventable(Wall.prototype); Wall.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.x, this.y ]; // z is constant }; Wall.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Wall.prototype.hit = function(bullet) { // coordinate for search niarest objects var x = this.x, y = this.y; if (bullet.speedX != 0) { switch (Math.ceil((y % 32) / 8)) { case 1: case 3: y += 8; break; case 2: case 4: y -= 8; break; } } else { // if (bullet.speedY > 0) switch (Math.ceil((x % 32) / 8)) { case 1: case 3: x += 8; break; case 2: case 4: x -= 8; break; } } this.field.remove(this); // after remove to avoid recusion var intersect = this.field.intersect(this, x, y, 1, 1); for (var i in intersect) { if (typeof intersect[i]['hit'] == 'function') { intersect[i].hit(bullet); } } return true; }; SteelWall = function SteelWall(x, y) { Wall.call(this, x, y, 8, 8); this.img[0] = 'img/steel-wall.png'; }; SteelWall.prototype = new Wall(); SteelWall.prototype.constructor = SteelWall; SteelWall.prototype.hit = function(bullet) { if (bullet.power == 2) { this.field.remove(this); } return true; };
JavaScript
/** * drawable * coordinates */ Checkpoint = function Checkpoint(x, y) { AbstractGameObject.call(this, 16, 16); this.x = x; this.y = y; this.z = 0; this.img[0] = 'img/checkpoint.png'; }; Checkpoint.prototype = new AbstractGameObject(); Checkpoint.prototype.constructor = Checkpoint; Eventable(Checkpoint.prototype); Checkpoint.prototype.serialize = function() { return [ serializeTypeMatches[this.constructor.name], // 0 this.id, // 1 this.x, // 2 this.y // 3 ]; // z is constant }; Checkpoint.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Checkpoint.prototype.hit = function(bullet) { return false; };
JavaScript
/** * drawable * coordinates */ Ice = function Ice(x, y) { AbstractGameObject.call(this, 8, 8); this.x = x; this.y = y; this.z = 0; this.img[0] = 'img/ice.png'; }; Ice.prototype = new AbstractGameObject(); Ice.prototype.constructor = Ice; Eventable(Ice.prototype); Ice.prototype.serialize = function() { return [ serializeTypeMatches['Ice'], // 0 this.id, // 1 this.x, this.y ]; // z is constant }; Ice.prototype.unserialize = function(data) { this.id = data[1]; if (this.field) { this.field.setXY(this, data[2], data[3]); } else { // first unserialize, before adding to field -> may set x and y directly this.x = data[2]; this.y = data[3]; } }; Ice.prototype.hit = function(bullet) { return false; };
JavaScript
Clan = function Clan(n, defaultArmoredTimer) { this.capacity = 2; // max users this.n = n; this.defaultArmoredTimer = defaultArmoredTimer; this.timer = 0; this.enemiesClan = null; this.users = []; this.goals = new TList(); this.base = new Base(); this.base.clan = this; this.tankPositions = Clan.tankPositions['clan' + n]; }; Clan.tankPositions = { 'clan1': [{x: 4, y: 12}, {x: 8, y: 12}], 'clan2': [{x: 4, y: 0}, {x: 8, y: 0}], 'bots' : [{x: 16, y: 16}, {x: 13*32 / 2, y: 16}, {x: 13*32 - 16, y: 16}] }; Clan.prototype.attachUser = function(user) { if (user.clan) user.clan.detachUser(user); for (var positionId = 0; positionId < this.capacity; positionId++) { if (this.users[positionId] === undefined) { this.users[positionId] = user; user.positionId = positionId; break; } } user.tank = new Tank(); user.tank.on('task-done', function(message){ user.clientMessage('task-done', message); }); user.tank.user = user; user.tank.clan = user.clan = this; user.emit('change'); }; Clan.prototype.detachUser = function(user) { if (this.users[user.positionId] == user) { delete this.users[user.positionId]; if (user.tank.field) { user.tank.field.remove(user.tank); } user.tank.clan = null; user.tank = null; user.clan = null; user.emit('change'); } }; Clan.prototype.size = function() { var res = 0; for (var i = 0; i < this.capacity; i++) { if (this.users[i]) { res++; } } return res; }; Clan.prototype.isFull = function() { return this.size() == this.capacity; }; /** * is this clan of classic bot team * @return */ Clan.prototype.isBots = function() { return false; }; Clan.prototype.step = function() { var activeUsers = 0; for (var i in this.users) { if (this.users[i].lives >= 0) { this.users[i].tank.step(this.timer > 0); activeUsers++; } } if (activeUsers == 0) { this.base.hit(); } this.base.step(); this.timer > 0 && this.timer--; }; Clan.prototype.startGame = function(game) { this.game = game; for (var i in this.users) { var user = this.users[i]; if (user.lives < 0) user.lives = 0; // todo hack // before add to field, may set x y directly user.tank.initialPosition.x = user.tank.x = 32*this.tankPositions[i].x + user.tank.hw; user.tank.initialPosition.y = user.tank.y = 32*this.tankPositions[i].y + user.tank.hh; user.tank.resetPosition(); this.game.field.add(user.tank); user.emit('change'); // user.tankId } this.base.shootDown = false; this.base.x = this.game.field.width / 2; this.base.y = (this.n == 1) ? (this.game.field.height - 16) : 16; this.game.field.add(this.base); }; Clan.prototype.pauseTanks = function() { this.timer = 3 * 30; // 30 steps per second }; BotsClan = function BotsClan(n) { Clan.apply(this, arguments); this.capacity = 6; this.tankPositions = Clan.tankPositions['bots']; }; BotsClan.prototype = new Clan(); BotsClan.prototype.constructor = BotsClan; BotsClan.prototype.isBots = function() { return true; }; BotsClan.prototype.step = function() { if (this.users.length == 0 && this.botStack.count() == 0) { this.base.hit(); } this.base.step(); if (!this.isFull() && this.botStack.count() > 0 && Math.random() < 0.01) { var botX = this.tankPositions[this.currentBotPosition].x; var botY = this.tankPositions[this.currentBotPosition].y; if (this.game && this.game.field.canPutTank(botX, botY)) { var bot = this.botStack.pop(); delete bot['id']; bot.removeAllListeners('change'); // before add to field, may set x y directly bot.x = botX; bot.y = botY; this.users.push({tank: bot}); this.game.field.add(bot); // "remove handler defined in constructor" WFT? this.currentBotPosition = (this.currentBotPosition + 1) % 3; } } for (var i in this.users) { this.users[i].tank.step(this.timer > 0); } this.timer > 0 && this.timer--; }; BotsClan.prototype.startGame = function(game, level) { this.game = game; var bots = this.users = []; this.game.field.on('remove', function(object) { for (var i in bots) { if (bots[i].tank == object) { bots.splice(i, 1); } } }); this.currentBotPosition = 0; this.botStack = new TList(); // todo move from this function var enemies = level.getEnemies(); for (var i = enemies.length - 1; i >= 0; i-- ) { var bonus = [3,10,17].indexOf(i) >= 0; var bot; // var bonus = true; switch (enemies[i]) { case 1: bot = new TankBot(0, 0, bonus); break; case 2: bot = new FastTankBot(0, 0, bonus); break; case 3: bot = new FastBulletTankBot(0, 0, bonus); break; case 4: bot = new HeavyTankBot(0, 0, bonus); break; } bot.clan = this; bot.id = Field.autoIncrement++; // todo hack, to bots in stack have id on client this.botStack.add(bot); } this.base.shootDown = false; }; BotsClan.prototype.pauseTanks = function() { this.timer = 10 * 1000/30; // 30ms step }; /** * FIXME should be a user's clan, not enemies * @param n * @return */ LearnerClan = function LearnerClan(n) { Clan.apply(this, arguments); }; LearnerClan.prototype = new Clan(); LearnerClan.prototype.constructor = LearnerClan; LearnerClan.prototype.startGame = function(game, level) { this.game = game; this.base.shootDown = false; this.base.x = this.game.field.width / 2; this.base.y = (this.n == 1) ? (this.game.field.height - 16) : 16; if (level.getGoals) { this.goals.clear(); var goals = level.getGoals(this); for (var i = 0 ; i < goals.length ; i++) { goals[i].reset(); this.goals.add(goals[i]); } } }; LearnerClan.prototype.step = function() { var self = this; if (this.goals.count() > 0) { var goals = 0; for (var i in this.goals.items) { this.goals.items[i].check(); if (this.goals.items[i].status) { goals++; } } if (goals == this.goals.count()) { self.premade.gameOver(self.enemiesClan, 1000); } } this.base.step(); };
JavaScript
Field = function Field(width, height) { this.width = width; this.height = height; this.objects = null; this.clear(); this.setMaxListeners(100); // @todo }; Eventable(Field.prototype); Field.autoIncrement = 1; // todo eliminate? Field.prototype.clear = function() { this.objects = new MapTiled(this.width, this.height); }; Field.prototype.add = function(object) { if (object.id === undefined) { object.id = Field.autoIncrement++; } object.field = this; this.objects.add(object); if (!isClient()) { this.emit('add', object); var self = this; object.on('change', function(){ self.emit('change', this); }); object.onAddToField && object.onAddToField(); } }; Field.prototype.remove = function(object) { if (this.objects.remove(object)) { this.emit('remove', object); object.removeAllListeners && object.removeAllListeners(); } }; Field.prototype.setXY = function(item, newX, newY) { return this.objects.setXY(item, newX, newY); }; Field.prototype.move = function(item, newX, newY) { return this.objects.move(item, newX, newY); }; Field.prototype.get = function(id) { return this.objects.get(id); }; /** * * @param object AbstractGameObject * @return */ Field.prototype.intersect = function(object, newX, newY, boundX, boundY) { return this.objects.intersects(object, newX, newY, boundX, boundY); }; Field.prototype.terrain = function(map) { this.add(new Delimiter( - 20, this.height / 2, 20, this.height / 2)); this.add(new Delimiter(this.width + 20, this.height / 2, 20, this.height / 2)); this.add(new Delimiter(this.width / 2, - 20, this.width / 2, 20)); this.add(new Delimiter(this.width / 2, this.height + 20, this.width / 2, 20)); for (var y = 0 ; y < 26 ; y++) { for (var x = 0 ; x < 26 ; x++) { switch (map[y][x]) { case 1: this.add(new Wall(x*16+ 4, y*16+ 4)); this.add(new Wall(x*16+12, y*16+ 4)); this.add(new Wall(x*16+ 4, y*16+12)); this.add(new Wall(x*16+12, y*16+12)); break; case 2: this.add(new SteelWall(x*16+8, y*16+8)); break; case 3: this.add(new Trees(x*16+8, y*16+8)); break; case 4: this.add(new Water(x*16+8, y*16+8)); break; case 5: this.add(new Ice(x*16+8, y*16+8)); break; } } } // this.add(new BonusTimer(10*16, 20*16)); }; Field.prototype.traversal = function(callback, thisObj) { this.objects.traversal(callback, thisObj); }; Field.prototype.canPutTank = function(x, y) { var res = true; var intersects = this.intersect({}, x, y, 16, 16); for (var i in intersects) { if (!(intersects[i] instanceof Bonus)) { res = false; } }; return res; }; //===== client methods ========================================================= /** * todo almost copy of TList.prototype.updateWith */ Field.prototype.updateWith = function(events) { for (var i in events) { var eventType = events[i][0/*type*/]; var eventData = events[i][1/*data*/]; var type = unserializeTypeMatches[eventData[0/*type*/]]; var id = parseInt(eventData[1/*id*/]); switch (eventType) { case 'r'/*remove*/: if (obj = this.objects.get(id)) { obj.unserialize(eventData); // for bullets finalX and finalY this.remove(obj); } break; case 'a'/*add*/: case 'c'/*change*/: var obj = this.objects.get(id); if (obj) { obj.unserialize(eventData); } else { obj = new (window[type])(); obj.unserialize(eventData); this.add(obj); } break; } } };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getGoals = function(clan) { return [new GoalCheckPoint(clan, 4*16, 20*16), new GoalCheckPoint(clan, 9*16, 15*16), new GoalCheckPoint(clan, 14*16, 20*16)]; }; /* Program Program4; var a: integer; begin for a:=1 to 3 do begin move(5); turn('left'); move(5); turn('left'); turn('left'); end end. */
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getGoals = function(clan) { return [new GoalCheckPoint(clan, (9 + (Math.random() > 0.5 ? +5 : -5))*16, 14*16)]; }; /* Program Program3; begin move(11); if x>checkpointx then turn('west') else turn('east'); move(5); end. */
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getGoals = function(clan) { return [new GoalCheckPoint(clan, 19*16, 14*16), new GoalCheckPoint(clan, 7*16, 10*16)]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getGoals = function(clan) { return [new GoalCheckPoint(clan, 19*16, 14*16)]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,3,3,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,2,2,2,2,0,0,0,1,1], [1,1,0,0,0,0,0,0,0,0,0,0,2,2,3,3,0,2,2,2,2,0,0,0,1,1], [0,0,0,0,0,0,0,0,3,3,0,2,2,2,2,0,0,0,2,2,3,3,0,0,0,0], [0,0,0,0,0,0,2,2,3,3,0,2,2,2,2,0,0,0,0,0,3,3,0,0,0,0], [0,0,0,0,0,2,2,2,2,0,0,0,2,2,3,3,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,2,2,2,2,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,0,0,3,3,0,0,3,3,0,0,3,3,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,2,2,3,3,0,0,3,3,2,2,3,3,0,0,0,0,0,0], [2,2,1,1,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,0,0,1,1,2,2], [2,2,1,1,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,0,0,1,1,2,2], [0,0,0,0,0,0,3,3,2,2,3,3,0,0,3,3,2,2,3,3,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,0,0,3,3,0,0,3,3,0,0,3,3,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,1,1], [1,1,0,0,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,1,1], [1,1,0,0,0,0,3,3,2,2,3,3,0,0,3,3,2,2,3,3,0,0,0,0,1,1], [1,1,0,0,0,0,3,3,0,0,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0], [0,0,0,0,1,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0], [0,0,0,0,1,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,3,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,3,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,0,0,3,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,3,3,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,3,3,0,0,0,0,0,0,0,0,3,3,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,0,0,0,0,3,3,0,0,3,3,0,0,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,0,0,0,0,3,3,0,0,3,3,2,2,0,0,0,0,0,0,0,0], [0,0,3,3,0,0,3,3,0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0], [0,0,3,3,0,0,3,3,0,0,3,3,0,0,0,0,3,3,1,1,0,0,0,0,0,0], [0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0], [0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,3,3,3,3,2,2,0,0,0,0], [0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0], [0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3,1,1,0,0], [0,0,0,0,0,0,3,3,0,0,0,0,3,3,0,0,3,3,3,3,3,3,3,3,0,0], [0,0,0,0,0,0,3,3,0,0,0,0,3,3,0,0,3,3,3,3,3,3,3,3,0,0], [1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,3,3,3,3,3,3,2,2], [1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,3,3,3,3,3,3,2,2], [1,1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,3,3,3,3,3,3,3,3], [1,1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,3,3,3,3,3,3,3,3], [2,2,1,1,1,1,0,0,0,0,0,0,0,0,0,0,3,3,0,0,3,3,3,3,3,3], [2,2,1,1,1,1,0,0,0,0,0,1,1,1,1,0,3,3,0,0,3,3,3,3,3,3], [2,2,2,2,1,1,1,1,0,0,0,1,0,0,1,0,3,3,0,0,0,0,3,3,3,3], [2,2,2,2,1,1,1,1,0,0,0,1,0,0,1,0,3,3,0,0,0,0,3,3,3,3] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,2,2,0,0,1,1,2,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,1,1,0,0,1,1,3,3,0,0,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,1,1,0,0,1,1,3,3,0,0,0,0,1,1,1,1,1,1,0,0,0,0], [0,0,3,3,3,3,0,0,1,1,3,3,0,1,1,0,0,0,0,0,0,0,2,2,2,2], [0,0,3,3,3,3,0,0,1,1,3,3,0,1,1,0,0,0,0,0,0,0,2,2,2,2], [3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,0,0,0,1,1,1,0,0], [3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,0,0,0,1,1,1,0,0], [0,0,0,0,3,3,3,3,0,0,0,0,2,2,1,1,0,0,0,1,1,1,1,1,0,1], [0,0,0,0,3,3,3,3,1,1,1,1,0,0,1,1,0,0,0,1,1,1,0,0,0,1], [1,1,2,2,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1], [1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1], [0,1,0,0,0,0,1,1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,1,1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,0,0,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,0,0,0,2,2,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,0,0,0,2,2,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [1,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [1,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,5,5,5,5,5], [0,1,0,0,1,1,0,0,0,0,0,1,1,1,1,0,5,5,5,5,5,5,5,5,5,5], [0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,5,5,5,5,5,5,5,5], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,5,5,5,5,5,5,5,5] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0], [3,3,0,0,0,0,3,3,1,1,3,3,1,1,3,3,0,0,0,0,3,3,0,0,0,0], [3,3,0,0,0,0,3,3,1,1,3,3,1,1,3,3,0,0,0,0,3,3,0,0,0,0], [1,1,3,3,3,3,1,1,1,1,1,1,1,1,1,1,3,3,3,3,1,1,3,3,0,0], [1,1,3,3,3,3,1,1,1,1,1,1,1,1,1,1,3,3,3,3,1,1,3,3,0,0], [1,1,1,1,1,1,1,1,2,2,1,1,2,2,1,1,1,1,1,1,1,1,3,3,0,0], [1,1,1,1,1,1,1,1,2,2,1,1,2,2,1,1,1,1,1,1,1,1,3,3,0,0], [4,4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,4,4,4,4,4,4,3,3,0,0], [4,4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,4,4,4,4,4,4,3,3,0,0], [4,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4,4,3,3], [4,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4,4,3,3], [1,1,1,1,1,1,4,4,1,1,1,1,1,1,4,4,1,1,1,1,1,1,3,3,3,3], [1,1,1,1,1,1,4,4,1,1,1,1,1,1,4,4,1,1,1,1,1,1,3,3,3,3], [1,1,1,1,4,4,4,4,4,4,1,1,4,4,4,4,4,4,1,1,1,1,4,4,4,4], [1,1,1,1,4,4,4,4,4,4,1,1,4,4,4,4,4,4,1,1,1,1,4,4,4,4], [3,3,4,4,4,4,3,3,3,3,3,3,3,3,3,3,4,4,4,4,3,3,4,4,3,3], [3,3,4,4,4,4,3,3,3,3,3,3,3,3,3,3,4,4,4,4,3,3,4,4,3,3], [0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,3,3,0,0], [0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,4,4,3,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0], [2,2,0,0,0,0,4,4,3,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0], [3,3,0,0,0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,4,4,4,4,0,0], [3,3,2,2,0,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,4,4,4,4,0,0], [3,3,3,3,0,0,2,2,0,0,0,1,0,0,0,0,2,0,3,3,4,4,0,0,0,0], [3,3,3,3,0,0,0,0,1,1,0,1,0,0,0,0,2,0,3,3,4,4,0,0,0,0], [3,3,3,3,3,3,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,3,3,0,0,0,0,2,2,1,1,0,1,0,0,0,0,0,0,0,0,2,2], [3,3,3,3,2,2,0,0,0,0,0,1,0,0,2,2,0,0,0,0,0,0,0,0,3,3], [3,3,3,3,0,0,2,2,0,0,0,1,0,0,2,2,1,1,0,0,0,0,2,2,3,3], [3,3,2,2,0,0,0,0,1,1,2,2,0,0,0,1,0,0,2,2,0,0,3,3,3,3], [3,3,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,1,0,1,1,2,2,0,0,0,0,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,2,0,0,0,0,3,3,3,3,3,3], [0,0,0,0,4,4,3,3,0,2,0,0,0,0,1,0,1,1,0,0,2,2,3,3,3,3], [0,0,0,0,4,4,3,3,0,2,0,0,0,0,1,0,0,0,2,2,0,0,3,3,3,3], [0,0,4,4,4,4,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,3,3], [0,0,4,4,4,4,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,3,3], [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,3,3,4,4,0,0,0,0,2,2], [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,3,3,4,4,0,0,0,0,0,0], [2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,4,4,0,0,0,0], [2,2,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,4,4,4,4,0,0,0,0], [2,2,2,2,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,2,2], [2,2,2,2,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,2,2] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1], [0,0,4,4,4,4,4,4,4,4,4,4,0,0,1,1,1,0,0,0,0,0,1,1,2,2], [0,0,4,4,4,4,4,4,4,4,4,4,0,0,1,1,1,0,0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,4,4,0,0,1,1,0,0,2,2,2,0,1,1,0,0], [0,0,0,0,2,2,2,2,2,2,4,4,0,0,1,1,0,0,2,2,2,0,1,1,0,0], [1,1,0,0,1,1,1,1,1,1,4,4,4,4,4,4,0,0,4,4,1,1,1,1,0,0], [1,1,0,0,1,1,1,1,1,1,4,4,4,4,4,4,0,0,4,4,1,1,1,1,0,0], [0,0,0,0,0,0,0,0,2,2,4,4,0,0,0,0,0,0,4,4,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,4,4,0,0,0,0,0,0,4,4,0,0,0,0,0,0], [4,4,4,4,4,4,0,0,4,4,4,4,1,1,1,1,0,0,4,4,0,0,0,0,0,0], [4,4,4,4,4,4,0,0,4,4,4,4,1,1,1,1,0,0,4,4,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2,0,0,4,4,4,4,4,4,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,4,4,4,4,4,4,0,0], [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,2,2,2,2,0,0,0,0,0,0,1,1,1,1,0,0,0,1], [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1], [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1], [1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0], [2,2,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [2,2,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0], [2,2,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,4,4,4,4,0,0,4,4], [1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,4,4,4,4,0,0,4,4], [1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,4,4,4,4,0,0,4,4,4,4,4,4,0,0,1,1,1,1], [0,0,0,0,1,1,0,0,4,4,4,4,0,0,4,4,4,4,4,4,0,0,1,1,1,1], [1,1,1,1,0,0,0,0,4,4,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0], [1,1,1,1,0,0,0,0,4,4,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0], [0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0], [4,4,4,4,4,4,0,0,4,4,0,0,2,2,0,0,1,1,0,0,0,2,0,0,0,0], [4,4,4,4,4,4,0,0,4,4,0,0,2,2,0,0,1,1,0,0,0,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1], [0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,2,1,1,1,1], [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0], [1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0], [1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,3,3,3,4,4,1,1,1,1,1,1,1,1,2,2,2,2,2]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,3,3,3,3,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,3,3,3,3,0,0,0,0,0,0], [0,0,1,0,0,2,0,0,1,0,0,0,0,0,0,0,0,1,3,3,1,0,0,1,3,3], [0,0,1,0,0,2,0,0,1,0,0,0,0,0,0,0,0,1,3,3,1,0,0,1,3,3], [0,0,1,0,0,2,0,0,1,0,0,0,1,1,0,0,0,1,3,3,1,0,0,1,3,3], [0,0,1,0,0,2,0,0,1,0,0,0,1,1,0,0,0,1,3,3,1,0,0,1,3,3], [0,0,1,1,0,0,0,0,1,1,0,0,2,2,0,0,1,1,3,3,0,0,1,1,3,3], [0,0,1,1,0,0,0,0,1,1,0,0,2,2,0,0,1,1,3,3,0,0,1,1,3,3], [0,0,0,0,0,0,0,1,2,2,0,0,1,1,0,0,1,1,2,0,0,0,3,3,3,3], [0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,2,0,0,0,3,3,3,3], [1,1,1,1,1,0,0,0,0,0,3,3,1,1,3,3,0,0,0,0,0,1,1,1,1,1], [1,1,1,1,1,0,0,0,0,0,3,3,1,1,3,3,0,0,0,0,0,1,1,1,1,1], [0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,1,3,3,3,3,3,3,1,0,0,0,0,0,0,0,0,0], [2,2,1,1,1,1,0,0,1,1,3,3,3,3,3,3,1,1,0,1,1,1,1,1,2,2], [2,2,1,1,1,1,0,0,0,0,0,3,3,3,3,3,0,0,0,1,1,1,1,1,2,2], [2,2,2,2,2,2,0,0,0,0,0,0,3,3,0,0,0,0,0,0,2,2,2,2,2,2], [0,0,0,0,0,0,0,0,1,1,0,0,3,3,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,1,1,1,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,1,1,1,3,3], [0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3], [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,3,3,3,3], [0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,3,3,3,3] ]; }; module.exports.getEnemies = function() { return [3,3,3,3,3,3,3,2,2,1,1,1,1,1,1,1,1,1,4,4]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0], [1,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0], [1,0,1,0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0], [1,0,1,0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0], [0,1,0,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,0], [0,1,0,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,0], [0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,1,1,1,1,1,0,0,0,0], [0,0,1,0,0,0,1,1,0,1,1,0,0,0,1,0,1,1,1,1,1,1,0,0,0,0], [0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0], [0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0], [0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,1,0,1,1,0,0,0,0], [0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,1,0,1,1,0,0,0,0], [0,0,0,1,0,0,0,0,1,0,1,1,1,1,1,0,0,0,1,0,1,1,0,0,0,0], [0,0,0,1,0,0,0,0,1,0,1,1,1,1,1,0,0,0,1,0,1,1,0,0,0,0], [0,0,0,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,0,1,0,1,1,1,1], [0,0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,0,1,0,0,0,1,1], [0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1], [0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1], [0,0,0,0,1,0,0,0,1,1,0,1,1,0,1,1,1,1,0,0,0,0,0,1,0,0], [0,0,0,0,1,0,0,0,1,1,0,1,1,0,1,1,1,1,0,0,0,0,0,1,0,0], [0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0], [0,0,0,0,1,0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,0,0,1,0,0,0], [0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0], [0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,2,2,2,2,3,3,3,3,1,1,2,2,1,1,3,3,3,3,2,2,2,2,0,0], [0,0,2,2,2,2,3,3,3,3,1,1,2,2,1,1,3,3,3,3,2,2,2,2,0,0], [0,0,0,0,0,0,2,2,3,3,3,3,2,2,3,3,3,3,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,3,3,3,3,2,2,3,3,3,3,2,2,0,0,0,0,0,0], [3,3,0,0,0,0,0,0,2,2,3,3,3,3,3,3,2,2,0,0,0,0,0,0,3,3], [3,3,0,0,0,0,0,0,2,2,3,3,3,3,3,3,2,2,0,0,0,0,0,0,3,3], [2,2,3,3,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,3,3,2,2], [2,2,3,3,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,3,3,2,2], [3,3,0,0,0,0,0,0,0,0,2,2,3,3,2,2,0,0,0,0,0,0,0,0,3,3], [3,3,0,0,0,0,0,0,2,2,0,0,3,3,0,0,2,2,0,0,0,0,0,0,3,3], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,0,0,2,2,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,3,3,0,0,0,0], [0,0,2,2,2,2,0,0,1,1,3,3,3,3,2,2,0,0,1,1,3,3,1,1,0,0], [0,0,3,3,3,3,0,0,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,0,0], [1,1,3,3,3,3,1,1,3,3,3,3,3,3,3,3,1,1,3,3,3,3,3,3,1,1], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [2,2,3,3,4,4,3,3,3,3,3,3,3,3,3,3,4,4,3,3,3,3,3,3,3,3], [2,2,3,3,4,4,3,3,3,3,3,3,3,3,3,3,4,4,3,3,3,3,3,3,3,3], [3,3,3,3,4,4,4,4,4,4,3,3,3,3,3,3,4,4,4,4,4,4,3,3,3,3], [3,3,3,3,4,4,4,4,4,4,3,3,3,3,3,3,4,4,4,4,4,4,3,3,3,3], [3,3,3,3,3,3,3,3,4,4,3,3,2,2,3,3,3,3,3,3,4,4,3,3,3,3], [3,3,3,3,3,3,3,3,4,4,3,3,2,2,3,3,3,3,3,3,4,4,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,1,1,1,1,3,3,3,3,3,3,3,3,3,3,2,2], [3,3,3,3,3,3,3,3,3,3,0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0], [3,3,3,3,3,3,3,3,1,1,0,0,0,0,1,1,3,3,3,3,3,3,2,2,0,0], [2,2,3,3,3,3,3,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0], [0,0,2,2,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0], [0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0], [3,3,3,3,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,3,3], [3,3,3,3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,3,3], [3,3,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,2,2], [3,3,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0], [2,2,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,0,0,0], [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0,0], [4,4,0,0,0,1,0,0,2,0,0,0,2,0,0,0,1,1,1,0,0,0,0,0,0,0], [4,4,0,0,0,1,0,0,2,0,0,0,2,0,0,0,1,1,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,4,4,4,4], [0,0,0,0,1,1,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,0,4,4,4,4], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0], [0,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,0,3,3], [0,0,1,1,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,3,3], [3,3,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,3,3,3,3], [3,3,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,3,3,3,3], [2,2,3,3,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,3,3,3,3,2,2], [2,2,3,3,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,3,3,3,3,2,2] ]; }; module.exports.getEnemies = function() { return [3,3,3,3,3,3,3,3,3,2,2,2,2,2,1,1,4,4,4,4]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,3,3,1,1,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2], [1,1,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,3,3,3,3,0,0,0,0,0,0,1,1,0,0,1,1,1,1,1,1,1,0], [3,3,3,3,3,3,3,3,0,0,0,0,0,0,1,1,0,0,1,1,1,1,1,1,1,0], [3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,1,0,0], [3,3,3,3,3,3,3,3,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0], [3,3,3,3,3,3,3,3,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0], [3,3,3,3,3,3,3,3,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,3,3,0,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,3,3,0,0], [0,0,3,3,0,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3], [1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3], [1,1,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0,0,3,3,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,3,3,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,1,3,3,3,3,3,3,3,3], [1,1,0,0,0,0,2,0,0,0,0,0,0,0,1,1,1,1,3,3,3,3,3,3,0,0], [1,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [1,1,1,1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [1,1,1,1,0,0,2,0,0,0,0,1,1,1,1,0,0,0,3,3,3,3,3,3,0,0], [2,2,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0], [2,2,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,4,4]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,3,3,1,1,0,0,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,3,3,3,3,3,3,2,2,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,3,3,3,3,5,5,3,3,3,3,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,1,1,3,3,3,3,5,5,3,3,3,3,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,3,3,3,3,5,5,5,5,5,5,3,3,3,3,1,0,0,0,0,0], [0,0,0,0,2,2,3,3,3,3,5,5,5,5,5,5,3,3,3,3,1,0,0,0,0,0], [0,0,0,0,3,3,3,3,5,5,5,5,5,5,5,5,5,5,3,3,3,3,0,0,0,0], [0,0,1,1,3,3,3,3,5,5,5,5,5,5,5,5,5,5,3,3,3,3,1,1,0,0], [0,0,3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3,0,0], [2,2,3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3,2,2], [3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3], [3,3,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3], [0,0,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,5,5,0,0,0,0,0,0,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,5,5,0,1,1,1,1,0,5,5,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,0,0,0,1,0,0,1,0,0,0,5,5,5,5,3,3,0,0], [0,0,3,3,5,5,5,5,0,0,0,1,0,0,1,0,0,0,5,5,5,5,3,3,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,4,4,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,4,4,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,4,4,0,0,0,0,2,2,0,0,1,1,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,4,4,0,0,1,1,2,2,0,0,1,1,0,0,1,1,0,0,0,0], [2,2,0,0,1,1,4,4,0,0,2,2,0,0,0,0,1,1,0,0,1,1,0,0,0,0], [0,0,0,0,1,1,4,4,0,0,2,2,0,0,1,1,0,0,0,0,1,1,0,0,0,0], [0,0,0,0,1,1,4,4,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,4,4,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,4,4,4,4,0,0,4,4,4,4,4,4,4,4,0,0,0,0,1,1], [1,1,0,0,1,1,4,4,4,4,0,0,4,4,4,4,4,4,4,4,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,4,4,0,0,2,2,2,2], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,3,3,0,0,4,4,0,0,0,0,0,0], [1,1,1,1,0,1,1,1,0,0,2,2,3,3,3,3,3,3,4,4,0,0,0,0,0,0], [1,1,1,1,0,1,1,1,0,0,2,2,3,3,3,3,3,3,4,4,0,0,1,1,1,1], [1,1,0,0,0,1,0,0,0,0,1,1,3,3,3,3,3,3,4,4,0,0,1,1,0,0], [0,0,0,0,0,1,0,0,0,0,1,1,3,3,3,3,3,3,4,4,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,3,3,0,0,4,4,0,0,3,3,0,0], [0,0,0,2,2,0,0,0,0,0,1,1,0,0,3,3,0,0,4,4,0,0,3,3,0,0], [0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,3,3,3,3,3,3], [0,0,0,1,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3], [0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,4,4,3,3,3,3,3,3], [0,0,0,1,1,0,1,1,0,0,0,1,1,1,1,0,0,0,4,4,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,4,4,0,0,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,4,4,0,0,3,3,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0], [0,0,1,1,4,4,4,4,0,0,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,4,4,4,4,0,0,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,4,4,4,4,1,1,3,3,3,3,3,3,4,4,4,4,0,0,2,2,0,0], [0,0,0,0,4,4,4,4,1,1,3,3,3,3,3,3,4,4,4,4,0,0,2,2,0,0], [0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,4,4,4,4,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,4,4,4,4,1,1,0,0,0,0], [0,0,2,2,0,0,0,0,4,4,4,4,0,0,3,3,0,0,0,0,0,0,0,0,0,0], [0,0,2,2,0,0,0,0,4,4,4,4,0,0,3,3,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,1,1,0,0,4,4,4,4,2,2,0,0,0,0,0,0,0,0,1,1,0,0], [3,3,3,3,1,1,0,0,4,4,4,4,2,2,0,0,0,0,0,0,0,0,1,1,0,0], [3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,2], [3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,2], [0,0,1,1,4,4,4,4,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,4,4,4,4,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [2,2,0,0,4,4,4,4,3,3,3,3,4,4,4,4,3,3,3,3,0,0,1,1,0,0], [2,2,0,0,4,4,4,4,3,3,3,3,4,4,4,4,3,3,3,3,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,3,3,0,0,4,4,4,4,3,3,3,3,4,4,4,4,0,0], [0,0,0,0,0,0,0,0,3,3,0,0,4,4,4,4,3,3,3,3,4,4,4,4,0,0], [0,0,0,0,0,0,2,2,3,3,0,0,0,0,0,0,3,3,3,3,4,4,4,4,0,0], [0,0,0,0,0,0,2,2,3,3,0,0,0,0,0,0,3,3,3,3,4,4,4,4,0,0], [0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,2,2,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,2,2,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,3,3,0,0,2,2,2,2,2,2,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,3,3,0,0,0,0,2,2,2,2,0,0,0,0], [0,0,2,2,0,0,0,0,0,0,3,3,2,2,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,2,2,0,0,0,0,0,0,3,3,2,2,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,3,3,2,2,2,2,0,0,0,0,0,0,2,2,2,2,0,0], [0,0,0,0,0,0,0,0,3,3,2,2,2,2,0,0,0,0,0,0,0,0,2,2,0,0], [0,0,2,2,0,0,3,3,2,2,2,2,2,2,0,0,2,2,0,0,0,0,0,0,0,0], [0,0,2,2,0,0,3,3,2,2,2,2,2,2,0,0,2,2,0,0,0,0,0,0,0,0], [0,0,0,2,0,0,2,2,2,2,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0], [0,0,0,2,0,0,2,2,2,2,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0], [2,0,0,0,0,0,0,0,2,2,0,0,2,2,2,2,2,2,0,0,0,0,0,2,0,0], [2,0,0,0,0,0,0,0,2,2,0,0,2,2,2,2,2,2,0,0,0,0,0,2,0,0], [0,0,0,2,2,2,0,0,0,0,0,0,2,2,2,2,3,3,0,0,0,0,2,2,0,0], [0,0,0,2,2,2,0,0,0,0,0,0,2,2,2,2,3,3,0,0,0,0,2,2,0,0], [0,0,2,2,0,0,0,0,0,0,0,0,2,2,3,3,0,0,0,0,2,2,2,2,0,0], [0,0,2,2,0,0,0,0,0,0,0,0,2,2,3,3,0,0,0,0,2,2,2,2,0,0], [0,0,2,2,2,2,2,2,0,0,0,0,3,3,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,3,3,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,2], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,2,2,0,0,2,2,2,2], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [2,2,2,2,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [1,1,1,2,2,2,2,3,3,3,3,3,3,1,1,1,1,1,1,1]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [2,2,2,2,0,0,0,0,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0], [2,2,2,2,0,0,0,0,2,2,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0], [0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,2,2,2,2,3,3], [0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,2,2,2,2,3,3], [0,0,2,2,0,0,0,0,2,2,2,2,2,2,0,0,3,3,0,0,2,2,0,0,0,0], [0,0,2,2,0,0,0,0,2,2,2,2,2,2,0,0,3,3,0,0,2,2,0,0,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,2,2,0,0,2,2,2,2,2,2,0,0,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,2,2,0,0,2,2,2,2,2,2,0,0,0,0], [3,3,2,2,2,2,0,0,2,2,1,1,2,2,1,1,1,1,0,0,0,0,0,0,0,0], [3,3,2,2,2,2,0,0,2,2,1,1,2,2,1,1,1,1,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,3,3,2,2,3,3,0,0,0,0,1,1,0,0,0,0,2,2,2,2], [0,0,0,0,2,2,3,3,2,2,3,3,0,0,0,0,1,1,0,0,0,0,2,2,2,2], [0,0,0,0,2,2,0,0,0,0,3,3,0,0,0,0,2,2,0,0,0,0,2,2,0,0], [0,0,0,0,2,2,0,0,0,0,3,3,0,0,0,0,2,2,0,0,0,0,2,2,0,0], [0,0,0,0,1,1,0,0,0,0,2,2,0,0,0,0,2,2,2,2,1,1,2,2,0,0], [0,0,0,0,1,1,0,0,0,0,2,2,0,0,0,0,2,2,2,2,1,1,2,2,0,0], [3,3,2,2,2,2,2,2,3,3,3,3,1,1,2,2,2,2,0,0,1,1,2,2,0,0], [3,3,2,2,2,2,2,2,3,3,3,3,1,1,2,2,2,2,0,0,1,1,2,2,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,3,3,3,3,0,0,1,1,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,3,3,3,3,0,0,1,1,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,3,3,0,0,1,1,0,0], [0,0,0,0,0,0,2,2,0,0,0,1,1,1,1,0,0,0,3,3,0,0,1,1,0,0], [0,0,0,0,0,0,2,2,0,0,0,1,0,0,1,0,0,0,2,2,0,0,1,1,0,0], [0,0,0,0,0,0,2,2,0,0,0,1,0,0,1,0,0,0,2,2,0,0,1,1,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0], [0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,2,2,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,2,2,0,0], [0,0,2,2,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1], [0,0,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,1], [0,0,1,1,0,0,1,0,3,3,0,0,2,2,0,0,3,3,0,1,0,0,2,2,1,1], [0,0,1,1,0,0,1,0,3,3,2,2,2,2,2,2,3,3,0,1,0,0,2,2,1,1], [0,0,1,1,0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,2,2,1,1], [0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,1,1], [1,1,0,0,0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,1,1], [1,1,2,2,0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,1,1,1,1], [1,1,2,2,0,0,1,0,3,3,2,2,2,2,2,2,3,3,0,1,0,0,1,1,0,0], [1,1,2,2,0,0,1,0,3,3,0,0,2,2,0,0,3,3,0,1,0,0,1,1,0,0], [1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,2,2,0,0], [1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,2,2,0,0], [1,1,2,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0], [1,1,2,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0], [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2], [1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2], [1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0], [1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0], [1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [1,1,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,5,5,5,5,5,5,5,5,5,5,0,0,5,5,5,5,5,5,5,5,5,5,0,0], [0,0,5,5,5,5,5,5,5,5,5,5,0,0,5,5,5,5,5,5,5,5,5,5,0,0], [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,1,1,5,5,5,5,5,5,5,5,5,5,1,1,5,5,5,5,5,5], [5,5,5,5,5,5,1,1,5,5,5,5,5,5,5,5,5,5,1,1,5,5,5,5,5,5], [5,5,1,1,0,0,1,1,0,0,1,1,5,5,1,1,0,0,1,1,0,0,1,1,5,5], [5,5,1,1,0,0,1,1,0,0,1,1,5,5,1,1,0,0,1,1,0,0,1,1,5,5], [5,5,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,5,5], [5,5,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,5,5], [5,5,5,5,5,5,1,1,0,0,1,1,2,2,1,1,0,0,1,1,5,5,5,5,5,5], [5,5,5,5,5,5,1,1,1,1,1,1,2,2,1,1,1,1,1,1,5,5,5,5,5,5], [2,2,5,5,5,5,5,5,0,0,2,2,0,0,2,2,0,0,5,5,5,5,5,5,2,2], [2,2,5,5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,5,2,2], [5,5,5,5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,5,5,0,0,1,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,5,5,0,0,1,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,5,5,0,0,1,1,0,0,1,1,0,0,5,5,5,5,5,5,5,5], [5,5,5,5,5,5,1,1,0,0,0,0,0,0,0,0,0,0,1,1,5,5,5,5,5,5], [5,5,5,5,5,5,1,1,0,0,0,0,1,1,0,0,0,0,1,1,5,5,5,5,5,5], [5,5,1,1,5,5,1,1,0,0,2,2,2,2,2,2,0,0,1,1,5,5,1,1,5,5], [5,5,1,1,5,5,1,1,0,0,0,0,0,0,0,0,0,0,1,1,5,5,1,1,5,5], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,0], [0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0], [0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0], [0,1,1,1,0,0,0,0,1,1,0,0,3,3,3,3,0,0,1,1,0,0,0,0,0,1], [0,1,0,0,0,0,0,0,1,1,0,0,3,3,3,3,0,0,1,1,0,0,0,0,0,1], [1,1,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3,1,1,0,0,0,0,0,1], [1,1,0,0,0,0,0,0,1,1,3,3,3,3,3,3,3,3,1,1,0,0,0,0,0,1], [1,1,0,0,0,0,0,1,1,1,3,3,2,2,2,2,3,3,1,1,1,0,0,0,1,1], [1,1,0,0,0,0,0,1,1,1,3,3,2,2,2,2,3,3,1,1,1,0,0,0,1,1], [0,1,0,0,0,0,1,1,4,4,4,4,4,4,4,4,4,4,4,4,1,1,1,1,1,1], [0,1,1,1,1,1,1,1,4,4,4,4,4,4,4,4,4,4,4,4,1,1,1,1,1,1], [0,0,1,1,1,1,1,1,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,1,1,0], [0,0,1,1,1,1,1,1,2,2,2,2,1,1,2,2,2,2,1,1,1,1,1,1,1,0], [0,0,0,0,1,1,1,1,2,2,0,0,1,1,0,0,2,2,1,1,1,1,1,0,0,0], [0,0,0,0,1,1,1,1,2,2,0,0,1,1,0,0,2,2,1,1,1,1,1,0,0,0], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [1,1,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,1,1,3,3,1,1], [1,1,3,3,0,0,0,0,0,0,2,2,2,2,0,0,0,0,0,0,0,0,3,3,1,1], [1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1], [1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1], [0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0], [0,0,0,0,3,3,3,3,3,3,0,1,1,1,1,0,3,3,3,3,3,3,3,3,0,0], [0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,2,2,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,2,2,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,2,2,1,1,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,2,2,1,1,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [3,3,0,0,0,0,1,1,0,0,0,0,2,2,0,0,0,0,1,1,3,3,1,1,2,2], [3,3,0,0,0,0,1,1,0,0,0,0,2,2,0,0,0,0,1,1,3,3,1,1,2,2], [3,3,3,3,0,0,0,0,0,0,1,1,0,0,0,0,2,2,0,0,3,3,0,0,0,0], [3,3,3,3,0,0,0,0,0,0,1,1,0,0,0,0,2,2,0,0,3,3,0,0,0,0], [0,0,1,1,1,1,1,1,3,3,3,3,3,3,2,2,0,0,0,0,3,3,1,1,0,0], [0,0,1,1,1,1,1,1,3,3,3,3,3,3,2,2,0,0,0,0,3,3,1,1,0,0], [0,0,0,0,0,0,2,2,3,3,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,2,2,3,3,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [2,2,1,1,0,0,2,2,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0], [2,2,1,1,0,0,2,2,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1,2,2,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1,2,2,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0] ]; }; module.exports.getEnemies = function() { return [4,4,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,3,3,3,3], [3,3,3,3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,3,3,3,3], [3,3,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,3,3], [3,3,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,3,3], [0,0,0,0,0,0,1,1,1,1,3,3,1,1,3,3,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,1,1,3,3,1,1,3,3,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,3,3,3,3,1,1,3,3,3,3,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,3,3,3,3,1,1,3,3,3,3,1,1,0,0,0,0,0,0], [3,3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,3,3], [3,3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,3,3], [3,3,3,3,0,0,0,0,1,1,3,3,1,1,3,3,1,1,0,0,0,0,3,3,3,3], [3,3,3,3,0,0,0,0,1,1,3,3,1,1,3,3,1,1,0,0,0,0,3,3,3,3], [4,4,4,4,4,4,0,0,1,1,1,1,1,1,1,1,1,1,0,0,4,4,4,4,4,4], [4,4,4,4,4,4,0,0,1,1,1,1,1,1,1,1,1,1,0,0,4,4,4,4,4,4], [0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0], [0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,2,0], [0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,2,0], [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1], [1,0,1,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,1,0,1], [2,0,2,0,2,0,0,2,0,0,0,1,0,0,1,0,0,0,2,0,0,2,0,2,0,2], [2,0,2,0,2,0,0,2,0,0,0,1,0,0,1,0,0,0,2,0,0,2,0,2,0,2] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0], [0,0,1,1,0,0,1,1,1,1,0,0,0,0,5,5,5,5,5,5,1,1,1,1,0,0], [0,0,1,1,0,0,1,1,1,1,0,0,0,0,5,5,5,5,5,5,1,1,1,1,0,0], [0,0,1,1,0,0,0,0,1,1,0,0,2,2,5,5,5,5,5,5,5,5,5,5,0,0], [0,0,1,1,0,0,0,0,1,1,0,0,2,2,5,5,5,5,5,5,5,5,5,5,0,0], [5,5,5,5,5,5,2,0,1,1,0,0,0,0,1,1,5,5,5,5,5,5,5,5,0,0], [5,5,5,5,5,5,2,0,1,1,0,0,0,0,1,1,5,5,5,5,5,5,5,5,0,0], [5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1,0,1,1,0,0,0,0,0,0,0], [5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1,0,1,1,0,0,0,0,0,0,0], [0,0,0,0,0,2,5,5,5,5,5,5,5,5,1,1,0,1,1,0,0,0,2,2,2,2], [0,0,0,0,0,2,5,5,5,5,5,5,5,5,1,1,0,1,1,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1], [1,1,1,1,1,1,1,1,5,5,5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1], [0,0,0,0,0,0,1,1,1,1,5,5,5,5,5,5,5,5,2,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,1,1,5,5,5,5,5,5,5,5,2,0,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,0,0,5,5,5,5,5,5,1,1,1,1,0,0,1,1,0,0], [0,0,1,1,1,1,1,1,0,0,5,5,5,5,5,5,1,1,1,1,0,0,1,1,0,0], [5,5,5,5,5,5,1,1,5,5,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [5,5,5,5,5,5,1,1,5,5,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [5,5,5,5,5,5,5,5,5,5,2,2,0,0,2,2,0,0,0,0,0,0,1,1,0,0], [5,5,5,5,5,5,5,5,5,5,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0], [1,1,5,5,5,5,5,5,5,5,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0], [1,1,5,5,5,5,5,5,5,5,0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0], [1,1,1,1,2,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,0], [1,1,1,1,2,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,3,3,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,2,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,2,0,0], [1,1,3,3,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,2,2,0,0], [1,1,3,3,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,2,2,0,0], [0,0,1,1,3,3,1,1,0,0,0,0,1,1,0,0,3,3,1,1,2,2,2,2,0,0], [0,0,1,1,3,3,1,1,0,0,0,0,1,1,0,0,3,3,1,1,2,2,2,2,0,0], [0,0,0,0,1,1,0,0,3,3,2,2,1,1,3,3,0,0,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,3,3,2,2,1,1,3,3,0,0,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,1,1,2,2,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,1,1,2,2,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,2,2,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,2,2,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,3,3,1,1,2,2,3,3,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,3,3,1,1,2,2,3,3,0,0,0,0,0,0,0,0,0,0], [2,2,2,2,2,2,3,3,0,0,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0], [2,2,2,2,2,2,3,3,0,0,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0], [2,2,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,1,2,2,2,2,0,0,0,0], [2,2,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,1,2,2,2,2,0,0,0,0], [2,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,0,0], [2,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,2,2,1,1,1,1,0,0], [3,3,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2], [3,3,2,2,2,2,2,2,0,0,0,1,1,1,1,0,0,0,0,0,1,1,2,2,2,2], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,2,2,2,2], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,2,2,2,2] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1], [1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1], [1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1], [2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2,0,0,2,2], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0], [3,3,3,3,0,0,0,0,1,1,0,0,3,3,0,0,1,1,0,0,0,0,3,3,3,3], [3,3,3,3,0,0,0,0,1,1,0,0,3,3,0,0,1,1,0,0,0,0,3,3,3,3], [3,3,3,3,3,3,3,3,1,1,1,1,3,3,1,1,1,1,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,1,1,0,0,3,3,0,0,1,1,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3], [0,0,0,0,0,0,0,0,1,1,3,3,3,3,3,3,1,1,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,0,0,1,1,3,3,3,3,3,3,1,1,0,0,1,1,0,0,1,1], [0,0,1,1,0,0,1,1,0,0,0,0,3,3,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,3,3,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,2,2,0,0,1,1,0,0,1,1,0,0,1,1,0,0,2,2,0,0], [0,0,0,0,0,0,2,2,0,0,1,1,0,0,1,1,0,0,1,1,0,0,2,2,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,2,2,0,0,0,0,2,2,0,0,2,2,2,2], [0,0,1,1,0,0,1,1,0,0,0,0,2,2,0,0,0,0,2,2,0,0,2,2,2,2], [0,0,1,1,0,0,0,0,0,0,1,1,0,0,2,2,1,1,0,0,0,0,0,0,2,2], [0,0,1,1,0,0,0,0,0,0,1,1,0,0,2,2,1,1,0,0,0,0,0,0,2,2], [0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,2,2,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,2,2,0,0,0,0], [0,0,0,0,2,2,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0], [0,0,0,0,2,2,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0], [2,2,0,0,2,2,0,0,0,0,1,1,0,0,2,2,0,0,0,0,2,2,1,1,0,0], [2,2,0,0,2,2,0,0,0,0,1,1,0,0,2,2,0,0,0,0,2,2,1,1,0,0], [0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,2,2,0,0,0,0], [0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,2,2,0,0,0,0], [0,0,2,2,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,1], [0,0,2,2,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,1], [0,0,1,1,0,0,0,0,0,0,1,1,2,2,0,0,0,0,0,0,0,0,1,1,1,1], [0,0,1,1,0,0,0,0,0,0,1,1,2,2,0,0,0,0,0,0,0,0,1,1,1,1], [0,0,0,0,0,0,1,1,0,0,1,1,1,1,2,2,0,0,2,2,0,0,0,0,1,1], [0,0,0,0,0,0,1,1,0,0,1,1,1,1,2,2,0,0,2,2,0,0,0,0,1,1], [1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,2,2,0,0,0,0], [1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,2,2,0,0,0,0], [1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0], [1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,2,2,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,1], [2,2,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,2,2], [0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,3,3,2,2,3,3,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,3,3,2,2,3,3,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,3,3,0,0,0,0,3,3,0,0,0,0,3,3,3,3,0,0,0,0,0,0], [0,0,0,0,3,3,0,0,0,0,3,3,0,0,0,0,3,3,3,3,0,0,0,0,0,0], [0,0,3,3,1,1,3,3,0,0,0,0,0,0,3,3,1,1,1,1,3,3,0,0,0,0], [0,0,3,3,1,1,3,3,0,0,0,0,0,0,3,3,1,1,1,1,3,3,0,0,0,0], [0,0,0,0,3,3,1,1,3,3,0,0,0,0,0,0,3,3,3,3,0,0,0,0,3,3], [0,0,0,0,3,3,1,1,3,3,0,0,0,0,0,0,3,3,3,3,0,0,0,0,3,3], [3,3,0,0,0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,2,2], [3,3,0,0,0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,2,2], [1,1,3,3,0,0,0,0,0,0,3,3,2,2,3,3,0,0,0,0,3,3,0,0,3,3], [1,1,3,3,0,0,0,0,0,0,3,3,2,2,3,3,0,0,0,0,3,3,0,0,3,3], [2,2,1,1,3,3,0,0,0,0,0,0,3,3,0,0,0,0,3,3,2,2,3,3,0,0], [2,2,1,1,3,3,0,0,0,0,0,0,3,3,0,0,0,0,3,3,2,2,3,3,0,0], [1,1,3,3,0,0,0,0,3,3,0,0,0,0,0,0,3,3,0,0,3,3,0,0,0,0], [1,1,3,3,0,0,0,0,3,3,0,0,0,0,0,0,3,3,0,0,3,3,0,0,0,0], [3,3,0,0,0,0,3,3,1,1,3,3,0,0,3,3,1,1,3,3,0,0,0,0,0,0], [3,3,0,0,0,0,3,3,1,1,3,3,0,0,3,3,1,1,3,3,0,0,0,0,0,0], [0,0,0,0,0,0,3,3,1,1,3,3,0,0,0,0,3,3,0,0,0,0,3,3,0,0], [0,0,0,0,0,0,3,3,1,1,3,3,0,0,0,0,3,3,0,0,0,0,3,3,0,0], [0,0,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,3,3,2,2,3,3], [0,0,3,3,0,0,0,0,3,3,0,1,1,1,1,0,0,0,0,0,3,3,2,2,3,3], [3,3,2,2,3,3,0,0,0,0,0,1,0,0,1,0,0,0,3,3,1,1,3,3,0,0], [3,3,2,2,3,3,0,0,0,0,0,1,0,0,1,0,0,0,3,3,1,1,3,3,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,2,2,0,0,1,1,0,0,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,2,2,0,0,1,1,0,0,1,1,1,1,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,1,0,0,3,3,3,3,3,3], [0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,1,0,0,3,3,3,3,3,3], [0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,3,3,3,3,3,3,3,3], [0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,2,0,0,3,3,3,3,3,3,3,3], [0,0,0,1,0,0,1,1,1,1,1,1,2,2,1,1,1,1,3,3,3,3,1,1,2,2], [0,0,0,1,0,0,1,1,1,1,1,1,2,2,1,1,1,1,3,3,3,3,0,0,2,2], [0,0,1,1,1,1,1,1,2,2,0,0,0,0,1,1,0,0,3,3,3,3,0,0,0,1], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,1,1,0,0,3,3,3,3,0,0,0,1], [0,1,1,1,1,1,1,1,0,0,2,2,3,3,3,3,3,3,3,3,3,3,0,0,0,0], [0,1,1,1,1,1,1,1,0,0,2,2,3,3,3,3,3,3,3,3,3,3,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,3,3,3,3,3,3,3,3,3,3,1,1,0,0], [0,0,0,0,0,0,2,2,0,0,0,0,3,3,3,3,3,3,3,3,3,3,1,1,0,0], [2,2,1,1,0,0,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,1,1,0,0], [2,2,1,1,0,0,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,1,1,0,0], [0,1,1,1,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1,1,0], [0,1,1,1,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1,1,0], [0,0,1,1,3,3,3,3,0,0,0,0,0,0,0,0,2,2,1,1,1,1,1,1,0,0], [0,0,1,1,3,3,3,3,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0], [0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0], [0,0,0,0,3,3,3,3,0,0,0,1,1,1,1,0,0,0,1,1,0,0,0,1,0,0], [0,0,0,0,3,3,3,3,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,3,3,3,3,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,2,2,3,3,3,3,0,0,0,0], [0,0,2,2,0,0,0,0,0,0,2,2,0,0,0,0,2,2,3,3,3,3,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,0,0,2,2,3,3,0,0,2,0,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,0,0,2,2,3,3,2,2,2,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,2,0,0], [0,0,0,0,0,0,2,2,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,2,0,0], [0,0,2,0,0,0,0,0,2,2,3,3,3,3,2,2,3,3,0,0,0,0,2,2,0,0], [0,0,2,0,0,0,0,0,2,2,3,3,3,3,2,2,3,3,0,0,0,0,2,2,0,0], [0,0,2,2,2,0,3,3,0,0,2,2,3,3,3,3,2,2,0,0,0,0,0,2,0,0], [0,0,0,0,2,0,3,3,0,0,2,2,3,3,3,3,2,2,0,0,0,0,0,2,0,0], [0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,3,3,3,3,3,3,3,3,3,3,0,0,0,0,2,2,0,0,0,0,0,0], [0,0,0,0,2,0,3,3,0,0,2,2,3,3,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,2,2,2,0,3,3,0,0,2,2,3,3,0,0,0,0,0,0,2,2,0,0,0,0], [0,0,3,3,3,3,3,3,2,2,0,0,2,2,0,0,0,0,0,0,0,0,2,2,0,0], [0,0,3,3,3,3,3,3,2,2,0,0,2,2,0,0,2,2,0,0,0,0,2,2,0,0], [3,3,3,3,3,3,2,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0], [3,3,3,3,3,3,2,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0], [0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2], [0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], [2,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [2,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,3,3,3,3,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,0,0,0,0,0], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,0,0,0,0,0], [3,3,2,2,1,1,3,3,1,1,1,1,1,1,3,3,3,3,3,3,3,3,1,1,2,2], [3,3,0,0,1,1,3,3,1,1,1,1,1,1,3,3,3,3,3,3,3,3,1,1,2,2], [3,3,3,3,1,1,3,3,3,3,3,3,2,2,3,3,3,3,1,1,2,0,1,1,0,0], [3,3,3,3,1,1,3,3,3,3,3,3,0,0,3,3,3,3,1,1,2,0,1,1,0,0], [0,0,3,3,3,3,1,1,0,0,3,3,3,3,3,3,3,3,1,1,0,0,1,1,0,0], [0,0,3,3,3,3,1,1,2,2,3,3,3,3,3,3,3,3,1,1,0,0,1,1,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,3,3,3,3,1,1,1,1,1,0,3,3,3,3], [0,0,1,1,1,1,1,1,1,1,1,1,3,3,3,3,1,1,1,1,1,0,3,3,3,3], [0,2,2,2,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,3,3], [0,2,0,0,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,3,3], [0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1,3,3,3,3,1,1,1,0,3,3], [0,0,1,1,0,0,1,1,0,0,2,2,1,1,0,0,3,3,3,3,1,1,1,0,3,3], [0,0,1,1,0,0,0,0,0,1,1,1,1,1,3,3,3,3,1,1,0,0,0,0,3,3], [0,0,1,1,0,0,0,0,0,1,1,1,0,0,3,3,3,3,1,1,0,0,0,0,3,3], [0,0,1,1,1,1,1,0,0,1,1,1,3,3,3,3,0,0,3,3,1,1,3,3,3,3], [0,0,1,1,1,1,1,0,0,1,0,0,3,3,3,3,1,1,3,3,1,1,3,3,3,3], [0,0,0,0,1,1,0,0,3,3,0,0,0,0,0,0,1,1,3,3,1,1,3,3,0,0], [0,0,0,0,1,1,0,0,3,3,0,1,1,1,1,0,1,1,3,3,0,0,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,3,3,3,3,3,3,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,3,3,3,3,3,3,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,0,0,0], [0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,0,0,0], [3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,1,1,1,1,0,0], [3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,1,1,1,1,0,0], [3,3,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [3,3,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [3,3,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [3,3,0,0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,3,3,3,3,3,3,0,0], [3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,3,1,1,1,1,1,0], [3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,3,1,1,1,1,1,0], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,0], [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,1,1,1,0], [1,1,3,3,3,3,1,1,1,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,0,0], [1,1,3,3,3,3,1,1,1,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,2,2], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,2,2], [2,2,0,0,1,1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2], [2,2,0,0,1,1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,2,2], [0,0,2,2,1,1,1,1,2,2,0,0,0,0,0,0,1,1,1,1,2,2,2,2,2,2], [0,0,2,2,1,1,0,0,2,2,0,1,1,1,1,0,1,1,1,1,2,2,2,2,2,2], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water module.exports.getMap = function() { return [ [0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0], [3,3,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0], [3,3,1,1,1,1,1,1,0,0,1,1,0,0,2,2,0,0,1,1,1,0,0,0,0,0], [3,3,3,3,3,3,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0], [3,3,3,3,3,3,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0], [3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,0,0,4,4], [3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,0,0,4,4], [0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2], [0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0], [1,1,1,1,0,0,1,1,0,0,0,1,1,1,1,1,3,3,1,1,0,0,0,0,1,1], [1,1,1,1,0,0,1,1,0,0,0,1,1,1,1,1,3,3,1,1,2,2,2,2,1,1], [0,0,0,0,0,0,2,2,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0], [0,0,0,0,0,0,2,2,0,0,2,2,0,0,3,3,3,3,3,3,3,3,0,0,0,0], [4,4,4,4,0,0,4,4,4,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4,4,4], [4,4,4,4,0,0,4,4,4,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4,4,4], [3,3,3,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0], [3,3,3,3,1,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,0,0], [3,3,3,3,1,1,0,0,1,0,0,0,0,0,0,1,0,0,2,2,1,1,1,1,0,0], [3,3,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0], [3,3,2,2,1,1,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,3,3,3,3,4,4,2,2,2,2,1,1,1,1]; };
JavaScript
// 1 - wall // 2 - steel wall // 3 - trees // 4 - water // 5 - ice module.exports.getMap = function() { return [ [0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0,4,4,0,0,0,0,0,0,0,0], [4,4,4,4,0,0,4,4,0,0,4,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4], [4,4,4,4,0,0,4,4,0,0,4,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4], [3,3,3,3,1,1,0,0,0,0,1,1,0,0,0,0,4,4,0,0,4,4,3,3,4,4], [3,3,3,3,1,1,0,0,0,0,1,1,0,0,0,0,4,4,0,0,4,4,3,3,4,4], [3,3,4,4,4,4,4,4,4,4,0,0,2,2,0,0,0,0,1,1,3,3,3,3,3,3], [3,3,4,4,4,4,4,4,4,4,0,0,2,2,0,0,0,0,1,1,3,3,3,3,3,3], [3,3,3,3,0,0,4,4,0,0,0,0,4,4,0,0,4,4,4,4,4,4,4,4,3,3], [3,3,3,3,0,0,4,4,0,0,0,0,4,4,0,0,4,4,4,4,4,4,4,4,3,3], [4,4,4,4,0,0,4,4,0,0,4,4,4,4,0,0,0,0,4,4,0,0,0,0,0,0], [4,4,4,4,0,0,4,4,0,0,4,4,4,4,0,0,0,0,4,4,0,0,0,0,0,0], [0,0,0,0,1,1,3,3,1,1,0,0,1,1,3,3,0,0,4,4,0,0,0,0,4,4], [0,0,0,0,1,1,3,3,1,1,0,0,1,1,3,3,0,0,4,4,0,0,0,0,4,4], [0,0,4,4,4,4,3,3,4,4,4,4,4,4,4,4,0,0,3,3,1,1,0,0,4,4], [0,0,4,4,4,4,3,3,4,4,4,4,4,4,4,4,0,0,3,3,1,1,0,0,4,4], [3,3,0,0,0,0,1,1,0,0,0,0,4,4,0,0,3,3,3,3,4,4,0,0,4,4], [3,3,0,0,0,0,1,1,0,0,0,0,4,4,0,0,3,3,3,3,4,4,0,0,4,4], [4,4,4,4,0,0,4,4,4,4,0,0,4,4,1,1,4,4,4,4,4,4,0,0,0,0], [4,4,4,4,0,0,4,4,4,4,0,0,4,4,1,1,4,4,4,4,4,4,0,0,0,0], [0,0,0,0,1,1,0,0,3,3,3,3,0,0,0,0,3,3,4,4,0,0,0,0,4,4], [0,0,0,0,1,1,0,0,3,3,3,3,0,0,0,0,3,3,4,4,0,0,0,0,4,4], [0,0,4,4,4,4,4,4,3,3,0,0,0,0,0,0,0,0,4,4,0,0,4,4,4,4], [0,0,4,4,4,4,4,4,3,3,0,1,1,1,1,0,0,0,4,4,0,0,4,4,4,4], [0,0,4,4,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,0,4,4,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0] ]; }; module.exports.getEnemies = function() { return [3,3,1,1,2,2,2,2,4,4,4,4,1,1,2,2,4,4,2,2]; //todo };
JavaScript