code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* Metadata - jQuery plugin for parsing metadata from elements
*
* Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
*
* 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.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
*
*/
/**
* Sets the type of metadata to use. Metadata is encoded in JSON, and each property
* in the JSON will become a property of the element itself.
*
* There are four supported types of metadata storage:
*
* attr: Inside an attribute. The name parameter indicates *which* attribute.
*
* class: Inside the class attribute, wrapped in curly braces: { }
*
* elem: Inside a child element (e.g. a script tag). The
* name parameter indicates *which* element.
* html5: Values are stored in data-* attributes.
*
* The metadata for an element is loaded the first time the element is accessed via jQuery.
*
* As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
* matched by expr, then redefine the metadata type and run another $(expr) for other elements.
*
* @name $.metadata.setType
*
* @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("class")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from the class attribute
*
* @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("attr", "data")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a "data" attribute
*
* @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
* @before $.metadata.setType("elem", "script")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a nested script element
*
* @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p>
* @before $.metadata.setType("html5")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a series of data-* attributes
*
* @param String type The encoding type
* @param String name The name of the attribute to be used to get metadata (optional)
* @cat Plugins/Metadata
* @descr Sets the type of encoding to be used when loading metadata for the first time
* @type undefined
* @see metadata()
*/
(function($) {
$.extend({
metadata : {
defaults : {
type: 'class',
name: 'metadata',
cre: /({.*})/,
single: 'metadata'
},
setType: function( type, name ){
this.defaults.type = type;
this.defaults.name = name;
},
get: function( elem, opts ){
var settings = $.extend({},this.defaults,opts);
// check for empty string in single property
if ( !settings.single.length ) settings.single = 'metadata';
var data = $.data(elem, settings.single);
// returned cached data if it already exists
if ( data ) return data;
data = "{}";
var getData = function(data) {
if(typeof data != "string") return data;
if( data.indexOf('{') < 0 ) {
data = eval("(" + data + ")");
}
};
var getObject = function(data) {
if(typeof data != "string") return data;
data = eval("(" + data + ")");
return data;
};
if ( settings.type == "html5" ) {
var object = {};
$( elem.attributes ).each(function() {
var name = this.nodeName;
if(name.match(/^data-/)) name = name.replace(/^data-/, '');
else return true;
object[name] = getObject(this.nodeValue);
});
} else {
if ( settings.type == "class" ) {
var m = settings.cre.exec( elem.className );
if ( m )
data = m[1];
} else if ( settings.type == "elem" ) {
if( !elem.getElementsByTagName ) return;
var e = elem.getElementsByTagName(settings.name);
if ( e.length )
data = $.trim(e[0].innerHTML);
} else if ( elem.getAttribute != undefined ) {
var attr = elem.getAttribute( settings.name );
if ( attr )
data = attr;
}
object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
}
$.data( elem, settings.single, object );
return object;
}
}
});
/**
* Returns the metadata object for the first member of the jQuery object.
*
* @name metadata
* @descr Returns element's metadata object
* @param Object opts An object contianing settings to override the defaults
* @type jQuery
* @cat Plugins/Metadata
*/
$.fn.metadata = function( opts ){
return $.metadata.get( this[0], opts );
};
})(jQuery); | JavaScript |
/**
* jQuery yiiactiveform plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id: jquery.yiiactiveform.js 3538 2012-01-14 18:24:30Z mdomba $
* @since 1.1.1
*/
(function ($) {
/*
* returns the value of the CActiveForm input field
* performs additional checks to get proper values for checkbox / radiobutton / checkBoxList / radioButtonList
* @param o object the jQuery object of the input element
*/
var getAFValue = function (o) {
var type,
c = [];
if (!o.length) {
return undefined;
}
if (o[0].tagName.toLowerCase() === 'span') {
o.find(':checked').each(function () {
c.push(this.value);
});
return c.join(',');
}
type = o.attr('type');
if (type === 'checkbox' || type === 'radio') {
return o.filter(':checked').val();
} else {
return o.val();
}
};
/**
* yiiactiveform set function.
* @param options map settings for the active form plugin. Please see {@link CActiveForm::options} for availablel options.
*/
$.fn.yiiactiveform = function (options) {
return this.each(function () {
var settings = $.extend({}, $.fn.yiiactiveform.defaults, options || {}),
$form = $(this);
if (settings.validationUrl === undefined) {
settings.validationUrl = $form.attr('action');
}
$.each(settings.attributes, function (i) {
this.value = getAFValue($form.find('#' + this.inputID));
settings.attributes[i] = $.extend({}, {
validationDelay: settings.validationDelay,
validateOnChange: settings.validateOnChange,
validateOnType: settings.validateOnType,
hideErrorMessage: settings.hideErrorMessage,
inputContainer: settings.inputContainer,
errorCssClass: settings.errorCssClass,
successCssClass: settings.successCssClass,
beforeValidateAttribute: settings.beforeValidateAttribute,
afterValidateAttribute: settings.afterValidateAttribute,
validatingCssClass: settings.validatingCssClass
}, this);
});
$form.data('settings', settings);
settings.submitting = false; // whether it is waiting for ajax submission result
var validate = function (attribute, forceValidate) {
if (forceValidate) {
attribute.status = 2;
}
$.each(settings.attributes, function () {
if (this.value !== getAFValue($form.find('#' + this.inputID))) {
this.status = 2;
forceValidate = true;
}
});
if (!forceValidate) {
return;
}
if (settings.timer !== undefined) {
clearTimeout(settings.timer);
}
settings.timer = setTimeout(function () {
if (settings.submitting || $form.is(':hidden')) {
return;
}
if (attribute.beforeValidateAttribute === undefined || attribute.beforeValidateAttribute($form, attribute)) {
$.each(settings.attributes, function () {
if (this.status === 2) {
this.status = 3;
$.fn.yiiactiveform.getInputContainer(this, $form).addClass(this.validatingCssClass);
}
});
$.fn.yiiactiveform.validate($form, function (data) {
var hasError = false;
$.each(settings.attributes, function () {
if (this.status === 2 || this.status === 3) {
hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
}
});
if (attribute.afterValidateAttribute !== undefined) {
attribute.afterValidateAttribute($form, attribute, data, hasError);
}
});
}
}, attribute.validationDelay);
};
$.each(settings.attributes, function (i, attribute) {
if (this.validateOnChange) {
$form.find('#' + this.inputID).change(function () {
validate(attribute, false);
}).blur(function () {
if (attribute.status !== 2 && attribute.status !== 3) {
validate(attribute, !attribute.status);
}
});
}
if (this.validateOnType) {
$form.find('#' + this.inputID).keyup(function () {
if (attribute.value !== getAFValue($(this))) {
validate(attribute, false);
}
});
}
});
if (settings.validateOnSubmit) {
$form.find(':submit').live('mouseup keyup', function () {
$form.data('submitObject', $(this));
});
var validated = false;
$form.submit(function () {
if (validated) {
return true;
}
if (settings.timer !== undefined) {
clearTimeout(settings.timer);
}
settings.submitting = true;
if (settings.beforeValidate === undefined || settings.beforeValidate($form)) {
$.fn.yiiactiveform.validate($form, function (data) {
var hasError = false;
$.each(settings.attributes, function () {
hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
});
$.fn.yiiactiveform.updateSummary($form, data);
if (settings.afterValidate === undefined || settings.afterValidate($form, data, hasError)) {
if (!hasError) {
validated = true;
var $button = $form.data('submitObject') || $form.find(':submit:first');
// TODO: if the submission is caused by "change" event, it will not work
if ($button.length) {
$button.click();
} else { // no submit button in the form
$form.submit();
}
return;
}
}
settings.submitting = false;
});
} else {
settings.submitting = false;
}
return false;
});
}
/*
* In case of reseting the form we need to reset error messages
* NOTE1: $form.reset - does not exist
* NOTE2: $form.live('reset', ...) does not work
*/
$form.bind('reset', function () {
/*
* because we bind directly to a form reset event, not to a reset button (that could or could not exist),
* when this function is executed form elements values have not been reset yet,
* because of that we use the setTimeout
*/
setTimeout(function () {
$.each(settings.attributes, function () {
this.status = 0;
var $error = $form.find('#' + this.errorID),
$container = $.fn.yiiactiveform.getInputContainer(this, $form);
$container.removeClass(
this.validatingCssClass + ' ' +
this.errorCssClass + ' ' +
this.successCssClass
);
$error.html('').hide();
/*
* without the setTimeout() we would get here the current entered value before the reset instead of the reseted value
*/
this.value = getAFValue($form.find('#' + this.inputID));
});
/*
* If the form is submited (non ajax) with errors, labels and input gets the class 'error'
*/
$form.find('label, input').each(function () {
$(this).removeClass('error');
});
$('#' + settings.summaryID).hide().find('ul').html('');
//.. set to initial focus on reset
if (settings.focus !== undefined && !window.location.hash) {
$form.find(settings.focus).focus();
}
}, 1);
});
/*
* set to initial focus
*/
if (settings.focus !== undefined && !window.location.hash) {
$form.find(settings.focus).focus();
}
});
};
/**
* Returns the container element of the specified attribute.
* @param attribute object the configuration for a particular attribute.
* @param form the form jQuery object
* @return jquery the jquery representation of the container
*/
$.fn.yiiactiveform.getInputContainer = function (attribute, form) {
if (attribute.inputContainer === undefined) {
return form.find('#' + attribute.inputID).closest('div');
} else {
return form.find(attribute.inputContainer).filter(':has("#' + attribute.inputID + '")');
}
};
/**
* updates the error message and the input container for a particular attribute.
* @param attribute object the configuration for a particular attribute.
* @param messages array the json data obtained from the ajax validation request
* @param form the form jQuery object
* @return boolean whether there is a validation error for the specified attribute
*/
$.fn.yiiactiveform.updateInput = function (attribute, messages, form) {
attribute.status = 1;
var $error, $container,
hasError = false,
$el = form.find('#' + attribute.inputID);
if ($el.length) {
hasError = messages !== null && $.isArray(messages[attribute.id]) && messages[attribute.id].length > 0;
$error = form.find('#' + attribute.errorID);
$container = $.fn.yiiactiveform.getInputContainer(attribute, form);
$container.removeClass(
attribute.validatingCssClass + ' ' +
attribute.errorCssClass + ' ' +
attribute.successCssClass
);
if (hasError) {
$error.html(messages[attribute.id][0]);
$container.addClass(attribute.errorCssClass);
} else if (attribute.enableAjaxValidation || attribute.clientValidation) {
$container.addClass(attribute.successCssClass);
}
if (!attribute.hideErrorMessage) {
$error.toggle(hasError);
}
attribute.value = getAFValue($el);
}
return hasError;
};
/**
* updates the error summary, if any.
* @param form jquery the jquery representation of the form
* @param messages array the json data obtained from the ajax validation request
*/
$.fn.yiiactiveform.updateSummary = function (form, messages) {
var settings = $(form).data('settings'),
content = '';
if (settings.summaryID === undefined) {
return;
}
if (messages) {
$.each(settings.attributes, function () {
if ($.isArray(messages[this.id])) {
$.each(messages[this.id], function (j, message) {
content = content + '<li>' + message + '</li>';
});
}
});
}
$('#' + settings.summaryID).toggle(content !== '').find('ul').html(content);
};
/**
* Performs the ajax validation request.
* This method is invoked internally to trigger the ajax validation.
* @param form jquery the jquery representation of the form
* @param successCallback function the function to be invoked if the ajax request succeeds
* @param errorCallback function the function to be invoked if the ajax request fails
*/
$.fn.yiiactiveform.validate = function (form, successCallback, errorCallback) {
var $form = $(form),
settings = $form.data('settings'),
needAjaxValidation = false,
messages = {};
$.each(settings.attributes, function () {
var value,
msg = [];
if (this.clientValidation !== undefined && (settings.submitting || this.status === 2 || this.status === 3)) {
value = getAFValue($form.find('#' + this.inputID));
this.clientValidation(value, msg, this);
if (msg.length) {
messages[this.id] = msg;
}
}
if (this.enableAjaxValidation && !msg.length && (settings.submitting || this.status === 2 || this.status === 3)) {
needAjaxValidation = true;
}
});
if (!needAjaxValidation || settings.submitting && !$.isEmptyObject(messages)) {
if (settings.submitting) {
// delay callback so that the form can be submitted without problem
setTimeout(function () {
successCallback(messages);
}, 200);
} else {
successCallback(messages);
}
return;
}
var $button = $form.data('submitObject'),
extData = '&' + settings.ajaxVar + '=' + $form.attr('id');
if ($button && $button.length) {
extData += '&' + $button.attr('name') + '=' + $button.attr('value');
}
$.ajax({
url : settings.validationUrl,
type : $form.attr('method'),
data : $form.serialize() + extData,
dataType : 'json',
success : function (data) {
if (data !== null && typeof data === 'object') {
$.each(settings.attributes, function () {
if (!this.enableAjaxValidation) {
delete data[this.id];
}
});
successCallback($.extend({}, messages, data));
} else {
successCallback(messages);
}
},
error : function () {
if (errorCallback !== undefined) {
errorCallback();
}
}
});
};
/**
* Returns the configuration for the specified form.
* The configuration contains all needed information to perform ajax-based validation.
* @param form jquery the jquery representation of the form
* @return object the configuration for the specified form.
*/
$.fn.yiiactiveform.getSettings = function (form) {
return $(form).data('settings');
};
$.fn.yiiactiveform.defaults = {
ajaxVar: 'ajax',
validationUrl: undefined,
validationDelay: 200,
validateOnSubmit : false,
validateOnChange : true,
validateOnType : false,
hideErrorMessage : false,
inputContainer : undefined,
errorCssClass : 'error',
successCssClass : 'success',
validatingCssClass : 'validating',
summaryID : undefined,
timer: undefined,
beforeValidateAttribute: undefined, // function (form, attribute) : boolean
afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
beforeValidate: undefined, // function (form) : boolean
afterValidate: undefined, // function (form, data, hasError) : boolean
/**
* list of attributes to be validated. Each array element is of the following structure:
* {
* id : 'ModelClass_attribute', // the unique attribute ID
* model : 'ModelClass', // the model class name
* name : 'name', // attribute name
* inputID : 'input-tag-id',
* errorID : 'error-tag-id',
* value : undefined,
* status : 0, // 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
* focus : undefined, // jquery selector that indicates which element to receive input focus initially
* validationDelay: 200,
* validateOnChange : true,
* validateOnType : false,
* hideErrorMessage : false,
* inputContainer : undefined,
* errorCssClass : 'error',
* successCssClass : 'success',
* validatingCssClass : 'validating',
* enableAjaxValidation : true,
* enableClientValidation : true,
* clientValidation : undefined, // function (value, messages, attribute) : client-side validation
* beforeValidateAttribute: undefined, // function (form, attribute) : boolean
* afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
* }
*/
attributes : []
};
})(jQuery); | JavaScript |
/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 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.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/
;(function($) {
// TODO rewrite as a widget, removing all the extra plugins
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
// TODO use event delegation
this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea if not present
var hitarea = this.find("div." + CLASSES.hitarea);
if (!hitarea.length)
hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
})
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
this.data("toggler", toggler);
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() {
return this.href.toLowerCase() == location.href.toLowerCase();
});
if ( current.length ) {
// TODO update the open/closed classes
var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
if (settings.prerendered) {
// if prerendered is on, replicate the basic class swapping
items.filter("li")
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
}
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this;
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
$.treeview = {};
var CLASSES = ($.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
});
})(jQuery); | JavaScript |
(function($) {
var CLASSES = $.treeview.classes;
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
settings = $.extend({}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if (settings.remove) {
return this.trigger("remove", [settings.remove]);
}
return proxied.apply(this, arguments).bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler"));
}).bind("remove", function(event, branches) {
var prev = $(branches).prev();
var parent = $(branches).parent();
$(branches).remove();
prev.filter(":last-child").addClass(CLASSES.last)
.filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end()
.find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end()
.filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end()
.find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea);
if (parent.is(":not(:has(>))") && parent[0] != this) {
parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable);
parent.siblings(".hitarea").andSelf().remove();
}
});
};
})(jQuery); | JavaScript |
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 2.1.2
*/
(function($){
$.fn.bgiframe = ($.browser.msie && /msie 6\.0/i.test(navigator.userAgent) ? function(s) {
s = $.extend({
top : 'auto', // auto == .currentStyle.borderTopWidth
left : 'auto', // auto == .currentStyle.borderLeftWidth
width : 'auto', // auto == offsetWidth
height : 'auto', // auto == offsetHeight
opacity : true,
src : 'javascript:false;'
}, s);
var html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;'+
(s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
'"/>';
return this.each(function() {
if ( $(this).children('iframe.bgiframe').length === 0 )
this.insertBefore( document.createElement(html), this.firstChild );
});
} : function() { return this; });
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
})(jQuery); | JavaScript |
/*
* Async Treeview 0.1 - Lazy-loading extension for Treeview
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
*
* Copyright (c) 2007 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$
*
*/
;(function($) {
function load(settings, root, child, container) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
$.ajax($.extend(true, {
url: settings.url,
dataType: "json",
data: {
root: root
},
success: function(response) {
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
}
}, settings.ajax));
/*
$.getJSON(settings.url, {root: root}, function(response) {
function createNode(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
$.each(this.children, createNode, [branch])
}
}
}
child.empty();
$.each(response, createNode, [child]);
$(container).treeview({add: child});
});
*/
}
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
if (!settings.url) {
return proxied.apply(this, arguments);
}
var container = this;
if (!container.children().size())
load(settings, "source", this, container);
var userToggle = settings.toggle;
return proxied.call(this, $.extend({}, settings, {
collapsed: true,
toggle: function() {
var $this = $(this);
if ($this.hasClass("hasChildren")) {
var childList = $this.removeClass("hasChildren").find("ul");
load(settings, this.id, childList, container);
}
if (userToggle) {
userToggle.apply(this, arguments);
}
}
}));
};
})(jQuery); | JavaScript |
/**
* jQuery Yii plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id: jquery.yiitab.js 1827 2010-02-20 00:43:32Z qiang.xue $
*/
;(function($) {
$.extend($.fn, {
yiitab: function() {
function activate(id) {
var pos = id.indexOf("#");
if (pos>=0) {
id = id.substring(pos);
}
var $tab=$(id);
var $container=$tab.parent();
$container.find('>ul a').removeClass('active');
$container.find('>ul a[href="'+id+'"]').addClass('active');
$container.children('div').hide();
$tab.show();
}
this.find('>ul a').click(function(event) {
var href=$(this).attr('href');
var pos=href.indexOf('#');
activate(href);
if(pos==0 || (pos>0 && (window.location.pathname=='' || window.location.pathname==href.substring(0,pos))))
return false;
});
// activate a tab based on the current anchor
var url = decodeURI(window.location);
var pos = url.indexOf("#");
if (pos >= 0) {
var id = url.substring(pos);
if (this.find('>ul a[href="'+id+'"]').length > 0) {
activate(id);
return;
}
}
}
});
})(jQuery);
| JavaScript |
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}; | JavaScript |
/*
Masked Input plugin for jQuery
Copyright (c) 2007-2011 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.3
*/
(function($) {
var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
var iPhone = (window.orientation != undefined);
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
dataName:"rawMaskFn"
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
if (this.length == 0) return;
if (typeof begin == 'number') {
end = (typeof end == 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() { return this.trigger("unmask"); },
mask: function(mask, settings) {
if (!mask && this.length > 0) {
var input = $(this[0]);
return input.data($.mask.dataName)();
}
settings = $.extend({
placeholder: "_",
completed: null
}, settings);
var defs = $.mask.definitions;
var tests = [];
var partialPosition = mask.length;
var firstNonMaskPos = null;
var len = mask.length;
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if(firstNonMaskPos==null)
firstNonMaskPos = tests.length - 1;
} else {
tests.push(null);
}
});
return this.trigger("unmask").each(function() {
var input = $(this);
var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
var focusText = input.val();
function seekNext(pos) {
while (++pos <= len && !tests[pos]);
return pos;
};
function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]);
return pos;
};
function shiftL(begin,end) {
if(begin<0)
return;
for (var i = begin,j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = settings.placeholder;
} else
break;
j = seekNext(j);
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, begin));
};
function shiftR(pos) {
for (var i = pos, c = settings.placeholder; i < len; i++) {
if (tests[i]) {
var j = seekNext(i);
var t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t))
c = t;
else
break;
}
}
};
function keydownEvent(e) {
var k=e.which;
//backspace, delete, and escape get special treatment
if(k == 8 || k == 46 || (iPhone && k == 127)){
var pos = input.caret(),
begin = pos.begin,
end = pos.end;
if(end-begin==0){
begin=k!=46?seekPrev(begin):(end=seekNext(begin-1));
end=k==46?seekNext(end):end;
}
clearBuffer(begin, end);
shiftL(begin,end-1);
return false;
} else if (k == 27) {//escape
input.val(focusText);
input.caret(0, checkVal());
return false;
}
};
function keypressEvent(e) {
var k = e.which,
pos = input.caret();
if (e.ctrlKey || e.altKey || e.metaKey || k<32) {//Ignore
return true;
} else if (k) {
if(pos.end-pos.begin!=0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
}
var p = seekNext(pos.begin - 1);
if (p < len) {
var c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
var next = seekNext(p);
input.caret(next);
if (settings.completed && next >= len)
settings.completed.call(input);
}
}
return false;
}
};
function clearBuffer(start, end) {
for (var i = start; i < end && i < len; i++) {
if (tests[i])
buffer[i] = settings.placeholder;
}
};
function writeBuffer() { return input.val(buffer.join('')).val(); };
function checkVal(allow) {
//try to place characters where they belong
var test = input.val();
var lastMatch = -1;
for (var i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = settings.placeholder;
while (pos++ < test.length) {
var c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length)
break;
} else if (buffer[i] == test.charAt(pos) && i!=partialPosition) {
pos++;
lastMatch = i;
}
}
if (!allow && lastMatch + 1 < partialPosition) {
input.val("");
clearBuffer(0, len);
} else if (allow || lastMatch + 1 >= partialPosition) {
writeBuffer();
if (!allow) input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
};
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
return tests[i]&&c!=settings.placeholder ? c : null;
}).join('');
})
if (!input.attr("readonly"))
input
.one("unmask", function() {
input
.unbind(".mask")
.removeData($.mask.dataName);
})
.bind("focus.mask", function() {
focusText = input.val();
var pos = checkVal();
writeBuffer();
var moveCaret=function(){
if (pos == mask.length)
input.caret(0, pos);
else
input.caret(pos);
};
($.browser.msie ? moveCaret:function(){setTimeout(moveCaret,0)})();
})
.bind("blur.mask", function() {
checkVal();
if (input.val() != focusText)
input.change();
})
.bind("keydown.mask", keydownEvent)
.bind("keypress.mask", keypressEvent)
.bind(pasteEventName, function() {
setTimeout(function() { input.caret(checkVal(true)); }, 0);
});
checkVal(); //Perform initial check for existing values
});
}
});
})(jQuery);
| JavaScript |
/**
* jQuery Yii ListView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id: jquery.yiilistview.js 3296 2011-06-22 17:15:17Z qiang.xue $
*/
;(function($) {
/**
* yiiListView set function.
* @param options map settings for the list view. Availablel options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - sorterClass: string, the CSS class for the sorter container
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
*/
$.fn.yiiListView = function(options) {
return this.each(function(){
var settings = $.extend({}, $.fn.yiiListView.defaults, options || {});
var $this = $(this);
var id = $this.attr('id');
if(settings.updateSelector == undefined) {
settings.updateSelector = '#'+id+' .'+settings.pagerClass.replace(/\s+/g,'.')+' a, #'+id+' .'+settings.sorterClass.replace(/\s+/g,'.')+' a';
}
$.fn.yiiListView.settings[id] = settings;
if(settings.ajaxUpdate.length > 0) {
$(settings.updateSelector).die('click').live('click',function(){
$.fn.yiiListView.update(id, {url: $(this).attr('href')});
return false;
});
}
});
};
$.fn.yiiListView.defaults = {
ajaxUpdate: [],
ajaxVar: 'ajax',
pagerClass: 'pager',
loadingClass: 'loading',
sorterClass: 'sorter'
// updateSelector: '#id .pager a, '#id .sort a',
// beforeAjaxUpdate: function(id) {},
// afterAjaxUpdate: function(id, data) {},
// url: 'ajax request URL'
};
$.fn.yiiListView.settings = {};
/**
* Returns the key value for the specified row
* @param id string the ID of the list view container
* @param index integer the zero-based index of the data item
* @return string the key value
*/
$.fn.yiiListView.getKey = function(id, index) {
return $('#'+id+' > div.keys > span:eq('+index+')').text();
};
/**
* Returns the URL that generates the list view content.
* @param id string the ID of the list view container
* @return string the URL that generates the list view content.
*/
$.fn.yiiListView.getUrl = function(id) {
var settings = $.fn.yiiListView.settings[id];
return settings.url || $('#'+id+' > div.keys').attr('title');
};
/**
* Performs an AJAX-based update of the list view contents.
* @param id string the ID of the list view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the list view.
*/
$.fn.yiiListView.update = function(id, options) {
var settings = $.fn.yiiListView.settings[id];
$('#'+id).addClass(settings.loadingClass);
options = $.extend({
type: 'GET',
url: $.fn.yiiListView.getUrl(id),
success: function(data,status) {
$.each(settings.ajaxUpdate, function(i,v) {
var id='#'+v;
$(id).replaceWith($(id,'<div>'+data+'</div>'));
});
if(settings.afterAjaxUpdate != undefined)
settings.afterAjaxUpdate(id, data);
$('#'+id).removeClass(settings.loadingClass);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#'+id).removeClass(settings.loadingClass);
alert(XMLHttpRequest.responseText);
}
}, options || {});
if(options.data!=undefined && options.type=='GET') {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id);
if(settings.beforeAjaxUpdate != undefined)
settings.beforeAjaxUpdate(id);
$.ajax(options);
};
})(jQuery); | JavaScript |
/**
* jQuery Yii GridView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright © 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @version $Id: jquery.yiigridview.js 3486 2011-12-16 00:25:01Z mdomba $
*/
(function ($) {
var selectCheckedRows, methods,
gridSettings = [];
/**
* 1. Selects rows that have checkbox checked (only checkbox that is connected with selecting a row)
* 2. Check if "check all" need to be checked/unchecked
* @return object the jQuery object
*/
selectCheckedRows = function (gridId) {
var settings = gridSettings[gridId],
table = $('#' + gridId).children('.' + settings.tableClass);
table.children('tbody').find('input.select-on-check').filter(':checked').each(function () {
$(this).closest('tr').addClass('selected');
});
table.children('thead').find('th input').filter('[type="checkbox"]').each(function () {
var name = this.name.substring(0, this.name.length - 4) + '[]', //.. remove '_all' and add '[]''
$checks = $("input[name='" + name + "']", table);
this.checked = $checks.length > 0 && $checks.length === $checks.filter(':checked').length;
});
return this;
};
methods = {
/**
* yiiGridView set function.
* @param options map settings for the grid view. Available options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - tableClass: string, the CSS class for the table
* - selectableRows: integer, the number of rows that can be selected
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
* - ajaxUpdateError: function, the function to be called if an ajax error occurs
* - selectionChanged: function, the function to be called after the row selection is changed
* @return object the jQuery object
*/
init: function (options) {
var settings = $.extend({
ajaxUpdate: [],
ajaxVar: 'ajax',
pagerClass: 'pager',
loadingClass: 'loading',
filterClass: 'filters',
tableClass: 'items',
selectableRows: 1
// updateSelector: '#id .pager a, '#id .grid thead th a',
// beforeAjaxUpdate: function (id) {},
// afterAjaxUpdate: function (id, data) {},
// selectionChanged: function (id) {},
// url: 'ajax request URL'
}, options || {});
return this.each(function () {
var $grid = $(this),
id = $grid.attr('id'),
inputSelector = '#' + id + ' .' + settings.filterClass + ' input, ' + '#' + id + ' .' + settings.filterClass + ' select';
settings.tableClass = settings.tableClass.replace(/\s+/g, '.');
if (settings.updateSelector === undefined) {
settings.updateSelector = '#' + id + ' .' + settings.pagerClass.replace(/\s+/g, '.') + ' a, #' + id + ' .' + settings.tableClass + ' thead th a';
}
gridSettings[id] = settings;
if (settings.ajaxUpdate.length > 0) {
$(document).on('click', settings.updateSelector, function () {
$('#' + id).yiiGridView('update', {url: $(this).attr('href')});
return false;
});
}
$(document).on('change', inputSelector, function () {
var data = $(inputSelector).serialize();
if (settings.pageVar !== undefined) {
data += '&' + settings.pageVar + '=1';
}
$('#' + id).yiiGridView('update', {data: data});
});
if (settings.selectableRows > 0) {
selectCheckedRows(this.id);
$(document).on('click', '#' + id + ' .' + settings.tableClass + ' > tbody > tr', function (e) {
var $currentGrid, $row, isRowSelected, $checks,
$target = $(e.target);
if ($target.closest('td').hasClass('button-column') || (e.target.type === 'checkbox' && !$target.hasClass('select-on-check'))) {
return;
}
$row = $(this);
$currentGrid = $('#' + id);
$checks = $('input.select-on-check', $currentGrid);
isRowSelected = $row.toggleClass('selected').hasClass('selected');
if (settings.selectableRows === 1) {
$row.siblings().removeClass('selected');
$checks.prop('checked', false);
}
$('input.select-on-check', $row).prop('checked', isRowSelected);
$("input.select-on-check-all", $currentGrid).prop('checked', $checks.length === $checks.filter(':checked').length);
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
if (settings.selectableRows > 1) {
$(document).on('click', '#' + id + ' .select-on-check-all', function () {
var $currentGrid = $('#' + id),
$checks = $('input.select-on-check', $currentGrid),
$checksAll = $('input.select-on-check-all', $currentGrid),
$rows = $currentGrid.children('.' + settings.tableClass).children('tbody').children();
if (this.checked) {
$rows.addClass('selected');
$checks.prop('checked', true);
$checksAll.prop('checked', true);
} else {
$rows.removeClass('selected');
$checks.prop('checked', false);
$checksAll.prop('checked', false);
}
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
}
} else {
$(document).on('click', '#' + id + ' .select-on-check', false);
}
});
},
/**
* Returns the key value for the specified row
* @param row integer the row number (zero-based index)
* @return string the key value
*/
getKey: function (row) {
return this.children('.keys').children('span').eq(row).text();
},
/**
* Returns the URL that generates the grid view content.
* @return string the URL that generates the grid view content.
*/
getUrl: function () {
var sUrl = gridSettings[this.attr('id')].url;
return sUrl || this.children('.keys').attr('title');
},
/**
* Returns the jQuery collection of the cells in the specified row.
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
getRow: function (row) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.children('.' + sClass).children('tbody').children('tr').eq(row).children();
},
/**
* Returns the jQuery collection of the cells in the specified column.
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
getColumn: function (column) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.children('.' + sClass).children('tbody').children('tr').children('td:nth-child(' + (column + 1) + ')');
},
/**
* Performs an AJAX-based update of the grid view contents.
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
* @return object the jQuery object
*/
update: function (options) {
var customError;
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
return this.each(function () {
var $form,
$grid = $(this),
id = $grid.attr('id'),
settings = gridSettings[id];
$grid.addClass(settings.loadingClass);
options = $.extend({
type: 'GET',
url: $grid.yiiGridView('getUrl'),
success: function (data) {
var $data = $('<div>' + data + '</div>');
$grid.removeClass(settings.loadingClass);
$.each(settings.ajaxUpdate, function (i, el) {
var updateId = '#' + el;
$(updateId).replaceWith($(updateId, $data));
});
if (settings.afterAjaxUpdate !== undefined) {
settings.afterAjaxUpdate(id, data);
}
if (settings.selectableRows > 0) {
selectCheckedRows(id);
}
},
error: function (XHR, textStatus, errorThrown) {
var ret, err;
$grid.removeClass(settings.loadingClass);
if (XHR.readyState === 0 || XHR.status === 0) {
return;
}
if (customError !== undefined) {
ret = customError(XHR);
if (ret !== undefined && !ret) {
return;
}
}
switch (textStatus) {
case 'timeout':
err = 'The request timed out!';
break;
case 'parsererror':
err = 'Parser error!';
break;
case 'error':
if (XHR.status && !/^\s*$/.test(XHR.status)) {
err = 'Error ' + XHR.status;
} else {
err = 'Error';
}
if (XHR.responseText && !/^\s*$/.test(XHR.responseText)) {
err = err + ': ' + XHR.responseText;
}
break;
}
if (settings.ajaxUpdateError !== undefined) {
settings.ajaxUpdateError(XHR, textStatus, errorThrown, err);
} else if (err) {
alert(err);
}
}
}, options || {});
if (options.data !== undefined && options.type === 'GET') {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
if (settings.ajaxUpdate !== false) {
options.url = $.param.querystring(options.url, settings.ajaxVar + '=' + id);
if (settings.beforeAjaxUpdate !== undefined) {
settings.beforeAjaxUpdate(id, options);
}
$.ajax(options);
} else { // non-ajax mode
if (options.type === 'GET') {
window.location.href = options.url;
} else { // POST mode
$form = $('<form action="' + options.url + '" method="post"></form>').appendTo('body');
if (options.data === undefined) {
options.data = {};
}
if (options.data.returnUrl === undefined) {
options.data.returnUrl = window.location.href;
}
$.each(options.data, function (name, value) {
$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
});
$form.submit();
}
}
});
},
/**
* Returns the key values of the currently selected rows.
* @return array the key values of the currently selected rows.
*/
getSelection: function () {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
selection = [];
this.children('.' + settings.tableClass).children('tbody').children().each(function (i) {
if ($(this).hasClass('selected')) {
selection.push(keys.eq(i).text());
}
});
return selection;
},
/**
* Returns the key values of the currently checked rows.
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
getChecked: function (column_id) {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
checked = [];
if (column_id.substring(column_id.length - 2) !== '[]') {
column_id = column_id + '[]';
}
this.children('.' + settings.tableClass).children('tbody').children('tr').children('td').children('input[name="' + column_id + '"]').each(function (i) {
if (this.checked) {
checked.push(keys.eq(i).text());
}
});
return checked;
}
};
$.fn.yiiGridView = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
return false;
}
};
/******************************************************************************
*** DEPRECATED METHODS
*** used before Yii 1.1.9
******************************************************************************/
$.fn.yiiGridView.settings = gridSettings;
/**
* Returns the key value for the specified row
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return string the key value
*/
$.fn.yiiGridView.getKey = function (id, row) {
return $('#' + id).yiiGridView('getKey', row);
};
/**
* Returns the URL that generates the grid view content.
* @param id string the ID of the grid view container
* @return string the URL that generates the grid view content.
*/
$.fn.yiiGridView.getUrl = function (id) {
return $('#' + id).yiiGridView('getUrl');
};
/**
* Returns the jQuery collection of the cells in the specified row.
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
$.fn.yiiGridView.getRow = function (id, row) {
return $('#' + id).yiiGridView('getRow', row);
};
/**
* Returns the jQuery collection of the cells in the specified column.
* @param id string the ID of the grid view container
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
$.fn.yiiGridView.getColumn = function (id, column) {
return $('#' + id).yiiGridView('getColumn', column);
};
/**
* Performs an AJAX-based update of the grid view contents.
* @param id string the ID of the grid view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
*/
$.fn.yiiGridView.update = function (id, options) {
$('#' + id).yiiGridView('update', options);
};
/**
* Returns the key values of the currently selected rows.
* @param id string the ID of the grid view container
* @return array the key values of the currently selected rows.
*/
$.fn.yiiGridView.getSelection = function (id) {
return $('#' + id).yiiGridView('getSelection');
};
/**
* Returns the key values of the currently checked rows.
* @param id string the ID of the grid view container
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
$.fn.yiiGridView.getChecked = function (id, column_id) {
return $('#' + id).yiiGridView('getChecked', column_id);
};
})(jQuery); | JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('insertfile', function(K) {
var self = this, name = 'insertfile',
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
lang = self.lang(name + '.');
self.plugin.fileDialog = function(options) {
var fileUrl = K.undef(options.fileUrl, 'http://'),
fileTitle = K.undef(options.fileTitle, ''),
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="keTitle" style="width:60px;">' + lang.title + '</label>',
'<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
'</div>',
//form end
'</form>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 180,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
title = titleBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (K.trim(title) === '') {
title = url;
}
clickFn.call(self, url, title);
}
},
beforeRemove : function() {
viewServerBtn.remove();
uploadbutton.remove();
}
}),
div = dialog.div;
var urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
titleBox = K('[name="title"]', div);
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=file'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'file',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
urlBox.val(fileUrl);
titleBox.val(fileTitle);
urlBox[0].focus();
urlBox[0].select();
};
self.clickToolbar(name, function() {
self.plugin.fileDialog({
clickFn : function(url, title) {
var html = '<a href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>';
self.insertHtml(html).hideDialog().focus();
}
});
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('flash', function(K) {
var self = this, name = 'flash', lang = self.lang(name + '.'),
allowFlashUpload = K.undef(self.allowFlashUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
self.plugin.flash = {
edit : function() {
var html = [
'<div style="padding:10px 20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 200,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType('.swf'),
width : width,
height : height,
quality : 'high'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div);
urlBox.val('http://');
if (allowFlashUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=flash'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
urlBox.width(250);
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'flash',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedFlash();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedFlash().remove();
}
};
self.clickToolbar(name, self.plugin.flash.edit);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('link', function(K) {
var self = this, name = 'link';
self.plugin.link = {
edit : function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
//url
'<div class="ke-dialog-row">' +
'<label for="keUrl">' + lang.url + '</label>' +
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:90%;" /></div>' +
//type
'<div class="ke-dialog-row"">' +
'<label for="keType">' + lang.linkType + '</label>' +
'<select id="keType" name="type"></select>' +
'</div>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 400,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val());
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
self.exec('createlink', url, typeBox.val()).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('input[name="url"]', div),
typeBox = K('select[name="type"]', div);
urlBox.val('http://');
typeBox[0].options[0] = new Option(lang.newWindow, '_blank');
typeBox[0].options[1] = new Option(lang.selfWindow, '');
self.cmd.selection();
var a = self.plugin.getSelectedLink();
if (a) {
self.cmd.range.selectNode(a[0]);
self.cmd.select();
urlBox.val(a.attr('data-ke-src'));
typeBox.val(a.attr('target'));
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.exec('unlink', null);
}
};
self.clickToolbar(name, self.plugin.link.edit);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('quickformat', function(K) {
var self = this, name = 'quickformat',
blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p');
self.clickToolbar(name, function() {
self.focus();
var doc = self.edit.doc,
range = self.cmd.range,
child = K(doc.body).first(), next,
nodeList = [], subList = [],
bookmark = range.createBookmark(true);
while(child) {
next = child.next();
if (blockMap[child.name]) {
child.html(child.html().replace(/^(\s| | )+/ig, ''));
child.css('text-indent', '2em');
} else {
subList.push(child);
}
if (!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) {
if (subList.length > 0) {
nodeList.push(subList);
}
subList = [];
}
child = next;
}
K.each(nodeList, function(i, subList) {
var wrapper = K('<p style="text-indent:2em;"></p>', doc);
subList[0].before(wrapper);
K.each(subList, function(i, knode) {
wrapper.append(knode);
});
});
range.moveToBookmark(bookmark);
self.addBookmark();
});
});
/**
--------------------------
abcd<br />
1234<br />
to
<p style="text-indent:2em;">
abcd<br />
1234<br />
</p>
--------------------------
abcd<img>1233
<p>1234</p>
to
<p style="text-indent:2em;">abcd<img>1233</p>
<p style="text-indent:2em;">1234</p>
--------------------------
*/ | JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('table', function(K) {
var self = this, name = 'table', lang = self.lang(name + '.'), zeroborder = 'ke-zeroborder';
// 取得下一行cell的index
function _getCellIndex(table, row, cell) {
var rowSpanCount = 0;
for (var i = 0, len = row.cells.length; i < len; i++) {
if (row.cells[i] == cell) {
break;
}
rowSpanCount += row.cells[i].rowSpan - 1;
}
return cell.cellIndex - rowSpanCount;
}
self.plugin.table = {
//insert or modify table
prop : function(isInsert) {
var html = [
'<div style="padding:10px 20px;">',
//rows, cols
'<div class="ke-dialog-row">',
'<label for="keRows" style="width:90px;">' + lang.cells + '</label>',
lang.rows + ' <input type="text" id="keRows" class="ke-input-text ke-input-number" name="rows" value="" maxlength="4" /> ',
lang.cols + ' <input type="text" class="ke-input-text ke-input-number" name="cols" value="" maxlength="4" />',
'</div>',
//width, height
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
'<select name="widthType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<select name="heightType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select>',
'</div>',
//space, padding
'<div class="ke-dialog-row">',
'<label for="kePadding" style="width:90px;">' + lang.space + '</label>',
lang.padding + ' <input type="text" id="kePadding" class="ke-input-text ke-input-number" name="padding" value="" maxlength="4" /> ',
lang.spacing + ' <input type="text" class="ke-input-text ke-input-number" name="spacing" value="" maxlength="4" />',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
'<select id="keAlign" name="align">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="left">' + lang.alignLeft + '</option>',
'<option value="center">' + lang.alignCenter + '</option>',
'<option value="right">' + lang.alignRight + '</option>',
'</select>',
'</div>',
//border
'<div class="ke-dialog-row">',
'<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> ',
lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
'</div>',
//background color
'<div class="ke-dialog-row">',
'<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
'<span class="ke-inline-block ke-input-color"></span>',
'</div>',
'</div>'
].join('');
var picker, currentElement;
function removePicker() {
if (picker) {
picker.remove();
picker = null;
currentElement = null;
}
}
var dialog = self.createDialog({
name : name,
width : 500,
height : 300,
title : self.lang(name),
body : html,
beforeDrag : removePicker,
beforeRemove : function() {
removePicker();
colorBox.unbind();
},
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var rows = rowsBox.val(),
cols = colsBox.val(),
width = widthBox.val(),
height = heightBox.val(),
widthType = widthTypeBox.val(),
heightType = heightTypeBox.val(),
padding = paddingBox.val(),
spacing = spacingBox.val(),
align = alignBox.val(),
border = borderBox.val(),
borderColor = K(colorBox[0]).html() || '',
bgColor = K(colorBox[1]).html() || '';
if (rows == 0 || !/^\d+$/.test(rows)) {
alert(self.lang('invalidRows'));
rowsBox[0].focus();
return;
}
if (cols == 0 || !/^\d+$/.test(cols)) {
alert(self.lang('invalidRows'));
colsBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
if (!/^\d*$/.test(padding)) {
alert(self.lang('invalidPadding'));
paddingBox[0].focus();
return;
}
if (!/^\d*$/.test(spacing)) {
alert(self.lang('invalidSpacing'));
spacingBox[0].focus();
return;
}
if (!/^\d*$/.test(border)) {
alert(self.lang('invalidBorder'));
borderBox[0].focus();
return;
}
//modify table
if (table) {
if (width !== '') {
table.width(width + widthType);
} else {
table.css('width', '');
}
if (table[0].width !== undefined) {
table.removeAttr('width');
}
if (height !== '') {
table.height(height + heightType);
} else {
table.css('height', '');
}
if (table[0].height !== undefined) {
table.removeAttr('height');
}
table.css('background-color', bgColor);
if (table[0].bgColor !== undefined) {
table.removeAttr('bgColor');
}
if (padding !== '') {
table[0].cellPadding = padding;
} else {
table.removeAttr('cellPadding');
}
if (spacing !== '') {
table[0].cellSpacing = spacing;
} else {
table.removeAttr('cellSpacing');
}
if (align !== '') {
table[0].align = align;
} else {
table.removeAttr('align');
}
if (border !== '') {
table.attr('border', border);
} else {
table.removeAttr('border');
}
if (border === '' || border === '0') {
table.addClass(zeroborder);
} else {
table.removeClass(zeroborder);
}
if (borderColor !== '') {
table.attr('borderColor', borderColor);
} else {
table.removeAttr('borderColor');
}
self.hideDialog().focus();
return;
}
//insert new table
var style = '';
if (width !== '') {
style += 'width:' + width + widthType + ';';
}
if (height !== '') {
style += 'height:' + height + heightType + ';';
}
if (bgColor !== '') {
style += 'background-color:' + bgColor + ';';
}
var html = '<table';
if (style !== '') {
html += ' style="' + style + '"';
}
if (padding !== '') {
html += ' cellpadding="' + padding + '"';
}
if (spacing !== '') {
html += ' cellspacing="' + spacing + '"';
}
if (align !== '') {
html += ' align="' + align + '"';
}
if (border !== '') {
html += ' border="' + border + '"';
}
if (border === '' || border === '0') {
html += ' class="' + zeroborder + '"';
}
if (borderColor !== '') {
html += ' bordercolor="' + borderColor + '"';
}
html += '>';
for (var i = 0; i < rows; i++) {
html += '<tr>';
for (var j = 0; j < cols; j++) {
html += '<td>' + (K.IE ? ' ' : '<br />') + '</td>';
}
html += '</tr>';
}
html += '</table>';
if (!K.IE) {
html += '<br />';
}
self.insertHtml(html);
self.select().hideDialog().focus();
self.addBookmark();
}
}
}),
div = dialog.div,
rowsBox = K('[name="rows"]', div).val(3),
colsBox = K('[name="cols"]', div).val(2),
widthBox = K('[name="width"]', div).val(100),
heightBox = K('[name="height"]', div),
widthTypeBox = K('[name="widthType"]', div),
heightTypeBox = K('[name="heightType"]', div),
paddingBox = K('[name="padding"]', div).val(2),
spacingBox = K('[name="spacing"]', div).val(0),
alignBox = K('[name="align"]', div),
borderBox = K('[name="border"]', div).val(1),
colorBox = K('.ke-input-color', div);
function setColor(box, color) {
color = color.toUpperCase();
box.css('background-color', color);
box.css('color', color === '#000000' ? '#FFFFFF' : '#000000');
box.html(color);
}
setColor(K(colorBox[0]), '#000000');
setColor(K(colorBox[1]), '');
function clickHandler(e) {
removePicker();
if (!picker || this !== currentElement) {
var box = K(this),
pos = box.pos();
picker = K.colorpicker({
x : pos.x,
y : pos.y + box.height(),
z : 811214,
selectedColor : K(this).html(),
colors : self.colorTable,
noColor : self.lang('noColor'),
shadowMode : self.shadowMode,
click : function(color) {
setColor(box, color);
removePicker();
}
});
currentElement = this;
}
}
colorBox.click(clickHandler);
// foucs and select
rowsBox[0].focus();
rowsBox[0].select();
var table;
if (isInsert) {
return;
}
//get selected table node
table = self.plugin.getSelectedTable();
if (table) {
rowsBox.val(table[0].rows.length);
colsBox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0);
rowsBox.attr('disabled', true);
colsBox.attr('disabled', true);
var match,
tableWidth = table[0].style.width || table[0].width,
tableHeight = table[0].style.height || table[0].height;
if (tableWidth !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableWidth))) {
widthBox.val(match[1]);
widthTypeBox.val(match[2]);
} else {
widthBox.val('');
}
if (tableHeight !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableHeight))) {
heightBox.val(match[1]);
heightTypeBox.val(match[2]);
}
paddingBox.val(table[0].cellPadding || '');
spacingBox.val(table[0].cellSpacing || '');
alignBox.val(table[0].align || '');
borderBox.val(table[0].border === undefined ? '' : table[0].border);
setColor(K(colorBox[0]), K.toHex(table.attr('borderColor') || ''));
setColor(K(colorBox[1]), K.toHex(table[0].style.backgroundColor || table[0].bgColor || ''));
widthBox[0].focus();
widthBox[0].select();
}
},
//modify cell
cellprop : function() {
var html = [
'<div style="padding:10px 20px;">',
//width, height
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
'<select name="widthType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<select name="heightType">',
'<option value="%">' + lang.percent + '</option>',
'<option value="px">' + lang.px + '</option>',
'</select>',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
lang.textAlign + ' <select id="keAlign" name="textAlign">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="left">' + lang.alignLeft + '</option>',
'<option value="center">' + lang.alignCenter + '</option>',
'<option value="right">' + lang.alignRight + '</option>',
'</select> ',
lang.verticalAlign + ' <select name="verticalAlign">',
'<option value="">' + lang.alignDefault + '</option>',
'<option value="top">' + lang.alignTop + '</option>',
'<option value="middle">' + lang.alignMiddle + '</option>',
'<option value="bottom">' + lang.alignBottom + '</option>',
'<option value="baseline">' + lang.alignBaseline + '</option>',
'</select>',
'</div>',
//border
'<div class="ke-dialog-row">',
'<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> ',
lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
'</div>',
//background color
'<div class="ke-dialog-row">',
'<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
'<span class="ke-inline-block ke-input-color"></span>',
'</div>',
'</div>'
].join('');
var picker, currentElement;
function removePicker() {
if (picker) {
picker.remove();
picker = null;
currentElement = null;
}
}
var dialog = self.createDialog({
name : name,
width : 500,
height : 220,
title : self.lang('tablecell'),
body : html,
beforeDrag : removePicker,
beforeRemove : function() {
removePicker();
colorBox.unbind();
},
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var width = widthBox.val(),
height = heightBox.val(),
widthType = widthTypeBox.val(),
heightType = heightTypeBox.val(),
padding = paddingBox.val(),
spacing = spacingBox.val(),
textAlign = textAlignBox.val(),
verticalAlign = verticalAlignBox.val(),
border = borderBox.val(),
borderColor = K(colorBox[0]).html() || '',
bgColor = K(colorBox[1]).html() || '';
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
if (!/^\d*$/.test(border)) {
alert(self.lang('invalidBorder'));
borderBox[0].focus();
return;
}
cell.css({
width : width !== '' ? (width + widthType) : '',
height : height !== '' ? (height + heightType) : '',
'background-color' : bgColor,
'text-align' : textAlign,
'vertical-align' : verticalAlign,
'border-width' : border,
'border-style' : border !== '' ? 'solid' : '',
'border-color' : borderColor
});
self.hideDialog().focus();
self.addBookmark();
}
}
}),
div = dialog.div,
widthBox = K('[name="width"]', div).val(100),
heightBox = K('[name="height"]', div),
widthTypeBox = K('[name="widthType"]', div),
heightTypeBox = K('[name="heightType"]', div),
paddingBox = K('[name="padding"]', div).val(2),
spacingBox = K('[name="spacing"]', div).val(0),
textAlignBox = K('[name="textAlign"]', div),
verticalAlignBox = K('[name="verticalAlign"]', div),
borderBox = K('[name="border"]', div).val(1),
colorBox = K('.ke-input-color', div);
function setColor(box, color) {
color = color.toUpperCase();
box.css('background-color', color);
box.css('color', color === '#000000' ? '#FFFFFF' : '#000000');
box.html(color);
}
setColor(K(colorBox[0]), '#000000');
setColor(K(colorBox[1]), '');
function clickHandler(e) {
removePicker();
if (!picker || this !== currentElement) {
var box = K(this),
pos = box.pos();
picker = K.colorpicker({
x : pos.x,
y : pos.y + box.height(),
z : 811214,
selectedColor : K(this).html(),
colors : self.colorTable,
noColor : self.lang('noColor'),
shadowMode : self.shadowMode,
click : function(color) {
setColor(box, color);
removePicker();
}
});
currentElement = this;
}
}
colorBox.click(clickHandler);
// foucs and select
widthBox[0].focus();
widthBox[0].select();
// get selected cell
var cell = self.plugin.getSelectedCell();
var match,
cellWidth = cell[0].style.width || cell[0].width || '',
cellHeight = cell[0].style.height || cell[0].height || '';
if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) {
widthBox.val(match[1]);
widthTypeBox.val(match[2]);
} else {
widthBox.val('');
}
if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) {
heightBox.val(match[1]);
heightTypeBox.val(match[2]);
}
textAlignBox.val(cell[0].style.textAlign || '');
verticalAlignBox.val(cell[0].style.verticalAlign || '');
var border = cell[0].style.borderWidth || '';
if (border) {
border = parseInt(border);
}
borderBox.val(border);
setColor(K(colorBox[0]), K.toHex(cell[0].style.borderColor || ''));
setColor(K(colorBox[1]), K.toHex(cell[0].style.backgroundColor || ''));
widthBox[0].focus();
widthBox[0].select();
},
insert : function() {
this.prop(true);
},
'delete' : function() {
var table = self.plugin.getSelectedTable();
self.cmd.range.setStartBefore(table[0]).collapse(true);
self.cmd.select();
table.remove();
self.addBookmark();
},
colinsert : function(offset) {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
index = cell.cellIndex + offset;
for (var i = 0, len = table.rows.length; i < len; i++) {
var newRow = table.rows[i],
newCell = newRow.insertCell(index);
newCell.innerHTML = K.IE ? '' : '<br />';
// 调整下一行的单元格index
index = _getCellIndex(table, newRow, newCell);
}
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colinsertleft : function() {
this.colinsert(0);
},
colinsertright : function() {
this.colinsert(1);
},
rowinsert : function(offset) {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
newRow;
if (offset === 1) {
newRow = table.insertRow(row.rowIndex + (cell.rowSpan - 1) + offset);
} else {
newRow = table.insertRow(row.rowIndex);
}
for (var i = 0, len = row.cells.length; i < len; i++) {
var newCell = newRow.insertCell(i);
// copy colspan
if (offset === 1 && row.cells[i].colSpan > 1) {
newCell.colSpan = row.cells[i].colSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
}
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
rowinsertabove : function() {
this.rowinsert(0);
},
rowinsertbelow : function() {
this.rowinsert(1);
},
rowmerge : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex, // 当前行的index
nextRowIndex = rowIndex + cell.rowSpan, // 下一行的index
nextRow = table.rows[nextRowIndex]; // 下一行
// 最后一行不能合并
if (table.rows.length <= nextRowIndex) {
return;
}
var cellIndex = _getCellIndex(table, row, cell); // 下一行单元格的index
if (nextRow.cells.length <= cellIndex) {
return;
}
var nextCell = nextRow.cells[cellIndex]; // 下一行单元格
// 上下行的colspan不一致时不能合并
if (cell.colSpan !== nextCell.colSpan) {
return;
}
cell.rowSpan += nextCell.rowSpan;
nextRow.deleteCell(cellIndex);
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colmerge : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex, // 当前行的index
cellIndex = cell.cellIndex,
nextCellIndex = cellIndex + 1;
// 最后一列不能合并
if (row.cells.length <= nextCellIndex) {
return;
}
var nextCell = row.cells[nextCellIndex];
// 左右列的rowspan不一致时不能合并
if (cell.rowSpan !== nextCell.rowSpan) {
return;
}
cell.colSpan += nextCell.colSpan;
row.deleteCell(nextCellIndex);
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
rowsplit : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex;
// 不是可分割单元格
if (cell.rowSpan === 1) {
return;
}
var cellIndex = _getCellIndex(table, row, cell);
for (var i = 1, len = cell.rowSpan; i < len; i++) {
var newRow = table.rows[rowIndex + i],
newCell = newRow.insertCell(cellIndex);
if (cell.colSpan > 1) {
newCell.colSpan = cell.colSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
// 调整下一行的单元格index
cellIndex = _getCellIndex(table, newRow, newCell);
}
K(cell).removeAttr('rowSpan');
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
colsplit : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
cellIndex = cell.cellIndex;
// 不是可分割单元格
if (cell.colSpan === 1) {
return;
}
for (var i = 1, len = cell.colSpan; i < len; i++) {
var newCell = row.insertCell(cellIndex + i);
if (cell.rowSpan > 1) {
newCell.rowSpan = cell.rowSpan;
}
newCell.innerHTML = K.IE ? '' : '<br />';
}
K(cell).removeAttr('colSpan');
self.cmd.range.selectNodeContents(cell).collapse(true);
self.cmd.select();
self.addBookmark();
},
coldelete : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
index = cell.cellIndex;
for (var i = 0, len = table.rows.length; i < len; i++) {
var newRow = table.rows[i],
newCell = newRow.cells[index];
if (newCell.colSpan > 1) {
newCell.colSpan -= 1;
if (newCell.colSpan === 1) {
K(newCell).removeAttr('colSpan');
}
} else {
newRow.deleteCell(index);
}
// 跳过不需要删除的行
if (newCell.rowSpan > 1) {
i += newCell.rowSpan - 1;
}
}
if (row.cells.length === 0) {
self.cmd.range.setStartBefore(table).collapse(true);
self.cmd.select();
K(table).remove();
} else {
self.cmd.selection(true);
}
self.addBookmark();
},
rowdelete : function() {
var table = self.plugin.getSelectedTable()[0],
row = self.plugin.getSelectedRow()[0],
cell = self.plugin.getSelectedCell()[0],
rowIndex = row.rowIndex;
// 从下到上删除
for (var i = cell.rowSpan - 1; i >= 0; i--) {
table.deleteRow(rowIndex + i);
}
if (table.rows.length === 0) {
self.cmd.range.setStartBefore(table).collapse(true);
self.cmd.select();
K(table).remove();
} else {
self.cmd.selection(true);
}
self.addBookmark();
}
};
self.clickToolbar(name, self.plugin.table.prop);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('media', function(K) {
var self = this, name = 'media', lang = self.lang(name + '.'),
allowMediaUpload = K.undef(self.allowMediaUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
self.plugin.media = {
edit : function() {
var html = [
'<div style="padding:10px 20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
'</div>',
//autostart
'<div class="ke-dialog-row">',
'<label for="keAutostart">' + lang.autostart + '</label>',
'<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 230,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType(url),
width : width,
height : height,
autostart : autostartBox[0].checked ? 'true' : 'false',
loop : 'true'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
autostartBox = K('[name="autostart"]', div);
urlBox.val('http://');
if (allowMediaUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=media'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
urlBox.width(250);
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'media',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedMedia();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
autostartBox[0].checked = (attrs.autostart === 'true');
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedMedia().remove();
}
};
self.clickToolbar(name, self.plugin.media.edit);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// google code prettify: http://google-code-prettify.googlecode.com/
// http://google-code-prettify.googlecode.com/
KindEditor.plugin('code', function(K) {
var self = this, name = 'code';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<select class="ke-code-type">',
'<option value="js">JavaScript</option>',
'<option value="html">HTML</option>',
'<option value="css">CSS</option>',
'<option value="php">PHP</option>',
'<option value="pl">Perl</option>',
'<option value="py">Python</option>',
'<option value="rb">Ruby</option>',
'<option value="java">Java</option>',
'<option value="vb">ASP/VB</option>',
'<option value="cpp">C/C++</option>',
'<option value="cs">C#</option>',
'<option value="xml">XML</option>',
'<option value="bsh">Shell</option>',
'<option value="">Other</option>',
'</select>',
'</div>',
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>',
'</div>'].join(''),
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var type = K('.ke-code-type', dialog.div).val(),
code = textarea.val(),
cls = type === '' ? '' : ' lang-' + type,
html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> ';
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('wordpaste', function(K) {
var self = this, name = 'wordpaste';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
'<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var str = doc.body.innerHTML;
str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags);
self.insertHtml(str).hideDialog().focus();
}
}
}),
div = dialog.div,
iframe = K('iframe', div),
doc = K.iframeDoc(iframe);
if (!K.IE) {
doc.designMode = 'on';
}
doc.open();
doc.write('<!doctype html><html><head><title>WordPaste</title></head>');
doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">');
if (!K.IE) {
doc.write('<br />');
}
doc.write('</body></html>');
doc.close();
if (K.IE) {
doc.body.contentEditable = 'true';
}
iframe[0].contentWindow.focus();
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('anchor', function(K) {
var self = this, name = 'anchor', lang = self.lang(name + '.');
self.plugin.anchor = {
edit : function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keName">' + lang.name + '</label>',
'<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />',
'</div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 300,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus();
}
}
});
var div = dialog.div,
nameBox = K('input[name="name"]', div);
var img = self.plugin.getSelectedAnchor();
if (img) {
nameBox.val(unescape(img.attr('data-ke-name')));
}
nameBox[0].focus();
nameBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedAnchor().remove();
}
};
self.clickToolbar(name, self.plugin.anchor.edit);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('filemanager', function(K) {
var self = this, name = 'filemanager',
fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'),
imgPath = self.pluginsPath + name + '/images/',
lang = self.lang(name + '.');
function makeFileTitle(filename, filesize, datetime) {
return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
}
function bindTitle(el, data) {
if (data.is_dir) {
el.attr('title', data.filename);
} else {
el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
}
}
self.plugin.filemanagerDialog = function(options) {
var width = K.undef(options.width, 520),
height = K.undef(options.height, 510),
dirName = K.undef(options.dirName, ''),
viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST" or "VIEW"
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
// header start
'<div class="ke-plugin-filemanager-header">',
// left start
'<div class="ke-left">',
'<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
'<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
'</div>',
// right start
'<div class="ke-right">',
lang.viewType + ' <select class="ke-inline-block" name="viewType">',
'<option value="VIEW">' + lang.viewImage + '</option>',
'<option value="LIST">' + lang.listImage + '</option>',
'</select> ',
lang.orderType + ' <select class="ke-inline-block" name="orderType">',
'<option value="NAME">' + lang.fileName + '</option>',
'<option value="SIZE">' + lang.fileSize + '</option>',
'<option value="TYPE">' + lang.fileType + '</option>',
'</select>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
// body start
'<div class="ke-plugin-filemanager-body"></div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : width,
height : height,
title : self.lang(name),
body : html
}),
div = dialog.div,
bodyDiv = K('.ke-plugin-filemanager-body', div),
moveupImg = K('[name="moveupImg"]', div),
moveupLink = K('[name="moveupLink"]', div),
viewServerBtn = K('[name="viewServer"]', div),
viewTypeBox = K('[name="viewType"]', div),
orderTypeBox = K('[name="orderType"]', div);
function reloadPage(path, order, func) {
var param = 'path=' + path + '&order=' + order + '&dir=' + dirName;
dialog.showLoading(self.lang('ajaxLoading'));
K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
dialog.hideLoading();
func(data);
});
}
var elList = [];
function bindEvent(el, result, data, createFunc) {
var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'),
dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/');
if (data.is_dir) {
el.click(function(e) {
reloadPage(dirPath, orderTypeBox.val(), createFunc);
});
} else if (data.is_photo) {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
} else {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
}
elList.push(el);
}
function createCommon(result, createFunc) {
// remove events
K.each(elList, function() {
this.unbind();
});
moveupLink.unbind();
viewTypeBox.unbind();
orderTypeBox.unbind();
// add events
if (result.current_dir_path) {
moveupLink.click(function(e) {
reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
});
}
function changeFunc() {
if (viewTypeBox.val() == 'VIEW') {
reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
} else {
reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
}
}
viewTypeBox.change(changeFunc);
orderTypeBox.change(changeFunc);
bodyDiv.html('');
}
function createList(result) {
createCommon(result, createList);
var table = document.createElement('table');
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
bodyDiv.append(table);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i], row = K(table.insertRow(i));
row.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
if (!data.is_dir || data.has_file) {
row.css('cursor', 'pointer');
cell0.attr('title', data.filename);
bindEvent(cell0, result, data, createList);
} else {
cell0.attr('title', lang.emptyFolder);
}
K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
}
}
function createView(result) {
createCommon(result, createView);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i],
div = K('<div class="ke-inline-block ke-item"></div>');
bodyDiv.append(div);
var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
div.append(photoDiv);
var fileUrl = result.current_url + data.filename,
iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
if (!data.is_dir || data.has_file) {
photoDiv.css('cursor', 'pointer');
bindTitle(photoDiv, data);
bindEvent(photoDiv, result, data, createView);
} else {
photoDiv.attr('title', lang.emptyFolder);
}
photoDiv.append(img);
div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
}
}
viewTypeBox.val(viewType);
reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
return dialog;
}
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('preview', function(K) {
var self = this, name = 'preview', undefined;
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 750,
title : self.lang(name),
body : html
}),
iframe = K('iframe', dialog.div),
doc = K.iframeDoc(iframe);
doc.open();
doc.write(self.fullHtml());
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// Google Maps: http://code.google.com/apis/maps/index.html
KindEditor.plugin('map', function(K) {
var self = this, name = 'map', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
'</span>',
'</div>',
'<div class="ke-map" style="width:558px;height:360px;"></div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 600,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var geocoder = win.geocoder,
map = win.map,
center = map.getCenter().lat() + ',' + map.getCenter().lng(),
zoom = map.getZoom(),
maptype = map.getMapTypeId(),
url = 'http://maps.googleapis.com/maps/api/staticmap';
url += '?center=' + encodeURIComponent(center);
url += '&zoom=' + encodeURIComponent(zoom);
url += '&size=558x360';
url += '&maptype=' + encodeURIComponent(maptype);
url += '&markers=' + encodeURIComponent(center);
url += '&language=' + self.langType;
url += '&sensor=false';
self.exec('insertimage', url).hideDialog().focus();
}
},
beforeRemove : function() {
searchBtn.remove();
if (doc) {
doc.write('');
}
iframe.remove();
}
});
var div = dialog.div,
addressBox = K('[name="address"]', div),
searchBtn = K('[name="searchBtn"]', div),
win, doc;
var iframeHtml = ['<!doctype html><html><head>',
'<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />',
'<style>',
' html { height: 100% }',
' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }',
' #map_canvas { height: 100% }',
'</style>',
'<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>',
'<script>',
'var map, geocoder;',
'function initialize() {',
' var latlng = new google.maps.LatLng(31.230393, 121.473704);',
' var options = {',
' zoom: 11,',
' center: latlng,',
' disableDefaultUI: true,',
' panControl: true,',
' zoomControl: true,',
' mapTypeControl: true,',
' scaleControl: true,',
' streetViewControl: false,',
' overviewMapControl: true,',
' mapTypeId: google.maps.MapTypeId.ROADMAP',
' };',
' map = new google.maps.Map(document.getElementById("map_canvas"), options);',
' geocoder = new google.maps.Geocoder();',
' geocoder.geocode({latLng: latlng}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' if (results[3]) {',
' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;',
' }',
' }',
' });',
'}',
'function search(address) {',
' if (!map) return;',
' geocoder.geocode({address : address}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' map.setZoom(11);',
' map.setCenter(results[0].geometry.location);',
' var marker = new google.maps.Marker({',
' map: map,',
' position: results[0].geometry.location',
' });',
' } else {',
' alert("Invalid address: " + address);',
' }',
' });',
'}',
'</script>',
'</head>',
'<body onload="initialize();">',
'<div id="map_canvas" style="width:100%; height:100%"></div>',
'</body></html>'].join('\n');
// TODO:用doc.write(iframeHtml)方式加载时,在IE6上第一次加载报错,暂时使用src方式
var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>');
function ready() {
win = iframe[0].contentWindow;
doc = K.iframeDoc(iframe);
//doc.open();
//doc.write(iframeHtml);
//doc.close();
}
iframe.bind('load', function() {
iframe.unbind('load');
if (K.IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
K('.ke-map', div).replaceWith(iframe);
// search map
searchBtn.click(function() {
win.search(addressBox.val());
});
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('plainpaste', function(K) {
var self = this, name = 'plainpaste';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var html = textarea.val();
html = K.escape(html);
html = html.replace(/ /g, ' ');
if (self.newlineTag == 'p') {
html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
} else {
html = html.replace(/\n/g, '<br />$&');
}
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('image', function(K) {
var self = this, name = 'image',
allowImageUpload = K.undef(self.allowImageUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
imgPath = self.basePath + 'plugins/image/images/',
lang = self.lang(name + '.');
self.plugin.imageDialog = function(options) {
var imageUrl = K.undef(options.imageUrl, 'http://'),
imageWidth = K.undef(options.imageWidth, ''),
imageHeight = K.undef(options.imageHeight, ''),
imageTitle = K.undef(options.imageTitle, ''),
imageAlign = K.undef(options.imageAlign, ''),
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
//tabs
'<div class="tabs"></div>',
//url or file
'<div class="ke-dialog-row">',
'<div class="tab1" style="display:none;">',
'<label for="keUrl" style="width:60px;">' + lang.remoteUrl + '</label>',
'<input type="text" id="keUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
'<div class="tab2" style="display:none;">',
'<label style="width:60px;">' + lang.localUrl + '</label>',
'<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.viewServer + '" />',
'</div>',
'</div>',
//size
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.size + '</label>',
lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
'<img class="ke-refresh-btn" src="' + imgPath + 'refresh.gif" width="16" height="16" alt="" style="cursor:pointer;" />',
'</div>',
//align
'<div class="ke-dialog-row">',
'<label style="width:60px;">' + lang.align + '</label>',
'<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="keTitle" style="width:60px;">' + lang.imgTitle + '</label>',
'<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:200px;" /></div>',
'</div>',
'</div>'
].join('');
var dialogWidth = allowImageUpload ? 450 : 400;
dialogHeight = allowImageUpload ? 300 : 250;
var dialog = self.createDialog({
name : name,
width : dialogWidth,
height : dialogHeight,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
// insert local image
if (tabs && tabs.selectedIndex === 1) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
localUrlBox.val('');
return;
}
// insert remote image
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val(),
title = titleBox.val(),
align = '';
alignBox.each(function() {
if (this.checked) {
align = this.value;
return false;
}
});
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
clickFn.call(self, url, title, width, height, 0, align);
}
},
beforeRemove : function() {
viewServerBtn.remove();
widthBox.remove();
heightBox.remove();
refreshBtn.remove();
uploadbutton.remove();
}
}),
div = dialog.div;
var tabs;
if (allowImageUpload) {
tabs = K.tabs({
src : K('.tabs', div),
afterSelect : function(i) {
}
});
tabs.add({
title : lang.remoteImage,
panel : K('.tab1', div)
});
tabs.add({
title : lang.localImage,
panel : K('.tab2', div)
});
tabs.select(0);
} else {
K('.tab1', div).show();
}
var urlBox = K('[name="url"]', div),
localUrlBox = K('[name="localUrl"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
refreshBtn = K('.ke-refresh-btn', div),
titleBox = K('[name="title"]', div),
alignBox = K('[name="align"]');
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=image'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var width = widthBox.val(),
height = heightBox.val(),
title = titleBox.val(),
align = '';
alignBox.each(function() {
if (this.checked) {
align = this.value;
return false;
}
});
var url = K.formatUrl(data.url, 'absolute');
clickFn.call(self, url, title, width, height, 0, align);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
localUrlBox.val(uploadbutton.fileBox.val());
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'VIEW',
dirName : 'image',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var originalWidth = 0, originalHeight = 0;
function setSize(width, height) {
widthBox.val(width);
heightBox.val(height);
originalWidth = width;
originalHeight = height;
}
refreshBtn.click(function(e) {
var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
position : 'absolute',
visibility : 'hidden',
top : 0,
left : '-1000px'
});
K(document.body).append(tempImg);
setSize(tempImg.width(), tempImg.height());
tempImg.remove();
});
widthBox.change(function(e) {
if (originalWidth > 0) {
heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
}
});
heightBox.change(function(e) {
if (originalHeight > 0) {
widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
}
});
urlBox.val(options.imageUrl);
setSize(options.imageWidth, options.imageHeight);
titleBox.val(options.imageTitle);
alignBox.each(function() {
if (this.value === options.imageAlign) {
this.checked = true;
return false;
}
});
urlBox[0].focus();
urlBox[0].select();
return dialog;
};
self.plugin.image = {
edit : function() {
var img = self.plugin.getSelectedImage();
self.plugin.imageDialog({
imageUrl : img ? img.attr('data-ke-src') : 'http://',
imageWidth : img ? img.width() : '',
imageHeight : img ? img.height() : '',
imageTitle : img ? img.attr('title') : '',
imageAlign : img ? img.attr('align') : '',
clickFn : function(url, title, width, height, border, align) {
self.exec('insertimage', url, title, width, height, border, align).hideDialog().focus();
}
});
},
'delete' : function() {
self.plugin.getSelectedImage().remove();
}
};
self.clickToolbar(name, self.plugin.image.edit);
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('lineheight', function(K) {
var self = this, name = 'lineheight', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'});
if (commonNode) {
curVal = commonNode.css('line-height');
}
var menu = self.createMenu({
name : name,
width : 150
});
K.each(lang.lineHeight, function(i, row) {
K.each(row, function(key, val) {
menu.addItem({
title : val,
checked : curVal === key,
click : function() {
self.cmd.toggle('<span style="line-height:' + key + ';"></span>', {
span : '.line-height=' + key
});
self.updateState();
self.addBookmark();
self.hideMenu();
}
});
});
});
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('template', function(K) {
var self = this, name = 'template', lang = self.lang(name + '.'),
htmlPath = self.pluginsPath + name + '/html/';
function getFilePath(fileName) {
return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION);
}
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
arr = ['<div class="ke-plugin-template" style="padding:10px 20px;">',
'<div class="ke-header">',
// left start
'<div class="ke-left">',
lang. selectTemplate + ' <select>'];
K.each(lang.fileList, function(key, val) {
arr.push('<option value="' + key + '">' + val + '</option>');
});
html = [arr.join(''),
'</select></div>',
// right start
'<div class="ke-right">',
'<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
'<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 500,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var doc = K.iframeDoc(iframe);
self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus();
}
}
});
var selectBox = K('select', dialog.div),
checkbox = K('[name="replaceFlag"]', dialog.div),
iframe = K('iframe', dialog.div);
checkbox[0].checked = true;
iframe.attr('src', getFilePath(selectBox.val()));
selectBox.change(function() {
iframe.attr('src', getFilePath(this.value));
});
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('emoticons', function(K) {
var self = this, name = 'emoticons',
path = (self.emoticonsPath || self.basePath + 'plugins/emoticons/images/'),
allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
currentPageNum = 1;
self.clickToolbar(name, function() {
var rows = 5, cols = 9, total = 135, startNum = 0,
cells = rows * cols, pages = Math.ceil(total / cells),
colsHalf = Math.floor(cols / 2),
wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
elements = [],
menu = self.createMenu({
name : name,
beforeRemove : function() {
removeEvent();
}
});
menu.div.append(wrapperDiv);
var previewDiv, previewImg;
if (allowPreview) {
previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
wrapperDiv.append(previewDiv);
previewDiv.append(previewImg);
}
function bindCellEvent(cell, j, num) {
if (previewDiv) {
cell.mouseover(function() {
if (j > colsHalf) {
previewDiv.css('left', 0);
previewDiv.css('right', '');
} else {
previewDiv.css('left', '');
previewDiv.css('right', 0);
}
previewImg.attr('src', path + num + '.gif');
K(this).addClass('ke-on');
});
} else {
cell.mouseover(function() {
K(this).addClass('ke-on');
});
}
cell.mouseout(function() {
K(this).removeClass('ke-on');
});
cell.click(function(e) {
self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
e.stop();
});
}
function createEmoticonsTable(pageNum, parentDiv) {
var table = document.createElement('table');
parentDiv.append(table);
if (previewDiv) {
K(table).mouseover(function() {
previewDiv.show();
});
K(table).mouseout(function() {
previewDiv.hide();
});
elements.push(K(table));
}
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var num = (pageNum - 1) * cells + startNum;
for (var i = 0; i < rows; i++) {
var row = table.insertRow(i);
for (var j = 0; j < cols; j++) {
var cell = K(row.insertCell(j));
cell.addClass('ke-cell');
bindCellEvent(cell, j, num);
var span = K('<span class="ke-img"></span>')
.css('background-position', '-' + (24 * num) + 'px 0px')
.css('background-image', 'url(' + path + 'static.gif)');
cell.append(span);
elements.push(cell);
num++;
}
}
return table;
}
var table = createEmoticonsTable(currentPageNum, wrapperDiv);
function removeEvent() {
K.each(elements, function() {
this.unbind();
});
}
var pageDiv;
function bindPageEvent(el, pageNum) {
el.click(function(e) {
removeEvent();
table.parentNode.removeChild(table);
pageDiv.remove();
table = createEmoticonsTable(pageNum, wrapperDiv);
createPageTable(pageNum);
currentPageNum = pageNum;
e.stop();
});
}
function createPageTable(currentPageNum) {
pageDiv = K('<div class="ke-page"></div>');
wrapperDiv.append(pageDiv);
for (var pageNum = 1; pageNum <= pages; pageNum++) {
if (currentPageNum !== pageNum) {
var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
bindPageEvent(a, pageNum);
pageDiv.append(a);
elements.push(a);
} else {
pageDiv.append(K('@[' + pageNum + ']'));
}
pageDiv.append(K('@ '));
}
}
createPageTable(currentPageNum);
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('clearhtml', function(K) {
var self = this, name = 'clearhtml';
self.clickToolbar(name, function() {
self.focus();
var html = self.html();
html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, '');
html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, '');
html = K.formatHtml(html, {
a : ['href', 'target'],
embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
img : ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'],
table : ['border'],
'td,th' : ['rowspan', 'colspan'],
'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : []
});
self.html(html);
self.cmd.selection(true);
self.addBookmark();
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('pagebreak', function(K) {
var self = this, name = 'pagebreak';
self.clickToolbar(name, function() {
var cmd = self.cmd, range = cmd.range;
self.focus();
range.enlarge(true);
cmd.split(true);
var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<p id="__kindeditor_tail_tag__"></p>';
self.insertHtml('<hr style="page-break-after: always;" class="ke-pagebreak" />' + tail);
if (tail !== '') {
var p = K('#__kindeditor_tail_tag__', self.edit.doc);
range.selectNodeContents(p[0]);
p.removeAttr('id');
cmd.select();
}
});
});
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @website http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
* @version 4.0.4 (2011-12-11)
*******************************************************************************/
(function (window, undefined) {
if (window.KindEditor) {
return;
}
if (!window.console) {
window.console = {};
}
if (!console.log) {
console.log = function () {};
}
var _VERSION = '4.0.4 (2011-12-11)',
_ua = navigator.userAgent.toLowerCase(),
_IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
_GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
_WEBKIT = _ua.indexOf('applewebkit') > -1,
_OPERA = _ua.indexOf('opera') > -1,
_MOBILE = _ua.indexOf('mobile') > -1,
_QUIRKS = document.compatMode != 'CSS1Compat',
_matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
_V = _matches ? _matches[1] : '0',
_TIME = new Date().getTime();
function _isArray(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Array]';
}
function _isFunction(val) {
if (!val) {
return false;
}
return Object.prototype.toString.call(val) === '[object Function]';
}
function _inArray(val, arr) {
for (var i = 0, len = arr.length; i < len; i++) {
if (val === arr[i]) {
return i;
}
}
return -1;
}
function _each(obj, fn) {
if (_isArray(obj)) {
for (var i = 0, len = obj.length; i < len; i++) {
if (fn.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (fn.call(obj[key], key, obj[key]) === false) {
break;
}
}
}
}
}
function _trim(str) {
return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
}
function _inString(val, str, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
}
function _addUnit(val, unit) {
unit = unit || 'px';
return val && /^\d+$/.test(val) ? val + 'px' : val;
}
function _removeUnit(val) {
var match;
return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
}
function _escape(val) {
return val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function _unescape(val) {
return val.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
}
function _toCamel(str) {
var arr = str.split('-');
str = '';
_each(arr, function(key, val) {
str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
});
return str;
}
function _toHex(val) {
function hex(d) {
var s = parseInt(d, 10).toString(16).toUpperCase();
return s.length > 1 ? s : '0' + s;
}
return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
function($0, $1, $2, $3) {
return '#' + hex($1) + hex($2) + hex($3);
}
);
}
function _toMap(val, delimiter) {
delimiter = delimiter === undefined ? ',' : delimiter;
var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
_each(arr, function(key, val) {
if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
map[i.toString()] = true;
}
} else {
map[val] = true;
}
});
return map;
}
function _toArray(obj, offset) {
return Array.prototype.slice.call(obj, offset || 0);
}
function _undef(val, defaultVal) {
return val === undefined ? defaultVal : val;
}
function _invalidUrl(url) {
return !url || /[<>"]/.test(url);
}
function _addParam(url, param) {
return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
}
function _extend(child, parent, proto) {
if (!proto) {
proto = parent;
parent = null;
}
var childProto;
if (parent) {
var fn = function () {};
fn.prototype = parent.prototype;
childProto = new fn();
_each(proto, function(key, val) {
childProto[key] = val;
});
} else {
childProto = proto;
}
childProto.constructor = child;
child.prototype = childProto;
child.parent = parent ? parent.prototype : null;
}
function _json(text) {
var match;
if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
text = match[0];
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
return eval('(' + text + ')');
}
throw 'JSON parse error';
}
var _round = Math.round;
var K = {
DEBUG : false,
VERSION : _VERSION,
IE : _IE,
GECKO : _GECKO,
WEBKIT : _WEBKIT,
OPERA : _OPERA,
V : _V,
TIME : _TIME,
each : _each,
isArray : _isArray,
isFunction : _isFunction,
inArray : _inArray,
inString : _inString,
trim : _trim,
addUnit : _addUnit,
removeUnit : _removeUnit,
escape : _escape,
unescape : _unescape,
toCamel : _toCamel,
toHex : _toHex,
toMap : _toMap,
toArray : _toArray,
undef : _undef,
invalidUrl : _invalidUrl,
addParam : _addParam,
extend : _extend,
json : _json
};
var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
_BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
_SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
_STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
_CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
_PRE_TAG_MAP = _toMap('pre,style,script'),
_NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
_AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
_FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
_VALUE_TAG_MAP = _toMap('input,button,textarea,select');
function _getBasePath() {
var els = document.getElementsByTagName('script'), src;
for (var i = 0, len = els.length; i < len; i++) {
src = els[i].src || '';
if (/kindeditor[\w\-\.]*\.js/.test(src)) {
return src.substring(0, src.lastIndexOf('/') + 1);
}
}
return '';
}
K.basePath = _getBasePath();
K.options = {
designMode : true,
fullscreenMode : false,
filterMode : false,
wellFormatMode : true,
shadowMode : true,
loadStyleMode : true,
basePath : K.basePath,
themesPath : K.basePath + 'themes/',
langPath : K.basePath + 'lang/',
pluginsPath : K.basePath + 'plugins/',
themeType : 'default',
langType : 'zh_CN',
urlType : '',
newlineTag : 'p',
resizeType : 2,
syncType : 'form',
pasteType : 2,
dialogAlignType : 'page',
useContextmenu : true,
bodyClass : 'ke-content',
indentChar : '\t',
cssPath : '',
cssData : '',
minWidth : 650,
minHeight : 100,
minChangeSize : 5,
items : [
'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'map', 'code', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about'
],
noDisableItems : ['source', 'fullscreen'],
colorTable : [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
],
fontSizeTable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
htmlTags : {
font : ['color', 'size', 'face', '.background-color'],
span : [
'.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
],
div : [
'align', '.border', '.margin', '.padding', '.text-align', '.color',
'.background-color', '.font-size', '.font-family', '.font-weight', '.background',
'.font-style', '.text-decoration', '.vertical-align', '.margin-left'
],
table: [
'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
'.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
'.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
'.width', '.height', '.border-collapse'
],
'td,th': [
'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
'.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
'.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
],
a : ['href', 'target', 'name'],
embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
img : ['src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
'.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
],
pre : ['class'],
hr : ['class', '.page-break-after'],
'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : []
},
layout : '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
};
var _useCapture = false;
var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
var _CURSORMOVE_KEY_MAP = _toMap('33..40');
var _CHANGE_KEY_MAP = {};
_each(_INPUT_KEY_MAP, function(key, val) {
_CHANGE_KEY_MAP[key] = val;
});
_each(_CURSORMOVE_KEY_MAP, function(key, val) {
_CHANGE_KEY_MAP[key] = val;
});
function _bindEvent(el, type, fn) {
if (el.addEventListener){
el.addEventListener(type, fn, _useCapture);
} else if (el.attachEvent){
el.attachEvent('on' + type, fn);
}
}
function _unbindEvent(el, type, fn) {
if (el.removeEventListener){
el.removeEventListener(type, fn, _useCapture);
} else if (el.detachEvent){
el.detachEvent('on' + type, fn);
}
}
var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
'data,detail,eventPhase,fromElement,handler,keyCode,layerX,layerY,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
function KEvent(el, event) {
this.init(el, event);
}
_extend(KEvent, {
init : function(el, event) {
var self = this, doc = el.ownerDocument || el.document || el;
self.event = event;
_each(_EVENT_PROPS, function(key, val) {
self[val] = event[val];
});
if (!self.target) {
self.target = self.srcElement || doc;
}
if (self.target.nodeType === 3) {
self.target = self.target.parentNode;
}
if (!self.relatedTarget && self.fromElement) {
self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
}
if (self.pageX == null && self.clientX != null) {
var d = doc.documentElement, body = doc.body;
self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
}
if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
self.which = self.charCode || self.keyCode;
}
if (!self.metaKey && self.ctrlKey) {
self.metaKey = self.ctrlKey;
}
if (!self.which && self.button !== undefined) {
self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
}
switch (self.which) {
case 186 :
self.which = 59;
break;
case 187 :
case 107 :
case 43 :
self.which = 61;
break;
case 189 :
case 45 :
self.which = 109;
break;
case 42 :
self.which = 106;
break;
case 47 :
self.which = 111;
break;
case 78 :
self.which = 110;
break;
}
if (self.which >= 96 && self.which <= 105) {
self.which -= 48;
}
},
preventDefault : function() {
var ev = this.event;
if (ev.preventDefault) {
ev.preventDefault();
}
ev.returnValue = false;
},
stopPropagation : function() {
var ev = this.event;
if (ev.stopPropagation) {
ev.stopPropagation();
}
ev.cancelBubble = true;
},
stop : function() {
this.preventDefault();
this.stopPropagation();
}
});
var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
function _getId(el) {
return el[_eventExpendo] || null;
}
function _setId(el) {
el[_eventExpendo] = ++_eventId;
return _eventId;
}
function _removeId(el) {
try {
delete el[_eventExpendo];
} catch(e) {
if (el.removeAttribute) {
el.removeAttribute(_eventExpendo);
}
}
}
function _bind(el, type, fn) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_bind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
id = _setId(el);
}
if (_eventData[id] === undefined) {
_eventData[id] = {};
}
var events = _eventData[id][type];
if (events && events.length > 0) {
_unbindEvent(el, type, events[0]);
} else {
_eventData[id][type] = [];
_eventData[id].el = el;
}
events = _eventData[id][type];
if (events.length === 0) {
events[0] = function(e) {
var kevent = e ? new KEvent(el, e) : undefined;
_each(events, function(i, event) {
if (i > 0 && event) {
event.call(el, kevent);
}
});
};
}
if (_inArray(fn, events) < 0) {
events.push(fn);
}
_bindEvent(el, type, events[0]);
}
function _unbind(el, type, fn) {
if (type && type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_unbind(el, this, fn);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
if (type === undefined) {
if (id in _eventData) {
_each(_eventData[id], function(key, events) {
if (key != 'el' && events.length > 0) {
_unbindEvent(el, key, events[0]);
}
});
delete _eventData[id];
_removeId(el);
}
return;
}
if (!_eventData[id]) {
return;
}
var events = _eventData[id][type];
if (events && events.length > 0) {
if (fn === undefined) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
} else {
_each(events, function(i, event) {
if (i > 0 && event === fn) {
events.splice(i, 1);
}
});
if (events.length == 1) {
_unbindEvent(el, type, events[0]);
delete _eventData[id][type];
}
}
var count = 0;
_each(_eventData[id], function() {
count++;
});
if (count < 2) {
delete _eventData[id];
_removeId(el);
}
}
}
function _fire(el, type) {
if (type.indexOf(',') >= 0) {
_each(type.split(','), function() {
_fire(el, this);
});
return;
}
var id = _getId(el);
if (!id) {
return;
}
var events = _eventData[id][type];
if (_eventData[id] && events && events.length > 0) {
events[0]();
}
}
function _ctrl(el, key, fn) {
var self = this;
key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
_bind(el, 'keydown', function(e) {
if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
fn.call(el);
e.stop();
}
});
}
function _ready(fn) {
var loaded = false;
function readyFunc() {
if (!loaded) {
loaded = true;
fn(KindEditor);
}
}
function ieReadyFunc() {
if (!loaded) {
try {
document.documentElement.doScroll('left');
} catch(e) {
setTimeout(ieReadyFunc, 100);
return;
}
readyFunc();
}
}
function ieReadyStateFunc() {
if (document.readyState === 'complete') {
readyFunc();
}
}
if (document.addEventListener) {
_bind(document, 'DOMContentLoaded', readyFunc);
} else if (document.attachEvent) {
_bind(document, 'readystatechange', ieReadyStateFunc);
if (document.documentElement.doScroll && window.frameElement === undefined) {
ieReadyFunc();
}
}
_bind(window, 'load', readyFunc);
}
if (_IE) {
window.attachEvent('onunload', function() {
_each(_eventData, function(key, events) {
if (events.el) {
_unbind(events.el);
}
});
});
}
K.ctrl = _ctrl;
K.ready = _ready;
function _getCssList(css) {
var list = {},
reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
match;
while ((match = reg.exec(css))) {
var key = _trim(match[1].toLowerCase()),
val = _trim(_toHex(match[2]));
list[key] = val;
}
return list;
}
function _getAttrList(tag) {
var list = {},
reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
match;
while ((match = reg.exec(tag))) {
var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
list[key] = val;
}
return list;
}
function _addClassToTag(tag, className) {
if (/\s+class\s*=/.test(tag)) {
tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
} else {
return $0;
}
});
} else {
tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
}
return tag;
}
function _formatCss(css) {
var str = '';
_each(_getCssList(css), function(key, val) {
str += key + ':' + val + ';';
});
return str;
}
function _formatUrl(url, mode, host, pathname) {
mode = _undef(mode, '').toLowerCase();
if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
return url;
}
host = host || location.protocol + '//' + location.host;
if (pathname === undefined) {
var m = location.pathname.match(/^(\/.*)\//);
pathname = m ? m[1] : '';
}
var match;
if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
if (match[1] !== host) {
return url;
}
} else if (/^\w+:/.test(url)) {
return url;
}
function getRealPath(path) {
var parts = path.split('/'), paths = [];
for (var i = 0, len = parts.length; i < len; i++) {
var part = parts[i];
if (part == '..') {
if (paths.length > 0) {
paths.pop();
}
} else if (part !== '' && part != '.') {
paths.push(part);
}
}
return '/' + paths.join('/');
}
if (/^\//.test(url)) {
url = host + getRealPath(url.substr(1));
} else if (!/^\w+:\/\//.test(url)) {
url = host + getRealPath(pathname + '/' + url);
}
function getRelativePath(path, depth) {
if (url.substr(0, path.length) === path) {
var arr = [];
for (var i = 0; i < depth; i++) {
arr.push('..');
}
var prefix = '.';
if (arr.length > 0) {
prefix += '/' + arr.join('/');
}
if (pathname == '/') {
prefix += '/';
}
return prefix + url.substr(path.length);
} else {
if ((match = /^(.*)\//.exec(path))) {
return getRelativePath(match[1], ++depth);
}
}
}
if (mode === 'relative') {
url = getRelativePath(host + pathname, 0).substr(2);
} else if (mode === 'absolute') {
if (url.substr(0, host.length) === host) {
url = url.substr(host.length);
}
}
return url;
}
function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
urlType = urlType || '';
wellFormatted = _undef(wellFormatted, false);
indentChar = _undef(indentChar, '\t');
var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
});
html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
html = html.replace(/\u200B/g, '');
var htmlTagMap = {};
if (htmlTags) {
_each(htmlTags, function(key, val) {
var arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
htmlTagMap[arr[i]] = _toMap(val);
}
});
if (!htmlTagMap.script) {
html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
}
if (!htmlTagMap.style) {
html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
}
}
var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
var tagStack = [];
html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
var full = $0,
startNewline = $1 || '',
startSlash = $2 || '',
tagName = $3.toLowerCase(),
attr = $4 || '',
endSlash = $5 ? ' ' + $5 : '',
endNewline = $6 || '';
if (htmlTags && !htmlTagMap[tagName]) {
return '';
}
if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
endSlash = ' /';
}
if (_INLINE_TAG_MAP[tagName]) {
if (startNewline) {
startNewline = ' ';
}
if (endNewline) {
endNewline = ' ';
}
}
if (_PRE_TAG_MAP[tagName]) {
if (startSlash) {
endNewline = '\n';
} else {
startNewline = '\n';
}
}
if (wellFormatted && tagName == 'br') {
endNewline = '\n';
}
if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
if (wellFormatted) {
if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
tagStack.pop();
} else {
tagStack.push(tagName);
}
startNewline = '\n';
endNewline = '\n';
for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
startNewline += indentChar;
if (!startSlash) {
endNewline += indentChar;
}
}
if (endSlash) {
tagStack.pop();
} else if (!startSlash) {
endNewline += indentChar;
}
} else {
startNewline = endNewline = '';
}
}
if (attr !== '') {
var attrMap = _getAttrList(full);
if (tagName === 'font') {
var fontStyleMap = {}, fontStyle = '';
_each(attrMap, function(key, val) {
if (key === 'color') {
fontStyleMap.color = val;
delete attrMap[key];
}
if (key === 'size') {
fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
delete attrMap[key];
}
if (key === 'face') {
fontStyleMap['font-family'] = val;
delete attrMap[key];
}
if (key === 'style') {
fontStyle = val;
}
});
if (fontStyle && !/;$/.test(fontStyle)) {
fontStyle += ';';
}
_each(fontStyleMap, function(key, val) {
if (val === '') {
return;
}
if (/\s/.test(val)) {
val = "'" + val + "'";
}
fontStyle += key + ':' + val + ';';
});
attrMap.style = fontStyle;
}
_each(attrMap, function(key, val) {
if (_FILL_ATTR_MAP[key]) {
attrMap[key] = key;
}
if (_inArray(key, ['src', 'href']) >= 0) {
attrMap[key] = _formatUrl(val, urlType);
}
if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
tagName === 'body' && key === 'contenteditable' ||
/^kindeditor_\d+$/.test(key)) {
delete attrMap[key];
}
if (key === 'style' && val !== '') {
var styleMap = _getCssList(val);
_each(styleMap, function(k, v) {
if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
delete styleMap[k];
}
});
var style = '';
_each(styleMap, function(k, v) {
style += k + ':' + v + ';';
});
attrMap.style = style;
}
});
attr = '';
_each(attrMap, function(key, val) {
if (key === 'style' && val === '') {
return;
}
val = val.replace(/"/g, '"');
attr += ' ' + key + '="' + val + '"';
});
}
if (tagName === 'font') {
tagName = 'span';
}
return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
});
html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
});
html = html.replace(/\n\s*\n/g, '\n');
html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
return _trim(html);
}
function _clearMsWord(html, htmlTags) {
html = html.replace(/<meta[\s\S]*?>/ig, '')
.replace(/<![\s\S]*?>/ig, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
.replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
.replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
.replace(/<(?:table|td)[^>]*>/ig, function(full) {
return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
});
return _formatHtml(html, htmlTags);
}
function _mediaType(src) {
if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
return 'audio/x-pn-realaudio-plugin';
}
if (/\.(swf|flv)(\?|$)/i.test(src)) {
return 'application/x-shockwave-flash';
}
return 'video/x-ms-asf-plugin';
}
function _mediaClass(type) {
if (/realaudio/i.test(type)) {
return 'ke-rm';
}
if (/flash/i.test(type)) {
return 'ke-flash';
}
return 'ke-media';
}
function _mediaAttrs(srcTag) {
return _getAttrList(unescape(srcTag));
}
function _mediaEmbed(attrs) {
var html = '<embed ';
_each(attrs, function(key, val) {
html += key + '="' + val + '" ';
});
html += '/>';
return html;
}
function _mediaImg(blankPath, attrs) {
var width = attrs.width,
height = attrs.height,
type = attrs.type || _mediaType(attrs.src),
srcTag = _mediaEmbed(attrs),
style = '';
if (width > 0) {
style += 'width:' + width + 'px;';
}
if (height > 0) {
style += 'height:' + height + 'px;';
}
var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
if (style !== '') {
html += 'style="' + style + '" ';
}
html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
return html;
}
K.formatUrl = _formatUrl;
K.formatHtml = _formatHtml;
K.getCssList = _getCssList;
K.getAttrList = _getAttrList;
K.mediaType = _mediaType;
K.mediaAttrs = _mediaAttrs;
K.mediaEmbed = _mediaEmbed;
K.mediaImg = _mediaImg;
K.clearMsWord = _clearMsWord;
function _contains(nodeA, nodeB) {
if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
return true;
}
while ((nodeB = nodeB.parentNode)) {
if (nodeB == nodeA) {
return true;
}
}
return false;
}
function _getAttr(el, key) {
key = key.toLowerCase();
var val = null;
if (_IE && _V < 8 && el.nodeName.toLowerCase() != 'script') {
var div = el.ownerDocument.createElement('div');
div.appendChild(el.cloneNode(false));
var list = _getAttrList(_unescape(div.innerHTML));
if (key in list) {
val = list[key];
}
} else {
try {
val = el.getAttribute(key, 2);
} catch(e) {
val = el.getAttribute(key, 1);
}
}
if (key === 'style' && val !== null) {
val = _formatCss(val);
}
return val;
}
function _queryAll(expr, root) {
var exprList = expr.split(',');
if (exprList.length > 1) {
var mergedResults = [];
_each(exprList, function() {
_each(_queryAll(this, root), function() {
if (_inArray(this, mergedResults) < 0) {
mergedResults.push(this);
}
});
});
return mergedResults;
}
root = root || document;
function escape(str) {
if (typeof str != 'string') {
return str;
}
return str.replace(/([^\w\-])/g, '\\$1');
}
function stripslashes(str) {
return str.replace(/\\/g, '');
}
function cmpTag(tagA, tagB) {
return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
}
function byId(id, tag, root) {
var arr = [],
doc = root.ownerDocument || root,
el = doc.getElementById(stripslashes(id));
if (el) {
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
arr.push(el);
}
}
return arr;
}
function byClass(className, tag, root) {
var doc = root.ownerDocument || root, arr = [], els, i, len, el;
if (root.getElementsByClassName) {
els = root.getElementsByClassName(stripslashes(className));
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName)) {
arr.push(el);
}
}
} else if (doc.querySelectorAll) {
els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (_contains(root, el)) {
arr.push(el);
}
}
} else {
els = root.getElementsByTagName(tag);
className = ' ' + className + ' ';
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
var cls = el.className;
if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
arr.push(el);
}
}
}
}
return arr;
}
function byName(name, tag, root) {
var arr = [], doc = root.ownerDocument || root,
els = doc.getElementsByName(stripslashes(name)), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
if (el.getAttributeNode('name')) {
arr.push(el);
}
}
}
return arr;
}
function byAttr(key, val, tag, root) {
var arr = [], els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
if (val === null) {
if (_getAttr(el, key) !== null) {
arr.push(el);
}
} else {
if (val === escape(_getAttr(el, key))) {
arr.push(el);
}
}
}
}
return arr;
}
function select(expr, root) {
var arr = [], matches;
matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
var tag = matches ? matches[1] : '*';
if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byId(matches[1], tag, root);
} else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
arr = byClass(matches[1], tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
arr = byAttr(matches[1].toLowerCase(), null, tag, root);
} else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
var key = matches[1].toLowerCase(), val = matches[2];
if (key === 'id') {
arr = byId(val, tag, root);
} else if (key === 'class') {
arr = byClass(val, tag, root);
} else if (key === 'name') {
arr = byName(val, tag, root);
} else {
arr = byAttr(key, val, tag, root);
}
} else {
var els = root.getElementsByTagName(tag), el;
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
if (el.nodeType == 1) {
arr.push(el);
}
}
}
return arr;
}
var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
while ((arr = re.exec(expr))) {
if (arr[1] !== ' ') {
parts.push(arr[1]);
}
}
var results = [];
if (parts.length == 1) {
return select(parts[0], root);
}
var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
for (i = 0, lenth = parts.length; i < lenth; i++) {
part = parts[i];
if (part === '>') {
isChild = true;
continue;
}
if (i > 0) {
els = [];
for (j = 0, len = results.length; j < len; j++) {
val = results[j];
subResults = select(part, val);
for (k = 0, l = subResults.length; k < l; k++) {
v = subResults[k];
if (isChild) {
if (val === v.parentNode) {
els.push(v);
}
} else {
els.push(v);
}
}
}
results = els;
} else {
results = select(part, root);
}
if (results.length === 0) {
return [];
}
}
return results;
}
function _query(expr, root) {
var arr = _queryAll(expr, root);
return arr.length > 0 ? arr[0] : null;
}
K.query = _query;
K.queryAll = _queryAll;
function _get(val) {
return K(val)[0];
}
function _getDoc(node) {
if (!node) {
return document;
}
return node.ownerDocument || node.document || node;
}
function _getWin(node) {
if (!node) {
return window;
}
var doc = _getDoc(node);
return doc.parentWindow || doc.defaultView;
}
function _setHtml(el, html) {
if (el.nodeType != 1) {
return;
}
var doc = _getDoc(el);
try {
el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
var temp = doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
} catch(e) {
K(el).empty();
K('@' + html, doc).each(function() {
el.appendChild(this);
});
}
}
function _hasClass(el, cls) {
return _inString(cls, el.className, ' ');
}
function _setAttr(el, key, val) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
el.setAttribute(key, '' + val);
}
function _removeAttr(el, key) {
if (_IE && _V < 8 && key.toLowerCase() == 'class') {
key = 'className';
}
_setAttr(el, key, '');
el.removeAttribute(key);
}
function _getNodeName(node) {
if (!node || !node.nodeName) {
return '';
}
return node.nodeName.toLowerCase();
}
function _computedCss(el, key) {
var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
if (win.getComputedStyle) {
var style = win.getComputedStyle(el, null);
val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
} else if (el.currentStyle) {
val = el.currentStyle[camelKey] || el.style[camelKey];
}
return val;
}
function _hasVal(node) {
return !!_VALUE_TAG_MAP[_getNodeName(node)];
}
function _docElement(doc) {
doc = doc || document;
return _QUIRKS ? doc.body : doc.documentElement;
}
function _docHeight(doc) {
var el = _docElement(doc);
return Math.max(el.scrollHeight, el.clientHeight);
}
function _docWidth(doc) {
var el = _docElement(doc);
return Math.max(el.scrollWidth, el.clientWidth);
}
function _getScrollPos(doc) {
doc = doc || document;
var x, y;
if (_IE || _OPERA) {
x = _docElement(doc).scrollLeft;
y = _docElement(doc).scrollTop;
} else {
x = _getWin(doc).scrollX;
y = _getWin(doc).scrollY;
}
return {x : x, y : y};
}
function KNode(node) {
this.init(node);
}
_extend(KNode, {
init : function(node) {
var self = this;
for (var i = 0, len = node.length; i < len; i++) {
self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
}
self.length = node.length;
self.doc = _getDoc(self[0]);
self.name = _getNodeName(self[0]);
self.type = self.length > 0 ? self[0].nodeType : null;
self.win = _getWin(self[0]);
self._data = {};
},
each : function(fn) {
var self = this;
for (var i = 0; i < self.length; i++) {
if (fn.call(self[i], i, self[i]) === false) {
return self;
}
}
return self;
},
bind : function(type, fn) {
this.each(function() {
_bind(this, type, fn);
});
return this;
},
unbind : function(type, fn) {
this.each(function() {
_unbind(this, type, fn);
});
return this;
},
fire : function(type) {
if (this.length < 1) {
return this;
}
_fire(this[0], type);
return this;
},
hasAttr : function(key) {
if (this.length < 1) {
return false;
}
return !!_getAttr(this[0], key);
},
attr : function(key, val) {
var self = this;
if (key === undefined) {
return _getAttrList(self.outer());
}
if (typeof key === 'object') {
_each(key, function(k, v) {
self.attr(k, v);
});
return self;
}
if (val === undefined) {
val = self.length < 1 ? null : _getAttr(self[0], key);
return val === null ? '' : val;
}
self.each(function() {
_setAttr(this, key, val);
});
return self;
},
removeAttr : function(key) {
this.each(function() {
_removeAttr(this, key);
});
return this;
},
get : function(i) {
if (this.length < 1) {
return null;
}
return this[i || 0];
},
hasClass : function(cls) {
if (this.length < 1) {
return false;
}
return _hasClass(this[0], cls);
},
addClass : function(cls) {
this.each(function() {
if (!_hasClass(this, cls)) {
this.className = _trim(this.className + ' ' + cls);
}
});
return this;
},
removeClass : function(cls) {
this.each(function() {
if (_hasClass(this, cls)) {
this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
}
});
return this;
},
html : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1 || self.type != 1) {
return '';
}
return _formatHtml(self[0].innerHTML);
}
self.each(function() {
_setHtml(this, val);
});
return self;
},
text : function() {
var self = this;
if (self.length < 1) {
return '';
}
return _IE ? self[0].innerText : self[0].textContent;
},
hasVal : function() {
if (this.length < 1) {
return false;
}
return _hasVal(this[0]);
},
val : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self.hasVal() ? self[0].value : self.attr('value');
} else {
self.each(function() {
if (_hasVal(this)) {
this.value = val;
} else {
_setAttr(this, 'value' , val);
}
});
return self;
}
},
css : function(key, val) {
var self = this;
if (key === undefined) {
return _getCssList(self.attr('style'));
}
if (typeof key === 'object') {
_each(key, function(k, v) {
self.css(k, v);
});
return self;
}
if (val === undefined) {
if (self.length < 1) {
return '';
}
return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
}
self.each(function() {
this.style[_toCamel(key)] = val;
});
return self;
},
width : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetWidth;
}
return self.css('width', _addUnit(val));
},
height : function(val) {
var self = this;
if (val === undefined) {
if (self.length < 1) {
return 0;
}
return self[0].offsetHeight;
}
return self.css('height', _addUnit(val));
},
opacity : function(val) {
this.each(function() {
if (this.style.opacity === undefined) {
this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
} else {
this.style.opacity = val == 1 ? '' : val;
}
});
return this;
},
data : function(key, val) {
var self = this;
if (val === undefined) {
return self._data[key];
}
self._data[key] = val;
return self;
},
pos : function() {
var self = this, node = self[0], x = 0, y = 0;
if (node) {
if (node.getBoundingClientRect) {
var box = node.getBoundingClientRect(),
pos = _getScrollPos(self.doc);
x = box.left + pos.x;
y = box.top + pos.y;
} else {
while (node) {
x += node.offsetLeft;
y += node.offsetTop;
node = node.offsetParent;
}
}
}
return {x : _round(x), y : _round(y)};
},
clone : function(bool) {
if (this.length < 1) {
return new KNode([]);
}
return new KNode([this[0].cloneNode(bool)]);
},
append : function(expr) {
this.each(function() {
if (this.appendChild) {
this.appendChild(_get(expr));
}
});
return this;
},
appendTo : function(expr) {
this.each(function() {
_get(expr).appendChild(this);
});
return this;
},
before : function(expr) {
this.each(function() {
this.parentNode.insertBefore(_get(expr), this);
});
return this;
},
after : function(expr) {
this.each(function() {
if (this.nextSibling) {
this.parentNode.insertBefore(_get(expr), this.nextSibling);
} else {
this.parentNode.appendChild(_get(expr));
}
});
return this;
},
replaceWith : function(expr) {
var nodes = [];
this.each(function(i, node) {
_unbind(node);
var newNode = _get(expr);
node.parentNode.replaceChild(newNode, node);
nodes.push(newNode);
});
return K(nodes);
},
empty : function() {
var self = this;
self.each(function(i, node) {
var child = node.firstChild;
while (child) {
if (!node.parentNode) {
return;
}
var next = child.nextSibling;
child.parentNode.removeChild(child);
child = next;
}
});
return self;
},
remove : function(keepChilds) {
var self = this;
self.each(function(i, node) {
if (!node.parentNode) {
return;
}
_unbind(node);
if (keepChilds) {
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
node.parentNode.insertBefore(child, node);
child = next;
}
}
node.parentNode.removeChild(node);
delete self[i];
});
self.length = 0;
self._data = {};
return self;
},
show : function(val) {
return this.css('display', val === undefined ? 'block' : val);
},
hide : function() {
return this.css('display', 'none');
},
outer : function() {
var self = this;
if (self.length < 1) {
return '';
}
var div = self.doc.createElement('div'), html;
div.appendChild(self[0].cloneNode(true));
html = _formatHtml(div.innerHTML);
div = null;
return html;
},
isSingle : function() {
return !!_SINGLE_TAG_MAP[this.name];
},
isInline : function() {
return !!_INLINE_TAG_MAP[this.name];
},
isBlock : function() {
return !!_BLOCK_TAG_MAP[this.name];
},
isStyle : function() {
return !!_STYLE_TAG_MAP[this.name];
},
isControl : function() {
return !!_CONTROL_TAG_MAP[this.name];
},
contains : function(otherNode) {
if (this.length < 1) {
return false;
}
return _contains(this[0], _get(otherNode));
},
parent : function() {
if (this.length < 1) {
return null;
}
var node = this[0].parentNode;
return node ? new KNode([node]) : null;
},
children : function() {
if (this.length < 1) {
return [];
}
var list = [], child = this[0].firstChild;
while (child) {
if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
list.push(new KNode([child]));
}
child = child.nextSibling;
}
return list;
},
first : function() {
var list = this.children();
return list.length > 0 ? list[0] : null;
},
last : function() {
var list = this.children();
return list.length > 0 ? list[list.length - 1] : null;
},
index : function() {
if (this.length < 1) {
return -1;
}
var i = -1, sibling = this[0];
while (sibling) {
i++;
sibling = sibling.previousSibling;
}
return i;
},
prev : function() {
if (this.length < 1) {
return null;
}
var node = this[0].previousSibling;
return node ? new KNode([node]) : null;
},
next : function() {
if (this.length < 1) {
return null;
}
var node = this[0].nextSibling;
return node ? new KNode([node]) : null;
},
scan : function(fn, order) {
if (this.length < 1) {
return;
}
order = (order === undefined) ? true : order;
function walk(node) {
var n = order ? node.firstChild : node.lastChild;
while (n) {
var next = order ? n.nextSibling : n.previousSibling;
if (fn(n) === false) {
return false;
}
if (walk(n) === false) {
return false;
}
n = next;
}
}
walk(this[0]);
return this;
}
});
_each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
KNode.prototype[type] = function(fn) {
return fn ? this.bind(type, fn) : this.fire(type);
};
});
var _K = K;
K = function(expr, root) {
if (expr === undefined || expr === null) {
return;
}
function newNode(node) {
if (!node[0]) {
node = [];
}
return new KNode(node);
}
if (typeof expr === 'string') {
if (root) {
root = _get(root);
}
var length = expr.length;
if (expr.charAt(0) === '@') {
expr = expr.substr(1);
}
if (expr.length !== length || /<.+>/.test(expr)) {
var doc = root ? root.ownerDocument || root : document,
div = doc.createElement('div'), list = [];
div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
for (var i = 0, len = div.childNodes.length; i < len; i++) {
var child = div.childNodes[i];
if (child.id == '__kindeditor_temp_tag__') {
continue;
}
list.push(child);
}
return newNode(list);
}
return newNode(_queryAll(expr, root));
}
if (expr && expr.constructor === KNode) {
return expr;
}
if (_isArray(expr)) {
return newNode(expr);
}
return newNode(_toArray(arguments));
};
_each(_K, function(key, val) {
K[key] = val;
});
window.KindEditor = K;
var _START_TO_START = 0,
_START_TO_END = 1,
_END_TO_END = 2,
_END_TO_START = 3,
_BOOKMARK_ID = 0;
function _updateCollapsed(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
return range;
}
function _copyAndDelete(range, isCopy, isDelete) {
var doc = range.doc, nodeList = [];
function splitTextNode(node, startOffset, endOffset) {
var length = node.nodeValue.length, centerNode;
if (isCopy) {
var cloneNode = node.cloneNode(true);
if (startOffset > 0) {
centerNode = cloneNode.splitText(startOffset);
} else {
centerNode = cloneNode;
}
if (endOffset < length) {
centerNode.splitText(endOffset - startOffset);
}
}
if (isDelete) {
var center = node;
if (startOffset > 0) {
center = node.splitText(startOffset);
range.setStart(node, startOffset);
}
if (endOffset < length) {
var right = center.splitText(endOffset - startOffset);
range.setEnd(right, 0);
}
nodeList.push(center);
}
return centerNode;
}
function removeNodes() {
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
}
var copyRange = range.cloneRange().down();
var start = -1, incStart = -1, incEnd = -1, end = -1,
ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
if (ancestor.nodeType == 3) {
var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
if (isCopy) {
frag.appendChild(textNode);
}
removeNodes();
return isCopy ? frag : range;
}
function extractNodes(parent, frag) {
var node = parent.firstChild, nextNode;
while (node) {
var testRange = new KRange(doc).selectNode(node);
start = testRange.compareBoundaryPoints(_START_TO_END, range);
if (start >= 0 && incStart <= 0) {
incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
}
if (incStart >= 0 && incEnd <= 0) {
incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
}
if (incEnd >= 0 && end <= 0) {
end = testRange.compareBoundaryPoints(_END_TO_START, range);
}
if (end >= 0) {
return false;
}
nextNode = node.nextSibling;
if (start > 0) {
if (node.nodeType == 1) {
if (incStart >= 0 && incEnd <= 0) {
if (isCopy) {
frag.appendChild(node.cloneNode(true));
}
if (isDelete) {
nodeList.push(node);
}
} else {
var childFlag;
if (isCopy) {
childFlag = node.cloneNode(false);
frag.appendChild(childFlag);
}
if (extractNodes(node, childFlag) === false) {
return false;
}
}
} else if (node.nodeType == 3) {
var textNode;
if (node == copyRange.startContainer) {
textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
} else if (node == copyRange.endContainer) {
textNode = splitTextNode(node, 0, copyRange.endOffset);
} else {
textNode = splitTextNode(node, 0, node.nodeValue.length);
}
if (isCopy) {
try {
frag.appendChild(textNode);
} catch(e) {}
}
}
}
node = nextNode;
}
}
extractNodes(ancestor, frag);
if (isDelete) {
range.up().collapse(true);
}
for (var i = 0, len = nodeList.length; i < len; i++) {
var node = nodeList[i];
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
return isCopy ? frag : range;
}
function _moveToElementText(range, el) {
var node = el;
while (node) {
var knode = K(node);
if (knode.name == 'marquee' || knode.name == 'select') {
return;
}
node = node.parentNode;
}
try {
range.moveToElementText(el);
} catch(e) {}
}
function _getStartEnd(rng, isStart) {
var doc = rng.parentElement().ownerDocument,
pointRange = rng.duplicate();
pointRange.collapse(isStart);
var parent = pointRange.parentElement(),
nodes = parent.childNodes;
if (nodes.length === 0) {
return {node: parent.parentNode, offset: K(parent).index()};
}
var startNode = doc, startPos = 0, cmp = -1;
var testRange = rng.duplicate();
_moveToElementText(testRange, parent);
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
cmp = testRange.compareEndPoints('StartToStart', pointRange);
if (cmp === 0) {
return {node: node.parentNode, offset: i};
}
if (node.nodeType == 1) {
var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
if (knode.isControl()) {
dummy = doc.createElement('span');
knode.after(dummy);
newNode = dummy;
startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
}
_moveToElementText(nodeRange, newNode);
testRange.setEndPoint('StartToEnd', nodeRange);
if (cmp > 0) {
startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
} else {
startPos = 0;
}
if (dummy) {
K(dummy).remove();
}
} else if (node.nodeType == 3) {
testRange.moveStart('character', node.nodeValue.length);
startPos += node.nodeValue.length;
}
if (cmp < 0) {
startNode = node;
}
}
if (cmp < 0 && startNode.nodeType == 1) {
return {node: parent, offset: K(parent.lastChild).index() + 1};
}
if (cmp > 0) {
while (startNode.nextSibling && startNode.nodeType == 1) {
startNode = startNode.nextSibling;
}
}
testRange = rng.duplicate();
_moveToElementText(testRange, parent);
testRange.setEndPoint('StartToEnd', pointRange);
startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
if (cmp > 0 && startNode.nodeType == 3) {
var prevNode = startNode.previousSibling;
while (prevNode && prevNode.nodeType == 3) {
startPos -= prevNode.nodeValue.length;
prevNode = prevNode.previousSibling;
}
}
return {node: startNode, offset: startPos};
}
function _getEndRange(node, offset) {
var doc = node.ownerDocument || node,
range = doc.body.createTextRange();
if (doc == node) {
range.collapse(true);
return range;
}
if (node.nodeType == 1 && node.childNodes.length > 0) {
var children = node.childNodes, isStart, child;
if (offset === 0) {
child = children[0];
isStart = true;
} else {
child = children[offset - 1];
isStart = false;
}
if (!child) {
return range;
}
if (K(child).name === 'head') {
if (offset === 1) {
isStart = true;
}
if (offset === 2) {
isStart = false;
}
range.collapse(isStart);
return range;
}
if (child.nodeType == 1) {
var kchild = K(child), span;
if (kchild.isControl()) {
span = doc.createElement('span');
if (isStart) {
kchild.before(span);
} else {
kchild.after(span);
}
child = span;
}
_moveToElementText(range, child);
range.collapse(isStart);
if (span) {
K(span).remove();
}
return range;
}
node = child;
offset = isStart ? 0 : child.nodeValue.length;
}
var dummy = doc.createElement('span');
K(node).before(dummy);
_moveToElementText(range, dummy);
range.moveStart('character', offset);
K(dummy).remove();
return range;
}
function _toRange(rng) {
var doc, range;
function tr2td(start) {
if (K(start.node).name == 'tr') {
start.node = start.node.cells[start.offset];
start.offset = 0;
}
}
if (_IE) {
if (rng.item) {
doc = _getDoc(rng.item(0));
range = new KRange(doc);
range.selectNode(rng.item(0));
return range;
}
doc = rng.parentElement().ownerDocument;
var start = _getStartEnd(rng, true),
end = _getStartEnd(rng, false);
tr2td(start);
tr2td(end);
range = new KRange(doc);
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
return range;
}
var startContainer = rng.startContainer;
doc = startContainer.ownerDocument || startContainer;
range = new KRange(doc);
range.setStart(startContainer, rng.startOffset);
range.setEnd(rng.endContainer, rng.endOffset);
return range;
}
function KRange(doc) {
this.init(doc);
}
_extend(KRange, {
init : function(doc) {
var self = this;
self.startContainer = doc;
self.startOffset = 0;
self.endContainer = doc;
self.endOffset = 0;
self.collapsed = true;
self.doc = doc;
},
commonAncestor : function() {
function getParents(node) {
var parents = [];
while (node) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
var parentsA = getParents(this.startContainer),
parentsB = getParents(this.endContainer),
i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
while (++i) {
parentA = parentsA[lenA - i];
parentB = parentsB[lenB - i];
if (!parentA || !parentB || parentA !== parentB) {
break;
}
}
return parentsA[lenA - i + 1];
},
setStart : function(node, offset) {
var self = this, doc = self.doc;
self.startContainer = node;
self.startOffset = offset;
if (self.endContainer === doc) {
self.endContainer = node;
self.endOffset = offset;
}
return _updateCollapsed(this);
},
setEnd : function(node, offset) {
var self = this, doc = self.doc;
self.endContainer = node;
self.endOffset = offset;
if (self.startContainer === doc) {
self.startContainer = node;
self.startOffset = offset;
}
return _updateCollapsed(this);
},
setStartBefore : function(node) {
return this.setStart(node.parentNode || this.doc, K(node).index());
},
setStartAfter : function(node) {
return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
},
setEndBefore : function(node) {
return this.setEnd(node.parentNode || this.doc, K(node).index());
},
setEndAfter : function(node) {
return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
},
selectNode : function(node) {
return this.setStartBefore(node).setEndAfter(node);
},
selectNodeContents : function(node) {
var knode = K(node);
if (knode.type == 3 || knode.isSingle()) {
return this.selectNode(node);
}
var children = knode.children();
if (children.length > 0) {
return this.setStartBefore(children[0][0]).setEndAfter(children[children.length - 1][0]);
}
return this.setStart(node, 0).setEnd(node, 0);
},
collapse : function(toStart) {
if (toStart) {
return this.setEnd(this.startContainer, this.startOffset);
}
return this.setStart(this.endContainer, this.endOffset);
},
compareBoundaryPoints : function(how, range) {
var rangeA = this.get(), rangeB = range.get();
if (_IE) {
var arr = {};
arr[_START_TO_START] = 'StartToStart';
arr[_START_TO_END] = 'EndToStart';
arr[_END_TO_END] = 'EndToEnd';
arr[_END_TO_START] = 'StartToEnd';
var cmp = rangeA.compareEndPoints(arr[how], rangeB);
if (cmp !== 0) {
return cmp;
}
var nodeA, nodeB, nodeC, posA, posB;
if (how === _START_TO_START || how === _END_TO_START) {
nodeA = this.startContainer;
posA = this.startOffset;
}
if (how === _START_TO_END || how === _END_TO_END) {
nodeA = this.endContainer;
posA = this.endOffset;
}
if (how === _START_TO_START || how === _START_TO_END) {
nodeB = range.startContainer;
posB = range.startOffset;
}
if (how === _END_TO_END || how === _END_TO_START) {
nodeB = range.endContainer;
posB = range.endOffset;
}
if (nodeA === nodeB) {
var diff = posA - posB;
return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
}
nodeC = nodeB;
while (nodeC && nodeC.parentNode !== nodeA) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posA ? -1 : 1;
}
nodeC = nodeA;
while (nodeC && nodeC.parentNode !== nodeB) {
nodeC = nodeC.parentNode;
}
if (nodeC) {
return K(nodeC).index() >= posB ? 1 : -1;
}
nodeC = K(nodeB).next();
if (nodeC && nodeC.contains(nodeA)) {
return 1;
}
nodeC = K(nodeA).next();
if (nodeC && nodeC.contains(nodeB)) {
return -1;
}
} else {
return rangeA.compareBoundaryPoints(how, rangeB);
}
},
cloneRange : function() {
return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
},
toString : function() {
var rng = this.get(), str = _IE ? rng.text : rng.toString();
return str.replace(/\r\n|\n|\r/g, '');
},
cloneContents : function() {
return _copyAndDelete(this, true, false);
},
deleteContents : function() {
return _copyAndDelete(this, false, true);
},
extractContents : function() {
return _copyAndDelete(this, true, true);
},
insertNode : function(node) {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset,
firstChild, lastChild, c, nodeCount = 1;
if (node.nodeName.toLowerCase() === '#document-fragment') {
firstChild = node.firstChild;
lastChild = node.lastChild;
nodeCount = node.childNodes.length;
}
if (sc.nodeType == 1) {
c = sc.childNodes[so];
if (c) {
sc.insertBefore(node, c);
if (sc === ec) {
eo += nodeCount;
}
} else {
sc.appendChild(node);
}
} else if (sc.nodeType == 3) {
if (so === 0) {
sc.parentNode.insertBefore(node, sc);
if (sc.parentNode === ec) {
eo += nodeCount;
}
} else if (so >= sc.nodeValue.length) {
if (sc.nextSibling) {
sc.parentNode.insertBefore(node, sc.nextSibling);
} else {
sc.parentNode.appendChild(node);
}
} else {
if (so > 0) {
c = sc.splitText(so);
} else {
c = sc;
}
sc.parentNode.insertBefore(node, c);
if (sc === ec) {
ec = c;
eo -= so;
}
}
}
if (firstChild) {
self.setStartBefore(firstChild).setEndAfter(lastChild);
} else {
self.selectNode(node);
}
if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
return self;
}
return self.setEnd(ec, eo);
},
surroundContents : function(node) {
node.appendChild(this.extractContents());
return this.insertNode(node).selectNode(node);
},
isControl : function() {
var self = this,
sc = self.startContainer, so = self.startOffset,
ec = self.endContainer, eo = self.endOffset, rng;
return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
},
get : function(hasControlRange) {
var self = this, doc = self.doc, node, rng;
if (!_IE) {
rng = doc.createRange();
try {
rng.setStart(self.startContainer, self.startOffset);
rng.setEnd(self.endContainer, self.endOffset);
} catch (e) {}
return rng;
}
if (hasControlRange && self.isControl()) {
rng = doc.body.createControlRange();
rng.addElement(self.startContainer.childNodes[self.startOffset]);
return rng;
}
var range = self.cloneRange().down();
rng = doc.body.createTextRange();
rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
return rng;
},
html : function() {
return K(this.cloneContents()).outer();
},
down : function() {
var self = this;
function downPos(node, pos, isStart) {
if (node.nodeType != 1) {
return;
}
var children = K(node).children();
if (children.length === 0) {
return;
}
var left, right, child, offset;
if (pos > 0) {
left = children[pos - 1];
}
if (pos < children.length) {
right = children[pos];
}
if (left && left.type == 3) {
child = left[0];
offset = child.nodeValue.length;
}
if (right && right.type == 3) {
child = right[0];
offset = 0;
}
if (!child) {
return;
}
if (isStart) {
self.setStart(child, offset);
} else {
self.setEnd(child, offset);
}
}
downPos(self.startContainer, self.startOffset, true);
downPos(self.endContainer, self.endOffset, false);
return self;
},
up : function() {
var self = this;
function upPos(node, pos, isStart) {
if (node.nodeType != 3) {
return;
}
if (pos === 0) {
if (isStart) {
self.setStartBefore(node);
} else {
self.setEndBefore(node);
}
} else if (pos == node.nodeValue.length) {
if (isStart) {
self.setStartAfter(node);
} else {
self.setEndAfter(node);
}
}
}
upPos(self.startContainer, self.startOffset, true);
upPos(self.endContainer, self.endOffset, false);
return self;
},
enlarge : function(toBlock) {
var self = this;
self.up();
function enlargePos(node, pos, isStart) {
var knode = K(node), parent;
if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
return;
}
if (pos === 0) {
while (!knode.prev()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartBefore(knode[0]);
} else {
self.setEndBefore(knode[0]);
}
} else if (pos == knode.children().length) {
while (!knode.next()) {
parent = knode.parent();
if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
break;
}
knode = parent;
}
if (isStart) {
self.setStartAfter(knode[0]);
} else {
self.setEndAfter(knode[0]);
}
}
}
enlargePos(self.startContainer, self.startOffset, true);
enlargePos(self.endContainer, self.endOffset, false);
return self;
},
shrink : function() {
var self = this, child, collapsed = self.collapsed;
while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setStart(child, 0);
}
if (collapsed) {
return self.collapse(collapsed);
}
while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
self.setEnd(child, child.childNodes.length);
}
return self;
},
createBookmark : function(serialize) {
var self = this, doc = self.doc, endNode,
startNode = K('<span style="display:none;"></span>', doc)[0];
startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
if (!self.collapsed) {
endNode = startNode.cloneNode(true);
endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
}
if (endNode) {
self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
}
self.insertNode(startNode).setStartAfter(startNode);
return {
start : serialize ? '#' + startNode.id : startNode,
end : endNode ? (serialize ? '#' + endNode.id : endNode) : null
};
},
moveToBookmark : function(bookmark) {
var self = this, doc = self.doc,
start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
if (!start || start.length < 1) {
return self;
}
self.setStartBefore(start[0]);
start.remove();
if (end && end.length > 0) {
self.setEndBefore(end[0]);
end.remove();
} else {
self.collapse(true);
}
return self;
},
dump : function() {
console.log('--------------------');
console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
}
});
function _range(mixed) {
if (!mixed.nodeName) {
return mixed.constructor === KRange ? mixed : _toRange(mixed);
}
return new KRange(mixed);
}
K.range = _range;
K.START_TO_START = _START_TO_START;
K.START_TO_END = _START_TO_END;
K.END_TO_END = _END_TO_END;
K.END_TO_START = _END_TO_START;
function _nativeCommand(doc, key, val) {
try {
doc.execCommand(key, false, val);
} catch(e) {}
}
function _nativeCommandValue(doc, key) {
var val = '';
try {
val = doc.queryCommandValue(key);
} catch (e) {}
if (typeof val !== 'string') {
val = '';
}
return val;
}
function _getSel(doc) {
var win = _getWin(doc);
return doc.selection || win.getSelection();
}
function _getRng(doc) {
var sel = _getSel(doc), rng;
try {
if (sel.rangeCount > 0) {
rng = sel.getRangeAt(0);
} else {
rng = sel.createRange();
}
} catch(e) {}
if (_IE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
return null;
}
return rng;
}
function _singleKeyMap(map) {
var newMap = {}, arr, v;
_each(map, function(key, val) {
arr = key.split(',');
for (var i = 0, len = arr.length; i < len; i++) {
v = arr[i];
newMap[v] = val;
}
});
return newMap;
}
function _hasAttrOrCss(knode, map) {
return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
}
function _hasAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return false;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return false;
}
var arr = newMap[mapKey].split(',');
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
return true;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
var method = match[1] ? 'css' : 'attr';
key = match[2];
var val = match[3] || '';
if (val === '' && knode[method](key) !== '') {
return true;
}
if (val !== '' && knode[method](key) === val) {
return true;
}
}
return false;
}
function _removeAttrOrCss(knode, map) {
if (knode.type != 1) {
return;
}
_removeAttrOrCssByKey(knode, map, '*');
_removeAttrOrCssByKey(knode, map);
}
function _removeAttrOrCssByKey(knode, map, mapKey) {
mapKey = mapKey || knode.name;
if (knode.type !== 1) {
return;
}
var newMap = _singleKeyMap(map);
if (!newMap[mapKey]) {
return;
}
var arr = newMap[mapKey].split(','), allFlag = false;
for (var i = 0, len = arr.length; i < len; i++) {
var key = arr[i];
if (key === '*') {
allFlag = true;
break;
}
var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
key = match[2];
if (match[1]) {
key = _toCamel(key);
if (knode[0].style[key]) {
knode[0].style[key] = '';
}
} else {
knode.removeAttr(key);
}
}
if (allFlag) {
knode.remove(true);
}
}
function _getInnerNode(knode) {
var inner = knode;
while (inner.first()) {
inner = inner.first();
}
return inner;
}
function _isEmptyNode(knode) {
return knode.type == 1 && knode.html().replace(/<[^>]+>/g, '') === '';
}
function _mergeWrapper(a, b) {
a = a.clone(true);
var lastA = _getInnerNode(a), childA = a, merged = false;
while (b) {
while (childA) {
if (childA.name === b.name) {
_mergeAttrs(childA, b.attr(), b.css());
merged = true;
}
childA = childA.first();
}
if (!merged) {
lastA.append(b.clone(false));
}
merged = false;
b = b.first();
}
return a;
}
function _wrapNode(knode, wrapper) {
wrapper = wrapper.clone(true);
if (knode.type == 3) {
_getInnerNode(wrapper).append(knode.clone(false));
knode.replaceWith(wrapper);
return wrapper;
}
var nodeWrapper = knode, child;
while ((child = knode.first()) && child.children().length == 1) {
knode = child;
}
child = knode.first();
var frag = knode.doc.createDocumentFragment();
while (child) {
frag.appendChild(child[0]);
child = child.next();
}
wrapper = _mergeWrapper(nodeWrapper, wrapper);
if (frag.firstChild) {
_getInnerNode(wrapper).append(frag);
}
nodeWrapper.replaceWith(wrapper);
return wrapper;
}
function _mergeAttrs(knode, attrs, styles) {
_each(attrs, function(key, val) {
if (key !== 'style') {
knode.attr(key, val);
}
});
_each(styles, function(key, val) {
knode.css(key, val);
});
}
function _inPreElement(knode) {
while (knode && knode.name != 'body') {
if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
return true;
}
knode = knode.parent();
}
return false;
}
function KCmd(range) {
this.init(range);
}
_extend(KCmd, {
init : function(range) {
var self = this, doc = range.doc;
self.doc = doc;
self.win = _getWin(doc);
self.sel = _getSel(doc);
self.range = range;
},
selection : function(forceReset) {
var self = this, doc = self.doc, rng = _getRng(doc);
self.sel = _getSel(doc);
if (rng) {
self.range = _range(rng);
if (K(self.range.startContainer).name == 'html') {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
}
if (forceReset) {
self.range.selectNodeContents(doc.body).collapse(false);
}
return self;
},
select : function(hasDummy) {
hasDummy = _undef(hasDummy, true);
var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
if (hasDummy && sc.nodeType == 1 && range.collapsed) {
if (_IE) {
var dummy = K('<span> </span>', doc);
range.insertNode(dummy[0]);
rng = doc.body.createTextRange();
try {
rng.moveToElementText(dummy[0]);
} catch(ex) {}
rng.collapse(false);
rng.select();
dummy.remove();
win.focus();
return self;
}
if (_WEBKIT) {
var children = sc.childNodes;
if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
range.insertNode(doc.createTextNode('\u200B'));
hasU200b = true;
}
}
}
if (_IE) {
try {
rng = range.get(true);
rng.select();
} catch(e) {}
} else {
if (hasU200b) {
range.collapse(false);
}
rng = range.get(true);
sel.removeAllRanges();
sel.addRange(rng);
}
win.focus();
return self;
},
wrap : function(val) {
var self = this, doc = self.doc, range = self.range, wrapper;
wrapper = K(val, doc);
if (range.collapsed) {
range.shrink();
range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
return self;
}
if (wrapper.isBlock()) {
var copyWrapper = wrapper.clone(true), child = copyWrapper;
while (child.first()) {
child = child.first();
}
child.append(range.extractContents());
range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
return self;
}
range.enlarge();
var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
K(ancestor).scan(function(node) {
if (!isStart && node == bookmark.start) {
isStart = true;
return;
}
if (isStart) {
if (node == bookmark.end) {
return false;
}
var knode = K(node);
if (_inPreElement(knode)) {
return;
}
if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
var parent;
while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
knode = parent;
}
_wrapNode(knode, wrapper);
}
}
});
range.moveToBookmark(bookmark);
return self;
},
split : function(isStart, map) {
var range = this.range, doc = range.doc;
var tempRange = range.cloneRange().collapse(isStart);
var node = tempRange.startContainer, pos = tempRange.startOffset,
parent = node.nodeType == 3 ? node.parentNode : node,
needSplit = false, knode;
while (parent && parent.parentNode) {
knode = K(parent);
if (map) {
if (!knode.isStyle()) {
break;
}
if (!_hasAttrOrCss(knode, map)) {
break;
}
} else {
if (_NOSPLIT_TAG_MAP[knode.name]) {
break;
}
}
needSplit = true;
parent = parent.parentNode;
}
if (needSplit) {
var dummy = doc.createElement('span');
range.cloneRange().collapse(!isStart).insertNode(dummy);
if (isStart) {
tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
} else {
tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
}
var frag = tempRange.extractContents(),
first = frag.firstChild, last = frag.lastChild;
if (isStart) {
tempRange.insertNode(frag);
range.setStartAfter(last).setEndBefore(dummy);
} else {
parent.appendChild(frag);
range.setStartBefore(dummy).setEndBefore(first);
}
var dummyParent = dummy.parentNode;
if (dummyParent == range.endContainer) {
var prev = K(dummy).prev(), next = K(dummy).next();
if (prev && next && prev.type == 3 && next.type == 3) {
range.setEnd(prev[0], prev[0].nodeValue.length);
} else if (!isStart) {
range.setEnd(range.endContainer, range.endOffset - 1);
}
}
dummyParent.removeChild(dummy);
}
return this;
},
remove : function(map) {
var self = this, doc = self.doc, range = self.range;
range.enlarge();
if (range.startOffset === 0) {
var ksc = K(range.startContainer), parent;
while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
ksc = parent;
}
range.setStart(ksc[0], 0);
ksc = K(range.startContainer);
if (ksc.isBlock()) {
_removeAttrOrCss(ksc, map);
}
var kscp = ksc.parent();
if (kscp && kscp.isBlock()) {
_removeAttrOrCss(kscp, map);
}
}
var sc, so;
if (range.collapsed) {
self.split(true, map);
sc = range.startContainer;
so = range.startOffset;
if (so > 0) {
var sb = K(sc.childNodes[so - 1]);
if (sb && _isEmptyNode(sb)) {
sb.remove();
range.setStart(sc, so - 1);
}
}
var sa = K(sc.childNodes[so]);
if (sa && _isEmptyNode(sa)) {
sa.remove();
}
if (_isEmptyNode(sc)) {
range.startBefore(sc);
sc.remove();
}
range.collapse(true);
return self;
}
self.split(true, map);
self.split(false, map);
var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
range.cloneRange().collapse(false).insertNode(endDummy);
range.cloneRange().collapse(true).insertNode(startDummy);
var nodeList = [], cmpStart = false;
K(range.commonAncestor()).scan(function(node) {
if (!cmpStart && node == startDummy) {
cmpStart = true;
return;
}
if (node == endDummy) {
return false;
}
if (cmpStart) {
nodeList.push(node);
}
});
K(startDummy).remove();
K(endDummy).remove();
sc = range.startContainer;
so = range.startOffset;
var ec = range.endContainer, eo = range.endOffset;
if (so > 0) {
var startBefore = K(sc.childNodes[so - 1]);
if (startBefore && _isEmptyNode(startBefore)) {
startBefore.remove();
range.setStart(sc, so - 1);
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
var startAfter = K(sc.childNodes[so]);
if (startAfter && _isEmptyNode(startAfter)) {
startAfter.remove();
if (sc == ec) {
range.setEnd(ec, eo - 1);
}
}
}
var endAfter = K(ec.childNodes[range.endOffset]);
if (endAfter && _isEmptyNode(endAfter)) {
endAfter.remove();
}
var bookmark = range.createBookmark(true);
_each(nodeList, function(i, node) {
_removeAttrOrCss(K(node), map);
});
range.moveToBookmark(bookmark);
return self;
},
commonNode : function(map) {
var range = this.range;
var ec = range.endContainer, eo = range.endOffset,
node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
var child = node, parent = node;
while (parent) {
if (_hasAttrOrCss(K(parent), map)) {
return K(parent);
}
parent = parent.parentNode;
}
while (child && (child = child.lastChild)) {
if (_hasAttrOrCss(K(child), map)) {
return K(child);
}
}
return null;
}
var cNode = find(node);
if (cNode) {
return cNode;
}
if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
var prev = K(node).prev();
if (prev) {
return find(prev);
}
}
return null;
},
commonAncestor : function(tagName) {
var range = this.range,
sc = range.startContainer, so = range.startOffset,
ec = range.endContainer, eo = range.endOffset,
startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
function find(node) {
while (node) {
if (node.nodeType == 1) {
if (node.tagName.toLowerCase() === tagName) {
return node;
}
}
node = node.parentNode;
}
return null;
}
var start = find(startNode), end = find(endNode);
if (start && end && start === end) {
return K(start);
}
return null;
},
state : function(key) {
var self = this, doc = self.doc, bool = false;
try {
bool = doc.queryCommandState(key);
} catch (e) {}
return bool;
},
val : function(key) {
var self = this, doc = self.doc, range = self.range;
function lc(val) {
return val.toLowerCase();
}
key = lc(key);
var val = '', knode;
if (key === 'fontfamily' || key === 'fontname') {
val = _nativeCommandValue(doc, 'fontname');
val = val.replace(/['"]/g, '');
return lc(val);
}
if (key === 'formatblock') {
val = _nativeCommandValue(doc, key);
if (val === '') {
knode = self.commonNode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'});
if (knode) {
val = knode.name;
}
}
if (val === 'Normal') {
val = 'p';
}
return lc(val);
}
if (key === 'fontsize') {
knode = self.commonNode({'*' : '.font-size'});
if (knode) {
val = knode.css('font-size');
}
return lc(val);
}
if (key === 'forecolor') {
knode = self.commonNode({'*' : '.color'});
if (knode) {
val = knode.css('color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
if (key === 'hilitecolor') {
knode = self.commonNode({'*' : '.background-color'});
if (knode) {
val = knode.css('background-color');
}
val = _toHex(val);
if (val === '') {
val = 'default';
}
return lc(val);
}
return val;
},
toggle : function(wrapper, map) {
var self = this;
if (self.commonNode(map)) {
self.remove(map);
} else {
self.wrap(wrapper);
}
return self.select();
},
bold : function() {
return this.toggle('<strong></strong>', {
span : '.font-weight=bold',
strong : '*',
b : '*'
});
},
italic : function() {
return this.toggle('<em></em>', {
span : '.font-style=italic',
em : '*',
i : '*'
});
},
underline : function() {
return this.toggle('<u></u>', {
span : '.text-decoration=underline',
u : '*'
});
},
strikethrough : function() {
return this.toggle('<s></s>', {
span : '.text-decoration=line-through',
s : '*'
});
},
forecolor : function(val) {
return this.toggle('<span style="color:' + val + ';"></span>', {
span : '.color=' + val,
font : 'color'
});
},
hilitecolor : function(val) {
return this.toggle('<span style="background-color:' + val + ';"></span>', {
span : '.background-color=' + val
});
},
fontsize : function(val) {
return this.toggle('<span style="font-size:' + val + ';"></span>', {
span : '.font-size=' + val,
font : 'size'
});
},
fontname : function(val) {
return this.fontfamily(val);
},
fontfamily : function(val) {
return this.toggle('<span style="font-family:' + val + ';"></span>', {
span : '.font-family=' + val,
font : 'face'
});
},
removeformat : function() {
var map = {
'*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
},
tags = _STYLE_TAG_MAP;
_each(tags, function(key, val) {
map[key] = '*';
});
this.remove(map);
return this.select();
},
inserthtml : function(val) {
var self = this, range = self.range;
if (val === '') {
return self;
}
if (_inPreElement(K(range.startContainer))) {
return self;
}
function pasteHtml(range, val) {
val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
var rng = range.get();
if (rng.item) {
rng.item(0).outerHTML = val;
} else {
rng.pasteHTML(val);
}
var temp = range.doc.getElementById('__kindeditor_temp_tag__');
temp.parentNode.removeChild(temp);
var newRange = _toRange(rng);
range.setEnd(newRange.endContainer, newRange.endOffset);
range.collapse(false);
self.select(false);
}
function insertHtml(range, val) {
var doc = range.doc,
frag = doc.createDocumentFragment();
K('@' + val, doc).each(function() {
frag.appendChild(this);
});
range.deleteContents();
range.insertNode(frag);
range.collapse(false);
self.select(false);
}
if (_IE) {
try {
pasteHtml(range, val);
} catch(e) {
insertHtml(range, val);
}
return self;
}
insertHtml(range, val);
return self;
},
hr : function() {
return this.inserthtml('<hr />');
},
print : function() {
this.win.print();
return this;
},
insertimage : function(url, title, width, height, border, align) {
title = _undef(title, '');
border = _undef(border, 0);
var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (width) {
html += 'width="' + _escape(width) + '" ';
}
if (height) {
html += 'height="' + _escape(height) + '" ';
}
if (title) {
html += 'title="' + _escape(title) + '" ';
}
if (align) {
html += 'align="' + _escape(align) + '" ';
}
html += 'alt="' + _escape(title) + '" ';
html += '/>';
return this.inserthtml(html);
},
createlink : function(url, type) {
var self = this, doc = self.doc, range = self.range;
self.select();
var a = self.commonNode({ a : '*' });
if (a && !range.isControl()) {
range.selectNode(a.get());
self.select();
}
var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
if (type) {
html += ' target="' + _escape(type) + '"';
}
if (range.collapsed) {
html += '>' + _escape(url) + '</a>';
return self.inserthtml(html);
}
if (range.isControl()) {
var node = K(range.startContainer.childNodes[range.startOffset]);
html += '></a>';
node.after(K(html, doc));
node.next().append(node);
range.selectNode(node[0]);
return self.select();
}
_nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
K(this).attr('href', url).attr('data-ke-src', url);
if (type) {
K(this).attr('target', type);
} else {
K(this).removeAttr('target');
}
});
return self;
},
unlink : function() {
var self = this, doc = self.doc, range = self.range;
self.select();
if (range.collapsed) {
var a = self.commonNode({ a : '*' });
if (a) {
range.selectNode(a.get());
self.select();
}
_nativeCommand(doc, 'unlink', null);
if (_WEBKIT && K(range.startContainer).name === 'img') {
var parent = K(range.startContainer).parent();
if (parent.name === 'a') {
parent.remove(true);
}
}
} else {
_nativeCommand(doc, 'unlink', null);
}
return self;
}
});
_each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
KCmd.prototype[name] = function(val) {
var self = this;
self.select();
_nativeCommand(self.doc, name, val);
if (!_IE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
self.selection();
}
return self;
};
});
_each('cut,copy,paste'.split(','), function(i, name) {
KCmd.prototype[name] = function() {
var self = this;
if (!self.doc.queryCommandSupported(name)) {
throw 'not supported';
}
self.select();
_nativeCommand(self.doc, name, null);
return self;
};
});
function _cmd(mixed) {
if (mixed.nodeName) {
var doc = _getDoc(mixed);
mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
}
return new KCmd(mixed);
}
K.cmd = _cmd;
function _drag(options) {
var moveEl = options.moveEl,
moveFn = options.moveFn,
clickEl = options.clickEl || moveEl,
beforeDrag = options.beforeDrag,
iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
var docs = [document],
poss = [{ x : 0, y : 0}],
listeners = [];
if (iframeFix) {
K('iframe').each(function() {
var doc;
try {
doc = _iframeDoc(this);
K(doc);
} catch(e) {
doc = null;
}
if (doc) {
docs.push(doc);
poss.push(K(this).pos());
}
});
}
clickEl.mousedown(function(e) {
var self = clickEl.get(),
x = _removeUnit(moveEl.css('left')),
y = _removeUnit(moveEl.css('top')),
width = moveEl.width(),
height = moveEl.height(),
pageX = e.pageX,
pageY = e.pageY,
dragging = true;
if (beforeDrag) {
beforeDrag();
}
_each(docs, function(i, doc) {
function moveListener(e) {
if (dragging) {
var diffX = _round(poss[i].x + e.pageX - pageX),
diffY = _round(poss[i].y + e.pageY - pageY);
moveFn.call(clickEl, x, y, width, height, diffX, diffY);
}
e.stop();
}
function selectListener(e) {
e.stop();
}
function upListener(e) {
dragging = false;
if (self.releaseCapture) {
self.releaseCapture();
}
_each(listeners, function() {
K(this.doc).unbind('mousemove', this.move)
.unbind('mouseup', this.up)
.unbind('selectstart', this.select);
});
e.stop();
}
K(doc).mousemove(moveListener)
.mouseup(upListener)
.bind('selectstart', selectListener);
listeners.push({
doc : doc,
move : moveListener,
up : upListener,
select : selectListener
});
});
if (self.setCapture) {
self.setCapture();
}
e.stop();
});
}
function KWidget(options) {
this.init(options);
}
_extend(KWidget, {
init : function(options) {
var self = this;
self.name = options.name || '';
self.doc = options.doc || document;
self.win = _getWin(self.doc);
self.x = _addUnit(options.x);
self.y = _addUnit(options.y);
self.z = options.z;
self.width = _addUnit(options.width);
self.height = _addUnit(options.height);
self.div = K('<div style="display:block;"></div>');
self.options = options;
self._alignEl = options.alignEl;
if (self.width) {
self.div.css('width', self.width);
}
if (self.height) {
self.div.css('height', self.height);
}
if (self.z) {
self.div.css({
position : 'absolute',
left : self.x,
top : self.y,
'z-index' : self.z
});
}
if (self.z && (self.x === undefined || self.y === undefined)) {
self.autoPos(self.width, self.height);
}
if (options.cls) {
self.div.addClass(options.cls);
}
if (options.shadowMode) {
self.div.addClass('ke-shadow');
}
if (options.css) {
self.div.css(options.css);
}
if (options.src) {
K(options.src).replaceWith(self.div);
} else {
K(self.doc.body).append(self.div);
}
if (options.html) {
self.div.html(options.html);
}
if (options.autoScroll) {
if (_IE && _V < 7 || _QUIRKS) {
var scrollPos = _getScrollPos();
K(self.win).bind('scroll', function(e) {
var pos = _getScrollPos(),
diffX = pos.x - scrollPos.x,
diffY = pos.y - scrollPos.y;
self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
});
} else {
self.div.css('position', 'fixed');
}
}
},
pos : function(x, y, updateProp) {
var self = this;
updateProp = _undef(updateProp, true);
if (x !== null) {
x = x < 0 ? 0 : _addUnit(x);
self.div.css('left', x);
if (updateProp) {
self.x = x;
}
}
if (y !== null) {
y = y < 0 ? 0 : _addUnit(y);
self.div.css('top', y);
if (updateProp) {
self.y = y;
}
}
return self;
},
autoPos : function(width, height) {
var self = this,
w = _removeUnit(width) || 0,
h = _removeUnit(height) || 0,
scrollPos = _getScrollPos();
if (self._alignEl) {
var knode = K(self._alignEl),
pos = knode.pos(),
diffX = _round(knode[0].clientWidth / 2 - w / 2),
diffY = _round(knode[0].clientHeight / 2 - h / 2);
x = diffX < 0 ? pos.x : pos.x + diffX;
y = diffY < 0 ? pos.y : pos.y + diffY;
} else {
var docEl = _docElement(self.doc);
x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
}
if (!(_IE && _V < 7 || _QUIRKS)) {
x -= scrollPos.x;
y -= scrollPos.y;
}
return self.pos(x, y);
},
remove : function() {
var self = this;
if (_IE && _V < 7) {
K(self.win).unbind('scroll');
}
self.div.remove();
_each(self, function(i) {
self[i] = null;
});
return this;
},
show : function() {
this.div.show();
return this;
},
hide : function() {
this.div.hide();
return this;
},
draggable : function(options) {
var self = this;
options = options || {};
options.moveEl = self.div;
options.moveFn = function(x, y, width, height, diffX, diffY) {
if ((x = x + diffX) < 0) {
x = 0;
}
if ((y = y + diffY) < 0) {
y = 0;
}
self.pos(x, y);
};
_drag(options);
return self;
}
});
function _widget(options) {
return new KWidget(options);
}
K.WidgetClass = KWidget;
K.widget = _widget;
function _iframeDoc(iframe) {
iframe = _get(iframe);
return iframe.contentDocument || iframe.contentWindow.document;
}
function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
var arr = [
'<html><head><meta charset="utf-8" /><title>KindEditor</title>',
'<style>',
'html {margin:0;padding:0;}',
'body {margin:0;padding:5px;}',
'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
'body, p, div {word-wrap: break-word;}',
'p {margin:5px 0;}',
'table {border-collapse:collapse;}',
'img {border:0;}',
'table.ke-zeroborder td {border:1px dotted #AAA;}',
'img.ke-flash {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/flash.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-rm {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/rm.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-media {',
' border:1px solid #AAA;',
' background-image:url(' + themesPath + 'common/media.gif);',
' background-position:center center;',
' background-repeat:no-repeat;',
' width:100px;',
' height:100px;',
'}',
'img.ke-anchor {',
' border:1px dashed #666;',
' width:16px;',
' height:16px;',
'}',
'.ke-script {',
' display:none;',
' font-size:0;',
' width:0;',
' height:0;',
'}',
'.ke-pagebreak {',
' border:1px dotted #AAA;',
' font-size:0;',
' height:2px;',
'}',
'</style>'
];
if (!_isArray(cssPath)) {
cssPath = [cssPath];
}
_each(cssPath, function(i, path) {
if (path) {
arr.push('<link href="' + path + '" rel="stylesheet" />');
}
});
if (cssData) {
arr.push('<style>' + cssData + '</style>');
}
arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
return arr.join('\n');
}
function _elementVal(knode, val) {
return knode.hasVal() ? knode.val(val) : knode.html(val);
}
function KEdit(options) {
this.init(options);
}
_extend(KEdit, KWidget, {
init : function(options) {
var self = this;
KEdit.parent.init.call(self, options);
self.srcElement = K(options.srcElement);
self.div.addClass('ke-edit');
self.designMode = _undef(options.designMode, true);
self.beforeGetHtml = options.beforeGetHtml;
self.beforeSetHtml = options.beforeSetHtml;
self.afterSetHtml = options.afterSetHtml;
var themesPath = _undef(options.themesPath, ''),
bodyClass = options.bodyClass,
cssPath = options.cssPath,
cssData = options.cssData,
isDocumentDomain = location.host.replace(/:\d+/, '') !== document.domain,
srcScript = ('document.open();' +
(isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
'document.close();'),
iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
if (self.width) {
self.setWidth(self.width);
}
if (self.height) {
self.setHeight(self.height);
}
if (self.designMode) {
self.textarea.hide();
} else {
self.iframe.hide();
}
function ready() {
var doc = _iframeDoc(self.iframe);
doc.open();
if (isDocumentDomain) {
doc.domain = document.domain;
}
doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
doc.close();
self.win = self.iframe[0].contentWindow;
self.doc = doc;
var cmd = _cmd(doc);
self.afterChange(function(e) {
cmd.selection();
});
if (_WEBKIT) {
K(doc).click(function(e) {
if (K(e.target).name === 'img') {
cmd.selection(true);
cmd.range.selectNode(e.target);
cmd.select();
}
});
}
if (_IE) {
K(doc).keydown(function(e) {
if (e.which == 8) {
cmd.selection();
var rng = cmd.range;
if (rng.isControl()) {
rng.collapse(true);
K(rng.startContainer.childNodes[rng.startOffset]).remove();
e.preventDefault();
}
}
});
}
self.cmd = cmd;
self.html(_elementVal(self.srcElement));
if (_IE) {
doc.body.disabled = true;
doc.body.contentEditable = true;
doc.body.removeAttribute('disabled');
} else {
doc.designMode = 'on';
}
if (options.afterCreate) {
options.afterCreate.call(self);
}
}
if (isDocumentDomain) {
self.iframe.bind('load', function(e) {
self.iframe.unbind('load');
if (_IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
}
self.div.append(self.iframe);
self.div.append(self.textarea);
self.srcElement.hide();
!isDocumentDomain && ready();
},
setWidth : function(val) {
this.div.css('width', _addUnit(val));
return this;
},
setHeight : function(val) {
var self = this;
val = _addUnit(val);
self.div.css('height', val);
self.iframe.css('height', val);
if ((_IE && _V < 8) || _QUIRKS) {
val = _addUnit(_removeUnit(val) - 2);
}
self.textarea.css('height', val);
return self;
},
remove : function() {
var self = this, doc = self.doc;
K(doc.body).unbind();
K(doc).unbind();
K(self.win).unbind();
_elementVal(self.srcElement, self.html());
self.srcElement.show();
doc.write('');
self.iframe.unbind();
self.textarea.unbind();
KEdit.parent.remove.call(self);
},
html : function(val, isFull) {
var self = this, doc = self.doc;
if (self.designMode) {
var body = doc.body;
if (val === undefined) {
if (isFull) {
val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
} else {
val = body.innerHTML;
}
if (self.beforeGetHtml) {
val = self.beforeGetHtml(val);
}
if (_GECKO && val == '<br />') {
val = '';
}
return val;
}
if (self.beforeSetHtml) {
val = self.beforeSetHtml(val);
}
K(body).html(val);
if (self.afterSetHtml) {
self.afterSetHtml();
}
return self;
}
if (val === undefined) {
return self.textarea.val();
}
self.textarea.val(val);
return self;
},
design : function(bool) {
var self = this, val;
if (bool === undefined ? !self.designMode : bool) {
if (!self.designMode) {
val = self.html();
self.designMode = true;
self.html(val);
self.textarea.hide();
self.iframe.show();
}
} else {
if (self.designMode) {
val = self.html();
self.designMode = false;
self.html(val);
self.iframe.hide();
self.textarea.show();
}
}
return self.focus();
},
focus : function() {
var self = this;
self.designMode ? self.win.focus() : self.textarea[0].focus();
return self;
},
blur : function() {
var self = this;
if (_IE) {
var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
self.div.append(input);
input[0].focus();
input.remove();
} else {
self.designMode ? self.win.blur() : self.textarea[0].blur();
}
return self;
},
afterChange : function(fn) {
var self = this, doc = self.doc, body = doc.body;
K(doc).keyup(function(e) {
if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
fn(e);
}
});
K(doc).mouseup(fn).contextmenu(fn);
K(self.win).blur(fn);
function timeoutHandler(e) {
setTimeout(function() {
fn(e);
}, 1);
}
K(body).bind('paste', timeoutHandler);
K(body).bind('cut', timeoutHandler);
return self;
}
});
function _edit(options) {
return new KEdit(options);
}
K.edit = _edit;
K.iframeDoc = _iframeDoc;
function _selectToolbar(name, fn) {
var self = this,
knode = self.get(name);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
fn(knode);
}
}
function KToolbar(options) {
this.init(options);
}
_extend(KToolbar, KWidget, {
init : function(options) {
var self = this;
KToolbar.parent.init.call(self, options);
self.disableMode = _undef(options.disableMode, false);
self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
self._itemMap = {};
self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
e.preventDefault();
}).attr('unselectable', 'on');
function find(target) {
var knode = K(target);
if (knode.hasClass('ke-outline')) {
return knode;
}
if (knode.hasClass('ke-toolbar-icon')) {
return knode.parent();
}
}
function hover(e, method) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
if (knode.hasClass('ke-selected')) {
return;
}
knode[method]('ke-on');
}
}
self.div.mouseover(function(e) {
hover(e, 'addClass');
})
.mouseout(function(e) {
hover(e, 'removeClass');
})
.click(function(e) {
var knode = find(e.target);
if (knode) {
if (knode.hasClass('ke-disabled')) {
return;
}
self.options.click.call(this, e, knode.attr('data-name'));
}
});
},
get : function(name) {
if (this._itemMap[name]) {
return this._itemMap[name];
}
return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
},
select : function(name) {
_selectToolbar.call(this, name, function(knode) {
knode.addClass('ke-selected');
});
return self;
},
unselect : function(name) {
_selectToolbar.call(this, name, function(knode) {
knode.removeClass('ke-selected').removeClass('ke-on');
});
return self;
},
enable : function(name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-disabled');
knode.opacity(1);
}
return self;
},
disable : function(name) {
var self = this,
knode = name.get ? name : self.get(name);
if (knode) {
knode.removeClass('ke-selected').addClass('ke-disabled');
knode.opacity(0.5);
}
return self;
},
disableAll : function(bool, noDisableItems) {
var self = this, map = self.noDisableItemMap, item;
if (noDisableItems) {
map = _toMap(noDisableItems);
}
if (bool === undefined ? !self.disableMode : bool) {
K('span.ke-outline', self.div).each(function() {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.disable(knode);
}
});
self.disableMode = true;
} else {
K('span.ke-outline', self.div).each(function() {
var knode = K(this),
name = knode[0].getAttribute('data-name', 2);
if (!map[name]) {
self.enable(knode);
}
});
self.disableMode = false;
}
return self;
}
});
function _toolbar(options) {
return new KToolbar(options);
}
K.toolbar = _toolbar;
function KMenu(options) {
this.init(options);
}
_extend(KMenu, KWidget, {
init : function(options) {
var self = this;
options.z = options.z || 811213;
KMenu.parent.init.call(self, options);
self.centerLineMode = _undef(options.centerLineMode, true);
self.div.addClass('ke-menu').bind('click,mousedown', function(e){
e.stopPropagation();
}).attr('unselectable', 'on');
},
addItem : function(item) {
var self = this;
if (item.title === '-') {
self.div.append(K('<div class="ke-menu-separator"></div>'));
return;
}
var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
height = _addUnit(item.height),
iconClass = _undef(item.iconClass, '');
self.div.append(itemDiv);
if (height) {
itemDiv.css('height', height);
rightDiv.css('line-height', height);
}
var centerDiv;
if (self.centerLineMode) {
centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
if (height) {
centerDiv.css('height', height);
}
}
itemDiv.mouseover(function(e) {
K(this).addClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.addClass('ke-menu-item-center-on');
}
})
.mouseout(function(e) {
K(this).removeClass('ke-menu-item-on');
if (centerDiv) {
centerDiv.removeClass('ke-menu-item-center-on');
}
})
.click(function(e) {
item.click.call(K(this));
e.stopPropagation();
})
.append(leftDiv);
if (centerDiv) {
itemDiv.append(centerDiv);
}
itemDiv.append(rightDiv);
if (item.checked) {
iconClass = 'ke-icon-checked';
}
if (iconClass !== '') {
leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
}
rightDiv.html(item.title);
return self;
},
remove : function() {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
K('.ke-menu-item', self.div[0]).unbind();
KMenu.parent.remove.call(self);
return self;
}
});
function _menu(options) {
return new KMenu(options);
}
K.menu = _menu;
function KColorPicker(options) {
this.init(options);
}
_extend(KColorPicker, KWidget, {
init : function(options) {
var self = this;
options.z = options.z || 811213;
KColorPicker.parent.init.call(self, options);
var colors = options.colors || [
['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
];
self.selectedColor = (options.selectedColor || '').toLowerCase();
self._cells = [];
self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e){
e.stopPropagation();
}).attr('unselectable', 'on');
var table = self.doc.createElement('table');
self.div.append(table);
table.className = 'ke-colorpicker-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var row = table.insertRow(0), cell = row.insertCell(0);
cell.colSpan = colors[0].length;
self._addAttr(cell, '', 'ke-colorpicker-cell-top');
for (var i = 0; i < colors.length; i++) {
row = table.insertRow(i + 1);
for (var j = 0; j < colors[i].length; j++) {
cell = row.insertCell(j);
self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
}
}
},
_addAttr : function(cell, color, cls) {
var self = this;
cell = K(cell).addClass(cls);
if (self.selectedColor === color.toLowerCase()) {
cell.addClass('ke-colorpicker-cell-selected');
}
cell.attr('title', color || self.options.noColor);
cell.mouseover(function(e) {
K(this).addClass('ke-colorpicker-cell-on');
});
cell.mouseout(function(e) {
K(this).removeClass('ke-colorpicker-cell-on');
});
cell.click(function(e) {
e.stop();
self.options.click.call(K(this), color);
});
if (color) {
cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
} else {
cell.html(self.options.noColor);
}
K(cell).attr('unselectable', 'on');
self._cells.push(cell);
},
remove : function() {
var self = this;
_each(self._cells, function() {
this.unbind();
});
KColorPicker.parent.remove.call(self);
return self;
}
});
function _colorpicker(options) {
return new KColorPicker(options);
}
K.colorpicker = _colorpicker;
function KUploadButton(options) {
this.init(options);
}
_extend(KUploadButton, {
init : function(options) {
var self = this,
button = K(options.button),
fieldName = options.fieldName || 'file',
url = options.url || '',
title = button.val(),
cls = button[0].className || '',
target = 'kindeditor_upload_iframe_' + new Date().getTime();
options.afterError = options.afterError || function(str) {
alert(str);
};
var html = [
'<div class="ke-inline-block ' + cls + '">',
'<iframe name="' + target + '" style="display:none;"></iframe>',
'<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">',
'<span class="ke-button-common">',
'<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
'</span>',
'<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
'</form></div>'].join('');
var div = K(html, button.doc);
button.hide();
button.before(div);
self.div = div;
self.button = button;
self.iframe = K('iframe', div);
self.form = K('form', div);
self.fileBox = K('.ke-upload-file', div).width(K('.ke-button-common').width());
self.options = options;
},
submit : function() {
var self = this,
iframe = self.iframe;
iframe.bind('load', function() {
iframe.unbind();
var doc = K.iframeDoc(iframe),
pre = doc.getElementsByTagName('pre')[0],
str = '', data;
if (pre) {
str = pre.innerHTML;
} else {
str = doc.body.innerHTML;
}
try {
data = K.json(str);
} catch (e) {
self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
}
if (data) {
self.options.afterUpload.call(self, data);
}
});
self.form[0].submit();
var tempForm = document.createElement('form');
self.fileBox.before(tempForm);
K(tempForm).append(self.fileBox);
tempForm.reset();
K(tempForm).remove(true);
return self;
},
remove : function() {
var self = this;
if (self.fileBox) {
self.fileBox.unbind();
}
self.div.remove();
self.button.show();
return self;
}
});
function _uploadbutton(options) {
return new KUploadButton(options);
}
K.uploadbutton = _uploadbutton;
function _createButton(arg) {
arg = arg || {};
var name = arg.name || '',
span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
if (arg.click) {
btn.click(arg.click);
}
span.append(btn);
return span;
}
function KDialog(options) {
this.init(options);
}
_extend(KDialog, KWidget, {
init : function(options) {
var self = this;
var shadowMode = options.shadowMode;
options.z = options.z || 811213;
options.shadowMode = false;
KDialog.parent.init.call(self, options);
var title = options.title,
body = K(options.body, self.doc),
previewBtn = options.previewBtn,
yesBtn = options.yesBtn,
noBtn = options.noBtn,
closeBtn = options.closeBtn,
showMask = _undef(options.showMask, true);
self.div.addClass('ke-dialog').bind('click,mousedown', function(e){
e.stopPropagation();
});
var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
if (_IE && _V < 7) {
self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
} else if (shadowMode) {
K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
}
var headerDiv = K('<div class="ke-dialog-header"></div>');
contentDiv.append(headerDiv);
headerDiv.html(title);
self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
headerDiv.append(self.closeIcon);
self.draggable({
clickEl : headerDiv,
beforeDrag : options.beforeDrag
});
var bodyDiv = K('<div class="ke-dialog-body"></div>');
contentDiv.append(bodyDiv);
bodyDiv.append(body);
var footerDiv = K('<div class="ke-dialog-footer"></div>');
if (previewBtn || yesBtn || noBtn) {
contentDiv.append(footerDiv);
}
_each([
{ btn : previewBtn, name : 'preview' },
{ btn : yesBtn, name : 'yes' },
{ btn : noBtn, name : 'no' }
], function() {
if (this.btn) {
var button = _createButton(this.btn);
button.addClass('ke-dialog-' + this.name);
footerDiv.append(button);
}
});
if (self.height) {
bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
}
self.div.width(self.div.width());
self.div.height(self.div.height());
self.mask = null;
if (showMask) {
var docEl = _docElement(self.doc),
docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
self.mask = _widget({
x : 0,
y : 0,
z : self.z - 1,
cls : 'ke-dialog-mask',
width : docWidth,
height : docHeight
});
}
self.autoPos(self.div.width(), self.div.height());
self.footerDiv = footerDiv;
self.bodyDiv = bodyDiv;
self.headerDiv = headerDiv;
},
setMaskIndex : function(z) {
var self = this;
self.mask.div.css('z-index', z);
},
showLoading : function(msg) {
msg = _undef(msg, '');
var self = this, body = self.bodyDiv;
self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
.width(body.width()).height(body.height())
.css('top', self.headerDiv.height() + 'px');
body.css('visibility', 'hidden').after(self.loading);
return self;
},
hideLoading : function() {
this.loading && this.loading.remove();
this.bodyDiv.css('visibility', 'visible');
return this;
},
remove : function() {
var self = this;
if (self.options.beforeRemove) {
self.options.beforeRemove.call(self);
}
self.mask && self.mask.remove();
self.iframeMask && self.iframeMask.remove();
self.closeIcon.unbind();
K('input', self.div).unbind();
self.footerDiv.unbind();
self.bodyDiv.unbind();
self.headerDiv.unbind();
KDialog.parent.remove.call(self);
return self;
}
});
function _dialog(options) {
return new KDialog(options);
}
K.dialog = _dialog;
function _tabs(options) {
var self = _widget(options),
remove = self.remove,
afterSelect = options.afterSelect,
div = self.div,
liList = [];
div.addClass('ke-tabs')
.bind('contextmenu,mousedown,mousemove', function(e) {
e.preventDefault();
});
var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
div.append(ul);
self.add = function(tab) {
var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
li.data('tab', tab);
liList.push(li);
ul.append(li);
};
self.selectedIndex = 0;
self.select = function(index) {
self.selectedIndex = index;
_each(liList, function(i, li) {
li.unbind();
if (i === index) {
li.addClass('ke-tabs-li-selected');
K(li.data('tab').panel).show('');
} else {
li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
.mouseover(function() {
K(this).addClass('ke-tabs-li-on');
})
.mouseout(function() {
K(this).removeClass('ke-tabs-li-on');
})
.click(function() {
self.select(i);
});
K(li.data('tab').panel).hide();
}
});
if (afterSelect) {
afterSelect.call(self, index);
}
};
self.remove = function() {
_each(liList, function() {
this.remove();
});
ul.remove();
remove.call(self);
};
return self;
}
K.tabs = _tabs;
function _loadScript(url, fn) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
script = document.createElement('script');
head.appendChild(script);
script.src = url;
script.charset = 'utf-8';
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === 'loaded') {
if (fn) {
fn();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
}
function _loadStyle(url) {
var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
link = document.createElement('link'),
absoluteUrl = _formatUrl(url, 'absolute');
var links = K('link[rel="stylesheet"]', head);
for (var i = 0, len = links.length; i < len; i++) {
if (_formatUrl(links[i].href, 'absolute') === absoluteUrl) {
return;
}
}
head.appendChild(link);
link.href = url;
link.rel = 'stylesheet';
}
function _ajax(url, fn, method, param, dataType) {
method = method || 'GET';
dataType = dataType || 'json';
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (fn) {
var data = _trim(xhr.responseText);
if (dataType == 'json') {
data = _json(data);
}
fn(data);
}
}
};
if (method == 'POST') {
var params = [];
_each(param, function(key, val) {
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
});
try {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
} catch (e) {}
xhr.send(params.join('&'));
} else {
xhr.send(null);
}
}
K.loadScript = _loadScript;
K.loadStyle = _loadStyle;
K.ajax = _ajax;
var _plugins = {};
function _plugin(name, fn) {
if (!fn) {
return _plugins[name];
}
_plugins[name] = fn;
}
var _language = {};
function _parseLangKey(key) {
var match, ns = 'core';
if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
ns = match[1];
key = match[2];
}
return { ns : ns, key : key };
}
function _lang(mixed, langType) {
langType = langType === undefined ? K.options.langType : langType;
if (typeof mixed === 'string') {
if (!_language[langType]) {
return 'no language';
}
var pos = mixed.length - 1;
if (mixed.substr(pos) === '.') {
return _language[langType][mixed.substr(0, pos)];
}
var obj = _parseLangKey(mixed);
return _language[langType][obj.ns][obj.key];
}
_each(mixed, function(key, val) {
var obj = _parseLangKey(key);
if (!_language[langType]) {
_language[langType] = {};
}
if (!_language[langType][obj.ns]) {
_language[langType][obj.ns] = {};
}
_language[langType][obj.ns][obj.key] = val;
});
}
function _getImageFromRange(range, fn) {
if (range.collapsed) {
return;
}
range = range.cloneRange().up();
var sc = range.startContainer, so = range.startOffset;
if (!_WEBKIT && !range.isControl()) {
return;
}
var img = K(sc.childNodes[so]);
if (!img || img.name != 'img') {
return;
}
if (fn(img)) {
return img;
}
}
function _bindContextmenuEvent() {
var self = this, doc = self.edit.doc;
K(doc).contextmenu(function(e) {
if (self.menu) {
self.hideMenu();
}
if (!self.useContextmenu) {
e.preventDefault();
return;
}
if (self._contextmenus.length === 0) {
return;
}
var maxWidth = 0, items = [];
_each(self._contextmenus, function() {
if (this.title == '-') {
items.push(this);
return;
}
if (this.cond && this.cond()) {
items.push(this);
if (this.width && this.width > maxWidth) {
maxWidth = this.width;
}
}
});
while (items.length > 0 && items[0].title == '-') {
items.shift();
}
while (items.length > 0 && items[items.length - 1].title == '-') {
items.pop();
}
var prevItem = null;
_each(items, function(i) {
if (this.title == '-' && prevItem.title == '-') {
delete items[i];
}
prevItem = this;
});
if (items.length > 0) {
e.preventDefault();
var pos = K(self.edit.iframe).pos(),
menu = _menu({
x : pos.x + e.clientX,
y : pos.y + e.clientY,
width : maxWidth,
css : { visibility: 'hidden' },
shadowMode : self.shadowMode
});
_each(items, function() {
if (this.title) {
menu.addItem(this);
}
});
var docEl = _docElement(menu.doc),
menuHeight = menu.div.height();
if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
}
menu.div.css('visibility', 'visible');
self.menu = menu;
}
});
}
function _bindNewlineEvent() {
var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
if (_IE && newlineTag !== 'br') {
return;
}
if (_GECKO && _V < 3 && newlineTag !== 'p') {
return;
}
if (_OPERA) {
return;
}
var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
function getAncestorTagName(range) {
var ancestor = K(range.commonAncestor());
while (ancestor) {
if (ancestor.type == 1 && !ancestor.isStyle()) {
break;
}
ancestor = ancestor.parent();
}
return ancestor.name;
}
K(doc).keydown(function(e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
e.preventDefault();
self.insertHtml('<br />');
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
});
K(doc).keyup(function(e) {
if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
return;
}
if (newlineTag == 'br') {
return;
}
self.cmd.selection();
var tagName = getAncestorTagName(self.cmd.range);
if (tagName == 'marquee' || tagName == 'select') {
return;
}
if (!pSkipTagMap[tagName]) {
_nativeCommand(doc, 'formatblock', '<p>');
}
var div = self.cmd.commonAncestor('div');
if (div) {
var p = K('<p></p>'),
child = div[0].firstChild;
while (child) {
var next = child.nextSibling;
p.append(child);
child = next;
}
div.before(p);
div.remove();
self.cmd.range.selectNodeContents(p[0]);
self.cmd.select();
}
});
}
function _bindTabEvent() {
var self = this, doc = self.edit.doc;
K(doc).keydown(function(e) {
if (e.which == 9) {
e.preventDefault();
if (self.afterTab) {
self.afterTab.call(self, e);
return;
}
var cmd = self.cmd, range = cmd.range;
range.shrink();
if (range.collapsed && range.startContainer.nodeType == 1) {
range.insertNode(K('@ ', doc)[0]);
cmd.select();
}
self.insertHtml(' ');
}
});
}
function _bindFocusEvent() {
var self = this;
K(self.edit.textarea[0], self.edit.win).focus(function(e) {
if (self.afterFocus) {
self.afterFocus.call(self, e);
}
}).blur(function(e) {
if (self.afterBlur) {
self.afterBlur.call(self, e);
}
});
}
function _removeBookmarkTag(html) {
return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
}
function _removeTempTag(html) {
return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
}
function _addBookmarkToStack(stack, bookmark) {
if (stack.length === 0) {
stack.push(bookmark);
return;
}
var prev = stack[stack.length - 1];
if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
stack.push(bookmark);
}
}
function _undoToRedo(fromStack, toStack) {
var self = this, edit = self.edit,
body = edit.doc.body,
range, bookmark;
if (fromStack.length === 0) {
return self;
}
if (edit.designMode) {
range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = body.innerHTML;
} else {
bookmark = {
html : body.innerHTML
};
}
_addBookmarkToStack(toStack, bookmark);
var prev = fromStack.pop();
if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
prev = fromStack.pop();
}
if (edit.designMode) {
edit.html(prev.html);
if (prev.start) {
range.moveToBookmark(prev);
self.select();
}
} else {
K(body).html(_removeBookmarkTag(prev.html));
}
return self;
}
function KEditor(options) {
var self = this;
self.options = {};
function setOption(key, val) {
if (KEditor.prototype[key] === undefined) {
self[key] = val;
}
self.options[key] = val;
}
_each(options, function(key, val) {
setOption(key, options[key]);
});
_each(K.options, function(key, val) {
if (self[key] === undefined) {
setOption(key, val);
}
});
setOption('width', _undef(self.width, self.minWidth));
setOption('height', _undef(self.height, self.minHeight));
setOption('width', _addUnit(self.width));
setOption('height', _addUnit(self.height));
if (_MOBILE) {
self.designMode = false;
}
var se = K(self.srcElement || '<textarea/>');
self.srcElement = se;
self.initContent = _elementVal(se);
self.plugin = {};
self.isCreated = false;
self.isLoading = false;
self._handlers = {};
self._contextmenus = [];
self._undoStack = [];
self._redoStack = [];
self._calledPlugins = {};
self._firstAddBookmark = true;
self.menu = self.contextmenu = null;
self.dialogs = [];
}
KEditor.prototype = {
lang : function(mixed) {
return _lang(mixed, this.langType);
},
loadPlugin : function(name, fn) {
var self = this;
if (_plugins[name]) {
if (self._calledPlugins[name]) {
if (fn) {
fn.call(self);
}
return self;
}
_plugins[name].call(self, KindEditor);
if (fn) {
fn.call(self);
}
self._calledPlugins[name] = true;
return self;
}
if (self.isLoading) {
return self;
}
self.isLoading = true;
_loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
self.isLoading = false;
if (_plugins[name]) {
self.loadPlugin(name, fn);
}
});
return self;
},
handler : function(key, fn) {
var self = this;
if (!self._handlers[key]) {
self._handlers[key] = [];
}
if (_isFunction(fn)) {
self._handlers[key].push(fn);
return self;
}
_each(self._handlers[key], function() {
fn = this.call(self, fn);
});
return fn;
},
clickToolbar : function(name, fn) {
var self = this, key = 'clickToolbar' + name;
if (fn === undefined) {
if (self._handlers[key]) {
return self.handler(key);
}
self.loadPlugin(name, function() {
self.handler(key);
});
return self;
}
return self.handler(key, fn);
},
updateState : function() {
var self = this;
_each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
});
return self;
},
addContextmenu : function(item) {
this._contextmenus.push(item);
return this;
},
afterCreate : function(fn) {
return this.handler('afterCreate', fn);
},
beforeRemove : function(fn) {
return this.handler('beforeRemove', fn);
},
beforeGetHtml : function(fn) {
return this.handler('beforeGetHtml', fn);
},
beforeSetHtml : function(fn) {
return this.handler('beforeSetHtml', fn);
},
afterSetHtml : function(fn) {
return this.handler('afterSetHtml', fn);
},
create : function() {
var self = this, fullscreenMode = self.fullscreenMode;
if (self.isCreated) {
return self;
}
if (fullscreenMode) {
_docElement().style.overflow = 'hidden';
} else {
_docElement().style.overflow = '';
}
var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
if ((_IE && _V < 8) || _QUIRKS) {
height = _addUnit(_removeUnit(height) + 2);
}
var container = self.container = K(self.layout);
if (fullscreenMode) {
K(document.body).append(container);
} else {
self.srcElement.before(container);
}
var toolbarDiv = K('.toolbar', container),
editDiv = K('.edit', container),
statusbar = self.statusbar = K('.statusbar', container);
container.removeClass('container')
.addClass('ke-container ke-container-' + self.themeType).css('width', width);
if (fullscreenMode) {
container.css({
position : 'absolute',
left : 0,
top : 0,
'z-index' : 811211
});
if (!_GECKO) {
self._scrollPos = _getScrollPos();
}
window.scrollTo(0, 0);
K(document.body).css({
'height' : '1px',
'overflow' : 'hidden'
});
K(document.body.parentNode).css('overflow', 'hidden');
} else {
if (self._scrollPos) {
K(document.body).css({
'height' : '',
'overflow' : ''
});
K(document.body.parentNode).css('overflow', '');
window.scrollTo(self._scrollPos.x, self._scrollPos.y);
}
}
var htmlList = [];
K.each(self.items, function(i, name) {
if (name == '|') {
htmlList.push('<span class="ke-inline-block ke-separator"></span>');
} else if (name == '/') {
htmlList.push('<div class="ke-hr"></div>');
} else {
htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
}
});
var toolbar = self.toolbar = _toolbar({
src : toolbarDiv,
html : htmlList.join(''),
noDisableItems : self.noDisableItems,
click : function(e, name) {
e.stop();
if (self.menu) {
var menuName = self.menu.name;
self.hideMenu();
if (menuName === name) {
return;
}
}
self.clickToolbar(name);
}
});
var editHeight = _removeUnit(height) - toolbar.div.height();
var edit = self.edit = _edit({
height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
src : editDiv,
srcElement : self.srcElement,
designMode : self.designMode,
themesPath : self.themesPath,
bodyClass : self.bodyClass,
cssPath : self.cssPath,
cssData : self.cssData,
beforeGetHtml : function(html) {
html = self.beforeGetHtml(html);
return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
},
beforeSetHtml : function(html) {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
return self.beforeSetHtml(html);
},
afterSetHtml : function() {
self.afterSetHtml();
},
afterCreate : function() {
self.edit = edit = this;
self.cmd = edit.cmd;
self._docMousedownFn = function(e) {
if (self.menu) {
self.hideMenu();
}
};
K(edit.doc, document).mousedown(self._docMousedownFn);
_bindContextmenuEvent.call(self);
_bindNewlineEvent.call(self);
_bindTabEvent.call(self);
_bindFocusEvent.call(self);
edit.afterChange(function(e) {
if (!edit.designMode) {
return;
}
self.updateState();
self.addBookmark();
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
edit.textarea.keyup(function(e) {
if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
});
if (self.readonlyMode) {
self.readonly();
}
self.isCreated = true;
self.initContent = self.html();
self.afterCreate();
if (self.options.afterCreate) {
self.options.afterCreate.call(self);
}
}
});
statusbar.removeClass('statusbar').addClass('ke-statusbar')
.append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
.append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
K(window).unbind('resize');
function initResize() {
if (statusbar.height() === 0) {
setTimeout(initResize, 100);
return;
}
self.resize(width, height);
}
initResize();
function newResize(width, height, updateProp) {
updateProp = _undef(updateProp, true);
if (width && width >= self.minWidth) {
self.resize(width, null);
if (updateProp) {
self.width = _addUnit(width);
}
}
if (height && height >= self.minHeight) {
self.resize(null, height);
if (updateProp) {
self.height = _addUnit(height);
}
}
}
if (fullscreenMode) {
K(window).bind('resize', function(e) {
if (self.isCreated) {
newResize(_docElement().clientWidth, _docElement().clientHeight, false);
}
});
toolbar.select('fullscreen');
statusbar.first().css('visibility', 'hidden');
statusbar.last().css('visibility', 'hidden');
} else {
if (_GECKO) {
K(window).bind('scroll', function(e) {
self._scrollPos = _getScrollPos();
});
}
if (self.resizeType > 0) {
_drag({
moveEl : container,
clickEl : statusbar,
moveFn : function(x, y, width, height, diffX, diffY) {
height += diffY;
newResize(null, height);
}
});
} else {
statusbar.first().css('visibility', 'hidden');
}
if (self.resizeType === 2) {
_drag({
moveEl : container,
clickEl : statusbar.last(),
moveFn : function(x, y, width, height, diffX, diffY) {
width += diffX;
height += diffY;
newResize(width, height);
}
});
} else {
statusbar.last().css('visibility', 'hidden');
}
}
return self;
},
remove : function() {
var self = this;
if (!self.isCreated) {
return self;
}
self.beforeRemove();
if (self.menu) {
self.hideMenu();
}
_each(self.dialogs, function() {
self.hideDialog();
});
K(document).unbind('mousedown', self._docMousedownFn);
self.toolbar.remove();
self.edit.remove();
self.statusbar.last().unbind();
self.statusbar.unbind();
self.container.remove();
self.container = self.toolbar = self.edit = self.menu = null;
self.dialogs = [];
self.isCreated = false;
return self;
},
resize : function(width, height) {
var self = this;
if (width !== null) {
if (_removeUnit(width) > self.minWidth) {
self.container.css('width', _addUnit(width));
}
}
if (height !== null) {
height = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
if (height > 0 && _removeUnit(height) > self.minHeight) {
self.edit.setHeight(height);
}
}
return self;
},
select : function() {
this.isCreated && this.cmd.select();
return this;
},
html : function(val) {
var self = this;
if (val === undefined) {
return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
}
self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
return self;
},
fullHtml : function() {
return this.isCreated ? this.edit.html(undefined, true) : '';
},
text : function(val) {
var self = this;
if (val === undefined) {
return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/ /ig, ' '));
} else {
return self.html(_escape(val));
}
},
isEmpty : function() {
return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
},
isDirty : function() {
return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
},
selectedHtml : function() {
return this.isCreated ? this.cmd.range.html() : '';
},
count : function(mode) {
var self = this;
mode = (mode || 'html').toLowerCase();
if (mode === 'html') {
return _removeBookmarkTag(_removeTempTag(self.html())).length;
}
if (mode === 'text') {
return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
}
return 0;
},
exec : function(key) {
key = key.toLowerCase();
var self = this, cmd = self.cmd,
changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
if (changeFlag) {
self.addBookmark(false);
}
cmd[key].apply(cmd, _toArray(arguments, 1));
if (changeFlag) {
self.updateState();
self.addBookmark(false);
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
}
return self;
},
insertHtml : function(val) {
if (!this.isCreated) {
return this;
}
val = this.beforeSetHtml(val);
this.exec('inserthtml', val);
return this;
},
appendHtml : function(val) {
this.html(this.html() + val);
if (this.isCreated) {
var cmd = this.cmd;
cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
cmd.select();
}
return this;
},
sync : function() {
_elementVal(this.srcElement, this.html());
return this;
},
focus : function() {
this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
return this;
},
blur : function() {
this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
return this;
},
addBookmark : function(checkSize) {
checkSize = _undef(checkSize, true);
var self = this, edit = self.edit,
body = edit.doc.body,
html = _removeTempTag(body.innerHTML), bookmark;
if (checkSize && self._undoStack.length > 0) {
var prev = self._undoStack[self._undoStack.length - 1];
if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
return self;
}
}
if (edit.designMode && !self._firstAddBookmark) {
var range = self.cmd.range;
bookmark = range.createBookmark(true);
bookmark.html = html;
range.moveToBookmark(bookmark);
} else {
bookmark = {
html : html
};
}
self._firstAddBookmark = false;
_addBookmarkToStack(self._undoStack, bookmark);
return self;
},
undo : function() {
return _undoToRedo.call(this, this._undoStack, this._redoStack);
},
redo : function() {
return _undoToRedo.call(this, this._redoStack, this._undoStack);
},
fullscreen : function(bool) {
this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
return this.remove().create();
},
readonly : function(isReadonly) {
isReadonly = _undef(isReadonly, true);
var self = this, edit = self.edit, doc = edit.doc;
if (self.designMode) {
self.toolbar.disableAll(isReadonly, []);
} else {
_each(self.noDisableItems, function() {
self.toolbar[isReadonly ? 'disable' : 'enable'](this);
});
}
if (_IE) {
doc.body.contentEditable = !isReadonly;
} else {
doc.designMode = isReadonly ? 'off' : 'on';
}
edit.textarea[0].disabled = isReadonly;
},
createMenu : function(options) {
var self = this,
name = options.name,
knode = self.toolbar.get(name),
pos = knode.pos();
options.x = pos.x;
options.y = pos.y + knode.height();
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
if (options.selectedColor !== undefined) {
options.cls = 'ke-colorpicker-' + self.themeType;
options.noColor = self.lang('noColor');
self.menu = _colorpicker(options);
} else {
options.cls = 'ke-menu-' + self.themeType;
options.centerLineMode = false;
self.menu = _menu(options);
}
return self.menu;
},
hideMenu : function() {
this.menu.remove();
this.menu = null;
return this;
},
hideContextmenu : function() {
this.contextmenu.remove();
this.contextmenu = null;
return this;
},
createDialog : function(options) {
var self = this, name = options.name;
options.autoScroll = _undef(options.autoScroll, true);
options.shadowMode = _undef(options.shadowMode, self.shadowMode);
options.closeBtn = _undef(options.closeBtn, {
name : self.lang('close'),
click : function(e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
options.noBtn = _undef(options.noBtn, {
name : self.lang(options.yesBtn ? 'no' : 'close'),
click : function(e) {
self.hideDialog();
if (_IE && self.cmd) {
self.cmd.select();
}
}
});
if (self.dialogAlignType != 'page') {
options.alignEl = self.container;
}
options.cls = 'ke-dialog-' + self.themeType;
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z + 2);
options.z = parentDialog.z + 3;
options.showMask = false;
}
var dialog = _dialog(options);
self.dialogs.push(dialog);
return dialog;
},
hideDialog : function() {
var self = this;
if (self.dialogs.length > 0) {
self.dialogs.pop().remove();
}
if (self.dialogs.length > 0) {
var firstDialog = self.dialogs[0],
parentDialog = self.dialogs[self.dialogs.length - 1];
firstDialog.setMaskIndex(parentDialog.z - 1);
}
return self;
},
errorDialog : function(html) {
var self = this;
var dialog = self.createDialog({
width : 750,
title : self.lang('uploadError'),
body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
});
var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
doc.open();
doc.write(html);
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
return self;
}
};
function _editor(options) {
return new KEditor(options);
}
function _create(expr, options) {
options = options || {};
options.basePath = _undef(options.basePath, K.basePath);
options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
options.langPath = _undef(options.langPath, options.basePath + 'lang/');
options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
var themeType = _undef(options.themeType, K.options.themeType);
_loadStyle(options.themesPath + 'default/default.css');
_loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
}
function create(editor) {
_each(_plugins, function(name, fn) {
fn.call(editor, KindEditor);
});
return editor.create();
}
var knode = K(expr);
if (!knode) {
return;
}
options.srcElement = knode[0];
if (!options.width) {
options.width = knode[0].style.width || knode.width();
}
if (!options.height) {
options.height = knode[0].style.height || knode.height();
}
var editor = new KEditor(options);
if (_language[editor.langType]) {
return create(editor);
}
_loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
return create(editor);
});
return editor;
}
if (_IE && _V < 7) {
_nativeCommand(document, 'BackgroundImageCache', true);
}
K.editor = _editor;
K.create = _create;
K.plugin = _plugin;
K.lang = _lang;
_plugin('core', function(K) {
var self = this,
shortcutKeys = {
undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
};
self.afterSetHtml(function() {
if (self.options.afterChange) {
self.options.afterChange.call(self);
}
});
if (self.syncType == 'form') {
var el = K(self.srcElement), hasForm = false;
while ((el = el.parent())) {
if (el.name == 'form') {
hasForm = true;
break;
}
}
if (hasForm) {
el.bind('submit', function(e) {
self.sync();
self.edit.textarea.remove();
});
var resetBtn = K('[type="reset"]', el);
resetBtn.click(function() {
self.html(self.initContent);
self.cmd.selection();
});
self.beforeRemove(function() {
el.unbind();
resetBtn.unbind();
});
}
}
self.clickToolbar('source', function() {
if (_MOBILE) {
return;
}
if (self.edit.designMode) {
self.toolbar.disableAll(true);
self.edit.design(false);
self.toolbar.select('source');
} else {
self.toolbar.disableAll(false);
self.edit.design(true);
self.toolbar.unselect('source');
}
self.designMode = self.edit.designMode;
});
self.afterCreate(function() {
if (!self.designMode) {
self.toolbar.disableAll(true).select('source');
}
});
self.clickToolbar('fullscreen', function() {
self.fullscreen();
});
var loaded = false;
self.afterCreate(function() {
K(self.edit.doc, self.edit.textarea).keyup(function(e) {
if (e.which == 27) {
setTimeout(function() {
self.fullscreen();
}, 0);
}
});
if (loaded) {
if (_IE && !self.designMode) {
return;
}
self.focus();
}
if (!loaded) {
loaded = true;
}
});
_each('undo,redo'.split(','), function(i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function() {
_ctrl(this.edit.doc, shortcutKeys[name], function() {
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function() {
self[name]();
});
});
self.clickToolbar('formatblock', function() {
var blocks = self.lang('formatblock.formatBlock'),
heights = {
h1 : 28,
h2 : 24,
h3 : 18,
H4 : 14,
p : 12
},
curVal = self.cmd.val('formatblock'),
menu = self.createMenu({
name : 'formatblock',
width : self.langType == 'en' ? 200 : 150
});
_each(blocks, function(key, val) {
var style = 'font-size:' + heights[key] + 'px;';
if (key.charAt(0) === 'h') {
style += 'font-weight:bold;';
}
menu.addItem({
title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
height : heights[key] + 12,
checked : (curVal === key || curVal === val),
click : function() {
self.select().exec('formatblock', '<' + key + '>').hideMenu();
}
});
});
});
self.clickToolbar('fontname', function() {
var curVal = self.cmd.val('fontname'),
menu = self.createMenu({
name : 'fontname',
width : 150
});
_each(self.lang('fontname.fontName'), function(key, val) {
menu.addItem({
title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
click : function() {
self.exec('fontname', key).hideMenu();
}
});
});
});
self.clickToolbar('fontsize', function() {
var curVal = self.cmd.val('fontsize'),
menu = self.createMenu({
name : 'fontsize',
width : 150
});
_each(self.fontSizeTable, function(i, val) {
menu.addItem({
title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
height : _removeUnit(val) + 12,
checked : curVal === val,
click : function() {
self.exec('fontsize', val).hideMenu();
}
});
});
});
_each('forecolor,hilitecolor'.split(','), function(i, name) {
self.clickToolbar(name, function() {
self.createMenu({
name : name,
selectedColor : self.cmd.val(name) || 'default',
colors : self.colorTable,
click : function(color) {
self.exec(name, color).hideMenu();
}
});
});
});
_each(('cut,copy,paste').split(','), function(i, name) {
self.clickToolbar(name, function() {
self.focus();
try {
self.exec(name, null);
} catch(e) {
alert(self.lang(name + 'Error'));
}
});
});
self.clickToolbar('about', function() {
var html = '<div style="margin:20px;">' +
'<div>KindEditor ' + _VERSION + '</div>' +
'<div>Copyright © <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
'</div>';
self.createDialog({
name : 'about',
width : 300,
title : self.lang('about'),
body : html
});
});
self.plugin.getSelectedLink = function() {
return self.cmd.commonAncestor('a');
};
self.plugin.getSelectedImage = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return !/^ke-\w+$/i.test(img[0].className);
});
};
self.plugin.getSelectedFlash = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-flash';
});
};
self.plugin.getSelectedMedia = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
});
};
self.plugin.getSelectedAnchor = function() {
return _getImageFromRange(self.edit.cmd.range, function(img) {
return img[0].className == 'ke-anchor';
});
};
_each('link,image,flash,media,anchor'.split(','), function(i, name) {
var uName = name.charAt(0).toUpperCase() + name.substr(1);
_each('edit,delete'.split(','), function(j, val) {
self.addContextmenu({
title : self.lang(val + uName),
click : function() {
self.loadPlugin(name, function() {
self.plugin[name][val]();
self.hideMenu();
});
},
cond : self.plugin['getSelected' + uName],
width : 150,
iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
});
});
self.addContextmenu({ title : '-' });
});
self.plugin.getSelectedTable = function() {
return self.cmd.commonAncestor('table');
};
self.plugin.getSelectedRow = function() {
return self.cmd.commonAncestor('tr');
};
self.plugin.getSelectedCell = function() {
return self.cmd.commonAncestor('td');
};
_each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
self.addContextmenu({
title : self.lang('table' + val),
click : function() {
self.loadPlugin('table', function() {
self.plugin.table[val]();
self.hideMenu();
});
},
cond : cond,
width : 170,
iconClass : 'ke-icon-table' + val
});
});
self.addContextmenu({ title : '-' });
_each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
if (shortcutKeys[name]) {
self.afterCreate(function() {
_ctrl(this.edit.doc, shortcutKeys[name], function() {
self.cmd.selection();
self.clickToolbar(name);
});
});
}
self.clickToolbar(name, function() {
self.focus().exec(name, null);
});
});
self.afterCreate(function() {
var doc = self.edit.doc, cmd, bookmark, div,
cls = '__kindeditor_paste__', pasting = false;
function movePastedData() {
cmd.range.moveToBookmark(bookmark);
cmd.select();
if (_WEBKIT) {
K('div.' + cls, div).each(function() {
K(this).after('<br />').remove(true);
});
K('span.Apple-style-span', div).remove(true);
K('meta', div).remove();
}
var html = div[0].innerHTML;
div.remove();
if (html === '') {
return;
}
if (self.pasteType === 2) {
if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
} else {
html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
html = self.beforeSetHtml(html);
}
}
if (self.pasteType === 1) {
html = html.replace(/<br[^>]*>/ig, '\n');
html = html.replace(/<\/p><p[^>]*>/ig, '\n');
html = html.replace(/<[^>]+>/g, '');
html = html.replace(/ /ig, ' ');
html = html.replace(/\n\s*\n/g, '\n');
if (self.newlineTag == 'p') {
html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
} else {
html = html.replace(/\n/g, '<br />$&');
}
}
self.insertHtml(html);
}
K(doc.body).bind('paste', function(e){
if (self.pasteType === 0) {
e.stop();
return;
}
if (pasting) {
return;
}
pasting = true;
K('div.' + cls, doc).remove();
cmd = self.cmd.selection();
bookmark = cmd.range.createBookmark();
div = K('<div class="' + cls + '"></div>', doc).css({
position : 'absolute',
width : '1px',
height : '1px',
overflow : 'hidden',
left : '-1981px',
top : K(bookmark.start).pos().y + 'px',
'white-space' : 'nowrap'
});
K(doc.body).append(div);
if (_IE) {
var rng = cmd.range.get(true);
rng.moveToElementText(div[0]);
rng.select();
rng.execCommand('paste');
e.preventDefault();
} else {
cmd.range.selectNodeContents(div[0]);
cmd.select();
}
setTimeout(function() {
movePastedData();
pasting = false;
}, 0);
});
});
self.beforeGetHtml(function(html) {
return html.replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
var imgAttrs = _getAttrList(full),
styles = _getCssList(imgAttrs.style || ''),
attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
attrs.width = _undef(imgAttrs.width, _removeUnit(_undef(styles.width, '')));
attrs.height = _undef(imgAttrs.height, _removeUnit(_undef(styles.height, '')));
return _mediaEmbed(attrs);
})
.replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
var imgAttrs = _getAttrList(full);
return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
})
.replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
})
.replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, '$1' + src + '$2');
full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
return full;
})
.replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
return start + end;
});
});
self.beforeSetHtml(function(html) {
return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
var attrs = _getAttrList(full);
attrs.src = _undef(attrs.src, '');
attrs.width = _undef(attrs.width, 0);
attrs.height = _undef(attrs.height, 0);
return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
})
.replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
var attrs = _getAttrList(full);
if (attrs.href !== undefined) {
return full;
}
return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
})
.replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
})
.replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
if (full.match(/\sdata-ke-src="[^"]*"/i)) {
return full;
}
full = start + key + '="' + src + '"' + ' data-ke-src="' + src + '"' + end;
return full;
})
.replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
return start + 'data-ke-' + end;
})
.replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
if (full.indexOf('ke-zeroborder') >= 0) {
return full;
}
return _addClassToTag(full, 'ke-zeroborder');
});
});
});
})(window);
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : '原始碼',
preview : '預覽',
undo : '復原(Ctrl+Z)',
redo : '重複(Ctrl+Y)',
cut : '剪下(Ctrl+X)',
copy : '複製(Ctrl+C)',
paste : '貼上(Ctrl+V)',
plainpaste : '貼為純文字格式',
wordpaste : '自Word貼上',
selectall : '全選(Ctrl+A)',
justifyleft : '靠左對齊',
justifycenter : '置中',
justifyright : '靠右對齊',
justifyfull : '左右對齊',
insertorderedlist : '編號清單',
insertunorderedlist : '項目清單',
indent : '增加縮排',
outdent : '減少縮排',
subscript : '下標',
superscript : '上標',
formatblock : '標題',
fontname : '字體',
fontsize : '文字大小',
forecolor : '文字顏色',
hilitecolor : '背景顏色',
bold : '粗體(Ctrl+B)',
italic : '斜體(Ctrl+I)',
underline : '底線(Ctrl+U)',
strikethrough : '刪除線',
removeformat : '清除格式',
image : '影像',
flash : 'Flash',
media : '多媒體',
table : '表格',
hr : '插入水平線',
emoticons : '插入表情',
link : '超連結',
unlink : '移除超連結',
fullscreen : '最大化',
about : '關於',
print : '列印(Ctrl+P)',
fileManager : '瀏覽伺服器',
code : '插入程式代碼',
map : 'Google地圖',
lineheight : '行距',
clearhtml : '清理HTML代碼',
pagebreak : '插入分頁符號',
quickformat : '快速排版',
insertfile : '插入文件',
template : '插入樣板',
anchor : '錨點',
yes : '確定',
no : '取消',
close : '關閉',
editImage : '影像屬性',
deleteImage : '刪除影像',
editFlash : 'Flash屬性',
deleteFlash : '删除Flash',
editMedia : '多媒體屬性',
deleteMedia : '删除多媒體',
editLink : '超連結屬性',
deleteLink : '移除超連結',
tableprop : '表格屬性',
tablecellprop : '儲存格屬性',
tableinsert : '插入表格',
tabledelete : '刪除表格',
tablecolinsertleft : '向左插入列',
tablecolinsertright : '向右插入列',
tablerowinsertabove : '向上插入欄',
tablerowinsertbelow : '下方插入欄',
tablerowmerge : '向下合併單元格',
tablecolmerge : '向右合併單元格',
tablerowsplit : '分割欄',
tablecolsplit : '分割列',
tablecoldelete : '删除列',
tablerowdelete : '删除欄',
noColor : '自動',
invalidImg : "請輸入有效的URL。\n只允許jpg,gif,bmp,png格式。",
invalidMedia : "請輸入有效的URL。\n只允許swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
invalidWidth : "寬度必須是數字。",
invalidHeight : "高度必須是數字。",
invalidBorder : "邊框必須是數字。",
invalidUrl : "請輸入有效的URL。",
invalidRows : '欄數是必須輸入項目,只允許輸入大於0的數字。',
invalidCols : '列數是必須輸入項目,只允許輸入大於0的數字。',
invalidPadding : '內距必須是數字。',
invalidSpacing : '間距必須是數字。',
invalidBorder : '边框必须为数字。',
pleaseInput : "請輸入內容。",
invalidJson : '伺服器發生故障。',
cutError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+X)完成。',
copyError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+C)完成。',
pasteError : '您的瀏覽器安全設置不允許使用剪下操作,請使用快捷鍵(Ctrl+V)完成。',
ajaxLoading : '加載中,請稍候 ...',
uploadLoading : '上傳中,請稍候 ...',
uploadError : '上傳錯誤',
'plainpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。',
'wordpaste.comment' : '請使用快捷鍵(Ctrl+V)把內容貼到下方區域裡。',
'link.url' : 'URL',
'link.linkType' : '打開類型',
'link.newWindow' : '新窗口',
'link.selfWindow' : '本頁窗口',
'flash.url' : 'URL',
'flash.width' : '寬度',
'flash.height' : '高度',
'flash.upload' : '上傳',
'flash.viewServer' : '瀏覽',
'media.url' : 'URL',
'media.width' : '寬度',
'media.height' : '高度',
'media.autostart' : '自動播放',
'media.upload' : '上傳',
'media.viewServer' : '瀏覽',
'image.remoteImage' : '影像URL',
'image.localImage' : '上傳影像',
'image.remoteUrl' : '影像URL',
'image.localUrl' : '影像URL',
'image.size' : '影像大小',
'image.width' : '寬度',
'image.height' : '高度',
'image.resetSize' : '原始大小',
'image.align' : '對齊方式',
'image.defaultAlign' : '未設定',
'image.leftAlign' : '向左對齊',
'image.rightAlign' : '向右對齊',
'image.imgTitle' : '影像說明',
'image.viewServer' : '瀏覽...',
'filemanager.emptyFolder' : '空文件夾',
'filemanager.moveup' : '至上一級文件夾',
'filemanager.viewType' : '顯示方式:',
'filemanager.viewImage' : '縮略圖',
'filemanager.listImage' : '詳細信息',
'filemanager.orderType' : '排序方式:',
'filemanager.fileName' : '名稱',
'filemanager.fileSize' : '大小',
'filemanager.fileType' : '類型',
'insertfile.url' : 'URL',
'insertfile.title' : '文件說明',
'insertfile.upload' : '上傳',
'insertfile.viewServer' : '瀏覽',
'table.cells' : '儲存格數',
'table.rows' : '欄數',
'table.cols' : '列數',
'table.size' : '表格大小',
'table.width' : '寬度',
'table.height' : '高度',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : '內距間距',
'table.padding' : '內距',
'table.spacing' : '間距',
'table.align' : '對齊方式',
'table.textAlign' : '水平對齊',
'table.verticalAlign' : '垂直對齊',
'table.alignDefault' : '未設定',
'table.alignLeft' : '向左對齊',
'table.alignCenter' : '置中',
'table.alignRight' : '向右對齊',
'table.alignTop' : '靠上',
'table.alignMiddle' : '置中',
'table.alignBottom' : '靠下',
'table.alignBaseline' : '基線',
'table.border' : '表格邊框',
'table.borderWidth' : '邊框',
'table.borderColor' : '顏色',
'table.backgroundColor' : '背景顏色',
'map.address' : '住所: ',
'map.search' : '尋找',
'anchor.name' : '錨點名稱',
'formatblock.formatBlock' : {
h1 : '標題 1',
h2 : '標題 2',
h3 : '標題 3',
h4 : '標題 4',
p : '一般'
},
'fontname.fontName' : {
'MingLiU' : '細明體',
'PMingLiU' : '新細明體',
'DFKai-SB' : '標楷體',
'SimSun' : '宋體',
'NSimSun' : '新宋體',
'FangSong' : '仿宋體',
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Times New Roman' : 'Times New Roman',
'Courier New' : 'Courier New',
'Tahoma' : 'Tahoma',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : '单倍行距'},
{'1.5' : '1.5倍行距'},
{'2' : '2倍行距'},
{'2.5' : '2.5倍行距'},
{'3' : '3倍行距'}
],
'template.selectTemplate' : '可選樣板',
'template.replaceContent' : '取代當前內容',
'template.fileList' : {
'1.html' : '影像和文字',
'2.html' : '表格',
'3.html' : '项目清單'
}
}, 'zh_TW');
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
* Arabic Translation By daif alotaibi (http://daif.net/)
*******************************************************************************/
KindEditor.lang({
source : 'عرض المصدر',
preview : 'معاينة الصفحة',
undo : 'تراجع(Ctrl+Z)',
redo : 'إعادة التراجع(Ctrl+Y)',
cut : 'قص(Ctrl+X)',
copy : 'نسخ(Ctrl+C)',
paste : 'لصق(Ctrl+V)',
plainpaste : 'لصق كنص عادي',
wordpaste : 'لصق من مايكروسفت ورد',
selectall : 'تحديد الكل',
justifyleft : 'محاذاه لليسار',
justifycenter : 'محاذاه للوسط',
justifyright : 'محاذاه لليمين',
justifyfull : 'محاذاه تلقائية',
insertorderedlist : 'قائمة مرقمه',
insertunorderedlist : 'قائمة نقطية',
indent : 'إزاحه النص',
outdent : 'إلغاء الازاحة',
subscript : 'أسفل النص',
superscript : 'أعلى النص',
formatblock : 'Paragraph format',
fontname : 'نوع الخط',
fontsize : 'حجم الخط',
forecolor : 'لون النص',
hilitecolor : 'لون خلفية النص',
bold : 'عريض(Ctrl+B)',
italic : 'مائل(Ctrl+I)',
underline : 'خط تحت النص(Ctrl+U)',
strikethrough : 'خط على النص',
removeformat : 'إزالة التنسيق',
image : 'إدراج صورة',
flash : 'إدراج فلاش',
media : 'إدراج وسائط متعددة',
table : 'إدراج جدول',
tablecell : 'خلية',
hr : 'إدراج خط أفقي',
emoticons : 'إدراج وجه ضاحك',
link : 'رابط',
unlink : 'إزالة الرابط',
fullscreen : 'محرر ملئ الشاشة(Esc)',
about : 'حول',
print : 'طباعة',
filemanager : 'مدير الملفات',
code : 'إدراج نص برمجي',
map : 'خرائط قووقل',
lineheight : 'إرتفاع السطر',
clearhtml : 'مسح كود HTML',
pagebreak : 'إدراج فاصل صفحات',
quickformat : 'تنسيق سريع',
insertfile : 'إدراج ملف',
template : 'إدراج قالب',
anchor : 'رابط',
yes : 'موافق',
no : 'إلغاء',
close : 'إغلاق',
editImage : 'خصائص الصورة',
deleteImage : 'حذفالصورة',
editFlash : 'خصائص الفلاش',
deleteFlash : 'حذف الفلاش',
editMedia : 'خصائص الوسائط',
deleteMedia : 'حذف الوسائط',
editLink : 'خصائص الرابط',
deleteLink : 'إزالة الرابط',
tableprop : 'خصائص الجدول',
tablecellprop : 'خصائص الخلية',
tableinsert : 'إدراج جدول',
tabledelete : 'حذف جدول',
tablecolinsertleft : 'إدراج عمود لليسار',
tablecolinsertright : 'إدراج عمود لليسار',
tablerowinsertabove : 'إدراج صف للأعلى',
tablerowinsertbelow : 'إدراج صف للأسفل',
tablerowmerge : 'دمج للأسفل',
tablecolmerge : 'دمج لليمين',
tablerowsplit : 'تقسم الصف',
tablecolsplit : 'تقسيم العمود',
tablecoldelete : 'حذف العمود',
tablerowdelete : 'حذف الصف',
noColor : 'إفتراضي',
invalidImg : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: jpg,gif,bmp,png",
invalidMedia : "الرجاء إدخال رابط صحيح.\nالملفات المسموح بها: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb",
invalidWidth : "العرض يجب أن يكون رقم.",
invalidHeight : "الإرتفاع يجب أن يكون رقم.",
invalidBorder : "عرض الحد يجب أن يكون رقم.",
invalidUrl : "الرجاء إدخال رابط حيح.",
invalidRows : 'صفوف غير صحيح.',
invalidCols : 'أعمدة غير صحيحة.',
invalidPadding : 'The padding must be number.',
invalidSpacing : 'The spacing must be number.',
invalidJson : 'Invalid JSON string.',
uploadSuccess : 'تم رفع الملف بنجاح.',
cutError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+X).',
copyError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+C).',
pasteError : 'حاليا غير مدعومة من المتصفح, إستخدم إختصار لوحة المفاتيح (Ctrl+V).',
ajaxLoading : 'Loading ...',
uploadLoading : 'Uploading ...',
uploadError : 'Upload Error',
'plainpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.',
'wordpaste.comment' : 'إستخدم إختصار لوحة المفاتيح (Ctrl+V) للصق داخل النافذة.',
'link.url' : 'الرابط',
'link.linkType' : 'الهدف',
'link.newWindow' : 'نافذة جديدة',
'link.selfWindow' : 'نفس النافذة',
'flash.url' : 'الرابط',
'flash.width' : 'العرض',
'flash.height' : 'الإرتفاع',
'flash.upload' : 'رفع',
'flash.viewServer' : 'أستعراض',
'media.url' : 'الرابط',
'media.width' : 'العرض',
'media.height' : 'الإرتفاع',
'media.autostart' : 'تشغيل تلقائي',
'media.upload' : 'رفع',
'media.viewServer' : 'أستعراض',
'image.remoteImage' : 'إدراج الرابط',
'image.localImage' : 'رفع',
'image.remoteUrl' : 'الرابط',
'image.localUrl' : 'الملف',
'image.size' : 'الحجم',
'image.width' : 'العرض',
'image.height' : 'الإرتفاع',
'image.resetSize' : 'إستعادة الأبعاد',
'image.align' : 'محاذاة',
'image.defaultAlign' : 'الإفتراضي',
'image.leftAlign' : 'اليسار',
'image.rightAlign' : 'اليمين',
'image.imgTitle' : 'العنوان',
'image.viewServer' : 'أستعراض',
'filemanager.emptyFolder' : 'فارغ',
'filemanager.moveup' : 'المجلد الأب',
'filemanager.viewType' : 'العرض: ',
'filemanager.viewImage' : 'مصغرات',
'filemanager.listImage' : 'قائمة',
'filemanager.orderType' : 'الترتيب: ',
'filemanager.fileName' : 'بالإسم',
'filemanager.fileSize' : 'بالحجم',
'filemanager.fileType' : 'بالنوع',
'insertfile.url' : 'الرابط',
'insertfile.title' : 'العنوان',
'insertfile.upload' : 'رفع',
'insertfile.viewServer' : 'أستعراض',
'table.cells' : 'خلايا',
'table.rows' : 'صفوف',
'table.cols' : 'أعمدة',
'table.size' : 'الأبعاد',
'table.width' : 'العرض',
'table.height' : 'الإرتفاع',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : 'الخارج',
'table.padding' : 'الداخل',
'table.spacing' : 'الفراغات',
'table.align' : 'محاذاه',
'table.textAlign' : 'افقى',
'table.verticalAlign' : 'رأسي',
'table.alignDefault' : 'إفتراضي',
'table.alignLeft' : 'يسار',
'table.alignCenter' : 'وسط',
'table.alignRight' : 'يمين',
'table.alignTop' : 'أعلى',
'table.alignMiddle' : 'منتصف',
'table.alignBottom' : 'أسفل',
'table.alignBaseline' : 'Baseline',
'table.border' : 'الحدود',
'table.borderWidth' : 'العرض',
'table.borderColor' : 'اللون',
'table.backgroundColor' : 'الخلفية',
'map.address' : 'العنوان: ',
'map.search' : 'بحث',
'anchor.name' : 'إسم الرابط',
'formatblock.formatBlock' : {
h1 : 'عنوان 1',
h2 : 'عنوان 2',
h3 : 'عنوان 3',
h4 : 'عنوان 4',
p : 'عادي'
},
'fontname.fontName' : {
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Comic Sans MS' : 'Comic Sans MS',
'Courier New' : 'Courier New',
'Garamond' : 'Garamond',
'Georgia' : 'Georgia',
'Tahoma' : 'Tahoma',
'Times New Roman' : 'Times New Roman',
'Trebuchet MS' : 'Trebuchet MS',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : 'إرتفاع السطر 1'},
{'1.5' : 'إرتفاع السطر 1.5'},
{'2' : 'إرتفاع السطر 2'},
{'2.5' : 'إرتفاع السطر 2.5'},
{'3' : 'إرتفاع السطر 3'}
],
'template.selectTemplate' : 'قالب',
'template.replaceContent' : 'إستبدال المحتوى الحالي',
'template.fileList' : {
'1.html' : 'صورة ونص',
'2.html' : 'جدول',
'3.html' : 'قائمة'
}
}, 'ar');
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'HTML代码',
preview : '预览',
undo : '后退(Ctrl+Z)',
redo : '前进(Ctrl+Y)',
cut : '剪切(Ctrl+X)',
copy : '复制(Ctrl+C)',
paste : '粘贴(Ctrl+V)',
plainpaste : '粘贴为无格式文本',
wordpaste : '从Word粘贴',
selectall : '全选(Ctrl+A)',
justifyleft : '左对齐',
justifycenter : '居中',
justifyright : '右对齐',
justifyfull : '两端对齐',
insertorderedlist : '编号',
insertunorderedlist : '项目符号',
indent : '增加缩进',
outdent : '减少缩进',
subscript : '下标',
superscript : '上标',
formatblock : '段落',
fontname : '字体',
fontsize : '文字大小',
forecolor : '文字颜色',
hilitecolor : '文字背景',
bold : '粗体(Ctrl+B)',
italic : '斜体(Ctrl+I)',
underline : '下划线(Ctrl+U)',
strikethrough : '删除线',
removeformat : '删除格式',
image : '图片',
flash : 'Flash',
media : '视音频',
table : '表格',
tablecell : '单元格',
hr : '插入横线',
emoticons : '插入表情',
link : '超级链接',
unlink : '取消超级链接',
fullscreen : '全屏显示(Esc)',
about : '关于',
print : '打印(Ctrl+P)',
filemanager : '浏览服务器',
code : '插入程序代码',
map : 'Google地图',
lineheight : '行距',
clearhtml : '清理HTML代码',
pagebreak : '插入分页符',
quickformat : '一键排版',
insertfile : '插入文件',
template : '插入模板',
anchor : '锚点',
yes : '确定',
no : '取消',
close : '关闭',
editImage : '图片属性',
deleteImage : '删除图片',
editFlash : 'Flash属性',
deleteFlash : '删除Flash',
editMedia : '视音频属性',
deleteMedia : '删除视音频',
editLink : '超级链接属性',
deleteLink : '取消超级链接',
editAnchor : '锚点属性',
deleteAnchor : '删除锚点',
tableprop : '表格属性',
tablecellprop : '单元格属性',
tableinsert : '插入表格',
tabledelete : '删除表格',
tablecolinsertleft : '左侧插入列',
tablecolinsertright : '右侧插入列',
tablerowinsertabove : '上方插入行',
tablerowinsertbelow : '下方插入行',
tablerowmerge : '向下合并单元格',
tablecolmerge : '向右合并单元格',
tablerowsplit : '拆分行',
tablecolsplit : '拆分列',
tablecoldelete : '删除列',
tablerowdelete : '删除行',
noColor : '无颜色',
invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。",
invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
invalidWidth : "宽度必须为数字。",
invalidHeight : "高度必须为数字。",
invalidBorder : "边框必须为数字。",
invalidUrl : "请输入有效的URL地址。",
invalidRows : '行数为必选项,只允许输入大于0的数字。',
invalidCols : '列数为必选项,只允许输入大于0的数字。',
invalidPadding : '边距必须为数字。',
invalidSpacing : '间距必须为数字。',
invalidJson : '服务器发生故障。',
uploadSuccess : '上传成功。',
cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。',
copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。',
pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。',
ajaxLoading : '加载中,请稍候 ...',
uploadLoading : '上传中,请稍候 ...',
uploadError : '上传错误',
'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
'link.url' : 'URL',
'link.linkType' : '打开类型',
'link.newWindow' : '新窗口',
'link.selfWindow' : '当前窗口',
'flash.url' : 'URL',
'flash.width' : '宽度',
'flash.height' : '高度',
'flash.upload' : '上传',
'flash.viewServer' : '浏览',
'media.url' : 'URL',
'media.width' : '宽度',
'media.height' : '高度',
'media.autostart' : '自动播放',
'media.upload' : '上传',
'media.viewServer' : '浏览',
'image.remoteImage' : '远程图片',
'image.localImage' : '本地上传',
'image.remoteUrl' : '图片地址',
'image.localUrl' : '图片地址',
'image.size' : '图片大小',
'image.width' : '宽',
'image.height' : '高',
'image.resetSize' : '重置大小',
'image.align' : '对齐方式',
'image.defaultAlign' : '默认方式',
'image.leftAlign' : '左对齐',
'image.rightAlign' : '右对齐',
'image.imgTitle' : '图片说明',
'image.viewServer' : '浏览...',
'filemanager.emptyFolder' : '空文件夹',
'filemanager.moveup' : '移到上一级文件夹',
'filemanager.viewType' : '显示方式:',
'filemanager.viewImage' : '缩略图',
'filemanager.listImage' : '详细信息',
'filemanager.orderType' : '排序方式:',
'filemanager.fileName' : '名称',
'filemanager.fileSize' : '大小',
'filemanager.fileType' : '类型',
'insertfile.url' : 'URL',
'insertfile.title' : '文件说明',
'insertfile.upload' : '上传',
'insertfile.viewServer' : '浏览',
'table.cells' : '单元格数',
'table.rows' : '行数',
'table.cols' : '列数',
'table.size' : '大小',
'table.width' : '宽度',
'table.height' : '高度',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : '边距间距',
'table.padding' : '边距',
'table.spacing' : '间距',
'table.align' : '对齐方式',
'table.textAlign' : '水平对齐',
'table.verticalAlign' : '垂直对齐',
'table.alignDefault' : '默认',
'table.alignLeft' : '左对齐',
'table.alignCenter' : '居中',
'table.alignRight' : '右对齐',
'table.alignTop' : '顶部',
'table.alignMiddle' : '中部',
'table.alignBottom' : '底部',
'table.alignBaseline' : '基线',
'table.border' : '边框',
'table.borderWidth' : '边框',
'table.borderColor' : '颜色',
'table.backgroundColor' : '背景颜色',
'map.address' : '地址: ',
'map.search' : '搜索',
'anchor.name' : '锚点名称',
'formatblock.formatBlock' : {
h1 : '标题 1',
h2 : '标题 2',
h3 : '标题 3',
h4 : '标题 4',
p : '正 文'
},
'fontname.fontName' : {
'SimSun' : '宋体',
'NSimSun' : '新宋体',
'FangSong_GB2312' : '仿宋_GB2312',
'KaiTi_GB2312' : '楷体_GB2312',
'SimHei' : '黑体',
'Microsoft YaHei' : '微软雅黑',
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Times New Roman' : 'Times New Roman',
'Courier New' : 'Courier New',
'Tahoma' : 'Tahoma',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : '单倍行距'},
{'1.5' : '1.5倍行距'},
{'2' : '2倍行距'},
{'2.5' : '2.5倍行距'},
{'3' : '3倍行距'}
],
'template.selectTemplate' : '可选模板',
'template.replaceContent' : '替换当前内容',
'template.fileList' : {
'1.html' : '图片和文字',
'2.html' : '表格',
'3.html' : '项目编号'
}
}, 'zh_CN');
| JavaScript |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.lang({
source : 'Source',
preview : 'Preview',
undo : 'Undo(Ctrl+Z)',
redo : 'Redo(Ctrl+Y)',
cut : 'Cut(Ctrl+X)',
copy : 'Copy(Ctrl+C)',
paste : 'Paste(Ctrl+V)',
plainpaste : 'Paste as plain text',
wordpaste : 'Paste from Word',
selectall : 'Select all',
justifyleft : 'Align left',
justifycenter : 'Align center',
justifyright : 'Align right',
justifyfull : 'Align full',
insertorderedlist : 'Ordered list',
insertunorderedlist : 'Unordered list',
indent : 'Increase indent',
outdent : 'Decrease indent',
subscript : 'Subscript',
superscript : 'Superscript',
formatblock : 'Paragraph format',
fontname : 'Font family',
fontsize : 'Font size',
forecolor : 'Text color',
hilitecolor : 'Highlight color',
bold : 'Bold(Ctrl+B)',
italic : 'Italic(Ctrl+I)',
underline : 'Underline(Ctrl+U)',
strikethrough : 'Strikethrough',
removeformat : 'Remove format',
image : 'Image',
flash : 'Flash',
media : 'Embeded media',
table : 'Table',
tablecell : 'Cell',
hr : 'Insert horizontal line',
emoticons : 'Insert emoticon',
link : 'Link',
unlink : 'Unlink',
fullscreen : 'Toggle fullscreen mode(Esc)',
about : 'About',
print : 'Print',
filemanager : 'File Manager',
code : 'Insert code',
map : 'Google Maps',
lineheight : 'Line height',
clearhtml : 'Clear HTML code',
pagebreak : 'Insert Page Break',
quickformat : 'Quick Format',
insertfile : 'Insert file',
template : 'Insert Template',
anchor : 'Anchor',
yes : 'OK',
no : 'Cancel',
close : 'Close',
editImage : 'Image properties',
deleteImage : 'Delete image',
editFlash : 'Flash properties',
deleteFlash : 'Delete flash',
editMedia : 'Media properties',
deleteMedia : 'Delete media',
editLink : 'Link properties',
deleteLink : 'Unlink',
tableprop : 'Table properties',
tablecellprop : 'Cell properties',
tableinsert : 'Insert table',
tabledelete : 'Delete table',
tablecolinsertleft : 'Insert column left',
tablecolinsertright : 'Insert column right',
tablerowinsertabove : 'Insert row above',
tablerowinsertbelow : 'Insert row below',
tablerowmerge : 'Merge down',
tablecolmerge : 'Merge right',
tablerowsplit : 'Split row',
tablecolsplit : 'Split column',
tablecoldelete : 'Delete column',
tablerowdelete : 'Delete row',
noColor : 'Default',
invalidImg : "Please type valid URL.\nAllowed file extension: jpg,gif,bmp,png",
invalidMedia : "Please type valid URL.\nAllowed file extension: swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb",
invalidWidth : "The width must be number.",
invalidHeight : "The height must be number.",
invalidBorder : "The border must be number.",
invalidUrl : "Please type valid URL.",
invalidRows : 'Invalid rows.',
invalidCols : 'Invalid columns.',
invalidPadding : 'The padding must be number.',
invalidSpacing : 'The spacing must be number.',
invalidJson : 'Invalid JSON string.',
uploadSuccess : 'Upload success.',
cutError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+X) instead.',
copyError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+C) instead.',
pasteError : 'Currently not supported by your browser, use keyboard shortcut(Ctrl+V) instead.',
ajaxLoading : 'Loading ...',
uploadLoading : 'Uploading ...',
uploadError : 'Upload Error',
'plainpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.',
'wordpaste.comment' : 'Use keyboard shortcut(Ctrl+V) to paste the text into the window.',
'link.url' : 'URL',
'link.linkType' : 'Target',
'link.newWindow' : 'New window',
'link.selfWindow' : 'Same window',
'flash.url' : 'URL',
'flash.width' : 'Width',
'flash.height' : 'Height',
'flash.upload' : 'Upload',
'flash.viewServer' : 'Browse',
'media.url' : 'URL',
'media.width' : 'Width',
'media.height' : 'Height',
'media.autostart' : 'Auto start',
'media.upload' : 'Upload',
'media.viewServer' : 'Browse',
'image.remoteImage' : 'Insert URL',
'image.localImage' : 'Upload',
'image.remoteUrl' : 'URL',
'image.localUrl' : 'File',
'image.size' : 'Size',
'image.width' : 'Width',
'image.height' : 'Height',
'image.resetSize' : 'Reset dimensions',
'image.align' : 'Align',
'image.defaultAlign' : 'Default',
'image.leftAlign' : 'Left',
'image.rightAlign' : 'Right',
'image.imgTitle' : 'Title',
'image.viewServer' : 'Browse',
'filemanager.emptyFolder' : 'Blank',
'filemanager.moveup' : 'Parent folder',
'filemanager.viewType' : 'Display: ',
'filemanager.viewImage' : 'Thumbnails',
'filemanager.listImage' : 'List',
'filemanager.orderType' : 'Sorting: ',
'filemanager.fileName' : 'By name',
'filemanager.fileSize' : 'By size',
'filemanager.fileType' : 'By type',
'insertfile.url' : 'URL',
'insertfile.title' : 'Title',
'insertfile.upload' : 'Upload',
'insertfile.viewServer' : 'Browse',
'table.cells' : 'Cells',
'table.rows' : 'Rows',
'table.cols' : 'Columns',
'table.size' : 'Dimensions',
'table.width' : 'Width',
'table.height' : 'Height',
'table.percent' : '%',
'table.px' : 'px',
'table.space' : 'Space',
'table.padding' : 'Padding',
'table.spacing' : 'Spacing',
'table.align' : 'Align',
'table.textAlign' : 'Horizontal',
'table.verticalAlign' : 'Vertical',
'table.alignDefault' : 'Default',
'table.alignLeft' : 'Left',
'table.alignCenter' : 'Center',
'table.alignRight' : 'Right',
'table.alignTop' : 'Top',
'table.alignMiddle' : 'Middle',
'table.alignBottom' : 'Bottom',
'table.alignBaseline' : 'Baseline',
'table.border' : 'Border',
'table.borderWidth' : 'Width',
'table.borderColor' : 'Color',
'table.backgroundColor' : 'Background',
'map.address' : 'Address: ',
'map.search' : 'Search',
'anchor.name' : 'Anchor name',
'formatblock.formatBlock' : {
h1 : 'Heading 1',
h2 : 'Heading 2',
h3 : 'Heading 3',
h4 : 'Heading 4',
p : 'Normal'
},
'fontname.fontName' : {
'Arial' : 'Arial',
'Arial Black' : 'Arial Black',
'Comic Sans MS' : 'Comic Sans MS',
'Courier New' : 'Courier New',
'Garamond' : 'Garamond',
'Georgia' : 'Georgia',
'Tahoma' : 'Tahoma',
'Times New Roman' : 'Times New Roman',
'Trebuchet MS' : 'Trebuchet MS',
'Verdana' : 'Verdana'
},
'lineheight.lineHeight' : [
{'1' : 'Line height 1'},
{'1.5' : 'Line height 1.5'},
{'2' : 'Line height 2'},
{'2.5' : 'Line height 2.5'},
{'3' : 'Line height 3'}
],
'template.selectTemplate' : 'Template',
'template.replaceContent' : 'Replace current content',
'template.fileList' : {
'1.html' : 'Image and Text',
'2.html' : 'Table',
'3.html' : 'List'
}
}, 'en');
| JavaScript |
/*
* jQuery treeTable Plugin VERSION
* http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/
*
* Copyright 2011, Ludo van den Boom
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function($) {
// Helps to make options available to all functions
// TODO: This gives problems when there are both expandable and non-expandable
// trees on a page. The options shouldn't be global to all these instances!
var options;
var defaultPaddingLeft;
var persistStore;
$.fn.treeTable = function(opts) {
options = $.extend({}, $.fn.treeTable.defaults, opts);
if(options.persist) {
persistStore = new Persist.Store(options.persistStoreName);
}
return this.each(function() {
$(this).addClass("treeTable").find("tbody tr").each(function() {
// Skip initialized nodes.
if (!$(this).hasClass('initialized')) {
var isRootNode = ($(this)[0].className.search(options.childPrefix) == -1);
// To optimize performance of indentation, I retrieve the padding-left
// value of the first root node. This way I only have to call +css+
// once.
if (isRootNode && isNaN(defaultPaddingLeft)) {
defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
}
// Set child nodes to initial state if we're in expandable mode.
if(!isRootNode && options.expandable && options.initialState == "collapsed") {
$(this).addClass('ui-helper-hidden');
}
// If we're not in expandable mode, initialize all nodes.
// If we're in expandable mode, only initialize root nodes.
if(!options.expandable || isRootNode) {
initialize($(this));
}
}
});
});
};
$.fn.treeTable.defaults = {
childPrefix: "child-of-",
clickableNodeNames: false,
expandable: true,
indent: 19,
initialState: "collapsed",
onNodeShow: null,
onNodeHide: null,
treeColumn: 0,
persist: false,
persistStoreName: 'treeTable',
stringExpand: "Expand",
stringCollapse: "Collapse"
};
//Expand all nodes
$.fn.expandAll = function() {
$(this).find("tr").each(function() {
$(this).expand();
});
};
//Collapse all nodes
$.fn.collapseAll = function() {
$(this).find("tr").each(function() {
$(this).collapse();
});
};
// Recursively hide all node's children in a tree
$.fn.collapse = function() {
return this.each(function() {
$(this).removeClass("expanded").addClass("collapsed");
if (options.persist) {
persistNodeState($(this));
}
childrenOf($(this)).each(function() {
if(!$(this).hasClass("collapsed")) {
$(this).collapse();
}
$(this).addClass('ui-helper-hidden');
if($.isFunction(options.onNodeHide)) {
options.onNodeHide.call(this);
}
});
});
};
// Recursively show all node's children in a tree
$.fn.expand = function() {
return this.each(function() {
$(this).removeClass("collapsed").addClass("expanded");
if (options.persist) {
persistNodeState($(this));
}
childrenOf($(this)).each(function() {
initialize($(this));
if($(this).is(".expanded.parent")) {
$(this).expand();
}
$(this).removeClass('ui-helper-hidden');
if($.isFunction(options.onNodeShow)) {
options.onNodeShow.call(this);
}
});
});
};
// Reveal a node by expanding all ancestors
$.fn.reveal = function() {
$(ancestorsOf($(this)).reverse()).each(function() {
initialize($(this));
$(this).expand().show();
});
return this;
};
// Add an entire branch to +destination+
$.fn.appendBranchTo = function(destination) {
var node = $(this);
var parent = parentOf(node);
var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });
// Conditions:
// 1: +node+ should not be inserted in a location in a branch if this would
// result in +node+ being an ancestor of itself.
// 2: +node+ should not have a parent OR the destination should not be the
// same as +node+'s current parent (this last condition prevents +node+
// from being moved to the same location where it already is).
// 3: +node+ should not be inserted as a child of +node+ itself.
if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation
if(parent) { node.removeClass(options.childPrefix + parent[0].id); }
node.addClass(options.childPrefix + destination.id);
move(node, destination); // Recursively move nodes to new location
indent(node, ancestorsOf(node).length * options.indent);
}
return this;
};
// Add reverse() function from JS Arrays
$.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
// Toggle an entire branch
$.fn.toggleBranch = function() {
if($(this).hasClass("collapsed")) {
$(this).expand();
} else {
$(this).collapse();
}
return this;
};
// === Private functions
function ancestorsOf(node) {
var ancestors = [];
while(node = parentOf(node)) {
ancestors[ancestors.length] = node[0];
}
return ancestors;
};
function childrenOf(node) {
return $(node).siblings("tr." + options.childPrefix + node[0].id);
};
function getPaddingLeft(node) {
var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
}
function indent(node, value) {
var cell = $(node.children("td")[options.treeColumn]);
cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";
childrenOf(node).each(function() {
indent($(this), value);
});
};
function initialize(node) {
if(!node.hasClass("initialized")) {
node.addClass("initialized");
var childNodes = childrenOf(node);
if(!node.hasClass("parent") && childNodes.length > 0) {
node.addClass("parent");
}
if(node.hasClass("parent")) {
var cell = $(node.children("td")[options.treeColumn]);
var padding = getPaddingLeft(cell) + options.indent;
childNodes.each(function() {
$(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
});
if(options.expandable) {
var newLink = '<a href="#" title="' + options.stringExpand + '" style="margin-left: -' + options.indent + 'px; padding-left: ' + options.indent + 'px" class="expander"></a>';
if(options.clickableNodeNames) {
cell.wrapInner(newLink);
} else {
cell.prepend(newLink);
}
$(cell[0].firstChild).click(function() { node.toggleBranch(); return false; }).mousedown(function() { return false; });
$(cell[0].firstChild).keydown(function(e) { if(e.keyCode == 13) { node.toggleBranch(); return false; }});
if(options.clickableNodeNames) {
cell[0].style.cursor = "pointer";
$(cell).click(function(e) {
// Don't double-toggle if the click is on the existing expander icon
if (e.target.className != 'expander') {
node.toggleBranch();
}
});
}
if (options.persist && getPersistedNodeState(node)) {
node.addClass('expanded');
}
// Check for a class set explicitly by the user, otherwise set the default class
if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
node.addClass(options.initialState);
}
if(node.hasClass("expanded")) {
node.expand();
}
}
}
}
};
function move(node, destination) {
node.insertAfter(destination);
childrenOf(node).reverse().each(function() { move($(this), node[0]); });
};
function parentOf(node) {
var classNames = node[0].className.split(' ');
for(var key=0; key<classNames.length; key++) {
if(classNames[key].match(options.childPrefix)) {
return $(node).siblings("#" + classNames[key].substring(options.childPrefix.length));
}
}
return null;
};
//saving state functions, not critical, so will not generate alerts on error
function persistNodeState(node) {
if(node.hasClass('expanded')) {
try {
persistStore.set(node.attr('id'), '1');
} catch (err) {
}
} else {
try {
persistStore.remove(node.attr('id'));
} catch (err) {
}
}
}
function getPersistedNodeState(node) {
try {
return persistStore.get(node.attr('id')) == '1';
} catch (err) {
return false;
}
}
})(jQuery);
| JavaScript |
var regexEnum =
{
intege:"^-?[1-9]\\d*$", //整数
intege1:"^[1-9]\\d*$", //正整数
intege2:"^-[1-9]\\d*$", //负整数
num:"^([+-]?)\\d*\\.?\\d+$", //数字
num1:"^[1-9]\\d*|0$", //正数(正整数 + 0)
num2:"^-[1-9]\\d*|0$", //负数(负整数 + 0)
decmal:"^([+-]?)\\d*\\.\\d+$", //浮点数
decmal1:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*$", //正浮点数
decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$", //负浮点数
decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$", //浮点数
decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$", //非负浮点数(正浮点数 + 0)
decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$", //非正浮点数(负浮点数 + 0)
email:"^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$", //邮件
color:"^[a-fA-F0-9]{6}$", //颜色
url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$", //url
chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", //仅中文
ascii:"^[\\x00-\\xFF]+$", //仅ACSII字符
zipcode:"^\\d{6}$", //邮编
mobile:"^(1)[0-9]{10}$", //手机
ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$", //ip地址
ip4_local:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)|localhost$", //支持本地localhost格式的ip地址验证
notempty:"^\\S+$", //非空
picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$", //图片
rar:"(.*)\\.(rar|zip|7zip|tgz)$", //压缩文件
date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$", //日期
qq:"^[1-9]*[1-9][0-9]*$", //QQ号码
tel:"^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$", //电话号码的函数(包括验证国内区号,国际区号,分机号)
username:"^\\w+$", //用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串
letter:"^[A-Za-z]+$", //字母
letter_u:"^[A-Z]+$", //大写字母
letter_l:"^[a-z]+$", //小写字母
idcard:"^[1-9]([0-9]{14}|[0-9]{17})$", //身份证
ps_username:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D_\\w]+$" //中文、字母、数字 _
}
function isCardID(sId){
var iSum=0 ;
var info="" ;
if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
sId=sId.replace(/x$/i,"a");
if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
var d=new Date(sBirthday.replace(/-/g,"/")) ;
if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
if(iSum%11!=1) return "你输入的身份证号非法";
return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")
}
//短时间,形如 (13:04:06)
function isTime(str)
{
var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
if (a == null) {return false}
if (a[1]>24 || a[3]>60 || a[4]>60)
{
return false;
}
return true;
}
//短日期,形如 (2003-12-05)
function isDate(str)
{
var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
if(r==null)return false;
var d= new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
//长时间,形如 (2003-12-05 13:04:06)
function isDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var r = str.match(reg);
if(r==null) return false;
var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
} | JavaScript |
//====================================================================================================
// [插件名称] jQuery formValidator
// [作者网名] 猫冬
// [邮 箱] wzmaodong@126.com
// [作者博客] http://wzmaodong.cnblogs.com
// [更新日期] 2008-01-24
// [版 本 号] ver3.3
// [修改记录] PHPCMS团队修正用于JQUERY 1.4
// [注 意] 所有参数使用小写字母
//====================================================================================================
var jQuery_formValidator_initConfig; (function($) {
$.formValidator = {
sustainType: function(id, setting) {
var elem = $("#" + id).get(0);
var srcTag = elem.tagName;
var stype = elem.type;
switch (setting.validatetype) {
case "InitValidator":
return true;
case "InputValidator":
if (srcTag == "INPUT" || srcTag == "TEXTAREA" || srcTag == "SELECT") {
return true
} else {
return false
}
case "CompareValidator":
if (srcTag == "INPUT" || srcTag == "TEXTAREA") {
if (stype == "checkbox" || stype == "radio") {
return false
} else {
return true
}
}
return false;
case "AjaxValidator":
if (stype == "text" || stype == "textarea" || stype == "file" || stype == "password" || stype == "select-one") {
return true
} else {
return false
}
case "RegexValidator":
if (srcTag == "INPUT" || srcTag == "TEXTAREA") {
if (stype == "checkbox" || stype == "radio") {
return false
} else {
return true
}
}
return false;
case "FunctionValidator":
return true
}
},
initConfig: function(controlOptions) {
var settings = {
debug: false,
validatorgroup: "1",
alertmessage: false,
validobjectids: "",
forcevalid: false,
onsuccess: function() {
return true
},
onerror: function() {},
submitonce: false,
formid: "",
autotip: false,
tidymode: false,
errorfocus: true,
wideword: true
};
controlOptions = controlOptions || {};
$.extend(settings, controlOptions);
if (settings.tidymode) {
settings.errorfocus = false
};
if (settings.formid != "") {
$("#" + settings.formid).submit(function() {
return $.formValidator.pageIsValid("1")
})
};
if (jQuery_formValidator_initConfig == null) {
jQuery_formValidator_initConfig = new Array()
}
jQuery_formValidator_initConfig.push(settings)
},
appendValid: function(id, setting) {
if (!$.formValidator.sustainType(id, setting)) return - 1;
var srcjo = $("#" + id).get(0);
if (setting.validatetype == "InitValidator" || srcjo.settings == undefined) {
srcjo.settings = new Array()
}
var len = srcjo.settings.push(setting);
srcjo.settings[len - 1].index = len - 1;
return len - 1
},
getInitConfig: function(validatorgroup) {
if (jQuery_formValidator_initConfig != null) {
for (i = 0; i < jQuery_formValidator_initConfig.length; i++) {
if (validatorgroup == jQuery_formValidator_initConfig[i].validatorgroup) {
return jQuery_formValidator_initConfig[i]
}
}
}
return null
},
triggerValidate: function(returnObj) {
switch (returnObj.setting.validatetype) {
case "InputValidator":
$.formValidator.inputValid(returnObj);
break;
case "CompareValidator":
$.formValidator.compareValid(returnObj);
break;
case "AjaxValidator":
$.formValidator.ajaxValid(returnObj);
break;
case "RegexValidator":
$.formValidator.regexValid(returnObj);
break;
case "FunctionValidator":
$.formValidator.functionValid(returnObj);
break
}
},
setTipState: function(elem, showclass, showmsg) {
var setting0 = elem.settings[0];
var initConfig = $.formValidator.getInitConfig(setting0.validatorgroup);
var tip = $("#" + setting0.tipid);
if (showmsg == null || showmsg == "") {
tip.hide()
} else {
if (initConfig.tidymode) {
$("#fv_content").html(showmsg);
elem.Tooltip = showmsg;
if (showclass != "onError") {
tip.hide()
}
}
tip.removeClass();
tip.addClass(showclass);
tip.html(showmsg)
}
},
resetTipState: function(validatorgroup) {
var initConfig = $.formValidator.getInitConfig(validatorgroup);
$(initConfig.validobjectids).each(function() {
$.formValidator.setTipState(this, "onShow", this.settings[0].onshow)
})
},
setFailState: function(tipid, showmsg) {
var tip = $("#" + tipid);
tip.removeClass();
tip.addClass("onError");
tip.html(showmsg)
},
showMessage: function(returnObj) {
var id = returnObj.id;
var elem = $("#" + id).get(0);
var isvalid = returnObj.isvalid;
var setting = returnObj.setting;
var showmsg = "",
showclass = "";
var settings = $("#" + id).get(0).settings;
var intiConfig = $.formValidator.getInitConfig(settings[0].validatorgroup);
if (!isvalid) {
showclass = "onError";
if (setting.validatetype == "AjaxValidator") {
if (setting.lastValid == "") {
showclass = "onLoad";
showmsg = setting.onwait
} else {
showmsg = setting.onerror
}
} else {
showmsg = (returnObj.errormsg == "" ? setting.onerror: returnObj.errormsg)
}
if (intiConfig.alertmessage) {
var elem = $("#" + id).get(0);
if (elem.validoldvalue != $(elem).val()) {
alert(showmsg)
}
} else {
$.formValidator.setTipState(elem, showclass, showmsg)
}
} else {
showmsg = $.formValidator.isEmpty(id) ? setting.onempty: setting.oncorrect;
$.formValidator.setTipState(elem, "onCorrect", showmsg)
}
return showmsg
},
showAjaxMessage: function(returnObj) {
var setting = returnObj.setting;
var elem = $("#" + returnObj.id).get(0);
if ((elem.settings[returnObj.ajax].cached ? elem.validoldvalue != $(elem).val() : true)) {
$.formValidator.ajaxValid(returnObj)
} else {
if (setting.isvalid != undefined && !setting.isvalid) {
elem.lastshowclass = "onError";
elem.lastshowmsg = setting.onerror
}
$.formValidator.setTipState(elem, elem.lastshowclass, elem.lastshowmsg)
}
},
getLength: function(id) {
var srcjo = $("#" + id);
var elem = srcjo.get(0);
sType = elem.type;
var len = 0;
switch (sType) {
case "text":
case "hidden":
case "password":
case "textarea":
case "file":
var val = srcjo.val();
var initConfig = $.formValidator.getInitConfig(elem.settings[0].validatorgroup);
if (initConfig.wideword) {
for (var i = 0; i < val.length; i++) {
if (val.charCodeAt(i) >= 0x4e00 && val.charCodeAt(i) <= 0x9fa5) {
len += 2
} else {
len++
}
}
} else {
len = val.length
}
break;
case "checkbox":
case "radio":
len = $("input[type='" + sType + "'][name='" + srcjo.attr("name") + "']:checked").length;
break;
case "select-one":
len = elem.options ? elem.options.selectedIndex: -1;
break;
case "select-multiple":
len = $("select[name=" + elem.name + "] option:selected").length;
break
}
return len
},
isEmpty: function(id) {
if ($("#" + id).get(0).settings[0].empty && $.formValidator.getLength(id) == 0) {
return true
} else {
return false
}
},
isOneValid: function(id) {
return $.formValidator.oneIsValid(id, 1).isvalid
},
oneIsValid: function(id, index) {
var returnObj = new Object();
returnObj.id = id;
returnObj.ajax = -1;
returnObj.errormsg = "";
var elem = $("#" + id).get(0);
var settings = elem.settings;
var settingslen = settings.length;
if (settingslen == 1) {
settings[0].bind = false
}
if (!settings[0].bind) {
return null
}
for (var i = 0; i < settingslen; i++) {
if (i == 0) {
if ($.formValidator.isEmpty(id)) {
returnObj.isvalid = true;
returnObj.setting = settings[0];
break
}
continue
}
returnObj.setting = settings[i];
if (settings[i].validatetype != "AjaxValidator") {
$.formValidator.triggerValidate(returnObj)
} else {
returnObj.ajax = i
}
if (!settings[i].isvalid) {
returnObj.isvalid = false;
returnObj.setting = settings[i];
break
} else {
returnObj.isvalid = true;
returnObj.setting = settings[0];
if (settings[i].validatetype == "AjaxValidator") break
}
}
return returnObj
},
pageIsValid: function(validatorgroup) {
if (validatorgroup == null || validatorgroup == undefined) {
validatorgroup = "1"
};
var isvalid = true;
var thefirstid = "",
thefirsterrmsg;
var returnObj, setting;
var error_tip = "^";
var initConfig = $.formValidator.getInitConfig(validatorgroup);
var jqObjs = $(initConfig.validobjectids);
jqObjs.each(function(i, elem) {
if (elem.settings[0].bind) {
returnObj = $.formValidator.oneIsValid(elem.id, 1);
if (returnObj) {
var tipid = elem.settings[0].tipid;
if (!returnObj.isvalid) {
isvalid = false;
if (thefirstid == "") {
thefirstid = returnObj.id;
thefirsterrmsg = (returnObj.errormsg == "" ? returnObj.setting.onerror: returnObj.errormsg)
}
}
if (!initConfig.alertmessage) {
if (error_tip.indexOf("^" + tipid + "^") == -1) {
if (!returnObj.isvalid) {
error_tip = error_tip + tipid + "^"
}
$.formValidator.showMessage(returnObj)
}
}
}
}
});
if (isvalid) {
isvalid = initConfig.onsuccess();
if (initConfig.submitonce) {
$("input[type='submit']").attr("disabled", true)
}
} else {
var obj = $("#" + thefirstid).get(0);
initConfig.onerror(thefirsterrmsg, obj);
if (thefirstid != "" && initConfig.errorfocus) {
$("#" + thefirstid).focus()
}
}
return ! initConfig.debug && isvalid
},
ajaxValid: function(returnObj) {
var id = returnObj.id;
var srcjo = $("#" + id);
var elem = srcjo.get(0);
var settings = elem.settings;
var setting = settings[returnObj.ajax];
var ls_url = setting.url;
if (srcjo.size() == 0 && settings[0].empty) {
returnObj.setting = settings[0];
returnObj.isvalid = true;
$.formValidator.showMessage(returnObj);
setting.isvalid = true;
return
}
if (setting.addidvalue) {
var parm = "clientid=" + id + "&" + id + "=" + encodeURIComponent(srcjo.val());
if (setting.getdata) {
$.each(setting.getdata,
function(i, n) {
parm += "&" + i + "=" + $('#' + n).val()
})
}
ls_url = ls_url + (ls_url.indexOf("?") > -1 ? ("&" + parm) : ("?" + parm));
if (typeof(pc_hash) != 'undefined') {
ls_url = ls_url + (ls_url.indexOf("?") > -1 ? ("&pc_hash=" + pc_hash) : ("?pc_hash=" + pc_hash))
}
}
$.ajax({
mode: "abort",
type: setting.type,
url: ls_url,
cache: setting.cache,
data: setting.data,
async: setting.async,
dataType: setting.datatype,
success: function(data) {
if (setting.success(data)) {
$.formValidator.setTipState(elem, "onCorrect", settings[0].oncorrect);
setting.isvalid = true
} else {
$.formValidator.setTipState(elem, "onError", setting.onerror);
setting.isvalid = false
}
},
complete: function() {
if (setting.buttons && setting.buttons.length > 0) {
setting.buttons.attr({
"disabled": false
})
};
setting.complete
},
beforeSend: function(xhr) {
if (setting.buttons && setting.buttons.length > 0) {
setting.buttons.attr({
"disabled": true
})
};
var isvalid = setting.beforesend(xhr);
if (isvalid) {
setting.isvalid = false;
$.formValidator.setTipState(elem, "onLoad", settings[returnObj.ajax].onwait)
}
setting.lastValid = "-1";
return isvalid
},
error: function() {
$.formValidator.setTipState(elem, "onError", setting.onerror);
setting.isvalid = false;
setting.error()
},
processData: setting.processdata
})
},
regexValid: function(returnObj) {
var id = returnObj.id;
var setting = returnObj.setting;
var srcTag = $("#" + id).get(0).tagName;
var elem = $("#" + id).get(0);
if (elem.settings[0].empty && elem.value == "") {
setting.isvalid = true
} else {
var regexpress = setting.regexp;
if (setting.datatype == "enum") {
regexpress = eval("regexEnum." + regexpress)
}
if (regexpress == undefined || regexpress == "") {
setting.isvalid = false;
return
}
setting.isvalid = (new RegExp(regexpress, setting.param)).test($("#" + id).val())
}
},
functionValid: function(returnObj) {
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#" + id);
var lb_ret = setting.fun(srcjo.val(), srcjo.get(0));
if (lb_ret != undefined) {
if (typeof lb_ret == "string") {
setting.isvalid = false;
returnObj.errormsg = lb_ret
} else {
setting.isvalid = lb_ret
}
}
},
inputValid: function(returnObj) {
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#" + id);
var elem = srcjo.get(0);
var val = srcjo.val();
var sType = elem.type;
var len = $.formValidator.getLength(id);
var empty = setting.empty,
emptyerror = false;
switch (sType) {
case "text":
case "hidden":
case "password":
case "textarea":
case "file":
if (setting.type == "size") {
empty = setting.empty;
if (!empty.leftempty) {
emptyerror = (val.replace(/^[ \s]+/, '').length != val.length)
}
if (!emptyerror && !empty.rightempty) {
emptyerror = (val.replace(/[ \s]+$/, '').length != val.length)
}
if (emptyerror && empty.emptyerror) {
returnObj.errormsg = empty.emptyerror
}
}
case "checkbox":
case "select-one":
case "select-multiple":
case "radio":
var lb_go_on = false;
if (sType == "select-one" || sType == "select-multiple") {
setting.type = "size"
}
var type = setting.type;
if (type == "size") {
if (!emptyerror) {
lb_go_on = true
}
if (lb_go_on) {
val = len
}
} else if (type == "date" || type == "datetime") {
var isok = false;
if (type == "date") {
lb_go_on = isDate(val)
};
if (type == "datetime") {
lb_go_on = isDate(val)
};
if (lb_go_on) {
val = new Date(val);
setting.min = new Date(setting.min);
setting.max = new Date(setting.max)
}
} else {
stype = (typeof setting.min);
if (stype == "number") {
val = (new Number(val)).valueOf();
if (!isNaN(val)) {
lb_go_on = true
}
}
if (stype == "string") {
lb_go_on = true
}
}
setting.isvalid = false;
if (lb_go_on) {
if (val < setting.min || val > setting.max) {
if (val < setting.min && setting.onerrormin) {
returnObj.errormsg = setting.onerrormin
}
if (val > setting.min && setting.onerrormax) {
returnObj.errormsg = setting.onerrormax
}
} else {
setting.isvalid = true
}
}
break
}
},
compareValid: function(returnObj) {
var id = returnObj.id;
var setting = returnObj.setting;
var srcjo = $("#" + id);
var desjo = $("#" + setting.desid);
var ls_datatype = setting.datatype;
setting.isvalid = false;
curvalue = srcjo.val();
ls_data = desjo.val();
if (ls_datatype == "number") {
if (!isNaN(curvalue) && !isNaN(ls_data)) {
curvalue = parseFloat(curvalue);
ls_data = parseFloat(ls_data)
} else {
return
}
}
if (ls_datatype == "date" || ls_datatype == "datetime") {
var isok = false;
if (ls_datatype == "date") {
isok = (isDate(curvalue) && isDate(ls_data))
};
if (ls_datatype == "datetime") {
isok = (isDateTime(curvalue) && isDateTime(ls_data))
};
if (isok) {
curvalue = new Date(curvalue);
ls_data = new Date(ls_data)
} else {
return
}
}
switch (setting.operateor) {
case "=":
if (curvalue == ls_data) {
setting.isvalid = true
}
break;
case "!=":
if (curvalue != ls_data) {
setting.isvalid = true
}
break;
case ">":
if (curvalue > ls_data) {
setting.isvalid = true
}
break;
case ">=":
if (curvalue >= ls_data) {
setting.isvalid = true
}
break;
case "<":
if (curvalue < ls_data) {
setting.isvalid = true
}
break;
case "<=":
if (curvalue <= ls_data) {
setting.isvalid = true
}
break
}
},
localTooltip: function(e) {
e = e || window.event;
var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft: 0);
var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop: 0);
$("#fvtt").css({
"top": (mouseY + 2) + "px",
"left": (mouseX - 40) + "px"
})
}
};
$.fn.formValidator = function(cs) {
var setting = {
validatorgroup: "1",
empty: false,
submitonce: false,
automodify: false,
onshow: "请输入内容",
onfocus: "请输入内容",
oncorrect: "输入正确",
onempty: "输入内容为空",
defaultvalue: null,
bind: true,
validatetype: "InitValidator",
tipcss: {
"left": "10px",
"top": "1px",
"height": "20px",
"width": "250px"
},
triggerevent: "blur",
forcevalid: false
};
cs = cs || {};
if (cs.validatorgroup == undefined) {
cs.validatorgroup = "1"
};
var initConfig = $.formValidator.getInitConfig(cs.validatorgroup);
if (initConfig.tidymode) {
setting.tipcss = {
"left": "2px",
"width": "22px",
"height": "22px",
"display": "none"
}
};
$.extend(true, setting, cs);
return this.each(function(e) {
var jqobj = $(this);
var setting_temp = {};
$.extend(true, setting_temp, setting);
var tip = setting_temp.tipid ? setting_temp.tipid: this.id + "Tip";
if (initConfig.autotip) {
if ($("body [id=" + tip + "]").length == 0) {
aftertip = setting_temp.relativeid ? setting_temp.relativeid: this.id;
$('#' + aftertip).parent().append("<div id='" + tip + "'></div>")
}
if (initConfig.tidymode) {
jqobj.showTooltips()
}
}
setting.tipid = tip;
$.formValidator.appendValid(this.id, setting);
var validobjectids = initConfig.validobjectids;
if (validobjectids.indexOf("#" + this.id + " ") == -1) {
initConfig.validobjectids = (validobjectids == "" ? "#" + this.id: validobjectids + ",#" + this.id)
}
if (!initConfig.alertmessage) {
$.formValidator.setTipState(this, "onShow", setting.onshow)
}
var srcTag = this.tagName.toLowerCase();
var stype = this.type;
var defaultval = setting.defaultvalue;
if (defaultval) {
jqobj.val(defaultval)
}
if (srcTag == "input" || srcTag == "textarea") {
jqobj.focus(function() {
if (!initConfig.alertmessage) {
var tipjq = $("#" + tip);
this.lastshowclass = tipjq.attr("class");
this.lastshowmsg = tipjq.html();
$.formValidator.setTipState(this, "onFocus", setting.onfocus)
}
});
jqobj.bind(setting.triggerevent,
function() {
var settings = this.settings;
var returnObj = $.formValidator.oneIsValid(this.id, 1);
if (returnObj == null) {
return
}
if (returnObj.ajax >= 0) {
$.formValidator.showAjaxMessage(returnObj)
} else {
var showmsg = $.formValidator.showMessage(returnObj);
if (!returnObj.isvalid) {
var auto = setting.automodify && (this.type == "text" || this.type == "textarea" || this.type == "file");
if (auto && !initConfig.alertmessage) {
alert(showmsg);
$.formValidator.setTipState(this, "onShow", setting.onshow)
} else {
if (initConfig.forcevalid || setting.forcevalid) {
alert(showmsg);
this.focus()
}
}
}
}
})
} else if (srcTag == "select") {
jqobj.bind("focus",
function() {
if (!initConfig.alertmessage) {
$.formValidator.setTipState(this, "onFocus", setting.onfocus)
}
});
jqobj.bind("blur",
function() {
jqobj.trigger("change")
});
jqobj.bind("change",
function() {
var returnObj = $.formValidator.oneIsValid(this.id, 1);
if (returnObj == null) {
return
}
if (returnObj.ajax >= 0) {
$.formValidator.showAjaxMessage(returnObj)
} else {
$.formValidator.showMessage(returnObj)
}
})
}
})
};
$.fn.inputValidator = function(controlOptions) {
var settings = {
isvalid: false,
min: 0,
max: 99999999999999,
type: "size",
onerror: "输入错误",
validatetype: "InputValidator",
empty: {
leftempty: true,
rightempty: true,
leftemptyerror: null,
rightemptyerror: null
},
wideword: true
};
controlOptions = controlOptions || {};
$.extend(true, settings, controlOptions);
return this.each(function() {
$.formValidator.appendValid(this.id, settings)
})
};
$.fn.compareValidator = function(controlOptions) {
var settings = {
isvalid: false,
desid: "",
operateor: "=",
onerror: "输入错误",
validatetype: "CompareValidator"
};
controlOptions = controlOptions || {};
$.extend(true, settings, controlOptions);
return this.each(function() {
$.formValidator.appendValid(this.id, settings)
})
};
$.fn.regexValidator = function(controlOptions) {
var settings = {
isvalid: false,
regexp: "",
param: "i",
datatype: "string",
onerror: "输入的格式不正确",
validatetype: "RegexValidator"
};
controlOptions = controlOptions || {};
$.extend(true, settings, controlOptions);
return this.each(function() {
$.formValidator.appendValid(this.id, settings)
})
};
$.fn.functionValidator = function(controlOptions) {
var settings = {
isvalid: true,
fun: function() {
this.isvalid = true
},
validatetype: "FunctionValidator",
onerror: "输入错误"
};
controlOptions = controlOptions || {};
$.extend(true, settings, controlOptions);
return this.each(function() {
$.formValidator.appendValid(this.id, settings)
})
};
$.fn.ajaxValidator = function(controlOptions) {
var settings = {
isvalid: false,
lastValid: "",
type: "GET",
url: "",
addidvalue: true,
datatype: "html",
data: "",
async: true,
cache: false,
cached: true,
getdata: '',
beforesend: function() {
return true
},
success: function() {
return true
},
complete: function() {},
processdata: false,
error: function() {},
buttons: null,
onerror: "服务器校验没有通过",
onwait: "正在等待服务器返回数据",
validatetype: "AjaxValidator"
};
controlOptions = controlOptions || {};
$.extend(true, settings, controlOptions);
return this.each(function() {
$.formValidator.appendValid(this.id, settings)
})
};
$.fn.defaultPassed = function(onshow) {
return this.each(function() {
var settings = this.settings;
for (var i = 1; i < settings.length; i++) {
settings[i].isvalid = true;
if (!$.formValidator.getInitConfig(settings[0].validatorgroup).alertmessage) {
var ls_style = onshow ? "onShow": "onCorrect";
$.formValidator.setTipState(this, ls_style, settings[0].oncorrect)
}
}
})
};
$.fn.unFormValidator = function(unbind) {
return this.each(function() {
this.settings[0].bind = !unbind;
if (unbind) {
$("#" + this.settings[0].tipid).hide()
} else {
$("#" + this.settings[0].tipid).show()
}
})
};
$.fn.showTooltips = function() {
if ($("body [id=fvtt]").length == 0) {
fvtt = $("<div id='fvtt' style='position:absolute;z-index:56002'></div>");
$("body").append(fvtt);
fvtt.before("<iframe src='about:blank' class='fv_iframe' scrolling='no' frameborder='0'></iframe>")
}
return this.each(function() {
jqobj = $(this);
s = $("<span class='top' id=fv_content style='display:block'></span>");
b = $("<b class='bottom' style='display:block' />");
this.tooltip = $("<span class='fv_tooltip' style='display:block'></span>").append(s).append(b).css({
"filter": "alpha(opacity:95)",
"KHTMLOpacity": "0.95",
"MozOpacity": "0.95",
"opacity": "0.95"
});
jqobj.mouseover(function(e) {
$("#fvtt").append(this.tooltip);
$("#fv_content").html(this.Tooltip);
$.formValidator.localTooltip(e)
});
jqobj.mouseout(function() {
$("#fvtt").empty()
});
jqobj.mousemove(function(e) {
$("#fv_content").html(this.Tooltip);
$.formValidator.localTooltip(e)
})
})
}
})(jQuery); | JavaScript |
(function($) {
var cachedata = {};
var arrweebox = new Array();
var weebox = function(content,options) {
var self = this;
this.dh = null;
this.mh = null;
this.dc = null;
this.dt = null;
this.db = null;
this.selector = null;
this.ajaxurl = null;
this.options = null;
this._dragging = false;
this._content = content || '';
this._options = options || {};
this._defaults = {
boxid: null,
boxclass: null,
cache: false,
type: 'dialog',
title: '',
width: 0,
height: 0,
timeout: 0,
draggable: true,
modal: true,
focus: null,
blur: null,
position: 'center',
overlay: 30,
showTitle: true,
showButton: true,
showCancel: true,
showHeader: true,
showOk: true,
isFull:true,
isCloseToHide:false,
okBtnName: '确定',
cancelBtnName: '取消',
contentType: 'text',
contentChange: false,
clickClose: false,
zIndex: 999,
animate: '',
showAnimate:'',
hideAnimate:'',
onclose: null,
onopen: null,
onready:null,
oncancel: null,
onok: null,
suggest:{url:'',tele:'',vele:'',fn:null},
select:{url:'',type:'radio', tele:'',vele:'',width:120,search:false,fn:null}
};
//初始化选项
this.initOptions = function() {
self._options = self._options || {};
self._options.animate = self._options.animate || '';
self._options.showAnimate = self._options.showAnimate || self._options.animate;
self._options.hideAnimate = self._options.hideAnimate || self._options.animate;
self._options.type = self._options.type || 'dialog';
self._options.title = self._options.title || '';
self._options.boxclass = self._options.boxclass || 'wee'+self._options.type;
self._options.contentType = self._options.contentType || "";
if (self._options.contentType == "") {
self._options.contentType = (self._content.substr(0,1) == '#') ? 'selector' : 'text';
}
self.options = $.extend({}, self._defaults, self._options);
self._options = null;
self._defaults = null;
};
//初始化弹窗Box
this.initBox = function() {
var html = '';
switch(self.options.type) {
case 'alert':
case 'select':
case 'dialog':
html = '<div class="weedialog">' +
' <div class="dialog-top">' +
' <div class="dialog-tl"></div>' +
' <div class="dialog-tc"></div>' +
' <div class="dialog-tr"></div>' +
' </div>' +
' <table width="100%" border="0" cellspacing="0" cellpadding="0" >' +
' <tr>' +
' <td class="dialog-cl"></td>' +
' <td>' +
' <div class="dialog-header">' +
' <div class="dialog-title"></div>' +
' <a href="javascript:;" onclick="return false" class="dialog-close"></a>' +
' </div>' +
' <div class="dialog-content"></div>' +
' <div class="dialog-button">' +
' <input type="button" class="dialog-ok" value="确定">' +
' <input type="button" class="dialog-cancel" value="取消">' +
' </div>' +
' </td>' +
' <td class="dialog-cr"></td>' +
' </tr>' +
' </table>' +
' <div class="dialog-bot">' +
' <div class="dialog-bl"></div>' +
' <div class="dialog-bc"></div>' +
' <div class="dialog-br"></div>' +
' </div>' +
'</div>';
break;
case 'custom':
case 'suggest':
html = '<div><div class="dialog-content"></div></div>';
break;
}
self.dh = $(html).appendTo('body').hide().css({
position: 'absolute',
overflow: 'hidden',
zIndex: self.options.zIndex
});
self.dc = self.find('.dialog-content');
self.dt = self.find('.dialog-title');
self.db = self.find('.dialog-button');
self.dhh = self.find('.dialog-header');
if (self.options.boxid) {
self.dh.attr('id', self.options.boxid);
}
if (self.options.boxclass) {
self.dh.addClass(self.options.boxclass);
}
if (self.options.height>0) {
self.dc.css('height', self.options.height);
}
if (self.options.width>0) {
self.dh.css('width', self.options.width);
}
self.dh.bgiframe();
}
//初始化遮照
this.initMask = function() {
if (self.options.modal) {
if ($.browser.msie) {
h= document.compatMode == "CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight;
w= document.compatMode == "CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth;
} else {
h= self.bheight();
w= self.bwidth();
}
self.mh = $("<div class='dialog-mask'></div>")
.appendTo('body').hide().css({
width: w,
height: h,
zIndex: self.options.zIndex-1
}).bgiframe();
}
}
//初始化弹窗内容
this.initContent = function(content) {
self.dh.find(".dialog-ok").val(self.options.okBtnName);
self.dh.find(".dialog-cancel").val(self.options.cancelBtnName);
if (self.options.title == '') {
//self.dt.hide();
//self.dt.html(self._titles[self._options.type] || '');
} else {
self.dt.html(self.options.title);
}
if (!self.options.showTitle) {
self.dt.hide();
}
if(self.options.draggable){
self.dt.css({"cursor":"move"});
}
if(!self.options.showHeader){
self.dhh.remove();
}
if (!self.options.showButton) {
self.dh.find('.dialog-button').hide();
}
if (!self.options.showCancel) {
self.dh.find('.dialog-cancel').hide();
}
if (!self.options.showOk) {
self.dh.find(".dialog-ok").hide();
}
if (self.options.type == 'suggest') {//例外处理
self.hide();
//self.options.clickClose = true;
$(self.options.suggest.tele).unbind('keyup').keyup(function(){
var val = $.trim(this.value);
var data = null;
for(key in cachedata) {
if (key == val) {
data = cachedata[key];
}
}
if (data === null) {
$.ajax({
type: "GET",
data:{q:val},
url: self.options.suggest.url || self._content,
success: function(res){data = res;},
dataType:'json',
async: false
});
}
cachedata[val] = data;
var html = '';
for(key in data) {
html += '<li>'+data[key].name+'</li>';
}
self.show();
self.setContent(html);
self.find('li').click(function(){
var i = self.find('li').index(this);
$(self.options.suggest.tele).val(data[i].name);
$(self.options.suggest.vele).val(data[i].id);
if (typeof self.options.suggest.fn == 'function') {
fn(data[i]);
}
self.hide();
});
});
} else if(self.options.type == 'select') {
var type = self.options.select.type || 'radio';
var url = self.options.select.url || self._content || '';
var search = self.options.select.search || false;
$.ajax({
type: "GET",
url: url,
success: function(data){
var html = '';
if (data === null) {
html = '没有数据';
} else {
if (search) {
html += '<div class="wsearch"><input type="text"><input type="button" value="查询"></div>';
}
var ovals = $.trim($(self.options.select.vele).val()).split(',');//原值
html += '<div class="wselect">';
for(key in data) {
var checked = ($.inArray(data[key].id, ovals)==-1)?'':'checked="checked"';
html += '<li><label><input name="wchoose" '+checked+' type="'+type+'" value="'+data[key].id+'">'+data[key].name+'</label></li>';
}
html += '</div>';
}
self.show();
self.setContent(html);
self.find('li').width(self.options.select.width);
self.find('.wsearch input').keyup(function(){
var v = $.trim(this.value);
self.find('li').hide();
for(i in data) {
if (data[i].id==v || data[i].name.indexOf(v)!=-1) {
self.find('li:eq('+i+')').show();
}
}
});
self.setOnok(function(){
if (type=='radio') {
if (self.find(':checked').length == 0) {
$(self.options.select.tele).val('');
$(self.options.select.vele).val('');
} else {
var i = self.find(':radio[name=wchoose]').index(self.find(':checked')[0]);
$(self.options.select.tele).val(data[i].name);
$(self.options.select.vele).val(data[i].id);
if (typeof self.options.select.fn == 'function') fn(data[i]);
}
} else {
if (self.find(':checked').length == 0) {
$(self.options.select.tele).val('');
$(self.options.select.vele).val('');
} else {
var temps=[],ids=[],names=[];
self.find(':checked').each(function(){
var i = self.find(':checkbox[name=wchoose]').index(this);
temps.push(data[i]);
ids.push(data[i].id);
names.push(data[i].name);
});
$(self.options.select.tele).val(names.join(","));
$(self.options.select.vele).val(ids.join(","));
if (typeof self.options.select.fn == 'function') fn(temps);
}
}
self.close();
});
},
dataType:'json'
});
} else {
if (self.options.contentType == "selector") {
self.show();
self.selector = self._content;
self._content = $(self.selector).html();
self.setContent(self._content);
//if have checkbox do
var cs = $(self.selector).find(':checkbox');
self.dc.find(':checkbox').each(function(i){
this.checked = cs[i].checked;
});
$(self.selector).empty();
self.focus();
self.onopen();
} else if (self.options.contentType == "ajax") {
self.ajaxurl = self._content;
self.show();
self.setLoading();
self.dh.find(".dialog-button").hide();
if (self.options.cache == false) {
if (self.ajaxurl.indexOf('?') == -1) {
self.ajaxurl += "?_t="+Math.random();
} else {
self.ajaxurl += "&_t="+Math.random();
}
}
$.get(self.ajaxurl, function(data) {
self._content = data;
self.show();
self.setContent(self._content);
self.focus();
self.onopen();
});
} else if (self.options.contentType == "iframe") { /*加入iframe使程序可以直接引用其它页面 by ePim*/
var html = '<style type="text/css">';
html += ('\n.dialog-box .dialog-content{padding:0px;}');
html += ('\n</style>');
html += ('<iframe class="dialogIframe" src="'+self._content+'" width="100%" height="100%" frameborder="0"></iframe>');
self.show();
self.setContent(html);
self.onopen();
} else {
self.show();
self.setContent(self._content);
self.focus();
self.onopen();
}
}
}
//初始化弹窗事件
this.initEvent = function() {
self.dh.find(".dialog-close,.dialog-cancel, .dialog-ok").unbind('click').click(function(){self.close()});
if (typeof(self.options.onok) == "function") {
self.dh.find(".dialog-ok").unbind('click').click(function(){self.options.onok(self)});
}
if (typeof(self.options.oncancel) == "function") {
self.dh.find(".dialog-cancel").unbind('click').click(function(){self.options.oncancel(self)});
}
if (self.options.timeout>0) {
window.setTimeout(self.close, (self.options.timeout * 1000));
}
this.drag();
}
//设置onok事件
this.setOnok = function(fn) {
self.dh.find(".dialog-ok").unbind('click');
if (typeof(fn)=="function") self.dh.find(".dialog-ok").click(function(){fn(self)});
}
//设置onOncancel事件
this.setOncancel = function(fn) {
self.dh.find(".dialog-cancel").unbind('click');
if (typeof(fn)=="function") self.dh.find(".dialog-cancel").click(function(){fn(self)});
}
//设置onOnclose事件
this.setOnclose = function(fn) {
self.options.onclose = fn;
}
//弹窗拖拽
this.drag = function() {
if (self.options.draggable && self.options.showTitle) {
self.dh.find('.dialog-header').mousedown(function(event){
var h = this;
var o = document;
var ox = self.dh.position().left;
var oy = self.dh.position().top;
var mx = event.clientX;
var my = event.clientY;
var width = self.dh.width();
var height = self.dh.height();
var bwidth = self.bwidth();
var bheight = self.bheight();
if(h.setCapture) {
h.setCapture();
}
$(document).mousemove(function(event){
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else {
document.selection.empty();
}
//TODO
var left = Math.max(ox+event.clientX-mx, 0);
var top = Math.max(oy+event.clientY-my, 0);
var left = Math.min(left, bwidth-width);
var top = Math.min(top, bheight-height);
self.dh.css({left: left, top: top});
}).mouseup(function(){
if(h.releaseCapture) {
h.releaseCapture();
}
$(document).unbind('mousemove');
$(document).unbind('mouseup');
});
});
}
}
//打开前的回弹函数
this.onopen = function() {
if (typeof(self.options.onopen) == "function") {
self.options.onopen(self);
}
}
//增加一个按钮
this.addButton = function(opt) {
opt = opt || {};
opt.title = opt.title || 'OK';
opt.bclass = opt.bclass || 'dialog-btn1';
opt.fn = opt.fn || null;
opt.index = opt.index || 0;
var btn = $('<input type="button" class="'+opt.bclass+'" value="'+opt.title+'">').click(function(){
if (typeof opt.fn == "function") opt.fn(self);
});
if (opt.index < self.db.find('input').length) {
self.db.find('input:eq('+opt.index+')').before(btn);
} else {
self.db.append(opt);
}
}
//显示弹窗
this.show = function() {
if (self.options.position == 'center') {
setTimeout(function() {self.setCenterPosition();}, 200);// 延迟200毫秒等待弹窗完全载入之后才能获得正确高度
} else {
self.setElementPosition();
}
if (self.mh) {
self.mh.show();
}
if (self.options.showButton) {
self.dh.find('.dialog-button').show();
}
if (typeof self.options.showAnimate == "string") {
self.dh.show(self.options.animate);
} else {
self.dh.animate(self.options.showAnimate.animate, self.options.showAnimate.speed);
}
}
this.hide = function(fn) {
if (typeof self.options.hideAnimate == "string") {
self.dh.hide(self.options.animate, fn);
} else {
self.dh.animate(self.options.hideAnimate.animate, self.options.hideAnimate.speed, "", fn);
}
}
//设置弹窗焦点
this.focus = function() {
if (self.options.focus) {
self.dh.find(self.options.focus).focus();//TODO IE中要两次
self.dh.find(self.options.focus).focus();
} else {
self.dh.find('.dialog-cancel').focus();
}
}
//在弹窗内查找元素
this.find = function(selector) {
return self.dh.find(selector);
}
//设置加载加状态
this.setLoading = function() {
self.dh.find(".dialog-button").hide();
self.setContent('<div class="dialog-loading"></div>',true);
}
this.setWidth = function(width) {
self.dh.width(width);
}
//设置标题
this.setTitle = function(title) {
self.dt.html(title);
}
//取得标题
this.getTitle = function() {
return self.dt.html();
}
//设置内容
this.setContent = function(content,isLoading) {
self.dc.html(content);
if (self.options.height>0) {
self.dc.css('height', self.options.height);
} else {
self.dc.css('height','auto');
}
if (self.options.width>0) {
self.dh.css('width', self.options.width);
} else {
self.dh.css('width','');
}
if (self.options.showButton) {
self.dh.find(".dialog-button").show();
}
// chrome会调用这段代码导致高度过小出现滚动条
/*
if (self.dc.height() < 90) {
self.dc.height(90);
}*/
if(isLoading !== true)
{
self.dc.ready(function(){
// 注释以下代码不显示弹窗滚动条
/*
if(self.options.isFull)
self.dc.height(self.dc.get(0).scrollHeight);*/
if (self.options.onready != null)
self.options.onready(self);
});
}
}
//取得内容
this.getContent = function() {
return self.dc.html();
}
//使能按钮
this.disabledButton = function(btname, state) {
self.dh.find('.dialog-'+btname).attr("disabled", state);
}
//隐藏按钮
this.hideButton = function(btname) {
self.dh.find('.dialog-'+btname).hide();
}
//显示按钮
this.showButton = function(btname) {
self.dh.find('.dialog-'+btname).show();
}
//设置按钮标题
this.setButtonTitle = function(btname, title) {
self.dh.find('.dialog-'+btname).val(title);
}
//操作完成
this.next = function(opt) {
opt = opt || {};
opt.title = opt.title || self.getTitle();
opt.content = opt.content || "";
opt.okname = opt.okname || "确定";
opt.width = opt.width || 260;
opt.onok = opt.onok || self.close;
opt.onclose = opt.onclose || null;
opt.oncancel = opt.oncancel || null;
opt.hideCancel = opt.hideCancel || true;
self.setTitle(opt.title);
self.setButtonTitle("ok", okname);
self.setWidth(width);
self.setOnok(opt.onok);
self.show();
if (opt.content != "") self.setContent(opt.content);
if (opt.hideCancel) self.hideButton("cancel");
if (typeof(opt.onclose) == "function") self.setOnclose(opt.onclose);
if (typeof(opt.oncancel) == "function") self.setOncancel(opt.oncancel);
}
//关闭弹窗
this.close = function(n) {
if(self.options.isCloseToHide)
{
self.hide();
self.mh.hide();
return;
}
if (typeof(self.options.onclose) == "function") {
self.options.onclose(self);
}
if (self.options.contentType == 'selector') {
if (self.options.contentChange) {
//if have checkbox do
var cs = self.find(':checkbox');
$(self.selector).html(self.getContent());
if (cs.length > 0) {
$(self.selector).find(':checkbox').each(function(i){
this.checked = cs[i].checked;
});
}
} else {
$(self.selector).html(self._content);
}
} else if(self.options.contentType == "iframe") {
var iframe = self.dh.find(".dialogIframe");
iframe.removeAttr("src");
}
//设置关闭后的焦点
if (self.options.blur) {
$(self.options.blur).focus();
}
//从数组中删除
for(i=0;i<arrweebox.length;i++) {
if (arrweebox[i].dh.get(0) == self.dh.get(0)) {
arrweebox.splice(i, 1);
break;
}
}
self.hide();
self.dh.remove();
if (self.mh) {
self.mh.remove();
}
}
//取得遮照高度
this.bheight = function() {
if ($.browser.msie && $.browser.version < 7) {
var scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
);
var offsetHeight = Math.max(
document.documentElement.offsetHeight,
document.body.offsetHeight
);
if (scrollHeight < offsetHeight) {
return $(window).height();
} else {
return scrollHeight;
}
} else {
return $(document).height();
}
}
//取得遮照宽度
this.bwidth = function() {
if ($.browser.msie && $.browser.version < 7) {
var scrollWidth = Math.max(
document.documentElement.scrollWidth,
document.body.scrollWidth
);
var offsetWidth = Math.max(
document.documentElement.offsetWidth,
document.body.offsetWidth
);
if (scrollWidth < offsetWidth) {
return $(window).width();
} else {
return scrollWidth;
}
} else {
return $(window).width();
}
}
//将弹窗显示在中间位置
this.setCenterPosition = function() {
var wnd = $(window), doc = $(document),
pTop = doc.scrollTop(), pLeft = doc.scrollLeft();
pTop += (wnd.height() - self.dh.height()) / 2;
pLeft += (wnd.width() - self.dh.width()) / 2;
self.dh.css({top: pTop, left: pLeft});
}
//根据元素设置弹窗显示位置
this.setElementPosition = function() {
var trigger = $(self.options.position.refele);
var reftop = self.options.position.reftop || 0;
var refleft = self.options.position.refleft || 0;
var adjust = (typeof self.options.position.adjust=="undefined")?true:self.options.position.adjust;
var top = trigger.offset().top + trigger.height();
if(self.options.addtop != null && self.options.addtop != 0)
top += self.options.addtop;
var left = trigger.offset().left;
var docWidth = document.documentElement.clientWidth || document.body.clientWidth;
var docHeight = document.documentElement.clientHeight|| document.body.clientHeight;
var docTop = document.documentElement.scrollTop|| document.body.scrollTop;
var docLeft = document.documentElement.scrollLeft|| document.body.scrollLeft;
var docBottom = docTop + docHeight;
var docRight = docLeft + docWidth;
if (adjust && left + self.dh.width() > docRight) {
left = docRight - self.dh.width() - 1;
}
if (adjust && top + self.dh.height() > docBottom) {
top = docBottom - self.dh.height() - 1;
}
left = Math.max(left+refleft, 0);
top = Math.max(top+reftop, 0);
self.dh.css({top: top, left: left});
}
this.initOptions();
this.initMask();
this.initBox();
this.initContent();
this.initEvent();
};
var weeboxs = function() {
var self = this;
this._onbox = false;
this._opening = false;
this.zIndex = 999;
this.length = function() {
return arrweebox.length;
}
this.open = function(content, options) {
self._opening = true;
if (typeof(options) == "undefined") {
options = {};
}
if (options.boxid) {
for(var i=0; i<arrweebox.length; i++) {
if (arrweebox[i].dh.attr('id') == options.boxid) {
arrweebox[i].close();
break;
}
}
}
options.zIndex = self.zIndex;
self.zIndex += 10;
var box = new weebox(content, options);
box.dh.click(function(){self._onbox = true;});
arrweebox.push(box);
/*-----解决在ie下页面过大时出现部分阴影没有覆盖的问题-----by ePim*/
if (box.options.position != "center"){
box.setElementPosition();
}
if (box.mh) {
box.mh.css({
width: box.bwidth(),
height: box.bheight()
});
}
/*-----解决在ie下页面过大时出现部分没有遮罩的问题-----by ePim(WanJiDong@gmail.com)*/
return box;
}
//关闭最上层窗体,程序调用方法:jQuery.weeboxs.close();
this.close = function(){
var closingBox = this.getTopBox();
if(false!=closingBox) {
closingBox.close();
}
}
this.getTopBox = function() {
if (arrweebox.length>0) {
return arrweebox[arrweebox.length-1];
} else {
return false;
}
}
$(window).scroll(function() {
if (arrweebox.length > 0) {
for(i=0;i<arrweebox.length;i++) {
var box = arrweebox[i];//self.getTopBox();
if (box.options.position == "center") {
box.setCenterPosition();
}
if (box.options.position != "center"){
box.setElementPosition();
}
if (box.mh) {
box.mh.css({
width: box.bwidth(),
height: box.bheight()
});
}
}
}
}).resize(function() {
if (arrweebox.length > 0) {
var box = self.getTopBox();
if (box.options.position == "center") {
box.setCenterPosition();
}
if (box.mh) {
box.mh.css({
width: box.bwidth(),
height: box.bheight()
});
}
}
});
$(document).click(function(event) {
if (event.button==2) return true;
if (arrweebox.length>0) {
var box = self.getTopBox();
if(!self._opening && !self._onbox && box.options.clickClose) {
box.close();
}
}
self._opening = false;
self._onbox = false;
});
}
$.extend({weeboxs: new weeboxs()});
})(jQuery); | JavaScript |
/**
* 后台公共JS函数库
*
*/
function confirmurl(url,message) {
window.top.art.dialog.confirm(message, function(){
redirect(url);
}, function(){
return true;
});
//if(confirm(message)) redirect(url);
}
function redirect(url) {
location.href = url;
}
/**
* 全选checkbox,注意:标识checkbox id固定为为check_box
* @param string name 列表check名称,如 uid[]
*/
function selectall(name) {
if ($("#check_box").attr("checked")=='checked') {
$("input[name='"+name+"']").each(function() {
$(this).attr("checked","checked");
});
} else {
$("input[name='"+name+"']").each(function() {
$(this).removeAttr("checked");
});
}
}
function openwinx(url,name,w,h) {
if(!w) w=screen.width-4;
if(!h) h=screen.height-95;
window.open(url,name,"top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
}
//表单提交时弹出确认消息
function submit_confirm(id,msg,w,h){
if(!w) w=250;
if(!h) h=100;
window.top.art.dialog({
content:msg,
lock:true,
width:w,
height:h,
ok:function(){
$("#"+id).submit();
return true;
},
cancel: true
});
} | JavaScript |
<!--
$(function(){
$("#dele-no").live('click',function(){
$(this).parents('#dele-tips').remove();
});
$('#dele-yes').live('click',function(){
var url = $(this).attr('url');
var id = $(this).attr('trid');
$.post(url,{},function(data){
if(data == 'file_noexist'){
alert('删除文件不存在');
}else if(data == 'dele_statice_success'){
alert('删除静态化文件成功');
$("#"+id).find('a.sta').html('静态化');
}else if(data == 'dele_statice_fail'){
alert('删除静态化文件失败');
}else if(data == 'delete_success'){
alert('删除成功');
$("#"+id).remove();
}else if(data == 'delete_fail'){
alert('删除失败');
}else if(data == 'statice_success'){
alert('静态化文件成功');
$("#"+id).find('a.sta').html('重新静态化');
}else if(data == 'statice_fail'){
alert('静态化文件失败');
}else if(data == 'pro_no_statice_name'){
alert('请先为产品添加静态化名称');
}else if(data == 'art_no_statice_name'){
alert('请先为文章添加静态化名称');
}else if(data == 'howto_no_statice_name'){
alert('请先为大类添加howto页静态化名称');
}else if(data == 'plate_no_statice_name'){
alert('请先为栏目添加静态化名称');
}
$('#dele-tips').remove();
});
});
});
function deleTip(url,id,dele){
var h3tips = '删除提示';
var deletips = '确定删除?';
if(dele == false){
h3tips = '静态化提示';
deletips = '确定静态化?';
}
$('#dele-tips').remove();
$html = '<div id="dele-tips"><h3>'+h3tips+'</h3><p class="make-sure-dele">'+deletips+'</p><p><span><a id="dele-yes" url="'+url+'" trid="'+id+'">是</a></span><span id="dele-no"><a>否</a></span></p></div>';
$($html).appendTo('body');
}
function changeStatus(_this,url,id){
$.post(url,{'id':id},function(data){
if(data == 2){
alert('切换失败');
}else{
$(_this).find('img').attr('src',"/Public/admin/images/status-"+data+".gif");
}
// $('#dele-tips').remove();
});
}
$(function($){
$.Show_Tooltip = function(msg,isErr)
{
var time=arguments[2]?arguments[2]:1500;
var readyFun = function(weebox){
var fun = function()
{
$.weeboxs.close();
}
$("#TOOLTIP_BOX").width(weebox.dc.get(0).scrollWidth + 100);
setTimeout(fun,time);
};
var c = 'lb_s';
if(isErr)
var c = 'lb_f';
var html = '<div class="lb_tooltip"><a class="lb_close" href="javascript:;" onclick="$.weeboxs.close()"></a><div class="'+c+'">'+msg+'</div></div>';
$.weeboxs.close();
$.weeboxs.open(html, {boxid:'TOOLTIP_BOX',contentType:'text',draggable:false,showButton:false,showHeader:false,width:100,onready:readyFun});
}
$.changeSort = function(_this,id,url,type){
var v = $(_this).val();
if(!v || isNaN(v)){
return false;
}
$.post(url,{'val':v,'id':id,'type':type},function(data){
if(data == 1){
$.Show_Tooltip('修改成功');
}else{
$.Show_Tooltip('修改失败');
}
});
}
$.changeAsort = function(_this,id,url){
var v = $(_this).val();
if(isNaN(v)){
return false;
}
$.post(url,{'val':v,'id':id},function(data){
if(data == 1){
$.Show_Tooltip('修改成功');
}else{
$.Show_Tooltip('修改失败');
}
});
}
})
--> | JavaScript |
$(function(){
$(".menu ul li").hover(function(){
$(this).children("div").stop("flase","true").fadeIn(100);
},function(){
$(this).children("div").stop("true","flase").fadeOut(10);
});
$(".menu ul li, #.menu ul li dl dd, .menu ul li p").click(function(){
$(".down_menu, .down_menu2").stop("true","flase").fadeOut(500);
});
}); | JavaScript |
$(function(){
//public
$('.home-banner').slides({paginationClass :'bannerPagination',generatePagination:false,effect: 'fade, fade',slideSpeed :500,play: 5000,pause: 3000,hoverPause: true,crossfade: true});
$(".commentList").slides({generatePagination:false,effect: 'fade, fade',slideSpeed :500,play: 5000,pause: 3000,generateNextPrev :false,prev :'.control .prev',next :'.control .next' });
});
| JavaScript |
var isIe=(document.all)?true:false;
function setSelectState(state)
{
var objl=document.getElementsByTagName('select');
for(var i=0;i<objl.length;i++)
{
objl[i].style.visibility=state;
}
}
//点击下载时进行判断cookie是不是存在
//设置cookie的值
function SetCookie (name, value) {
var exp = new Date();
exp.setTime (exp.getTime()+864000);
document.cookie = name + "=" + value + "; expires=" + exp.toGMTString()+"; path=/";
}
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function DelCookie(name)
{
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString();
}
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getScrollTop()
{
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}else
{
return document.body.scrollTop;
}
}
//弹出要求输入email的框
function showregister(_this){
var bWidth=parseInt(document.documentElement.scrollWidth);
var bHeight=parseInt(document.documentElement.scrollHeight);
var tablewidth=400;
var tableheight=300;
var clientHeight=parseInt(document.documentElement.clientHeight);
if(!document.getElementById("back")){
var back=document.createElement("div");
back.id="back";
var styleStr="z-index:997;top:0px;left:0px;position:absolute;background:#666;width:"+bWidth+"px;height:"+bHeight+"px;";
styleStr+=(isIe)?"filter:alpha(opacity=0);":"opacity:0;";
back.style.cssText=styleStr;
document.body.appendChild(back);
showBackground(back,50);
}
styleStr="left:"+(bWidth-tablewidth)/2+"px;top:"+(getScrollTop()+(clientHeight-tableheight)/2)+ "px;position:absolute;z-index:999;";
document.getElementById("registerWindow").style.cssText=styleStr;
$("#registerWindow").css("display","block");
}
function showdetail(effectname,thrumburl,protype,hasvideo,videourl,author,requirever,submitdate,downloadurl)
{
closeWindow2();
var bWidth=parseInt(document.documentElement.scrollWidth);
var bHeight=parseInt(document.documentElement.scrollHeight);
if(isIe){
var curscrolltop=document.documentElement.scrollTop;
setSelectState('hidden');
}
if(protype==0) //free download
{
var downloadpic="freedownload.gif";
}else
{
var downloadpic="prodownload.gif";
}
var back=document.createElement("div");
back.id="back";
var styleStr="z-index:997;top:0px;left:0px;position:absolute;background:#666;width:"+bWidth+"px;height:"+bHeight+"px;";
styleStr+=(isIe)?"filter:alpha(opacity=0);":"opacity:0;";
back.style.cssText=styleStr;
document.body.appendChild(back);
showBackground(back,50);
//
var host = "http://"+window.location.hostname;
var clientHeight=parseInt(document.documentElement.clientHeight);
var styleStr2="z-index:999";
var mesW=document.createElement("div");
mesW.id="mesWindow";
mesW.className="mesWindow";
var tablewidth=460;
var tableheight=464;
if(hasvideo==1)//是视频介绍
{
var divwidth=460;
var divheight=470;
var tablewidth=420;
var effectnameleft=18;
var descurl="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' width='392px' height='294px'>"+
"<param name='movie' value='vcastr22.swf?vcastr_file="+ videourl +"&LogoText=&IsAutoPlay=0'>"+
"<param name='quality' value='high'>"+
"<param name='wmode' value='transparent'>"+
"<param name='allowFullScreen' value='true'>"+
"<embed src='"+host+"/effect/vcastr22.swf?vcastr_file="+ videourl +"&LogoText=&IsAutoPlay=0' allowfullscreen='true' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='392px' height='294px'>"+
"</object>";
}else //图片介绍
{
var divwidth=420;
var divheight=410;
var tablewidth=410;
var effectnameleft=3;
var descurl="<div style='border:5px solid #0099CC; width:320px; height:240px; background:#FFFFFF;' class='websjy2'><img src='"+videourl+"' width='320' height='240'/></div>";
}
mesW.innerHTML="<div style=' border:1px solid #0099CC; width:"+divwidth+"px; height:"+divheight+"px; background:#FFFFFF;' class='websjy2'><div style='border:0px solid #0099CC; width:"+divwidth+"px; height:20px; background:#FFFFFF;' class='websjy2'><table width='"+divwidth+"' border='0'><tr><td width='390' align='left'><div style='padding-left:"+effectnameleft+"px'><strong>"+effectname+"</strong></div></td><td width='20' align='right'><span style='cursor:pointer'><a onclick= 'closeWindow();'><img src='"+host+"/Public/home/images/close.png' width='20' height='20' /></a></span></td></tr></table></div><table width="+tablewidth+" border='0' align='center' style='margin:0 auto;'><tr><td colspan='3' align='center'>"+descurl+"</td></tr><tr><td colspan='3'><img src='"+host+"/Public/home/images/fenge.gif' width='400' height='9' /></td></tr><tr><td width='82' rowspan='3'><img src='"+thrumburl+"' width='79' height='59' /></td><td width='45' height='18' align='right'> </td><td width='285' align='left'><strong>Submitted by: </strong>"+author+"</td></tr><tr><td height='19' align='right'> </td><td width='285' align='left'><strong>Requires version: </strong>"+requirever+" or newer</td></tr><tr><td height='15' align='right'> </td><td width='285' align='left'><strong>Date: </strong>"+submitdate+"</td></tr><tr><td> </td><td align='right'> </td><td align='right'><a href='javascript:;'><img onclick='IsSetcookie(this)'; durl='"+downloadurl+"' src='"+host+"/Public/home/images/"+downloadpic+"' width='152' height='27' border='0' /></a></td></tr></table></div>";
styleStr="left:"+(bWidth-tablewidth)/2+"px;top:"+(getScrollTop()+(clientHeight-tableheight)/2)+"px;position:absolute;";
//styleStr="left:"+(bWidth-tablewidth)/2+"px;top:500px;position:absolute;";
//styleStr="left:"+(((pos.x-wWidth)>0)?(pos.x-wWidth):pos.x)+"px;top:"+(pos.y)+"px;position:absolute;";
styleStr +="z-index:998;";
mesW.style.cssText=styleStr;
document.body.appendChild(mesW);
}
//让背景渐渐变暗
function showBackground(obj,endInt)
{
if(isIe)
{
obj.filters.alpha.opacity+=1;
if(obj.filters.alpha.opacity<endInt)
{
setTimeout(function(){showBackground(obj,endInt)},5);
}
}else{
var al=parseFloat(obj.style.opacity);al+=0.01;
obj.style.opacity=al;
if(al<(endInt/100))
{
setTimeout(function(){showBackground(obj,endInt)},5);
}
}
}
//关闭窗口
function closeWindow()
{
if(document.getElementById('back')!=null)
{
document.getElementById('back').parentNode.removeChild(document.getElementById('back'));
}
if(document.getElementById('mesWindow')!=null)
{
document.getElementById('mesWindow').parentNode.removeChild(document.getElementById('mesWindow'));
}
if(isIe){
setSelectState('');}
}
//关闭窗口
function closeWindow2()
{
if(document.getElementById('back')!=null)
{
document.getElementById('back').parentNode.removeChild(document.getElementById('back'));
}
if(document.getElementById('registerWindow').style.display!="none")
{
document.getElementById('registerWindow').style.display = "none";
}
if(isIe){
setSelectState('');}
}
function checkemail(email)
{
//对电子邮件的验证
var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
if(!myreg.test(email))
{
alert('提示\n\n请输入有效的E_mail!');
return false;
}else return true;
}
$(function(){
$('#sub_btn').click(function(){
var email = $('input#uname').val();
var durl = $(this).attr('durl');
if(!checkemail(email)){
return false;
}
//alert($(this).parents('form').serialize());return false;
var url="http://"+window.location.hostname+"/index.php/Index/email";
//$(this).parents('form').attr('action',url);
$.post(url,{'email':email},function(ret){
if(ret==1 || ret==2){
SetCookie('down','local');
closeWindow2();
window.location = 'http://' + window.location.host + '/' + durl;
return;
}else{
alert('失败');
}
});
});
$('#uname').keydown(function(e){
if(e.keyCode==13){
var email = $('input#uname').val();
var durl = $(this).attr('durl');
if(!checkemail(email)){
return false;
}
//alert($(this).parents('form').serialize());return false;
var url="http://"+window.location.hostname+"/index.php/Index/email";
//$(this).parents('form').attr('action',url);
$.post(url,{'email':email},function(ret){
if(ret==1 || ret==2){
SetCookie('down','local');
closeWindow2();
window.location = 'http://' + window.location.host + '/' + durl;
return;
}else{
alert('失败');
}
});
}
});
})
function IsSetcookie(_this){
var durl = $(_this).attr('durl');
$('#uname').attr('durl',durl);
$('#sub_btn').attr('durl',durl);
var cval = GetCookie('down');
if(cval == 'local'){
window.location = 'http://' + window.location.host + '/' + durl;
}
else{
showregister();
}
}
| JavaScript |
<!--
host = window.location.hostname;
url = window.location.href;
if(host == "android-recovery.net")
{
var newUrl = url.replace(/android-recovery.net/g,"www.android-recovery.net");
location.href = newUrl;
}
$(function(){
/*$(".down").click(function(){
var pid=$(this).attr("pid");
var timeStamp= new Date().getTime();
$.post('/index.php/Index/tongji',{'id':pid ,'ti':timeStamp},function(){
});
});
*/
$("#SearchScoping").toggle(function(){
$("#dropNavSearch").css({border:"2px solid #d2d2d2",height:"85px"});
$("#dropNavSearch").children('li').css({margin:"5px 0"});
return false;
},function(){
$("#dropNavSearch").css({height:"0",border:"0"});
return false;
});
$('#dropNavSearch').children('li').hover(function(){
$(this).css({background:"#505050"});
$(this).children('a').css({color:"#fff"});
$(this).siblings().children('a').css({color:"#000"});
$(this).siblings().css({background:"#fff"});
}
);
$('.forumSelect').click(function(){
var v=$(this).html();
$("#SearchTerm").val(v);
});
$('#SearchTerm').click(function(){
if($(this).val()=="Search..."){
$(this).val('').css({color:"#000"});
}
});
$('.im').mouseover(function(){
$(this).find('img').eq(0).hide().siblings().show();
}).mouseout(function(){
$(this).find('img').eq(1).hide().siblings().show();
})
$('.apl').mouseover(function(){
$(this).children().show();
}).mouseout(function(){
$(this).children('.col').hide();
})
$('.toggle').mouseover(function(){
$(this).children('ul').show();
}).mouseout(function(){
$(this).children('ul').hide();
});
$('.addbg').mouseover(function(){
$(this).addClass('new');
}).mouseout(function(){
$(this).removeClass('new');
});
$('#plist').hover(function(){
$(this).contents('div').show();
},function(){
$(this).contents('div').hide();
})
$('.duoLink').mouseover(function(){
$(this).children('div.down_box').show();
}).mouseout(function(){
$(this).children('div.down_box').hide();
});
$.countdownloadnum = function(id){
var url = '/index.php/Index/downloadNum';
if(isNaN(id)){
//return false;
}
$.post(url,{'id':id},function(data){
/*if(data == 1){
$.Show_Tooltip('修改成功');
}else{
$.Show_Tooltip('修改失败');
}*/
});
}
});
function down(pid,url){
$.post('/index.php/Index/tongji',{'id':pid},function(){
lo(url);
});
}
function lo(url){
window.open(url,'_self');
}
function buy(pid){
$.post('/index.php/Index/buytongji',{'id':pid},function(){
});
}
(function($){
$.fn.myScroll = function(options){
//默认配置
var defaults = {
speed:60, //滚动速度,值越大速度越慢
rowHeight:24 //每行的高度
};
var opts = $.extend({}, defaults, options),intId = [];
function marquee(obj, step){
obj.find("ul").animate({
marginTop: '-=1'
},0,function(){
var s = Math.abs(parseInt($(this).css("margin-top")));
if(s >= step){
$(this).find("li").slice(0, 1).appendTo($(this));
$(this).css("margin-top", 0);
}
});
}
this.each(function(i){
var sh = opts["rowHeight"],speed = opts["speed"],_this = $(this);
intId[i] = setInterval(function(){
if(_this.find("ul").height()<=_this.height()){
clearInterval(intId[i]);
}else{
marquee(_this, sh);
}
}, speed);
_this.hover(function(){
clearInterval(intId[i]);
},function(){
intId[i] = setInterval(function(){
if(_this.find("ul").height()<=_this.height()){
clearInterval(intId[i]);
}else{
marquee(_this, sh);
}
}, speed);
});
});
}
})(jQuery);
$(function(){
$("").myScroll({
speed:80,
rowHeight:38
});
});
--> | JavaScript |
addEvent(window, 'load', initForm);
var highlight_array = new Array();
function initForm(){
var paymentRedirecting = checkPaypal();
initializeFocus();
var activeForm = document.getElementsByTagName('form')[0];
addEvent(activeForm, 'submit', disableSubmitButton);
ifInstructs();
showRangeCounters();
checkMechanicalTurk();
if(!paymentRedirecting) initAutoResize();
}
function disableSubmitButton() {
document.getElementById('saveForm').disabled = true;
}
// for radio and checkboxes, they have to be cleared manually, so they are added to the
// global array highlight_array so we dont have to loop through the dom every time.
function initializeFocus(){
fields = getElementsByClassName(document, "*", "field");
for(i = 0; i < fields.length; i++) {
if(fields[i].type == 'radio' || fields[i].type == 'checkbox') {
fields[i].onclick = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode.parentNode, "focused", true)};
fields[i].onfocus = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode.parentNode, "focused", true)};
highlight_array.splice(highlight_array.length,0,fields[i]);
}
else if(fields[i].className.match('addr')){
fields[i].onfocus = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode.parentNode, "focused", true)};
fields[i].onblur = function(){removeClassName(this.parentNode.parentNode.parentNode, "focused")};
}
else if(fields[i].className.match('other')){
fields[i].onfocus = function(){clearSafariRadios(); addClassName(this.parentNode.parentNode.parentNode, "focused", true)};
}
else {
fields[i].onfocus = function(){clearSafariRadios();addClassName(this.parentNode.parentNode, "focused", true)};
fields[i].onblur = function(){removeClassName(this.parentNode.parentNode, "focused")};
}
}
}
function initAutoResize() {
var key = 'wufooForm';
if(typeof(__EMBEDKEY) != 'undefined') key = __EMBEDKEY;
if(parent.postMessage) {
parent.postMessage(document.body.offsetHeight+'|'+key, "*");
}
else createTempCookie(key, document.body.offsetHeight);
}
function createTempCookie(name, value)
{
var date = new Date();
date.setTime(date.getTime()+(60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = name+"="+value+expires+"; domain=.wufoo.com; path=/";
if(readTempCookie(name) != value) {
var script = document.createElement("script");
script.setAttribute("src", "http://wufoo.com/forms/height.js?action=set&embedKey="+name+"&height="+value+"×tamp = "+ new Date().getTime().toString());
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
}
}
function readTempCookie(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 '';
}
function clearSafariRadios() {
for(var i = 0; i < highlight_array.length; i++) {
if(highlight_array[i].parentNode) {
removeClassName(highlight_array[i].parentNode.parentNode.parentNode, 'focused');
}
}
}
function ifInstructs(){
var container = document.getElementById('public');
if(container){
removeClassName(container,'noI');
var instructs = getElementsByClassName(document,"*","instruct");
if(instructs == ''){
addClassName(container,'noI',true);
}
if(container.offsetWidth <= 450){
addClassName(container,'altInstruct',true);
}
}
}
function checkPaypal() {
var ret = false;
if(document.getElementById('merchant')) {
ret = true;
if(typeof(__EMBEDKEY) == 'undefined'){
document.getElementById('merchantMessage').innerHTML = 'Your order is being processed. Please wait a moment while we redirect you to our payment page.';
document.getElementById('merchantButton').style.display = 'none';
}
document.getElementById('merchant').submit();
}
return ret;
}
function checkMechanicalTurk() {
if(document.getElementById('mechanicalTurk')) {
document.getElementById('merchantMessage').innerHTML = 'Your submission is being processed. You will be redirected shortly.';
document.getElementById('merchantButton').style.display = 'none';
document.getElementById('mechanicalTurk').submit();
}
}
function showRangeCounters(){
counters = getElementsByClassName(document, "em", "currently");
for(i = 0; i < counters.length; i++) {
counters[i].style.display = 'inline';
}
}
function validateRange(ColumnId, RangeType) {
if(document.getElementById('rangeUsedMsg'+ColumnId)) {
var field = document.getElementById('Field'+ColumnId);
var msg = document.getElementById('rangeUsedMsg'+ColumnId);
switch(RangeType) {
case 'character':
msg.innerHTML = field.value.length;
break;
case 'word':
var val = field.value;
val = val.replace(/\n/g, " ");
var words = val.split(" ");
var used = 0;
for(i =0; i < words.length; i++) {
if(words[i].replace(/\s+$/,"") != "") used++;
}
msg.innerHTML = used;
break;
case 'digit':
msg.innerHTML = field.value.length;
break;
}
}
}
/*--------------------------------------------------------------------------*/
//http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
//http://www.bigbold.com/snippets/posts/show/2630
function addClassName(objElement, strClass, blnMayAlreadyExist){
if ( objElement.className ){
var arrList = objElement.className.split(' ');
if ( blnMayAlreadyExist ){
var strClassUpper = strClass.toUpperCase();
for ( var i = 0; i < arrList.length; i++ ){
if ( arrList[i].toUpperCase() == strClassUpper ){
arrList.splice(i, 1);
i--;
}
}
}
arrList[arrList.length] = strClass;
objElement.className = arrList.join(' ');
}
else{
objElement.className = strClass;
}
}
//http://www.bigbold.com/snippets/posts/show/2630
function removeClassName(objElement, strClass){
if ( objElement.className ){
var arrList = objElement.className.split(' ');
var strClassUpper = strClass.toUpperCase();
for ( var i = 0; i < arrList.length; i++ ){
if ( arrList[i].toUpperCase() == strClassUpper ){
arrList.splice(i, 1);
i--;
}
}
objElement.className = arrList.join(' ');
}
}
//http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ) };
obj.attachEvent( "on"+type, obj[type+fn] );
}
else{
obj.addEventListener( type, fn, false );
}
} | JavaScript |
/*
* Inline Form Validation Engine 2.2, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null ) {
methods._saveOptions(form, options);
// bind all formError elements to close on click
$(".formError").live("click", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).remove();
});
});
}
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
var validateAttribute = (form.find("[data-validation-engine*=validate]")) ? "data-validation-engine" : "class";
if (!options.binded) {
if (options.bindMethod == "bind"){
// bind fields
form.find("[class*=validate]:not([type=checkbox])").bind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").bind("click", methods._onFieldEvent);
// bind form.submit
form.bind("submit", methods._onSubmitEvent);
} else if (options.bindMethod == "live") {
// bind fields with LIVE (for persistant state)
form.find("[class*=validate]:not([type=checkbox])").live(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").live("click", methods._onFieldEvent);
// bind form.submit
form.live("submit", methods._onSubmitEvent);
}
options.binded = true;
}
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
if (options.binded) {
// unbind fields
form.find("[class*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").unbind("click", methods._onFieldEvent);
// unbind form.submit
form.unbind("submit", methods.onAjaxFormComplete);
// unbind live fields (kill)
form.find("[class*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent);
form.find("[class*=validate][type=checkbox]").die("click", methods._onFieldEvent);
// unbind form.submit
form.die("submit", methods.onAjaxFormComplete);
form.removeData('jqv');
}
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function() {
return methods._validateFields(this);
},
/**
* Validates one field, shows prompt accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validateField: function(el) {
var options = $(this).data('jqv');
return methods._validateField($(el), options);
},
/**
* Validates the form fields, shows prompts accordingly.
* Note: this methods performs fields and form ajax validations(if setup)
*
* @return true if the form validates, false if it fails, undefined if ajax is used for form validation
*/
validateform: function() {
return methods._onSubmitEvent.call(this);
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form');
var options = form.data('jqv');
// No option, take default one
if(!options) options = methods._saveOptions(this, options);
if(promptPosition)
options.promptPosition=promptPosition;
options.showArrow = showArrow==true;
methods._showPrompt(this, promptText, type, false, options);
},
/**
* Closes all error prompts on the page
*/
hidePrompt: function() {
var promptClass = "."+ methods._getClassName($(this).attr("id")) + "formError";
$(promptClass).fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var closingtag;
if($(this).is("form")){
closingtag = "parentForm"+$(this).attr('id');
}else{
closingtag = $(this).attr('id') +"formError";
}
$('.'+closingtag).fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
$('.formError').fadeTo("fast", 0.3, function() {
$(this).remove();
});
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function() {
var field = $(this);
var form = field.closest('form');
var options = form.data('jqv');
// validate the current field
methods._validateField(field, options);
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
// validate each field (- skip field ajax validation, no necessary since we will perform an ajax form validation)
var r=methods._validateFields(form, true);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
return false;
}
if(options.onValidationComplete) {
options.onValidationComplete(form, r);
return false;
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form, skipAjaxValidation) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
form.find('[class*=validate]').not(':hidden').each( function() {
var field = $(this);
errorFound |= methods._validateField(field, options, skipAjaxValidation);
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// thrird, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
// look for the visually top prompt
var destination = Number.MAX_VALUE;
var fixleft = 0;
var lst = $(".formError:not('.greenPopup')");
for (var i = 0; i < lst.length; i++) {
var d = $(lst[i]).offset().top;
if (d < destination){
destination = d;
fixleft = $(lst[i]).offset().left;
}
}
if (!options.isOverflown)
$("html:not(:animated),body:not(:animated)").animate({
scrollTop: destination,
scrollLeft: fixleft
}, 1100);
else {
var overflowDIV = $(options.overflownDIV);
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV + ":not(:animated)");
scrollContainer.animate({
scrollTop: destination
}, 1100);
$("html:not(:animated),body:not(:animated)").animate({
scrollTop: overflowDIV.offset().top,
scrollLeft: fixleft
}, 1100);
}
}
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
$.ajax({
type: "GET",
url: url,
cache: false,
dataType: "json",
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if (json !== true) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, "", options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return true if field is valid
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id"))
$.error("jQueryValidate: an ID attribute is required for this field: " + field.attr("name") + " class:" +
field.attr("class"));
var rulesParsing = field.attr('class');
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var required = false;
options.isError = false;
options.showArrow = true;
for (var i = 0; i < rules.length; i++) {
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._required(field, rules, i, options);
break;
case "custom":
errorMsg = methods._customRegex(field, rules, i, options);
break;
case "ajax":
// ajax has its own prompts handling technique
if(!skipAjaxValidation){
methods._ajax(field, rules, i, options);
isAjaxValidator = true;
}
break;
case "minSize":
errorMsg = methods._minSize(field, rules, i, options);
break;
case "maxSize":
errorMsg = methods._maxSize(field, rules, i, options);
break;
case "min":
errorMsg = methods._min(field, rules, i, options);
break;
case "max":
errorMsg = methods._max(field, rules, i, options);
break;
case "past":
errorMsg = methods._past(field, rules, i, options);
break;
case "future":
errorMsg = methods._future(field, rules, i, options);
break;
case "maxCheckbox":
errorMsg = methods._maxCheckbox(field, rules, i, options);
field = $($("input[name='" + fieldName + "']"));
break;
case "minCheckbox":
errorMsg = methods._minCheckbox(field, rules, i, options);
field = $($("input[name='" + fieldName + "']"));
break;
case "equals":
errorMsg = methods._equals(field, rules, i, options);
break;
case "funcCall":
errorMsg = methods._funcCall(field, rules, i, options);
break;
default:
//$.error("jQueryValidator rule not found"+rules[i]);
}
if (errorMsg !== undefined) {
promptText += errorMsg + "<br/>";
options.isError = true;
}
}
// If the rules required is not added, an empty field is not validated
if(!required){
if(field.val() == "") options.isError = false;
}
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.attr("type");
if ((fieldType == "radio" || fieldType == "checkbox") && $("input[name='" + fieldName + "']").size() > 1) {
field = $($("input[name='" + fieldName + "'][type!=hidden]:first"));
options.showArrow = false;
}
if (options.isError){
methods._showPrompt(field, promptText, "", false, options);
}else{
if (!isAjaxValidator) methods._closePrompt(field);
}
field.trigger("jqv.field.result", [field, options.isError, promptText]);
return options.isError;
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_required: function(field, rules, i, options) {
switch (field.attr("type")) {
case "text":
case "password":
case "textarea":
case "file":
default:
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "radio":
case "checkbox":
var name = field.attr("name");
if ($("input[name='" + name + "']:checked").size() == 0) {
if ($("input[name='" + name + "']").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
// required for <select>
case "select-one":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.val())
return options.allrules[rules[i]].alertText;
break;
case "select-multiple":
// added by paul@kinetek.net for select boxes, Thank you
if (!field.find("option:selected").val())
return options.allrules[rules[i]].alertText;
break;
}
},
/**
* Validate Regex rules
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_customRegex: function(field, rules, i, options) {
var customRule = rules[i + 1];
var rule = options.allrules[customRule];
if(!rule) {
alert("jqv:custom rule not found "+customRule);
return;
}
var ex=rule.regex;
if(!ex) {
alert("jqv:custom regex not found "+customRule);
return;
}
var pattern = new RegExp(ex);
if (!pattern.test(field.val()))
return options.allrules[customRule].alertText;
},
/**
* Validate custom function outside of the engine scope
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_funcCall: function(field, rules, i, options) {
var functionName = rules[i + 1];
var fn = window[functionName];
if (typeof(fn) == 'function')
return fn(field, rules, i, options);
},
/**
* Field match
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_equals: function(field, rules, i, options) {
var equalsField = rules[i + 1];
if (field.val() != $("#" + equalsField).val())
return options.allrules.equals.alertText;
},
/**
* Check the maximum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxSize: function(field, rules, i, options) {
var max = rules[i + 1];
var len = field.val().length;
if (len > max) {
var rule = options.allrules.maxSize;
return rule.alertText + max + rule.alertText2;
}
},
/**
* Check the minimum size (in characters)
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minSize: function(field, rules, i, options) {
var min = rules[i + 1];
var len = field.val().length;
if (len < min) {
var rule = options.allrules.minSize;
return rule.alertText + min + rule.alertText2;
}
},
/**
* Check number minimum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_min: function(field, rules, i, options) {
var min = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len < min) {
var rule = options.allrules.min;
if (rule.alertText2) return rule.alertText + min + rule.alertText2;
return rule.alertText + min;
}
},
/**
* Check number maximum value
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_max: function(field, rules, i, options) {
var max = parseFloat(rules[i + 1]);
var len = parseFloat(field.val());
if (len >max ) {
var rule = options.allrules.max;
if (rule.alertText2) return rule.alertText + max + rule.alertText2;
//orefalo: to review, also do the translations
return rule.alertText + max;
}
},
/**
* Checks date is in the past
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_past: function(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p);
var vdate = methods._parseDate(field.val());
if (vdate < pdate ) {
var rule = options.allrules.past;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Checks date is in the future
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_future: function(field, rules, i, options) {
var p=rules[i + 1];
var pdate = (p.toLowerCase() == "now")? new Date():methods._parseDate(p);
var vdate = methods._parseDate(field.val());
if (vdate > pdate ) {
var rule = options.allrules.future;
if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2;
return rule.alertText + methods._dateToString(pdate);
}
},
/**
* Max number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_maxCheckbox: function(field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = $("input[name='" + groupname + "']:checked").size();
if (groupSize > nbCheck) {
options.showArrow = false;
if (options.allrules.maxCheckbox.alertText2) return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2;
return options.allrules.maxCheckbox.alertText;
}
},
/**
* Min number of checkbox selected
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_minCheckbox: function(field, rules, i, options) {
var nbCheck = rules[i + 1];
var groupname = field.attr("name");
var groupSize = $("input[name='" + groupname + "']:checked").size();
if (groupSize < nbCheck) {
options.showArrow = false;
return options.allrules.minCheckbox.alertText + " " + nbCheck + " " +
options.allrules.minCheckbox.alertText2;
}
},
/**
* Ajax field validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return nothing! the ajax validator handles the prompts itself
*/
_ajax: function(field, rules, i, options) {
var errorSelector = rules[i + 1];
var rule = options.allrules[errorSelector];
var extraData = rule.extraData;
var extraDataDynamic = rule.extraDataDynamic;
if (!extraData)
extraData = "";
if (extraDataDynamic) {
var tmpData = [];
var domIds = String(extraDataDynamic).split(",");
for (var i = 0; i < domIds.length; i++) {
var id = domIds[i];
if ($(id).length) {
var inputValue = field.closest("form").find(id).val();
var keyValue = id.replace('#', '') + '=' + escape(inputValue);
tmpData.push(keyValue);
}
}
extraDataDynamic = tmpData.join("&");
} else {
extraDataDynamic = "";
}
if (!options.isError) {
$.ajax({
type: "GET",
url: rule.url,
cache: false,
dataType: "json",
data: "fieldId=" + field.attr("id") + "&fieldValue=" + field.val() + "&extraData=" + extraData + "&" + extraDataDynamic,
field: field,
rule: rule,
methods: methods,
options: options,
beforeSend: function() {
// build the loading prompt
var loadingText = rule.alertTextLoad;
if (loadingText)
methods._showPrompt(field, loadingText, "load", true, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
// asynchronously called on success, data is the json answer from the server
var errorFieldId = json[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
var status = json[1];
// read the optional msg from the server
var msg = json[2];
if (!status) {
// Houston we got a problem - display an red prompt
options.ajaxValidCache[errorFieldId] = false;
options.isError = true;
// resolve the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
}
else
msg = rule.alertText;
methods._showPrompt(errorField, msg, "", true, options);
} else {
if (options.ajaxValidCache[errorFieldId] !== undefined)
options.ajaxValidCache[errorFieldId] = true;
// resolves the msg prompt
if(msg) {
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
}
else
msg = rule.alertTextOk;
// see if we should display a green prompt
if (msg)
methods._showPrompt(errorField, msg, "pass", true, options);
else
methods._closePrompt(errorField);
}
}
}
});
}
},
/**
* Common method to handle ajax errors
*
* @param {Object} data
* @param {Object} transport
*/
_ajaxError: function(data, transport) {
if(data.status == 0 && transport == null)
alert("The page is not served from a server! ajax call failed");
else if(typeof console != "undefined")
console.log("Ajax error: " + data.status + " " + transport);
},
/**
* date -> string
*
* @param {Object} date
*/
_dateToString: function(date) {
return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
},
/**
* Parses an ISO date
* @param {String} d
*/
_parseDate: function(d) {
var dateParts = d.split("-");
if(dateParts==d)
dateParts = d.split("/");
return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);
},
/**
* Builds or updates a prompt with the given information
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) {
var prompt = methods._getPrompt(field);
// The ajax submit errors are not see has an error in the form,
// When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time
// Because no error was found befor submitting
if(ajaxform) prompt = false;
if (prompt)
methods._updatePrompt(field, prompt, promptText, type, ajaxed, options);
else
methods._buildPrompt(field, promptText, type, ajaxed, options);
},
/**
* Builds and shades a prompt for the given field.
*
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_buildPrompt: function(field, promptText, type, ajaxed, options) {
// create the prompt
var prompt = $('<div>');
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
if(field.is(":input")) prompt.addClass("parentForm"+methods._getClassName(field.parents('form').attr("id")));
prompt.addClass("formError");
switch (type) {
case "pass":
prompt.addClass("greenPopup");
break;
case "load":
prompt.addClass("blackPopup");
}
if (ajaxed)
prompt.addClass("ajaxed");
// create the prompt content
var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);
// create the css arrow pointing at the field
// note that there is no triangle on max-checkbox and radio
if (options.showArrow) {
var arrow = $('<div>').addClass("formErrorArrow");
switch (options.promptPosition) {
case "bottomLeft":
case "bottomRight":
prompt.find(".formErrorContent").before(arrow);
arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
break;
case "topLeft":
case "topRight":
arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
prompt.append(arrow);
break;
}
}
//Cedric: Needed if a container is in position:relative
// insert prompt in the form or in the overflown container?
if (options.isOverflown)
field.before(prompt);
else
$("body").append(prompt);
var pos = methods._calculatePosition(field, prompt, options);
prompt.css({
"top": pos.callerTopPosition,
"left": pos.callerleftPosition,
"marginTop": pos.marginTopSize,
"opacity": 0
});
return prompt.animate({
"opacity": 0.87
});
},
/**
* Updates the prompt text field - the field for which the prompt
* @param {jqObject} field
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {boolean} ajaxed - use to mark fields than being validated with ajax
* @param {Map} options user options
*/
_updatePrompt: function(field, prompt, promptText, type, ajaxed, options) {
if (prompt) {
if (type == "pass")
prompt.addClass("greenPopup");
else
prompt.removeClass("greenPopup");
if (type == "load")
prompt.addClass("blackPopup");
else
prompt.removeClass("blackPopup");
if (ajaxed)
prompt.addClass("ajaxed");
else
prompt.removeClass("ajaxed");
prompt.find(".formErrorContent").html(promptText);
var pos = methods._calculatePosition(field, prompt, options);
prompt.animate({
"top": pos.callerTopPosition,
"marginTop": pos.marginTopSize
});
}
},
/**
* Closes the prompt associated with the given field
*
* @param {jqObject}
* field
*/
_closePrompt: function(field) {
var prompt = methods._getPrompt(field);
if (prompt)
prompt.fadeTo("fast", 0, function() {
prompt.remove();
});
},
closePrompt: function(field) {
return methods._closePrompt(field);
},
/**
* Returns the error prompt matching the field if any
*
* @param {jqObject}
* field
* @return undefined or the error prompt (jqObject)
*/
_getPrompt: function(field) {
var className = "." + methods._getClassName(field.attr("id")) + "formError";
var match = $(className)[0];
if (match)
return $(match);
},
/**
* Calculates prompt position
*
* @param {jqObject}
* field
* @param {jqObject}
* the prompt
* @param {Map}
* options
* @return positions
*/
_calculatePosition: function(field, promptElmt, options) {
var promptTopPosition, promptleftPosition, marginTopSize;
var fieldWidth = field.width();
var promptHeight = promptElmt.height();
var overflow = options.isOverflown;
if (overflow) {
// is the form contained in an overflown container?
promptTopPosition = promptleftPosition = 0;
// compensation for the arrow
marginTopSize = -promptHeight;
} else {
var offset = field.offset();
promptTopPosition = offset.top;
promptleftPosition = offset.left;
marginTopSize = 0;
}
switch (options.promptPosition) {
default:
case "topRight":
if (overflow)
// Is the form contained in an overflown container?
promptleftPosition += fieldWidth - 30;
else {
promptleftPosition += fieldWidth - 30;
promptTopPosition += -promptHeight;
}
break;
case "topLeft":
promptTopPosition += -promptHeight - 10;
break;
case "centerRight":
promptleftPosition += fieldWidth + 13;
break;
case "bottomLeft":
promptTopPosition = promptTopPosition + field.height() + 15;
break;
case "bottomRight":
promptleftPosition += fieldWidth - 30;
promptTopPosition += field.height() + 5;
}
return {
"callerTopPosition": promptTopPosition + "px",
"callerleftPosition": promptleftPosition + "px",
"marginTopSize": marginTopSize + "px"
};
},
/**
* Saves the user options and variables in the form.data
*
* @param {jqObject}
* form - the form where the user option should be saved
* @param {Map}
* options - the user options
* @return the user options (extended from the defaults)
*/
_saveOptions: function(form, options) {
// is there a language localisation ?
if ($.validationEngineLanguage)
var allRules = $.validationEngineLanguage.allRules;
else
$.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page");
var userOptions = $.extend({
// Name of the event triggering field validation
validationEventTrigger: "blur",
// Automatically scroll viewport to the first error
scroll: true,
// Opening box position, possible locations are: topLeft,
// topRight, bottomLeft, centerRight, bottomRight
promptPosition: "topRight",
bindMethod:"bind",
// internal, automatically set to true when it parse a _ajax rule
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
ajaxFormValidationURL: false,
// The url to send the submit ajax validation (default to action)
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function assiciated with it
onValidationComplete: false,
// Used when the form is displayed within a scrolling DIV
isOverflown: false,
overflownDIV: "",
// --- Internals DO NOT TOUCH or OVERLOAD ---
// validation rules and i18
allrules: allRules,
// true when form and fields are binded
binded: false,
// set to true, when the prompt arrow needs to be displayed
showArrow: true,
// did one of the validation fail ? kept global to stop further ajax validations
isError: false,
// Caches field validation status, typically only bad status are created.
// the array is used during ajax form validation to detect issues early and prevent an expensive submit
ajaxValidCache: {}
}, options);
form.data('jqv', userOptions);
return userOptions;
},
/**
* Removes forbidden characters from class name
* @param {String} className
*/
_getClassName: function(className) {
return className.replace(":","_").replace(".","_");
}
};
/**
* Plugin entry point.
* You may pass an action as a parameter or a list of options.
* if none, the init and attach methods are being called.
* Remember: if you pass options, the attached method is NOT called automatically
*
* @param {String}
* method (optional) action
*/
$.fn.validationEngine = function(method) {
var form = $(this);
if(!form[0]) return false; // stop here if the form does not exist
if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) {
// make sure init is called once
if(method != "showPrompt" && method != "hidePrompt" && method != "hide" && method != "hideAll")
methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object' || !method) {
// default constructor with or without arguments
methods.init.apply(form, arguments);
return methods.attach.apply(form);
} else {
$.error('Method ' + method + ' does not exist in jQuery.validationEngine');
}
};
})(jQuery);
| JavaScript |
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* This field is required",
"alertTextCheckboxMultiple": "* Please select an option",
"alertTextCheckboxe": "* This checkbox is required"
},
"minSize": {
"regex": "none",
"alertText": "* Minimum ",
"alertText2": " characters allowed"
},
"maxSize": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " characters allowed"
},
"min": {
"regex": "none",
"alertText": "* Minimum value is "
},
"max": {
"regex": "none",
"alertText": "* Maximum value is "
},
"past": {
"regex": "none",
"alertText": "* Date prior to "
},
"future": {
"regex": "none",
"alertText": "* Date past "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* Maximum ",
"alertText2": " options allowed"
},
"minCheckbox": {
"regex": "none",
"alertText": "* Please select ",
"alertText2": " options"
},
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
"alertText": "* Invalid phone number"
},
"email": {
// Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
"regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* Not a valid integer"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/,
"alertText": "* Invalid floating decimal number"
},
"date": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* Invalid IP address"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* Numbers only"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* Letters only"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* No special characters allowed"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* This name is already taken",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* This name is already taken",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
"alertText": "* Please input HELLO"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery); | JavaScript |
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* The lexer should work on a number of languages including C and friends,
* Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles.
* It works passably on Ruby, PHP and Awk and a decent subset of Perl, but,
* because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or
* CAML-like languages.
*
* If there's a language not mentioned here, then I don't know it, and don't
* know whether it works. If it has a C-like, Bash-like, or XML-like syntax
* then it should work passably.
*
* Usage:
* 1) include this source file in an html page via
* <script type="text/javascript" src="/path/to/prettify.js"></script>
* 2) define style rules. See the example page for examples.
* 3) mark the <pre> and <code> tags in your source with class=prettyprint.
* You can also use the (html deprecated) <xmp> tag, but the pretty printer
* needs to do more substantial DOM manipulations to support that, so some
* css styles may not be preserved.
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in.
*
* Change log:
* cbeust, 2006/08/22
* Java annotations (start with "@") are now captured as literals ("lit")
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window */
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
var PR_SHOULD_USE_CONTINUATION = true;
/** the number of characters between tab columns */
var PR_TAB_WIDTH = 8;
/** Walks the DOM returning a properly escaped version of innerHTML.
* @param {Node} node
* @param {Array.<string>} out output buffer that receives chunks of HTML.
*/
var PR_normalizedHtml;
/** Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR;
/** Pretty print a chunk of code.
*
* @param {string} sourceCodeHtml code as html
* @return {string} code as html, but prettier
*/
var prettyPrintOne;
/** find all the < pre > and < code > tags in the DOM with class=prettyprint
* and prettify them.
* @param {Function} opt_whenDone if specified, called when the last entry
* has been finished.
*/
var prettyPrint;
/** browser detection. @extern */
function _pr_isIE6() {
var isIE6 = navigator && navigator.userAgent &&
/\bMSIE 6\./.test(navigator.userAgent);
_pr_isIE6 = function () { return isIE6; };
return isIE6;
}
(function () {
/** Splits input on space and returns an Object mapping each non-empty part to
* true.
*/
function wordSet(words) {
words = words.split(/ /g);
var set = {};
for (var i = words.length; --i >= 0;) {
var w = words[i];
if (w) { set[w] = null; }
}
return set;
}
// Keyword lists for various languages.
var FLOW_CONTROL_KEYWORDS =
"break continue do else for if return while ";
var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " +
"double enum extern float goto int long register short signed sizeof " +
"static struct switch typedef union unsigned void volatile ";
var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " +
"new operator private protected public this throw true try ";
var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " +
"concept concept_map const_cast constexpr decltype " +
"dynamic_cast explicit export friend inline late_check " +
"mutable namespace nullptr reinterpret_cast static_assert static_cast " +
"template typeid typename typeof using virtual wchar_t where ";
var JAVA_KEYWORDS = COMMON_KEYWORDS +
"boolean byte extends final finally implements import instanceof null " +
"native package strictfp super synchronized throws transient ";
var CSHARP_KEYWORDS = JAVA_KEYWORDS +
"as base by checked decimal delegate descending event " +
"fixed foreach from group implicit in interface internal into is lock " +
"object out override orderby params readonly ref sbyte sealed " +
"stackalloc string select uint ulong unchecked unsafe ushort var ";
var JSCRIPT_KEYWORDS = COMMON_KEYWORDS +
"debugger eval export function get null set undefined var with " +
"Infinity NaN ";
var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " +
"goto if import last local my next no our print package redo require " +
"sub undef unless until use wantarray while BEGIN END ";
var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " +
"elif except exec finally from global import in is lambda " +
"nonlocal not or pass print raise try with yield " +
"False True None ";
var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" +
" defined elsif end ensure false in module next nil not or redo rescue " +
"retry self super then true undef unless until when yield BEGIN END ";
var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " +
"function in local set then until ";
var ALL_KEYWORDS = (
CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS +
PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS);
// token style names. correspond to css classes
/** token style for a string literal */
var PR_STRING = 'str';
/** token style for a keyword */
var PR_KEYWORD = 'kwd';
/** token style for a comment */
var PR_COMMENT = 'com';
/** token style for a type */
var PR_TYPE = 'typ';
/** token style for a literal value. e.g. 1, null, true. */
var PR_LITERAL = 'lit';
/** token style for a punctuation string. */
var PR_PUNCTUATION = 'pun';
/** token style for a punctuation string. */
var PR_PLAIN = 'pln';
/** token style for an sgml tag. */
var PR_TAG = 'tag';
/** token style for a markup declaration such as a DOCTYPE. */
var PR_DECLARATION = 'dec';
/** token style for embedded source. */
var PR_SOURCE = 'src';
/** token style for an sgml attribute name. */
var PR_ATTRIB_NAME = 'atn';
/** token style for an sgml attribute value. */
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
*/
var PR_NOCODE = 'nocode';
function isWordChar(ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
/** Splice one array into another.
* Like the python <code>
* container[containerPosition:containerPosition + countReplaced] = inserted
* </code>
* @param {Array} inserted
* @param {Array} container modified in place
* @param {Number} containerPosition
* @param {Number} countReplaced
*/
function spliceArrayInto(
inserted, container, containerPosition, countReplaced) {
inserted.unshift(containerPosition, countReplaced || 0);
try {
container.splice.apply(container, inserted);
} finally {
inserted.splice(0, 2);
}
}
/** A set of tokens that can precede a regular expression literal in
* javascript.
* http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
* list, but I've removed ones that might be problematic when seen in
* languages that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
* @private
*/
var REGEXP_PRECEDER_PATTERN = function () {
var preceders = [
"!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
"&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
"->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
"<", "<<", "<<=", "<=", "=", "==", "===", ">",
">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
"^", "^=", "^^", "^^=", "{", "|", "|=", "||",
"||=", "~" /* handles =~ and !~ */,
"break", "case", "continue", "delete",
"do", "else", "finally", "instanceof",
"return", "throw", "try", "typeof"
];
var pattern = '(?:' +
'(?:(?:^|[^0-9.])\\.{1,3})|' + // a dot that's not part of a number
'(?:(?:^|[^\\+])\\+)|' + // allow + but not ++
'(?:(?:^|[^\\-])-)'; // allow - but not --
for (var i = 0; i < preceders.length; ++i) {
var preceder = preceders[i];
if (isWordChar(preceder.charAt(0))) {
pattern += '|\\b' + preceder;
} else {
pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1');
}
}
pattern += '|^)\\s*$'; // matches at end, and matches empty string
return new RegExp(pattern);
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not
// valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
}();
// Define regexps here so that the interpreter doesn't have to create an
// object each time the function containing them is called.
// The language spec requires a new object created even if you don't access
// the $1 members.
var pr_amp = /&/g;
var pr_lt = /</g;
var pr_gt = />/g;
var pr_quot = /\"/g;
/** like textToHtml but escapes double quotes to be attribute safe. */
function attribToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>')
.replace(pr_quot, '"');
}
/** escapest html special characters to html. */
function textToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>');
}
var pr_ltEnt = /</g;
var pr_gtEnt = />/g;
var pr_aposEnt = /'/g;
var pr_quotEnt = /"/g;
var pr_ampEnt = /&/g;
var pr_nbspEnt = / /g;
/** unescapes html to plain text. */
function htmlToText(html) {
var pos = html.indexOf('&');
if (pos < 0) { return html; }
// Handle numeric entities specially. We can't use functional substitution
// since that doesn't work in older versions of Safari.
// These should be rare since most browsers convert them to normal chars.
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
var end = html.indexOf(';', pos);
if (end >= 0) {
var num = html.substring(pos + 3, end);
var radix = 10;
if (num && num.charAt(0) === 'x') {
num = num.substring(1);
radix = 16;
}
var codePoint = parseInt(num, radix);
if (!isNaN(codePoint)) {
html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
html.substring(end + 1));
}
}
}
return html.replace(pr_ltEnt, '<')
.replace(pr_gtEnt, '>')
.replace(pr_aposEnt, "'")
.replace(pr_quotEnt, '"')
.replace(pr_ampEnt, '&')
.replace(pr_nbspEnt, ' ');
}
/** is the given node's innerHTML normally unescaped? */
function isRawContent(node) {
return 'XMP' === node.tagName;
}
function normalizedHtml(node, out) {
switch (node.nodeType) {
case 1: // an element
var name = node.tagName.toLowerCase();
out.push('<', name);
for (var i = 0; i < node.attributes.length; ++i) {
var attr = node.attributes[i];
if (!attr.specified) { continue; }
out.push(' ');
normalizedHtml(attr, out);
}
out.push('>');
for (var child = node.firstChild; child; child = child.nextSibling) {
normalizedHtml(child, out);
}
if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
out.push('<\/', name, '>');
}
break;
case 2: // an attribute
out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"');
break;
case 3: case 4: // text
out.push(textToHtml(node.nodeValue));
break;
}
}
var PR_innerHtmlWorks = null;
function getInnerHtml(node) {
// inner html is hopelessly broken in Safari 2.0.4 when the content is
// an html description of well formed XML and the containing tag is a PRE
// tag, so we detect that case and emulate innerHTML.
if (null === PR_innerHtmlWorks) {
var testNode = document.createElement('PRE');
testNode.appendChild(
document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
}
if (PR_innerHtmlWorks) {
var content = node.innerHTML;
// XMP tags contain unescaped entities so require special handling.
if (isRawContent(node)) {
content = textToHtml(content);
}
return content;
}
var out = [];
for (var child = node.firstChild; child; child = child.nextSibling) {
normalizedHtml(child, out);
}
return out.join('');
}
/** returns a function that expand tabs to spaces. This function can be fed
* successive chunks of text, and will maintain its own internal state to
* keep track of how tabs are expanded.
* @return {function (string) : string} a function that takes
* plain text and return the text with tabs expanded.
* @private
*/
function makeTabExpander(tabWidth) {
var SPACES = ' ';
var charInLine = 0;
return function (plainText) {
// walk over each character looking for tabs and newlines.
// On tabs, expand them. On newlines, reset charInLine.
// Otherwise increment charInLine
var out = null;
var pos = 0;
for (var i = 0, n = plainText.length; i < n; ++i) {
var ch = plainText.charAt(i);
switch (ch) {
case '\t':
if (!out) { out = []; }
out.push(plainText.substring(pos, i));
// calculate how much space we need in front of this part
// nSpaces is the amount of padding -- the number of spaces needed
// to move us to the next column, where columns occur at factors of
// tabWidth.
var nSpaces = tabWidth - (charInLine % tabWidth);
charInLine += nSpaces;
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
out.push(SPACES.substring(0, nSpaces));
}
pos = i + 1;
break;
case '\n':
charInLine = 0;
break;
default:
++charInLine;
}
}
if (!out) { return plainText; }
out.push(plainText.substring(pos));
return out.join('');
};
}
// The below pattern matches one of the following
// (1) /[^<]+/ : A run of characters other than '<'
// (2) /<!--.*?-->/: an HTML comment
// (3) /<!\[CDATA\[.*?\]\]>/: a cdata section
// (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted
// (4) /</ : A '<' that does not begin a larger chunk. Treated as 1
var pr_chunkPattern =
/(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g;
var pr_commentPrefix = /^<!--/;
var pr_cdataPrefix = /^<\[CDATA\[/;
var pr_brPrefix = /^<br\b/i;
var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/;
/** split markup into chunks of html tags (style null) and
* plain text (style {@link #PR_PLAIN}), converting tags which are
* significant for tokenization (<br>) into their textual equivalent.
*
* @param {string} s html where whitespace is considered significant.
* @return {Object} source code and extracted tags.
* @private
*/
function extractTags(s) {
// since the pattern has the 'g' modifier and defines no capturing groups,
// this will return a list of all chunks which we then classify and wrap as
// PR_Tokens
var matches = s.match(pr_chunkPattern);
var sourceBuf = [];
var sourceBufLen = 0;
var extractedTags = [];
if (matches) {
for (var i = 0, n = matches.length; i < n; ++i) {
var match = matches[i];
if (match.length > 1 && match.charAt(0) === '<') {
if (pr_commentPrefix.test(match)) { continue; }
if (pr_cdataPrefix.test(match)) {
// strip CDATA prefix and suffix. Don't unescape since it's CDATA
sourceBuf.push(match.substring(9, match.length - 3));
sourceBufLen += match.length - 12;
} else if (pr_brPrefix.test(match)) {
// <br> tags are lexically significant so convert them to text.
// This is undone later.
sourceBuf.push('\n');
++sourceBufLen;
} else {
if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) {
// A <span class="nocode"> will start a section that should be
// ignored. Continue walking the list until we see a matching end
// tag.
var name = match.match(pr_tagNameRe)[2];
var depth = 1;
end_tag_loop:
for (var j = i + 1; j < n; ++j) {
var name2 = matches[j].match(pr_tagNameRe);
if (name2 && name2[2] === name) {
if (name2[1] === '/') {
if (--depth === 0) { break end_tag_loop; }
} else {
++depth;
}
}
}
if (j < n) {
extractedTags.push(
sourceBufLen, matches.slice(i, j + 1).join(''));
i = j;
} else { // Ignore unclosed sections.
extractedTags.push(sourceBufLen, match);
}
} else {
extractedTags.push(sourceBufLen, match);
}
}
} else {
var literalText = htmlToText(match);
sourceBuf.push(literalText);
sourceBufLen += literalText.length;
}
}
}
return { source: sourceBuf.join(''), tags: extractedTags };
}
/** True if the given tag contains a class attribute with the nocode class. */
function isNoCodeTag(tag) {
return !!tag
// First canonicalize the representation of attributes
.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,
' $1="$2$3$4"')
// Then look for the attribute we want.
.match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/);
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, context : RegExp, shortcut : string].
&
* Style is a style constant like PR_PLAIN.
*
* Pattern must only match prefixes, and if it matches a prefix and context
* is null or matches the last non-comment token parsed, then that match is
* considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (string, number?) : Array.<number|string>} a
* function that takes source code and returns a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns,
fallthroughStylePatterns) {
var shortcuts = {};
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
for (var i = allPatterns.length; --i >= 0;) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
}
})();
var nPatterns = fallthroughStylePatterns.length;
var notWs = /\S/;
return function (sourceCode, opt_basePos) {
opt_basePos = opt_basePos || 0;
var decorations = [opt_basePos, PR_PLAIN];
var lastToken = '';
var pos = 0; // index into sourceCode
var tail = sourceCode;
while (tail.length) {
var style;
var token = null;
var match;
var patternParts = shortcuts[tail.charAt(0)];
if (patternParts) {
match = tail.match(patternParts[1]);
token = match[0];
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
var contextPattern = patternParts[2];
if (contextPattern && !contextPattern.test(lastToken)) {
// rule can't be used
continue;
}
match = tail.match(patternParts[1]);
if (match) {
token = match[0];
style = patternParts[0];
break;
}
}
if (!token) { // make sure that we make progress
style = PR_PLAIN;
token = tail.substring(0, 1);
}
}
decorations.push(opt_basePos + pos, style);
pos += token.length;
tail = tail.substring(token.length);
if (style !== PR_COMMENT && notWs.test(token)) { lastToken = token; }
}
return decorations;
};
}
var PR_MARKUP_LEXER = createSimpleLexer([], [
[PR_PLAIN, /^[^<]+/, null],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null],
[PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null],
[PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null],
[PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null],
[PR_SOURCE,
// Tags whose content is not escaped, and which contain source code.
/^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null],
[PR_TAG, /^<\/?\w[^<>]*>/, null]
]);
// Splits any of the source|style|xmp entries above into a start tag,
// source content, and end tag.
var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/;
/** split markup on tags, comments, application directives, and other top
* level constructs. Tags are returned as a single token - attributes are
* not yet broken out.
* @private
*/
function tokenizeMarkup(source) {
var decorations = PR_MARKUP_LEXER(source);
for (var i = 0; i < decorations.length; i += 2) {
if (decorations[i + 1] === PR_SOURCE) {
var start, end;
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
// Split out start and end script tags as actual tags, and leave the
// body with style SCRIPT.
var sourceChunk = source.substring(start, end);
var match = sourceChunk.match(PR_SOURCE_CHUNK_PARTS);
if (match) {
decorations.splice(
i, 2,
start, PR_TAG, // the open chunk
start + match[1].length, PR_SOURCE,
start + match[1].length + (match[2] || '').length, PR_TAG);
}
}
}
return decorations;
}
var PR_TAG_LEXER = createSimpleLexer([
[PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"],
[PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'],
[PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/=']
], [
[PR_TAG, /^[\w:\-]+/, /^</],
[PR_ATTRIB_VALUE, /^[\w\-]+/, /^=/],
[PR_ATTRIB_NAME, /^[\w:\-]+/, null],
[PR_PLAIN, /^\s+/, null, ' \t\r\n']
]);
/** split tags attributes and their values out from the tag name, and
* recursively lex source chunks.
* @private
*/
function splitTagAttributes(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_TAG) {
var start, end;
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var chunk = source.substring(start, end);
var subDecorations = PR_TAG_LEXER(chunk, start);
spliceArrayInto(subDecorations, decorations, i, 2);
i += subDecorations.length - 2;
}
}
return decorations;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (string) : Array.<string|number>} a
* decorator that takes sourceCode as plain text and that returns a
* decoration list
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options.tripleQuotedStrings) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options.multiLineStrings) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
fallthroughStylePatterns.push(
[PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n']);
if (options.hashComments) {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
if (options.cStyleComments) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
if (options.regexLiterals) {
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'^/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '(?:/|$)');
fallthroughStylePatterns.push(
[PR_STRING, new RegExp(REGEX_LITERAL), REGEXP_PRECEDER_PATTERN]);
}
var keywords = wordSet(options.keywords);
options = null;
/** splits the given string into comment, string, and "other" tokens.
* @param {string} sourceCode as plain text
* @return {Array.<number|string>} a decoration list.
* @private
*/
var splitStringAndCommentTokens = createSimpleLexer(
shortcutStylePatterns, fallthroughStylePatterns);
var styleLiteralIdentifierPuncRecognizer = createSimpleLexer([], [
[PR_PLAIN, /^\s+/, null, ' \r\n'],
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null],
// A hex number
[PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null],
// An octal or decimal number, possibly in scientific notation
[PR_LITERAL,
/^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i,
null, '123456789'],
[PR_PUNCTUATION, /^[^\s\w\.$@]+/, null]
// Fallback will handle decimal points not adjacent to a digit
]);
/** splits plain text tokens into more specific tokens, and then tries to
* recognize keywords, and types.
* @private
*/
function splitNonStringNonCommentTokens(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_PLAIN) {
var start, end, chunk, subDecs;
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
chunk = source.substring(start, end);
subDecs = styleLiteralIdentifierPuncRecognizer(chunk, start);
for (var j = 0, m = subDecs.length; j < m; j += 2) {
var subStyle = subDecs[j + 1];
if (subStyle === PR_PLAIN) {
var subStart = subDecs[j];
var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length;
var token = source.substring(subStart, subEnd);
if (token === '.') {
subDecs[j + 1] = PR_PUNCTUATION;
} else if (token in keywords) {
subDecs[j + 1] = PR_KEYWORD;
} else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) {
// classify types and annotations using Java's style conventions
subDecs[j + 1] = token.charAt(0) === '@' ? PR_LITERAL : PR_TYPE;
}
}
}
spliceArrayInto(subDecs, decorations, i, 2);
i += subDecs.length - 2;
}
}
return decorations;
}
return function (sourceCode) {
// Split into strings, comments, and other.
// We do this because strings and comments are easily recognizable and can
// contain stuff that looks like other tokens, so we want to mark those
// early so we don't recurse into them.
var decorations = splitStringAndCommentTokens(sourceCode);
// Split non comment|string tokens on whitespace and word boundaries
decorations = splitNonStringNonCommentTokens(sourceCode, decorations);
return decorations;
};
}
var decorateSource = sourceDecorator({
keywords: ALL_KEYWORDS,
hashComments: true,
cStyleComments: true,
multiLineStrings: true,
regexLiterals: true
});
/** identify regions of markup that are really source code, and recursivley
* lex them.
* @private
*/
function splitSourceNodes(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_SOURCE) {
// Recurse using the non-markup lexer
var start, end;
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var subDecorations = decorateSource(source.substring(start, end));
for (var j = 0, m = subDecorations.length; j < m; j += 2) {
subDecorations[j] += start;
}
spliceArrayInto(subDecorations, decorations, i, 2);
i += subDecorations.length - 2;
}
}
return decorations;
}
/** identify attribute values that really contain source code and recursively
* lex them.
* @private
*/
function splitSourceAttributes(source, decorations) {
var nextValueIsSource = false;
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
var start, end;
if (style === PR_ATTRIB_NAME) {
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
nextValueIsSource = /^on|^style$/i.test(source.substring(start, end));
} else if (style === PR_ATTRIB_VALUE) {
if (nextValueIsSource) {
start = decorations[i];
end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var attribValue = source.substring(start, end);
var attribLen = attribValue.length;
var quoted =
(attribLen >= 2 && /^[\"\']/.test(attribValue) &&
attribValue.charAt(0) === attribValue.charAt(attribLen - 1));
var attribSource;
var attribSourceStart;
var attribSourceEnd;
if (quoted) {
attribSourceStart = start + 1;
attribSourceEnd = end - 1;
attribSource = attribValue;
} else {
attribSourceStart = start + 1;
attribSourceEnd = end - 1;
attribSource = attribValue.substring(1, attribValue.length - 1);
}
var attribSourceDecorations = decorateSource(attribSource);
for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) {
attribSourceDecorations[j] += attribSourceStart;
}
if (quoted) {
attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE);
spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0);
} else {
spliceArrayInto(attribSourceDecorations, decorations, i, 2);
}
}
nextValueIsSource = false;
}
}
return decorations;
}
/** returns a decoration list given a string of markup.
*
* This code recognizes a number of constructs.
* <!-- ... --> comment
* <!\w ... > declaration
* <\w ... > tag
* </\w ... > tag
* <?...?> embedded source
* <%...%> embedded source
* &[#\w]...; entity
*
* It does not recognizes %foo; doctype entities from .
*
* It will recurse into any <style>, <script>, and on* attributes using
* PR_lexSource.
*/
function decorateMarkup(sourceCode) {
// This function works as follows:
// 1) Start by splitting the markup into text and tag chunks
// Input: string s
// Output: List<PR_Token> where style in (PR_PLAIN, null)
// 2) Then split the text chunks further into comments, declarations,
// tags, etc.
// After each split, consider whether the token is the start of an
// embedded source section, i.e. is an open <script> tag. If it is, find
// the corresponding close token, and don't bother to lex in between.
// Input: List<string>
// Output: List<PR_Token> with style in
// (PR_TAG, PR_PLAIN, PR_SOURCE, null)
// 3) Finally go over each tag token and split out attribute names and
// values.
// Input: List<PR_Token>
// Output: List<PR_Token> where style in
// (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null)
var decorations = tokenizeMarkup(sourceCode);
decorations = splitTagAttributes(sourceCode, decorations);
decorations = splitSourceNodes(sourceCode, decorations);
decorations = splitSourceAttributes(sourceCode, decorations);
return decorations;
}
/**
* @param {string} sourceText plain text
* @param {Array.<number|string>} extractedTags chunks of raw html preceded
* by their position in sourceText in order.
* @param {Array.<number|string>} decorations style classes preceded by their
* position in sourceText in order.
* @return {string} html
* @private
*/
function recombineTagsAndDecorations(sourceText, extractedTags, decorations) {
var html = [];
// index past the last char in sourceText written to html
var outputIdx = 0;
var openDecoration = null;
var currentDecoration = null;
var tagPos = 0; // index into extractedTags
var decPos = 0; // index into decorations
var tabExpander = makeTabExpander(PR_TAB_WIDTH);
var adjacentSpaceRe = /([\r\n ]) /g;
var startOrSpaceRe = /(^| ) /gm;
var newlineRe = /\r\n?|\n/g;
var trailingSpaceRe = /[ \r\n]$/;
var lastWasSpace = true; // the last text chunk emitted ended with a space.
// A helper function that is responsible for opening sections of decoration
// and outputing properly escaped chunks of source
function emitTextUpTo(sourceIdx) {
if (sourceIdx > outputIdx) {
if (openDecoration && openDecoration !== currentDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
if (!openDecoration && currentDecoration) {
openDecoration = currentDecoration;
html.push('<span class="', openDecoration, '">');
}
// This interacts badly with some wikis which introduces paragraph tags
// into pre blocks for some strange reason.
// It's necessary for IE though which seems to lose the preformattedness
// of <pre> tags when their innerHTML is assigned.
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
// and it serves to undo the conversion of <br>s to newlines done in
// chunkify.
var htmlChunk = textToHtml(
tabExpander(sourceText.substring(outputIdx, sourceIdx)))
.replace(lastWasSpace
? startOrSpaceRe
: adjacentSpaceRe, '$1 ');
// Keep track of whether we need to escape space at the beginning of the
// next chunk.
lastWasSpace = trailingSpaceRe.test(htmlChunk);
html.push(htmlChunk.replace(newlineRe, '<br />'));
outputIdx = sourceIdx;
}
}
while (true) {
// Determine if we're going to consume a tag this time around. Otherwise
// we consume a decoration or exit.
var outputTag;
if (tagPos < extractedTags.length) {
if (decPos < decorations.length) {
// Pick one giving preference to extractedTags since we shouldn't open
// a new style that we're going to have to immediately close in order
// to output a tag.
outputTag = extractedTags[tagPos] <= decorations[decPos];
} else {
outputTag = true;
}
} else {
outputTag = false;
}
// Consume either a decoration or a tag or exit.
if (outputTag) {
emitTextUpTo(extractedTags[tagPos]);
if (openDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
html.push(extractedTags[tagPos + 1]);
tagPos += 2;
} else if (decPos < decorations.length) {
emitTextUpTo(decorations[decPos]);
currentDecoration = decorations[decPos + 1];
decPos += 2;
} else {
break;
}
}
emitTextUpTo(sourceText.length);
if (openDecoration) {
html.push('</span>');
}
return html.join('');
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (string) : Array.<number|string>} handler
* a function from source code to a list of decorations.
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if ('console' in window) {
console.log('cannot override language handler %s', ext);
}
}
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(decorateMarkup,
['default-markup', 'html', 'htm', 'xhtml', 'xml', 'xsl']);
registerLangHandler(sourceDecorator({
keywords: CPP_KEYWORDS,
hashComments: true,
cStyleComments: true
}), ['c', 'cc', 'cpp', 'cxx', 'cyc']);
registerLangHandler(sourceDecorator({
keywords: CSHARP_KEYWORDS,
hashComments: true,
cStyleComments: true
}), ['cs']);
registerLangHandler(sourceDecorator({
keywords: JAVA_KEYWORDS,
cStyleComments: true
}), ['java']);
registerLangHandler(sourceDecorator({
keywords: SH_KEYWORDS,
hashComments: true,
multiLineStrings: true
}), ['bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
keywords: PYTHON_KEYWORDS,
hashComments: true,
multiLineStrings: true,
tripleQuotedStrings: true
}), ['cv', 'py']);
registerLangHandler(sourceDecorator({
keywords: PERL_KEYWORDS,
hashComments: true,
multiLineStrings: true,
regexLiterals: true
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
keywords: RUBY_KEYWORDS,
hashComments: true,
multiLineStrings: true,
regexLiterals: true
}), ['rb']);
registerLangHandler(sourceDecorator({
keywords: JSCRIPT_KEYWORDS,
cStyleComments: true,
regexLiterals: true
}), ['js']);
function prettyPrintOne(sourceCodeHtml, opt_langExtension) {
try {
// Extract tags, and convert the source code to plain text.
var sourceAndExtractedTags = extractTags(sourceCodeHtml);
/** Plain text. @type {string} */
var source = sourceAndExtractedTags.source;
/** Even entries are positions in source in ascending order. Odd entries
* are tags that were extracted at that position.
* @type {Array.<number|string>}
*/
var extractedTags = sourceAndExtractedTags.tags;
// Pick a lexer and apply it.
if (!langHandlerRegistry.hasOwnProperty(opt_langExtension)) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
opt_langExtension =
/^\s*</.test(source) ? 'default-markup' : 'default-code';
}
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = langHandlerRegistry[opt_langExtension].call({}, source);
// Integrate the decorations and tags back into the source code to produce
// a decorated html string.
return recombineTagsAndDecorations(source, extractedTags, decorations);
} catch (e) {
if ('console' in window) {
console.log(e);
console.trace();
}
return sourceCodeHtml;
}
}
function prettyPrint(opt_whenDone) {
var isIE6 = _pr_isIE6();
// fetch a list of nodes to rewrite
var codeSegments = [
document.getElementsByTagName('pre'),
document.getElementsByTagName('code'),
document.getElementsByTagName('xmp') ];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0; j < codeSegments[i].length; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
// the loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
function doWork() {
var endTime = (PR_SHOULD_USE_CONTINUATION ?
new Date().getTime() + 250 /* ms */ :
Infinity);
for (; k < elements.length && new Date().getTime() < endTime; k++) {
var cs = elements[k];
if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler as
// passed to PR_registerLangHandler.
var langExtension = cs.className.match(/\blang-(\w+)\b/);
if (langExtension) { langExtension = langExtension[1]; }
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
if ((p.tagName === 'pre' || p.tagName === 'code' ||
p.tagName === 'xmp') &&
p.className && p.className.indexOf('prettyprint') >= 0) {
nested = true;
break;
}
}
if (!nested) {
// fetch the content as a snippet of properly escaped HTML.
// Firefox adds newlines at the end.
var content = getInnerHtml(cs);
content = content.replace(/(?:\r\n?|\n)$/, '');
// do the pretty printing
var newContent = prettyPrintOne(content, langExtension);
// push the prettified html back into the tag.
if (!isRawContent(cs)) {
// just replace the old html with the new
cs.innerHTML = newContent;
} else {
// we need to change the tag to a <pre> since <xmp>s do not allow
// embedded tags such as the span tags used to attach styles to
// sections of source code.
var pre = document.createElement('PRE');
for (var i = 0; i < cs.attributes.length; ++i) {
var a = cs.attributes[i];
if (a.specified) {
var aname = a.name.toLowerCase();
if (aname === 'class') {
pre.className = a.value; // For IE 6
} else {
pre.setAttribute(a.name, a.value);
}
}
}
pre.innerHTML = newContent;
// remove the old
cs.parentNode.replaceChild(pre, cs);
cs = pre;
}
// Replace <br>s with line-feeds so that copying and pasting works
// on IE 6.
// Doing this on other browsers breaks lots of stuff since \r\n is
// treated as two newlines on Firefox, and doing this also slows
// down rendering.
if (isIE6 && cs.tagName === 'PRE') {
var lineBreaks = cs.getElementsByTagName('br');
for (var j = lineBreaks.length; --j >= 0;) {
var lineBreak = lineBreaks[j];
lineBreak.parentNode.replaceChild(
document.createTextNode('\r\n'), lineBreak);
}
}
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if (opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
window['PR_normalizedHtml'] = normalizedHtml;
window['prettyPrintOne'] = prettyPrintOne;
window['prettyPrint'] = prettyPrint;
window['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE
};
})();
| JavaScript |
// Copyright 2010 Google
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Google IO Mall Map
* @constructor
*/
function GoogleIo() {
this.center_ = new google.maps.LatLng(37.78313383211993,
-122.40394949913025);
this.mapDiv_ = document.getElementById(this.MAP_ID);
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: this.center_,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.HYBRID
});
this.infoWindow_ = new google.maps.InfoWindow({
maxWidth: 330
});
this.isMobile_();
var that = this;
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
that.enableToolbox_();
if (that.hasMapContainer_()) {
MAP_CONTAINER.onMapReady();
}
});
this.addLevelMarkers_();
if (!document.location.hash) {
this.showLevel(this.LEVELS_[0], true);
}
this.checkLocalStorage_();
this.loadMallMapContent_();
if (!this.hasMapContainer_()) {
this.initLocationHashWatcher_();
}
}
/**
* @type {string}
*/
GoogleIo.prototype.MAP_ID = 'map-canvas';
/**
* @type {Array.<string>}
* @private
*/
GoogleIo.prototype.LEVELS_ = ['1', '2', '3'];
/**
* @type {number?}
* @private
*/
GoogleIo.prototype.currentLevel_ = null;
/**
* @type {google.maps.LatLng?}
* @private
*/
GoogleIo.prototype.userPosition_ = null;
/**
* @type {number?}
* @private
*/
GoogleIo.prototype.userLevel_ = null;
/**
* @type {string?}
* @private
*/
GoogleIo.prototype.currentHash_ = null;
/**
* @type {string}
* @private
*/
GoogleIo.prototype.SESSION_BASE_ =
'http://code.google.com/events/io/2010/sessions/';
/**
* @type {Object}
* @private
*/
GoogleIo.prototype.markers_ = {
'LEVEL1': [],
'LEVEL2': [],
'LEVEL3': []
};
/**
* @type {number}
* @private
*/
GoogleIo.prototype.markerIndex_ = 10;
/**
* @type {number}
* @private
*/
GoogleIo.prototype.userIndex_ = 11;
/**
* @type {string}
* @private
*/
GoogleIo.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/2/';
/**
* @type {string}
* @private
*/
GoogleIo.prototype.TILE_TEMPLATE_URL_ = GoogleIo.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
GoogleIo.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
GoogleIo.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* @type {number}
* @private
*/
GoogleIo.prototype.MIN_RESOLUTION_ = 16;
/**
* @type {number}
* @private
*/
GoogleIo.prototype.MAX_RESOLUTION_ = 20;
/**
* @type {boolean}
* @private
*/
GoogleIo.prototype.ready_ = false;
/**
* @type {Object}
* @private
*/
GoogleIo.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* Initialise the location hash watcher.
*
* @private
*/
GoogleIo.prototype.initLocationHashWatcher_ = function() {
var that = this;
window.setInterval(function() {
that.checkLocationHash_();
}, 100);
};
/**
* Checks if a MAP_CONTAINER object exists
*
* @return {boolean} Whether the object exists or not.
* @private
*/
GoogleIo.prototype.hasMapContainer_ = function() {
return typeof(window['MAP_CONTAINER']) !== 'undefined';
};
/**
* Checks the local storage
* @private
*/
GoogleIo.prototype.checkLocalStorage_ = function() {
var sandboxItems = this.getFromLocalStorage_('sandbox');
if (sandboxItems) {
this.sandboxItems_ = sandboxItems;
}
var sessionItems = this.getFromLocalStorage_('sessions');
if (sessionItems) {
this.sessionItems_ = sessionItems;
}
};
/**
* Get a item from the local storage
* @param {string} key the key of the item to get.
* @return {Object|string|null} The item from the local storage.
* @private
*/
GoogleIo.prototype.getFromLocalStorage_ = function(key) {
if (typeof(window['localStorage']) !== 'undefined' &&
typeof(window['JSON']) !== 'undefined' && localStorage && JSON) {
var value = localStorage.getItem(key);
// Crude hack to see if its a json object string.
// Suits our purpose
if (value && value.indexOf('{') !== -1) {
return JSON.parse(value);
}
return value;
}
};
/**
* Adds data to the local storage
* @param {string} key The key of the item to store.
* @param {string|Object} value The item to store in the local store.
* @private
*/
GoogleIo.prototype.addToLocalStorage_ = function(key, value) {
if (typeof(window['localStorage']) !== 'undefined' &&
typeof(window['JSON']) !== 'undefined' && localStorage && JSON) {
if (typeof(value) == 'object') {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
}
};
/**
* Detects if mobile and some mobile specific events.
* @private
*/
GoogleIo.prototype.isMobile_ = function() {
var logo = document.getElementById('io-logo');
if (logo && logo.offsetWidth == 265) {
this.setContentHeight();
var that = this;
this.map_.setOptions({
scaleControl: false
});
google.maps.event.addDomListener(window, 'resize', function() {
that.setContentHeight();
});
google.maps.event.addListener(this.map_, 'click', function() {
that.infoWindow_.close();
});
google.maps.event.addDomListenerOnce(window, 'load', function() {
window.setTimeout(function() {
window.scrollTo(0, 1);
}, 200);
});
}
};
/**
* Converts a name to id
*
* @param {string} name The name to convert.
* @return {string} id A nice id.
* @private
*/
GoogleIo.prototype.nameToId_ = function(name) {
return name.toLowerCase().replace(/[^a-z0-9-_]/ig, '');
};
/**
* Sets the height of the content area so that the map takes up all the
* available height.
*/
GoogleIo.prototype.setContentHeight = function() {
var height = document.body.clientHeight;
var topHeight = document.getElementById('top').clientHeight;
var bottomHeight = document.getElementById('bottom').clientHeight;
var mapCanvas = document.getElementById('map-canvas');
mapCanvas.style.height = (height - topHeight - bottomHeight + 30) + 'px';
google.maps.event.trigger(this.map_, 'resize');
};
/**
* Check the location hash and update if neeed.
*
* @param {boolean} force To force the location hash update.
* @private
*/
GoogleIo.prototype.checkLocationHash_ = function(force) {
var hash = document.location.hash;
if (force || this.currentHash_ != hash) {
this.currentHash_ = hash;
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
if (force || this.currentLevel_ != match[1]) {
this.showLevel(match[1], false, force);
}
if (match[2] && this.mallMapContent_) {
for (var i = 0, content; content = this.mallMapContent_[i]; i++) {
if (content.id == match[2]) {
this.openContentInfo(content);
break;
}
}
} else {
this.closeInfoWindow();
}
}
}
};
/**
* Close the info window
*/
GoogleIo.prototype.closeInfoWindow = function() {
this.infoWindow_.close();
};
/**
* Trim whitespace from a string
*
* @param {string} s The string to trim.
* @return {string} A trimmed string.
*/
GoogleIo.prototype.trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g, '');
};
/**
* Creates the markers for each room and sandbox.
* @private
*/
GoogleIo.prototype.addLevelMarkers_ = function() {
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var id = 'LEVEL' + level;
var rooms = this.LOCATIONS[id];
for (var room in rooms) {
var info = rooms[room];
info.id = room;
if (info.type) {
var marker = this.createContentMarker_(info);
this.markers_[id].push(marker);
}
}
}
};
/**
* Loads the Mall maps content.
*
* @private
*/
GoogleIo.prototype.loadMallMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 't0bDxnEqbFO4XuYpkA070Nw';
var worksheetIDs = {
'sessions': 'od6',
'sandbox': 'od5'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Converts a time to 24 hour time.
* @param {string} time A time string in 12 hour format.
* @return {string} A time in 24 hour format.
* @private
*/
GoogleIo.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* The callback for when the map json is loaded.
*
* @param {Object} json The json object with the map content.
*/
GoogleIo.prototype.loadSandboxCallback = function(json) {
var updated = json.feed.updated.$t;
var lastUpdated = this.getFromLocalStorage_('sandboxUpdated');
var sandbox = this.getFromLocalStorage_('sandbox');
if (updated == lastUpdated && sandbox) {
return;
}
var contentItems = [];
var entries = json.feed.entry;
for (var i = 0, entry; entry = entries[i]; i++) {
contentItems.push({
companyName: entry.gsx$companyname.$t,
companyDesc: entry.gsx$companydesc.$t,
companyUrl: entry.gsx$companyurl.$t,
pod: this.nameToId_(entry.gsx$companypod.$t)
});
}
this.sandboxItems_ = contentItems;
this.addToLocalStorage_('sandbox', contentItems);
this.addToLocalStorage_('sandboxUpdated', updated);
this.checkLocationHash_(true);
};
/**
* The callback for when the map json is loaded.
*
* @param {Object} json The json object with the map content.
*/
GoogleIo.prototype.loadSessionsCallback = function(json) {
var updated = json.feed.updated.$t;
var lastUpdated = this.getFromLocalStorage_('sessionsUpdated');
var sessions = this.getFromLocalStorage_('sessions');
if (updated == lastUpdated && sessions) {
return;
}
var contentItems = [];
var entries = json.feed.entry;
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {
sessionDate: entry.gsx$sessiondate.$t,
sessionTime: entry.gsx$sessiontime.$t,
room: this.nameToId_(entry.gsx$room.$t),
product: entry.gsx$product.$t,
track: entry.gsx$track.$t,
waveId: entry.gsx$waveid.$t,
sessionTitle: entry.gsx$sessiontitle.$t,
sessionLink: entry.gsx$sessionlink.$t,
sessionSpeakers: entry.gsx$sessionspeakers.$t,
sessionAbstract: entry.gsx$sessionabstract.$t
};
if (item.sessionDate.indexOf('19') != -1) {
item.sessionDay = 19;
} else {
item.sessionDay = 20;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.addToLocalStorage_('sessions', contentItems);
this.addToLocalStorage_('sessionsUpdated', updated);
this.sessionItems_ = contentItems;
this.checkLocationHash_(true);
};
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
GoogleIo.prototype.createContentMarker_ = function(item) {
var image = new google.maps.MarkerImage(
'images/marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'images/marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new google.maps.Marker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
zIndex: this.markerIndex_
});
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo(item);
});
return marker;
};
/**
* Open a info window for a content item.
*
* @param {Object} item A content item that was read from the IO speradher that
* contains a type, id and title.
*/
GoogleIo.prototype.openContentInfo = function(item) {
if (this.hasMapContainer_()) {
MAP_CONTAINER.openContentInfo(item.id);
return;
}
var now = new Date();
var may20 = new Date('May 20, 2010');
var day = now < may20 ? 19 : 20;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session' && this.sessionItems_) {
if (day == 19) {
content.push('<h3>' + title + ' - Wednesday May 19</h3>');
} else {
content.push('<h3>' + title + ' - Thursday May 20</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.room == item.id && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions = sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
this.SESSION_BASE_ + session.sessionLink + '.html">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox' && this.sandboxItems_) {
content.push('<h3>' + item.name + '</h3>');
content.push('<div class="sandbox">');
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.pod == item.id) {
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
}
if (item.type == 'officehours' && this.officeHoursItems_) {
if (day == 19) {
content.push('<h3>Office Hours - Wednesday May 19</h3>');
} else {
content.push('<h3>Office Hours - Thursday May 20</h3>');
}
empty = false;
var items = this.officeHoursItems_[day];
for (var time in items) {
content.push('<div class="session"><div class="session-time">' +
time + '</div><div class="session-products">');
for (var i = 0, product; product = items[time][i]; i++) {
content.push('<div>' + product + '</div>');
}
content.push('</div></div>');
}
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
var that = this;
google.maps.event.addListenerOnce(this.infoWindow_, 'closeclick', function() {
that.updateLocationHash(that.currentLevel_);
});
};
/**
* Custom sort function for sessions
* @param {string} a Session a.
* @param {string} b Session b.
* @return {number} 1 if greater, -1 if less, 0 if equal.
* @private
*/
GoogleIo.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return ((aStart < bStart) ? -1 : ((aStart > bStart) ? 1 : 0));
};
/**
* Shows the toolbox and add the events to the level buttons.
* @private
*/
GoogleIo.prototype.enableToolbox_ = function() {
var toolbox = document.getElementById('toolbox');
var btnLevel1 = document.getElementById('btn-level1');
var btnLevel2 = document.getElementById('btn-level2');
var btnLevel3 = document.getElementById('btn-level3');
var myLocation = document.getElementById('my-location');
var that = this;
toolbox.className = toolbox.className.replace('hide', '');
google.maps.event.addDomListener(btnLevel1, 'click', function(e) {
that.handleLevelClick_(e);
});
google.maps.event.addDomListener(btnLevel2, 'click', function(e) {
that.handleLevelClick_(e);
});
google.maps.event.addDomListener(btnLevel3, 'click', function(e) {
that.handleLevelClick_(e);
});
if (myLocation) {
google.maps.event.addDomListener(myLocation, 'click', function(e) {
that.handleMyLocationClick_(e);
});
}
};
/**
* Handles the click of a level button.
*
* @param {Event} e The event.
* @private
*/
GoogleIo.prototype.handleMyLocationClick_ = function(e) {
e.stopPropagation();
e.preventDefault();
this.map_.setCenter(this.userPosition_);
this.showLevel(this.userLevel_, true);
};
/**
* Handles the click of a level button.
*
* @param {boolean} show To show or not.
* @private
*/
GoogleIo.prototype.toggleMyLocationButton_ = function(show) {
var myLocation = document.getElementById('my-location');
if (show) {
myLocation.className = myLocation.className.replace('hide', '');
} else {
myLocation.className += ' hide';
}
};
/**
* Handles the click of a level button.
*
* @param {Event} e The event.
* @private
*/
GoogleIo.prototype.handleLevelClick_ = function(e) {
e.stopPropagation();
e.preventDefault();
var link = e.currentTarget;
var level = link.id.replace('btn-level', '');
this.showLevel(level, true);
};
/**
* Updates the location hash.
*
* @param {string} level The level of the map.
* @param {string} opt_id The id of the marker (optional).
*/
GoogleIo.prototype.updateLocationHash = function(level, opt_id) {
document.location.hash = 'level' + level + (opt_id ? ':' + opt_id : '');
};
/**
* Sets a level to show.
*
* @param {string} level The level of the map.
* @param {boolean?} opt_updateHash Whether to update the hash (optional).
* @param {boolean?} opt_force Whether to force the update or not (optional).
*/
GoogleIo.prototype.showLevel = function(level, opt_updateHash, opt_force) {
if (!opt_force && level == this.currentLevel_) {
// Already on this level so do nothing;
return;
}
var prevLevel = this.currentLevel_;
var prevLevelBtn = document.getElementById('btn-level' + this.currentLevel_);
var currentLevelBtn = document.getElementById('btn-level' + level);
if (prevLevelBtn) {
prevLevelBtn.className = prevLevelBtn.className.replace(/selected/, '');
}
if (currentLevelBtn) {
currentLevelBtn.className += ' selected';
}
this.currentLevel_ = parseInt(level, 10);
if (this.map_.overlayMapTypes.length != 0) {
this.map_.overlayMapTypes.removeAt(0);
}
if (this.userLocationMarker_) {
var image;
if (this.currentLevel_ == this.userLevel_) {
image = new google.maps.MarkerImage(
'images/my_location.png',
new google.maps.Size(14, 14),
new google.maps.Point(0, 0));
} else {
image = new google.maps.MarkerImage(
'images/my_location_diff.png',
new google.maps.Size(14, 14),
new google.maps.Point(0, 0));
}
this.userLocationMarker_.setIcon(image);
}
this.addMallMapOverlay_();
if (this.markers_) {
if (prevLevel) {
var key = 'LEVEL' + prevLevel;
for (var i = 0, marker; marker = this.markers_[key][i]; i++) {
marker.setMap(null);
}
}
for (var i = 0, marker; marker = this.markers_['LEVEL' + level][i]; i++) {
marker.setMap(this.map_);
}
}
this.closeInfoWindow();
if (opt_updateHash && !this.hasMapContainer_()) {
this.updateLocationHash(level);
}
};
/**
* Add the mall floor overlay to the map.
*
* @private
*/
GoogleIo.prototype.addMallMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256),
isPng: true
});
this.map_.overlayMapTypes.insertAt(0, overlay);
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
GoogleIo.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_RESOLUTION_ > zoom || zoom > this.MAX_RESOLUTION_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
template = template.replace('{L}', this.currentLevel_).replace('{Z}',
zoom).replace('{X}', coord.x).replace('{Y}', coord.y);
return template;
};
/**
* Sets the users location on the map.
* @param {string} lat The users lat position.
* @param {string} lng The users lng position.
* @param {string} level The level that the user is on.
* @param {boolean} opt_center To center on the user or not.
* @param {booelan} opt_showLevel To change the level or not.
*/
GoogleIo.prototype.setUserLocation = function(lat, lng, level, opt_center,
opt_showLevel) {
if (!this.userLocationMarker_) {
var image = new google.maps.MarkerImage(
'images/my_location.png',
new google.maps.Size(14, 14),
new google.maps.Point(0, 0));
this.userLocationMarker_ = new google.maps.Marker({
icon: image,
zIndex: this.userIndex_
});
} else {
if (this.currentLevel_ == level) {
image = new google.maps.MarkerImage(
'images/my_location.png',
new google.maps.Size(14, 14),
new google.maps.Point(0, 0));
} else {
image = new google.maps.MarkerImage(
'images/my_location_diff.png',
new google.maps.Size(14, 14),
new google.maps.Point(0, 0));
}
this.userLocationMarker_.setIcon(image);
}
var ne = new google.maps.LatLng(37.785001391734994, -122.40050554275513);
var sw = new google.maps.LatLng(37.779718683356776, -122.40721106529236);
var buildingBounds = new google.maps.LatLngBounds(sw, ne);
this.userPosition_ = new google.maps.LatLng(lat, lng);
if (buildingBounds.contains(this.userPosition_)) {
this.userLocationMarker_.setPosition(this.userPosition_);
this.userLocationMarker_.setMap(this.map_);
this.userLevel_ = level;
if (opt_showLevel) {
this.showLevel(level, true);
}
if (opt_center) {
this.map_.setCenter(this.userPosition_);
}
this.toggleMyLocationButton_(true);
} else {
this.userPosition_ = null;
this.userLocationMarker_.setMap(null);
this.toggleMyLocationButton_(false);
}
};
/**
* Show the location based on the id.
*
* @param {string} id The id of the location to show.
*/
GoogleIo.prototype.showLocationById = function(id) {
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var levelId = 'LEVEL' + level;
for (var room in this.LOCATIONS[levelId]) {
if (room == id) {
var info = this.LOCATIONS[levelId][room];
var latLng = new google.maps.LatLng(info.lat, info.lng);
if (this.userPosition_) {
var bounds = new google.maps.LatLngBounds(latLng, this.userPosition_);
this.map_.fitBounds(bounds);
} else {
this.map_.setCenter(latLng);
this.map_.setZoom(this.MAX_RESOLUTION_);
}
this.showLevel(level, true);
}
}
}
};
/**
* @type {Object}
* @private
*/
GoogleIo.prototype.officeHoursItems_ = {
'19': {
'12:00pm-2:30pm': [
'Enterprise',
'Go Programming Language',
'Google Project Hosting',
'Social Web',
'Google APIs',
'App Engine'],
'2:30pm-5:00pm': [
'Chrome',
'Closure Compiler',
'Geo',
'GWT',
'Wave',
'Developer Docs',
'App Engine']
},
'20': {
'12:00pm-3:00pm': [
'Chrome',
'Android',
'Geo',
'GWT',
'Wave',
'Developer Docs',
'App Engine'],
'3:00pm-5:30pm': [
'Enterprise',
'Android',
'Google Project Hosting',
'Social Web',
'Google APIs',
'App Engine']
}
};
/**
* @type {Object}
*/
GoogleIo.prototype.LOCATIONS = {
'LEVEL1': {},
'LEVEL2': {
'firesidechatroom': {
lat: 37.783046918434756,
lng: -122.40462005138397,
icon: 'info',
title: 'Fireside Chats',
type: 'session'
},
'1': {
lat: 37.78342001060504,
lng: -122.4041486531496,
icon: 'media',
title: 'Room 1',
type: 'session'
},
'2': {
lat: 37.78331189886305,
lng: -122.40430690348148,
icon: 'media',
title: 'Room 2',
type: 'session'
},
'3': {
lat: 37.78317304923709,
lng: -122.40448258817196,
icon: 'media',
title: 'Room 3',
type: 'session'
},
'4': {
lat: 37.78328222110238,
lng: -122.40380935370922,
icon: 'media',
title: 'Room 4',
type: 'session'
},
'5': {
lat: 37.78314443134288,
lng: -122.40397699177265,
icon: 'media',
title: 'Room 5',
type: 'session'
},
'6': {
lat: 37.78292608704408,
lng: -122.4042559415102,
icon: 'media',
title: 'Room 6',
type: 'session'
},
'7': {
lat: 37.7830098210991,
lng: -122.40380734205246,
icon: 'media',
title: 'Room 7',
type: 'session'
},
'8': {
lat: 37.782828573847965,
lng: -122.40403197705746 ,
icon: 'media',
title: 'Room 8',
type: 'session'
},
'9': {
lat: 37.78269608288613 ,
lng: -122.40420296788216,
icon: 'media',
title: 'Room 9',
type: 'session'
},
'pressroom': {
lat: 37.78311899320535,
lng: -122.4036256223917
},
'appengine': {
lat: 37.78361387539269,
lng: -122.40358136594296,
type: 'sandbox',
icon: 'generic',
name: 'App Engine'
},
'chrome': {
lat: 37.7832864607833,
lng: -122.4032662063837,
type: 'sandbox',
icon: 'generic',
name: 'Chrome'
},
'enterprise': {
lat: 37.78332143814089,
lng: -122.4031562358141,
type: 'sandbox',
icon: 'generic',
name: 'Enterprise'
},
'android': {
lat: 37.78343484945917,
lng: -122.40348614752293,
type: 'sandbox',
icon: 'generic',
name: 'Android'
},
'geo': {
lat: 37.783660611659144,
lng: -122.40379594266415,
type: 'sandbox',
icon: 'generic',
name: 'Geo'
},
'googleapis': {
lat: 37.78362245471605,
lng: -122.40368865430355,
type: 'sandbox',
icon: 'generic',
name: 'Google APIs'
},
'gwt': {
lat: 37.78322286554527,
lng: -122.40321524441242,
type: 'sandbox',
icon: 'generic',
name: 'GWT'
},
'socialweb': {
lat: 37.783549320520045,
lng: -122.40365378558636,
type: 'sandbox',
icon: 'generic',
name: 'Social Web'
},
'wave': {
lat: 37.78369982849679,
lng: -122.4037168174982,
type: 'sandbox',
icon: 'generic',
name: 'Wave'
},
'scvngr': {
lat: 37.78356521926445,
lng: -122.40382008254528
},
'chevvy': {
lat: 37.78331613854221,
lng: -122.40365445613861
}
},
'LEVEL3': {
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote'
},
'officehours': {
lat: 37.78367969012315,
lng: -122.4036893248558,
icon: 'generic',
title: 'Office Hours',
type: 'officehours'
},
'gtug': {
lat: 37.783293880224164,
lng: -122.40323670208454
}
}
};
// Create the Google Io map object.
var googleIo = new GoogleIo();
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
var HAS_SEARCH_PAGE = false;
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
if (HAS_SEARCH_PAGE) {
return true;
} else {
sync_selection_table(toroot);
return false;
}
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
if (HAS_SEARCH_PAGE) {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
}
return false;
}
| JavaScript |
var NAVTREE_DATA =
[ [ "com.caverock.androidsvg", "com/caverock/androidsvg/package-summary.html", [ [ "Classes", null, [ [ "PreserveAspectRatio", "com/caverock/androidsvg/PreserveAspectRatio.html", null, "" ], [ "SimpleAssetResolver", "com/caverock/androidsvg/SimpleAssetResolver.html", null, "" ], [ "SVG", "com/caverock/androidsvg/SVG.html", null, "" ], [ "SVGExternalFileResolver", "com/caverock/androidsvg/SVGExternalFileResolver.html", null, "" ], [ "SVGImageView", "com/caverock/androidsvg/SVGImageView.html", null, "" ] ]
, "" ], [ "Enums", null, [ [ "PreserveAspectRatio.Alignment", "com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", null, "" ], [ "PreserveAspectRatio.Scale", "com/caverock/androidsvg/PreserveAspectRatio.Scale.html", null, "" ] ]
, "" ], [ "Exceptions", null, [ [ "SVGParseException", "com/caverock/androidsvg/SVGParseException.html", null, "" ] ]
, "" ] ]
, "" ] ]
;
| JavaScript |
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_INDEX_COOKIE = "api_level_index";
var minLevelIndex = 0;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevelIndex = readCookie(API_LEVEL_INDEX_COOKIE); // No cookie (zero) is the same as maxLevel.
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevelValue = $("body").attr("class");
minLevelIndex = apiKeyToIndex(minLevelValue);
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = SINCE_DATA.length-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_LABELS[i]);
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option").get(SINCE_DATA.length - userApiLevelIndex - 1);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevelIndex = SINCE_DATA.length - 1;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevelIndex, "body");
} else {
selectedLevelIndex = getSelectedLevelIndex();
toggleVisisbleApis(selectedLevelIndex, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_INDEX_COOKIE, selectedLevelIndex, null, expiration);
}
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
showApiWarning(thing, selectedLevelIndex, minLevelIndex);
}
function showApiWarning(thing, selectedLevelIndex, minLevelIndex) {
if (selectedLevelIndex < minLevelIndex) {
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " is not available with API version "
+ SINCE_LABELS[selectedLevelIndex] + ".</strong></p>"
+ "<p>To reveal this "
+ "document, change the value in the API filter above.</p>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevelIndex, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelPos = className.lastIndexOf("-")+1;
var apiLevelEndPos = className.indexOf(" ", apiLevelPos);
apiLevelEndPos = apiLevelEndPos != -1 ? apiLevelEndPos : className.length;
var apiLevelName = className.substring(apiLevelPos, apiLevelEndPos);
var apiLevelIndex = apiKeyToIndex(apiLevelName);
if (apiLevelIndex > selectedLevelIndex) {
obj.addClass("absent").attr("title","Requires API Level "+SINCE_LABELS[apiLevelIndex]+" or higher");
} else {
obj.removeClass("absent").removeAttr("title");
}
});
}
function apiKeyToIndex(key) {
for (i = 0; i < SINCE_DATA.length; i++) {
if (SINCE_DATA[i] == key) {
return i;
}
}
return -1;
}
function getSelectedLevelIndex() {
return SINCE_DATA.length - $("#apiLevelSelector").attr("selectedIndex") - 1;
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary.
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = toAssets + "images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data() {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toAssets + "navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toAssets + "images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toAssets + "images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var toAssets;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root, assets) {
toRoot = root;
toAssets = assets;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var DATA = [
{ id:0, label:"com.caverock.androidsvg", link:"com/caverock/androidsvg/package-summary.html", type:"package" },
{ id:1, label:"com.caverock.androidsvg.PreserveAspectRatio", link:"com/caverock/androidsvg/PreserveAspectRatio.html", type:"class" },
{ id:2, label:"com.caverock.androidsvg.PreserveAspectRatio.Alignment", link:"com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", type:"class" },
{ id:3, label:"com.caverock.androidsvg.PreserveAspectRatio.Scale", link:"com/caverock/androidsvg/PreserveAspectRatio.Scale.html", type:"class" },
{ id:4, label:"com.caverock.androidsvg.SVG", link:"com/caverock/androidsvg/SVG.html", type:"class" },
{ id:5, label:"com.caverock.androidsvg.SVGExternalFileResolver", link:"com/caverock/androidsvg/SVGExternalFileResolver.html", type:"class" },
{ id:6, label:"com.caverock.androidsvg.SVGImageView", link:"com/caverock/androidsvg/SVGImageView.html", type:"class" },
{ id:7, label:"com.caverock.androidsvg.SVGParseException", link:"com/caverock/androidsvg/SVGParseException.html", type:"class" },
{ id:8, label:"com.caverock.androidsvg.SimpleAssetResolver", link:"com/caverock/androidsvg/SimpleAssetResolver.html", type:"class" }
];
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
var HAS_SEARCH_PAGE = false;
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
if (HAS_SEARCH_PAGE) {
return true;
} else {
sync_selection_table(toroot);
return false;
}
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
if (HAS_SEARCH_PAGE) {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
}
return false;
}
| JavaScript |
var NAVTREE_DATA =
[ [ "com.caverock.androidsvg", "com/caverock/androidsvg/package-summary.html", [ [ "Classes", null, [ [ "PreserveAspectRatio", "com/caverock/androidsvg/PreserveAspectRatio.html", null, "" ], [ "SimpleAssetResolver", "com/caverock/androidsvg/SimpleAssetResolver.html", null, "" ], [ "SVG", "com/caverock/androidsvg/SVG.html", null, "" ], [ "SVGExternalFileResolver", "com/caverock/androidsvg/SVGExternalFileResolver.html", null, "" ], [ "SVGImageView", "com/caverock/androidsvg/SVGImageView.html", null, "" ] ]
, "" ], [ "Enums", null, [ [ "PreserveAspectRatio.Alignment", "com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", null, "" ], [ "PreserveAspectRatio.Scale", "com/caverock/androidsvg/PreserveAspectRatio.Scale.html", null, "" ] ]
, "" ], [ "Exceptions", null, [ [ "SVGParseException", "com/caverock/androidsvg/SVGParseException.html", null, "" ] ]
, "" ] ]
, "" ] ]
;
| JavaScript |
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_INDEX_COOKIE = "api_level_index";
var minLevelIndex = 0;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevelIndex = readCookie(API_LEVEL_INDEX_COOKIE); // No cookie (zero) is the same as maxLevel.
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevelValue = $("body").attr("class");
minLevelIndex = apiKeyToIndex(minLevelValue);
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = SINCE_DATA.length-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_LABELS[i]);
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option").get(SINCE_DATA.length - userApiLevelIndex - 1);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevelIndex = SINCE_DATA.length - 1;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevelIndex, "body");
} else {
selectedLevelIndex = getSelectedLevelIndex();
toggleVisisbleApis(selectedLevelIndex, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_INDEX_COOKIE, selectedLevelIndex, null, expiration);
}
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
showApiWarning(thing, selectedLevelIndex, minLevelIndex);
}
function showApiWarning(thing, selectedLevelIndex, minLevelIndex) {
if (selectedLevelIndex < minLevelIndex) {
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " is not available with API version "
+ SINCE_LABELS[selectedLevelIndex] + ".</strong></p>"
+ "<p>To reveal this "
+ "document, change the value in the API filter above.</p>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevelIndex, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelPos = className.lastIndexOf("-")+1;
var apiLevelEndPos = className.indexOf(" ", apiLevelPos);
apiLevelEndPos = apiLevelEndPos != -1 ? apiLevelEndPos : className.length;
var apiLevelName = className.substring(apiLevelPos, apiLevelEndPos);
var apiLevelIndex = apiKeyToIndex(apiLevelName);
if (apiLevelIndex > selectedLevelIndex) {
obj.addClass("absent").attr("title","Requires API Level "+SINCE_LABELS[apiLevelIndex]+" or higher");
} else {
obj.removeClass("absent").removeAttr("title");
}
});
}
function apiKeyToIndex(key) {
for (i = 0; i < SINCE_DATA.length; i++) {
if (SINCE_DATA[i] == key) {
return i;
}
}
return -1;
}
function getSelectedLevelIndex() {
return SINCE_DATA.length - $("#apiLevelSelector").attr("selectedIndex") - 1;
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = toAssets + "images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary.
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = toAssets + "images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data() {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toAssets + "navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector").attr("selectedIndex");
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toAssets + "images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toAssets + "images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var toAssets;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root, assets) {
toRoot = root;
toAssets = assets;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var DATA = [
{ id:0, label:"com.caverock.androidsvg", link:"com/caverock/androidsvg/package-summary.html", type:"package" },
{ id:1, label:"com.caverock.androidsvg.PreserveAspectRatio", link:"com/caverock/androidsvg/PreserveAspectRatio.html", type:"class" },
{ id:2, label:"com.caverock.androidsvg.PreserveAspectRatio.Alignment", link:"com/caverock/androidsvg/PreserveAspectRatio.Alignment.html", type:"class" },
{ id:3, label:"com.caverock.androidsvg.PreserveAspectRatio.Scale", link:"com/caverock/androidsvg/PreserveAspectRatio.Scale.html", type:"class" },
{ id:4, label:"com.caverock.androidsvg.SVG", link:"com/caverock/androidsvg/SVG.html", type:"class" },
{ id:5, label:"com.caverock.androidsvg.SVGExternalFileResolver", link:"com/caverock/androidsvg/SVGExternalFileResolver.html", type:"class" },
{ id:6, label:"com.caverock.androidsvg.SVGImageView", link:"com/caverock/androidsvg/SVGImageView.html", type:"class" },
{ id:7, label:"com.caverock.androidsvg.SVGParseException", link:"com/caverock/androidsvg/SVGParseException.html", type:"class" },
{ id:8, label:"com.caverock.androidsvg.SimpleAssetResolver", link:"com/caverock/androidsvg/SimpleAssetResolver.html", type:"class" }
];
| JavaScript |
(function () {
var host = window.location.hostname;
var port = window.location.port;
var videoPlugin;
var videoStream;
var audioPlugin;
var audioStream;
var error;
function stream(object,type,done) {
var state = "idle";
return {
restart: function () {
state = "restarting";
done();
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
setTimeout(function () {
this.start(false);
}.bind(this),2000);
} else {
this.start(false);
}
},
start: function (e) {
var req = generateUriParams(type);
state = "starting";
if (e!==false) done();
$.ajax({
type: 'GET',
url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri,
success: function (e) {
setTimeout(function () {
state = "streaming";
object.playlist.add('http://'+host+':'+port+'/spydroid.sdp?id='+(type==='video'?0:1)+'&'+req.uri,'',req.params);
object.playlist.playItem(0);
setTimeout(function () {
done();
},600);
},1000);
},
error: function () {
state = "error";
getError();
}
});
},
stop: function () {
$.ajax({
type: 'GET',
url: 'spydroid.sdp?id='+(type==='video'?0:1)+'&stop',
success: function (e) {
//done(); ??
},
error: function () {
state = "error";
getError();
}
});
if (object.playlist.isPlaying) {
object.playlist.stop();
object.playlist.clear();
object.playlist.items.clear();
}
state = "idle";
done();
},
getState: function() {
return state;
},
isStreaming: function () {
return object.playlist.isPlaying;
}
}
}
function sendRequest(request,success,error) {
var data;
if (typeof request === "string") data = {'action':request}; else data = request;
$.ajax({type: 'POST', url: 'request.json', data: JSON.stringify(data), success:success, error:error});
}
function updateBatteryLevel(level) {
$('#battery>#level').text(level);
setTimeout(function () {
sendRequest(
"battery",
function (e) {
updateBatteryLevel(e.battery);
},
function () {
updateBatteryLevel('??');
}
);
},100000);
}
function updateTooltip(title) {
$('#tooltip>div').hide();
$('#tooltip #'+title).show();
}
function loadSettings(config) {
$('#resolution,#framerate,#bitrate,#audioEncoder,#videoEncoder').children().each(function (c) {
if ($(this).val()===config.videoResolution ||
$(this).val()===config.videoFramerate ||
$(this).val()===config.videoBitrate ||
$(this).val()===config.audioEncoder ||
$(this).val()===config.videoEncoder ) {
$(this).parent().children().prop('selected',false);
$(this).prop('selected',true);
}
});
if (config.streamAudio===false) $('#audioEnabled').prop('checked',false);
if (config.streamVideo===false) $('#videoEnabled').prop('checked',false);
}
function saveSettings() {
var res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
var videoQuality = /[0-9]+/.exec($('#bitrate').val())[0]+'-'+/[0-9]+/.exec($('#framerate').val())[0]+'-'+res[1]+'-'+res[2];
var settings = {
'stream_video': $('#videoEnabled').prop('checked')===true,
'stream_audio': $('#audioEnabled').prop('checked')===true,
'video_encoder': $('#videoEncoder').val(),
'audio_encoder': $('#audioEncoder').val(),
'video_quality': videoQuality
};
sendRequest({'action':'set','settings':settings});
}
function loadSoundsList(sounds) {
var list = $('#soundslist'), category, name;
sounds.forEach(function (e) {
category = e.match(/([a-z0-9]+)_/)[1];
name = e.match(/[a-z0-9]+_([a-z0-9_]+)/)[1];
if ($('.category.'+category).length==0) list.append(
'<div class="category '+category+'"><span class="category-name">'+category+'</span><div class="category-separator"></div></div>'
);
$('.category.'+category).append('<div class="sound" id="'+e+'"><a>'+name.replace(/_/g,' ')+'</a></div>');
});
}
function testScreenState(state) {
if (state===0) {
$('#error-screenoff').fadeIn(1000);
$('#glass').fadeIn(1000);
}
}
function generateUriParams(type) {
var audioEncoder, videoEncoder, cache, rotation, flash, camera, res;
// Audio conf
if ($('#audioEnabled').prop('checked')) {
audioEncoder = $('#audioEncoder').val()=='AMR-NB'?'amr':'aac';
} else {
audioEncoder = "nosound";
}
// Resolution
res = /([0-9]+)x([0-9]+)/.exec($('#resolution').val());
// Video conf
if ($('#videoEnabled').prop('checked')) {
videoEncoder = ($('#videoEncoder').val()=='H.263'?'h263':'h264')+'='+
/[0-9]+/.exec($('#bitrate').val())[0]+'-'+
/[0-9]+/.exec($('#framerate').val())[0]+'-';
videoEncoder += res[1]+'-'+res[2];
} else {
videoEncoder = "novideo";
}
// Flash
if ($('#flashEnabled').val()==='1') flash = 'on'; else flash = 'off';
// Camera
camera = $('#cameraId').val();
// Params
cache = /[0-9]+/.exec($('#cache').val())[0];
return {
uri:type==='audio'?audioEncoder:(videoEncoder+'&flash='+flash+'&camera='+camera),
params:[':network-caching='+cache]
}
}
function getError() {
sendRequest(
'state',
function (e) {
error = e.state.lastError;
updateStatus();
},
function () {
error = 'Phone unreachable !';
updateStatus();
}
);
}
function updateStatus() {
var status = $('#status'), button = $('#connect>div>h1'), cover = $('#vlc-container #upper-layer');
// STATUS
if (videoStream.getState()==='starting' || videoStream.getState()==='restarting' ||
audioStream.getState()==='starting' || audioStream.getState()==='restarting') {
status.html(__('Trying to connect...'))
} else {
if (!videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('NOT CONNECTED'));
else if (videoStream.isStreaming() && !audioStream.isStreaming()) status.html(__('Streaming video but not audio'));
else if (!videoStream.isStreaming() && audioStream.isStreaming()) status.html(__('Streaming audio but not video'));
else status.html(__('Streaming audio and video'));
}
// BUTTON
if ((videoStream.getState()==='idle' || videoStream.getState()==='error') &&
(audioStream.getState()==='idle' || audioStream.getState()==='error')) {
button.html(__('Connect !!'));
} else button.text(__('Disconnect ?!'));
// WINDOW
if (videoStream.getState()==='error' || audioStream.getState()==='error') {
videoPlugin.css('visibility','hidden');
cover.html('<div id="wrapper"><h1>'+__('An error occurred')+' :(</h1><p>'+error+'</p></div>');
} else if (videoStream.getState()==='restarting' || audioStream.getState()==='restarting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('UPDATING SETTINGS')+'</h1></div>').show();
} else if (videoStream.getState()==='starting' || audioStream.getState()==='starting') {
videoPlugin.css('visibility','hidden');
cover.css('background','black').html('<div id="mask"></div><div id="wrapper"><h1>'+__('CONNECTION')+'</h1></div>').show();
} else if (videoStream.getState()==='streaming') {
videoPlugin.css('visibility','inherit');
cover.hide();
}
if (videoStream.getState()==='idle') {
if (audioStream.getState()==='streaming') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/speaker.png") center no-repeat').show();
} else if (audioStream.getState()==='idle') {
videoPlugin.css('visibility','hidden');
cover.html('').css('background','url("images/eye.png") center no-repeat').show();
}
}
}
function disableAndEnable(input) {
input.prop('disabled',true);
setTimeout(function () {
input.prop('disabled',false);
},1000);
}
function setupEvents() {
var cover = $('#vlc-container #upper-layer');
var status = $('#status');
var button = $('#connect>div>h1');
$('.popup #close').click(function (){
$('#glass').fadeOut();
$('.popup').fadeOut();
});
$('#connect').click(function () {
if ($(this).prop('disabled')===true) return;
disableAndEnable($(this));
if ((videoStream.getState()!=='idle' && videoStream.getState()!=='error') ||
(audioStream.getState()!=='idle' && audioStream.getState()!=='error')) {
videoStream.stop();
audioStream.stop();
} else {
if (!$('#videoEnabled').prop('checked') && !$('#audioEnabled').prop('checked')) return;
if ($('#videoEnabled').prop('checked')) videoStream.start();
if ($('#audioEnabled').prop('checked')) audioStream.start();
}
});
$('#torch-button').click(function () {
if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return;
disableAndEnable($(this));
if ($('#flashEnabled').val()=='0') {
$('#flashEnabled').val('1');
$(this).addClass('torch-on');
} else {
$('#flashEnabled').val('0');
$(this).removeClass('torch-on');
}
if (videoStream.getState()==='streaming') videoStream.restart();
});
$('#buzz-button').click(function () {
$(this).animate({'padding-left':'+=10'}, 40, 'linear')
.animate({'padding-left':'-=20'}, 80, 'linear')
.animate({'padding-left':'+=10'}, 40, 'linear');
sendRequest('buzz');
});
$(document).on('click', '.camera-not-selected', function () {
if ($(this).prop('disabled')===true || videoStream.getState()==='starting') return;
$('#cameras span').addClass('camera-not-selected');
$(this).removeClass('camera-not-selected');
disableAndEnable($('.camera-not-selected'));
$('#cameraId').val($(this).attr('data-id'));
if (videoStream.getState()==='streaming') videoStream.restart();
})
$('.audio select').change(function () {
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('.audio input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#audioEnabled').prop('checked')) audioStream.restart(); else audioStream.stop();
disableAndEnable($(this));
}
});
$('.video select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
});
$('.video input').change(function () {
if (audioStream.isStreaming() || videoStream.isStreaming()) {
if ($('#videoEnabled').prop('checked')) videoStream.restart(); else videoStream.stop();
disableAndEnable($(this));
}
});
$('.cache select').change(function () {
if (videoStream.isStreaming()) {
videoStream.restart();
}
if (audioStream.isStreaming()) {
audioStream.restart();
}
});
$('select,input').change(function () {
saveSettings();
});
$('.section').click(function () {
$('.section').removeClass('selected');
$(this).addClass('selected');
updateTooltip($(this).attr('id'));
});
$(document).on('click', '.sound', function () {
sendRequest([{'action':'play','name':$(this).attr('id')}]);
});
$('#fullscreen').click(function () {
videoPlugin[0].video.toggleFullscreen();
});
$('#hide-tooltip').click(function () {
$('body').width($('body').width() - $('#tooltip').width());
$('#tooltip').hide();
$('#need-help').show();
});
$('#need-help').click(function () {
$('body').width($('body').width() + $('#tooltip').width());
$('#tooltip').show();
$('#need-help').hide();
});
window.onbeforeunload = function (e) {
videoStream.stop();
audioStream.stop();
}
};
$(document).ready(function () {
videoPlugin = $('#vlcv');
videoStream = stream(videoPlugin[0],'video',updateStatus);
audioPlugin = $('#vlca');
audioStream = stream(audioPlugin[0],'audio',updateStatus);
sendRequest([{'action':'sounds'},{'action':'screen'},{'action':'get'},{'action':'battery'}], function (data) {
// Verify that the screen is not turned off
testScreenState(data.screen);
// Fetch the list of sounds available on the phone
loadSoundsList(data.sounds);
// Retrieve the configuration of Spydroid on the phone
loadSettings(data.get);
// Retrieve the battery level
updateBatteryLevel(data.battery);
});
// Translate the interface in the appropriate language
$('h1,h2,h3,span,p,a,em').translate();
$('.popup').each(function () {
$(this).css({'top':($(window).height()-$(this).height())/2,'left':($(window).width()-$(this).width())/2});
});
$('#tooltip').hide();
$('#need-help').show();
// Bind DOM events
setupEvents();
});
}()); | JavaScript |
(function () {
var translations = {
en: {
1:"About",
2:"Return",
3:"Change quality settings",
4:"Flash/Vibrator",
5:"Click on the torch to enable or disable the flash",
6:"Play a prerecorded sound",
7:"Connect !!",
8:"Disconnect ?!",
9:"STATUS",
10:"NOT CONNECTED",
11:"ERROR :(",
12:"CONNECTION",
13:"UPDATING SETTINGS",
14:"CONNECTED",
15:"Show some tips",
16:"Hide those tips",
17:"Those buttons will trigger sounds on your phone...",
18:"Use them to surprise your victim.",
19:"Or you could use this to surprise your victim !",
20:"This will simply toggle the led in front of you're phone, so that even in the deepest darkness, you shall not be blind...",
21:"If the stream is choppy, try reducing the bitrate or increasing the cache size.",
22:"Try it instead of H.263 if video streaming is not working at all !",
23:"The H.264 compression algorithm is more efficient but may not work on your phone...",
24:"You need to install VLC first !",
25:"During the installation make sure to check the firefox plugin !",
26:"Close",
27:"You must leave the screen of your smartphone on !",
28:"Front facing camera",
29:"Back facing camera",
30:"Switch between cameras",
31:"Streaming video but not audio",
32:"Streaming audio but not video",
33:"Streaming audio and video",
34:"Trying to connect...",
35:"Stream sound",
36:"Stream video",
37:"Fullscreen",
38:"Encoder",
39:"Resolution",
40:"Cache size",
41:"This generally happens when you are trying to use settings that are not supported by your phone.",
42:"Retrieving error message...",
43:"An error occurred",
44:"Click on the phone to make your phone buzz"
},
fr: {
1:"À propos",
2:"Retour",
3:"Changer la qualité du stream",
4:"Flash/Vibreur",
5:"Clique sur l'ampoule pour activer ou désactiver le flash",
6:"Jouer un son préenregistré",
7:"Connexion !!",
8:"Déconnecter ?!",
9:"STATUT",
10:"DÉCONNECTÉ",
11:"ERREUR :(",
12:"CONNEXION",
13:"M.A.J.",
14:"CONNECTÉ",
15:"Afficher l'aide",
16:"Masquer l'aide",
17:"Clique sur un de ces boutons pour lancer un son préenregistré sur ton smartphone !",
18:"Utilise les pour surprendre ta victime !!",
19:"Ça peut aussi servir à surprendre ta victime !",
20:"Clique sur l'ampoule pour allumer le flash de ton smartphone",
21:"Si le stream est saccadé essaye de réduire le bitrate ou d'augmenter la taille du cache.",
22:"Essaye le à la place du H.263 si le streaming de la vidéo ne marche pas du tout !",
23:"Le H.264 est un algo plus efficace pour compresser la vidéo mais il a moins de chance de marcher sur ton smartphone...",
24:"Tu dois d'abord installer VLC !!",
25:"Pendant l'installation laisse cochée l'option plugin mozilla !",
26:"Fermer",
27:"Tu dois laisser l'écran de ton smartphone allumé",
28:"Caméra face avant",
29:"Caméra face arrière",
30:"Choisir la caméra",
31:"Streaming de la vidéo",
32:"Streaming de l'audio",
33:"Streaming de l'audio et de la vidéo",
34:"Connexion en cours...",
35:"Streaming du son",
36:"Streaming de la vidéo",
37:"Plein écran",
38:"Encodeur",
39:"Résolution",
40:"Taille cache",
41:"En général, cette erreur se produit quand les paramètres sélectionnés ne sont pas compatibles avec le smartphone.",
42:"Attente du message d'erreur...",
43:"Une erreur s'est produite",
44:"Clique pour faire vibrer ton tel."
},
ru: {
1:"Спасибо",
2:"Вернуться",
3:"Изменить настройки качества",
4:"Переключатель вспышки",
5:"Нажмите здесь, чтобы включить или выключить вспышку",
6:"Проиграть звук на телефоне",
7:"Подключиться !!",
8:"Отключиться ?!",
9:"СОСТОЯНИЕ",
10:"НЕТ ПОДКЛЮЧЕНИЯ",
11:"ОШИБКА :(",
12:"ПОДКЛЮЧЕНИЕ",
13:"ОБНОВЛЕНИЕ НАСТРОЕК",
14:"ПОДКЛЮЧЕНО",
15:"Показать поясняющие советы",
16:"Спрятать эти советы",
17:"Эти кнопки будут проигрывать звуки на вашем телефоне...",
18:"Используйте их, чтобы удивить вашу жертву.",
19:"Или вы можете удивить свою жертву!",
20:"Это переключатель режима подсветки на передней части вашего телефона, так что даже в самой кромешной тьме, вы не будете слепы ...",
21:"Если поток прерывается, попробуйте уменьшить битрейт или увеличив размер кэша.",
22:"Если топоковое видео не работает совсем, попробуйте сжатие Н.263",
23:"Алгоритм сжатия H.264, является более эффективным, но может не работать на вашем телефоне ...",
24:"Вначале Вам необходимо установить VLC !",
25:"При установке убедитесь в наличии плагина для firefox !",
26:"Закрыть",
27:"Вам надо отойти от вашего смартфона.",
28:"Фронтальная камера",
29:"Камера с обратной стороны",
30:"Переключиться на другую камеру",
31:"Передача видео без звука",
32:"Передача звука без видео",
33:"Передача звука и видео",
34:"Пытаемся подключится",
35:"Аудио поток",
36:"Видео поток",
37:"На весь экран",
38:"Кодек",
39:"Разрешение",
40:"Размер кеша",
41:"Как правило, это происходит, когда вы пытаетесь использовать настройки, не поддерживаемые вашим телефоном.",
42:"Получение сообщения об ошибке ..."
},
de : {
1:"Apropos",
2:"Zurück",
3:"Qualität des Streams verändern",
4:"Fotolicht ein/aus",
5:"Klick die Glühbirne an, um das Fotolicht einzuschalten oder azufallen",
6:"Vereinbarten Ton spielen",
7:"Verbindung !!",
8:"Verbinden ?!",
9:"STATUS",
10:"NICHT VERBUNDEN",
11:"FEHLER :(",
12:"VERBINDUNG",
13:"UPDATE",
14:"VERBUNDEN",
15:"Hilfe anzeigen",
16:"Hilfe ausblenden",
17:"Klick diese Tasten an, um Töne auf deinem Smartphone spielen zu lassen !",
18:"Benutz sie, um deine Opfer zu überraschen !!",
19:"Das kann auch dein Opfer erschrecken !",
20:"Es wird die LED hinter deinem Handy anmachen, damit du nie blind bleibst, auch im tiefsten Dunkeln",
21:"Wenn das Stream ruckartig ist, versuch mal die Bitrate zu reduzieren oder die Größe vom Cache zu steigern.",
22:"Probier es ansatt H.263, wenn das Videostream überhaupt nicht funktionert !",
23:"Der H.264 Kompressionalgorithmus ist effizienter aber er wird auf deinem Handy vielleicht nicht funktionieren...",
24:"Du musst zuerst VLC installieren !!",
25:"Während der Installation, prüfe dass das Firefox plugin abgecheckt ist!",
26:"Zumachen",
27:"Du musst den Bildschirm deines Smartphones eingeschaltet lassen !",
28:"Frontkamera",
29:"Rückkamera",
30:"Kamera auswählen",
31:"Videostreaming",
32:"Audiostreaming",
33:"Video- und Audiostreaming",
34:"Ausstehende Verbindung...",
35:"Soundstreaming",
36:"Videostreaming",
37:"Ganzer Bildschirm",
38:"Encoder",
39:"Auflösung",
40:"Cachegröße",
41:"Dieser Fehler gescheht überhaupt, wenn die gewählten Einstellungen mit dem Smartphone nicht kompatibel sind.",
42:"Es wird auf die Fehlermeldung gewartet...",
43:"Ein Fehler ist geschehen..."
}
};
var lang = window.navigator.userLanguage || window.navigator.language;
//var lang = "ru";
var __ = function (text) {
var x,y=0,z;
if (lang.match(/en/i)!=null) return text;
for (x in translations) {
if (lang.match(new RegExp(x,"i"))!=null) {
for (z in translations.en) {
if (text==translations.en[z]) {
y = z;
break;
}
}
return translations[x][y]==undefined?text:translations[x][y];
}
}
return text;
};
$.fn.extend({
translate: function () {
return this.each(function () {
$(this).html(__($(this).html()));
});
}
});
window.__ = __;
}());
| JavaScript |
document.createElement('header');
document.createElement('nav');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
document.createElement('hgroup');
$(document).ready(function () {
$('.section-content,#status-container').addClass('ie8-background');
$('.category-separator').hide();
}); | JavaScript |
function refer(pageNo){
$("[name=PAGE_CURR]").val(pageNo);
$("#frmSearch").submit();
}
function referTo(pageNo,maxPage){
if($("[name=currentPage]").val()>maxPage){
alert("输入的页数超过最大页码!")
}else if($("[name=currentPage]").val()==''){
alert("请输入您需要查找的页码");
}else if($("[name=currentPage]").val()<1){
alert("请输入正确的页码!")
}else{
$("[name=PAGE_CURR]").val($("[name=currentPage]").val());
$("#frmSearch").submit();
}
}
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
return true;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
return false;
}
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var mPagePath; // initialized in ready() function
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
var GOOGLE_DATA; // combined data for google service apis, used for search suggest
// Ensure that all ajax getScript() requests allow caching
$.ajaxSetup({
cache: true
});
/****** ON LOAD SET UP STUFF *********/
$(document).ready(function() {
// show lang dialog if the URL includes /intl/
//if (location.pathname.substring(0,6) == "/intl/") {
// var lang = location.pathname.split('/')[2];
// if (lang != getLangPref()) {
// $("#langMessage a.yes").attr("onclick","changeLangPref('" + lang
// + "', true); $('#langMessage').hide(); return false;");
// $("#langMessage .lang." + lang).show();
// $("#langMessage").show();
// }
//}
// load json file for JD doc search suggestions
$.getScript(toRoot + 'jd_lists_unified.js');
// load json file for Android API search suggestions
$.getScript(toRoot + 'reference/lists.js');
// load json files for Google services API suggestions
$.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
// once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
if(jqxhr.status === 200) {
$.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
// combine GCM and GMS data
GOOGLE_DATA = GMS_DATA;
var start = GOOGLE_DATA.length;
for (var i=0; i<GCM_DATA.length; i++) {
GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
link:GCM_DATA[i].link, type:GCM_DATA[i].type});
}
}
});
}
});
// setup keyboard listener for search shortcut
$('body').keyup(function(event) {
if (event.which == 191) {
$('#search_autocomplete').focus();
}
});
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2')
.not('#tb h2')
.not('.sidebox h2')
.not('#devdoc-nav h2')
.not('h2.norule').css({marginBottom:0})
.after('<hr/>');
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false);
hideResults();
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
// Need a copy of the pagePath before it gets changed in the next block;
// it's needed to perform proper tab highlighting in offline docs (see rootDir below)
var pagePathOriginal = pagePath;
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
$("#sticky-header").addClass("design");
// highlight About tabs
} else if ($("body").hasClass("about")) {
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "about") {
$("#nav-x li.about a").addClass("selected");
} else if (rootDir == "wear") {
$("#nav-x li.wear a").addClass("selected");
} else if (rootDir == "tv") {
$("#nav-x li.tv a").addClass("selected");
} else if (rootDir == "auto") {
$("#nav-x li.auto a").addClass("selected");
}
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
$("#sticky-header").addClass("develop");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else if ($("body").hasClass("samples")) {
$("#nav-x li.samples a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
$("#sticky-header").addClass("distribute");
var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
if (secondFrag == "users") {
$("#nav-x li.users a").addClass("selected");
} else if (secondFrag == "engage") {
$("#nav-x li.engage a").addClass("selected");
} else if (secondFrag == "monetize") {
$("#nav-x li.monetize a").addClass("selected");
} else if (secondFrag == "tools") {
$("#nav-x li.disttools a").addClass("selected");
} else if (secondFrag == "stories") {
$("#nav-x li.stories a").addClass("selected");
} else if (secondFrag == "essentials") {
$("#nav-x li.essentials a").addClass("selected");
} else if (secondFrag == "googleplay") {
$("#nav-x li.googleplay a").addClass("selected");
}
} else if ($("body").hasClass("about")) {
$("#sticky-header").addClass("about");
}
// set global variable so we can highlight the sidenav a bit later (such as for google reference)
// and highlight the sidenav
mPagePath = pagePath;
highlightSidenav();
buildBreadcrumbs();
// set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if ($nextLink.length == 0) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
if ($nextLink.length == 0) {
// if that doesn't work, we're at the end of the list, so disable NEXT link
$('.next-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
}
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
if ($nextLink.length) {
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide")
.append(": " + $nextLink.html());
$('.next-class-link').find('.new').empty();
}
} else {
$('.next-page-link').attr('href', $nextLink.attr('href'))
.removeClass("hide");
// for the footer link, also add the next page title
$('.content-footer .next-page-link').append(": " + $nextLink.html());
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
// create an array for all the class descriptions
var $classDescriptions = new Array($classLinks.length);
var lang = getLangPref();
$classLinks.each(function(index) {
var langDescr = $(this).attr(lang + "-description");
if (typeof langDescr !== 'undefined' && langDescr !== false) {
// if there's a class description in the selected language, use that
$classDescriptions[index] = langDescr;
} else {
// otherwise, use the default english description
$classDescriptions[index] = $(this).attr("description");
}
});
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
+ ' width="64" height="64" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
+ ' width="64" height="64" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
initExpandableNavItems("#nav");
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (sticky) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
// Resize once loading is finished
resizeNav();
// Check if there's an anchor that we need to scroll into view.
// A delay is needed, because some browsers do not immediately scroll down to the anchor
window.setTimeout(offsetScrollForSticky, 100);
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
/* setup shadowbox for any videos that want it */
var $videoLinks = $("a.video-shadowbox-button, a.notice-developers-video");
if ($videoLinks.length) {
// if there's at least one, add the shadowbox HTML to the body
$('body').prepend(
'<div id="video-container">'+
'<div id="video-frame">'+
'<div class="video-close">'+
'<span id="icon-video-close" onclick="closeVideo()"> </span>'+
'</div>'+
'<div id="youTubePlayer"></div>'+
'</div>'+
'</div>');
// loads the IFrame Player API code asynchronously.
$.getScript("https://www.youtube.com/iframe_api");
$videoLinks.each(function() {
var videoId = $(this).attr('href').split('?v=')[1];
$(this).click(function(event) {
event.preventDefault();
startYouTubePlayer(videoId);
});
});
}
});
// END of the onload event
var youTubePlayer;
function onYouTubeIframeAPIReady() {
}
function startYouTubePlayer(videoId) {
var idAndHash = videoId.split("#");
var startTime = 0;
var lang = getLangPref();
var captionsOn = lang == 'en' ? 0 : 1;
if (idAndHash.length > 1) {
startTime = idAndHash[1].split("t=")[1] != undefined ? idAndHash[1].split("t=")[1] : 0;
}
if (youTubePlayer == null) {
youTubePlayer = new YT.Player('youTubePlayer', {
height: '529',
width: '940',
videoId: idAndHash[0],
playerVars: {start: startTime, hl: lang, cc_load_policy: captionsOn},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} else {
youTubePlayer.playVideo();
}
$("#video-container").fadeIn(200, function(){$("#video-frame").show()});
}
function onPlayerReady(event) {
event.target.playVideo();
// track the start playing event so we know from which page the video was selected
ga('send', 'event', 'Videos', 'Start: ' +
youTubePlayer.getVideoUrl().split('?v=')[1], 'on: ' + document.location.href);
}
function closeVideo() {
try {
youTubePlayer.pauseVideo();
$("#video-container").fadeOut(200);
} catch(e) {
console.log('Video not available');
$("#video-container").fadeOut(200);
}
}
/* Track youtube playback for analytics */
function onPlayerStateChange(event) {
// Video starts, send the video ID
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'Videos', 'Play',
youTubePlayer.getVideoUrl().split('?v=')[1]);
}
// Video paused, send video ID and video elapsed time
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Videos', 'Paused',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
// Video finished, send video ID and video elapsed time
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Videos', 'Finished',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
}
function initExpandableNavItems(rootTag) {
$(rootTag + ' li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me and descendants */
section.find('ul').slideUp(250, function() {
// remove 'expanded' class from my section and any children
section.closest('li').removeClass('expanded');
$('li.nav-section', section).removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
// Stop expand/collapse behavior when clicking on nav section links
// (since we're navigating away from the page)
// This selector captures the first instance of <a>, but not those with "#" as the href.
$('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
}
/** Create the list of breadcrumb links in the sticky header */
function buildBreadcrumbs() {
var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
// Add the secondary horizontal nav item, if provided
var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
if ($selectedSecondNav.length) {
$breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
}
// Add the primary horizontal nav
var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
// If there's no header nav item, use the logo link and title from alt text
if ($selectedFirstNav.length < 1) {
$selectedFirstNav = $("<a>")
.attr('href', $("div#header .logo a").attr('href'))
.text($("div#header .logo img").attr('alt'));
}
$breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
}
/** Highlight the current page in sidenav, expanding children as appropriate */
function highlightSidenav() {
// if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
if ($("ul#nav li.selected").length) {
unHighlightSidenav();
}
// look for URL in sidenav, including the hash
var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
// If the selNavLink is still empty, look for it without the hash
if ($selNavLink.length == 0) {
$selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
}
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
}
}
function unHighlightSidenav() {
$("ul#nav li.selected").removeClass("selected");
$('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
}
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
$(document).ready(function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
});
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header-wrapper').outerHeight();
var headerVisible = scrollTop < stickyTop;
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) {
// If no selected item found, exit
return;
}
// get the selected item's offset from its container nav by measuring the item's offset
// relative to the document then subtract the container nav's offset relative to the document
var selectedOffset = $selected.offset().top - $nav.offset().top;
if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
// if it's more than 80% down the nav
// scroll the item up by an amount equal to 80% the container nav's height
api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
var age = 2*365*24*60*60; // set max-age to 2 years
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; max-age=" + age +"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
var sticky = false;
var stickyTop;
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
/* Sets the vertical scoll position at which the sticky bar should appear.
This method is called to reset the position when search results appear or hide */
function setStickyTop() {
stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
}
/*
* Displays sticky nav bar on pages when dac header scrolls out of view
*/
$(window).scroll(function(event) {
setStickyTop();
var hiding = false;
var $stickyEl = $('#sticky-header');
var $menuEl = $('.menu-container');
// Exit if there's no sidenav
if ($('#side-nav').length == 0) return;
// Exit if the mouse target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
if ($(event.target).nodeName == "DIV") {
return;
}
var top = $(window).scrollTop();
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var shouldBeSticky = top >= stickyTop;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
shouldBeSticky = false;
}
// Account for horizontal scroll
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (sticky && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (sticky == shouldBeSticky) {
return;
}
// If sticky header visible and position is now near top, hide sticky
if (sticky && !shouldBeSticky) {
sticky = false;
hiding = true;
// make the sidenav static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
// delay hide the sticky
$menuEl.removeClass('sticky-menu');
$stickyEl.fadeOut(250);
hiding = false;
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (!sticky && shouldBeSticky) {
sticky = true;
$stickyEl.fadeIn(10);
$menuEl.addClass('sticky-menu');
// make the sidenav fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (hiding && top < 15) {
$menuEl.removeClass('sticky-menu');
$stickyEl.hide();
hiding = false;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
/*
* Manages secion card states and nav resize to conclude loading
*/
(function() {
$(document).ready(function() {
// Stack hover states
$('.section-card-menu').each(function(index, el) {
var height = $(el).height();
$(el).css({height:height+'px', position:'relative'});
var $cardInfo = $(el).find('.card-info');
$cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
});
});
})();
/* MISC LIBRARY FUNCTIONS */
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function hideNestedItems(list, toggle) {
$list = $(list);
// hide nested lists
if($list.hasClass('showing')) {
$("li ol", $list).hide('fast');
$list.removeClass('showing');
// show nested lists
} else {
$("li ol", $list).show('fast');
$list.addClass('showing');
}
$(".more,.less",$(toggle)).toggle();
}
/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
function setupIdeDocToggle() {
$( "select.ide" ).change(function() {
var selected = $(this).find("option:selected").attr("value");
$(".select-ide").hide();
$(".select-ide."+selected).show();
$("select.ide").val(selected);
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
writeCookie("nav", nav_pref, "reference");
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
writeCookie("pref_lang", lang, null);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj).closest(".toggle-content");
var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("open").addClass("closed");
div.find(".toggle-content").removeClass("open").addClass("closed")
.find(".toggle-content-toggleme").hide();
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
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);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
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);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1; // the index position of currently highlighted suggestion
var gSelectedColumn = -1; // which column of suggestion lists is currently focused
var gMatches = new Array();
var gLastText = "";
var gInitialized = false;
var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
var gListLength = 0;
var gGoogleMatches = new Array();
var ROW_COUNT_GOOGLE = 15; // max number of results in list
var gGoogleListLength = 0;
var gDocsMatches = new Array();
var ROW_COUNT_DOCS = 100; // max number of results in list
var gDocsListLength = 0;
function onSuggestionClick(link) {
// When user clicks a suggested document, track it
ga('send', 'event', 'Suggestion Click', 'clicked: ' + $(link).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
}
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function set_item_values_jd(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.title);
$link.attr('href',toroot + match.url);
}
function new_suggestion($list) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('.search_filtered_wrapper li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
});
$li.append("<a onclick='onSuggestionClick(this)'></a>");
$li.attr('class','show-item');
return $li;
}
function sync_selection_table(toroot)
{
var $li; //list item jquery object
var i; //list item iterator
// if there are NO results at all, hide all columns
if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
$('.suggest-card').hide(300);
return;
}
// if there are api results
if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
// reveal suggestion list
$('.suggest-card.dummy').show();
$('.suggest-card.reference').show();
var listIndex = 0; // list index position
// reset the lists
$(".search_filtered_wrapper.reference li").remove();
// ########### ANDROID RESULTS #############
if (gMatches.length > 0) {
// determine android results to show
gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
gMatches.length : ROW_COUNT_FRAMEWORK;
for (i=0; i<gListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
// ########### GOOGLE RESULTS #############
if (gGoogleMatches.length > 0) {
// show header for list
$(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
// determine google results to show
gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
for (i=0; i<gGoogleListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gGoogleMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
} else {
$('.suggest-card.reference').hide();
$('.suggest-card.dummy').hide();
}
// ########### JD DOC RESULTS #############
if (gDocsMatches.length > 0) {
// reset the lists
$(".search_filtered_wrapper.docs li").remove();
// determine google results to show
// NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
// The order must match the reverse order that each section appears as a card in
// the suggestion UI... this may be only for the "develop" grouped items though.
gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
for (i=0; i<gDocsListLength; i++) {
var sugg = gDocsMatches[i];
var $li;
if (sugg.type == "design") {
$li = new_suggestion($(".suggest-card.design ul"));
} else
if (sugg.type == "distribute") {
$li = new_suggestion($(".suggest-card.distribute ul"));
} else
if (sugg.type == "samples") {
$li = new_suggestion($(".suggest-card.develop .child-card.samples"));
} else
if (sugg.type == "training") {
$li = new_suggestion($(".suggest-card.develop .child-card.training"));
} else
if (sugg.type == "about"||"guide"||"tools"||"google") {
$li = new_suggestion($(".suggest-card.develop .child-card.guides"));
} else {
continue;
}
set_item_values_jd(toroot, $li, sugg);
set_item_selected($li, i == gSelectedIndex);
}
// add heading and show or hide card
if ($(".suggest-card.design li").length > 0) {
$(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
$(".suggest-card.design").show(300);
} else {
$('.suggest-card.design').hide(300);
}
if ($(".suggest-card.distribute li").length > 0) {
$(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
$(".suggest-card.distribute").show(300);
} else {
$('.suggest-card.distribute').hide(300);
}
if ($(".child-card.guides li").length > 0) {
$(".child-card.guides").prepend("<li class='header'>Guides:</li>");
$(".child-card.guides li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.training li").length > 0) {
$(".child-card.training").prepend("<li class='header'>Training:</li>");
$(".child-card.training li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.samples li").length > 0) {
$(".child-card.samples").prepend("<li class='header'>Samples:</li>");
$(".child-card.samples li").appendTo(".suggest-card.develop ul");
}
if ($(".suggest-card.develop li").length > 0) {
$(".suggest-card.develop").show(300);
} else {
$('.suggest-card.develop').hide(300);
}
} else {
$('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
}
}
/** Called by the search input's onkeydown and onkeyup events.
* Handles navigation with keyboard arrows, Enter key to invoke search,
* otherwise invokes search suggestions on key-up event.
* @param e The JS event
* @param kd True if the event is key-down
* @param toroot A string for the site's root path
* @returns True if the event should bubble up
*/
function search_changed(e, kd, toroot)
{
var currentLang = getLangPref();
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// get the ul hosting the currently selected item
gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
var $selectedUl = $columns[gSelectedColumn];
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 27 = esc
if (e.keyCode == 27) {
// close all search results
if (kd) $('.search .close').trigger('click');
return true;
}
// 13 = enter
else if (e.keyCode == 13) {
if (gSelectedIndex < 0) {
$('.suggest-card').hide();
if ($("#searchResults").is(":hidden") && (search.value != "")) {
// if results aren't showing (and text not empty), return true to allow search to execute
$('body,html').animate({scrollTop:0}, '500', 'swing');
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
// click the link corresponding to selected item
$("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
return false;
}
}
// If Google results are showing, return true to allow ajax search to execute
else if ($("#searchResults").is(":visible")) {
// Also, if search_results is scrolled out of view, scroll to top to make results visible
if ((sticky ) && (search.value != "")) {
$('body,html').animate({scrollTop:0}, '500', 'swing');
}
return true;
}
// 38 UP ARROW
else if (kd && (e.keyCode == 38)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
gSelectedIndex--;
}
if (gSelectedIndex >= 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex--;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
// If user reaches top, reset selected column
if (gSelectedIndex < 0) {
gSelectedColumn = -1;
}
}
return false;
}
// 40 DOWN ARROW
else if (kd && (e.keyCode == 40)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
gSelectedIndex++;
}
if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex++;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
}
return false;
}
// Consider left/right arrow navigation
// NOTE: Order of suggest columns are reverse order (index position 0 is on right)
else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
// 37 LEFT ARROW
// go left only if current column is not left-most column (last column)
if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn++;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
// 39 RIGHT ARROW
// go right only if current column is not the right-most column (first column)
else if (e.keyCode == 39 && gSelectedColumn > 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn--;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
}
// if key-up event and not arrow down/up/left/right,
// read the search query and add suggestions to gMatches
else if (!kd && (e.keyCode != 40)
&& (e.keyCode != 38)
&& (e.keyCode != 37)
&& (e.keyCode != 39)) {
gSelectedIndex = -1;
gMatches = new Array();
matchedCount = 0;
gGoogleMatches = new Array();
matchedCountGoogle = 0;
gDocsMatches = new Array();
matchedCountDocs = 0;
// Search for Android matches
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_api_results(text, gMatches);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
}
// Search for Google matches
for (var i=0; i<GOOGLE_DATA.length; i++) {
var s = GOOGLE_DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gGoogleMatches[matchedCountGoogle] = s;
matchedCountGoogle++;
}
}
rank_autocomplete_api_results(text, gGoogleMatches);
for (var i=0; i<gGoogleMatches.length; i++) {
var s = gGoogleMatches[i];
}
highlight_autocomplete_result_labels(text);
// Search for matching JD docs
if (text.length >= 2) {
// Regex to match only the beginning of a word
var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
// Search for Training classes
for (var i=0; i<TRAINING_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TRAINING_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Don't consider doc title for lessons (only for class landing pages),
// unless the lesson has a tag that already matches
if ((s.lang == currentLang) &&
(!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
// it matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for API Guides
for (var i=0; i<GUIDE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GUIDE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Tools Guides
for (var i=0; i<TOOLS_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TOOLS_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for About docs
for (var i=0; i<ABOUT_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = ABOUT_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Design guides
for (var i=0; i<DESIGN_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DESIGN_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Distribute guides
for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DISTRIBUTE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Google guides
for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GOOGLE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Samples
for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = SAMPLES_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title.t
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Rank/sort all the matched pages
rank_autocomplete_doc_results(text, gDocsMatches);
}
// draw the suggestions
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
/* Order the jd doc result list based on match quality */
function rank_autocomplete_doc_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
var _resultScoreFn = function(match) {
var score = 1.0;
// if the query matched a tag
if (match.matched_tag > 0) {
// multiply score by factor relative to position in tags list (max of 3)
score *= 3 / match.matched_tag;
// if it also matched the title
if (match.matched_title > 0) {
score *= 2;
}
} else if (match.matched_title > 0) {
score *= 3;
}
return score;
};
for (var i=0; i<matches.length; i++) {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Order the result list based on match quality */
function rank_autocomplete_api_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<matches.length; i++) {
// if the API is deprecated, default score is 0; otherwise, perform scoring
if (matches[i].deprecated == "true") {
matches[i].__resultScore = 0;
} else {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Add emphasis to part of string that matches query */
function highlight_autocomplete_result_labels(query) {
query = query || '';
if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
for (var i=0; i<gGoogleMatches.length; i++) {
gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
$(".suggest-card").hide();
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow', setStickyTop);
return false;
}
function hideResults() {
$("#searchResults").slideUp('fast', setStickyTop);
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
var searchControl;
google.load('search', '1', {"callback" : function() {
searchControl = new google.search.SearchControl();
} });
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// once search results load, set up click listeners
searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
addResultClickListeners();
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow', setStickyTop);
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
/* Adjust the scroll position to account for sticky header, only if the hash matches an id.
This does not handle <a name=""> tags. Some CSS fixes those, but only for reference docs. */
function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
}
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
// If the hash isn't a search query or there's an error in the query,
// then adjust the scroll position to account for sticky header, then exit.
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
offsetScrollForSticky();
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow', setStickyTop);
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
// add analytics tracking events to each result link
function addResultClickListeners() {
$("#searchResults a.gs-title").each(function(index, link) {
// When user clicks enter for Google search results, track it
$(link).click(function() {
ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
});
});
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference") == 0) {
if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
&& !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
&& !(location.pathname.indexOf("/reference/com/google") == 0)) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
writeCookie(API_LEVEL_COOKIE, selectedLevel, null);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher. To reveal, change the target API level "
+ "above the left navigation.");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
}
});
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
/****** NEW version of script to build google and sample navs dynamically ******/
// TODO: update Google reference docs to tolerate this new implementation
var NODE_NAME = 0;
var NODE_HREF = 1;
var NODE_GROUP = 2;
var NODE_TAGS = 3;
var NODE_CHILDREN = 4;
function init_google_navtree2(navtree_id, data)
{
var $containerUl = $("#"+navtree_id);
for (var i in data) {
var node_data = data[i];
$containerUl.append(new_google_node2(node_data));
}
// Make all third-generation list items 'sticky' to prevent them from collapsing
$containerUl.find('li li li.nav-section').addClass('sticky');
initExpandableNavItems("#"+navtree_id);
}
function new_google_node2(node_data)
{
var linkText = node_data[NODE_NAME];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
var $li = $('<li>');
var $a;
if (node_data[NODE_HREF] != null) {
$a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
+ linkText + '</a>');
} else {
$a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
+ linkText + '/</a>');
}
var $childUl = $('<ul>');
if (node_data[NODE_CHILDREN] != null) {
$li.addClass("nav-section");
$a = $('<div class="nav-section-header">').append($a);
if (node_data[NODE_HREF] == null) $a.addClass('empty');
for (var i in node_data[NODE_CHILDREN]) {
var child_node_data = node_data[NODE_CHILDREN][i];
$childUl.append(new_google_node2(child_node_data));
}
$li.append($childUl);
}
$li.prepend($a);
return $li;
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
}
function init_default_google_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function init_default_gcm_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function showSamplesRefTree() {
init_default_samples_navtree(toRoot);
}
function init_default_samples_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
// hack to remove the "about the samples" link then put it back in
// after we nuke the list to remove the dummy static list of samples
var $firstLi = $("#nav.samples-nav > li:first-child").clone();
$("#nav.samples-nav").empty();
$("#nav.samples-nav").append($firstLi);
init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
highlightSidenav();
resizeNav();
if ($("#jd-content #samples").length) {
showSamples();
}
}
});
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
/* On-demand functions */
/** Move sample code line numbers out of PRE block and into non-copyable column */
function initCodeLineNumbers() {
var numbers = $("#codesample-block a.number");
if (numbers.length) {
$("#codesample-line-numbers").removeClass("hidden").append(numbers);
}
$(document).ready(function() {
// select entire line when clicked
$("span.code-line").click(function() {
if (!shifted) {
selectText(this);
}
});
// invoke line link on double click
$(".code-line").dblclick(function() {
document.location.hash = $(this).attr('id');
});
// highlight the line when hovering on the number
$("#codesample-line-numbers a.number").mouseover(function() {
var id = $(this).attr('href');
$(id).css('background','#e7e7e7');
});
$("#codesample-line-numbers a.number").mouseout(function() {
var id = $(this).attr('href');
$(id).css('background','none');
});
});
}
// create SHIFT key binder to avoid the selectText method when selecting multiple lines
var shifted = false;
$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
// courtesy of jasonedelman.com
function selectText(element) {
var doc = document
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
/** Display links and other information about samples that match the
group specified by the URL */
function showSamples() {
var group = $("#samples").attr('class');
$("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
var $ul = $("<ul>");
$selectedLi = $("#nav li.selected");
$selectedLi.children("ul").children("li").each(function() {
var $li = $("<li>").append($(this).find("a").first().clone());
$ul.append($li);
});
$("#samples").append($ul);
}
/* ########################################################## */
/* ################### RESOURCE CARDS ##################### */
/* ########################################################## */
/** Handle resource queries, collections, and grids (sections). Requires
jd_tag_helpers.js and the *_unified_data.js to be loaded. */
(function() {
// Prevent the same resource from being loaded more than once per page.
var addedPageResources = {};
$(document).ready(function() {
$('.resource-widget').each(function() {
initResourceWidget(this);
});
/* Pass the line height to ellipsisfade() to adjust the height of the
text container to show the max number of lines possible, without
showing lines that are cut off. This works with the css ellipsis
classes to fade last text line and apply an ellipsis char. */
//card text currently uses 15px line height.
var lineHeight = 15;
$('.card-info .text').ellipsisfade(lineHeight);
});
/*
Three types of resource layouts:
Flow - Uses a fixed row-height flow using float left style.
Carousel - Single card slideshow all same dimension absolute.
Stack - Uses fixed columns and flexible element height.
*/
function initResourceWidget(widget) {
var $widget = $(widget);
var isFlow = $widget.hasClass('resource-flow-layout'),
isCarousel = $widget.hasClass('resource-carousel-layout'),
isStack = $widget.hasClass('resource-stack-layout');
// find size of widget by pulling out its class name
var sizeCols = 1;
var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
if (m) {
sizeCols = parseInt(m[1], 10);
}
var opts = {
cardSizes: ($widget.data('cardsizes') || '').split(','),
maxResults: parseInt($widget.data('maxresults') || '100', 10),
itemsPerPage: $widget.data('itemsperpage'),
sortOrder: $widget.data('sortorder'),
query: $widget.data('query'),
section: $widget.data('section'),
sizeCols: sizeCols,
/* Added by LFL 6/6/14 */
resourceStyle: $widget.data('resourcestyle') || 'card',
stackSort: $widget.data('stacksort') || 'true'
};
// run the search for the set of resources to show
var resources = buildResourceList(opts);
if (isFlow) {
drawResourcesFlowWidget($widget, opts, resources);
} else if (isCarousel) {
drawResourcesCarouselWidget($widget, opts, resources);
} else if (isStack) {
/* Looks like this got removed and is not used, so repurposing for the
homepage style layout.
Modified by LFL 6/6/14
*/
//var sections = buildSectionList(opts);
opts['numStacks'] = $widget.data('numstacks');
drawResourcesStackWidget($widget, opts, resources/*, sections*/);
}
}
/* Initializes a Resource Carousel Widget */
function drawResourcesCarouselWidget($widget, opts, resources) {
$widget.empty();
var plusone = true; //always show plusone on carousel
$widget.addClass('resource-card slideshow-container')
.append($('<a>').addClass('slideshow-prev').text('Prev'))
.append($('<a>').addClass('slideshow-next').text('Next'));
var css = { 'width': $widget.width() + 'px',
'height': $widget.height() + 'px' };
var $ul = $('<ul>');
for (var i = 0; i < resources.length; ++i) {
var $card = $('<a>')
.attr('href', cleanUrl(resources[i].url))
.decorateResourceCard(resources[i],plusone);
$('<li>').css(css)
.append($card)
.appendTo($ul);
}
$('<div>').addClass('frame')
.append($ul)
.appendTo($widget);
$widget.dacSlideshow({
auto: true,
btnPrev: '.slideshow-prev',
btnNext: '.slideshow-next'
});
};
/* Initializes a Resource Card Stack Widget (column-based layout)
Modified by LFL 6/6/14
*/
function drawResourcesStackWidget($widget, opts, resources, sections) {
// Don't empty widget, grab all items inside since they will be the first
// items stacked, followed by the resource query
var plusone = true; //by default show plusone on section cards
var cards = $widget.find('.resource-card').detach().toArray();
var numStacks = opts.numStacks || 1;
var $stacks = [];
var urlString;
for (var i = 0; i < numStacks; ++i) {
$stacks[i] = $('<div>').addClass('resource-card-stack')
.appendTo($widget);
}
var sectionResources = [];
// Extract any subsections that are actually resource cards
if (sections) {
for (var i = 0; i < sections.length; ++i) {
if (!sections[i].sections || !sections[i].sections.length) {
// Render it as a resource card
sectionResources.push(
$('<a>')
.addClass('resource-card section-card')
.attr('href', cleanUrl(sections[i].resource.url))
.decorateResourceCard(sections[i].resource,plusone)[0]
);
} else {
cards.push(
$('<div>')
.addClass('resource-card section-card-menu')
.decorateResourceSection(sections[i],plusone)[0]
);
}
}
}
cards = cards.concat(sectionResources);
for (var i = 0; i < resources.length; ++i) {
var $card = createResourceElement(resources[i], opts);
if (opts.resourceStyle.indexOf('related') > -1) {
$card.addClass('related-card');
}
cards.push($card[0]);
}
if (opts.stackSort != 'false') {
for (var i = 0; i < cards.length; ++i) {
// Find the stack with the shortest height, but give preference to
// left to right order.
var minHeight = $stacks[0].height();
var minIndex = 0;
for (var j = 1; j < numStacks; ++j) {
var height = $stacks[j].height();
if (height < minHeight - 45) {
minHeight = height;
minIndex = j;
}
}
$stacks[minIndex].append($(cards[i]));
}
}
};
/*
Create a resource card using the given resource object and a list of html
configured options. Returns a jquery object containing the element.
*/
function createResourceElement(resource, opts, plusone) {
var $el;
// The difference here is that generic cards are not entirely clickable
// so its a div instead of an a tag, also the generic one is not given
// the resource-card class so it appears with a transparent background
// and can be styled in whatever way the css setup.
if (opts.resourceStyle == 'generic') {
$el = $('<div>')
.addClass('resource')
.attr('href', cleanUrl(resource.url))
.decorateResource(resource, opts);
} else {
var cls = 'resource resource-card';
$el = $('<a>')
.addClass(cls)
.attr('href', cleanUrl(resource.url))
.decorateResourceCard(resource, plusone);
}
return $el;
}
/* Initializes a flow widget, see distribute.scss for generating accompanying css */
function drawResourcesFlowWidget($widget, opts, resources) {
$widget.empty();
var cardSizes = opts.cardSizes || ['6x6'];
var i = 0, j = 0;
var plusone = true; // by default show plusone on resource cards
while (i < resources.length) {
var cardSize = cardSizes[j++ % cardSizes.length];
cardSize = cardSize.replace(/^\s+|\s+$/,'');
// Some card sizes do not get a plusone button, such as where space is constrained
// or for cards commonly embedded in docs (to improve overall page speed).
plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
(cardSize == "9x2") || (cardSize == "9x3") ||
(cardSize == "12x2") || (cardSize == "12x3"));
// A stack has a third dimension which is the number of stacked items
var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
var stackCount = 0;
var $stackDiv = null;
if (isStack) {
// Create a stack container which should have the dimensions defined
// by the product of the items inside.
$stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+ 'x' + isStack[2] * isStack[3]) .appendTo($widget);
}
// Build each stack item or just a single item
do {
var resource = resources[i];
var $card = createResourceElement(resources[i], opts, plusone);
$card.addClass('resource-card-' + cardSize +
' resource-card-' + resource.type);
if (isStack) {
$card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
if (++stackCount == parseInt(isStack[3])) {
$card.addClass('resource-card-row-stack-last');
stackCount = 0;
}
} else {
stackCount = 0;
}
$card.appendTo($stackDiv || $widget);
} while (++i < resources.length && stackCount > 0);
}
}
/* Build a site map of resources using a section as a root. */
function buildSectionList(opts) {
if (opts.section && SECTION_BY_ID[opts.section]) {
return SECTION_BY_ID[opts.section].sections || [];
}
return [];
}
function buildResourceList(opts) {
var maxResults = opts.maxResults || 100;
var query = opts.query || '';
var expressions = parseResourceQuery(query);
var addedResourceIndices = {};
var results = [];
for (var i = 0; i < expressions.length; i++) {
var clauses = expressions[i];
// build initial set of resources from first clause
var firstClause = clauses[0];
var resources = [];
switch (firstClause.attr) {
case 'type':
resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
break;
case 'lang':
resources = ALL_RESOURCES_BY_LANG[firstClause.value];
break;
case 'tag':
resources = ALL_RESOURCES_BY_TAG[firstClause.value];
break;
case 'collection':
var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
case 'section':
var urls = SITE_MAP[firstClause.value].sections || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
}
// console.log(firstClause.attr + ':' + firstClause.value);
resources = resources || [];
// use additional clauses to filter corpus
if (clauses.length > 1) {
var otherClauses = clauses.slice(1);
resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
}
// filter out resources already added
if (i > 1) {
resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
}
// add to list of already added indices
for (var j = 0; j < resources.length; j++) {
// console.log(resources[j].title);
addedResourceIndices[resources[j].index] = 1;
}
// concat to final results list
results = results.concat(resources);
}
if (opts.sortOrder && results.length) {
var attr = opts.sortOrder;
if (opts.sortOrder == 'random') {
var i = results.length, j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = results[i];
results[i] = results[j];
results[j] = temp;
}
} else {
var desc = attr.charAt(0) == '-';
if (desc) {
attr = attr.substring(1);
}
results = results.sort(function(x,y) {
return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
});
}
}
results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
results = results.slice(0, maxResults);
for (var j = 0; j < results.length; ++j) {
addedPageResources[results[j].index] = 1;
}
return results;
}
function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
return function(resource) {
return !addedResourceIndices[resource.index];
};
}
function getResourceMatchesClausesFilter(clauses) {
return function(resource) {
return doesResourceMatchClauses(resource, clauses);
};
}
function doesResourceMatchClauses(resource, clauses) {
for (var i = 0; i < clauses.length; i++) {
var map;
switch (clauses[i].attr) {
case 'type':
map = IS_RESOURCE_OF_TYPE[clauses[i].value];
break;
case 'lang':
map = IS_RESOURCE_IN_LANG[clauses[i].value];
break;
case 'tag':
map = IS_RESOURCE_TAGGED[clauses[i].value];
break;
}
if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
return clauses[i].negative;
}
}
return true;
}
function cleanUrl(url)
{
if (url && url.indexOf('//') === -1) {
url = toRoot + url;
}
return url;
}
function parseResourceQuery(query) {
// Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
var expressions = [];
var expressionStrs = query.split(',') || [];
for (var i = 0; i < expressionStrs.length; i++) {
var expr = expressionStrs[i] || '';
// Break expression into clauses (clause e.g. 'tag:foo')
var clauses = [];
var clauseStrs = expr.split(/(?=[\+\-])/);
for (var j = 0; j < clauseStrs.length; j++) {
var clauseStr = clauseStrs[j] || '';
// Get attribute and value from clause (e.g. attribute='tag', value='foo')
var parts = clauseStr.split(':');
var clause = {};
clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
if (clause.attr) {
if (clause.attr.charAt(0) == '+') {
clause.attr = clause.attr.substring(1);
} else if (clause.attr.charAt(0) == '-') {
clause.negative = true;
clause.attr = clause.attr.substring(1);
}
}
if (parts.length > 1) {
clause.value = parts[1].replace(/^\s+|\s+$/g,'');
}
clauses.push(clause);
}
if (!clauses.length) {
continue;
}
expressions.push(clauses);
}
return expressions;
}
})();
(function($) {
/*
Utility method for creating dom for the description area of a card.
Used in decorateResourceCard and decorateResource.
*/
function buildResourceCardDescription(resource, plusone) {
var $description = $('<div>').addClass('description ellipsis');
$description.append($('<div>').addClass('text').html(resource.summary));
if (resource.cta) {
$description.append($('<a>').addClass('cta').html(resource.cta));
}
if (plusone) {
var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
"//developer.android.com/" + resource.url;
$description.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', plusurl)));
}
return $description;
}
/* Simple jquery function to create dom for a standard resource card */
$.fn.decorateResourceCard = function(resource,plusone) {
var section = resource.group || resource.type;
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
$('<div>').addClass('card-bg')
.css('background-image', 'url(' + (imgUrl || toRoot +
'assets/images/resource-card-default-android.jpg') + ')')
.appendTo(this);
$('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
.append($('<div>').addClass('section').text(section))
.append($('<div>').addClass('title').html(resource.title))
.append(buildResourceCardDescription(resource, plusone))
.appendTo(this);
return this;
};
/* Simple jquery function to create dom for a resource section card (menu) */
$.fn.decorateResourceSection = function(section,plusone) {
var resource = section.resource;
//keep url clean for matching and offline mode handling
var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
var $base = $('<a>')
.addClass('card-bg')
.attr('href', resource.url)
.append($('<div>').addClass('card-section-icon')
.append($('<div>').addClass('icon'))
.append($('<div>').addClass('section').html(resource.title)))
.appendTo(this);
var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
if (section.sections && section.sections.length) {
// Recurse the section sub-tree to find a resource image.
var stack = [section];
while (stack.length) {
if (stack[0].resource.image) {
$base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
break;
}
if (stack[0].sections) {
stack = stack.concat(stack[0].sections);
}
stack.shift();
}
var $ul = $('<ul>')
.appendTo($cardInfo);
var max = section.sections.length > 3 ? 3 : section.sections.length;
for (var i = 0; i < max; ++i) {
var subResource = section.sections[i];
if (!plusone) {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util'))))
.appendTo($ul);
} else {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', resource.url)))))
.appendTo($ul);
}
}
// Add a more row
if (max < section.sections.length) {
$('<li>')
.append($('<a>').attr('href', resource.url)
.append($('<div>')
.addClass('title')
.text('More')))
.appendTo($ul);
}
} else {
// No sub-resources, just render description?
}
return this;
};
/* Render other types of resource styles that are not cards. */
$.fn.decorateResource = function(resource, opts) {
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
var linkUrl = resource.url;
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
if (linkUrl && linkUrl.indexOf('//') === -1) {
linkUrl = toRoot + linkUrl;
}
$(this).append(
$('<div>').addClass('image')
.css('background-image', 'url(' + imgUrl + ')'),
$('<div>').addClass('info').append(
$('<h4>').addClass('title').html(resource.title),
$('<p>').addClass('summary').html(resource.summary),
$('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
)
);
return this;
};
})(jQuery);
/* Calculate the vertical area remaining */
(function($) {
$.fn.ellipsisfade= function(lineHeight) {
this.each(function() {
// get element text
var $this = $(this);
var remainingHeight = $this.parent().parent().height();
$this.parent().siblings().each(function ()
{
if ($(this).is(":visible")) {
var h = $(this).height();
remainingHeight = remainingHeight - h;
}
});
adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
$this.parent().css({'height': adjustedRemainingHeight});
$this.css({'height': "auto"});
});
return this;
};
}) (jQuery);
/*
Fullscreen Carousel
The following allows for an area at the top of the page that takes over the
entire browser height except for its top offset and an optional bottom
padding specified as a data attribute.
HTML:
<div class="fullscreen-carousel">
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
etc ...
</div>
Control over how the carousel takes over the screen can mostly be defined in
a css file. Setting min-height on the .fullscreen-carousel-content elements
will prevent them from shrinking to far vertically when the browser is very
short, and setting max-height on the .fullscreen-carousel itself will prevent
the area from becoming to long in the case that the browser is stretched very
tall.
There is limited functionality for having multiple sections since that request
was removed, but it is possible to add .next-arrow and .prev-arrow elements to
scroll between multiple content areas.
*/
(function() {
$(document).ready(function() {
$('.fullscreen-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var topOffset = $widget.offset().top;
var padBottom = parseInt($widget.data('paddingbottom')) || 0;
var maxHeight = 0;
var minHeight = 0;
var $content = $widget.find('.fullscreen-carousel-content');
var $nextArrow = $widget.find('.next-arrow');
var $prevArrow = $widget.find('.prev-arrow');
var $curSection = $($content[0]);
if ($content.length <= 1) {
$nextArrow.hide();
$prevArrow.hide();
} else {
$nextArrow.click(function() {
var index = ($content.index($curSection) + 1);
$curSection.hide();
$curSection = $($content[index >= $content.length ? 0 : index]);
$curSection.show();
});
$prevArrow.click(function() {
var index = ($content.index($curSection) - 1);
$curSection.hide();
$curSection = $($content[index < 0 ? $content.length - 1 : 0]);
$curSection.show();
});
}
// Just hide all content sections except first.
$content.each(function(index) {
if ($(this).height() > minHeight) minHeight = $(this).height();
$(this).css({position: 'absolute', display: index > 0 ? 'none' : ''});
});
// Register for changes to window size, and trigger.
$(window).resize(resizeWidget);
resizeWidget();
function resizeWidget() {
var height = $(window).height() - topOffset - padBottom;
$widget.width($(window).width());
$widget.height(height < minHeight ? minHeight :
(maxHeight && height > maxHeight ? maxHeight : height));
}
}
})();
/*
Tab Carousel
The following allows tab widgets to be installed via the html below. Each
tab content section should have a data-tab attribute matching one of the
nav items'. Also each tab content section should have a width matching the
tab carousel.
HTML:
<div class="tab-carousel">
<ul class="tab-nav">
<li><a href="#" data-tab="handsets">Handsets</a>
<li><a href="#" data-tab="wearable">Wearable</a>
<li><a href="#" data-tab="tv">TV</a>
</ul>
<div class="tab-carousel-content">
<div data-tab="handsets">
<!--Full width content here-->
</div>
<div data-tab="wearable">
<!--Full width content here-->
</div>
<div data-tab="tv">
<!--Full width content here-->
</div>
</div>
</div>
*/
(function() {
$(document).ready(function() {
$('.tab-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var $nav = $widget.find('.tab-nav');
var $anchors = $nav.find('[data-tab]');
var $li = $nav.find('li');
var $contentContainer = $widget.find('.tab-carousel-content');
var $tabs = $contentContainer.find('[data-tab]');
var $curTab = $($tabs[0]); // Current tab is first tab.
var width = $widget.width();
// Setup nav interactivity.
$anchors.click(function(evt) {
evt.preventDefault();
var query = '[data-tab=' + $(this).data('tab') + ']';
transitionWidget($tabs.filter(query));
});
// Add highlight for navigation on first item.
var $highlight = $('<div>').addClass('highlight')
.css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
.appendTo($nav);
// Store height since we will change contents to absolute.
$contentContainer.height($contentContainer.height());
// Absolutely position tabs so they're ready for transition.
$tabs.each(function(index) {
$(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
});
function transitionWidget($toTab) {
if (!$curTab.is($toTab)) {
var curIndex = $tabs.index($curTab[0]);
var toIndex = $tabs.index($toTab[0]);
var dir = toIndex > curIndex ? 1 : -1;
// Animate content sections.
$toTab.css({left:(width * dir) + 'px'});
$curTab.animate({left:(width * -dir) + 'px'});
$toTab.animate({left:'0'});
// Animate navigation highlight.
$highlight.animate({left:$($li[toIndex]).position().left + 'px',
width:$($li[toIndex]).outerWidth() + 'px'})
// Store new current section.
$curTab = $toTab;
}
}
}
})();
| JavaScript |
$(document).ready(function() {
// prep nav expandos
var pagePath = document.location.pathname;
if (pagePath.indexOf(SITE_ROOT) == 0) {
pagePath = pagePath.substr(SITE_ROOT.length);
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path should be an absolute URL.
pagePath = SITE_ROOT + pagePath;
}
// select current page in sidenav and set up prev/next links if they exist
var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]');
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
$selListItem.closest('li>ul').addClass('expanded');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
$prevLink = $selListItem.parents('li').find('a');
}
if ($prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
$('.prev-page-link').hide();
} else {
$('.prev-page-link').attr('href', prevHref).show();
}
} else {
$('.prev-page-link').hide();
}
// set up next links
var $nextLink = [];
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul').find('a:eq(0)')
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)');
}
}
if ($nextLink.length) {
$('.next-page-link').attr('href', $nextLink.attr('href')).show();
} else {
$('.next-page-link').hide();
}
}
// Set up expand/collapse behavior
$('.nav-y li').has('ul').click(function() {
if ($(this).hasClass('expanded')) {
return;
}
// hide other
var $old = $('.nav-y li.expanded');
if ($old.length) {
var $oldUl = $old.children('ul');
$oldUl.css('height', $oldUl.height() + 'px');
window.setTimeout(function() {
$oldUl
.addClass('animate-height')
.css('height', '');
}, 0);
$old.removeClass('expanded');
}
// show me
$(this).addClass('expanded');
var $ul = $(this).children('ul');
var expandedHeight = $ul.height();
$ul
.removeClass('animate-height')
.css('height', 0);
window.setTimeout(function() {
$ul
.addClass('animate-height')
.css('height', expandedHeight + 'px');
}, 0);
});
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.text($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
// Set up fixed navbar
var navBarIsFixed = false;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var navBarShouldBeFixed = (scrollTop > (100 - 40));
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
$('#nav')
.addClass('fixed')
.prependTo('#page-container');
} else {
$('#nav')
.removeClass('fixed')
.prependTo('#nav-container');
}
navBarIsFixed = navBarShouldBeFixed;
}
});
}); | JavaScript |
/* API LEVEL TOGGLE */
<?cs if:reference.apilevels ?>
addLoadEvent(changeApiLevel);
<?cs /if ?>
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevel = readCookie(API_LEVEL_COOKIE);
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevel = $("body").attr("class");
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevel = maxLevel;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevel, "body");
} else {
selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
}
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>"
+ "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest "
+ "and be compiled against a version of the library that supports an equal or higher API Level. To reveal this "
+ "document, change the value of the API Level filter above.</p>"
+ "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher");
else obj.removeClass("absent").removeAttr("title");
});
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data(toroot) {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toroot+"navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root) {
toRoot = root;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var BUILD_TIMESTAMP = "";
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
return true;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
return false;
}
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var mPagePath; // initialized in ready() function
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
var GOOGLE_DATA; // combined data for google service apis, used for search suggest
// Ensure that all ajax getScript() requests allow caching
$.ajaxSetup({
cache: true
});
/****** ON LOAD SET UP STUFF *********/
$(document).ready(function() {
// show lang dialog if the URL includes /intl/
//if (location.pathname.substring(0,6) == "/intl/") {
// var lang = location.pathname.split('/')[2];
// if (lang != getLangPref()) {
// $("#langMessage a.yes").attr("onclick","changeLangPref('" + lang
// + "', true); $('#langMessage').hide(); return false;");
// $("#langMessage .lang." + lang).show();
// $("#langMessage").show();
// }
//}
// load json file for JD doc search suggestions
$.getScript(toRoot + 'jd_lists_unified.js');
// load json file for Android API search suggestions
$.getScript(toRoot + 'reference/lists.js');
// load json files for Google services API suggestions
$.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
// once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
if(jqxhr.status === 200) {
$.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
// combine GCM and GMS data
GOOGLE_DATA = GMS_DATA;
var start = GOOGLE_DATA.length;
for (var i=0; i<GCM_DATA.length; i++) {
GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
link:GCM_DATA[i].link, type:GCM_DATA[i].type});
}
}
});
}
});
// setup keyboard listener for search shortcut
$('body').keyup(function(event) {
if (event.which == 191) {
$('#search_autocomplete').focus();
}
});
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2')
.not('#tb h2')
.not('.sidebox h2')
.not('#devdoc-nav h2')
.not('h2.norule').css({marginBottom:0})
.after('<hr/>');
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false);
hideResults();
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
// Need a copy of the pagePath before it gets changed in the next block;
// it's needed to perform proper tab highlighting in offline docs (see rootDir below)
var pagePathOriginal = pagePath;
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
$("#sticky-header").addClass("design");
// highlight About tabs
} else if ($("body").hasClass("about")) {
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "about") {
$("#nav-x li.about a").addClass("selected");
} else if (rootDir == "wear") {
$("#nav-x li.wear a").addClass("selected");
} else if (rootDir == "tv") {
$("#nav-x li.tv a").addClass("selected");
} else if (rootDir == "auto") {
$("#nav-x li.auto a").addClass("selected");
}
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
$("#sticky-header").addClass("develop");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else if ($("body").hasClass("samples")) {
$("#nav-x li.samples a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
$("#sticky-header").addClass("distribute");
var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
if (secondFrag == "users") {
$("#nav-x li.users a").addClass("selected");
} else if (secondFrag == "engage") {
$("#nav-x li.engage a").addClass("selected");
} else if (secondFrag == "monetize") {
$("#nav-x li.monetize a").addClass("selected");
} else if (secondFrag == "tools") {
$("#nav-x li.disttools a").addClass("selected");
} else if (secondFrag == "stories") {
$("#nav-x li.stories a").addClass("selected");
} else if (secondFrag == "essentials") {
$("#nav-x li.essentials a").addClass("selected");
} else if (secondFrag == "googleplay") {
$("#nav-x li.googleplay a").addClass("selected");
}
} else if ($("body").hasClass("about")) {
$("#sticky-header").addClass("about");
}
// set global variable so we can highlight the sidenav a bit later (such as for google reference)
// and highlight the sidenav
mPagePath = pagePath;
highlightSidenav();
buildBreadcrumbs();
// set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if ($nextLink.length == 0) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
if ($nextLink.length == 0) {
// if that doesn't work, we're at the end of the list, so disable NEXT link
$('.next-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
}
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
if ($nextLink.length) {
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide")
.append(": " + $nextLink.html());
$('.next-class-link').find('.new').empty();
}
} else {
$('.next-page-link').attr('href', $nextLink.attr('href'))
.removeClass("hide");
// for the footer link, also add the next page title
$('.content-footer .next-page-link').append(": " + $nextLink.html());
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
// create an array for all the class descriptions
var $classDescriptions = new Array($classLinks.length);
var lang = getLangPref();
$classLinks.each(function(index) {
var langDescr = $(this).attr(lang + "-description");
if (typeof langDescr !== 'undefined' && langDescr !== false) {
// if there's a class description in the selected language, use that
$classDescriptions[index] = langDescr;
} else {
// otherwise, use the default english description
$classDescriptions[index] = $(this).attr("description");
}
});
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
+ ' width="64" height="64" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
+ ' width="64" height="64" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
initExpandableNavItems("#nav");
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (sticky) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
// Resize once loading is finished
resizeNav();
// Check if there's an anchor that we need to scroll into view.
// A delay is needed, because some browsers do not immediately scroll down to the anchor
window.setTimeout(offsetScrollForSticky, 100);
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
/* setup shadowbox for any videos that want it */
var $videoLinks = $("a.video-shadowbox-button, a.notice-developers-video");
if ($videoLinks.length) {
// if there's at least one, add the shadowbox HTML to the body
$('body').prepend(
'<div id="video-container">'+
'<div id="video-frame">'+
'<div class="video-close">'+
'<span id="icon-video-close" onclick="closeVideo()"> </span>'+
'</div>'+
'<div id="youTubePlayer"></div>'+
'</div>'+
'</div>');
// loads the IFrame Player API code asynchronously.
$.getScript("https://www.youtube.com/iframe_api");
$videoLinks.each(function() {
var videoId = $(this).attr('href').split('?v=')[1];
$(this).click(function(event) {
event.preventDefault();
startYouTubePlayer(videoId);
});
});
}
});
// END of the onload event
var youTubePlayer;
function onYouTubeIframeAPIReady() {
}
function startYouTubePlayer(videoId) {
var idAndHash = videoId.split("#");
var startTime = 0;
var lang = getLangPref();
var captionsOn = lang == 'en' ? 0 : 1;
if (idAndHash.length > 1) {
startTime = idAndHash[1].split("t=")[1] != undefined ? idAndHash[1].split("t=")[1] : 0;
}
if (youTubePlayer == null) {
youTubePlayer = new YT.Player('youTubePlayer', {
height: '529',
width: '940',
videoId: idAndHash[0],
playerVars: {start: startTime, hl: lang, cc_load_policy: captionsOn},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} else {
youTubePlayer.playVideo();
}
$("#video-container").fadeIn(200, function(){$("#video-frame").show()});
}
function onPlayerReady(event) {
event.target.playVideo();
// track the start playing event so we know from which page the video was selected
ga('send', 'event', 'Videos', 'Start: ' +
youTubePlayer.getVideoUrl().split('?v=')[1], 'on: ' + document.location.href);
}
function closeVideo() {
try {
youTubePlayer.pauseVideo();
$("#video-container").fadeOut(200);
} catch(e) {
console.log('Video not available');
$("#video-container").fadeOut(200);
}
}
/* Track youtube playback for analytics */
function onPlayerStateChange(event) {
// Video starts, send the video ID
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'Videos', 'Play',
youTubePlayer.getVideoUrl().split('?v=')[1]);
}
// Video paused, send video ID and video elapsed time
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Videos', 'Paused',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
// Video finished, send video ID and video elapsed time
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Videos', 'Finished',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
}
function initExpandableNavItems(rootTag) {
$(rootTag + ' li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me and descendants */
section.find('ul').slideUp(250, function() {
// remove 'expanded' class from my section and any children
section.closest('li').removeClass('expanded');
$('li.nav-section', section).removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
// Stop expand/collapse behavior when clicking on nav section links
// (since we're navigating away from the page)
// This selector captures the first instance of <a>, but not those with "#" as the href.
$('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
}
/** Create the list of breadcrumb links in the sticky header */
function buildBreadcrumbs() {
var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
// Add the secondary horizontal nav item, if provided
var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
if ($selectedSecondNav.length) {
$breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
}
// Add the primary horizontal nav
var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
// If there's no header nav item, use the logo link and title from alt text
if ($selectedFirstNav.length < 1) {
$selectedFirstNav = $("<a>")
.attr('href', $("div#header .logo a").attr('href'))
.text($("div#header .logo img").attr('alt'));
}
$breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
}
/** Highlight the current page in sidenav, expanding children as appropriate */
function highlightSidenav() {
// if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
if ($("ul#nav li.selected").length) {
unHighlightSidenav();
}
// look for URL in sidenav, including the hash
var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
// If the selNavLink is still empty, look for it without the hash
if ($selNavLink.length == 0) {
$selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
}
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
}
}
function unHighlightSidenav() {
$("ul#nav li.selected").removeClass("selected");
$('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
}
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
$(document).ready(function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
});
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header-wrapper').outerHeight();
var headerVisible = scrollTop < stickyTop;
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) {
// If no selected item found, exit
return;
}
// get the selected item's offset from its container nav by measuring the item's offset
// relative to the document then subtract the container nav's offset relative to the document
var selectedOffset = $selected.offset().top - $nav.offset().top;
if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
// if it's more than 80% down the nav
// scroll the item up by an amount equal to 80% the container nav's height
api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
var age = 2*365*24*60*60; // set max-age to 2 years
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; max-age=" + age +"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
var sticky = false;
var stickyTop;
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
/* Sets the vertical scoll position at which the sticky bar should appear.
This method is called to reset the position when search results appear or hide */
function setStickyTop() {
stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
}
/*
* Displays sticky nav bar on pages when dac header scrolls out of view
*/
$(window).scroll(function(event) {
setStickyTop();
var hiding = false;
var $stickyEl = $('#sticky-header');
var $menuEl = $('.menu-container');
// Exit if there's no sidenav
if ($('#side-nav').length == 0) return;
// Exit if the mouse target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
if ($(event.target).nodeName == "DIV") {
return;
}
var top = $(window).scrollTop();
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var shouldBeSticky = top >= stickyTop;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
shouldBeSticky = false;
}
// Account for horizontal scroll
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (sticky && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (sticky == shouldBeSticky) {
return;
}
// If sticky header visible and position is now near top, hide sticky
if (sticky && !shouldBeSticky) {
sticky = false;
hiding = true;
// make the sidenav static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
// delay hide the sticky
$menuEl.removeClass('sticky-menu');
$stickyEl.fadeOut(250);
hiding = false;
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (!sticky && shouldBeSticky) {
sticky = true;
$stickyEl.fadeIn(10);
$menuEl.addClass('sticky-menu');
// make the sidenav fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (hiding && top < 15) {
$menuEl.removeClass('sticky-menu');
$stickyEl.hide();
hiding = false;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
/*
* Manages secion card states and nav resize to conclude loading
*/
(function() {
$(document).ready(function() {
// Stack hover states
$('.section-card-menu').each(function(index, el) {
var height = $(el).height();
$(el).css({height:height+'px', position:'relative'});
var $cardInfo = $(el).find('.card-info');
$cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
});
});
})();
/* MISC LIBRARY FUNCTIONS */
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function hideNestedItems(list, toggle) {
$list = $(list);
// hide nested lists
if($list.hasClass('showing')) {
$("li ol", $list).hide('fast');
$list.removeClass('showing');
// show nested lists
} else {
$("li ol", $list).show('fast');
$list.addClass('showing');
}
$(".more,.less",$(toggle)).toggle();
}
/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
function setupIdeDocToggle() {
$( "select.ide" ).change(function() {
var selected = $(this).find("option:selected").attr("value");
$(".select-ide").hide();
$(".select-ide."+selected).show();
$("select.ide").val(selected);
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
writeCookie("nav", nav_pref, "reference");
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
writeCookie("pref_lang", lang, null);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj).closest(".toggle-content");
var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("open").addClass("closed");
div.find(".toggle-content").removeClass("open").addClass("closed")
.find(".toggle-content-toggleme").hide();
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
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);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
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);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1; // the index position of currently highlighted suggestion
var gSelectedColumn = -1; // which column of suggestion lists is currently focused
var gMatches = new Array();
var gLastText = "";
var gInitialized = false;
var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
var gListLength = 0;
var gGoogleMatches = new Array();
var ROW_COUNT_GOOGLE = 15; // max number of results in list
var gGoogleListLength = 0;
var gDocsMatches = new Array();
var ROW_COUNT_DOCS = 100; // max number of results in list
var gDocsListLength = 0;
function onSuggestionClick(link) {
// When user clicks a suggested document, track it
ga('send', 'event', 'Suggestion Click', 'clicked: ' + $(link).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
}
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function set_item_values_jd(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.title);
$link.attr('href',toroot + match.url);
}
function new_suggestion($list) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('.search_filtered_wrapper li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
});
$li.append("<a onclick='onSuggestionClick(this)'></a>");
$li.attr('class','show-item');
return $li;
}
function sync_selection_table(toroot)
{
var $li; //list item jquery object
var i; //list item iterator
// if there are NO results at all, hide all columns
if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
$('.suggest-card').hide(300);
return;
}
// if there are api results
if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
// reveal suggestion list
$('.suggest-card.dummy').show();
$('.suggest-card.reference').show();
var listIndex = 0; // list index position
// reset the lists
$(".search_filtered_wrapper.reference li").remove();
// ########### ANDROID RESULTS #############
if (gMatches.length > 0) {
// determine android results to show
gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
gMatches.length : ROW_COUNT_FRAMEWORK;
for (i=0; i<gListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
// ########### GOOGLE RESULTS #############
if (gGoogleMatches.length > 0) {
// show header for list
$(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
// determine google results to show
gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
for (i=0; i<gGoogleListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gGoogleMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
} else {
$('.suggest-card.reference').hide();
$('.suggest-card.dummy').hide();
}
// ########### JD DOC RESULTS #############
if (gDocsMatches.length > 0) {
// reset the lists
$(".search_filtered_wrapper.docs li").remove();
// determine google results to show
// NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
// The order must match the reverse order that each section appears as a card in
// the suggestion UI... this may be only for the "develop" grouped items though.
gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
for (i=0; i<gDocsListLength; i++) {
var sugg = gDocsMatches[i];
var $li;
if (sugg.type == "design") {
$li = new_suggestion($(".suggest-card.design ul"));
} else
if (sugg.type == "distribute") {
$li = new_suggestion($(".suggest-card.distribute ul"));
} else
if (sugg.type == "samples") {
$li = new_suggestion($(".suggest-card.develop .child-card.samples"));
} else
if (sugg.type == "training") {
$li = new_suggestion($(".suggest-card.develop .child-card.training"));
} else
if (sugg.type == "about"||"guide"||"tools"||"google") {
$li = new_suggestion($(".suggest-card.develop .child-card.guides"));
} else {
continue;
}
set_item_values_jd(toroot, $li, sugg);
set_item_selected($li, i == gSelectedIndex);
}
// add heading and show or hide card
if ($(".suggest-card.design li").length > 0) {
$(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
$(".suggest-card.design").show(300);
} else {
$('.suggest-card.design').hide(300);
}
if ($(".suggest-card.distribute li").length > 0) {
$(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
$(".suggest-card.distribute").show(300);
} else {
$('.suggest-card.distribute').hide(300);
}
if ($(".child-card.guides li").length > 0) {
$(".child-card.guides").prepend("<li class='header'>Guides:</li>");
$(".child-card.guides li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.training li").length > 0) {
$(".child-card.training").prepend("<li class='header'>Training:</li>");
$(".child-card.training li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.samples li").length > 0) {
$(".child-card.samples").prepend("<li class='header'>Samples:</li>");
$(".child-card.samples li").appendTo(".suggest-card.develop ul");
}
if ($(".suggest-card.develop li").length > 0) {
$(".suggest-card.develop").show(300);
} else {
$('.suggest-card.develop').hide(300);
}
} else {
$('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
}
}
/** Called by the search input's onkeydown and onkeyup events.
* Handles navigation with keyboard arrows, Enter key to invoke search,
* otherwise invokes search suggestions on key-up event.
* @param e The JS event
* @param kd True if the event is key-down
* @param toroot A string for the site's root path
* @returns True if the event should bubble up
*/
function search_changed(e, kd, toroot)
{
var currentLang = getLangPref();
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// get the ul hosting the currently selected item
gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
var $selectedUl = $columns[gSelectedColumn];
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 27 = esc
if (e.keyCode == 27) {
// close all search results
if (kd) $('.search .close').trigger('click');
return true;
}
// 13 = enter
else if (e.keyCode == 13) {
if (gSelectedIndex < 0) {
$('.suggest-card').hide();
if ($("#searchResults").is(":hidden") && (search.value != "")) {
// if results aren't showing (and text not empty), return true to allow search to execute
$('body,html').animate({scrollTop:0}, '500', 'swing');
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
// click the link corresponding to selected item
$("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
return false;
}
}
// If Google results are showing, return true to allow ajax search to execute
else if ($("#searchResults").is(":visible")) {
// Also, if search_results is scrolled out of view, scroll to top to make results visible
if ((sticky ) && (search.value != "")) {
$('body,html').animate({scrollTop:0}, '500', 'swing');
}
return true;
}
// 38 UP ARROW
else if (kd && (e.keyCode == 38)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
gSelectedIndex--;
}
if (gSelectedIndex >= 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex--;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
// If user reaches top, reset selected column
if (gSelectedIndex < 0) {
gSelectedColumn = -1;
}
}
return false;
}
// 40 DOWN ARROW
else if (kd && (e.keyCode == 40)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
gSelectedIndex++;
}
if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex++;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
}
return false;
}
// Consider left/right arrow navigation
// NOTE: Order of suggest columns are reverse order (index position 0 is on right)
else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
// 37 LEFT ARROW
// go left only if current column is not left-most column (last column)
if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn++;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
// 39 RIGHT ARROW
// go right only if current column is not the right-most column (first column)
else if (e.keyCode == 39 && gSelectedColumn > 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn--;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
}
// if key-up event and not arrow down/up/left/right,
// read the search query and add suggestions to gMatches
else if (!kd && (e.keyCode != 40)
&& (e.keyCode != 38)
&& (e.keyCode != 37)
&& (e.keyCode != 39)) {
gSelectedIndex = -1;
gMatches = new Array();
matchedCount = 0;
gGoogleMatches = new Array();
matchedCountGoogle = 0;
gDocsMatches = new Array();
matchedCountDocs = 0;
// Search for Android matches
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_api_results(text, gMatches);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
}
// Search for Google matches
for (var i=0; i<GOOGLE_DATA.length; i++) {
var s = GOOGLE_DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gGoogleMatches[matchedCountGoogle] = s;
matchedCountGoogle++;
}
}
rank_autocomplete_api_results(text, gGoogleMatches);
for (var i=0; i<gGoogleMatches.length; i++) {
var s = gGoogleMatches[i];
}
highlight_autocomplete_result_labels(text);
// Search for matching JD docs
if (text.length >= 2) {
// Regex to match only the beginning of a word
var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
// Search for Training classes
for (var i=0; i<TRAINING_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TRAINING_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Don't consider doc title for lessons (only for class landing pages),
// unless the lesson has a tag that already matches
if ((s.lang == currentLang) &&
(!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
// it matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for API Guides
for (var i=0; i<GUIDE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GUIDE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Tools Guides
for (var i=0; i<TOOLS_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TOOLS_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for About docs
for (var i=0; i<ABOUT_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = ABOUT_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Design guides
for (var i=0; i<DESIGN_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DESIGN_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Distribute guides
for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DISTRIBUTE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Google guides
for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GOOGLE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Samples
for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = SAMPLES_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title.t
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Rank/sort all the matched pages
rank_autocomplete_doc_results(text, gDocsMatches);
}
// draw the suggestions
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
/* Order the jd doc result list based on match quality */
function rank_autocomplete_doc_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
var _resultScoreFn = function(match) {
var score = 1.0;
// if the query matched a tag
if (match.matched_tag > 0) {
// multiply score by factor relative to position in tags list (max of 3)
score *= 3 / match.matched_tag;
// if it also matched the title
if (match.matched_title > 0) {
score *= 2;
}
} else if (match.matched_title > 0) {
score *= 3;
}
return score;
};
for (var i=0; i<matches.length; i++) {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Order the result list based on match quality */
function rank_autocomplete_api_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<matches.length; i++) {
// if the API is deprecated, default score is 0; otherwise, perform scoring
if (matches[i].deprecated == "true") {
matches[i].__resultScore = 0;
} else {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Add emphasis to part of string that matches query */
function highlight_autocomplete_result_labels(query) {
query = query || '';
if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
for (var i=0; i<gGoogleMatches.length; i++) {
gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
$(".suggest-card").hide();
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow', setStickyTop);
return false;
}
function hideResults() {
$("#searchResults").slideUp('fast', setStickyTop);
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
var searchControl;
google.load('search', '1', {"callback" : function() {
searchControl = new google.search.SearchControl();
} });
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// once search results load, set up click listeners
searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
addResultClickListeners();
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow', setStickyTop);
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
/* Adjust the scroll position to account for sticky header, only if the hash matches an id.
This does not handle <a name=""> tags. Some CSS fixes those, but only for reference docs. */
function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
}
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
// If the hash isn't a search query or there's an error in the query,
// then adjust the scroll position to account for sticky header, then exit.
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
offsetScrollForSticky();
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow', setStickyTop);
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
// add analytics tracking events to each result link
function addResultClickListeners() {
$("#searchResults a.gs-title").each(function(index, link) {
// When user clicks enter for Google search results, track it
$(link).click(function() {
ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
});
});
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference") == 0) {
if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
&& !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
&& !(location.pathname.indexOf("/reference/com/google") == 0)) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
writeCookie(API_LEVEL_COOKIE, selectedLevel, null);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher. To reveal, change the target API level "
+ "above the left navigation.");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
}
});
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
/****** NEW version of script to build google and sample navs dynamically ******/
// TODO: update Google reference docs to tolerate this new implementation
var NODE_NAME = 0;
var NODE_HREF = 1;
var NODE_GROUP = 2;
var NODE_TAGS = 3;
var NODE_CHILDREN = 4;
function init_google_navtree2(navtree_id, data)
{
var $containerUl = $("#"+navtree_id);
for (var i in data) {
var node_data = data[i];
$containerUl.append(new_google_node2(node_data));
}
// Make all third-generation list items 'sticky' to prevent them from collapsing
$containerUl.find('li li li.nav-section').addClass('sticky');
initExpandableNavItems("#"+navtree_id);
}
function new_google_node2(node_data)
{
var linkText = node_data[NODE_NAME];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
var $li = $('<li>');
var $a;
if (node_data[NODE_HREF] != null) {
$a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
+ linkText + '</a>');
} else {
$a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
+ linkText + '/</a>');
}
var $childUl = $('<ul>');
if (node_data[NODE_CHILDREN] != null) {
$li.addClass("nav-section");
$a = $('<div class="nav-section-header">').append($a);
if (node_data[NODE_HREF] == null) $a.addClass('empty');
for (var i in node_data[NODE_CHILDREN]) {
var child_node_data = node_data[NODE_CHILDREN][i];
$childUl.append(new_google_node2(child_node_data));
}
$li.append($childUl);
}
$li.prepend($a);
return $li;
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
}
function init_default_google_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function init_default_gcm_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function showSamplesRefTree() {
init_default_samples_navtree(toRoot);
}
function init_default_samples_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
// hack to remove the "about the samples" link then put it back in
// after we nuke the list to remove the dummy static list of samples
var $firstLi = $("#nav.samples-nav > li:first-child").clone();
$("#nav.samples-nav").empty();
$("#nav.samples-nav").append($firstLi);
init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
highlightSidenav();
resizeNav();
if ($("#jd-content #samples").length) {
showSamples();
}
}
});
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
/* On-demand functions */
/** Move sample code line numbers out of PRE block and into non-copyable column */
function initCodeLineNumbers() {
var numbers = $("#codesample-block a.number");
if (numbers.length) {
$("#codesample-line-numbers").removeClass("hidden").append(numbers);
}
$(document).ready(function() {
// select entire line when clicked
$("span.code-line").click(function() {
if (!shifted) {
selectText(this);
}
});
// invoke line link on double click
$(".code-line").dblclick(function() {
document.location.hash = $(this).attr('id');
});
// highlight the line when hovering on the number
$("#codesample-line-numbers a.number").mouseover(function() {
var id = $(this).attr('href');
$(id).css('background','#e7e7e7');
});
$("#codesample-line-numbers a.number").mouseout(function() {
var id = $(this).attr('href');
$(id).css('background','none');
});
});
}
// create SHIFT key binder to avoid the selectText method when selecting multiple lines
var shifted = false;
$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
// courtesy of jasonedelman.com
function selectText(element) {
var doc = document
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
/** Display links and other information about samples that match the
group specified by the URL */
function showSamples() {
var group = $("#samples").attr('class');
$("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
var $ul = $("<ul>");
$selectedLi = $("#nav li.selected");
$selectedLi.children("ul").children("li").each(function() {
var $li = $("<li>").append($(this).find("a").first().clone());
$ul.append($li);
});
$("#samples").append($ul);
}
/* ########################################################## */
/* ################### RESOURCE CARDS ##################### */
/* ########################################################## */
/** Handle resource queries, collections, and grids (sections). Requires
jd_tag_helpers.js and the *_unified_data.js to be loaded. */
(function() {
// Prevent the same resource from being loaded more than once per page.
var addedPageResources = {};
$(document).ready(function() {
$('.resource-widget').each(function() {
initResourceWidget(this);
});
/* Pass the line height to ellipsisfade() to adjust the height of the
text container to show the max number of lines possible, without
showing lines that are cut off. This works with the css ellipsis
classes to fade last text line and apply an ellipsis char. */
//card text currently uses 15px line height.
var lineHeight = 15;
$('.card-info .text').ellipsisfade(lineHeight);
});
/*
Three types of resource layouts:
Flow - Uses a fixed row-height flow using float left style.
Carousel - Single card slideshow all same dimension absolute.
Stack - Uses fixed columns and flexible element height.
*/
function initResourceWidget(widget) {
var $widget = $(widget);
var isFlow = $widget.hasClass('resource-flow-layout'),
isCarousel = $widget.hasClass('resource-carousel-layout'),
isStack = $widget.hasClass('resource-stack-layout');
// find size of widget by pulling out its class name
var sizeCols = 1;
var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
if (m) {
sizeCols = parseInt(m[1], 10);
}
var opts = {
cardSizes: ($widget.data('cardsizes') || '').split(','),
maxResults: parseInt($widget.data('maxresults') || '100', 10),
itemsPerPage: $widget.data('itemsperpage'),
sortOrder: $widget.data('sortorder'),
query: $widget.data('query'),
section: $widget.data('section'),
sizeCols: sizeCols,
/* Added by LFL 6/6/14 */
resourceStyle: $widget.data('resourcestyle') || 'card',
stackSort: $widget.data('stacksort') || 'true'
};
// run the search for the set of resources to show
var resources = buildResourceList(opts);
if (isFlow) {
drawResourcesFlowWidget($widget, opts, resources);
} else if (isCarousel) {
drawResourcesCarouselWidget($widget, opts, resources);
} else if (isStack) {
/* Looks like this got removed and is not used, so repurposing for the
homepage style layout.
Modified by LFL 6/6/14
*/
//var sections = buildSectionList(opts);
opts['numStacks'] = $widget.data('numstacks');
drawResourcesStackWidget($widget, opts, resources/*, sections*/);
}
}
/* Initializes a Resource Carousel Widget */
function drawResourcesCarouselWidget($widget, opts, resources) {
$widget.empty();
var plusone = true; //always show plusone on carousel
$widget.addClass('resource-card slideshow-container')
.append($('<a>').addClass('slideshow-prev').text('Prev'))
.append($('<a>').addClass('slideshow-next').text('Next'));
var css = { 'width': $widget.width() + 'px',
'height': $widget.height() + 'px' };
var $ul = $('<ul>');
for (var i = 0; i < resources.length; ++i) {
var $card = $('<a>')
.attr('href', cleanUrl(resources[i].url))
.decorateResourceCard(resources[i],plusone);
$('<li>').css(css)
.append($card)
.appendTo($ul);
}
$('<div>').addClass('frame')
.append($ul)
.appendTo($widget);
$widget.dacSlideshow({
auto: true,
btnPrev: '.slideshow-prev',
btnNext: '.slideshow-next'
});
};
/* Initializes a Resource Card Stack Widget (column-based layout)
Modified by LFL 6/6/14
*/
function drawResourcesStackWidget($widget, opts, resources, sections) {
// Don't empty widget, grab all items inside since they will be the first
// items stacked, followed by the resource query
var plusone = true; //by default show plusone on section cards
var cards = $widget.find('.resource-card').detach().toArray();
var numStacks = opts.numStacks || 1;
var $stacks = [];
var urlString;
for (var i = 0; i < numStacks; ++i) {
$stacks[i] = $('<div>').addClass('resource-card-stack')
.appendTo($widget);
}
var sectionResources = [];
// Extract any subsections that are actually resource cards
if (sections) {
for (var i = 0; i < sections.length; ++i) {
if (!sections[i].sections || !sections[i].sections.length) {
// Render it as a resource card
sectionResources.push(
$('<a>')
.addClass('resource-card section-card')
.attr('href', cleanUrl(sections[i].resource.url))
.decorateResourceCard(sections[i].resource,plusone)[0]
);
} else {
cards.push(
$('<div>')
.addClass('resource-card section-card-menu')
.decorateResourceSection(sections[i],plusone)[0]
);
}
}
}
cards = cards.concat(sectionResources);
for (var i = 0; i < resources.length; ++i) {
var $card = createResourceElement(resources[i], opts);
if (opts.resourceStyle.indexOf('related') > -1) {
$card.addClass('related-card');
}
cards.push($card[0]);
}
if (opts.stackSort != 'false') {
for (var i = 0; i < cards.length; ++i) {
// Find the stack with the shortest height, but give preference to
// left to right order.
var minHeight = $stacks[0].height();
var minIndex = 0;
for (var j = 1; j < numStacks; ++j) {
var height = $stacks[j].height();
if (height < minHeight - 45) {
minHeight = height;
minIndex = j;
}
}
$stacks[minIndex].append($(cards[i]));
}
}
};
/*
Create a resource card using the given resource object and a list of html
configured options. Returns a jquery object containing the element.
*/
function createResourceElement(resource, opts, plusone) {
var $el;
// The difference here is that generic cards are not entirely clickable
// so its a div instead of an a tag, also the generic one is not given
// the resource-card class so it appears with a transparent background
// and can be styled in whatever way the css setup.
if (opts.resourceStyle == 'generic') {
$el = $('<div>')
.addClass('resource')
.attr('href', cleanUrl(resource.url))
.decorateResource(resource, opts);
} else {
var cls = 'resource resource-card';
$el = $('<a>')
.addClass(cls)
.attr('href', cleanUrl(resource.url))
.decorateResourceCard(resource, plusone);
}
return $el;
}
/* Initializes a flow widget, see distribute.scss for generating accompanying css */
function drawResourcesFlowWidget($widget, opts, resources) {
$widget.empty();
var cardSizes = opts.cardSizes || ['6x6'];
var i = 0, j = 0;
var plusone = true; // by default show plusone on resource cards
while (i < resources.length) {
var cardSize = cardSizes[j++ % cardSizes.length];
cardSize = cardSize.replace(/^\s+|\s+$/,'');
// Some card sizes do not get a plusone button, such as where space is constrained
// or for cards commonly embedded in docs (to improve overall page speed).
plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
(cardSize == "9x2") || (cardSize == "9x3") ||
(cardSize == "12x2") || (cardSize == "12x3"));
// A stack has a third dimension which is the number of stacked items
var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
var stackCount = 0;
var $stackDiv = null;
if (isStack) {
// Create a stack container which should have the dimensions defined
// by the product of the items inside.
$stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+ 'x' + isStack[2] * isStack[3]) .appendTo($widget);
}
// Build each stack item or just a single item
do {
var resource = resources[i];
var $card = createResourceElement(resources[i], opts, plusone);
$card.addClass('resource-card-' + cardSize +
' resource-card-' + resource.type);
if (isStack) {
$card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
if (++stackCount == parseInt(isStack[3])) {
$card.addClass('resource-card-row-stack-last');
stackCount = 0;
}
} else {
stackCount = 0;
}
$card.appendTo($stackDiv || $widget);
} while (++i < resources.length && stackCount > 0);
}
}
/* Build a site map of resources using a section as a root. */
function buildSectionList(opts) {
if (opts.section && SECTION_BY_ID[opts.section]) {
return SECTION_BY_ID[opts.section].sections || [];
}
return [];
}
function buildResourceList(opts) {
var maxResults = opts.maxResults || 100;
var query = opts.query || '';
var expressions = parseResourceQuery(query);
var addedResourceIndices = {};
var results = [];
for (var i = 0; i < expressions.length; i++) {
var clauses = expressions[i];
// build initial set of resources from first clause
var firstClause = clauses[0];
var resources = [];
switch (firstClause.attr) {
case 'type':
resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
break;
case 'lang':
resources = ALL_RESOURCES_BY_LANG[firstClause.value];
break;
case 'tag':
resources = ALL_RESOURCES_BY_TAG[firstClause.value];
break;
case 'collection':
var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
case 'section':
var urls = SITE_MAP[firstClause.value].sections || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
}
// console.log(firstClause.attr + ':' + firstClause.value);
resources = resources || [];
// use additional clauses to filter corpus
if (clauses.length > 1) {
var otherClauses = clauses.slice(1);
resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
}
// filter out resources already added
if (i > 1) {
resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
}
// add to list of already added indices
for (var j = 0; j < resources.length; j++) {
// console.log(resources[j].title);
addedResourceIndices[resources[j].index] = 1;
}
// concat to final results list
results = results.concat(resources);
}
if (opts.sortOrder && results.length) {
var attr = opts.sortOrder;
if (opts.sortOrder == 'random') {
var i = results.length, j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = results[i];
results[i] = results[j];
results[j] = temp;
}
} else {
var desc = attr.charAt(0) == '-';
if (desc) {
attr = attr.substring(1);
}
results = results.sort(function(x,y) {
return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
});
}
}
results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
results = results.slice(0, maxResults);
for (var j = 0; j < results.length; ++j) {
addedPageResources[results[j].index] = 1;
}
return results;
}
function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
return function(resource) {
return !addedResourceIndices[resource.index];
};
}
function getResourceMatchesClausesFilter(clauses) {
return function(resource) {
return doesResourceMatchClauses(resource, clauses);
};
}
function doesResourceMatchClauses(resource, clauses) {
for (var i = 0; i < clauses.length; i++) {
var map;
switch (clauses[i].attr) {
case 'type':
map = IS_RESOURCE_OF_TYPE[clauses[i].value];
break;
case 'lang':
map = IS_RESOURCE_IN_LANG[clauses[i].value];
break;
case 'tag':
map = IS_RESOURCE_TAGGED[clauses[i].value];
break;
}
if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
return clauses[i].negative;
}
}
return true;
}
function cleanUrl(url)
{
if (url && url.indexOf('//') === -1) {
url = toRoot + url;
}
return url;
}
function parseResourceQuery(query) {
// Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
var expressions = [];
var expressionStrs = query.split(',') || [];
for (var i = 0; i < expressionStrs.length; i++) {
var expr = expressionStrs[i] || '';
// Break expression into clauses (clause e.g. 'tag:foo')
var clauses = [];
var clauseStrs = expr.split(/(?=[\+\-])/);
for (var j = 0; j < clauseStrs.length; j++) {
var clauseStr = clauseStrs[j] || '';
// Get attribute and value from clause (e.g. attribute='tag', value='foo')
var parts = clauseStr.split(':');
var clause = {};
clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
if (clause.attr) {
if (clause.attr.charAt(0) == '+') {
clause.attr = clause.attr.substring(1);
} else if (clause.attr.charAt(0) == '-') {
clause.negative = true;
clause.attr = clause.attr.substring(1);
}
}
if (parts.length > 1) {
clause.value = parts[1].replace(/^\s+|\s+$/g,'');
}
clauses.push(clause);
}
if (!clauses.length) {
continue;
}
expressions.push(clauses);
}
return expressions;
}
})();
(function($) {
/*
Utility method for creating dom for the description area of a card.
Used in decorateResourceCard and decorateResource.
*/
function buildResourceCardDescription(resource, plusone) {
var $description = $('<div>').addClass('description ellipsis');
$description.append($('<div>').addClass('text').html(resource.summary));
if (resource.cta) {
$description.append($('<a>').addClass('cta').html(resource.cta));
}
if (plusone) {
var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
"//developer.android.com/" + resource.url;
$description.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', plusurl)));
}
return $description;
}
/* Simple jquery function to create dom for a standard resource card */
$.fn.decorateResourceCard = function(resource,plusone) {
var section = resource.group || resource.type;
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
$('<div>').addClass('card-bg')
.css('background-image', 'url(' + (imgUrl || toRoot +
'assets/images/resource-card-default-android.jpg') + ')')
.appendTo(this);
$('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
.append($('<div>').addClass('section').text(section))
.append($('<div>').addClass('title').html(resource.title))
.append(buildResourceCardDescription(resource, plusone))
.appendTo(this);
return this;
};
/* Simple jquery function to create dom for a resource section card (menu) */
$.fn.decorateResourceSection = function(section,plusone) {
var resource = section.resource;
//keep url clean for matching and offline mode handling
var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
var $base = $('<a>')
.addClass('card-bg')
.attr('href', resource.url)
.append($('<div>').addClass('card-section-icon')
.append($('<div>').addClass('icon'))
.append($('<div>').addClass('section').html(resource.title)))
.appendTo(this);
var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
if (section.sections && section.sections.length) {
// Recurse the section sub-tree to find a resource image.
var stack = [section];
while (stack.length) {
if (stack[0].resource.image) {
$base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
break;
}
if (stack[0].sections) {
stack = stack.concat(stack[0].sections);
}
stack.shift();
}
var $ul = $('<ul>')
.appendTo($cardInfo);
var max = section.sections.length > 3 ? 3 : section.sections.length;
for (var i = 0; i < max; ++i) {
var subResource = section.sections[i];
if (!plusone) {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util'))))
.appendTo($ul);
} else {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', resource.url)))))
.appendTo($ul);
}
}
// Add a more row
if (max < section.sections.length) {
$('<li>')
.append($('<a>').attr('href', resource.url)
.append($('<div>')
.addClass('title')
.text('More')))
.appendTo($ul);
}
} else {
// No sub-resources, just render description?
}
return this;
};
/* Render other types of resource styles that are not cards. */
$.fn.decorateResource = function(resource, opts) {
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
var linkUrl = resource.url;
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
if (linkUrl && linkUrl.indexOf('//') === -1) {
linkUrl = toRoot + linkUrl;
}
$(this).append(
$('<div>').addClass('image')
.css('background-image', 'url(' + imgUrl + ')'),
$('<div>').addClass('info').append(
$('<h4>').addClass('title').html(resource.title),
$('<p>').addClass('summary').html(resource.summary),
$('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
)
);
return this;
};
})(jQuery);
/* Calculate the vertical area remaining */
(function($) {
$.fn.ellipsisfade= function(lineHeight) {
this.each(function() {
// get element text
var $this = $(this);
var remainingHeight = $this.parent().parent().height();
$this.parent().siblings().each(function ()
{
if ($(this).is(":visible")) {
var h = $(this).height();
remainingHeight = remainingHeight - h;
}
});
adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
$this.parent().css({'height': adjustedRemainingHeight});
$this.css({'height': "auto"});
});
return this;
};
}) (jQuery);
/*
Fullscreen Carousel
The following allows for an area at the top of the page that takes over the
entire browser height except for its top offset and an optional bottom
padding specified as a data attribute.
HTML:
<div class="fullscreen-carousel">
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
etc ...
</div>
Control over how the carousel takes over the screen can mostly be defined in
a css file. Setting min-height on the .fullscreen-carousel-content elements
will prevent them from shrinking to far vertically when the browser is very
short, and setting max-height on the .fullscreen-carousel itself will prevent
the area from becoming to long in the case that the browser is stretched very
tall.
There is limited functionality for having multiple sections since that request
was removed, but it is possible to add .next-arrow and .prev-arrow elements to
scroll between multiple content areas.
*/
(function() {
$(document).ready(function() {
$('.fullscreen-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var topOffset = $widget.offset().top;
var padBottom = parseInt($widget.data('paddingbottom')) || 0;
var maxHeight = 0;
var minHeight = 0;
var $content = $widget.find('.fullscreen-carousel-content');
var $nextArrow = $widget.find('.next-arrow');
var $prevArrow = $widget.find('.prev-arrow');
var $curSection = $($content[0]);
if ($content.length <= 1) {
$nextArrow.hide();
$prevArrow.hide();
} else {
$nextArrow.click(function() {
var index = ($content.index($curSection) + 1);
$curSection.hide();
$curSection = $($content[index >= $content.length ? 0 : index]);
$curSection.show();
});
$prevArrow.click(function() {
var index = ($content.index($curSection) - 1);
$curSection.hide();
$curSection = $($content[index < 0 ? $content.length - 1 : 0]);
$curSection.show();
});
}
// Just hide all content sections except first.
$content.each(function(index) {
if ($(this).height() > minHeight) minHeight = $(this).height();
$(this).css({position: 'absolute', display: index > 0 ? 'none' : ''});
});
// Register for changes to window size, and trigger.
$(window).resize(resizeWidget);
resizeWidget();
function resizeWidget() {
var height = $(window).height() - topOffset - padBottom;
$widget.width($(window).width());
$widget.height(height < minHeight ? minHeight :
(maxHeight && height > maxHeight ? maxHeight : height));
}
}
})();
/*
Tab Carousel
The following allows tab widgets to be installed via the html below. Each
tab content section should have a data-tab attribute matching one of the
nav items'. Also each tab content section should have a width matching the
tab carousel.
HTML:
<div class="tab-carousel">
<ul class="tab-nav">
<li><a href="#" data-tab="handsets">Handsets</a>
<li><a href="#" data-tab="wearable">Wearable</a>
<li><a href="#" data-tab="tv">TV</a>
</ul>
<div class="tab-carousel-content">
<div data-tab="handsets">
<!--Full width content here-->
</div>
<div data-tab="wearable">
<!--Full width content here-->
</div>
<div data-tab="tv">
<!--Full width content here-->
</div>
</div>
</div>
*/
(function() {
$(document).ready(function() {
$('.tab-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var $nav = $widget.find('.tab-nav');
var $anchors = $nav.find('[data-tab]');
var $li = $nav.find('li');
var $contentContainer = $widget.find('.tab-carousel-content');
var $tabs = $contentContainer.find('[data-tab]');
var $curTab = $($tabs[0]); // Current tab is first tab.
var width = $widget.width();
// Setup nav interactivity.
$anchors.click(function(evt) {
evt.preventDefault();
var query = '[data-tab=' + $(this).data('tab') + ']';
transitionWidget($tabs.filter(query));
});
// Add highlight for navigation on first item.
var $highlight = $('<div>').addClass('highlight')
.css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
.appendTo($nav);
// Store height since we will change contents to absolute.
$contentContainer.height($contentContainer.height());
// Absolutely position tabs so they're ready for transition.
$tabs.each(function(index) {
$(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
});
function transitionWidget($toTab) {
if (!$curTab.is($toTab)) {
var curIndex = $tabs.index($curTab[0]);
var toIndex = $tabs.index($toTab[0]);
var dir = toIndex > curIndex ? 1 : -1;
// Animate content sections.
$toTab.css({left:(width * dir) + 'px'});
$curTab.animate({left:(width * -dir) + 'px'});
$toTab.animate({left:'0'});
// Animate navigation highlight.
$highlight.animate({left:$($li[toIndex]).position().left + 'px',
width:$($li[toIndex]).outerWidth() + 'px'})
// Store new current section.
$curTab = $toTab;
}
}
}
})();
| JavaScript |
$(document).ready(function() {
// prep nav expandos
var pagePath = document.location.pathname;
if (pagePath.indexOf(SITE_ROOT) == 0) {
pagePath = pagePath.substr(SITE_ROOT.length);
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path should be an absolute URL.
pagePath = SITE_ROOT + pagePath;
}
// select current page in sidenav and set up prev/next links if they exist
var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]');
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
$selListItem.closest('li>ul').addClass('expanded');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
$prevLink = $selListItem.parents('li').find('a');
}
if ($prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
$('.prev-page-link').hide();
} else {
$('.prev-page-link').attr('href', prevHref).show();
}
} else {
$('.prev-page-link').hide();
}
// set up next links
var $nextLink = [];
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul').find('a:eq(0)')
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)');
}
}
if ($nextLink.length) {
$('.next-page-link').attr('href', $nextLink.attr('href')).show();
} else {
$('.next-page-link').hide();
}
}
// Set up expand/collapse behavior
$('.nav-y li').has('ul').click(function() {
if ($(this).hasClass('expanded')) {
return;
}
// hide other
var $old = $('.nav-y li.expanded');
if ($old.length) {
var $oldUl = $old.children('ul');
$oldUl.css('height', $oldUl.height() + 'px');
window.setTimeout(function() {
$oldUl
.addClass('animate-height')
.css('height', '');
}, 0);
$old.removeClass('expanded');
}
// show me
$(this).addClass('expanded');
var $ul = $(this).children('ul');
var expandedHeight = $ul.height();
$ul
.removeClass('animate-height')
.css('height', 0);
window.setTimeout(function() {
$ul
.addClass('animate-height')
.css('height', expandedHeight + 'px');
}, 0);
});
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.text($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
// Set up fixed navbar
var navBarIsFixed = false;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var navBarShouldBeFixed = (scrollTop > (100 - 40));
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
$('#nav')
.addClass('fixed')
.prependTo('#page-container');
} else {
$('#nav')
.removeClass('fixed')
.prependTo('#nav-container');
}
navBarIsFixed = navBarShouldBeFixed;
}
});
}); | JavaScript |
/* API LEVEL TOGGLE */
<?cs if:reference.apilevels ?>
addLoadEvent(changeApiLevel);
<?cs /if ?>
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevel = readCookie(API_LEVEL_COOKIE);
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevel = $("body").attr("class");
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevel = maxLevel;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevel, "body");
} else {
selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
}
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>"
+ "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest "
+ "and be compiled against a version of the library that supports an equal or higher API Level. To reveal this "
+ "document, change the value of the API Level filter above.</p>"
+ "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher");
else obj.removeClass("absent").removeAttr("title");
});
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data(toroot) {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toroot+"navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root) {
toRoot = root;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var BUILD_TIMESTAMP = "";
| JavaScript |
var NAVTREE_DATA =
[ [ "android.support.test.espresso", "reference/android/support/test/espresso/package-summary.html", [ [ "Interfaces", null, [ [ "IdlingResource", "reference/android/support/test/espresso/IdlingResource.html", null, null ], [ "IdlingResource.ResourceCallback", "reference/android/support/test/espresso/IdlingResource.ResourceCallback.html", null, null ] ]
, null ] ]
, null ], [ "android.support.test.espresso.idling", "reference/android/support/test/espresso/idling/package-summary.html", [ [ "Classes", null, [ [ "BuildConfig", "reference/android/support/test/espresso/idling/BuildConfig.html", null, null ] ]
, null ] ]
, null ] ]
;
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
return true;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
return false;
}
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var mPagePath; // initialized in ready() function
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
var GOOGLE_DATA; // combined data for google service apis, used for search suggest
// Ensure that all ajax getScript() requests allow caching
$.ajaxSetup({
cache: true
});
/****** ON LOAD SET UP STUFF *********/
$(document).ready(function() {
// show lang dialog if the URL includes /intl/
//if (location.pathname.substring(0,6) == "/intl/") {
// var lang = location.pathname.split('/')[2];
// if (lang != getLangPref()) {
// $("#langMessage a.yes").attr("onclick","changeLangPref('" + lang
// + "', true); $('#langMessage').hide(); return false;");
// $("#langMessage .lang." + lang).show();
// $("#langMessage").show();
// }
//}
// load json file for JD doc search suggestions
$.getScript(toRoot + 'jd_lists_unified.js');
// load json file for Android API search suggestions
$.getScript(toRoot + 'reference/lists.js');
// load json files for Google services API suggestions
$.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
// once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
if(jqxhr.status === 200) {
$.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
// combine GCM and GMS data
GOOGLE_DATA = GMS_DATA;
var start = GOOGLE_DATA.length;
for (var i=0; i<GCM_DATA.length; i++) {
GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
link:GCM_DATA[i].link, type:GCM_DATA[i].type});
}
}
});
}
});
// setup keyboard listener for search shortcut
$('body').keyup(function(event) {
if (event.which == 191) {
$('#search_autocomplete').focus();
}
});
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2')
.not('#tb h2')
.not('.sidebox h2')
.not('#devdoc-nav h2')
.not('h2.norule').css({marginBottom:0})
.after('<hr/>');
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false);
hideResults();
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
// Need a copy of the pagePath before it gets changed in the next block;
// it's needed to perform proper tab highlighting in offline docs (see rootDir below)
var pagePathOriginal = pagePath;
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
$("#sticky-header").addClass("design");
// highlight About tabs
} else if ($("body").hasClass("about")) {
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "about") {
$("#nav-x li.about a").addClass("selected");
} else if (rootDir == "wear") {
$("#nav-x li.wear a").addClass("selected");
} else if (rootDir == "tv") {
$("#nav-x li.tv a").addClass("selected");
} else if (rootDir == "auto") {
$("#nav-x li.auto a").addClass("selected");
}
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
$("#sticky-header").addClass("develop");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else if ($("body").hasClass("samples")) {
$("#nav-x li.samples a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
$("#sticky-header").addClass("distribute");
var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
if (secondFrag == "users") {
$("#nav-x li.users a").addClass("selected");
} else if (secondFrag == "engage") {
$("#nav-x li.engage a").addClass("selected");
} else if (secondFrag == "monetize") {
$("#nav-x li.monetize a").addClass("selected");
} else if (secondFrag == "tools") {
$("#nav-x li.disttools a").addClass("selected");
} else if (secondFrag == "stories") {
$("#nav-x li.stories a").addClass("selected");
} else if (secondFrag == "essentials") {
$("#nav-x li.essentials a").addClass("selected");
} else if (secondFrag == "googleplay") {
$("#nav-x li.googleplay a").addClass("selected");
}
} else if ($("body").hasClass("about")) {
$("#sticky-header").addClass("about");
}
// set global variable so we can highlight the sidenav a bit later (such as for google reference)
// and highlight the sidenav
mPagePath = pagePath;
highlightSidenav();
buildBreadcrumbs();
// set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if ($nextLink.length == 0) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
if ($nextLink.length == 0) {
// if that doesn't work, we're at the end of the list, so disable NEXT link
$('.next-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
}
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
if ($nextLink.length) {
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide")
.append(": " + $nextLink.html());
$('.next-class-link').find('.new').empty();
}
} else {
$('.next-page-link').attr('href', $nextLink.attr('href'))
.removeClass("hide");
// for the footer link, also add the next page title
$('.content-footer .next-page-link').append(": " + $nextLink.html());
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
// create an array for all the class descriptions
var $classDescriptions = new Array($classLinks.length);
var lang = getLangPref();
$classLinks.each(function(index) {
var langDescr = $(this).attr(lang + "-description");
if (typeof langDescr !== 'undefined' && langDescr !== false) {
// if there's a class description in the selected language, use that
$classDescriptions[index] = langDescr;
} else {
// otherwise, use the default english description
$classDescriptions[index] = $(this).attr("description");
}
});
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
+ ' width="64" height="64" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
+ ' width="64" height="64" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
initExpandableNavItems("#nav");
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (sticky) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
// Resize once loading is finished
resizeNav();
// Check if there's an anchor that we need to scroll into view.
// A delay is needed, because some browsers do not immediately scroll down to the anchor
window.setTimeout(offsetScrollForSticky, 100);
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
/* setup shadowbox for any videos that want it */
var $videoLinks = $("a.video-shadowbox-button, a.notice-developers-video");
if ($videoLinks.length) {
// if there's at least one, add the shadowbox HTML to the body
$('body').prepend(
'<div id="video-container">'+
'<div id="video-frame">'+
'<div class="video-close">'+
'<span id="icon-video-close" onclick="closeVideo()"> </span>'+
'</div>'+
'<div id="youTubePlayer"></div>'+
'</div>'+
'</div>');
// loads the IFrame Player API code asynchronously.
$.getScript("https://www.youtube.com/iframe_api");
$videoLinks.each(function() {
var videoId = $(this).attr('href').split('?v=')[1];
$(this).click(function(event) {
event.preventDefault();
startYouTubePlayer(videoId);
});
});
}
});
// END of the onload event
var youTubePlayer;
function onYouTubeIframeAPIReady() {
}
function startYouTubePlayer(videoId) {
var idAndHash = videoId.split("#");
var startTime = 0;
var lang = getLangPref();
var captionsOn = lang == 'en' ? 0 : 1;
if (idAndHash.length > 1) {
startTime = idAndHash[1].split("t=")[1] != undefined ? idAndHash[1].split("t=")[1] : 0;
}
if (youTubePlayer == null) {
youTubePlayer = new YT.Player('youTubePlayer', {
height: '529',
width: '940',
videoId: idAndHash[0],
playerVars: {start: startTime, hl: lang, cc_load_policy: captionsOn},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} else {
youTubePlayer.playVideo();
}
$("#video-container").fadeIn(200, function(){$("#video-frame").show()});
}
function onPlayerReady(event) {
event.target.playVideo();
// track the start playing event so we know from which page the video was selected
ga('send', 'event', 'Videos', 'Start: ' +
youTubePlayer.getVideoUrl().split('?v=')[1], 'on: ' + document.location.href);
}
function closeVideo() {
try {
youTubePlayer.pauseVideo();
$("#video-container").fadeOut(200);
} catch(e) {
console.log('Video not available');
$("#video-container").fadeOut(200);
}
}
/* Track youtube playback for analytics */
function onPlayerStateChange(event) {
// Video starts, send the video ID
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'Videos', 'Play',
youTubePlayer.getVideoUrl().split('?v=')[1]);
}
// Video paused, send video ID and video elapsed time
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Videos', 'Paused',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
// Video finished, send video ID and video elapsed time
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Videos', 'Finished',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
}
function initExpandableNavItems(rootTag) {
$(rootTag + ' li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me and descendants */
section.find('ul').slideUp(250, function() {
// remove 'expanded' class from my section and any children
section.closest('li').removeClass('expanded');
$('li.nav-section', section).removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
// Stop expand/collapse behavior when clicking on nav section links
// (since we're navigating away from the page)
// This selector captures the first instance of <a>, but not those with "#" as the href.
$('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
}
/** Create the list of breadcrumb links in the sticky header */
function buildBreadcrumbs() {
var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
// Add the secondary horizontal nav item, if provided
var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
if ($selectedSecondNav.length) {
$breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
}
// Add the primary horizontal nav
var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
// If there's no header nav item, use the logo link and title from alt text
if ($selectedFirstNav.length < 1) {
$selectedFirstNav = $("<a>")
.attr('href', $("div#header .logo a").attr('href'))
.text($("div#header .logo img").attr('alt'));
}
$breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
}
/** Highlight the current page in sidenav, expanding children as appropriate */
function highlightSidenav() {
// if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
if ($("ul#nav li.selected").length) {
unHighlightSidenav();
}
// look for URL in sidenav, including the hash
var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
// If the selNavLink is still empty, look for it without the hash
if ($selNavLink.length == 0) {
$selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
}
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
}
}
function unHighlightSidenav() {
$("ul#nav li.selected").removeClass("selected");
$('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
}
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
$(document).ready(function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
});
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header-wrapper').outerHeight();
var headerVisible = scrollTop < stickyTop;
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) {
// If no selected item found, exit
return;
}
// get the selected item's offset from its container nav by measuring the item's offset
// relative to the document then subtract the container nav's offset relative to the document
var selectedOffset = $selected.offset().top - $nav.offset().top;
if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
// if it's more than 80% down the nav
// scroll the item up by an amount equal to 80% the container nav's height
api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
var age = 2*365*24*60*60; // set max-age to 2 years
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; max-age=" + age +"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
var sticky = false;
var stickyTop;
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
/* Sets the vertical scoll position at which the sticky bar should appear.
This method is called to reset the position when search results appear or hide */
function setStickyTop() {
stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
}
/*
* Displays sticky nav bar on pages when dac header scrolls out of view
*/
$(window).scroll(function(event) {
setStickyTop();
var hiding = false;
var $stickyEl = $('#sticky-header');
var $menuEl = $('.menu-container');
// Exit if there's no sidenav
if ($('#side-nav').length == 0) return;
// Exit if the mouse target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
if ($(event.target).nodeName == "DIV") {
return;
}
var top = $(window).scrollTop();
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var shouldBeSticky = top >= stickyTop;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
shouldBeSticky = false;
}
// Account for horizontal scroll
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (sticky && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (sticky == shouldBeSticky) {
return;
}
// If sticky header visible and position is now near top, hide sticky
if (sticky && !shouldBeSticky) {
sticky = false;
hiding = true;
// make the sidenav static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
// delay hide the sticky
$menuEl.removeClass('sticky-menu');
$stickyEl.fadeOut(250);
hiding = false;
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (!sticky && shouldBeSticky) {
sticky = true;
$stickyEl.fadeIn(10);
$menuEl.addClass('sticky-menu');
// make the sidenav fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (hiding && top < 15) {
$menuEl.removeClass('sticky-menu');
$stickyEl.hide();
hiding = false;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
/*
* Manages secion card states and nav resize to conclude loading
*/
(function() {
$(document).ready(function() {
// Stack hover states
$('.section-card-menu').each(function(index, el) {
var height = $(el).height();
$(el).css({height:height+'px', position:'relative'});
var $cardInfo = $(el).find('.card-info');
$cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
});
});
})();
/* MISC LIBRARY FUNCTIONS */
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function hideNestedItems(list, toggle) {
$list = $(list);
// hide nested lists
if($list.hasClass('showing')) {
$("li ol", $list).hide('fast');
$list.removeClass('showing');
// show nested lists
} else {
$("li ol", $list).show('fast');
$list.addClass('showing');
}
$(".more,.less",$(toggle)).toggle();
}
/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
function setupIdeDocToggle() {
$( "select.ide" ).change(function() {
var selected = $(this).find("option:selected").attr("value");
$(".select-ide").hide();
$(".select-ide."+selected).show();
$("select.ide").val(selected);
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
writeCookie("nav", nav_pref, "reference");
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
writeCookie("pref_lang", lang, null);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj).closest(".toggle-content");
var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("open").addClass("closed");
div.find(".toggle-content").removeClass("open").addClass("closed")
.find(".toggle-content-toggleme").hide();
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
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);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
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);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1; // the index position of currently highlighted suggestion
var gSelectedColumn = -1; // which column of suggestion lists is currently focused
var gMatches = new Array();
var gLastText = "";
var gInitialized = false;
var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
var gListLength = 0;
var gGoogleMatches = new Array();
var ROW_COUNT_GOOGLE = 15; // max number of results in list
var gGoogleListLength = 0;
var gDocsMatches = new Array();
var ROW_COUNT_DOCS = 100; // max number of results in list
var gDocsListLength = 0;
function onSuggestionClick(link) {
// When user clicks a suggested document, track it
ga('send', 'event', 'Suggestion Click', 'clicked: ' + $(link).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
}
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function set_item_values_jd(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.title);
$link.attr('href',toroot + match.url);
}
function new_suggestion($list) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('.search_filtered_wrapper li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
});
$li.append("<a onclick='onSuggestionClick(this)'></a>");
$li.attr('class','show-item');
return $li;
}
function sync_selection_table(toroot)
{
var $li; //list item jquery object
var i; //list item iterator
// if there are NO results at all, hide all columns
if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
$('.suggest-card').hide(300);
return;
}
// if there are api results
if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
// reveal suggestion list
$('.suggest-card.dummy').show();
$('.suggest-card.reference').show();
var listIndex = 0; // list index position
// reset the lists
$(".search_filtered_wrapper.reference li").remove();
// ########### ANDROID RESULTS #############
if (gMatches.length > 0) {
// determine android results to show
gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
gMatches.length : ROW_COUNT_FRAMEWORK;
for (i=0; i<gListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
// ########### GOOGLE RESULTS #############
if (gGoogleMatches.length > 0) {
// show header for list
$(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
// determine google results to show
gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
for (i=0; i<gGoogleListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gGoogleMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
} else {
$('.suggest-card.reference').hide();
$('.suggest-card.dummy').hide();
}
// ########### JD DOC RESULTS #############
if (gDocsMatches.length > 0) {
// reset the lists
$(".search_filtered_wrapper.docs li").remove();
// determine google results to show
// NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
// The order must match the reverse order that each section appears as a card in
// the suggestion UI... this may be only for the "develop" grouped items though.
gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
for (i=0; i<gDocsListLength; i++) {
var sugg = gDocsMatches[i];
var $li;
if (sugg.type == "design") {
$li = new_suggestion($(".suggest-card.design ul"));
} else
if (sugg.type == "distribute") {
$li = new_suggestion($(".suggest-card.distribute ul"));
} else
if (sugg.type == "samples") {
$li = new_suggestion($(".suggest-card.develop .child-card.samples"));
} else
if (sugg.type == "training") {
$li = new_suggestion($(".suggest-card.develop .child-card.training"));
} else
if (sugg.type == "about"||"guide"||"tools"||"google") {
$li = new_suggestion($(".suggest-card.develop .child-card.guides"));
} else {
continue;
}
set_item_values_jd(toroot, $li, sugg);
set_item_selected($li, i == gSelectedIndex);
}
// add heading and show or hide card
if ($(".suggest-card.design li").length > 0) {
$(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
$(".suggest-card.design").show(300);
} else {
$('.suggest-card.design').hide(300);
}
if ($(".suggest-card.distribute li").length > 0) {
$(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
$(".suggest-card.distribute").show(300);
} else {
$('.suggest-card.distribute').hide(300);
}
if ($(".child-card.guides li").length > 0) {
$(".child-card.guides").prepend("<li class='header'>Guides:</li>");
$(".child-card.guides li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.training li").length > 0) {
$(".child-card.training").prepend("<li class='header'>Training:</li>");
$(".child-card.training li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.samples li").length > 0) {
$(".child-card.samples").prepend("<li class='header'>Samples:</li>");
$(".child-card.samples li").appendTo(".suggest-card.develop ul");
}
if ($(".suggest-card.develop li").length > 0) {
$(".suggest-card.develop").show(300);
} else {
$('.suggest-card.develop').hide(300);
}
} else {
$('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
}
}
/** Called by the search input's onkeydown and onkeyup events.
* Handles navigation with keyboard arrows, Enter key to invoke search,
* otherwise invokes search suggestions on key-up event.
* @param e The JS event
* @param kd True if the event is key-down
* @param toroot A string for the site's root path
* @returns True if the event should bubble up
*/
function search_changed(e, kd, toroot)
{
var currentLang = getLangPref();
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// get the ul hosting the currently selected item
gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
var $selectedUl = $columns[gSelectedColumn];
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 27 = esc
if (e.keyCode == 27) {
// close all search results
if (kd) $('.search .close').trigger('click');
return true;
}
// 13 = enter
else if (e.keyCode == 13) {
if (gSelectedIndex < 0) {
$('.suggest-card').hide();
if ($("#searchResults").is(":hidden") && (search.value != "")) {
// if results aren't showing (and text not empty), return true to allow search to execute
$('body,html').animate({scrollTop:0}, '500', 'swing');
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
// click the link corresponding to selected item
$("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
return false;
}
}
// If Google results are showing, return true to allow ajax search to execute
else if ($("#searchResults").is(":visible")) {
// Also, if search_results is scrolled out of view, scroll to top to make results visible
if ((sticky ) && (search.value != "")) {
$('body,html').animate({scrollTop:0}, '500', 'swing');
}
return true;
}
// 38 UP ARROW
else if (kd && (e.keyCode == 38)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
gSelectedIndex--;
}
if (gSelectedIndex >= 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex--;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
// If user reaches top, reset selected column
if (gSelectedIndex < 0) {
gSelectedColumn = -1;
}
}
return false;
}
// 40 DOWN ARROW
else if (kd && (e.keyCode == 40)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
gSelectedIndex++;
}
if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex++;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
}
return false;
}
// Consider left/right arrow navigation
// NOTE: Order of suggest columns are reverse order (index position 0 is on right)
else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
// 37 LEFT ARROW
// go left only if current column is not left-most column (last column)
if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn++;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
// 39 RIGHT ARROW
// go right only if current column is not the right-most column (first column)
else if (e.keyCode == 39 && gSelectedColumn > 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn--;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
}
// if key-up event and not arrow down/up/left/right,
// read the search query and add suggestions to gMatches
else if (!kd && (e.keyCode != 40)
&& (e.keyCode != 38)
&& (e.keyCode != 37)
&& (e.keyCode != 39)) {
gSelectedIndex = -1;
gMatches = new Array();
matchedCount = 0;
gGoogleMatches = new Array();
matchedCountGoogle = 0;
gDocsMatches = new Array();
matchedCountDocs = 0;
// Search for Android matches
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_api_results(text, gMatches);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
}
// Search for Google matches
for (var i=0; i<GOOGLE_DATA.length; i++) {
var s = GOOGLE_DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gGoogleMatches[matchedCountGoogle] = s;
matchedCountGoogle++;
}
}
rank_autocomplete_api_results(text, gGoogleMatches);
for (var i=0; i<gGoogleMatches.length; i++) {
var s = gGoogleMatches[i];
}
highlight_autocomplete_result_labels(text);
// Search for matching JD docs
if (text.length >= 2) {
// Regex to match only the beginning of a word
var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
// Search for Training classes
for (var i=0; i<TRAINING_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TRAINING_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Don't consider doc title for lessons (only for class landing pages),
// unless the lesson has a tag that already matches
if ((s.lang == currentLang) &&
(!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
// it matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for API Guides
for (var i=0; i<GUIDE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GUIDE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Tools Guides
for (var i=0; i<TOOLS_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TOOLS_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for About docs
for (var i=0; i<ABOUT_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = ABOUT_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Design guides
for (var i=0; i<DESIGN_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DESIGN_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Distribute guides
for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DISTRIBUTE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Google guides
for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GOOGLE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Samples
for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = SAMPLES_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title.t
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Rank/sort all the matched pages
rank_autocomplete_doc_results(text, gDocsMatches);
}
// draw the suggestions
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
/* Order the jd doc result list based on match quality */
function rank_autocomplete_doc_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
var _resultScoreFn = function(match) {
var score = 1.0;
// if the query matched a tag
if (match.matched_tag > 0) {
// multiply score by factor relative to position in tags list (max of 3)
score *= 3 / match.matched_tag;
// if it also matched the title
if (match.matched_title > 0) {
score *= 2;
}
} else if (match.matched_title > 0) {
score *= 3;
}
return score;
};
for (var i=0; i<matches.length; i++) {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Order the result list based on match quality */
function rank_autocomplete_api_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<matches.length; i++) {
// if the API is deprecated, default score is 0; otherwise, perform scoring
if (matches[i].deprecated == "true") {
matches[i].__resultScore = 0;
} else {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Add emphasis to part of string that matches query */
function highlight_autocomplete_result_labels(query) {
query = query || '';
if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
for (var i=0; i<gGoogleMatches.length; i++) {
gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
$(".suggest-card").hide();
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow', setStickyTop);
return false;
}
function hideResults() {
$("#searchResults").slideUp('fast', setStickyTop);
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
var searchControl;
google.load('search', '1', {"callback" : function() {
searchControl = new google.search.SearchControl();
} });
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// once search results load, set up click listeners
searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
addResultClickListeners();
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow', setStickyTop);
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
/* Adjust the scroll position to account for sticky header, only if the hash matches an id.
This does not handle <a name=""> tags. Some CSS fixes those, but only for reference docs. */
function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
}
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
// If the hash isn't a search query or there's an error in the query,
// then adjust the scroll position to account for sticky header, then exit.
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
offsetScrollForSticky();
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow', setStickyTop);
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
// add analytics tracking events to each result link
function addResultClickListeners() {
$("#searchResults a.gs-title").each(function(index, link) {
// When user clicks enter for Google search results, track it
$(link).click(function() {
ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
});
});
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference") == 0) {
if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
&& !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
&& !(location.pathname.indexOf("/reference/com/google") == 0)) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
writeCookie(API_LEVEL_COOKIE, selectedLevel, null);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher. To reveal, change the target API level "
+ "above the left navigation.");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
}
});
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
/****** NEW version of script to build google and sample navs dynamically ******/
// TODO: update Google reference docs to tolerate this new implementation
var NODE_NAME = 0;
var NODE_HREF = 1;
var NODE_GROUP = 2;
var NODE_TAGS = 3;
var NODE_CHILDREN = 4;
function init_google_navtree2(navtree_id, data)
{
var $containerUl = $("#"+navtree_id);
for (var i in data) {
var node_data = data[i];
$containerUl.append(new_google_node2(node_data));
}
// Make all third-generation list items 'sticky' to prevent them from collapsing
$containerUl.find('li li li.nav-section').addClass('sticky');
initExpandableNavItems("#"+navtree_id);
}
function new_google_node2(node_data)
{
var linkText = node_data[NODE_NAME];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
var $li = $('<li>');
var $a;
if (node_data[NODE_HREF] != null) {
$a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
+ linkText + '</a>');
} else {
$a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
+ linkText + '/</a>');
}
var $childUl = $('<ul>');
if (node_data[NODE_CHILDREN] != null) {
$li.addClass("nav-section");
$a = $('<div class="nav-section-header">').append($a);
if (node_data[NODE_HREF] == null) $a.addClass('empty');
for (var i in node_data[NODE_CHILDREN]) {
var child_node_data = node_data[NODE_CHILDREN][i];
$childUl.append(new_google_node2(child_node_data));
}
$li.append($childUl);
}
$li.prepend($a);
return $li;
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
}
function init_default_google_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function init_default_gcm_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function showSamplesRefTree() {
init_default_samples_navtree(toRoot);
}
function init_default_samples_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
// hack to remove the "about the samples" link then put it back in
// after we nuke the list to remove the dummy static list of samples
var $firstLi = $("#nav.samples-nav > li:first-child").clone();
$("#nav.samples-nav").empty();
$("#nav.samples-nav").append($firstLi);
init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
highlightSidenav();
resizeNav();
if ($("#jd-content #samples").length) {
showSamples();
}
}
});
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
/* On-demand functions */
/** Move sample code line numbers out of PRE block and into non-copyable column */
function initCodeLineNumbers() {
var numbers = $("#codesample-block a.number");
if (numbers.length) {
$("#codesample-line-numbers").removeClass("hidden").append(numbers);
}
$(document).ready(function() {
// select entire line when clicked
$("span.code-line").click(function() {
if (!shifted) {
selectText(this);
}
});
// invoke line link on double click
$(".code-line").dblclick(function() {
document.location.hash = $(this).attr('id');
});
// highlight the line when hovering on the number
$("#codesample-line-numbers a.number").mouseover(function() {
var id = $(this).attr('href');
$(id).css('background','#e7e7e7');
});
$("#codesample-line-numbers a.number").mouseout(function() {
var id = $(this).attr('href');
$(id).css('background','none');
});
});
}
// create SHIFT key binder to avoid the selectText method when selecting multiple lines
var shifted = false;
$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
// courtesy of jasonedelman.com
function selectText(element) {
var doc = document
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
/** Display links and other information about samples that match the
group specified by the URL */
function showSamples() {
var group = $("#samples").attr('class');
$("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
var $ul = $("<ul>");
$selectedLi = $("#nav li.selected");
$selectedLi.children("ul").children("li").each(function() {
var $li = $("<li>").append($(this).find("a").first().clone());
$ul.append($li);
});
$("#samples").append($ul);
}
/* ########################################################## */
/* ################### RESOURCE CARDS ##################### */
/* ########################################################## */
/** Handle resource queries, collections, and grids (sections). Requires
jd_tag_helpers.js and the *_unified_data.js to be loaded. */
(function() {
// Prevent the same resource from being loaded more than once per page.
var addedPageResources = {};
$(document).ready(function() {
$('.resource-widget').each(function() {
initResourceWidget(this);
});
/* Pass the line height to ellipsisfade() to adjust the height of the
text container to show the max number of lines possible, without
showing lines that are cut off. This works with the css ellipsis
classes to fade last text line and apply an ellipsis char. */
//card text currently uses 15px line height.
var lineHeight = 15;
$('.card-info .text').ellipsisfade(lineHeight);
});
/*
Three types of resource layouts:
Flow - Uses a fixed row-height flow using float left style.
Carousel - Single card slideshow all same dimension absolute.
Stack - Uses fixed columns and flexible element height.
*/
function initResourceWidget(widget) {
var $widget = $(widget);
var isFlow = $widget.hasClass('resource-flow-layout'),
isCarousel = $widget.hasClass('resource-carousel-layout'),
isStack = $widget.hasClass('resource-stack-layout');
// find size of widget by pulling out its class name
var sizeCols = 1;
var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
if (m) {
sizeCols = parseInt(m[1], 10);
}
var opts = {
cardSizes: ($widget.data('cardsizes') || '').split(','),
maxResults: parseInt($widget.data('maxresults') || '100', 10),
itemsPerPage: $widget.data('itemsperpage'),
sortOrder: $widget.data('sortorder'),
query: $widget.data('query'),
section: $widget.data('section'),
sizeCols: sizeCols,
/* Added by LFL 6/6/14 */
resourceStyle: $widget.data('resourcestyle') || 'card',
stackSort: $widget.data('stacksort') || 'true'
};
// run the search for the set of resources to show
var resources = buildResourceList(opts);
if (isFlow) {
drawResourcesFlowWidget($widget, opts, resources);
} else if (isCarousel) {
drawResourcesCarouselWidget($widget, opts, resources);
} else if (isStack) {
/* Looks like this got removed and is not used, so repurposing for the
homepage style layout.
Modified by LFL 6/6/14
*/
//var sections = buildSectionList(opts);
opts['numStacks'] = $widget.data('numstacks');
drawResourcesStackWidget($widget, opts, resources/*, sections*/);
}
}
/* Initializes a Resource Carousel Widget */
function drawResourcesCarouselWidget($widget, opts, resources) {
$widget.empty();
var plusone = true; //always show plusone on carousel
$widget.addClass('resource-card slideshow-container')
.append($('<a>').addClass('slideshow-prev').text('Prev'))
.append($('<a>').addClass('slideshow-next').text('Next'));
var css = { 'width': $widget.width() + 'px',
'height': $widget.height() + 'px' };
var $ul = $('<ul>');
for (var i = 0; i < resources.length; ++i) {
var $card = $('<a>')
.attr('href', cleanUrl(resources[i].url))
.decorateResourceCard(resources[i],plusone);
$('<li>').css(css)
.append($card)
.appendTo($ul);
}
$('<div>').addClass('frame')
.append($ul)
.appendTo($widget);
$widget.dacSlideshow({
auto: true,
btnPrev: '.slideshow-prev',
btnNext: '.slideshow-next'
});
};
/* Initializes a Resource Card Stack Widget (column-based layout)
Modified by LFL 6/6/14
*/
function drawResourcesStackWidget($widget, opts, resources, sections) {
// Don't empty widget, grab all items inside since they will be the first
// items stacked, followed by the resource query
var plusone = true; //by default show plusone on section cards
var cards = $widget.find('.resource-card').detach().toArray();
var numStacks = opts.numStacks || 1;
var $stacks = [];
var urlString;
for (var i = 0; i < numStacks; ++i) {
$stacks[i] = $('<div>').addClass('resource-card-stack')
.appendTo($widget);
}
var sectionResources = [];
// Extract any subsections that are actually resource cards
if (sections) {
for (var i = 0; i < sections.length; ++i) {
if (!sections[i].sections || !sections[i].sections.length) {
// Render it as a resource card
sectionResources.push(
$('<a>')
.addClass('resource-card section-card')
.attr('href', cleanUrl(sections[i].resource.url))
.decorateResourceCard(sections[i].resource,plusone)[0]
);
} else {
cards.push(
$('<div>')
.addClass('resource-card section-card-menu')
.decorateResourceSection(sections[i],plusone)[0]
);
}
}
}
cards = cards.concat(sectionResources);
for (var i = 0; i < resources.length; ++i) {
var $card = createResourceElement(resources[i], opts);
if (opts.resourceStyle.indexOf('related') > -1) {
$card.addClass('related-card');
}
cards.push($card[0]);
}
if (opts.stackSort != 'false') {
for (var i = 0; i < cards.length; ++i) {
// Find the stack with the shortest height, but give preference to
// left to right order.
var minHeight = $stacks[0].height();
var minIndex = 0;
for (var j = 1; j < numStacks; ++j) {
var height = $stacks[j].height();
if (height < minHeight - 45) {
minHeight = height;
minIndex = j;
}
}
$stacks[minIndex].append($(cards[i]));
}
}
};
/*
Create a resource card using the given resource object and a list of html
configured options. Returns a jquery object containing the element.
*/
function createResourceElement(resource, opts, plusone) {
var $el;
// The difference here is that generic cards are not entirely clickable
// so its a div instead of an a tag, also the generic one is not given
// the resource-card class so it appears with a transparent background
// and can be styled in whatever way the css setup.
if (opts.resourceStyle == 'generic') {
$el = $('<div>')
.addClass('resource')
.attr('href', cleanUrl(resource.url))
.decorateResource(resource, opts);
} else {
var cls = 'resource resource-card';
$el = $('<a>')
.addClass(cls)
.attr('href', cleanUrl(resource.url))
.decorateResourceCard(resource, plusone);
}
return $el;
}
/* Initializes a flow widget, see distribute.scss for generating accompanying css */
function drawResourcesFlowWidget($widget, opts, resources) {
$widget.empty();
var cardSizes = opts.cardSizes || ['6x6'];
var i = 0, j = 0;
var plusone = true; // by default show plusone on resource cards
while (i < resources.length) {
var cardSize = cardSizes[j++ % cardSizes.length];
cardSize = cardSize.replace(/^\s+|\s+$/,'');
// Some card sizes do not get a plusone button, such as where space is constrained
// or for cards commonly embedded in docs (to improve overall page speed).
plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
(cardSize == "9x2") || (cardSize == "9x3") ||
(cardSize == "12x2") || (cardSize == "12x3"));
// A stack has a third dimension which is the number of stacked items
var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
var stackCount = 0;
var $stackDiv = null;
if (isStack) {
// Create a stack container which should have the dimensions defined
// by the product of the items inside.
$stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+ 'x' + isStack[2] * isStack[3]) .appendTo($widget);
}
// Build each stack item or just a single item
do {
var resource = resources[i];
var $card = createResourceElement(resources[i], opts, plusone);
$card.addClass('resource-card-' + cardSize +
' resource-card-' + resource.type);
if (isStack) {
$card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
if (++stackCount == parseInt(isStack[3])) {
$card.addClass('resource-card-row-stack-last');
stackCount = 0;
}
} else {
stackCount = 0;
}
$card.appendTo($stackDiv || $widget);
} while (++i < resources.length && stackCount > 0);
}
}
/* Build a site map of resources using a section as a root. */
function buildSectionList(opts) {
if (opts.section && SECTION_BY_ID[opts.section]) {
return SECTION_BY_ID[opts.section].sections || [];
}
return [];
}
function buildResourceList(opts) {
var maxResults = opts.maxResults || 100;
var query = opts.query || '';
var expressions = parseResourceQuery(query);
var addedResourceIndices = {};
var results = [];
for (var i = 0; i < expressions.length; i++) {
var clauses = expressions[i];
// build initial set of resources from first clause
var firstClause = clauses[0];
var resources = [];
switch (firstClause.attr) {
case 'type':
resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
break;
case 'lang':
resources = ALL_RESOURCES_BY_LANG[firstClause.value];
break;
case 'tag':
resources = ALL_RESOURCES_BY_TAG[firstClause.value];
break;
case 'collection':
var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
case 'section':
var urls = SITE_MAP[firstClause.value].sections || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
}
// console.log(firstClause.attr + ':' + firstClause.value);
resources = resources || [];
// use additional clauses to filter corpus
if (clauses.length > 1) {
var otherClauses = clauses.slice(1);
resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
}
// filter out resources already added
if (i > 1) {
resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
}
// add to list of already added indices
for (var j = 0; j < resources.length; j++) {
// console.log(resources[j].title);
addedResourceIndices[resources[j].index] = 1;
}
// concat to final results list
results = results.concat(resources);
}
if (opts.sortOrder && results.length) {
var attr = opts.sortOrder;
if (opts.sortOrder == 'random') {
var i = results.length, j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = results[i];
results[i] = results[j];
results[j] = temp;
}
} else {
var desc = attr.charAt(0) == '-';
if (desc) {
attr = attr.substring(1);
}
results = results.sort(function(x,y) {
return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
});
}
}
results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
results = results.slice(0, maxResults);
for (var j = 0; j < results.length; ++j) {
addedPageResources[results[j].index] = 1;
}
return results;
}
function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
return function(resource) {
return !addedResourceIndices[resource.index];
};
}
function getResourceMatchesClausesFilter(clauses) {
return function(resource) {
return doesResourceMatchClauses(resource, clauses);
};
}
function doesResourceMatchClauses(resource, clauses) {
for (var i = 0; i < clauses.length; i++) {
var map;
switch (clauses[i].attr) {
case 'type':
map = IS_RESOURCE_OF_TYPE[clauses[i].value];
break;
case 'lang':
map = IS_RESOURCE_IN_LANG[clauses[i].value];
break;
case 'tag':
map = IS_RESOURCE_TAGGED[clauses[i].value];
break;
}
if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
return clauses[i].negative;
}
}
return true;
}
function cleanUrl(url)
{
if (url && url.indexOf('//') === -1) {
url = toRoot + url;
}
return url;
}
function parseResourceQuery(query) {
// Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
var expressions = [];
var expressionStrs = query.split(',') || [];
for (var i = 0; i < expressionStrs.length; i++) {
var expr = expressionStrs[i] || '';
// Break expression into clauses (clause e.g. 'tag:foo')
var clauses = [];
var clauseStrs = expr.split(/(?=[\+\-])/);
for (var j = 0; j < clauseStrs.length; j++) {
var clauseStr = clauseStrs[j] || '';
// Get attribute and value from clause (e.g. attribute='tag', value='foo')
var parts = clauseStr.split(':');
var clause = {};
clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
if (clause.attr) {
if (clause.attr.charAt(0) == '+') {
clause.attr = clause.attr.substring(1);
} else if (clause.attr.charAt(0) == '-') {
clause.negative = true;
clause.attr = clause.attr.substring(1);
}
}
if (parts.length > 1) {
clause.value = parts[1].replace(/^\s+|\s+$/g,'');
}
clauses.push(clause);
}
if (!clauses.length) {
continue;
}
expressions.push(clauses);
}
return expressions;
}
})();
(function($) {
/*
Utility method for creating dom for the description area of a card.
Used in decorateResourceCard and decorateResource.
*/
function buildResourceCardDescription(resource, plusone) {
var $description = $('<div>').addClass('description ellipsis');
$description.append($('<div>').addClass('text').html(resource.summary));
if (resource.cta) {
$description.append($('<a>').addClass('cta').html(resource.cta));
}
if (plusone) {
var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
"//developer.android.com/" + resource.url;
$description.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', plusurl)));
}
return $description;
}
/* Simple jquery function to create dom for a standard resource card */
$.fn.decorateResourceCard = function(resource,plusone) {
var section = resource.group || resource.type;
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
$('<div>').addClass('card-bg')
.css('background-image', 'url(' + (imgUrl || toRoot +
'assets/images/resource-card-default-android.jpg') + ')')
.appendTo(this);
$('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
.append($('<div>').addClass('section').text(section))
.append($('<div>').addClass('title').html(resource.title))
.append(buildResourceCardDescription(resource, plusone))
.appendTo(this);
return this;
};
/* Simple jquery function to create dom for a resource section card (menu) */
$.fn.decorateResourceSection = function(section,plusone) {
var resource = section.resource;
//keep url clean for matching and offline mode handling
var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
var $base = $('<a>')
.addClass('card-bg')
.attr('href', resource.url)
.append($('<div>').addClass('card-section-icon')
.append($('<div>').addClass('icon'))
.append($('<div>').addClass('section').html(resource.title)))
.appendTo(this);
var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
if (section.sections && section.sections.length) {
// Recurse the section sub-tree to find a resource image.
var stack = [section];
while (stack.length) {
if (stack[0].resource.image) {
$base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
break;
}
if (stack[0].sections) {
stack = stack.concat(stack[0].sections);
}
stack.shift();
}
var $ul = $('<ul>')
.appendTo($cardInfo);
var max = section.sections.length > 3 ? 3 : section.sections.length;
for (var i = 0; i < max; ++i) {
var subResource = section.sections[i];
if (!plusone) {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util'))))
.appendTo($ul);
} else {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', resource.url)))))
.appendTo($ul);
}
}
// Add a more row
if (max < section.sections.length) {
$('<li>')
.append($('<a>').attr('href', resource.url)
.append($('<div>')
.addClass('title')
.text('More')))
.appendTo($ul);
}
} else {
// No sub-resources, just render description?
}
return this;
};
/* Render other types of resource styles that are not cards. */
$.fn.decorateResource = function(resource, opts) {
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
var linkUrl = resource.url;
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
if (linkUrl && linkUrl.indexOf('//') === -1) {
linkUrl = toRoot + linkUrl;
}
$(this).append(
$('<div>').addClass('image')
.css('background-image', 'url(' + imgUrl + ')'),
$('<div>').addClass('info').append(
$('<h4>').addClass('title').html(resource.title),
$('<p>').addClass('summary').html(resource.summary),
$('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
)
);
return this;
};
})(jQuery);
/* Calculate the vertical area remaining */
(function($) {
$.fn.ellipsisfade= function(lineHeight) {
this.each(function() {
// get element text
var $this = $(this);
var remainingHeight = $this.parent().parent().height();
$this.parent().siblings().each(function ()
{
if ($(this).is(":visible")) {
var h = $(this).height();
remainingHeight = remainingHeight - h;
}
});
adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
$this.parent().css({'height': adjustedRemainingHeight});
$this.css({'height': "auto"});
});
return this;
};
}) (jQuery);
/*
Fullscreen Carousel
The following allows for an area at the top of the page that takes over the
entire browser height except for its top offset and an optional bottom
padding specified as a data attribute.
HTML:
<div class="fullscreen-carousel">
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
etc ...
</div>
Control over how the carousel takes over the screen can mostly be defined in
a css file. Setting min-height on the .fullscreen-carousel-content elements
will prevent them from shrinking to far vertically when the browser is very
short, and setting max-height on the .fullscreen-carousel itself will prevent
the area from becoming to long in the case that the browser is stretched very
tall.
There is limited functionality for having multiple sections since that request
was removed, but it is possible to add .next-arrow and .prev-arrow elements to
scroll between multiple content areas.
*/
(function() {
$(document).ready(function() {
$('.fullscreen-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var topOffset = $widget.offset().top;
var padBottom = parseInt($widget.data('paddingbottom')) || 0;
var maxHeight = 0;
var minHeight = 0;
var $content = $widget.find('.fullscreen-carousel-content');
var $nextArrow = $widget.find('.next-arrow');
var $prevArrow = $widget.find('.prev-arrow');
var $curSection = $($content[0]);
if ($content.length <= 1) {
$nextArrow.hide();
$prevArrow.hide();
} else {
$nextArrow.click(function() {
var index = ($content.index($curSection) + 1);
$curSection.hide();
$curSection = $($content[index >= $content.length ? 0 : index]);
$curSection.show();
});
$prevArrow.click(function() {
var index = ($content.index($curSection) - 1);
$curSection.hide();
$curSection = $($content[index < 0 ? $content.length - 1 : 0]);
$curSection.show();
});
}
// Just hide all content sections except first.
$content.each(function(index) {
if ($(this).height() > minHeight) minHeight = $(this).height();
$(this).css({position: 'absolute', display: index > 0 ? 'none' : ''});
});
// Register for changes to window size, and trigger.
$(window).resize(resizeWidget);
resizeWidget();
function resizeWidget() {
var height = $(window).height() - topOffset - padBottom;
$widget.width($(window).width());
$widget.height(height < minHeight ? minHeight :
(maxHeight && height > maxHeight ? maxHeight : height));
}
}
})();
/*
Tab Carousel
The following allows tab widgets to be installed via the html below. Each
tab content section should have a data-tab attribute matching one of the
nav items'. Also each tab content section should have a width matching the
tab carousel.
HTML:
<div class="tab-carousel">
<ul class="tab-nav">
<li><a href="#" data-tab="handsets">Handsets</a>
<li><a href="#" data-tab="wearable">Wearable</a>
<li><a href="#" data-tab="tv">TV</a>
</ul>
<div class="tab-carousel-content">
<div data-tab="handsets">
<!--Full width content here-->
</div>
<div data-tab="wearable">
<!--Full width content here-->
</div>
<div data-tab="tv">
<!--Full width content here-->
</div>
</div>
</div>
*/
(function() {
$(document).ready(function() {
$('.tab-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var $nav = $widget.find('.tab-nav');
var $anchors = $nav.find('[data-tab]');
var $li = $nav.find('li');
var $contentContainer = $widget.find('.tab-carousel-content');
var $tabs = $contentContainer.find('[data-tab]');
var $curTab = $($tabs[0]); // Current tab is first tab.
var width = $widget.width();
// Setup nav interactivity.
$anchors.click(function(evt) {
evt.preventDefault();
var query = '[data-tab=' + $(this).data('tab') + ']';
transitionWidget($tabs.filter(query));
});
// Add highlight for navigation on first item.
var $highlight = $('<div>').addClass('highlight')
.css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
.appendTo($nav);
// Store height since we will change contents to absolute.
$contentContainer.height($contentContainer.height());
// Absolutely position tabs so they're ready for transition.
$tabs.each(function(index) {
$(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
});
function transitionWidget($toTab) {
if (!$curTab.is($toTab)) {
var curIndex = $tabs.index($curTab[0]);
var toIndex = $tabs.index($toTab[0]);
var dir = toIndex > curIndex ? 1 : -1;
// Animate content sections.
$toTab.css({left:(width * dir) + 'px'});
$curTab.animate({left:(width * -dir) + 'px'});
$toTab.animate({left:'0'});
// Animate navigation highlight.
$highlight.animate({left:$($li[toIndex]).position().left + 'px',
width:$($li[toIndex]).outerWidth() + 'px'})
// Store new current section.
$curTab = $toTab;
}
}
}
})();
| JavaScript |
$(document).ready(function() {
// prep nav expandos
var pagePath = document.location.pathname;
if (pagePath.indexOf(SITE_ROOT) == 0) {
pagePath = pagePath.substr(SITE_ROOT.length);
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path should be an absolute URL.
pagePath = SITE_ROOT + pagePath;
}
// select current page in sidenav and set up prev/next links if they exist
var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]');
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
$selListItem.closest('li>ul').addClass('expanded');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
$prevLink = $selListItem.parents('li').find('a');
}
if ($prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
$('.prev-page-link').hide();
} else {
$('.prev-page-link').attr('href', prevHref).show();
}
} else {
$('.prev-page-link').hide();
}
// set up next links
var $nextLink = [];
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul').find('a:eq(0)')
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)');
}
}
if ($nextLink.length) {
$('.next-page-link').attr('href', $nextLink.attr('href')).show();
} else {
$('.next-page-link').hide();
}
}
// Set up expand/collapse behavior
$('.nav-y li').has('ul').click(function() {
if ($(this).hasClass('expanded')) {
return;
}
// hide other
var $old = $('.nav-y li.expanded');
if ($old.length) {
var $oldUl = $old.children('ul');
$oldUl.css('height', $oldUl.height() + 'px');
window.setTimeout(function() {
$oldUl
.addClass('animate-height')
.css('height', '');
}, 0);
$old.removeClass('expanded');
}
// show me
$(this).addClass('expanded');
var $ul = $(this).children('ul');
var expandedHeight = $ul.height();
$ul
.removeClass('animate-height')
.css('height', 0);
window.setTimeout(function() {
$ul
.addClass('animate-height')
.css('height', expandedHeight + 'px');
}, 0);
});
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.text($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
// Set up fixed navbar
var navBarIsFixed = false;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var navBarShouldBeFixed = (scrollTop > (100 - 40));
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
$('#nav')
.addClass('fixed')
.prependTo('#page-container');
} else {
$('#nav')
.removeClass('fixed')
.prependTo('#nav-container');
}
navBarIsFixed = navBarShouldBeFixed;
}
});
}); | JavaScript |
/* API LEVEL TOGGLE */
<?cs if:reference.apilevels ?>
addLoadEvent(changeApiLevel);
<?cs /if ?>
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevel = readCookie(API_LEVEL_COOKIE);
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevel = $("body").attr("class");
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevel = maxLevel;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevel, "body");
} else {
selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
}
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>"
+ "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest "
+ "and be compiled against a version of the library that supports an equal or higher API Level. To reveal this "
+ "document, change the value of the API Level filter above.</p>"
+ "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher");
else obj.removeClass("absent").removeAttr("title");
});
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data(toroot) {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toroot+"navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root) {
toRoot = root;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var BUILD_TIMESTAMP = "";
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
return true;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
return false;
}
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var mPagePath; // initialized in ready() function
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
var GOOGLE_DATA; // combined data for google service apis, used for search suggest
// Ensure that all ajax getScript() requests allow caching
$.ajaxSetup({
cache: true
});
/****** ON LOAD SET UP STUFF *********/
$(document).ready(function() {
// show lang dialog if the URL includes /intl/
//if (location.pathname.substring(0,6) == "/intl/") {
// var lang = location.pathname.split('/')[2];
// if (lang != getLangPref()) {
// $("#langMessage a.yes").attr("onclick","changeLangPref('" + lang
// + "', true); $('#langMessage').hide(); return false;");
// $("#langMessage .lang." + lang).show();
// $("#langMessage").show();
// }
//}
// load json file for JD doc search suggestions
$.getScript(toRoot + 'jd_lists_unified.js');
// load json file for Android API search suggestions
$.getScript(toRoot + 'reference/lists.js');
// load json files for Google services API suggestions
$.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
// once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
if(jqxhr.status === 200) {
$.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
// combine GCM and GMS data
GOOGLE_DATA = GMS_DATA;
var start = GOOGLE_DATA.length;
for (var i=0; i<GCM_DATA.length; i++) {
GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
link:GCM_DATA[i].link, type:GCM_DATA[i].type});
}
}
});
}
});
// setup keyboard listener for search shortcut
$('body').keyup(function(event) {
if (event.which == 191) {
$('#search_autocomplete').focus();
}
});
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2')
.not('#tb h2')
.not('.sidebox h2')
.not('#devdoc-nav h2')
.not('h2.norule').css({marginBottom:0})
.after('<hr/>');
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false);
hideResults();
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
// Need a copy of the pagePath before it gets changed in the next block;
// it's needed to perform proper tab highlighting in offline docs (see rootDir below)
var pagePathOriginal = pagePath;
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
$("#sticky-header").addClass("design");
// highlight About tabs
} else if ($("body").hasClass("about")) {
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "about") {
$("#nav-x li.about a").addClass("selected");
} else if (rootDir == "wear") {
$("#nav-x li.wear a").addClass("selected");
} else if (rootDir == "tv") {
$("#nav-x li.tv a").addClass("selected");
} else if (rootDir == "auto") {
$("#nav-x li.auto a").addClass("selected");
}
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
$("#sticky-header").addClass("develop");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else if ($("body").hasClass("samples")) {
$("#nav-x li.samples a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
$("#sticky-header").addClass("distribute");
var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
if (secondFrag == "users") {
$("#nav-x li.users a").addClass("selected");
} else if (secondFrag == "engage") {
$("#nav-x li.engage a").addClass("selected");
} else if (secondFrag == "monetize") {
$("#nav-x li.monetize a").addClass("selected");
} else if (secondFrag == "tools") {
$("#nav-x li.disttools a").addClass("selected");
} else if (secondFrag == "stories") {
$("#nav-x li.stories a").addClass("selected");
} else if (secondFrag == "essentials") {
$("#nav-x li.essentials a").addClass("selected");
} else if (secondFrag == "googleplay") {
$("#nav-x li.googleplay a").addClass("selected");
}
} else if ($("body").hasClass("about")) {
$("#sticky-header").addClass("about");
}
// set global variable so we can highlight the sidenav a bit later (such as for google reference)
// and highlight the sidenav
mPagePath = pagePath;
highlightSidenav();
buildBreadcrumbs();
// set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if ($nextLink.length == 0) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
if ($nextLink.length == 0) {
// if that doesn't work, we're at the end of the list, so disable NEXT link
$('.next-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
}
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
if ($nextLink.length) {
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide")
.append(": " + $nextLink.html());
$('.next-class-link').find('.new').empty();
}
} else {
$('.next-page-link').attr('href', $nextLink.attr('href'))
.removeClass("hide");
// for the footer link, also add the next page title
$('.content-footer .next-page-link').append(": " + $nextLink.html());
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
// create an array for all the class descriptions
var $classDescriptions = new Array($classLinks.length);
var lang = getLangPref();
$classLinks.each(function(index) {
var langDescr = $(this).attr(lang + "-description");
if (typeof langDescr !== 'undefined' && langDescr !== false) {
// if there's a class description in the selected language, use that
$classDescriptions[index] = langDescr;
} else {
// otherwise, use the default english description
$classDescriptions[index] = $(this).attr("description");
}
});
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
+ ' width="64" height="64" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
+ ' width="64" height="64" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
initExpandableNavItems("#nav");
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (sticky) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
// Resize once loading is finished
resizeNav();
// Check if there's an anchor that we need to scroll into view.
// A delay is needed, because some browsers do not immediately scroll down to the anchor
window.setTimeout(offsetScrollForSticky, 100);
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
/* setup shadowbox for any videos that want it */
var $videoLinks = $("a.video-shadowbox-button, a.notice-developers-video");
if ($videoLinks.length) {
// if there's at least one, add the shadowbox HTML to the body
$('body').prepend(
'<div id="video-container">'+
'<div id="video-frame">'+
'<div class="video-close">'+
'<span id="icon-video-close" onclick="closeVideo()"> </span>'+
'</div>'+
'<div id="youTubePlayer"></div>'+
'</div>'+
'</div>');
// loads the IFrame Player API code asynchronously.
$.getScript("https://www.youtube.com/iframe_api");
$videoLinks.each(function() {
var videoId = $(this).attr('href').split('?v=')[1];
$(this).click(function(event) {
event.preventDefault();
startYouTubePlayer(videoId);
});
});
}
});
// END of the onload event
var youTubePlayer;
function onYouTubeIframeAPIReady() {
}
function startYouTubePlayer(videoId) {
var idAndHash = videoId.split("#");
var startTime = 0;
var lang = getLangPref();
var captionsOn = lang == 'en' ? 0 : 1;
if (idAndHash.length > 1) {
startTime = idAndHash[1].split("t=")[1] != undefined ? idAndHash[1].split("t=")[1] : 0;
}
if (youTubePlayer == null) {
youTubePlayer = new YT.Player('youTubePlayer', {
height: '529',
width: '940',
videoId: idAndHash[0],
playerVars: {start: startTime, hl: lang, cc_load_policy: captionsOn},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} else {
youTubePlayer.playVideo();
}
$("#video-container").fadeIn(200, function(){$("#video-frame").show()});
}
function onPlayerReady(event) {
event.target.playVideo();
// track the start playing event so we know from which page the video was selected
ga('send', 'event', 'Videos', 'Start: ' +
youTubePlayer.getVideoUrl().split('?v=')[1], 'on: ' + document.location.href);
}
function closeVideo() {
try {
youTubePlayer.pauseVideo();
$("#video-container").fadeOut(200);
} catch(e) {
console.log('Video not available');
$("#video-container").fadeOut(200);
}
}
/* Track youtube playback for analytics */
function onPlayerStateChange(event) {
// Video starts, send the video ID
if (event.data == YT.PlayerState.PLAYING) {
ga('send', 'event', 'Videos', 'Play',
youTubePlayer.getVideoUrl().split('?v=')[1]);
}
// Video paused, send video ID and video elapsed time
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Videos', 'Paused',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
// Video finished, send video ID and video elapsed time
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Videos', 'Finished',
youTubePlayer.getVideoUrl().split('?v=')[1], youTubePlayer.getCurrentTime());
}
}
function initExpandableNavItems(rootTag) {
$(rootTag + ' li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me and descendants */
section.find('ul').slideUp(250, function() {
// remove 'expanded' class from my section and any children
section.closest('li').removeClass('expanded');
$('li.nav-section', section).removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
// Stop expand/collapse behavior when clicking on nav section links
// (since we're navigating away from the page)
// This selector captures the first instance of <a>, but not those with "#" as the href.
$('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
}
/** Create the list of breadcrumb links in the sticky header */
function buildBreadcrumbs() {
var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
// Add the secondary horizontal nav item, if provided
var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
if ($selectedSecondNav.length) {
$breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
}
// Add the primary horizontal nav
var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
// If there's no header nav item, use the logo link and title from alt text
if ($selectedFirstNav.length < 1) {
$selectedFirstNav = $("<a>")
.attr('href', $("div#header .logo a").attr('href'))
.text($("div#header .logo img").attr('alt'));
}
$breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
}
/** Highlight the current page in sidenav, expanding children as appropriate */
function highlightSidenav() {
// if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
if ($("ul#nav li.selected").length) {
unHighlightSidenav();
}
// look for URL in sidenav, including the hash
var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
// If the selNavLink is still empty, look for it without the hash
if ($selNavLink.length == 0) {
$selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
}
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
}
}
function unHighlightSidenav() {
$("ul#nav li.selected").removeClass("selected");
$('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
}
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
$(document).ready(function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
});
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header-wrapper').outerHeight();
var headerVisible = scrollTop < stickyTop;
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) {
// If no selected item found, exit
return;
}
// get the selected item's offset from its container nav by measuring the item's offset
// relative to the document then subtract the container nav's offset relative to the document
var selectedOffset = $selected.offset().top - $nav.offset().top;
if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
// if it's more than 80% down the nav
// scroll the item up by an amount equal to 80% the container nav's height
api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
var age = 2*365*24*60*60; // set max-age to 2 years
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; max-age=" + age +"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
var sticky = false;
var stickyTop;
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
/* Sets the vertical scoll position at which the sticky bar should appear.
This method is called to reset the position when search results appear or hide */
function setStickyTop() {
stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
}
/*
* Displays sticky nav bar on pages when dac header scrolls out of view
*/
$(window).scroll(function(event) {
setStickyTop();
var hiding = false;
var $stickyEl = $('#sticky-header');
var $menuEl = $('.menu-container');
// Exit if there's no sidenav
if ($('#side-nav').length == 0) return;
// Exit if the mouse target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
if ($(event.target).nodeName == "DIV") {
return;
}
var top = $(window).scrollTop();
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var shouldBeSticky = top >= stickyTop;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
shouldBeSticky = false;
}
// Account for horizontal scroll
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (sticky && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (sticky == shouldBeSticky) {
return;
}
// If sticky header visible and position is now near top, hide sticky
if (sticky && !shouldBeSticky) {
sticky = false;
hiding = true;
// make the sidenav static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
// delay hide the sticky
$menuEl.removeClass('sticky-menu');
$stickyEl.fadeOut(250);
hiding = false;
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (!sticky && shouldBeSticky) {
sticky = true;
$stickyEl.fadeIn(10);
$menuEl.addClass('sticky-menu');
// make the sidenav fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (hiding && top < 15) {
$menuEl.removeClass('sticky-menu');
$stickyEl.hide();
hiding = false;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
/*
* Manages secion card states and nav resize to conclude loading
*/
(function() {
$(document).ready(function() {
// Stack hover states
$('.section-card-menu').each(function(index, el) {
var height = $(el).height();
$(el).css({height:height+'px', position:'relative'});
var $cardInfo = $(el).find('.card-info');
$cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
});
});
})();
/* MISC LIBRARY FUNCTIONS */
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function hideNestedItems(list, toggle) {
$list = $(list);
// hide nested lists
if($list.hasClass('showing')) {
$("li ol", $list).hide('fast');
$list.removeClass('showing');
// show nested lists
} else {
$("li ol", $list).show('fast');
$list.addClass('showing');
}
$(".more,.less",$(toggle)).toggle();
}
/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
function setupIdeDocToggle() {
$( "select.ide" ).change(function() {
var selected = $(this).find("option:selected").attr("value");
$(".select-ide").hide();
$(".select-ide."+selected).show();
$("select.ide").val(selected);
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
writeCookie("nav", nav_pref, "reference");
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
writeCookie("pref_lang", lang, null);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj).closest(".toggle-content");
var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("open").addClass("closed");
div.find(".toggle-content").removeClass("open").addClass("closed")
.find(".toggle-content-toggleme").hide();
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
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);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
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);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1; // the index position of currently highlighted suggestion
var gSelectedColumn = -1; // which column of suggestion lists is currently focused
var gMatches = new Array();
var gLastText = "";
var gInitialized = false;
var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
var gListLength = 0;
var gGoogleMatches = new Array();
var ROW_COUNT_GOOGLE = 15; // max number of results in list
var gGoogleListLength = 0;
var gDocsMatches = new Array();
var ROW_COUNT_DOCS = 100; // max number of results in list
var gDocsListLength = 0;
function onSuggestionClick(link) {
// When user clicks a suggested document, track it
ga('send', 'event', 'Suggestion Click', 'clicked: ' + $(link).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
}
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function set_item_values_jd(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.title);
$link.attr('href',toroot + match.url);
}
function new_suggestion($list) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('.search_filtered_wrapper li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
});
$li.append("<a onclick='onSuggestionClick(this)'></a>");
$li.attr('class','show-item');
return $li;
}
function sync_selection_table(toroot)
{
var $li; //list item jquery object
var i; //list item iterator
// if there are NO results at all, hide all columns
if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
$('.suggest-card').hide(300);
return;
}
// if there are api results
if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
// reveal suggestion list
$('.suggest-card.dummy').show();
$('.suggest-card.reference').show();
var listIndex = 0; // list index position
// reset the lists
$(".search_filtered_wrapper.reference li").remove();
// ########### ANDROID RESULTS #############
if (gMatches.length > 0) {
// determine android results to show
gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
gMatches.length : ROW_COUNT_FRAMEWORK;
for (i=0; i<gListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
// ########### GOOGLE RESULTS #############
if (gGoogleMatches.length > 0) {
// show header for list
$(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
// determine google results to show
gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
for (i=0; i<gGoogleListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gGoogleMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
} else {
$('.suggest-card.reference').hide();
$('.suggest-card.dummy').hide();
}
// ########### JD DOC RESULTS #############
if (gDocsMatches.length > 0) {
// reset the lists
$(".search_filtered_wrapper.docs li").remove();
// determine google results to show
// NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
// The order must match the reverse order that each section appears as a card in
// the suggestion UI... this may be only for the "develop" grouped items though.
gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
for (i=0; i<gDocsListLength; i++) {
var sugg = gDocsMatches[i];
var $li;
if (sugg.type == "design") {
$li = new_suggestion($(".suggest-card.design ul"));
} else
if (sugg.type == "distribute") {
$li = new_suggestion($(".suggest-card.distribute ul"));
} else
if (sugg.type == "samples") {
$li = new_suggestion($(".suggest-card.develop .child-card.samples"));
} else
if (sugg.type == "training") {
$li = new_suggestion($(".suggest-card.develop .child-card.training"));
} else
if (sugg.type == "about"||"guide"||"tools"||"google") {
$li = new_suggestion($(".suggest-card.develop .child-card.guides"));
} else {
continue;
}
set_item_values_jd(toroot, $li, sugg);
set_item_selected($li, i == gSelectedIndex);
}
// add heading and show or hide card
if ($(".suggest-card.design li").length > 0) {
$(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
$(".suggest-card.design").show(300);
} else {
$('.suggest-card.design').hide(300);
}
if ($(".suggest-card.distribute li").length > 0) {
$(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
$(".suggest-card.distribute").show(300);
} else {
$('.suggest-card.distribute').hide(300);
}
if ($(".child-card.guides li").length > 0) {
$(".child-card.guides").prepend("<li class='header'>Guides:</li>");
$(".child-card.guides li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.training li").length > 0) {
$(".child-card.training").prepend("<li class='header'>Training:</li>");
$(".child-card.training li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.samples li").length > 0) {
$(".child-card.samples").prepend("<li class='header'>Samples:</li>");
$(".child-card.samples li").appendTo(".suggest-card.develop ul");
}
if ($(".suggest-card.develop li").length > 0) {
$(".suggest-card.develop").show(300);
} else {
$('.suggest-card.develop').hide(300);
}
} else {
$('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
}
}
/** Called by the search input's onkeydown and onkeyup events.
* Handles navigation with keyboard arrows, Enter key to invoke search,
* otherwise invokes search suggestions on key-up event.
* @param e The JS event
* @param kd True if the event is key-down
* @param toroot A string for the site's root path
* @returns True if the event should bubble up
*/
function search_changed(e, kd, toroot)
{
var currentLang = getLangPref();
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// get the ul hosting the currently selected item
gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
var $selectedUl = $columns[gSelectedColumn];
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 27 = esc
if (e.keyCode == 27) {
// close all search results
if (kd) $('.search .close').trigger('click');
return true;
}
// 13 = enter
else if (e.keyCode == 13) {
if (gSelectedIndex < 0) {
$('.suggest-card').hide();
if ($("#searchResults").is(":hidden") && (search.value != "")) {
// if results aren't showing (and text not empty), return true to allow search to execute
$('body,html').animate({scrollTop:0}, '500', 'swing');
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
// click the link corresponding to selected item
$("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
return false;
}
}
// If Google results are showing, return true to allow ajax search to execute
else if ($("#searchResults").is(":visible")) {
// Also, if search_results is scrolled out of view, scroll to top to make results visible
if ((sticky ) && (search.value != "")) {
$('body,html').animate({scrollTop:0}, '500', 'swing');
}
return true;
}
// 38 UP ARROW
else if (kd && (e.keyCode == 38)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
gSelectedIndex--;
}
if (gSelectedIndex >= 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex--;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
// If user reaches top, reset selected column
if (gSelectedIndex < 0) {
gSelectedColumn = -1;
}
}
return false;
}
// 40 DOWN ARROW
else if (kd && (e.keyCode == 40)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
gSelectedIndex++;
}
if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex++;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
}
return false;
}
// Consider left/right arrow navigation
// NOTE: Order of suggest columns are reverse order (index position 0 is on right)
else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
// 37 LEFT ARROW
// go left only if current column is not left-most column (last column)
if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn++;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
// 39 RIGHT ARROW
// go right only if current column is not the right-most column (first column)
else if (e.keyCode == 39 && gSelectedColumn > 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn--;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
}
// if key-up event and not arrow down/up/left/right,
// read the search query and add suggestions to gMatches
else if (!kd && (e.keyCode != 40)
&& (e.keyCode != 38)
&& (e.keyCode != 37)
&& (e.keyCode != 39)) {
gSelectedIndex = -1;
gMatches = new Array();
matchedCount = 0;
gGoogleMatches = new Array();
matchedCountGoogle = 0;
gDocsMatches = new Array();
matchedCountDocs = 0;
// Search for Android matches
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_api_results(text, gMatches);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
}
// Search for Google matches
for (var i=0; i<GOOGLE_DATA.length; i++) {
var s = GOOGLE_DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gGoogleMatches[matchedCountGoogle] = s;
matchedCountGoogle++;
}
}
rank_autocomplete_api_results(text, gGoogleMatches);
for (var i=0; i<gGoogleMatches.length; i++) {
var s = gGoogleMatches[i];
}
highlight_autocomplete_result_labels(text);
// Search for matching JD docs
if (text.length >= 2) {
// Regex to match only the beginning of a word
var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
// Search for Training classes
for (var i=0; i<TRAINING_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TRAINING_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Don't consider doc title for lessons (only for class landing pages),
// unless the lesson has a tag that already matches
if ((s.lang == currentLang) &&
(!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
// it matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for API Guides
for (var i=0; i<GUIDE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GUIDE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Tools Guides
for (var i=0; i<TOOLS_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TOOLS_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for About docs
for (var i=0; i<ABOUT_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = ABOUT_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Design guides
for (var i=0; i<DESIGN_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DESIGN_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Distribute guides
for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DISTRIBUTE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Google guides
for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GOOGLE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Samples
for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = SAMPLES_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title.t
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Rank/sort all the matched pages
rank_autocomplete_doc_results(text, gDocsMatches);
}
// draw the suggestions
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
/* Order the jd doc result list based on match quality */
function rank_autocomplete_doc_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
var _resultScoreFn = function(match) {
var score = 1.0;
// if the query matched a tag
if (match.matched_tag > 0) {
// multiply score by factor relative to position in tags list (max of 3)
score *= 3 / match.matched_tag;
// if it also matched the title
if (match.matched_title > 0) {
score *= 2;
}
} else if (match.matched_title > 0) {
score *= 3;
}
return score;
};
for (var i=0; i<matches.length; i++) {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Order the result list based on match quality */
function rank_autocomplete_api_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<matches.length; i++) {
// if the API is deprecated, default score is 0; otherwise, perform scoring
if (matches[i].deprecated == "true") {
matches[i].__resultScore = 0;
} else {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Add emphasis to part of string that matches query */
function highlight_autocomplete_result_labels(query) {
query = query || '';
if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
for (var i=0; i<gGoogleMatches.length; i++) {
gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
$(".suggest-card").hide();
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow', setStickyTop);
return false;
}
function hideResults() {
$("#searchResults").slideUp('fast', setStickyTop);
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
var searchControl;
google.load('search', '1', {"callback" : function() {
searchControl = new google.search.SearchControl();
} });
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// once search results load, set up click listeners
searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
addResultClickListeners();
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow', setStickyTop);
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
/* Adjust the scroll position to account for sticky header, only if the hash matches an id.
This does not handle <a name=""> tags. Some CSS fixes those, but only for reference docs. */
function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
}
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
// If the hash isn't a search query or there's an error in the query,
// then adjust the scroll position to account for sticky header, then exit.
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
offsetScrollForSticky();
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow', setStickyTop);
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
// add analytics tracking events to each result link
function addResultClickListeners() {
$("#searchResults a.gs-title").each(function(index, link) {
// When user clicks enter for Google search results, track it
$(link).click(function() {
ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
});
});
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference") == 0) {
if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
&& !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
&& !(location.pathname.indexOf("/reference/com/google") == 0)) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
writeCookie(API_LEVEL_COOKIE, selectedLevel, null);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher. To reveal, change the target API level "
+ "above the left navigation.");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
}
});
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
/****** NEW version of script to build google and sample navs dynamically ******/
// TODO: update Google reference docs to tolerate this new implementation
var NODE_NAME = 0;
var NODE_HREF = 1;
var NODE_GROUP = 2;
var NODE_TAGS = 3;
var NODE_CHILDREN = 4;
function init_google_navtree2(navtree_id, data)
{
var $containerUl = $("#"+navtree_id);
for (var i in data) {
var node_data = data[i];
$containerUl.append(new_google_node2(node_data));
}
// Make all third-generation list items 'sticky' to prevent them from collapsing
$containerUl.find('li li li.nav-section').addClass('sticky');
initExpandableNavItems("#"+navtree_id);
}
function new_google_node2(node_data)
{
var linkText = node_data[NODE_NAME];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
var $li = $('<li>');
var $a;
if (node_data[NODE_HREF] != null) {
$a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
+ linkText + '</a>');
} else {
$a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
+ linkText + '/</a>');
}
var $childUl = $('<ul>');
if (node_data[NODE_CHILDREN] != null) {
$li.addClass("nav-section");
$a = $('<div class="nav-section-header">').append($a);
if (node_data[NODE_HREF] == null) $a.addClass('empty');
for (var i in node_data[NODE_CHILDREN]) {
var child_node_data = node_data[NODE_CHILDREN][i];
$childUl.append(new_google_node2(child_node_data));
}
$li.append($childUl);
}
$li.prepend($a);
return $li;
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
}
function init_default_google_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function init_default_gcm_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function showSamplesRefTree() {
init_default_samples_navtree(toRoot);
}
function init_default_samples_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
// hack to remove the "about the samples" link then put it back in
// after we nuke the list to remove the dummy static list of samples
var $firstLi = $("#nav.samples-nav > li:first-child").clone();
$("#nav.samples-nav").empty();
$("#nav.samples-nav").append($firstLi);
init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
highlightSidenav();
resizeNav();
if ($("#jd-content #samples").length) {
showSamples();
}
}
});
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
/* On-demand functions */
/** Move sample code line numbers out of PRE block and into non-copyable column */
function initCodeLineNumbers() {
var numbers = $("#codesample-block a.number");
if (numbers.length) {
$("#codesample-line-numbers").removeClass("hidden").append(numbers);
}
$(document).ready(function() {
// select entire line when clicked
$("span.code-line").click(function() {
if (!shifted) {
selectText(this);
}
});
// invoke line link on double click
$(".code-line").dblclick(function() {
document.location.hash = $(this).attr('id');
});
// highlight the line when hovering on the number
$("#codesample-line-numbers a.number").mouseover(function() {
var id = $(this).attr('href');
$(id).css('background','#e7e7e7');
});
$("#codesample-line-numbers a.number").mouseout(function() {
var id = $(this).attr('href');
$(id).css('background','none');
});
});
}
// create SHIFT key binder to avoid the selectText method when selecting multiple lines
var shifted = false;
$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
// courtesy of jasonedelman.com
function selectText(element) {
var doc = document
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
/** Display links and other information about samples that match the
group specified by the URL */
function showSamples() {
var group = $("#samples").attr('class');
$("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
var $ul = $("<ul>");
$selectedLi = $("#nav li.selected");
$selectedLi.children("ul").children("li").each(function() {
var $li = $("<li>").append($(this).find("a").first().clone());
$ul.append($li);
});
$("#samples").append($ul);
}
/* ########################################################## */
/* ################### RESOURCE CARDS ##################### */
/* ########################################################## */
/** Handle resource queries, collections, and grids (sections). Requires
jd_tag_helpers.js and the *_unified_data.js to be loaded. */
(function() {
// Prevent the same resource from being loaded more than once per page.
var addedPageResources = {};
$(document).ready(function() {
$('.resource-widget').each(function() {
initResourceWidget(this);
});
/* Pass the line height to ellipsisfade() to adjust the height of the
text container to show the max number of lines possible, without
showing lines that are cut off. This works with the css ellipsis
classes to fade last text line and apply an ellipsis char. */
//card text currently uses 15px line height.
var lineHeight = 15;
$('.card-info .text').ellipsisfade(lineHeight);
});
/*
Three types of resource layouts:
Flow - Uses a fixed row-height flow using float left style.
Carousel - Single card slideshow all same dimension absolute.
Stack - Uses fixed columns and flexible element height.
*/
function initResourceWidget(widget) {
var $widget = $(widget);
var isFlow = $widget.hasClass('resource-flow-layout'),
isCarousel = $widget.hasClass('resource-carousel-layout'),
isStack = $widget.hasClass('resource-stack-layout');
// find size of widget by pulling out its class name
var sizeCols = 1;
var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
if (m) {
sizeCols = parseInt(m[1], 10);
}
var opts = {
cardSizes: ($widget.data('cardsizes') || '').split(','),
maxResults: parseInt($widget.data('maxresults') || '100', 10),
itemsPerPage: $widget.data('itemsperpage'),
sortOrder: $widget.data('sortorder'),
query: $widget.data('query'),
section: $widget.data('section'),
sizeCols: sizeCols,
/* Added by LFL 6/6/14 */
resourceStyle: $widget.data('resourcestyle') || 'card',
stackSort: $widget.data('stacksort') || 'true'
};
// run the search for the set of resources to show
var resources = buildResourceList(opts);
if (isFlow) {
drawResourcesFlowWidget($widget, opts, resources);
} else if (isCarousel) {
drawResourcesCarouselWidget($widget, opts, resources);
} else if (isStack) {
/* Looks like this got removed and is not used, so repurposing for the
homepage style layout.
Modified by LFL 6/6/14
*/
//var sections = buildSectionList(opts);
opts['numStacks'] = $widget.data('numstacks');
drawResourcesStackWidget($widget, opts, resources/*, sections*/);
}
}
/* Initializes a Resource Carousel Widget */
function drawResourcesCarouselWidget($widget, opts, resources) {
$widget.empty();
var plusone = true; //always show plusone on carousel
$widget.addClass('resource-card slideshow-container')
.append($('<a>').addClass('slideshow-prev').text('Prev'))
.append($('<a>').addClass('slideshow-next').text('Next'));
var css = { 'width': $widget.width() + 'px',
'height': $widget.height() + 'px' };
var $ul = $('<ul>');
for (var i = 0; i < resources.length; ++i) {
var $card = $('<a>')
.attr('href', cleanUrl(resources[i].url))
.decorateResourceCard(resources[i],plusone);
$('<li>').css(css)
.append($card)
.appendTo($ul);
}
$('<div>').addClass('frame')
.append($ul)
.appendTo($widget);
$widget.dacSlideshow({
auto: true,
btnPrev: '.slideshow-prev',
btnNext: '.slideshow-next'
});
};
/* Initializes a Resource Card Stack Widget (column-based layout)
Modified by LFL 6/6/14
*/
function drawResourcesStackWidget($widget, opts, resources, sections) {
// Don't empty widget, grab all items inside since they will be the first
// items stacked, followed by the resource query
var plusone = true; //by default show plusone on section cards
var cards = $widget.find('.resource-card').detach().toArray();
var numStacks = opts.numStacks || 1;
var $stacks = [];
var urlString;
for (var i = 0; i < numStacks; ++i) {
$stacks[i] = $('<div>').addClass('resource-card-stack')
.appendTo($widget);
}
var sectionResources = [];
// Extract any subsections that are actually resource cards
if (sections) {
for (var i = 0; i < sections.length; ++i) {
if (!sections[i].sections || !sections[i].sections.length) {
// Render it as a resource card
sectionResources.push(
$('<a>')
.addClass('resource-card section-card')
.attr('href', cleanUrl(sections[i].resource.url))
.decorateResourceCard(sections[i].resource,plusone)[0]
);
} else {
cards.push(
$('<div>')
.addClass('resource-card section-card-menu')
.decorateResourceSection(sections[i],plusone)[0]
);
}
}
}
cards = cards.concat(sectionResources);
for (var i = 0; i < resources.length; ++i) {
var $card = createResourceElement(resources[i], opts);
if (opts.resourceStyle.indexOf('related') > -1) {
$card.addClass('related-card');
}
cards.push($card[0]);
}
if (opts.stackSort != 'false') {
for (var i = 0; i < cards.length; ++i) {
// Find the stack with the shortest height, but give preference to
// left to right order.
var minHeight = $stacks[0].height();
var minIndex = 0;
for (var j = 1; j < numStacks; ++j) {
var height = $stacks[j].height();
if (height < minHeight - 45) {
minHeight = height;
minIndex = j;
}
}
$stacks[minIndex].append($(cards[i]));
}
}
};
/*
Create a resource card using the given resource object and a list of html
configured options. Returns a jquery object containing the element.
*/
function createResourceElement(resource, opts, plusone) {
var $el;
// The difference here is that generic cards are not entirely clickable
// so its a div instead of an a tag, also the generic one is not given
// the resource-card class so it appears with a transparent background
// and can be styled in whatever way the css setup.
if (opts.resourceStyle == 'generic') {
$el = $('<div>')
.addClass('resource')
.attr('href', cleanUrl(resource.url))
.decorateResource(resource, opts);
} else {
var cls = 'resource resource-card';
$el = $('<a>')
.addClass(cls)
.attr('href', cleanUrl(resource.url))
.decorateResourceCard(resource, plusone);
}
return $el;
}
/* Initializes a flow widget, see distribute.scss for generating accompanying css */
function drawResourcesFlowWidget($widget, opts, resources) {
$widget.empty();
var cardSizes = opts.cardSizes || ['6x6'];
var i = 0, j = 0;
var plusone = true; // by default show plusone on resource cards
while (i < resources.length) {
var cardSize = cardSizes[j++ % cardSizes.length];
cardSize = cardSize.replace(/^\s+|\s+$/,'');
// Some card sizes do not get a plusone button, such as where space is constrained
// or for cards commonly embedded in docs (to improve overall page speed).
plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
(cardSize == "9x2") || (cardSize == "9x3") ||
(cardSize == "12x2") || (cardSize == "12x3"));
// A stack has a third dimension which is the number of stacked items
var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
var stackCount = 0;
var $stackDiv = null;
if (isStack) {
// Create a stack container which should have the dimensions defined
// by the product of the items inside.
$stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+ 'x' + isStack[2] * isStack[3]) .appendTo($widget);
}
// Build each stack item or just a single item
do {
var resource = resources[i];
var $card = createResourceElement(resources[i], opts, plusone);
$card.addClass('resource-card-' + cardSize +
' resource-card-' + resource.type);
if (isStack) {
$card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
if (++stackCount == parseInt(isStack[3])) {
$card.addClass('resource-card-row-stack-last');
stackCount = 0;
}
} else {
stackCount = 0;
}
$card.appendTo($stackDiv || $widget);
} while (++i < resources.length && stackCount > 0);
}
}
/* Build a site map of resources using a section as a root. */
function buildSectionList(opts) {
if (opts.section && SECTION_BY_ID[opts.section]) {
return SECTION_BY_ID[opts.section].sections || [];
}
return [];
}
function buildResourceList(opts) {
var maxResults = opts.maxResults || 100;
var query = opts.query || '';
var expressions = parseResourceQuery(query);
var addedResourceIndices = {};
var results = [];
for (var i = 0; i < expressions.length; i++) {
var clauses = expressions[i];
// build initial set of resources from first clause
var firstClause = clauses[0];
var resources = [];
switch (firstClause.attr) {
case 'type':
resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
break;
case 'lang':
resources = ALL_RESOURCES_BY_LANG[firstClause.value];
break;
case 'tag':
resources = ALL_RESOURCES_BY_TAG[firstClause.value];
break;
case 'collection':
var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
case 'section':
var urls = SITE_MAP[firstClause.value].sections || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
}
// console.log(firstClause.attr + ':' + firstClause.value);
resources = resources || [];
// use additional clauses to filter corpus
if (clauses.length > 1) {
var otherClauses = clauses.slice(1);
resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
}
// filter out resources already added
if (i > 1) {
resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
}
// add to list of already added indices
for (var j = 0; j < resources.length; j++) {
// console.log(resources[j].title);
addedResourceIndices[resources[j].index] = 1;
}
// concat to final results list
results = results.concat(resources);
}
if (opts.sortOrder && results.length) {
var attr = opts.sortOrder;
if (opts.sortOrder == 'random') {
var i = results.length, j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = results[i];
results[i] = results[j];
results[j] = temp;
}
} else {
var desc = attr.charAt(0) == '-';
if (desc) {
attr = attr.substring(1);
}
results = results.sort(function(x,y) {
return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
});
}
}
results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
results = results.slice(0, maxResults);
for (var j = 0; j < results.length; ++j) {
addedPageResources[results[j].index] = 1;
}
return results;
}
function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
return function(resource) {
return !addedResourceIndices[resource.index];
};
}
function getResourceMatchesClausesFilter(clauses) {
return function(resource) {
return doesResourceMatchClauses(resource, clauses);
};
}
function doesResourceMatchClauses(resource, clauses) {
for (var i = 0; i < clauses.length; i++) {
var map;
switch (clauses[i].attr) {
case 'type':
map = IS_RESOURCE_OF_TYPE[clauses[i].value];
break;
case 'lang':
map = IS_RESOURCE_IN_LANG[clauses[i].value];
break;
case 'tag':
map = IS_RESOURCE_TAGGED[clauses[i].value];
break;
}
if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
return clauses[i].negative;
}
}
return true;
}
function cleanUrl(url)
{
if (url && url.indexOf('//') === -1) {
url = toRoot + url;
}
return url;
}
function parseResourceQuery(query) {
// Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
var expressions = [];
var expressionStrs = query.split(',') || [];
for (var i = 0; i < expressionStrs.length; i++) {
var expr = expressionStrs[i] || '';
// Break expression into clauses (clause e.g. 'tag:foo')
var clauses = [];
var clauseStrs = expr.split(/(?=[\+\-])/);
for (var j = 0; j < clauseStrs.length; j++) {
var clauseStr = clauseStrs[j] || '';
// Get attribute and value from clause (e.g. attribute='tag', value='foo')
var parts = clauseStr.split(':');
var clause = {};
clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
if (clause.attr) {
if (clause.attr.charAt(0) == '+') {
clause.attr = clause.attr.substring(1);
} else if (clause.attr.charAt(0) == '-') {
clause.negative = true;
clause.attr = clause.attr.substring(1);
}
}
if (parts.length > 1) {
clause.value = parts[1].replace(/^\s+|\s+$/g,'');
}
clauses.push(clause);
}
if (!clauses.length) {
continue;
}
expressions.push(clauses);
}
return expressions;
}
})();
(function($) {
/*
Utility method for creating dom for the description area of a card.
Used in decorateResourceCard and decorateResource.
*/
function buildResourceCardDescription(resource, plusone) {
var $description = $('<div>').addClass('description ellipsis');
$description.append($('<div>').addClass('text').html(resource.summary));
if (resource.cta) {
$description.append($('<a>').addClass('cta').html(resource.cta));
}
if (plusone) {
var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
"//developer.android.com/" + resource.url;
$description.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', plusurl)));
}
return $description;
}
/* Simple jquery function to create dom for a standard resource card */
$.fn.decorateResourceCard = function(resource,plusone) {
var section = resource.group || resource.type;
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
$('<div>').addClass('card-bg')
.css('background-image', 'url(' + (imgUrl || toRoot +
'assets/images/resource-card-default-android.jpg') + ')')
.appendTo(this);
$('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
.append($('<div>').addClass('section').text(section))
.append($('<div>').addClass('title').html(resource.title))
.append(buildResourceCardDescription(resource, plusone))
.appendTo(this);
return this;
};
/* Simple jquery function to create dom for a resource section card (menu) */
$.fn.decorateResourceSection = function(section,plusone) {
var resource = section.resource;
//keep url clean for matching and offline mode handling
var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
var $base = $('<a>')
.addClass('card-bg')
.attr('href', resource.url)
.append($('<div>').addClass('card-section-icon')
.append($('<div>').addClass('icon'))
.append($('<div>').addClass('section').html(resource.title)))
.appendTo(this);
var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
if (section.sections && section.sections.length) {
// Recurse the section sub-tree to find a resource image.
var stack = [section];
while (stack.length) {
if (stack[0].resource.image) {
$base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
break;
}
if (stack[0].sections) {
stack = stack.concat(stack[0].sections);
}
stack.shift();
}
var $ul = $('<ul>')
.appendTo($cardInfo);
var max = section.sections.length > 3 ? 3 : section.sections.length;
for (var i = 0; i < max; ++i) {
var subResource = section.sections[i];
if (!plusone) {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util'))))
.appendTo($ul);
} else {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', resource.url)))))
.appendTo($ul);
}
}
// Add a more row
if (max < section.sections.length) {
$('<li>')
.append($('<a>').attr('href', resource.url)
.append($('<div>')
.addClass('title')
.text('More')))
.appendTo($ul);
}
} else {
// No sub-resources, just render description?
}
return this;
};
/* Render other types of resource styles that are not cards. */
$.fn.decorateResource = function(resource, opts) {
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
var linkUrl = resource.url;
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
if (linkUrl && linkUrl.indexOf('//') === -1) {
linkUrl = toRoot + linkUrl;
}
$(this).append(
$('<div>').addClass('image')
.css('background-image', 'url(' + imgUrl + ')'),
$('<div>').addClass('info').append(
$('<h4>').addClass('title').html(resource.title),
$('<p>').addClass('summary').html(resource.summary),
$('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
)
);
return this;
};
})(jQuery);
/* Calculate the vertical area remaining */
(function($) {
$.fn.ellipsisfade= function(lineHeight) {
this.each(function() {
// get element text
var $this = $(this);
var remainingHeight = $this.parent().parent().height();
$this.parent().siblings().each(function ()
{
if ($(this).is(":visible")) {
var h = $(this).height();
remainingHeight = remainingHeight - h;
}
});
adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
$this.parent().css({'height': adjustedRemainingHeight});
$this.css({'height': "auto"});
});
return this;
};
}) (jQuery);
/*
Fullscreen Carousel
The following allows for an area at the top of the page that takes over the
entire browser height except for its top offset and an optional bottom
padding specified as a data attribute.
HTML:
<div class="fullscreen-carousel">
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
etc ...
</div>
Control over how the carousel takes over the screen can mostly be defined in
a css file. Setting min-height on the .fullscreen-carousel-content elements
will prevent them from shrinking to far vertically when the browser is very
short, and setting max-height on the .fullscreen-carousel itself will prevent
the area from becoming to long in the case that the browser is stretched very
tall.
There is limited functionality for having multiple sections since that request
was removed, but it is possible to add .next-arrow and .prev-arrow elements to
scroll between multiple content areas.
*/
(function() {
$(document).ready(function() {
$('.fullscreen-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var topOffset = $widget.offset().top;
var padBottom = parseInt($widget.data('paddingbottom')) || 0;
var maxHeight = 0;
var minHeight = 0;
var $content = $widget.find('.fullscreen-carousel-content');
var $nextArrow = $widget.find('.next-arrow');
var $prevArrow = $widget.find('.prev-arrow');
var $curSection = $($content[0]);
if ($content.length <= 1) {
$nextArrow.hide();
$prevArrow.hide();
} else {
$nextArrow.click(function() {
var index = ($content.index($curSection) + 1);
$curSection.hide();
$curSection = $($content[index >= $content.length ? 0 : index]);
$curSection.show();
});
$prevArrow.click(function() {
var index = ($content.index($curSection) - 1);
$curSection.hide();
$curSection = $($content[index < 0 ? $content.length - 1 : 0]);
$curSection.show();
});
}
// Just hide all content sections except first.
$content.each(function(index) {
if ($(this).height() > minHeight) minHeight = $(this).height();
$(this).css({position: 'absolute', display: index > 0 ? 'none' : ''});
});
// Register for changes to window size, and trigger.
$(window).resize(resizeWidget);
resizeWidget();
function resizeWidget() {
var height = $(window).height() - topOffset - padBottom;
$widget.width($(window).width());
$widget.height(height < minHeight ? minHeight :
(maxHeight && height > maxHeight ? maxHeight : height));
}
}
})();
/*
Tab Carousel
The following allows tab widgets to be installed via the html below. Each
tab content section should have a data-tab attribute matching one of the
nav items'. Also each tab content section should have a width matching the
tab carousel.
HTML:
<div class="tab-carousel">
<ul class="tab-nav">
<li><a href="#" data-tab="handsets">Handsets</a>
<li><a href="#" data-tab="wearable">Wearable</a>
<li><a href="#" data-tab="tv">TV</a>
</ul>
<div class="tab-carousel-content">
<div data-tab="handsets">
<!--Full width content here-->
</div>
<div data-tab="wearable">
<!--Full width content here-->
</div>
<div data-tab="tv">
<!--Full width content here-->
</div>
</div>
</div>
*/
(function() {
$(document).ready(function() {
$('.tab-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var $nav = $widget.find('.tab-nav');
var $anchors = $nav.find('[data-tab]');
var $li = $nav.find('li');
var $contentContainer = $widget.find('.tab-carousel-content');
var $tabs = $contentContainer.find('[data-tab]');
var $curTab = $($tabs[0]); // Current tab is first tab.
var width = $widget.width();
// Setup nav interactivity.
$anchors.click(function(evt) {
evt.preventDefault();
var query = '[data-tab=' + $(this).data('tab') + ']';
transitionWidget($tabs.filter(query));
});
// Add highlight for navigation on first item.
var $highlight = $('<div>').addClass('highlight')
.css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
.appendTo($nav);
// Store height since we will change contents to absolute.
$contentContainer.height($contentContainer.height());
// Absolutely position tabs so they're ready for transition.
$tabs.each(function(index) {
$(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
});
function transitionWidget($toTab) {
if (!$curTab.is($toTab)) {
var curIndex = $tabs.index($curTab[0]);
var toIndex = $tabs.index($toTab[0]);
var dir = toIndex > curIndex ? 1 : -1;
// Animate content sections.
$toTab.css({left:(width * dir) + 'px'});
$curTab.animate({left:(width * -dir) + 'px'});
$toTab.animate({left:'0'});
// Animate navigation highlight.
$highlight.animate({left:$($li[toIndex]).position().left + 'px',
width:$($li[toIndex]).outerWidth() + 'px'})
// Store new current section.
$curTab = $toTab;
}
}
}
})();
| JavaScript |
$(document).ready(function() {
// prep nav expandos
var pagePath = document.location.pathname;
if (pagePath.indexOf(SITE_ROOT) == 0) {
pagePath = pagePath.substr(SITE_ROOT.length);
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path should be an absolute URL.
pagePath = SITE_ROOT + pagePath;
}
// select current page in sidenav and set up prev/next links if they exist
var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]');
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
$selListItem.closest('li>ul').addClass('expanded');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
$prevLink = $selListItem.parents('li').find('a');
}
if ($prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
$('.prev-page-link').hide();
} else {
$('.prev-page-link').attr('href', prevHref).show();
}
} else {
$('.prev-page-link').hide();
}
// set up next links
var $nextLink = [];
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul').find('a:eq(0)')
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)');
}
}
if ($nextLink.length) {
$('.next-page-link').attr('href', $nextLink.attr('href')).show();
} else {
$('.next-page-link').hide();
}
}
// Set up expand/collapse behavior
$('.nav-y li').has('ul').click(function() {
if ($(this).hasClass('expanded')) {
return;
}
// hide other
var $old = $('.nav-y li.expanded');
if ($old.length) {
var $oldUl = $old.children('ul');
$oldUl.css('height', $oldUl.height() + 'px');
window.setTimeout(function() {
$oldUl
.addClass('animate-height')
.css('height', '');
}, 0);
$old.removeClass('expanded');
}
// show me
$(this).addClass('expanded');
var $ul = $(this).children('ul');
var expandedHeight = $ul.height();
$ul
.removeClass('animate-height')
.css('height', 0);
window.setTimeout(function() {
$ul
.addClass('animate-height')
.css('height', expandedHeight + 'px');
}, 0);
});
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.text($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
// Set up fixed navbar
var navBarIsFixed = false;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var navBarShouldBeFixed = (scrollTop > (100 - 40));
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
$('#nav')
.addClass('fixed')
.prependTo('#page-container');
} else {
$('#nav')
.removeClass('fixed')
.prependTo('#nav-container');
}
navBarIsFixed = navBarShouldBeFixed;
}
});
}); | JavaScript |
/* API LEVEL TOGGLE */
<?cs if:reference.apilevels ?>
addLoadEvent(changeApiLevel);
<?cs /if ?>
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevel = readCookie(API_LEVEL_COOKIE);
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevel = $("body").attr("class");
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevel = maxLevel;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevel, "body");
} else {
selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
}
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>"
+ "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest "
+ "and be compiled against a version of the library that supports an equal or higher API Level. To reveal this "
+ "document, change the value of the API Level filter above.</p>"
+ "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher");
else obj.removeClass("absent").removeAttr("title");
});
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data(toroot) {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toroot+"navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root) {
toRoot = root;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var BUILD_TIMESTAMP = "";
| JavaScript |
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
var DEFAULT_TEXT = "search developer docs";
function set_row_selected(row, selected)
{
var c1 = row.cells[0];
// var c2 = row.cells[1];
if (selected) {
c1.className = "jd-autocomplete jd-selected";
// c2.className = "jd-autocomplete jd-selected jd-linktype";
} else {
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
}
}
function set_row_values(toroot, row, match)
{
var link = row.cells[0].childNodes[0];
link.innerHTML = match.__hilabel || match.label;
link.href = toroot + match.link
// row.cells[1].innerHTML = match.type;
}
function sync_selection_table(toroot)
{
var filtered = document.getElementById("search_filtered");
var r; //TR DOM object
var i; //TR iterator
gSelectedID = -1;
filtered.onmouseover = function() {
if(gSelectedIndex >= 0) {
set_row_selected(this.rows[gSelectedIndex], false);
gSelectedIndex = -1;
}
}
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
// var c2 = r.insertCell(-1);
c1.className = "jd-autocomplete";
// c2.className = "jd-autocomplete jd-linktype";
var link = document.createElement("a");
c1.onmousedown = function() {
window.location = this.firstChild.getAttribute("href");
}
c1.onmouseover = function() {
this.className = this.className + " jd-selected";
}
c1.onmouseout = function() {
this.className = "jd-autocomplete";
}
c1.appendChild(link);
}
/* var r = filtered.insertRow(-1);
var c1 = r.insertCell(-1);
c1.className = "jd-autocomplete jd-linktype";
c1.colSpan = 2; */
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
document.getElementById("search_filtered_div").className = "showing";
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
r = filtered.rows[i];
r.className = "show-row";
set_row_values(toroot, r, gMatches[i]);
set_row_selected(r, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
r = filtered.rows[i];
r.className = "no-display";
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
r = filtered.rows[ROW_COUNT];
r.className = "show-row";
c1 = r.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
filtered.rows[ROW_COUNT].className = "hide-row";
}*/
//if we have no results, hide the table
} else {
document.getElementById("search_filtered_div").className = "no-display";
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// 13 = enter
if (e.keyCode == 13) {
document.getElementById("search_filtered_div").className = "no-display";
if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
} else if (gSelectedIndex < 0) {
return true;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
gSelectedIndex--;
}
sync_selection_table(toroot);
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
gSelectedIndex++;
}
sync_selection_table(toroot);
return false;
}
else if (!kd) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (focused) {
if(obj.value == DEFAULT_TEXT){
obj.value = "";
obj.style.color="#000000";
}
} else {
if(obj.value == ""){
obj.value = DEFAULT_TEXT;
obj.style.color="#aaaaaa";
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
document.location = toRoot + 'search.html#q=' + query + '&t=0';
return false;
}
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var mPagePath; // initialized in ready() function
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
var GOOGLE_DATA; // combined data for google service apis, used for search suggest
// Ensure that all ajax getScript() requests allow caching
$.ajaxSetup({
cache: true
});
/****** ON LOAD SET UP STUFF *********/
$(document).ready(function() {
// show lang dialog if the URL includes /intl/
//if (location.pathname.substring(0,6) == "/intl/") {
// var lang = location.pathname.split('/')[2];
// if (lang != getLangPref()) {
// $("#langMessage a.yes").attr("onclick","changeLangPref('" + lang
// + "', true); $('#langMessage').hide(); return false;");
// $("#langMessage .lang." + lang).show();
// $("#langMessage").show();
// }
//}
// load json file for JD doc search suggestions
$.getScript(toRoot + 'jd_lists_unified.js');
// load json file for Android API search suggestions
$.getScript(toRoot + 'reference/lists.js');
// load json files for Google services API suggestions
$.getScript(toRoot + 'reference/gcm_lists.js', function(data, textStatus, jqxhr) {
// once the GCM json (GCM_DATA) is loaded, load the GMS json (GMS_DATA) and merge the data
if(jqxhr.status === 200) {
$.getScript(toRoot + 'reference/gms_lists.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
// combine GCM and GMS data
GOOGLE_DATA = GMS_DATA;
var start = GOOGLE_DATA.length;
for (var i=0; i<GCM_DATA.length; i++) {
GOOGLE_DATA.push({id:start+i, label:GCM_DATA[i].label,
link:GCM_DATA[i].link, type:GCM_DATA[i].type});
}
}
});
}
});
// setup keyboard listener for search shortcut
$('body').keyup(function(event) {
if (event.which == 191) {
$('#search_autocomplete').focus();
}
});
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2')
.not('#tb h2')
.not('.sidebox h2')
.not('#devdoc-nav h2')
.not('h2.norule').css({marginBottom:0})
.after('<hr/>');
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false);
hideResults();
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
// Need a copy of the pagePath before it gets changed in the next block;
// it's needed to perform proper tab highlighting in offline docs (see rootDir below)
var pagePathOriginal = pagePath;
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
$("#sticky-header").addClass("design");
// highlight About tabs
} else if ($("body").hasClass("about")) {
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "about") {
$("#nav-x li.about a").addClass("selected");
} else if (rootDir == "wear") {
$("#nav-x li.wear a").addClass("selected");
} else if (rootDir == "tv") {
$("#nav-x li.tv a").addClass("selected");
} else if (rootDir == "auto") {
$("#nav-x li.auto a").addClass("selected");
}
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
$("#sticky-header").addClass("develop");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePathOriginal.substring(1,pagePathOriginal.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else if ($("body").hasClass("samples")) {
$("#nav-x li.samples a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
$("#sticky-header").addClass("distribute");
var baseFrag = pagePathOriginal.indexOf('/', 1) + 1;
var secondFrag = pagePathOriginal.substring(baseFrag, pagePathOriginal.indexOf('/', baseFrag));
if (secondFrag == "users") {
$("#nav-x li.users a").addClass("selected");
} else if (secondFrag == "engage") {
$("#nav-x li.engage a").addClass("selected");
} else if (secondFrag == "monetize") {
$("#nav-x li.monetize a").addClass("selected");
} else if (secondFrag == "analyze") {
$("#nav-x li.analyze a").addClass("selected");
} else if (secondFrag == "tools") {
$("#nav-x li.disttools a").addClass("selected");
} else if (secondFrag == "stories") {
$("#nav-x li.stories a").addClass("selected");
} else if (secondFrag == "essentials") {
$("#nav-x li.essentials a").addClass("selected");
} else if (secondFrag == "googleplay") {
$("#nav-x li.googleplay a").addClass("selected");
}
} else if ($("body").hasClass("about")) {
$("#sticky-header").addClass("about");
}
// set global variable so we can highlight the sidenav a bit later (such as for google reference)
// and highlight the sidenav
mPagePath = pagePath;
highlightSidenav();
buildBreadcrumbs();
// set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section') || crossBoundaries) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section') && $selListItem.children('div.empty').length == 0) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if ($nextLink.length == 0) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
if ($nextLink.length == 0) {
// if that doesn't work, we're at the end of the list, so disable NEXT link
$('.next-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
}
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
// and completely hide the one in the footer
$('.content-footer .next-page-link').hide();
if ($nextLink.length) {
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide")
.append(": " + $nextLink.html());
$('.next-class-link').find('.new').empty();
}
} else {
$('.next-page-link').attr('href', $nextLink.attr('href'))
.removeClass("hide");
// for the footer link, also add the next page title
$('.content-footer .next-page-link').append(": " + $nextLink.html());
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
// create an array for all the class descriptions
var $classDescriptions = new Array($classLinks.length);
var lang = getLangPref();
$classLinks.each(function(index) {
var langDescr = $(this).attr(lang + "-description");
if (typeof langDescr !== 'undefined' && langDescr !== false) {
// if there's a class description in the selected language, use that
$classDescriptions[index] = langDescr;
} else {
// otherwise, use the default english description
$classDescriptions[index] = $(this).attr("description");
}
});
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $classDescriptions[index] + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" '
+ ' width="64" height="64" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" '
+ ' width="64" height="64" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
initExpandableNavItems("#nav");
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (sticky) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
// Resize once loading is finished
resizeNav();
// Check if there's an anchor that we need to scroll into view.
// A delay is needed, because some browsers do not immediately scroll down to the anchor
window.setTimeout(offsetScrollForSticky, 100);
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
/* setup shadowbox for any videos that want it */
var $videoLinks = $("a.video-shadowbox-button, a.notice-developers-video");
if ($videoLinks.length) {
// if there's at least one, add the shadowbox HTML to the body
$('body').prepend(
'<div id="video-container">'+
'<div id="video-frame">'+
'<div class="video-close">'+
'<span id="icon-video-close" onclick="closeVideo()"> </span>'+
'</div>'+
'<div id="youTubePlayer"></div>'+
'</div>'+
'</div>');
// loads the IFrame Player API code asynchronously.
$.getScript("https://www.youtube.com/iframe_api");
$videoLinks.each(function() {
var videoId = $(this).attr('href').split('?v=')[1];
$(this).click(function(event) {
event.preventDefault();
startYouTubePlayer(videoId);
});
});
}
});
// END of the onload event
var youTubePlayer;
function onYouTubeIframeAPIReady() {
}
/* Returns the height the shadowbox video should be. It's based on the current
height of the "video-frame" element, which is 100% height for the window.
Then minus the margin so the video isn't actually the full window height. */
function getVideoHeight() {
var frameHeight = $("#video-frame").height();
var marginTop = $("#video-frame").css('margin-top').split('px')[0];
return frameHeight - (marginTop * 2);
}
var mPlayerPaused = false;
function startYouTubePlayer(videoId) {
$("#video-container").show();
$("#video-frame").show();
mPlayerPaused = false;
// compute the size of the player so it's centered in window
var maxWidth = 940; // the width of the web site content
var videoAspect = .5625; // based on 1280x720 resolution
var maxHeight = maxWidth * videoAspect;
var videoHeight = getVideoHeight();
var videoWidth = videoHeight / videoAspect;
if (videoWidth > maxWidth) {
videoWidth = maxWidth;
videoHeight = maxHeight;
}
$("#video-frame").css('width', videoWidth);
// check if we've already created this player
if (youTubePlayer == null) {
// check if there's a start time specified
var idAndHash = videoId.split("#");
var startTime = 0;
if (idAndHash.length > 1) {
startTime = idAndHash[1].split("t=")[1] != undefined ? idAndHash[1].split("t=")[1] : 0;
}
// enable localized player
var lang = getLangPref();
var captionsOn = lang == 'en' ? 0 : 1;
youTubePlayer = new YT.Player('youTubePlayer', {
height: videoHeight,
width: videoWidth,
videoId: idAndHash[0],
playerVars: {start: startTime, hl: lang, cc_load_policy: captionsOn},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
} else {
// reset the size in case the user adjusted the window since last play
youTubePlayer.setSize(videoWidth, videoHeight);
// if a video different from the one already playing was requested, cue it up
if (videoId != youTubePlayer.getVideoUrl().split('?v=')[1].split('&')[0].split('%')[0]) {
youTubePlayer.cueVideoById(videoId);
}
youTubePlayer.playVideo();
}
}
function onPlayerReady(event) {
event.target.playVideo();
mPlayerPaused = false;
}
function closeVideo() {
try {
youTubePlayer.pauseVideo();
} catch(e) {
}
$("#video-container").fadeOut(200);
}
/* Track youtube playback for analytics */
function onPlayerStateChange(event) {
// Video starts, send the video ID
if (event.data == YT.PlayerState.PLAYING) {
if (mPlayerPaused) {
ga('send', 'event', 'Videos', 'Resume',
youTubePlayer.getVideoUrl().split('?v=')[1].split('&')[0].split('%')[0]);
} else {
// track the start playing event so we know from which page the video was selected
ga('send', 'event', 'Videos', 'Start: ' +
youTubePlayer.getVideoUrl().split('?v=')[1].split('&')[0].split('%')[0],
'on: ' + document.location.href);
}
mPlayerPaused = false;
}
// Video paused, send video ID and video elapsed time
if (event.data == YT.PlayerState.PAUSED) {
ga('send', 'event', 'Videos', 'Paused',
youTubePlayer.getVideoUrl().split('?v=')[1].split('&')[0].split('%')[0],
youTubePlayer.getCurrentTime());
mPlayerPaused = true;
}
// Video finished, send video ID and video elapsed time
if (event.data == YT.PlayerState.ENDED) {
ga('send', 'event', 'Videos', 'Finished',
youTubePlayer.getVideoUrl().split('?v=')[1].split('&')[0].split('%')[0],
youTubePlayer.getCurrentTime());
mPlayerPaused = true;
}
}
function initExpandableNavItems(rootTag) {
$(rootTag + ' li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me and descendants */
section.find('ul').slideUp(250, function() {
// remove 'expanded' class from my section and any children
section.closest('li').removeClass('expanded');
$('li.nav-section', section).removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul')).not('.sticky');
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
// Stop expand/collapse behavior when clicking on nav section links
// (since we're navigating away from the page)
// This selector captures the first instance of <a>, but not those with "#" as the href.
$('.nav-section-header').find('a:eq(0)').not('a[href="#"]').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
}
/** Create the list of breadcrumb links in the sticky header */
function buildBreadcrumbs() {
var $breadcrumbUl = $("#sticky-header ul.breadcrumb");
// Add the secondary horizontal nav item, if provided
var $selectedSecondNav = $("div#nav-x ul.nav-x a.selected").clone().removeClass("selected");
if ($selectedSecondNav.length) {
$breadcrumbUl.prepend($("<li>").append($selectedSecondNav))
}
// Add the primary horizontal nav
var $selectedFirstNav = $("div#header-wrap ul.nav-x a.selected").clone().removeClass("selected");
// If there's no header nav item, use the logo link and title from alt text
if ($selectedFirstNav.length < 1) {
$selectedFirstNav = $("<a>")
.attr('href', $("div#header .logo a").attr('href'))
.text($("div#header .logo img").attr('alt'));
}
$breadcrumbUl.prepend($("<li>").append($selectedFirstNav));
}
/** Highlight the current page in sidenav, expanding children as appropriate */
function highlightSidenav() {
// if something is already highlighted, undo it. This is for dynamic navigation (Samples index)
if ($("ul#nav li.selected").length) {
unHighlightSidenav();
}
// look for URL in sidenav, including the hash
var $selNavLink = $('#nav').find('a[href="' + mPagePath + location.hash + '"]');
// If the selNavLink is still empty, look for it without the hash
if ($selNavLink.length == 0) {
$selNavLink = $('#nav').find('a[href="' + mPagePath + '"]');
}
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
}
}
function unHighlightSidenav() {
$("ul#nav li.selected").removeClass("selected");
$('ul#nav li.nav-section.expanded').removeClass('expanded').children('ul').hide();
}
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
$(document).ready(function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
});
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header-wrapper').outerHeight();
var headerVisible = scrollTop < stickyTop;
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) {
// If no selected item found, exit
return;
}
// get the selected item's offset from its container nav by measuring the item's offset
// relative to the document then subtract the container nav's offset relative to the document
var selectedOffset = $selected.offset().top - $nav.offset().top;
if (selectedOffset > $nav.height() * .8) { // multiply nav height by .8 so we move up the item
// if it's more than 80% down the nav
// scroll the item up by an amount equal to 80% the container nav's height
api.scrollTo(0, selectedOffset - ($nav.height() * .8), false);
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
var age = 2*365*24*60*60; // set max-age to 2 years
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; max-age=" + age +"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
var sticky = false;
var stickyTop;
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
/* Sets the vertical scoll position at which the sticky bar should appear.
This method is called to reset the position when search results appear or hide */
function setStickyTop() {
stickyTop = $('#header-wrapper').outerHeight() - $('#sticky-header').outerHeight();
}
/*
* Displays sticky nav bar on pages when dac header scrolls out of view
*/
$(window).scroll(function(event) {
setStickyTop();
var hiding = false;
var $stickyEl = $('#sticky-header');
var $menuEl = $('.menu-container');
// Exit if there's no sidenav
if ($('#side-nav').length == 0) return;
// Exit if the mouse target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
if ($(event.target).nodeName == "DIV") {
return;
}
var top = $(window).scrollTop();
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var shouldBeSticky = top >= stickyTop;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
shouldBeSticky = false;
}
// Account for horizontal scroll
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (sticky && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (sticky == shouldBeSticky) {
return;
}
// If sticky header visible and position is now near top, hide sticky
if (sticky && !shouldBeSticky) {
sticky = false;
hiding = true;
// make the sidenav static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
// delay hide the sticky
$menuEl.removeClass('sticky-menu');
$stickyEl.fadeOut(250);
hiding = false;
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (!sticky && shouldBeSticky) {
sticky = true;
$stickyEl.fadeIn(10);
$menuEl.addClass('sticky-menu');
// make the sidenav fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else if (hiding && top < 15) {
$menuEl.removeClass('sticky-menu');
$stickyEl.hide();
hiding = false;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
/*
* Manages secion card states and nav resize to conclude loading
*/
(function() {
$(document).ready(function() {
// Stack hover states
$('.section-card-menu').each(function(index, el) {
var height = $(el).height();
$(el).css({height:height+'px', position:'relative'});
var $cardInfo = $(el).find('.card-info');
$cardInfo.css({position: 'absolute', bottom:'0px', left:'0px', right:'0px', overflow:'visible'});
});
});
})();
/* MISC LIBRARY FUNCTIONS */
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function hideNestedItems(list, toggle) {
$list = $(list);
// hide nested lists
if($list.hasClass('showing')) {
$("li ol", $list).hide('fast');
$list.removeClass('showing');
// show nested lists
} else {
$("li ol", $list).show('fast');
$list.addClass('showing');
}
$(".more,.less",$(toggle)).toggle();
}
/* Call this to add listeners to a <select> element for Studio/Eclipse/Other docs */
function setupIdeDocToggle() {
$( "select.ide" ).change(function() {
var selected = $(this).find("option:selected").attr("value");
$(".select-ide").hide();
$(".select-ide."+selected).show();
$("select.ide").val(selected);
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
writeCookie("nav", nav_pref, "reference");
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
writeCookie("pref_lang", lang, null);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj).closest(".toggle-content");
var toggleMe = $(".toggle-content-toggleme:eq(0)",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img:eq(0)", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text:eq(0)", obj).toggle();
div.removeClass("open").addClass("closed");
div.find(".toggle-content").removeClass("open").addClass("closed")
.find(".toggle-content-toggleme").hide();
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
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);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
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);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1; // the index position of currently highlighted suggestion
var gSelectedColumn = -1; // which column of suggestion lists is currently focused
var gMatches = new Array();
var gLastText = "";
var gInitialized = false;
var ROW_COUNT_FRAMEWORK = 20; // max number of results in list
var gListLength = 0;
var gGoogleMatches = new Array();
var ROW_COUNT_GOOGLE = 15; // max number of results in list
var gGoogleListLength = 0;
var gDocsMatches = new Array();
var ROW_COUNT_DOCS = 100; // max number of results in list
var gDocsListLength = 0;
function onSuggestionClick(link) {
// When user clicks a suggested document, track it
ga('send', 'event', 'Suggestion Click', 'clicked: ' + $(link).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
}
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function set_item_values_jd(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.title);
$link.attr('href',toroot + match.url);
}
function new_suggestion($list) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('.search_filtered_wrapper li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedColumn = $(".search_filtered:visible").index($(this).closest('.search_filtered'));
gSelectedIndex = $("li", $(".search_filtered:visible")[gSelectedColumn]).index(this);
});
$li.append("<a onclick='onSuggestionClick(this)'></a>");
$li.attr('class','show-item');
return $li;
}
function sync_selection_table(toroot)
{
var $li; //list item jquery object
var i; //list item iterator
// if there are NO results at all, hide all columns
if (!(gMatches.length > 0) && !(gGoogleMatches.length > 0) && !(gDocsMatches.length > 0)) {
$('.suggest-card').hide(300);
return;
}
// if there are api results
if ((gMatches.length > 0) || (gGoogleMatches.length > 0)) {
// reveal suggestion list
$('.suggest-card.dummy').show();
$('.suggest-card.reference').show();
var listIndex = 0; // list index position
// reset the lists
$(".search_filtered_wrapper.reference li").remove();
// ########### ANDROID RESULTS #############
if (gMatches.length > 0) {
// determine android results to show
gListLength = gMatches.length < ROW_COUNT_FRAMEWORK ?
gMatches.length : ROW_COUNT_FRAMEWORK;
for (i=0; i<gListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
// ########### GOOGLE RESULTS #############
if (gGoogleMatches.length > 0) {
// show header for list
$(".suggest-card.reference ul").append("<li class='header'>in Google Services:</li>");
// determine google results to show
gGoogleListLength = gGoogleMatches.length < ROW_COUNT_GOOGLE ? gGoogleMatches.length : ROW_COUNT_GOOGLE;
for (i=0; i<gGoogleListLength; i++) {
var $li = new_suggestion($(".suggest-card.reference ul"));
set_item_values(toroot, $li, gGoogleMatches[i]);
set_item_selected($li, i == gSelectedIndex);
}
}
} else {
$('.suggest-card.reference').hide();
$('.suggest-card.dummy').hide();
}
// ########### JD DOC RESULTS #############
if (gDocsMatches.length > 0) {
// reset the lists
$(".search_filtered_wrapper.docs li").remove();
// determine google results to show
// NOTE: The order of the conditions below for the sugg.type MUST BE SPECIFIC:
// The order must match the reverse order that each section appears as a card in
// the suggestion UI... this may be only for the "develop" grouped items though.
gDocsListLength = gDocsMatches.length < ROW_COUNT_DOCS ? gDocsMatches.length : ROW_COUNT_DOCS;
for (i=0; i<gDocsListLength; i++) {
var sugg = gDocsMatches[i];
var $li;
if (sugg.type == "design") {
$li = new_suggestion($(".suggest-card.design ul"));
} else
if (sugg.type == "distribute") {
$li = new_suggestion($(".suggest-card.distribute ul"));
} else
if (sugg.type == "samples") {
$li = new_suggestion($(".suggest-card.develop .child-card.samples"));
} else
if (sugg.type == "training") {
$li = new_suggestion($(".suggest-card.develop .child-card.training"));
} else
if (sugg.type == "about"||"guide"||"tools"||"google") {
$li = new_suggestion($(".suggest-card.develop .child-card.guides"));
} else {
continue;
}
set_item_values_jd(toroot, $li, sugg);
set_item_selected($li, i == gSelectedIndex);
}
// add heading and show or hide card
if ($(".suggest-card.design li").length > 0) {
$(".suggest-card.design ul").prepend("<li class='header'>Design:</li>");
$(".suggest-card.design").show(300);
} else {
$('.suggest-card.design').hide(300);
}
if ($(".suggest-card.distribute li").length > 0) {
$(".suggest-card.distribute ul").prepend("<li class='header'>Distribute:</li>");
$(".suggest-card.distribute").show(300);
} else {
$('.suggest-card.distribute').hide(300);
}
if ($(".child-card.guides li").length > 0) {
$(".child-card.guides").prepend("<li class='header'>Guides:</li>");
$(".child-card.guides li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.training li").length > 0) {
$(".child-card.training").prepend("<li class='header'>Training:</li>");
$(".child-card.training li").appendTo(".suggest-card.develop ul");
}
if ($(".child-card.samples li").length > 0) {
$(".child-card.samples").prepend("<li class='header'>Samples:</li>");
$(".child-card.samples li").appendTo(".suggest-card.develop ul");
}
if ($(".suggest-card.develop li").length > 0) {
$(".suggest-card.develop").show(300);
} else {
$('.suggest-card.develop').hide(300);
}
} else {
$('.search_filtered_wrapper.docs .suggest-card:not(.dummy)').hide(300);
}
}
/** Called by the search input's onkeydown and onkeyup events.
* Handles navigation with keyboard arrows, Enter key to invoke search,
* otherwise invokes search suggestions on key-up event.
* @param e The JS event
* @param kd True if the event is key-down
* @param toroot A string for the site's root path
* @returns True if the event should bubble up
*/
function search_changed(e, kd, toroot)
{
var currentLang = getLangPref();
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// get the ul hosting the currently selected item
gSelectedColumn = gSelectedColumn >= 0 ? gSelectedColumn : 0;
var $columns = $(".search_filtered_wrapper").find(".search_filtered:visible");
var $selectedUl = $columns[gSelectedColumn];
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 27 = esc
if (e.keyCode == 27) {
// close all search results
if (kd) $('.search .close').trigger('click');
return true;
}
// 13 = enter
else if (e.keyCode == 13) {
if (gSelectedIndex < 0) {
$('.suggest-card').hide();
if ($("#searchResults").is(":hidden") && (search.value != "")) {
// if results aren't showing (and text not empty), return true to allow search to execute
$('body,html').animate({scrollTop:0}, '500', 'swing');
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
// click the link corresponding to selected item
$("a",$("li",$selectedUl)[gSelectedIndex]).get()[0].click();
return false;
}
}
// If Google results are showing, return true to allow ajax search to execute
else if ($("#searchResults").is(":visible")) {
// Also, if search_results is scrolled out of view, scroll to top to make results visible
if ((sticky ) && (search.value != "")) {
$('body,html').animate({scrollTop:0}, '500', 'swing');
}
return true;
}
// 38 UP ARROW
else if (kd && (e.keyCode == 38)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex-1]).hasClass("header")) {
gSelectedIndex--;
}
if (gSelectedIndex >= 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex--;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
// If user reaches top, reset selected column
if (gSelectedIndex < 0) {
gSelectedColumn = -1;
}
}
return false;
}
// 40 DOWN ARROW
else if (kd && (e.keyCode == 40)) {
// if the next item is a header, skip it
if ($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header")) {
gSelectedIndex++;
}
if ((gSelectedIndex < $("li", $selectedUl).length-1) ||
($($("li", $selectedUl)[gSelectedIndex+1]).hasClass("header"))) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedIndex++;
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
}
return false;
}
// Consider left/right arrow navigation
// NOTE: Order of suggest columns are reverse order (index position 0 is on right)
else if (kd && $columns.length > 1 && gSelectedColumn >= 0) {
// 37 LEFT ARROW
// go left only if current column is not left-most column (last column)
if (e.keyCode == 37 && gSelectedColumn < $columns.length - 1) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn++;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
// 39 RIGHT ARROW
// go right only if current column is not the right-most column (first column)
else if (e.keyCode == 39 && gSelectedColumn > 0) {
$('li', $selectedUl).removeClass('jd-selected');
gSelectedColumn--;
$selectedUl = $columns[gSelectedColumn];
// keep or reset the selected item to last item as appropriate
gSelectedIndex = gSelectedIndex >
$("li", $selectedUl).length-1 ?
$("li", $selectedUl).length-1 : gSelectedIndex;
// if the corresponding item is a header, move down
if ($($("li", $selectedUl)[gSelectedIndex]).hasClass("header")) {
gSelectedIndex++;
}
// set item selected
$('li:nth-child('+(gSelectedIndex+1)+')', $selectedUl).addClass('jd-selected');
return false;
}
}
// if key-up event and not arrow down/up/left/right,
// read the search query and add suggestions to gMatches
else if (!kd && (e.keyCode != 40)
&& (e.keyCode != 38)
&& (e.keyCode != 37)
&& (e.keyCode != 39)) {
gSelectedIndex = -1;
gMatches = new Array();
matchedCount = 0;
gGoogleMatches = new Array();
matchedCountGoogle = 0;
gDocsMatches = new Array();
matchedCountDocs = 0;
// Search for Android matches
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_api_results(text, gMatches);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
}
// Search for Google matches
for (var i=0; i<GOOGLE_DATA.length; i++) {
var s = GOOGLE_DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gGoogleMatches[matchedCountGoogle] = s;
matchedCountGoogle++;
}
}
rank_autocomplete_api_results(text, gGoogleMatches);
for (var i=0; i<gGoogleMatches.length; i++) {
var s = gGoogleMatches[i];
}
highlight_autocomplete_result_labels(text);
// Search for matching JD docs
if (text.length >= 2) {
// Regex to match only the beginning of a word
var textRegex = new RegExp("\\b" + text.toLowerCase(), "g");
// Search for Training classes
for (var i=0; i<TRAINING_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TRAINING_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Don't consider doc title for lessons (only for class landing pages),
// unless the lesson has a tag that already matches
if ((s.lang == currentLang) &&
(!(s.type == "training" && s.url.indexOf("index.html") == -1) || matched)) {
// it matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for API Guides
for (var i=0; i<GUIDE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GUIDE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Tools Guides
for (var i=0; i<TOOLS_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = TOOLS_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for About docs
for (var i=0; i<ABOUT_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = ABOUT_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Design guides
for (var i=0; i<DESIGN_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DESIGN_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Distribute guides
for (var i=0; i<DISTRIBUTE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = DISTRIBUTE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Google guides
for (var i=0; i<GOOGLE_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = GOOGLE_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Search for Samples
for (var i=0; i<SAMPLES_RESOURCES.length; i++) {
// current search comparison, with counters for tag and title,
// used later to improve ranking
var s = SAMPLES_RESOURCES[i];
s.matched_tag = 0;
s.matched_title = 0;
var matched = false;
// Check if query matches any tags; work backwards toward 1 to assist ranking
for (var j = s.keywords.length - 1; j >= 0; j--) {
// it matches a tag
if (s.keywords[j].toLowerCase().match(textRegex)) {
matched = true;
s.matched_tag = j + 1; // add 1 to index position
}
}
// Check if query matches the doc title, but only for current language
if (s.lang == currentLang) {
// if query matches the doc title.t
if (s.title.toLowerCase().match(textRegex)) {
matched = true;
s.matched_title = 1;
}
}
if (matched) {
gDocsMatches[matchedCountDocs] = s;
matchedCountDocs++;
}
}
// Rank/sort all the matched pages
rank_autocomplete_doc_results(text, gDocsMatches);
}
// draw the suggestions
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
/* Order the jd doc result list based on match quality */
function rank_autocomplete_doc_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
var _resultScoreFn = function(match) {
var score = 1.0;
// if the query matched a tag
if (match.matched_tag > 0) {
// multiply score by factor relative to position in tags list (max of 3)
score *= 3 / match.matched_tag;
// if it also matched the title
if (match.matched_title > 0) {
score *= 2;
}
} else if (match.matched_title > 0) {
score *= 3;
}
return score;
};
for (var i=0; i<matches.length; i++) {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Order the result list based on match quality */
function rank_autocomplete_api_results(query, matches) {
query = query || '';
if (!matches || !matches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<matches.length; i++) {
// if the API is deprecated, default score is 0; otherwise, perform scoring
if (matches[i].deprecated == "true") {
matches[i].__resultScore = 0;
} else {
matches[i].__resultScore = _resultScoreFn(matches[i]);
}
}
matches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
/* Add emphasis to part of string that matches query */
function highlight_autocomplete_result_labels(query) {
query = query || '';
if ((!gMatches || !gMatches.length) && (!gGoogleMatches || !gGoogleMatches.length))
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
for (var i=0; i<gGoogleMatches.length; i++) {
gGoogleMatches[i].__hilabel = gGoogleMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
$(".suggest-card").hide();
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow', setStickyTop);
return false;
}
function hideResults() {
$("#searchResults").slideUp('fast', setStickyTop);
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
var searchControl;
google.load('search', '1', {"callback" : function() {
searchControl = new google.search.SearchControl();
} });
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// once search results load, set up click listeners
searchControl.setSearchCompleteCallback(this, function(control, searcher, query) {
addResultClickListeners();
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow', setStickyTop);
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
/* Adjust the scroll position to account for sticky header, only if the hash matches an id.
This does not handle <a name=""> tags. Some CSS fixes those, but only for reference docs. */
function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
}
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
// If the hash isn't a search query or there's an error in the query,
// then adjust the scroll position to account for sticky header, then exit.
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
offsetScrollForSticky();
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow', setStickyTop);
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
// add analytics tracking events to each result link
function addResultClickListeners() {
$("#searchResults a.gs-title").each(function(index, link) {
// When user clicks enter for Google search results, track it
$(link).click(function() {
ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),
'query: ' + $("#search_autocomplete").val().toLowerCase());
});
});
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference") == 0) {
if(!(location.pathname.indexOf("/reference-gms/packages.html") == 0)
&& !(location.pathname.indexOf("/reference-gcm/packages.html") == 0)
&& !(location.pathname.indexOf("/reference/com/google") == 0)) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!sticky) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
writeCookie(API_LEVEL_COOKIE, selectedLevel, null);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher. To reveal, change the target API level "
+ "above the left navigation.");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
}
});
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
/****** NEW version of script to build google and sample navs dynamically ******/
// TODO: update Google reference docs to tolerate this new implementation
var NODE_NAME = 0;
var NODE_HREF = 1;
var NODE_GROUP = 2;
var NODE_TAGS = 3;
var NODE_CHILDREN = 4;
function init_google_navtree2(navtree_id, data)
{
var $containerUl = $("#"+navtree_id);
for (var i in data) {
var node_data = data[i];
$containerUl.append(new_google_node2(node_data));
}
// Make all third-generation list items 'sticky' to prevent them from collapsing
$containerUl.find('li li li.nav-section').addClass('sticky');
initExpandableNavItems("#"+navtree_id);
}
function new_google_node2(node_data)
{
var linkText = node_data[NODE_NAME];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
var $li = $('<li>');
var $a;
if (node_data[NODE_HREF] != null) {
$a = $('<a href="' + toRoot + node_data[NODE_HREF] + '" title="' + linkText + '" >'
+ linkText + '</a>');
} else {
$a = $('<a href="#" onclick="return false;" title="' + linkText + '" >'
+ linkText + '/</a>');
}
var $childUl = $('<ul>');
if (node_data[NODE_CHILDREN] != null) {
$li.addClass("nav-section");
$a = $('<div class="nav-section-header">').append($a);
if (node_data[NODE_HREF] == null) $a.addClass('empty');
for (var i in node_data[NODE_CHILDREN]) {
var child_node_data = node_data[NODE_CHILDREN][i];
$childUl.append(new_google_node2(child_node_data));
}
$li.append($childUl);
}
$li.prepend($a);
return $li;
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
}
function init_default_google_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gms_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function init_default_gcm_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'gcm_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
highlightSidenav();
resizeNav();
}
});
}
function showSamplesRefTree() {
init_default_samples_navtree(toRoot);
}
function init_default_samples_navtree(toroot) {
// load json file for navtree data
$.getScript(toRoot + 'samples_navtree_data.js', function(data, textStatus, jqxhr) {
// when the file is loaded, initialize the tree
if(jqxhr.status === 200) {
// hack to remove the "about the samples" link then put it back in
// after we nuke the list to remove the dummy static list of samples
var $firstLi = $("#nav.samples-nav > li:first-child").clone();
$("#nav.samples-nav").empty();
$("#nav.samples-nav").append($firstLi);
init_google_navtree2("nav.samples-nav", SAMPLES_NAVTREE_DATA);
highlightSidenav();
resizeNav();
if ($("#jd-content #samples").length) {
showSamples();
}
}
});
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
/* On-demand functions */
/** Move sample code line numbers out of PRE block and into non-copyable column */
function initCodeLineNumbers() {
var numbers = $("#codesample-block a.number");
if (numbers.length) {
$("#codesample-line-numbers").removeClass("hidden").append(numbers);
}
$(document).ready(function() {
// select entire line when clicked
$("span.code-line").click(function() {
if (!shifted) {
selectText(this);
}
});
// invoke line link on double click
$(".code-line").dblclick(function() {
document.location.hash = $(this).attr('id');
});
// highlight the line when hovering on the number
$("#codesample-line-numbers a.number").mouseover(function() {
var id = $(this).attr('href');
$(id).css('background','#e7e7e7');
});
$("#codesample-line-numbers a.number").mouseout(function() {
var id = $(this).attr('href');
$(id).css('background','none');
});
});
}
// create SHIFT key binder to avoid the selectText method when selecting multiple lines
var shifted = false;
$(document).bind('keyup keydown', function(e){shifted = e.shiftKey; return true;} );
// courtesy of jasonedelman.com
function selectText(element) {
var doc = document
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
/** Display links and other information about samples that match the
group specified by the URL */
function showSamples() {
var group = $("#samples").attr('class');
$("#samples").html("<p>Here are some samples for <b>" + group + "</b> apps:</p>");
var $ul = $("<ul>");
$selectedLi = $("#nav li.selected");
$selectedLi.children("ul").children("li").each(function() {
var $li = $("<li>").append($(this).find("a").first().clone());
$ul.append($li);
});
$("#samples").append($ul);
}
/* ########################################################## */
/* ################### RESOURCE CARDS ##################### */
/* ########################################################## */
/** Handle resource queries, collections, and grids (sections). Requires
jd_tag_helpers.js and the *_unified_data.js to be loaded. */
(function() {
// Prevent the same resource from being loaded more than once per page.
var addedPageResources = {};
$(document).ready(function() {
$('.resource-widget').each(function() {
initResourceWidget(this);
});
/* Pass the line height to ellipsisfade() to adjust the height of the
text container to show the max number of lines possible, without
showing lines that are cut off. This works with the css ellipsis
classes to fade last text line and apply an ellipsis char. */
//card text currently uses 15px line height.
var lineHeight = 15;
$('.card-info .text').ellipsisfade(lineHeight);
});
/*
Three types of resource layouts:
Flow - Uses a fixed row-height flow using float left style.
Carousel - Single card slideshow all same dimension absolute.
Stack - Uses fixed columns and flexible element height.
*/
function initResourceWidget(widget) {
var $widget = $(widget);
var isFlow = $widget.hasClass('resource-flow-layout'),
isCarousel = $widget.hasClass('resource-carousel-layout'),
isStack = $widget.hasClass('resource-stack-layout');
// find size of widget by pulling out its class name
var sizeCols = 1;
var m = $widget.get(0).className.match(/\bcol-(\d+)\b/);
if (m) {
sizeCols = parseInt(m[1], 10);
}
var opts = {
cardSizes: ($widget.data('cardsizes') || '').split(','),
maxResults: parseInt($widget.data('maxresults') || '100', 10),
itemsPerPage: $widget.data('itemsperpage'),
sortOrder: $widget.data('sortorder'),
query: $widget.data('query'),
section: $widget.data('section'),
sizeCols: sizeCols,
/* Added by LFL 6/6/14 */
resourceStyle: $widget.data('resourcestyle') || 'card',
stackSort: $widget.data('stacksort') || 'true'
};
// run the search for the set of resources to show
var resources = buildResourceList(opts);
if (isFlow) {
drawResourcesFlowWidget($widget, opts, resources);
} else if (isCarousel) {
drawResourcesCarouselWidget($widget, opts, resources);
} else if (isStack) {
/* Looks like this got removed and is not used, so repurposing for the
homepage style layout.
Modified by LFL 6/6/14
*/
//var sections = buildSectionList(opts);
opts['numStacks'] = $widget.data('numstacks');
drawResourcesStackWidget($widget, opts, resources/*, sections*/);
}
}
/* Initializes a Resource Carousel Widget */
function drawResourcesCarouselWidget($widget, opts, resources) {
$widget.empty();
var plusone = true; //always show plusone on carousel
$widget.addClass('resource-card slideshow-container')
.append($('<a>').addClass('slideshow-prev').text('Prev'))
.append($('<a>').addClass('slideshow-next').text('Next'));
var css = { 'width': $widget.width() + 'px',
'height': $widget.height() + 'px' };
var $ul = $('<ul>');
for (var i = 0; i < resources.length; ++i) {
var $card = $('<a>')
.attr('href', cleanUrl(resources[i].url))
.decorateResourceCard(resources[i],plusone);
$('<li>').css(css)
.append($card)
.appendTo($ul);
}
$('<div>').addClass('frame')
.append($ul)
.appendTo($widget);
$widget.dacSlideshow({
auto: true,
btnPrev: '.slideshow-prev',
btnNext: '.slideshow-next'
});
};
/* Initializes a Resource Card Stack Widget (column-based layout)
Modified by LFL 6/6/14
*/
function drawResourcesStackWidget($widget, opts, resources, sections) {
// Don't empty widget, grab all items inside since they will be the first
// items stacked, followed by the resource query
var plusone = true; //by default show plusone on section cards
var cards = $widget.find('.resource-card').detach().toArray();
var numStacks = opts.numStacks || 1;
var $stacks = [];
var urlString;
for (var i = 0; i < numStacks; ++i) {
$stacks[i] = $('<div>').addClass('resource-card-stack')
.appendTo($widget);
}
var sectionResources = [];
// Extract any subsections that are actually resource cards
if (sections) {
for (var i = 0; i < sections.length; ++i) {
if (!sections[i].sections || !sections[i].sections.length) {
// Render it as a resource card
sectionResources.push(
$('<a>')
.addClass('resource-card section-card')
.attr('href', cleanUrl(sections[i].resource.url))
.decorateResourceCard(sections[i].resource,plusone)[0]
);
} else {
cards.push(
$('<div>')
.addClass('resource-card section-card-menu')
.decorateResourceSection(sections[i],plusone)[0]
);
}
}
}
cards = cards.concat(sectionResources);
for (var i = 0; i < resources.length; ++i) {
var $card = createResourceElement(resources[i], opts);
if (opts.resourceStyle.indexOf('related') > -1) {
$card.addClass('related-card');
}
cards.push($card[0]);
}
if (opts.stackSort != 'false') {
for (var i = 0; i < cards.length; ++i) {
// Find the stack with the shortest height, but give preference to
// left to right order.
var minHeight = $stacks[0].height();
var minIndex = 0;
for (var j = 1; j < numStacks; ++j) {
var height = $stacks[j].height();
if (height < minHeight - 45) {
minHeight = height;
minIndex = j;
}
}
$stacks[minIndex].append($(cards[i]));
}
}
};
/*
Create a resource card using the given resource object and a list of html
configured options. Returns a jquery object containing the element.
*/
function createResourceElement(resource, opts, plusone) {
var $el;
// The difference here is that generic cards are not entirely clickable
// so its a div instead of an a tag, also the generic one is not given
// the resource-card class so it appears with a transparent background
// and can be styled in whatever way the css setup.
if (opts.resourceStyle == 'generic') {
$el = $('<div>')
.addClass('resource')
.attr('href', cleanUrl(resource.url))
.decorateResource(resource, opts);
} else {
var cls = 'resource resource-card';
$el = $('<a>')
.addClass(cls)
.attr('href', cleanUrl(resource.url))
.decorateResourceCard(resource, plusone);
}
return $el;
}
/* Initializes a flow widget, see distribute.scss for generating accompanying css */
function drawResourcesFlowWidget($widget, opts, resources) {
$widget.empty();
var cardSizes = opts.cardSizes || ['6x6'];
var i = 0, j = 0;
var plusone = true; // by default show plusone on resource cards
while (i < resources.length) {
var cardSize = cardSizes[j++ % cardSizes.length];
cardSize = cardSize.replace(/^\s+|\s+$/,'');
// Some card sizes do not get a plusone button, such as where space is constrained
// or for cards commonly embedded in docs (to improve overall page speed).
plusone = !((cardSize == "6x2") || (cardSize == "6x3") ||
(cardSize == "9x2") || (cardSize == "9x3") ||
(cardSize == "12x2") || (cardSize == "12x3"));
// A stack has a third dimension which is the number of stacked items
var isStack = cardSize.match(/(\d+)x(\d+)x(\d+)/);
var stackCount = 0;
var $stackDiv = null;
if (isStack) {
// Create a stack container which should have the dimensions defined
// by the product of the items inside.
$stackDiv = $('<div>').addClass('resource-card-stack resource-card-' + isStack[1]
+ 'x' + isStack[2] * isStack[3]) .appendTo($widget);
}
// Build each stack item or just a single item
do {
var resource = resources[i];
var $card = createResourceElement(resources[i], opts, plusone);
$card.addClass('resource-card-' + cardSize +
' resource-card-' + resource.type);
if (isStack) {
$card.addClass('resource-card-' + isStack[1] + 'x' + isStack[2]);
if (++stackCount == parseInt(isStack[3])) {
$card.addClass('resource-card-row-stack-last');
stackCount = 0;
}
} else {
stackCount = 0;
}
$card.appendTo($stackDiv || $widget);
} while (++i < resources.length && stackCount > 0);
}
}
/* Build a site map of resources using a section as a root. */
function buildSectionList(opts) {
if (opts.section && SECTION_BY_ID[opts.section]) {
return SECTION_BY_ID[opts.section].sections || [];
}
return [];
}
function buildResourceList(opts) {
var maxResults = opts.maxResults || 100;
var query = opts.query || '';
var expressions = parseResourceQuery(query);
var addedResourceIndices = {};
var results = [];
for (var i = 0; i < expressions.length; i++) {
var clauses = expressions[i];
// build initial set of resources from first clause
var firstClause = clauses[0];
var resources = [];
switch (firstClause.attr) {
case 'type':
resources = ALL_RESOURCES_BY_TYPE[firstClause.value];
break;
case 'lang':
resources = ALL_RESOURCES_BY_LANG[firstClause.value];
break;
case 'tag':
resources = ALL_RESOURCES_BY_TAG[firstClause.value];
break;
case 'collection':
var urls = RESOURCE_COLLECTIONS[firstClause.value].resources || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
case 'section':
var urls = SITE_MAP[firstClause.value].sections || [];
resources = urls.map(function(url){ return ALL_RESOURCES_BY_URL[url]; });
break;
}
// console.log(firstClause.attr + ':' + firstClause.value);
resources = resources || [];
// use additional clauses to filter corpus
if (clauses.length > 1) {
var otherClauses = clauses.slice(1);
resources = resources.filter(getResourceMatchesClausesFilter(otherClauses));
}
// filter out resources already added
if (i > 1) {
resources = resources.filter(getResourceNotAlreadyAddedFilter(addedResourceIndices));
}
// add to list of already added indices
for (var j = 0; j < resources.length; j++) {
// console.log(resources[j].title);
addedResourceIndices[resources[j].index] = 1;
}
// concat to final results list
results = results.concat(resources);
}
if (opts.sortOrder && results.length) {
var attr = opts.sortOrder;
if (opts.sortOrder == 'random') {
var i = results.length, j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = results[i];
results[i] = results[j];
results[j] = temp;
}
} else {
var desc = attr.charAt(0) == '-';
if (desc) {
attr = attr.substring(1);
}
results = results.sort(function(x,y) {
return (desc ? -1 : 1) * (parseInt(x[attr], 10) - parseInt(y[attr], 10));
});
}
}
results = results.filter(getResourceNotAlreadyAddedFilter(addedPageResources));
results = results.slice(0, maxResults);
for (var j = 0; j < results.length; ++j) {
addedPageResources[results[j].index] = 1;
}
return results;
}
function getResourceNotAlreadyAddedFilter(addedResourceIndices) {
return function(resource) {
return !addedResourceIndices[resource.index];
};
}
function getResourceMatchesClausesFilter(clauses) {
return function(resource) {
return doesResourceMatchClauses(resource, clauses);
};
}
function doesResourceMatchClauses(resource, clauses) {
for (var i = 0; i < clauses.length; i++) {
var map;
switch (clauses[i].attr) {
case 'type':
map = IS_RESOURCE_OF_TYPE[clauses[i].value];
break;
case 'lang':
map = IS_RESOURCE_IN_LANG[clauses[i].value];
break;
case 'tag':
map = IS_RESOURCE_TAGGED[clauses[i].value];
break;
}
if (!map || (!!clauses[i].negative ? map[resource.index] : !map[resource.index])) {
return clauses[i].negative;
}
}
return true;
}
function cleanUrl(url)
{
if (url && url.indexOf('//') === -1) {
url = toRoot + url;
}
return url;
}
function parseResourceQuery(query) {
// Parse query into array of expressions (expression e.g. 'tag:foo + type:video')
var expressions = [];
var expressionStrs = query.split(',') || [];
for (var i = 0; i < expressionStrs.length; i++) {
var expr = expressionStrs[i] || '';
// Break expression into clauses (clause e.g. 'tag:foo')
var clauses = [];
var clauseStrs = expr.split(/(?=[\+\-])/);
for (var j = 0; j < clauseStrs.length; j++) {
var clauseStr = clauseStrs[j] || '';
// Get attribute and value from clause (e.g. attribute='tag', value='foo')
var parts = clauseStr.split(':');
var clause = {};
clause.attr = parts[0].replace(/^\s+|\s+$/g,'');
if (clause.attr) {
if (clause.attr.charAt(0) == '+') {
clause.attr = clause.attr.substring(1);
} else if (clause.attr.charAt(0) == '-') {
clause.negative = true;
clause.attr = clause.attr.substring(1);
}
}
if (parts.length > 1) {
clause.value = parts[1].replace(/^\s+|\s+$/g,'');
}
clauses.push(clause);
}
if (!clauses.length) {
continue;
}
expressions.push(clauses);
}
return expressions;
}
})();
(function($) {
/*
Utility method for creating dom for the description area of a card.
Used in decorateResourceCard and decorateResource.
*/
function buildResourceCardDescription(resource, plusone) {
var $description = $('<div>').addClass('description ellipsis');
$description.append($('<div>').addClass('text').html(resource.summary));
if (resource.cta) {
$description.append($('<a>').addClass('cta').html(resource.cta));
}
if (plusone) {
var plusurl = resource.url.indexOf("//") > -1 ? resource.url :
"//developer.android.com/" + resource.url;
$description.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', plusurl)));
}
return $description;
}
/* Simple jquery function to create dom for a standard resource card */
$.fn.decorateResourceCard = function(resource,plusone) {
var section = resource.group || resource.type;
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
$('<div>').addClass('card-bg')
.css('background-image', 'url(' + (imgUrl || toRoot +
'assets/images/resource-card-default-android.jpg') + ')')
.appendTo(this);
$('<div>').addClass('card-info' + (!resource.summary ? ' empty-desc' : ''))
.append($('<div>').addClass('section').text(section))
.append($('<div>').addClass('title').html(resource.title))
.append(buildResourceCardDescription(resource, plusone))
.appendTo(this);
return this;
};
/* Simple jquery function to create dom for a resource section card (menu) */
$.fn.decorateResourceSection = function(section,plusone) {
var resource = section.resource;
//keep url clean for matching and offline mode handling
var urlPrefix = resource.image.indexOf("//") > -1 ? "" : toRoot;
var $base = $('<a>')
.addClass('card-bg')
.attr('href', resource.url)
.append($('<div>').addClass('card-section-icon')
.append($('<div>').addClass('icon'))
.append($('<div>').addClass('section').html(resource.title)))
.appendTo(this);
var $cardInfo = $('<div>').addClass('card-info').appendTo(this);
if (section.sections && section.sections.length) {
// Recurse the section sub-tree to find a resource image.
var stack = [section];
while (stack.length) {
if (stack[0].resource.image) {
$base.css('background-image', 'url(' + urlPrefix + stack[0].resource.image + ')');
break;
}
if (stack[0].sections) {
stack = stack.concat(stack[0].sections);
}
stack.shift();
}
var $ul = $('<ul>')
.appendTo($cardInfo);
var max = section.sections.length > 3 ? 3 : section.sections.length;
for (var i = 0; i < max; ++i) {
var subResource = section.sections[i];
if (!plusone) {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util'))))
.appendTo($ul);
} else {
$('<li>')
.append($('<a>').attr('href', subResource.url)
.append($('<div>').addClass('title').html(subResource.title))
.append($('<div>').addClass('description ellipsis')
.append($('<div>').addClass('text').html(subResource.summary))
.append($('<div>').addClass('util')
.append($('<div>').addClass('g-plusone')
.attr('data-size', 'small')
.attr('data-align', 'right')
.attr('data-href', resource.url)))))
.appendTo($ul);
}
}
// Add a more row
if (max < section.sections.length) {
$('<li>')
.append($('<a>').attr('href', resource.url)
.append($('<div>')
.addClass('title')
.text('More')))
.appendTo($ul);
}
} else {
// No sub-resources, just render description?
}
return this;
};
/* Render other types of resource styles that are not cards. */
$.fn.decorateResource = function(resource, opts) {
var imgUrl = resource.image ||
'assets/images/resource-card-default-android.jpg';
var linkUrl = resource.url;
if (imgUrl.indexOf('//') === -1) {
imgUrl = toRoot + imgUrl;
}
if (linkUrl && linkUrl.indexOf('//') === -1) {
linkUrl = toRoot + linkUrl;
}
$(this).append(
$('<div>').addClass('image')
.css('background-image', 'url(' + imgUrl + ')'),
$('<div>').addClass('info').append(
$('<h4>').addClass('title').html(resource.title),
$('<p>').addClass('summary').html(resource.summary),
$('<a>').attr('href', linkUrl).addClass('cta').html('Learn More')
)
);
return this;
};
})(jQuery);
/* Calculate the vertical area remaining */
(function($) {
$.fn.ellipsisfade= function(lineHeight) {
this.each(function() {
// get element text
var $this = $(this);
var remainingHeight = $this.parent().parent().height();
$this.parent().siblings().each(function ()
{
if ($(this).is(":visible")) {
var h = $(this).height();
remainingHeight = remainingHeight - h;
}
});
adjustedRemainingHeight = ((remainingHeight)/lineHeight>>0)*lineHeight
$this.parent().css({'height': adjustedRemainingHeight});
$this.css({'height': "auto"});
});
return this;
};
}) (jQuery);
/*
Fullscreen Carousel
The following allows for an area at the top of the page that takes over the
entire browser height except for its top offset and an optional bottom
padding specified as a data attribute.
HTML:
<div class="fullscreen-carousel">
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
<div class="fullscreen-carousel-content">
<!-- content here -->
</div>
etc ...
</div>
Control over how the carousel takes over the screen can mostly be defined in
a css file. Setting min-height on the .fullscreen-carousel-content elements
will prevent them from shrinking to far vertically when the browser is very
short, and setting max-height on the .fullscreen-carousel itself will prevent
the area from becoming to long in the case that the browser is stretched very
tall.
There is limited functionality for having multiple sections since that request
was removed, but it is possible to add .next-arrow and .prev-arrow elements to
scroll between multiple content areas.
*/
(function() {
$(document).ready(function() {
$('.fullscreen-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var topOffset = $widget.offset().top;
var padBottom = parseInt($widget.data('paddingbottom')) || 0;
var maxHeight = 0;
var minHeight = 0;
var $content = $widget.find('.fullscreen-carousel-content');
var $nextArrow = $widget.find('.next-arrow');
var $prevArrow = $widget.find('.prev-arrow');
var $curSection = $($content[0]);
if ($content.length <= 1) {
$nextArrow.hide();
$prevArrow.hide();
} else {
$nextArrow.click(function() {
var index = ($content.index($curSection) + 1);
$curSection.hide();
$curSection = $($content[index >= $content.length ? 0 : index]);
$curSection.show();
});
$prevArrow.click(function() {
var index = ($content.index($curSection) - 1);
$curSection.hide();
$curSection = $($content[index < 0 ? $content.length - 1 : 0]);
$curSection.show();
});
}
// Just hide all content sections except first.
$content.each(function(index) {
if ($(this).height() > minHeight) minHeight = $(this).height();
$(this).css({position: 'absolute', display: index > 0 ? 'none' : ''});
});
// Register for changes to window size, and trigger.
$(window).resize(resizeWidget);
resizeWidget();
function resizeWidget() {
var height = $(window).height() - topOffset - padBottom;
$widget.width($(window).width());
$widget.height(height < minHeight ? minHeight :
(maxHeight && height > maxHeight ? maxHeight : height));
}
}
})();
/*
Tab Carousel
The following allows tab widgets to be installed via the html below. Each
tab content section should have a data-tab attribute matching one of the
nav items'. Also each tab content section should have a width matching the
tab carousel.
HTML:
<div class="tab-carousel">
<ul class="tab-nav">
<li><a href="#" data-tab="handsets">Handsets</a>
<li><a href="#" data-tab="wearable">Wearable</a>
<li><a href="#" data-tab="tv">TV</a>
</ul>
<div class="tab-carousel-content">
<div data-tab="handsets">
<!--Full width content here-->
</div>
<div data-tab="wearable">
<!--Full width content here-->
</div>
<div data-tab="tv">
<!--Full width content here-->
</div>
</div>
</div>
*/
(function() {
$(document).ready(function() {
$('.tab-carousel').each(function() {
initWidget(this);
});
});
function initWidget(widget) {
var $widget = $(widget);
var $nav = $widget.find('.tab-nav');
var $anchors = $nav.find('[data-tab]');
var $li = $nav.find('li');
var $contentContainer = $widget.find('.tab-carousel-content');
var $tabs = $contentContainer.find('[data-tab]');
var $curTab = $($tabs[0]); // Current tab is first tab.
var width = $widget.width();
// Setup nav interactivity.
$anchors.click(function(evt) {
evt.preventDefault();
var query = '[data-tab=' + $(this).data('tab') + ']';
transitionWidget($tabs.filter(query));
});
// Add highlight for navigation on first item.
var $highlight = $('<div>').addClass('highlight')
.css({left:$li.position().left + 'px', width:$li.outerWidth() + 'px'})
.appendTo($nav);
// Store height since we will change contents to absolute.
$contentContainer.height($contentContainer.height());
// Absolutely position tabs so they're ready for transition.
$tabs.each(function(index) {
$(this).css({position: 'absolute', left: index > 0 ? width + 'px' : '0'});
});
function transitionWidget($toTab) {
if (!$curTab.is($toTab)) {
var curIndex = $tabs.index($curTab[0]);
var toIndex = $tabs.index($toTab[0]);
var dir = toIndex > curIndex ? 1 : -1;
// Animate content sections.
$toTab.css({left:(width * dir) + 'px'});
$curTab.animate({left:(width * -dir) + 'px'});
$toTab.animate({left:'0'});
// Animate navigation highlight.
$highlight.animate({left:$($li[toIndex]).position().left + 'px',
width:$($li[toIndex]).outerWidth() + 'px'})
// Store new current section.
$curTab = $toTab;
}
}
}
})();
| JavaScript |
$(document).ready(function() {
// prep nav expandos
var pagePath = document.location.pathname;
if (pagePath.indexOf(SITE_ROOT) == 0) {
pagePath = pagePath.substr(SITE_ROOT.length);
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path should be an absolute URL.
pagePath = SITE_ROOT + pagePath;
}
// select current page in sidenav and set up prev/next links if they exist
var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]');
if ($selNavLink.length) {
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
$selListItem.closest('li>ul').addClass('expanded');
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
$prevLink = $selListItem.parents('li').find('a');
}
if ($prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
$('.prev-page-link').hide();
} else {
$('.prev-page-link').attr('href', prevHref).show();
}
} else {
$('.prev-page-link').hide();
}
// set up next links
var $nextLink = [];
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul').find('a:eq(0)')
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)');
}
}
if ($nextLink.length) {
$('.next-page-link').attr('href', $nextLink.attr('href')).show();
} else {
$('.next-page-link').hide();
}
}
// Set up expand/collapse behavior
$('.nav-y li').has('ul').click(function() {
if ($(this).hasClass('expanded')) {
return;
}
// hide other
var $old = $('.nav-y li.expanded');
if ($old.length) {
var $oldUl = $old.children('ul');
$oldUl.css('height', $oldUl.height() + 'px');
window.setTimeout(function() {
$oldUl
.addClass('animate-height')
.css('height', '');
}, 0);
$old.removeClass('expanded');
}
// show me
$(this).addClass('expanded');
var $ul = $(this).children('ul');
var expandedHeight = $ul.height();
$ul
.removeClass('animate-height')
.css('height', 0);
window.setTimeout(function() {
$ul
.addClass('animate-height')
.css('height', expandedHeight + 'px');
}, 0);
});
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.text($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
// Set up fixed navbar
var navBarIsFixed = false;
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var navBarShouldBeFixed = (scrollTop > (100 - 40));
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
$('#nav')
.addClass('fixed')
.prependTo('#page-container');
} else {
$('#nav')
.removeClass('fixed')
.prependTo('#nav-container');
}
navBarIsFixed = navBarShouldBeFixed;
}
});
}); | JavaScript |
/* API LEVEL TOGGLE */
<?cs if:reference.apilevels ?>
addLoadEvent(changeApiLevel);
<?cs /if ?>
var API_LEVEL_ENABLED_COOKIE = "api_level_enabled";
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
function toggleApiLevelSelector(checkbox) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
if (checkbox.checked) {
$("#apiLevelSelector").removeAttr("disabled");
$("#api-level-toggle label").removeClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration);
} else {
$("#apiLevelSelector").attr("disabled","disabled");
$("#api-level-toggle label").addClass("disabled");
writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration);
}
changeApiLevel();
}
function buildApiLevelSelector() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var userApiLevel = readCookie(API_LEVEL_COOKIE);
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
if (userApiLevelEnabled == 0) {
$("#apiLevelSelector").attr("disabled","disabled");
} else {
$("#apiLevelCheckbox").attr("checked","checked");
$("#api-level-toggle label").removeClass("disabled");
}
minLevel = $("body").attr("class");
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
var maxLevel = SINCE_DATA.length;
var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE);
var selectedLevel = maxLevel;
if (userApiLevelEnabled == 0) {
toggleVisisbleApis(selectedLevel, "body");
} else {
selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
}
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>"
+ "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest "
+ "and be compiled against a version of the library that supports an equal or higher API Level. To reveal this "
+ "document, change the value of the API Level filter above.</p>"
+ "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher");
else obj.removeClass("absent").removeAttr("title");
});
}
/* NAVTREE */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
node.label_div.style.paddingLeft = 10*node.depth + "px";
if (children_data == null) {
// 12 is the width of the triangle and padding extra space
node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px";
} else {
node.label_div.style.paddingLeft = 10*node.depth + "px";
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent");
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function load_navtree_data(toroot) {
var navtreeData = document.createElement("script");
navtreeData.setAttribute("type","text/javascript");
navtreeData.setAttribute("src", toroot+"navtree_data.js");
$("head").append($(navtreeData));
}
function init_default_navtree(toroot) {
init_navtree("nav-tree", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#doc-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#doc-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
}); | JavaScript |
var resizePackagesNav;
var classesNav;
var devdocNav;
var sidenav;
var content;
var HEADER_HEIGHT = -1;
var cookie_namespace = 'doclava_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var toRoot;
var isMobile = false; // true if mobile, so we can adjust some layout
var isIE6 = false; // true if IE6
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
addLoadEvent(mobileSetup);
// If not a mobile browser, set the onresize event for IE6, and others
} else if (agent.indexOf("msie 6") != -1) {
isIE6 = true;
addLoadEvent(function() {
window.onresize = resizeAll;
});
} else {
addLoadEvent(function() {
window.onresize = resizeHeight;
});
}
function mobileSetup() {
$("body").css({'overflow':'auto'});
$("html").css({'overflow':'auto'});
$("#body-content").css({'position':'relative', 'top':'0'});
$("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'});
$("#side-nav").css({'padding':'0'});
$("#nav-tree").css({'overflow-y': 'auto'});
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
function setToRoot(root) {
toRoot = root;
// note: toRoot also used by carousel.js
}
function restoreWidth(navWidth) {
var windowWidth = $(window).width() + "px";
content.css({marginLeft:parseInt(navWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); // necessary in order for scrollbars to be visible
}
sidenav.css({width:navWidth});
resizePackagesNav.css({width:navWidth});
classesNav.css({width:navWidth});
$("#packages-nav").css({width:navWidth});
}
function restoreHeight(packageHeight) {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
sidenav.css({height:windowHeight + "px"});
content.css({height:windowHeight + "px"});
resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight});
classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"});
$("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle
devdocNav.css({height:sidenav.css("height")});
$("#nav-tree").css({height:swapperHeight + "px"});
}
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
document.cookie = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/";
}
function getSection() {
if (location.href.indexOf("/reference/") != -1) {
return "reference";
} else if (location.href.indexOf("/guide/") != -1) {
return "guide";
} else if (location.href.indexOf("/resources/") != -1) {
return "resources";
}
var basePath = getBaseUri(location.pathname);
return basePath.substring(1,basePath.indexOf("/",1));
}
function init() {
HEADER_HEIGHT = $("#header").height()+3;
$("#side-nav").css({position:"absolute",left:0});
content = $("#doc-content");
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
sidenav = $("#side-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = getSection() + "_";
if (!isMobile) {
$("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizePackagesHeight(); } });
$(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } });
var cookieWidth = readCookie(cookiePath+'width');
var cookieHeight = readCookie(cookiePath+'height');
if (cookieWidth) {
restoreWidth(cookieWidth);
} else if ($(".side-nav-resizable").length) {
resizeWidth();
}
if (cookieHeight) {
restoreHeight(cookieHeight);
} else {
resizeHeight();
}
}
if (devdocNav.length) { // only dev guide, resources, and sdk
tryPopulateResourcesNav();
highlightNav(location.href);
}
}
function highlightNav(fullPageName) {
var lastSlashPos = fullPageName.lastIndexOf("/");
var firstSlashPos;
if (fullPageName.indexOf("/guide/") != -1) {
firstSlashPos = fullPageName.indexOf("/guide/");
} else if (fullPageName.indexOf("/sdk/") != -1) {
firstSlashPos = fullPageName.indexOf("/sdk/");
} else {
firstSlashPos = fullPageName.indexOf("/resources/");
}
if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html')
fullPageName = fullPageName + "index.html";
}
// First check if the exact URL, with query string and all, is in the navigation menu
var pathPageName = fullPageName.substr(firstSlashPos);
var link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if (link.length == 0) {
var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length);
pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); // +5 advances past ".html"
link = $("#devdoc-nav a[href$='"+ pathPageName+"']");
if ((link.length == 0) && ((fullPageName.indexOf("/guide/") != -1) || (fullPageName.indexOf("/resources/") != -1))) {
// if there's no match, then let's backstep through the directory until we find an index.html page
// that matches our ancestor directories (only for dev guide and resources)
lastBackstep = pathPageName.lastIndexOf("/");
while (link.length == 0) {
backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep);
link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']");
lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1);
if (lastBackstep == 0) break;
}
}
}
// add 'selected' to the <li> or <div> that wraps this <a>
link.parent().addClass('selected');
// if we're in a toggleable root link (<li class=toggle-list><div><a>)
if (link.parent().parent().hasClass('toggle-list')) {
toggle(link.parent().parent(), false); // open our own list
// then also check if we're in a third-level nested list that's toggleable
if (link.parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent(), false); // open the super parent list
}
}
// if we're in a normal nav link (<li><a>) and the parent <ul> is hidden
else if (link.parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent(), false); // open the parent list
// then also check if the parent list is also nested in a hidden list
if (link.parent().parent().parent().parent().is(':hidden')) {
toggle(link.parent().parent().parent().parent().parent(), false); // open the super parent list
}
}
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function resizePackagesHeight() {
var windowHeight = ($(window).height() - HEADER_HEIGHT);
var swapperHeight = windowHeight - 13; // move 13px for swapper link at the bottom
resizePackagesNav.css({maxHeight:swapperHeight + "px"});
classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#swapper").css({height:swapperHeight + "px"});
$("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle
var section = getSection();
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
/* Resize the height of the side-nav and doc-content divs,
* which creates the frame effect */
function resizeHeight() {
var docContent = $("#doc-content");
// Get the window height and always resize the doc-content and side-nav divs
var windowHeight = ($(window).height() - HEADER_HEIGHT);
docContent.css({height:windowHeight + "px"});
$("#side-nav").css({height:windowHeight + "px"});
var href = location.href;
// If in the reference docs, also resize the "swapper", "classes-nav", and "nav-tree" divs
if (href.indexOf("/reference/") != -1) {
var swapperHeight = windowHeight - 13;
$("#swapper").css({height:swapperHeight + "px"});
$("#classes-nav").css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"});
$("#nav-tree").css({height:swapperHeight + "px"});
// If in the dev guide docs, also resize the "devdoc-nav" div
} else if (href.indexOf("/guide/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
} else if (href.indexOf("/resources/") != -1) {
$("#devdoc-nav").css({height:sidenav.css("height")});
}
// Hide the "Go to top" link if there's no vertical scroll
if ( parseInt($("#jd-content").css("height")) <= parseInt(docContent.css("height")) ) {
$("a[href='#top']").css({'display':'none'});
} else {
$("a[href='#top']").css({'display':'inline'});
}
}
/* Resize the width of the "side-nav" and the left margin of the "doc-content" div,
* which creates the resizable side bar */
function resizeWidth() {
var windowWidth = $(window).width() + "px";
if (sidenav.length) {
var sidenavWidth = sidenav.css("width");
} else {
var sidenavWidth = 0;
}
content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px"}); //account for 6px-wide handle-bar
if (isIE6) {
content.css({width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); // necessary in order to for scrollbars to be visible
}
resizePackagesNav.css({width:sidenavWidth});
classesNav.css({width:sidenavWidth});
$("#packages-nav").css({width:sidenavWidth});
if ($(".side-nav-resizable").length) { // Must check if the nav is resizable because IE6 calls resizeWidth() from resizeAll() for all pages
var section = getSection();
writeCookie("width", sidenavWidth, section, null);
}
}
/* For IE6 only,
* because it can't properly perform auto width for "doc-content" div,
* avoiding this for all browsers provides better performance */
function resizeAll() {
resizeHeight();
resizeWidth();
}
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if (path.indexOf("/resources/") != -1) {
writeCookie("lastpage", path, "resources", null);
}
});
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree");
else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
function scrollIntoView(nav) {
var navObj = $("#"+nav);
if (navObj.is(':visible')) {
var selected = $(".selected", navObj);
if (selected.length == 0) return;
if (selected.is("div")) selected = selected.parent();
var scrolling = document.getElementById(nav);
var navHeight = navObj.height();
var offsetTop = selected.position().top;
if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top;
if(offsetTop > navHeight - 92) {
scrolling.scrollTop = offsetTop - navHeight + 92;
}
}
}
function changeTabLang(lang) {
var nodes = $("#header-tabs").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { //if this languages node has a translation, show it
node.css("display","inline");
} else { //otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeNavLang(lang) {
var nodes = $("#side-nav").find("."+lang);
for (i=0; i < nodes.length; i++) { // for each node in this language
var node = $(nodes[i]);
node.siblings().css("display","none"); // hide all siblings
if (node.not(":empty").length != 0) { // if this languages node has a translation, show it
node.css("display","inline");
} else { // otherwise, show English instead
node.css("display","none");
node.siblings().filter(".en").css("display","inline");
}
}
}
function changeDocLang(lang) {
changeTabLang(lang);
changeNavLang(lang);
}
function changeLangPref(lang, refresh) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
//changeDocLang(lang);
if (refresh) {
l = getBaseUri(location.pathname);
window.location = l;
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
function toggleContent(obj) {
var button = $(obj);
var div = $(obj.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (button.hasClass("show")) {
toggleMe.slideDown();
button.removeClass("show").addClass("hide");
} else {
toggleMe.slideUp();
button.removeClass("hide").addClass("show");
}
$("span", button).toggle();
} | JavaScript |
var BUILD_TIMESTAMP = "";
| JavaScript |
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2011, IBM Corporation
*/
/**
* Constructor
*/
function FileOpener() {
};
FileOpener.prototype.open = function(url) {
cordova.exec(null, null, "FileOpener", "openFile", [url]);
};
/**
* Load Plugin
*/
if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.fileOpener) {
window.plugins.fileOpener = new FileOpener();
}
| JavaScript |
function excecuteLocalization(arrFiles, level){
$.each(arrFiles, function (index, value) {
doLocalize(value, level)
});
}
function doLocalize(pageName, level){
//alert(pageName);
var lang = {
autoDetect: true, //This tells the APP to detect the language preference and load the translation file automatically
langPref: "es", // if you set "autoDetect:false" you should mention the name of the translation file you want to load
langBundle:"lang", //folder name that contains all translation files
fileExtention: ".json"
}
var locale = window.localStorage.getItem("locale");
if(locale && locale!=""){
lang.langPref = lang.langBundle.toString() + '/' + pageName + '_' + locale + lang.fileExtention;
} else{
if(lang.autoDetect){
navigator.globalization.getLocaleName(
function (locale) {
//alert('locale: ' + locale.value + '\n');
var arrLocale = locale.value.split("_");
locale.value = arrLocale[0];
//alert('locale: ' + locale.value + '\n');
lang.langPref = lang.langBundle.toString() + '/' + pageName + '_' + locale.value + lang.fileExtention;
$('html').attr('lang',locale.value);
},
function () {
alert('Error getting locale. Using default: ' + lang.langPref);
$('html').attr('lang',lang.langPref.toString());
lang.langPref = lang.langBundle.toString() + '/' + pageName + '_' + lang.langPref + lang.fileExtention;
}
);
} else {
$('html').attr('lang',lang.langPref.toString());
lang.langPref = lang.langBundle.toString() + '/' + pageName + '_' + lang.langPref + lang.fileExtention;
}
}
if(level){
lang.langPref = level + lang.langPref;
}
//alert(lang.langPref);
$.ajax({
url:lang.langPref,
dataType:'JSON',
'global': false,
'async': false,
success: function(data){
//alert(data);
$.each(data, function(key, val) {
//alert("key:" + key + ", val: " + val);
$("[data-translate='localize']").each(function(){
//alert("tengo: " + $(this).html() + ", busco: " + key);
if(key == $(this).html()){
//alert("reemplazo por: " + val);
$(this).html(val);
//return false;
}
});
});
var interval = setInterval(function(){
$.mobile.loading('hide');
clearInterval(interval);
$("[data-role='page']").fadeIn("slow");
},1);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
} | JavaScript |
$(document).on('pagebeforecreate', function(){
var interval = setInterval(function(){
$.mobile.loading('show');
clearInterval(interval);
},1);
});
function openMenu(){
$( "#menu-panel" ).panel("open");
}
function exitAPP(){
if(confirm($("#confirm_msgTag").html())){
navigator.app.exitApp();
}
}
function backToHome(){
window.location.href='main.html';
}
function backToHomeDeep(){
window.location.href='../main.html';
}
function backToMenu(){
window.location.href='../menu_decisions.html';
}
| JavaScript |
function setLocalizedTemplates(type){
$.mobile.loading('show');
var locale = window.localStorage.getItem("locale");
if(locale && locale!=""){
loadLocalizedFile(type + "_" + locale + ".json");
} else{
navigator.globalization.getLocaleName(
function (locale) {
//alert('locale: ' + locale.value + '\n');
var arrLocale = locale.value.split("_");
loadLocalizedFile(type + "_" + arrLocale[0] + ".json");
},
function () {
alert('Error getting locale. Using default: en');
loadLocalizedFile(type + "_en.json");
}
);
}
}
function loadLocalizedFile(fileName){
//alert("decisionTemplates/" + fileName);
$.ajax({
url:"decisionTemplates/" + fileName,
dataType:'JSON',
'global': false,
'async': false,
success: function(data){
//alert(data);
$.each(data, function(key, val) {
//alert("key:" + key + ", val: " + val);
preloadedCriterias.push(val);
});
var interval = setInterval(function(){
$.mobile.loading('hide');
clearInterval(interval);
//$("#step_1").fadeIn("fast", function(){
setCriterias();
//});
},1);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
} | JavaScript |
function getParameter(name){
//alert(name);
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ){
return "";
}
else{
return results[1];
}
}
function checkNetwork(level){
if(!level || level == null || level == ""){
level = "./";
}
var url = "http://www.xeliom.com/TD/dummy.php"
$.mobile.loadingMessage = "Checking...";
$.mobile.loading('show');
$.getJSON(url).done(function(data) {
$.mobile.loading('hide');
return true;
}).fail(function(jqxhr, textStatus, error) {
//alert("No hay conexion a internet: " + textStatus + ", " + error);
alert("No hay conexion a internet.");
window.location.href = level + 'main.html';
$.mobile.loading('hide');
return false;
});
$.mobile.loading('hide');
return false;
} | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.