code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
function LineMotion(x1, x2, t) {
return x1.value + (x2.value - x1.value) * t;
}
var t2 = 0;
var t3 = 0;
function SplineMotion(x1, x2, r1, r2, t) {
t2 = t * t;
t3 = t2 * t;
return x1.value * (2.0 * t3 - 3.0 * t2 + 1.0) + r1.gradient * (t3 - 2.0 * t2 + t) + x2.value * (-2.0 * t3 + 3.0 * t2) + r2.gradient * (t3 - t2);
}
var motion_line = 1;
var motion_spline = 2;
var motion_discontinuous = 3;
function MotionValues() {
this._type;
this.keys = [];
this.start;
this.end;
this.middle;
this.Clear = function () {
this.keys.length = 0;
};
this.AddKey = function (time, value) {
var key = {};
key.time = +time;
key.value = +value;
this.keys.push(key);
return time;
};
this.SetType = function (type) {
this._type = type;
if (this.keys.length == 1) {
this.AddKey(1.0, this.keys[0].value);
}
if (type == motion_spline) {
this.keys[0].gradient = this.keys[1].value - this.keys[0].value;
this.keys[this.keys.length - 1].gradient =
this.keys[this.keys.length - 1].value - this.keys[this.keys.length - 2].value;
var g1, g2, g3;
for (var i = 1; i < (this.keys.length - 1); i++) {
g1 = this.keys[i].value - this.keys[i - 1].value;
g2 = this.keys[i + 1].value - this.keys[i].value;
g3 = g2 - g1;
this.keys[i].gradient = g1 + 0.5 * g3;
}
}
};
return this;
}
function Value(t, obj) {
var cord = obj._x;
if (cord.keys[0].time > t || t > cord.keys[cord.keys.length - 1].time) {
return -1;
}
cord.start = 0;
cord.end = cord.keys.length - 2;
cord.middle = Math.floor((cord.start + cord.end) / 2);
while (!(cord.keys[cord.middle].time <= t && t <= cord.keys[cord.middle + 1].time)) {
if (cord.keys[cord.middle].time > t) {
cord.end = cord.middle;
} else if (cord.keys[cord.middle + 1].time < t) {
cord.start = cord.middle + 1;
}
cord.middle = Math.floor((cord.start + cord.end) / 2);
}
obj.localT = (t - cord.keys[cord.middle].time) / (cord.keys[cord.middle + 1].time - cord.keys[cord.middle].time);
return cord.middle;
}
function GetFrame(obj, i, t) {
if (obj._type == motion_line) {
return LineMotion(obj.keys[i], obj.keys[i + 1], t);
} else if (obj._type == motion_discontinuous) {
return obj.keys[i].value;
} else {
return SplineMotion(obj.keys[i], obj.keys[i + 1],
obj.keys[i], obj.keys[i + 1], t);
}
}
function Point2D() {
this.x = 0;
this.y = 0;
return this;
}
function Read(xe, name, defaultValue) {
var tmp = xe.attributes.getNamedItem(name);
return (tmp ? +tmp.value : defaultValue);
}
function Matrix() {
this._matrix = [
[1,0,0],
[0,1,0],
[0,0,1]
];
this.MulM = function (m) {
var m00 = m[0][0],
m01 = m[0][1],
m02 = m[0][2],
m10 = m[1][0],
m11 = m[1][1],
m12 = m[1][2],
m20 = m[2][0],
m21 = m[2][1],
m22 = m[2][2],
n00 = this._matrix[0][0],
n01 = this._matrix[0][1],
n02 = this._matrix[0][2],
n10 = this._matrix[1][0],
n11 = this._matrix[1][1],
n12 = this._matrix[1][2],
n20 = this._matrix[2][0],
n21 = this._matrix[2][1],
n22 = this._matrix[2][2];
this._matrix[0][0] = m00 * n00 + m01 * n10 + m02 * n20;
this._matrix[0][1] = m00 * n01 + m01 * n11 + m02 * n21;
this._matrix[0][2] = m00 * n02 + m01 * n12 + m02 * n22;
this._matrix[1][0] = m10 * n00 + m11 * n10 + m12 * n20;
this._matrix[1][1] = m10 * n01 + m11 * n11 + m12 * n21;
this._matrix[1][2] = m10 * n02 + m11 * n12 + m12 * n22;
this._matrix[2][0] = m20 * n00 + m21 * n10 + m22 * n20;
this._matrix[2][1] = m20 * n01 + m21 * n11 + m22 * n21;
this._matrix[2][2] = m20 * n02 + m21 * n12 + m22 * n22;
};
this.Unit = function () {
this._matrix[0][0] = 1;
this._matrix[0][1] = 0;
this._matrix[0][2] = 0;
this._matrix[1][0] = 0;
this._matrix[1][1] = 1;
this._matrix[1][2] = 0;
this._matrix[2][0] = 0;
this._matrix[2][1] = 0;
this._matrix[2][2] = 1;
};
this.Assign = function (m) {
this._matrix[0][0] = m._matrix[0][0];
this._matrix[0][1] = m._matrix[0][1];
this._matrix[0][2] = m._matrix[0][2];
this._matrix[1][0] = m._matrix[1][0];
this._matrix[1][1] = m._matrix[1][1];
this._matrix[1][2] = m._matrix[1][2];
this._matrix[2][0] = m._matrix[2][0];
this._matrix[2][1] = m._matrix[2][1];
this._matrix[2][2] = m._matrix[2][2];
};
var tmp = [
[],
[],
[]
];
this.Rotate = function (angle) {
tmp[0][0] = Math.cos(angle);
tmp[0][1] = Math.sin(angle);
tmp[0][2] = 0;
tmp[1][0] = -Math.sin(angle);
tmp[1][1] = Math.cos(angle);
tmp[1][2] = 0;
tmp[2][0] = 0;
tmp[2][1] = 0;
tmp[2][2] = 1;
this.MulM(tmp);
};
this.Scale = function (scx, scy) {
tmp[0][0] = scx;
tmp[0][1] = 0;
tmp[0][2] = 0;
tmp[1][0] = 0;
tmp[1][1] = scy;
tmp[1][2] = 0;
tmp[2][0] = 0;
tmp[2][1] = 0;
tmp[2][2] = 1;
this.MulM(tmp);
};
this.Move = function (x, y) {
tmp[0][0] = 1.0;
tmp[0][1] = 0.0;
tmp[0][2] = 0;
tmp[1][0] = 0.0;
tmp[1][1] = 1.0;
tmp[1][2] = 0;
tmp[2][0] = x;
tmp[2][1] = y;
tmp[2][2] = 1;
this.MulM(tmp);
};
this.MulMatrix = function (transform) {
this.MulM(transform._matrix);
};
this.MulXY = function (sx, sy, x, y) {
x[0] = this._matrix[0][0] * sx + this._matrix[1][0] * sy + this._matrix[2][0];
y[0] = this._matrix[0][1] * sx + this._matrix[1][1] * sy + this._matrix[2][1];
};
this.Determinant = function () {
return this._matrix[0][0] * this._matrix[1][1] * this._matrix[2][2]
- this._matrix[0][0] * this._matrix[1][2] * this._matrix[2][1]
- this._matrix[0][1] * this._matrix[1][0] * this._matrix[2][2]
+ this._matrix[0][1] * this._matrix[1][2] * this._matrix[2][0]
+ this._matrix[0][2] * this._matrix[1][0] * this._matrix[2][1]
- this._matrix[0][2] * this._matrix[1][1] * this._matrix[2][0];
};
this.Flip = function () {
var t;
t = this._matrix[1][0];
this._matrix[1][0] = this._matrix[0][1];
this._matrix[0][1] = t;
t = this._matrix[1][2];
this._matrix[1][2] = this._matrix[2][1];
this._matrix[2][1] = t;
t = this._matrix[2][0];
this._matrix[2][0] = this._matrix[0][2];
this._matrix[0][2] = t;
};
this.Mul = function (f) {
this._matrix[0][0] *= f;
this._matrix[1][0] *= f;
this._matrix[2][0] *= f;
this._matrix[0][1] *= f;
this._matrix[1][1] *= f;
this._matrix[2][1] *= f;
this._matrix[0][2] *= f;
this._matrix[1][2] *= f;
this._matrix[2][2] *= f;
};
this.MakeRevers = function (transform) {
var det = transform.Determinant();
this._matrix[0][0] = (transform._matrix[1][1] * transform._matrix[2][2] - transform._matrix[2][1] * transform._matrix[1][2]);
this._matrix[1][0] = -(transform._matrix[0][1] * transform._matrix[2][2] - transform._matrix[2][1] * transform._matrix[0][2]);
this._matrix[2][0] = (transform._matrix[0][1] * transform._matrix[1][2] - transform._matrix[1][1] * transform._matrix[0][2]);
this._matrix[0][1] = -(transform._matrix[1][0] * transform._matrix[2][2] - transform._matrix[2][0] * transform._matrix[1][2]);
this._matrix[1][1] = (transform._matrix[0][0] * transform._matrix[2][2] - transform._matrix[2][0] * transform._matrix[0][2]);
this._matrix[2][1] = -(transform._matrix[0][0] * transform._matrix[1][2] - transform._matrix[1][0] * transform._matrix[0][2]);
this._matrix[0][2] = (transform._matrix[1][0] * transform._matrix[2][1] - transform._matrix[2][0] * transform._matrix[1][1]);
this._matrix[1][2] = -(transform._matrix[0][0] * transform._matrix[2][1] - transform._matrix[2][0] * transform._matrix[0][1]);
this._matrix[2][2] = (transform._matrix[0][0] * transform._matrix[1][1] - transform._matrix[1][0] * transform._matrix[0][1]);
this.Flip();
this.Mul(1 / det);
};
this.ApplyTransform = function (context) {
context.transform(this._matrix[0][0], this._matrix[0][1], this._matrix[1][0], this._matrix[1][1], this._matrix[2][0], this._matrix[2][1])
};
return this;
}
function MovingPart(animation, xe, texture) {
this.boneName;
this._center = new Point2D();
this._x = new MotionValues();
this._y = new MotionValues();
this._angle = new MotionValues();
this._scaleX = new MotionValues();
this._scaleY = new MotionValues();
this._movingType;
this._bones = [];
this._order;
this._texture;
this._center = new Point2D();
// sprite's texture coords
this._sx;
this._sy;
this._sw;
this._sh;
this._offsetx;
this._offsety;
this._visible = false;
this._screenMatrix = new Matrix();
this.MovingPart_constructor = function (animation, xe, texture) {
animation.AddBone(this);
this._texture = texture;
this.boneName = xe.attributes.getNamedItem("name").value;
var tmp = xe.attributes.getNamedItem("moving_type") && xe.attributes.getNamedItem("moving_type").value;
if (!tmp || tmp == "spline") {
this._movingType = motion_spline;
} else if (tmp == "line") {
this._movingType = motion_line;
} else {
this._movingType = motion_discontinuous;
}
this._order = +xe.attributes.getNamedItem("order").value;
this._center.x = Read(xe, "centerX", 0);
this._center.y = Read(xe, "centerY", 0);
var description = xe.attributes.getNamedItem("texture").value;
CreateQuad(texture, description, this);
var poses = xe.getElementsByTagName("pos");
if (poses.length == 0) {
this._x.AddKey(0, 0);
this._y.AddKey(0, 0);
this._scaleX.AddKey(0, 1);
this._scaleY.AddKey(0, 1);
this._angle.AddKey(0, 0);
}
else {
for (var i = 0; i < poses.length; ++i) {
if (poses.item(i).parentNode == xe) {
var time = Read(poses.item(i), "time", 0);
this._x.AddKey(time, Read(poses.item(i), "x", 0));
this._y.AddKey(time, Read(poses.item(i), "y", 0));
this._scaleX.AddKey(time, Read(poses.item(i), "scaleX", 1));
this._scaleY.AddKey(time, Read(poses.item(i), "scaleY", 1));
this._angle.AddKey(time, Read(poses.item(i), "angle", 0));
}
}
}
this._x.SetType(this._movingType);
this._y.SetType(this._movingType);
this._scaleX.SetType(this._movingType);
this._scaleY.SetType(this._movingType);
this._angle.SetType(this._movingType);
var elements = xe.getElementsByTagName("movingPart");
for (var i = 0; i < elements.length; ++i) {
if (elements.item(i).parentNode == xe) {
this._bones.push(new MovingPart(animation, elements.item(i), texture));
}
}
};
this.localT = 0;
this.PreDraw = function (p, stack) {
var index = Value(p, this);
if (this._visible = (index >= 0)) {
this._screenMatrix.Assign(stack);
this._screenMatrix.Move(GetFrame(this._x, index, this.localT), GetFrame(this._y, index, this.localT));
this._screenMatrix.Rotate(GetFrame(this._angle, index, this.localT));
this._screenMatrix.Scale(GetFrame(this._scaleX, index, this.localT), GetFrame(this._scaleY, index, this.localT));
this._screenMatrix.Move(-this._center.x, -this._center.y);
for (var i = 0; i < this._bones.length; ++i) {
this._bones[i].PreDraw(p, this._screenMatrix);
}
}
};
this.Draw = function (context) {
if (this._visible) {
this._screenMatrix.ApplyTransform(context);
context.drawImage(this._texture
, this._sx, this._sy, this._sw, this._sh,
0, 0, this._sw, this._sh);
}
};
var CreateQuad = function (texture, description, obj) {
obj._texture = texture;
var desArr = description.split(":");
obj._sx = +desArr[0];
obj._sy = +desArr[1];
obj._sw = +desArr[2];
obj._sh = +desArr[3];
obj._offsetx = +desArr[4];
obj.offsety = +desArr[5];
};
this.MovingPart_constructor(animation, xe, texture);
this.MovingPart_constructor = null;
return this;
}
function CmpMovingPart(one, two) {
return one._order - two._order;
}
function Animation(xe, texture) {
this._pivotPos = new Point2D();
this._bones = [];
this._matrix = new Matrix();
this._renderList = [];
this.SetPos = function (x, y, mirror) {
this._matrix.Unit();
this._matrix.Move(x, y);
if (mirror) {
this._matrix.Scale(-1, 1);
}
};
this.AddBone = function (bone) {
this._renderList.push(bone);
};
this.Draw = function (context, position) {
for (var i = 0; i < this._renderList.length; ++i) {
this._renderList[i]._visible = false;
}
for (var i = 0; i < this._bones.length; ++i) {
this._bones[i].PreDraw(position, this._matrix);
}
for (var i = 0; i < this._renderList.length; ++i) {
context.save();
this._renderList[i].Draw(context);
context.restore();
//context.setTransform(1, 0, 0, 1, 0, 0);
}
};
this.Time = function () {
return this._time;
};
this.position = 0;
this.SetFPS = function (value) {
this.fps = value;
};
this.Update = function () {
this.position += 1 / this.fps / this._time;
while (this.position > 1) {
this.position -= 1;
}
};
this.DrawAtPoint = function (context, x, y, mirror) {
this.SetPos(x, y, mirror != "undefined" ? mirror : false);
this.Draw(context, this.position);
};
this._time = +xe.attributes.getNamedItem("time").value;
this._pivotPos.x = +xe.attributes.getNamedItem("pivotX").value;
this._pivotPos.y = +xe.attributes.getNamedItem("pivotY").value;
var elements = xe.getElementsByTagName("movingPart");
for (i = 0; i < elements.length; ++i) {
if (elements.item(i).parentNode == xe) {
this._bones.push(new MovingPart(this, elements.item(i), texture));
}
}
this._renderList.sort(CmpMovingPart);
return this;
}
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
function AnimationsCollection(name, onReady) {
this.animations = [];
this.callOnReady = onReady;
this.fileName = name;
this.load = function () {
this.imageObj = new Image();
this.imageObj.src = this.fileName + ".png";
this.imageObj.onload = this.onImageLoad(this);
};
this.onImageLoad = function (obj) {
var xmlDoc = loadXMLDoc(obj.fileName + ".xml");
var elements = xmlDoc.getElementsByTagName("Animation");
for (var i = 0; i < elements.length; ++i) {
var name = elements.item(i).attributes.getNamedItem("id").value;
obj.animations[name] = new Animation(elements.item(i), obj.imageObj);
}
obj.callOnReady();
};
this.get = function (id) {
return this.animations[id];
};
return this;
}
| JavaScript |
/**
*
* 1.获得数组中不重复的项目
*
* @param {Array} a 可能包含重复元素的数组
* @returns {Array} 返回一个不包含重复元素的新数组
*/
function unique(a) {
var temp_array = new Array();
for(var index in a){
temp_array.push(a[index]);
}
var return_array = new Array();
}
/**
* 2.同jQuery.map方法
*/
function mapArray(a,f) {
}
/**
* 3. 同jQuery.trim
*/
function trim(s) {
}
/**
* 4. escapeHTML,将字符串中的<,>,&,"转换成对应实体
* 同PHP中的htmlspecialchars方法
*
* @param {String} s 可能包含HTML特殊字符的字符串
* @returns {String} 返回escape之后的字符串
*/
function escapeHTML(s) {
}
//实现以下几个和PHP中对应函数功能相同的JS函数
//5.实现和PHP中str_repeat功能一样的函数
//6.array_filter
//7.array_sum
//8.in_array
//9.is_array
//10.array_keys
//11.get_object_vars | JavaScript |
/*
下面的一些函数实现都是实现和jQuery中的方法类似的功能,你可以完成后和jQuery中对应函数返回結果比较一下
1.
实现jQuery中的:
addClass,
removeClass,
hasClass三个函数,
函数签名如下,完成下面的代码
//下面是文档注释,你可以看一下jsdoc这个项目,里面有下面注释含义的说明
@param {HTMLElement} ele
@param {String|[]String} classNames
*/
function addClass(ele,classNames){
if(Object.prototype.toString.call(classNames) == '[object Array]'){ //判断是否为数组
for(i=0;i<classNames.length;i++){
ele.className += " "+classNames[i];
}
}else{
if(!ele.className){
ele.className = classNames;
}else{
ele.className += " ";
ele.className += classNames;
}
}
}
function removeClass(ele,classNames) {
if(Object.prototype.toString.call(classNames) == '[object Array]'){
for(var i=0;i<classNames.length;i++){
ele.className = ele.className.replace(classNames[i],"");
}
}else{
ele.className="";
}
}
function hasClass(ele,classNames) {
if(Object.prototype.toString.call(classNames) == '[object Array]'){
for(var i=0;i<classNames.length;i++){
if(ele.className.match(classNames[i])) return true;
}
}else{
if(ele.className.match(classNames)) return true;
}
}
/*2.实现jQuery中的width与height方法:*/
/*JS获取外部CSS样式方法(只能获取,无法设置样式!)
currentStyle //ie
getComputedStyle //w3c
*/
function getLinkStyle(ele){
if(navigator.userAgent.indexOf("MSIE")>0){ //判断是否为IE浏览器
var style = ele.currentStyle; //IE浏览器。接口:元素名.currentStyle
}else{ //For W3C ,非IE浏览器。接口:document.defauleView.getComputedStyle(元素名,伪元素":after"[不需要伪元素就null])
var style = document.defaultView.getComputedStyle(ele,null);
}
return style;
}
function getWidth(ele) {
var style = getLinkStyle(ele);
return style.width;
}
function getHeight(ele) {
var style = getLinkStyle(ele);
return style.height;
}
/*
3.实现jQuery中的css方法
@param {String} name css名称,如color,font-size,padding等
@returns {String} 返回CSS设置的值
*/
function css(ele,name) {
var style = getLinkStyle(ele);
return style.name;
}
/*
4.设置DOM元素的透明度
@param {Number} opacity 为透明度值,0到1之间的小数,(同CSS规范中的opacity)
*/
function setOpacity(ele,opacity) {
if(opacity >= 0 && opacity <= 1){
ele.style.opacity = opacity;
}else{
alert("警告:不透明度取值范围是0~1间的小数!");
}
}
/*
5.将一个元素的左上角与另一个元素的左上角对齐,使用绝对定位
将ele设为绝对定位,将它的左上角和to的左上角对齐
@param {HTMLElement} to 作为对齐参考对象的元素
*/
function alignTo(ele,to) {
var css = getLinkStyle(to);
var to_left = parseFloat(css.left);
var to_top = parseFloat(css.top);
ele.style.position = "absolute";
ele.style.left = to_left+"px";
ele.style.top = to_top+"px";
} | JavaScript |
/*
1.判断一个对象是否具有指定的方法
@param {Object} obj
@param {[]String} methodNames 方法名称
@returns {Boolean} 如果obj具有methodNames列出来的方法,返回true
如
isImplements({
method1:function () {}
},["method1"]) 返回true
isImplements({
method1:function () {}
},["getName"]) 返回false
*/
function isImplements(obj,methodNames) {
var methods = "";
for(var method in obj){
methods = method;
}
if(Object.prototype.toString.call(methodNames) == '[object Array]'){
for(var i=0;i<methodNames.length;i++){
if(methods == methodNames[i]) return true;
else return false;
}
}else{
if(methods == methodNames) return true;
else return false;
}
}
/*
2.实现类似jQuery中的each方法
@param {Array} list
@param {Function} f
*/
function each(list,f) {
}
/*
3.下面是一个简单的动画函数,将ele从页面中从左往右飞行,但是有错误,找出错误的原因,将它修改正确
@param {HTMLElement} ele
*/
function animateFly(ele) {
var max=600;
ele.style.position = "absolute";
for (var i=0;i<max;i++){
setTimeout(function(){
ele.style.left = i+"px";
},i*10);
}
}
var i=0;
function animateFly(fly){
if(i<600)
{
css = fly.style;
css.position = "absolute";
css.left=i+"px";
i++;
setTimeout('animateFly(fly)',600/i);
}
}
setTimeout('animateFly(fly)',600/i);
/*
function animate(){
var ele = document.getElementById("fly");
var left = parseFloat(ele.style.left);
var top = parseFloat(ele.style.top);
if(left < 500)
{
left++;
}
if(left > 500)
{
left--;
}
if(top < 500)
{
top++;
}
if(top > 500)
{
top--;
}
ele.style.left = left+"px";
ele.style.top = top+"px";
move = setTimeout("animate()",10);
}
*/
/*
4.实现Class构造器,使得下面的testClassImplement能正确运行
*/
function Class(methods) {
}
function testClassImplement() {
//保证Class构造函数的实现能使此函数正确运行,不会抛出错误
var Person=new Class({
getName:function () {
return this.name;
},
setName:function (name) {
this.name=name;
},
getAge:function () {
return this.age;
},
constructor:function (name,age) {
this.name=name;
this.age=age;
}
});
var CJ="CJ",age=21;
var p1=new Person(CJ,age);
assert(p1.getName(),CJ);
assert(p1.getAge(),age);
}
function assert(a,b) {
if (a!==b) {
throw new Error('期望返回值为:'+b+",但得到的返回值却是:"+a);
}
} | JavaScript |
/**
* @version $Id: k2tags.js 1919 2013-02-11 19:02:02Z joomlaworks $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
$K2(document).ready(function() {
// Generic function to get URL params passed in .js script include
function getUrlParams(targetScript, varName) {
var scripts = document.getElementsByTagName('script');
var scriptCount = scripts.length;
for (var a = 0; a < scriptCount; a++) {
var scriptSrc = scripts[a].src;
if (scriptSrc.indexOf(targetScript) >= 0) {
varName = varName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var re = new RegExp("[\\?&]" + varName + "=([^&#]*)");
var parsedVariables = re.exec(scriptSrc);
if (parsedVariables !== null) {
return parsedVariables[1];
}
}
}
}
// Set the site root path
var K2SitePath = getUrlParams('k2.js', 'sitepath');
$K2('.tagRemove').click(function(event) {
event.preventDefault();
$K2(this).parent().remove();
});
/*
$K2('ul.tags').click(function() {
//$K2('#search-field').focus();
});
*/
$K2('.k2-search-field').keypress(function(event) {
if (event.which == '13') {
if ($K2(this).val() != '') {
$K2('<li id="' + this.attributes['rel'].value + '_tagAdd" class="addedTag">' + $K2(this).val() + '<span class="tagRemove" onclick="Josetta.itemChanged('+this.id+');$K2(this).parent().remove();">x</span><input type="hidden" value="' + $K2(this).val() + '" name="'+this.attributes['rel'].value + '[tags][]"></li>').insertBefore('.tags #' + this.attributes['rel'].value + '_tagAdd.tagAdd');
Josetta.itemChanged(this);
$K2(this).val('');
}
}
});
$K2('.k2-search-field').autocomplete({
source : function(request, response) {
var target = this.element[0];
$K2.ajax({
type : 'post',
url : K2SitePath + 'index.php?option=com_k2&view=item&task=tags',
data : 'q=' + request.term,
dataType : 'json',
success : function(data) {
target.removeClass('tagsLoading');
response($K2.map(data, function(item) {
return item;
}));
}
});
},
minLength : 3,
select : function(event, ui) {
$K2('<li id="' + this.attributes['rel'].value + '_tagAdd" class="addedTag">' + ui.item.label + '<span class="tagRemove" onclick="Josetta.itemChanged('+this.id+');$K2(this).parent().remove();">x</span><input type="hidden" value="' + ui.item.value + '" name="'+this.attributes['rel'].value + '[tags][]"></li>').insertBefore('.tags #' + this.attributes['rel'].value + '_tagAdd.tagAdd');
Josetta.itemChanged(this);
this.value = '';
return false;
},
search : function(event, ui) {
event.target.addClass('tagsLoading');
}
});
}); | JavaScript |
/**
* @version $Id: k2extrafields.js 1812 2013-01-14 18:45:06Z lefteris.kavadas $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
$K2(document).ready(function() {
extraFields();
setTimeout(function() {
initExtraFieldsEditor();
}, 1000);
$K2('[id$=josetta_form_catid]').change(function() {
if ($K2(this).find('option:selected').attr('disabled')) {
alert(K2Language[4]);
$K2(this).val('0');
return;
}
extraFields();
});
});
function extraFields() {
var selectedValue = $K2('[id$=josetta_form_catid]').val();
var url = K2BasePath + '/index.php?option=com_k2&view=item&task=extraFields&cid=' + selectedValue + '&id=' + Josetta.josettaItemid;
$K2('#extraFieldsContainer').fadeOut('slow', function() {
$K2.ajax({
url : url,
type : 'get',
success : function(response) {
$K2('#extraFieldsContainer').html(response);
initExtraFieldsEditor();
$K2('img.calendar').each(function() {
inputFieldID = $K2(this).prev().attr('id');
imgFieldID = $K2(this).attr('id');
Calendar.setup({
inputField : inputFieldID,
ifFormat : "%Y-%m-%d",
button : imgFieldID,
align : "Tl",
singleClick : true
});
});
$K2('#extraFieldsContainer').fadeIn('slow');
}
});
});
}
function initExtraFieldsEditor() {
$K2('.k2ExtraFieldEditor').each(function() {
var id = $K2(this).attr('id');
if ( typeof tinymce != 'undefined') {
if (tinyMCE.get(id)) {
tinymce.EditorManager.remove(tinyMCE.get(id));
}
tinyMCE.execCommand('mceAddControl', false, id);
} else {
new nicEditor({
fullPanel : true,
maxHeight : 180,
iconsPath : K2BasePath + '/media/k2/assets/images/system/nicEditorIcons.gif'
}).panelInstance($K2(this).attr('id'));
}
});
}
function syncExtraFieldsEditor() {
$K2('.k2ExtraFieldEditor').each(function() {
editor = nicEditors.findEditor($K2(this).attr('id'));
if ( typeof editor != 'undefined') {
if (editor.content == '<br>' || editor.content == '<br />') {
editor.setContent('');
}
editor.saveContent();
}
});
} | JavaScript |
/**
* @version $Id: k2.js 1987 2013-06-27 11:51:59Z lefteris.kavadas $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
var $K2 = jQuery.noConflict();
$K2(document).ready(function(){
// Generic function to get URL params passed in .js script include
function getUrlParams(targetScript, varName) {
var scripts = document.getElementsByTagName('script');
var scriptCount = scripts.length;
for (var a = 0; a < scriptCount; a++) {
var scriptSrc = scripts[a].src;
if (scriptSrc.indexOf(targetScript) >= 0) {
varName = varName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var re = new RegExp("[\\?&]" + varName + "=([^&#]*)");
var parsedVariables = re.exec(scriptSrc);
if (parsedVariables !== null) {
return parsedVariables[1];
}
}
}
}
// Set the site root path
var K2SitePath = getUrlParams('k2.js', 'sitepath');
// Comments
$K2('#comment-form').submit(function(event){
event.preventDefault();
$K2('#formLog').empty().addClass('formLogLoading');
$K2.ajax({
url: $K2('#comment-form').attr('action'),
type: 'post',
dataType: 'json',
data: $K2('#comment-form').serialize(),
success: function(response){
$K2('#formLog').removeClass('formLogLoading').html(response.message);
if(typeof(Recaptcha) != "undefined"){
Recaptcha.reload();
}
if (response.refresh) {
window.location.reload();
}
}
});
});
$K2('.commentRemoveLink').click(function(event){
event.preventDefault();
var element = $K2(this);
$K2(element).parent().addClass('commentToolbarLoading');
$K2.ajax({
url: $K2(element).attr('href'),
type: 'post',
data: $K2('#comment-form input:last').serialize(),
success: function(response){
$K2(element).parent().removeClass('commentToolbarLoading');
if(response=='true'){
$K2(element).parent().parent().remove();
}
}
});
});
$K2('.commentApproveLink').click(function(event){
event.preventDefault();
var element = $K2(this);
$K2(element).parent().addClass('commentToolbarLoading');
$K2.ajax({
url: $K2(element).attr('href'),
type: 'post',
data: $K2('#comment-form input:last').serialize(),
success: function(response){
$K2(element).parent().removeClass('commentToolbarLoading');
if(response=='true'){
$K2(element).parent().parent().removeClass('unpublishedComment');
}
}
});
});
$K2('.k2ReportUserButton').click(function(event){
event.preventDefault();
if (confirm(K2Language[0])) {
var element = $K2(this);
$K2(element).parent().addClass('commentToolbarLoading');
$K2.ajax({
url: $K2(element).attr('href'),
type: 'GET',
success: function(response){
$K2(element).parent().removeClass('commentToolbarLoading');
alert(response);
}
});
}
});
$K2('#k2ReportCommentForm').submit(function(event){
event.preventDefault();
$K2('#formLog').empty().addClass('formLogLoading');
$K2.ajax({
url: $K2('#k2ReportCommentForm').attr('action'),
type: 'post',
data: $K2('#k2ReportCommentForm').serialize(),
success: function(response){
$K2('#formLog').removeClass('formLogLoading').html(response);
if(typeof(Recaptcha) != "undefined"){
Recaptcha.reload();
}
}
});
});
// Text Resizer
$K2('#fontDecrease').click(function(event){
event.preventDefault();
$K2('.itemFullText').removeClass('largerFontSize');
$K2('.itemFullText').addClass('smallerFontSize');
});
$K2('#fontIncrease').click(function(event){
event.preventDefault();
$K2('.itemFullText').removeClass('smallerFontSize');
$K2('.itemFullText').addClass('largerFontSize');
});
// Smooth Scroll
$K2('.k2Anchor').click(function(event){
event.preventDefault();
var target = this.hash;
$K2('html, body').stop().animate({
scrollTop: $K2(target).offset().top
}, 500);
});
// Rating
$K2('.itemRatingForm a').click(function(event){
event.preventDefault();
var itemID = $K2(this).attr('rel');
var log = $K2('#itemRatingLog' + itemID).empty().addClass('formLogLoading');
var rating = $K2(this).html();
$K2.ajax({
url: K2SitePath+"index.php?option=com_k2&view=item&task=vote&format=raw&user_rating=" + rating + "&itemID=" + itemID,
type: 'get',
success: function(response){
log.removeClass('formLogLoading');
log.html(response);
$K2.ajax({
url: K2SitePath+"index.php?option=com_k2&view=item&task=getVotesPercentage&format=raw&itemID=" + itemID,
type: 'get',
success: function(percentage){
$K2('#itemCurrentRating' + itemID).css('width', percentage + "%");
setTimeout(function(){
$K2.ajax({
url: K2SitePath+"index.php?option=com_k2&view=item&task=getVotesNum&format=raw&itemID=" + itemID,
type: 'get',
success: function(response){
log.html(response);
}
});
}, 2000);
}
});
}
});
});
// Classic popup
$K2('.classicPopup').click(function(event){
event.preventDefault();
if($K2(this).attr('rel')){
var json = $K2(this).attr('rel');
json = json.replace(/'/g, '"');
var options = $K2.parseJSON(json);
} else {
var options = {x:900,y:600}; /* use some default values if not defined */
}
window.open($K2(this).attr('href'),'K2PopUpWindow','width='+options.x+',height='+options.y+',menubar=yes,resizable=yes');
});
// Live search
$K2('div.k2LiveSearchBlock form input[name=searchword]').keyup(function(event){
var parentElement = $K2(this).parent().parent();
if($K2(this).val().length>3 && event.key!='enter'){
$K2(this).addClass('k2SearchLoading');
parentElement.find('.k2LiveSearchResults').css('display','none').empty();
parentElement.find('input[name=t]').val($K2.now());
parentElement.find('input[name=format]').val('raw');
var url = 'index.php?option=com_k2&view=itemlist&task=search&' + parentElement.find('form').serialize();
parentElement.find('input[name=format]').val('html');
$K2.ajax({
url: url,
type: 'get',
success: function(response){
parentElement.find('.k2LiveSearchResults').html(response);
parentElement.find('input[name=searchword]').removeClass('k2SearchLoading');
parentElement.find('.k2LiveSearchResults').css('display', 'block');
}
});
} else {
parentElement.find('.k2LiveSearchResults').css('display','none').empty();
}
});
// Calendar
if (typeof($K2().live) == "undefined") {
$K2('.k2CalendarBlock').on('click', '.calendarNavLink', function(event){
event.preventDefault();
var parentElement = $K2(this).parent().parent().parent().parent();
var url = $K2(this).attr('href');
parentElement.empty().addClass('k2CalendarLoader');
$K2.ajax({
url: url,
type: 'post',
success: function(response){
parentElement.html(response);
parentElement.removeClass('k2CalendarLoader');
}
});
});
}
else {
$K2('a.calendarNavLink').live('click', function(event){
event.preventDefault();
var parentElement = $K2(this).parent().parent().parent().parent();
var url = $K2(this).attr('href');
parentElement.empty().addClass('k2CalendarLoader');
$K2.ajax({
url: url,
type: 'post',
success: function(response){
parentElement.html(response);
parentElement.removeClass('k2CalendarLoader');
}
});
});
}
// Generic Element Scroller (use .k2Scroller in the container and .k2ScrollerElement for each contained element)
$K2('.k2Scroller').css('width',($K2('.k2Scroller').find('.k2ScrollerElement:first').outerWidth(true))*$K2('.k2Scroller').children('.k2ScrollerElement').length);
});
// Equal block heights for the "default" view
$K2(window).load(function () {
var blocks = $K2('.subCategory, .k2EqualHeights');
var maxHeight = 0;
blocks.each(function(){
maxHeight = Math.max(maxHeight, parseInt($K2(this).css('height')));
});
blocks.css('height', maxHeight);
});
| JavaScript |
/* Tokenizer for JavaScript code */
var tokenizeJavaScript = (function() {
// Advance the stream until the given character (not preceded by a
// backslash) is encountered, or the end of the line is reached.
function nextUntilUnescaped(source, end) {
var escaped = false;
while (!source.endOfLine()) {
var next = source.next();
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// A map of JavaScript's keywords. The a/b/c keyword distinction is
// very rough, but it gives the parser enough information to parse
// correct code correctly (we don't care that much how we parse
// incorrect code). The style information included in these objects
// is used by the highlighter to pick the correct CSS style for a
// token.
var keywords = function(){
function result(type, style){
return {type: type, style: "js-" + style};
}
// keywords that take a parenthised expression, and then a
// statement (if)
var keywordA = result("keyword a", "keyword");
// keywords that take just a statement (else)
var keywordB = result("keyword b", "keyword");
// keywords that optionally take an expression, and form a
// statement (return)
var keywordC = result("keyword c", "keyword");
var operator = result("operator", "keyword");
var atom = result("atom", "atom");
return {
"if": keywordA, "while": keywordA, "with": keywordA,
"else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB,
"return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC,
"in": operator, "typeof": operator, "instanceof": operator,
"var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"),
"for": result("for", "keyword"), "switch": result("switch", "keyword"),
"case": result("case", "keyword"), "default": result("default", "keyword"),
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
};
}();
// Some helper regexps
var isOperatorChar = /[+\-*&%=<>!?|]/;
var isHexDigit = /[0-9A-Fa-f]/;
var isWordChar = /[\w\$_]/;
// Wrapper around jsToken that helps maintain parser state (whether
// we are inside of a multi-line comment and whether the next token
// could be a regular expression).
function jsTokenState(inside, regexp) {
return function(source, setState) {
var newInside = inside;
var type = jsToken(inside, regexp, source, function(c) {newInside = c;});
var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/);
if (newRegexp != regexp || newInside != inside)
setState(jsTokenState(newInside, newRegexp));
return type;
};
}
// The token reader, intended to be used by the tokenizer from
// tokenize.js (through jsTokenState). Advances the source stream
// over a token, and returns an object containing the type and style
// of that token.
function jsToken(inside, regexp, source, setInside) {
function readHexNumber(){
source.next(); // skip the 'x'
source.nextWhileMatches(isHexDigit);
return {type: "number", style: "js-atom"};
}
function readNumber() {
source.nextWhileMatches(/[0-9]/);
if (source.equals(".")){
source.next();
source.nextWhileMatches(/[0-9]/);
}
if (source.equals("e") || source.equals("E")){
source.next();
if (source.equals("-"))
source.next();
source.nextWhileMatches(/[0-9]/);
}
return {type: "number", style: "js-atom"};
}
// Read a word, look it up in keywords. If not found, it is a
// variable, otherwise it is a keyword of the type found.
function readWord() {
source.nextWhileMatches(isWordChar);
var word = source.get();
var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
return known ? {type: known.type, style: known.style, content: word} :
{type: "variable", style: "js-variable", content: word};
}
function readRegexp() {
nextUntilUnescaped(source, "/");
source.nextWhileMatches(/[gimy]/); // 'y' is "sticky" option in Mozilla
return {type: "regexp", style: "js-string"};
}
// Mutli-line comments are tricky. We want to return the newlines
// embedded in them as regular newline tokens, and then continue
// returning a comment token for every line of the comment. So
// some state has to be saved (inside) to indicate whether we are
// inside a /* */ sequence.
function readMultilineComment(start){
var newInside = "/*";
var maybeEnd = (start == "*");
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == "/" && maybeEnd){
newInside = null;
break;
}
maybeEnd = (next == "*");
}
setInside(newInside);
return {type: "comment", style: "js-comment"};
}
function readOperator() {
source.nextWhileMatches(isOperatorChar);
return {type: "operator", style: "js-operator"};
}
function readString(quote) {
var endBackSlash = nextUntilUnescaped(source, quote);
setInside(endBackSlash ? quote : null);
return {type: "string", style: "js-string"};
}
// Fetch the next token. Dispatches on first character in the
// stream, or first two characters when the first is a slash.
if (inside == "\"" || inside == "'")
return readString(inside);
var ch = source.next();
if (inside == "/*")
return readMultilineComment(ch);
else if (ch == "\"" || ch == "'")
return readString(ch);
// with punctuation, the type of the token is the symbol itself
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return {type: ch, style: "js-punctuation"};
else if (ch == "0" && (source.equals("x") || source.equals("X")))
return readHexNumber();
else if (/[0-9]/.test(ch))
return readNumber();
else if (ch == "/"){
if (source.equals("*"))
{ source.next(); return readMultilineComment(ch); }
else if (source.equals("/"))
{ nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};}
else if (regexp)
return readRegexp();
else
return readOperator();
}
else if (isOperatorChar.test(ch))
return readOperator();
else
return readWord();
}
// The external interface to the tokenizer.
return function(source, startState) {
return tokenizer(source, startState || jsTokenState(false, true));
};
})();
| JavaScript |
var SparqlParser = Editor.Parser = (function() {
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
"isblank", "isliteral", "union", "a"]);
var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
"ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
"graph", "by", "asc", "desc"]);
var operatorChars = /[*+\-<>=&|]/;
var tokenizeSparql = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "$" || ch == "?") {
source.nextWhileMatches(/[\w\d]/);
return "sp-var";
}
else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) {
source.nextWhileMatches(/[^\s\u00a0>]/);
if (source.equals(">")) source.next();
return "sp-uri";
}
else if (ch == "\"" || ch == "'") {
setState(inLiteral(ch));
return null;
}
else if (/[{}\(\),\.;\[\]]/.test(ch)) {
return "sp-punc";
}
else if (ch == "#") {
while (!source.endOfLine()) source.next();
return "sp-comment";
}
else if (operatorChars.test(ch)) {
source.nextWhileMatches(operatorChars);
return "sp-operator";
}
else if (ch == ":") {
source.nextWhileMatches(/[\w\d\._\-]/);
return "sp-prefixed";
}
else {
source.nextWhileMatches(/[_\w\d]/);
if (source.equals(":")) {
source.next();
source.nextWhileMatches(/[\w\d_\-]/);
return "sp-prefixed";
}
var word = source.get(), type;
if (ops.test(word))
type = "sp-operator";
else if (keywords.test(word))
type = "sp-keyword";
else
type = "sp-word";
return {style: type, content: word};
}
}
function inLiteral(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped) {
setState(normal);
break;
}
escaped = !escaped && ch == "\\";
}
return "sp-literal";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentSparql(context) {
return function(nextChars) {
var firstChar = nextChars && nextChars.charAt(0);
if (/[\]\}]/.test(firstChar))
while (context && context.type == "pattern") context = context.prev;
var closing = context && firstChar == matching[context.type];
if (!context)
return 0;
else if (context.type == "pattern")
return context.col;
else if (context.align)
return context.col - (closing ? context.width : 0);
else
return context.indent + (closing ? 0 : indentUnit);
}
}
function parseSparql(source) {
var tokens = tokenizeSparql(source);
var context = null, indent = 0, col = 0;
function pushContext(type, width) {
context = {prev: context, indent: indent, col: col, type: type, width: width};
}
function popContext() {
context = context.prev;
}
var iter = {
next: function() {
var token = tokens.next(), type = token.style, content = token.content, width = token.value.length;
if (content == "\n") {
token.indentation = indentSparql(context);
indent = col = 0;
if (context && context.align == null) context.align = false;
}
else if (type == "whitespace" && col == 0) {
indent = width;
}
else if (type != "sp-comment" && context && context.align == null) {
context.align = true;
}
if (content != "\n") col += width;
if (/[\[\{\(]/.test(content)) {
pushContext(content, width);
}
else if (/[\]\}\)]/.test(content)) {
while (context && context.type == "pattern")
popContext();
if (context && content == matching[context.type])
popContext();
}
else if (content == "." && context && context.type == "pattern") {
popContext();
}
else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") &&
context && /[\{\[]/.test(context.type)) {
pushContext("pattern", width);
}
return token;
},
copy: function() {
var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeSparql(source, _tokenState);
context = _context;
indent = _indent;
col = _col;
return iter;
};
}
};
return iter;
}
return {make: parseSparql, electricChars: "}]"};
})();
| JavaScript |
// Minimal framing needed to use CodeMirror-style parsers to highlight
// code. Load this along with tokenize.js, stringstream.js, and your
// parser. Then call highlightText, passing a string as the first
// argument, and as the second argument either a callback function
// that will be called with an array of SPAN nodes for every line in
// the code, or a DOM node to which to append these spans, and
// optionally (not needed if you only loaded one parser) a parser
// object.
// Stuff from util.js that the parsers are using.
var StopIteration = {toString: function() {return "StopIteration"}};
var Editor = {};
var indentUnit = 2;
(function(){
function normaliseString(string) {
var tab = "";
for (var i = 0; i < indentUnit; i++) tab += " ";
string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n");
var pos = 0, parts = [], lines = string.split("\n");
for (var line = 0; line < lines.length; line++) {
if (line != 0) parts.push("\n");
parts.push(lines[line]);
}
return {
next: function() {
if (pos < parts.length) return parts[pos++];
else throw StopIteration;
}
};
}
window.highlightText = function(string, callback, parser) {
parser = (parser || Editor.Parser).make(stringStream(normaliseString(string)));
var line = [];
if (callback.nodeType == 1) {
var node = callback;
callback = function(line) {
for (var i = 0; i < line.length; i++)
node.appendChild(line[i]);
node.appendChild(document.createElement("br"));
};
}
try {
while (true) {
var token = parser.next();
if (token.value == "\n") {
callback(line);
line = [];
}
else {
var span = document.createElement("span");
span.className = token.style;
span.appendChild(document.createTextNode(token.value));
line.push(span);
}
}
}
catch (e) {
if (e != StopIteration) throw e;
}
if (line.length) callback(line);
}
})();
| JavaScript |
/* The Editor object manages the content of the editable frame. It
* catches events, colours nodes, and indents lines. This file also
* holds some functions for transforming arbitrary DOM structures into
* plain sequences of <span> and <br> elements
*/
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
var webkit = /AppleWebKit/.test(navigator.userAgent);
var safari = /Apple Computer, Inc/.test(navigator.vendor);
var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i);
if (gecko) gecko = Number(gecko[1]);
var mac = /Mac/.test(navigator.platform);
// TODO this is related to the backspace-at-end-of-line bug. Remove
// this if Opera gets their act together, make the version check more
// broad if they don't.
var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent);
// TODO remove this once WebKit 533 becomes less common.
var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent);
// Make sure a string does not contain two consecutive 'collapseable'
// whitespace characters.
function makeWhiteSpace(n) {
var buffer = [], nb = true;
for (; n > 0; n--) {
buffer.push((nb || n == 1) ? nbsp : " ");
nb ^= true;
}
return buffer.join("");
}
// Create a set of white-space characters that will not be collapsed
// by the browser, but will not break text-wrapping either.
function fixSpaces(string) {
if (string.charAt(0) == " ") string = nbsp + string.slice(1);
return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);})
.replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
}
function cleanText(text) {
return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
}
// Create a SPAN node with the expected properties for document part
// spans.
function makePartSpan(value) {
var text = value;
if (value.nodeType == 3) text = value.nodeValue;
else value = document.createTextNode(text);
var span = document.createElement("span");
span.isPart = true;
span.appendChild(value);
span.currentText = text;
return span;
}
function alwaysZero() {return 0;}
// On webkit, when the last BR of the document does not have text
// behind it, the cursor can not be put on the line after it. This
// makes pressing enter at the end of the document occasionally do
// nothing (or at least seem to do nothing). To work around it, this
// function makes sure the document ends with a span containing a
// zero-width space character. The traverseDOM iterator filters such
// character out again, so that the parsers won't see them. This
// function is called from a few strategic places to make sure the
// zwsp is restored after the highlighting process eats it.
var webkitLastLineHack = webkit ?
function(container) {
var last = container.lastChild;
if (!last || !last.hackBR) {
var br = document.createElement("br");
br.hackBR = true;
container.appendChild(br);
}
} : function() {};
function asEditorLines(string) {
var tab = makeWhiteSpace(indentUnit);
return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
}
var Editor = (function(){
// The HTML elements whose content should be suffixed by a newline
// when converting them to flat text.
var newlineElements = {"P": true, "DIV": true, "LI": true};
// Helper function for traverseDOM. Flattens an arbitrary DOM node
// into an array of textnodes and <br> tags.
function simplifyDOM(root, atEnd) {
var result = [];
var leaving = true;
function simplifyNode(node, top) {
if (node.nodeType == 3) {
var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
if (text.length) leaving = false;
result.push(node);
}
else if (isBR(node) && node.childNodes.length == 0) {
leaving = true;
result.push(node);
}
else {
for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n);
if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
leaving = true;
if (!atEnd || !top)
result.push(document.createElement("br"));
}
}
}
simplifyNode(root, true);
return result;
}
// Creates a MochiKit-style iterator that goes over a series of DOM
// nodes. The values it yields are strings, the textual content of
// the nodes. It makes sure that all nodes up to and including the
// one whose text is being yielded have been 'normalized' to be just
// <span> and <br> elements.
function traverseDOM(start){
var nodeQueue = [];
// Create a function that can be used to insert nodes after the
// one given as argument.
function pointAt(node){
var parent = node.parentNode;
var next = node.nextSibling;
return function(newnode) {
parent.insertBefore(newnode, next);
};
}
var point = null;
// This an Opera-specific hack -- always insert an empty span
// between two BRs, because Opera's cursor code gets terribly
// confused when the cursor is between two BRs.
var afterBR = true;
// Insert a normalized node at the current point. If it is a text
// node, wrap it in a <span>, and give that span a currentText
// property -- this is used to cache the nodeValue, because
// directly accessing nodeValue is horribly slow on some browsers.
// The dirty property is used by the highlighter to determine
// which parts of the document have to be re-highlighted.
function insertPart(part){
var text = "\n";
if (part.nodeType == 3) {
select.snapshotChanged();
part = makePartSpan(part);
text = part.currentText;
afterBR = false;
}
else {
if (afterBR && window.opera)
point(makePartSpan(""));
afterBR = true;
}
part.dirty = true;
nodeQueue.push(part);
point(part);
return text;
}
// Extract the text and newlines from a DOM node, insert them into
// the document, and return the textual content. Used to replace
// non-normalized nodes.
function writeNode(node, end) {
var simplified = simplifyDOM(node, end);
for (var i = 0; i < simplified.length; i++)
simplified[i] = insertPart(simplified[i]);
return simplified.join("");
}
// Check whether a node is a normalized <span> element.
function partNode(node){
if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
var text = node.firstChild.nodeValue;
node.dirty = node.dirty || text != node.currentText;
node.currentText = text;
return !/[\n\t\r]/.test(node.currentText);
}
return false;
}
// Advance to next node, return string for current node.
function next() {
if (!start) throw StopIteration;
var node = start;
start = node.nextSibling;
if (partNode(node)){
nodeQueue.push(node);
afterBR = false;
return node.currentText;
}
else if (isBR(node)) {
if (afterBR && window.opera)
node.parentNode.insertBefore(makePartSpan(""), node);
nodeQueue.push(node);
afterBR = true;
return "\n";
}
else {
var end = !node.nextSibling;
point = pointAt(node);
removeElement(node);
return writeNode(node, end);
}
}
// MochiKit iterators are objects with a next function that
// returns the next value or throws StopIteration when there are
// no more values.
return {next: next, nodes: nodeQueue};
}
// Determine the text size of a processed node.
function nodeSize(node) {
return isBR(node) ? 1 : node.currentText.length;
}
// Search backwards through the top-level nodes until the next BR or
// the start of the frame.
function startOfLine(node) {
while (node && !isBR(node)) node = node.previousSibling;
return node;
}
function endOfLine(node, container) {
if (!node) node = container.firstChild;
else if (isBR(node)) node = node.nextSibling;
while (node && !isBR(node)) node = node.nextSibling;
return node;
}
function time() {return new Date().getTime();}
// Client interface for searching the content of the editor. Create
// these by calling CodeMirror.getSearchCursor. To use, call
// findNext on the resulting object -- this returns a boolean
// indicating whether anything was found, and can be called again to
// skip to the next find. Use the select and replace methods to
// actually do something with the found locations.
function SearchCursor(editor, pattern, from, caseFold) {
this.editor = editor;
this.history = editor.history;
this.history.commit();
this.valid = !!pattern;
this.atOccurrence = false;
if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase();
function getText(node){
var line = cleanText(editor.history.textAfter(node));
return (caseFold ? line.toLowerCase() : line);
}
var topPos = {node: null, offset: 0}, self = this;
if (from && typeof from == "object" && typeof from.character == "number") {
editor.checkLine(from.line);
var pos = {node: from.line, offset: from.character};
this.pos = {from: pos, to: pos};
}
else if (from) {
this.pos = {from: select.cursorPos(editor.container, true) || topPos,
to: select.cursorPos(editor.container, false) || topPos};
}
else {
this.pos = {from: topPos, to: topPos};
}
if (typeof pattern != "string") { // Regexp match
this.matches = function(reverse, node, offset) {
if (reverse) {
var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0;
while (match) {
var ind = line.indexOf(match[0]);
start += ind;
line = line.slice(ind + 1);
var newmatch = line.match(pattern);
if (newmatch) match = newmatch;
else break;
}
}
else {
var line = getText(node).slice(offset), match = line.match(pattern),
start = match && offset + line.indexOf(match[0]);
}
if (match) {
self.currentMatch = match;
return {from: {node: node, offset: start},
to: {node: node, offset: start + match[0].length}};
}
};
return;
}
if (caseFold) pattern = pattern.toLowerCase();
// Create a matcher function based on the kind of string we have.
var target = pattern.split("\n");
this.matches = (target.length == 1) ?
// For one-line strings, searching can be done simply by calling
// indexOf or lastIndexOf on the current line.
function(reverse, node, offset) {
var line = getText(node), len = pattern.length, match;
if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1)
: (match = line.indexOf(pattern, offset)) != -1)
return {from: {node: node, offset: match},
to: {node: node, offset: match + len}};
} :
// Multi-line strings require internal iteration over lines, and
// some clunky checks to make sure the first match ends at the
// end of the line and the last match starts at the start.
function(reverse, node, offset) {
var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node);
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
if (reverse ? offsetA >= offset || offsetA != match.length
: offsetA <= offset || offsetA != line.length - match.length)
return;
var pos = node;
while (true) {
if (reverse && !pos) return;
pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) );
if (!reverse && !pos) return;
line = getText(pos);
match = target[reverse ? --idx : ++idx];
if (idx > 0 && idx < target.length - 1) {
if (line != match) return;
else continue;
}
var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
return;
return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA},
to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}};
}
};
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
if (!this.valid) return false;
var self = this, pos = reverse ? this.pos.from : this.pos.to,
node = pos.node, offset = pos.offset;
// Reset the cursor if the current line is no longer in the DOM tree.
if (node && !node.parentNode) {
node = null; offset = 0;
}
function savePosAndFail() {
var pos = {node: node, offset: offset};
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
while (true) {
if (this.pos = this.matches(reverse, node, offset)) {
this.atOccurrence = true;
return true;
}
if (reverse) {
if (!node) return savePosAndFail();
node = this.history.nodeBefore(node);
offset = this.history.textAfter(node).length;
}
else {
var next = this.history.nodeAfter(node);
if (!next) {
offset = this.history.textAfter(node).length;
return savePosAndFail();
}
node = next;
offset = 0;
}
}
},
select: function() {
if (this.atOccurrence) {
select.setCursorPos(this.editor.container, this.pos.from, this.pos.to);
select.scrollToCursor(this.editor.container);
}
},
replace: function(string) {
if (this.atOccurrence) {
var fragments = this.currentMatch;
if (fragments)
string = string.replace(/\\(\d)/, function(m, i){return fragments[i];});
var end = this.editor.replaceRange(this.pos.from, this.pos.to, string);
this.pos.to = end;
this.atOccurrence = false;
}
},
position: function() {
if (this.atOccurrence)
return {line: this.pos.from.node, character: this.pos.from.offset};
}
};
// The Editor object is the main inside-the-iframe interface.
function Editor(options) {
this.options = options;
window.indentUnit = options.indentUnit;
var container = this.container = document.body;
this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this);
var self = this;
if (!Editor.Parser)
throw "No parser loaded.";
if (options.parserConfig && Editor.Parser.configure)
Editor.Parser.configure(options.parserConfig);
if (!options.readOnly && !internetExplorer)
select.setCursorPos(container, {node: null, offset: 0});
this.dirty = [];
this.importCode(options.content || "");
this.history.onChange = options.onChange;
if (!options.readOnly) {
if (options.continuousScanning !== false) {
this.scanner = this.documentScanner(options.passTime);
this.delayScanning();
}
function setEditable() {
// Use contentEditable instead of designMode on IE, since designMode frames
// can not run any scripts. It would be nice if we could use contentEditable
// everywhere, but it is significantly flakier than designMode on every
// single non-IE browser.
if (document.body.contentEditable != undefined && internetExplorer)
document.body.contentEditable = "true";
else
document.designMode = "on";
// Work around issue where you have to click on the actual
// body of the document to focus it in IE, making focusing
// hard when the document is small.
if (internetExplorer && options.height != "dynamic")
document.body.style.minHeight = (
window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px";
document.documentElement.style.borderWidth = "0";
if (!options.textWrapping)
container.style.whiteSpace = "nowrap";
}
// If setting the frame editable fails, try again when the user
// focus it (happens when the frame is not visible on
// initialisation, in Firefox).
try {
setEditable();
}
catch(e) {
var focusEvent = addEventHandler(document, "focus", function() {
focusEvent();
setEditable();
}, true);
}
addEventHandler(document, "keydown", method(this, "keyDown"));
addEventHandler(document, "keypress", method(this, "keyPress"));
addEventHandler(document, "keyup", method(this, "keyUp"));
function cursorActivity() {self.cursorActivity(false);}
addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity);
addEventHandler(document.body, "cut", cursorActivity);
// workaround for a gecko bug [?] where going forward and then
// back again breaks designmode (no more cursor)
if (gecko)
addEventHandler(window, "pagehide", function(){self.unloaded = true;});
addEventHandler(document.body, "paste", function(event) {
cursorActivity();
var text = null;
try {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) text = clipboardData.getData('Text');
}
catch(e) {}
if (text !== null) {
event.stop();
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
});
if (this.options.autoMatchParens)
addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
}
else if (!options.textWrapping) {
container.style.whiteSpace = "nowrap";
}
}
function isSafeKey(code) {
return (code >= 16 && code <= 18) || // shift, control, alt
(code >= 33 && code <= 40); // arrows, home, end
}
Editor.prototype = {
// Import a piece of code into the editor.
importCode: function(code) {
var lines = asEditorLines(code), chunk = 1000;
if (!this.options.incrementalLoading || lines.length < chunk) {
this.history.push(null, null, lines);
this.history.reset();
}
else {
var cur = 0, self = this;
function addChunk() {
var chunklines = lines.slice(cur, cur + chunk);
chunklines.push("");
self.history.push(self.history.nodeBefore(null), null, chunklines);
self.history.reset();
cur += chunk;
if (cur < lines.length)
parent.setTimeout(addChunk, 1000);
}
addChunk();
}
},
// Extract the code from the editor.
getCode: function() {
if (!this.container.firstChild)
return "";
var accum = [];
select.markSelection();
forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
select.selectMarked();
// On webkit, don't count last (empty) line if the webkitLastLineHack BR is present
if (webkit && this.container.lastChild.hackBR)
accum.pop();
webkitLastLineHack(this.container);
return cleanText(accum.join(""));
},
checkLine: function(node) {
if (node === false || !(node == null || node.parentNode == this.container || node.hackBR))
throw parent.CodeMirror.InvalidLineHandle;
},
cursorPosition: function(start) {
if (start == null) start = true;
var pos = select.cursorPos(this.container, start);
if (pos) return {line: pos.node, character: pos.offset};
else return {line: null, character: 0};
},
firstLine: function() {
return null;
},
lastLine: function() {
var last = this.container.lastChild;
if (last) last = startOfLine(last);
if (last && last.hackBR) last = startOfLine(last.previousSibling);
return last;
},
nextLine: function(line) {
this.checkLine(line);
var end = endOfLine(line, this.container);
if (!end || end.hackBR) return false;
else return end;
},
prevLine: function(line) {
this.checkLine(line);
if (line == null) return false;
return startOfLine(line.previousSibling);
},
visibleLineCount: function() {
var line = this.container.firstChild;
while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable
if (!line) return false;
var innerHeight = (window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight);
return Math.floor(innerHeight / line.offsetHeight);
},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.checkLine(startLine);
var start = {node: startLine, offset: startOffset}, end = null;
if (endOffset !== undefined) {
this.checkLine(endLine);
end = {node: endLine, offset: endOffset};
}
select.setCursorPos(this.container, start, end);
select.scrollToCursor(this.container);
},
lineContent: function(line) {
var accum = [];
for (line = line ? line.nextSibling : this.container.firstChild;
line && !isBR(line); line = line.nextSibling)
accum.push(nodeText(line));
return cleanText(accum.join(""));
},
setLineContent: function(line, content) {
this.history.commit();
this.replaceRange({node: line, offset: 0},
{node: line, offset: this.history.textAfter(line).length},
content);
this.addDirtyNode(line);
this.scheduleHighlight();
},
removeLine: function(line) {
var node = line ? line.nextSibling : this.container.firstChild;
while (node) {
var next = node.nextSibling;
removeElement(node);
if (isBR(node)) break;
node = next;
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
insertIntoLine: function(line, position, content) {
var before = null;
if (position == "end") {
before = endOfLine(line, this.container);
}
else {
for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
if (position == 0) {
before = cur;
break;
}
var text = nodeText(cur);
if (text.length > position) {
before = cur.nextSibling;
content = text.slice(0, position) + content + text.slice(position);
removeElement(cur);
break;
}
position -= text.length;
}
}
var lines = asEditorLines(content);
for (var i = 0; i < lines.length; i++) {
if (i > 0) this.container.insertBefore(document.createElement("BR"), before);
this.container.insertBefore(makePartSpan(lines[i]), before);
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
// Retrieve the selected text.
selectedText: function() {
var h = this.history;
h.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return "";
if (start.node == end.node)
return h.textAfter(start.node).slice(start.offset, end.offset);
var text = [h.textAfter(start.node).slice(start.offset)];
for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
text.push(h.textAfter(pos));
text.push(h.textAfter(end.node).slice(0, end.offset));
return cleanText(text.join("\n"));
},
// Replace the selection with another piece of text.
replaceSelection: function(text) {
this.history.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return;
end = this.replaceRange(start, end, text);
select.setCursorPos(this.container, end);
webkitLastLineHack(this.container);
},
cursorCoords: function(start, internal) {
var sel = select.cursorPos(this.container, start);
if (!sel) return null;
var off = sel.offset, node = sel.node, self = this;
function measureFromNode(node, xOffset) {
var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0),
x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset;
forEach([node, internal ? null : window.frameElement], function(n) {
while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;}
});
return {x: x, y: y, yBot: y + node.offsetHeight};
}
function withTempNode(text, f) {
var node = document.createElement("SPAN");
node.appendChild(document.createTextNode(text));
try {return f(node);}
finally {if (node.parentNode) node.parentNode.removeChild(node);}
}
while (off) {
node = node ? node.nextSibling : this.container.firstChild;
var txt = nodeText(node);
if (off < txt.length)
return withTempNode(txt.substr(0, off), function(tmp) {
tmp.style.position = "absolute"; tmp.style.visibility = "hidden";
tmp.className = node.className;
self.container.appendChild(tmp);
return measureFromNode(node, tmp.offsetWidth);
});
off -= txt.length;
}
if (node && isSpan(node))
return measureFromNode(node, node.offsetWidth);
else if (node && node.nextSibling && isSpan(node.nextSibling))
return measureFromNode(node.nextSibling, 0);
else
return withTempNode("\u200b", function(tmp) {
if (node) node.parentNode.insertBefore(tmp, node.nextSibling);
else self.container.insertBefore(tmp, self.container.firstChild);
return measureFromNode(tmp, 0);
});
},
reroutePasteEvent: function() {
if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return;
this.capturingPaste = true;
var te = window.frameElement.CodeMirror.textareaHack;
var coords = this.cursorCoords(true, true);
te.style.top = coords.y + "px";
if (internetExplorer) {
var snapshot = select.getBookmark(this.container);
if (snapshot) this.selectionSnapshot = snapshot;
}
parent.focus();
te.value = "";
te.focus();
var self = this;
parent.setTimeout(function() {
self.capturingPaste = false;
window.focus();
if (self.selectionSnapshot) // IE hack
window.select.setBookmark(self.container, self.selectionSnapshot);
var text = te.value;
if (text) {
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
}, 10);
},
replaceRange: function(from, to, text) {
var lines = asEditorLines(text);
lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
var lastLine = lines[lines.length - 1];
lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
var end = this.history.nodeAfter(to.node);
this.history.push(from.node, end, lines);
return {node: this.history.nodeBefore(end),
offset: lastLine.length};
},
getSearchCursor: function(string, fromCursor, caseFold) {
return new SearchCursor(this, string, fromCursor, caseFold);
},
// Re-indent the whole buffer
reindent: function() {
if (this.container.firstChild)
this.indentRegion(null, this.container.lastChild);
},
reindentSelection: function(direction) {
if (!select.somethingSelected()) {
this.indentAtCursor(direction);
}
else {
var start = select.selectionTopNode(this.container, true),
end = select.selectionTopNode(this.container, false);
if (start === false || end === false) return;
this.indentRegion(start, end, direction, true);
}
},
grabKeys: function(eventHandler, filter) {
this.frozen = eventHandler;
this.keyFilter = filter;
},
ungrabKeys: function() {
this.frozen = "leave";
},
setParser: function(name, parserConfig) {
Editor.Parser = window[name];
parserConfig = parserConfig || this.options.parserConfig;
if (parserConfig && Editor.Parser.configure)
Editor.Parser.configure(parserConfig);
if (this.container.firstChild) {
forEach(this.container.childNodes, function(n) {
if (n.nodeType != 3) n.dirty = true;
});
this.addDirtyNode(this.firstChild);
this.scheduleHighlight();
}
},
// Intercept enter and tab, and assign their new functions.
keyDown: function(event) {
if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;}
if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) {
event.stop();
this.frozen(event);
return;
}
var code = event.keyCode;
// Don't scan when the user is typing.
this.delayScanning();
// Schedule a paren-highlight event, if configured.
if (this.options.autoMatchParens)
this.scheduleParenHighlight();
// The various checks for !altKey are there because AltGr sets both
// ctrlKey and altKey to true, and should not be recognised as
// Control.
if (code == 13) { // enter
if (event.ctrlKey && !event.altKey) {
this.reparseBuffer();
}
else {
select.insertNewlineAtCursor();
var mode = this.options.enterMode;
if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined);
select.scrollToCursor(this.container);
}
event.stop();
}
else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
this.handleTab(!event.shiftKey);
event.stop();
}
else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
this.handleTab(true);
event.stop();
}
else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
if (this.home()) event.stop();
}
else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
if (this.end()) event.stop();
}
// Only in Firefox is the default behavior for PgUp/PgDn correct.
else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp
if (this.pageUp()) event.stop();
}
else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn
if (this.pageDown()) event.stop();
}
else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
this.highlightParens(event.shiftKey, true);
event.stop();
}
else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
var cursor = select.selectionTopNode(this.container);
if (cursor === false || !this.container.firstChild) return;
if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
else {
var end = endOfLine(cursor, this.container);
select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
}
event.stop();
}
else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
select.scrollToNode(this.history.redo());
event.stop();
}
else if (code == 90 || (safari && code == 8)) { // Z, backspace
select.scrollToNode(this.history.undo());
event.stop();
}
else if (code == 83 && this.options.saveFunction) { // S
this.options.saveFunction();
event.stop();
}
else if (code == 86 && !mac) { // V
this.reroutePasteEvent();
}
}
},
// Check for characters that should re-indent the current line,
// and prevent Opera from handling enter and tab anyway.
keyPress: function(event) {
var electric = this.options.electricChars && Editor.Parser.electricChars, self = this;
// Hack for Opera, and Firefox on OS X, in which stopping a
// keydown event does not prevent the associated keypress event
// from happening, so we have to cancel enter and tab again
// here.
if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) ||
event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
(event.code == 32 && event.shiftKey && this.options.tabMode == "default"))
event.stop();
else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") {
this.reroutePasteEvent();
}
else if (electric && electric.indexOf(event.character) != -1)
parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
// Work around a bug where pressing backspace at the end of a
// line, or delete at the start, often causes the cursor to jump
// to the start of the line in Opera 10.60.
else if (brokenOpera) {
if (event.code == 8) { // backspace
var sel = select.selectionTopNode(this.container), self = this,
next = sel ? sel.nextSibling : this.container.firstChild;
if (sel !== false && next && isBR(next))
parent.setTimeout(function(){
if (select.selectionTopNode(self.container) == next)
select.focusAfterNode(next.previousSibling, self.container);
}, 20);
}
else if (event.code == 46) { // delete
var sel = select.selectionTopNode(this.container), self = this;
if (sel && isBR(sel)) {
parent.setTimeout(function(){
if (select.selectionTopNode(self.container) != sel)
select.focusAfterNode(sel, self.container);
}, 20);
}
}
}
// In 533.* WebKit versions, when the document is big, typing
// something at the end of a line causes the browser to do some
// kind of stupid heavy operation, creating delays of several
// seconds before the typed characters appear. This very crude
// hack inserts a temporary zero-width space after the cursor to
// make it not be at the end of the line.
else if (slowWebkit) {
var sel = select.selectionTopNode(this.container),
next = sel ? sel.nextSibling : this.container.firstChild;
// Doesn't work on empty lines, for some reason those always
// trigger the delay.
if (sel && next && isBR(next) && !isBR(sel)) {
var cheat = document.createTextNode("\u200b");
this.container.insertBefore(cheat, next);
parent.setTimeout(function() {
if (cheat.nodeValue == "\u200b") removeElement(cheat);
else cheat.nodeValue = cheat.nodeValue.replace("\u200b", "");
}, 20);
}
}
// Magic incantation that works abound a webkit bug when you
// can't type on a blank line following a line that's wider than
// the window.
if (webkit && !this.options.textWrapping)
setTimeout(function () {
var node = select.selectionTopNode(self.container, true);
if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling)
&& node.nextSibling && isBR(node.nextSibling))
node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling);
}, 50);
},
// Mark the node at the cursor dirty when a non-safe key is
// released.
keyUp: function(event) {
this.cursorActivity(isSafeKey(event.keyCode));
},
// Indent the line following a given <br>, or null for the first
// line. If given a <br> element, this must have been highlighted
// so that it has an indentation method. Returns the whitespace
// element that has been modified or created (if any).
indentLineAfter: function(start, direction) {
function whiteSpaceAfter(node) {
var ws = node ? node.nextSibling : self.container.firstChild;
if (!ws || !hasClass(ws, "whitespace")) return null;
return ws;
}
// whiteSpace is the whitespace span at the start of the line,
// or null if there is no such node.
var self = this, whiteSpace = whiteSpaceAfter(start);
var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
if (direction == "keep") {
if (start) {
var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling))
if (prevWS) newIndent = prevWS.currentText.length;
}
}
else {
// Sometimes the start of the line can influence the correct
// indentation, so we retrieve it.
var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
// Ask the lexical context for the correct indentation, and
// compute how much this differs from the current indentation.
if (direction != null && this.options.tabMode != "indent")
newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
else if (start)
newIndent = start.indentation(nextChars, curIndent, direction, firstText);
else if (Editor.Parser.firstIndentation)
newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText);
}
var indentDiff = newIndent - curIndent;
// If there is too much, this is just a matter of shrinking a span.
if (indentDiff < 0) {
if (newIndent == 0) {
if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0);
removeElement(whiteSpace);
whiteSpace = null;
}
else {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
}
// Not enough...
else if (indentDiff > 0) {
// If there is whitespace, we grow it.
if (whiteSpace) {
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
}
// Otherwise, we have to add a new whitespace node.
else {
whiteSpace = makePartSpan(makeWhiteSpace(newIndent));
whiteSpace.className = "whitespace";
if (start) insertAfter(whiteSpace, start);
else this.container.insertBefore(whiteSpace, this.container.firstChild);
select.snapshotMove(firstText && (firstText.firstChild || firstText),
whiteSpace.firstChild, newIndent, false, true);
}
}
// Make sure cursor ends up after the whitespace
else if (whiteSpace) {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false);
}
if (indentDiff != 0) this.addDirtyNode(start);
},
// Re-highlight the selected part of the document.
highlightAtCursor: function() {
var pos = select.selectionTopNode(this.container, true);
var to = select.selectionTopNode(this.container, false);
if (pos === false || to === false) return false;
select.markSelection();
if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
return false;
select.selectMarked();
return true;
},
// When tab is pressed with text selected, the whole selection is
// re-indented, when nothing is selected, the line with the cursor
// is re-indented.
handleTab: function(direction) {
if (this.options.tabMode == "spaces" && !select.somethingSelected())
select.insertTabAtCursor();
else
this.reindentSelection(direction);
},
// Custom home behaviour that doesn't land the cursor in front of
// leading whitespace unless pressed twice.
home: function() {
var cur = select.selectionTopNode(this.container, true), start = cur;
if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
return false;
while (cur && !isBR(cur)) cur = cur.previousSibling;
var next = cur ? cur.nextSibling : this.container.firstChild;
if (next && next != start && next.isPart && hasClass(next, "whitespace"))
select.focusAfterNode(next, this.container);
else
select.focusAfterNode(cur, this.container);
select.scrollToCursor(this.container);
return true;
},
// Some browsers (Opera) don't manage to handle the end key
// properly in the face of vertical scrolling.
end: function() {
var cur = select.selectionTopNode(this.container, true);
if (cur === false) return false;
cur = endOfLine(cur, this.container);
if (!cur) return false;
select.focusAfterNode(cur.previousSibling, this.container);
select.scrollToCursor(this.container);
return true;
},
pageUp: function() {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to keep one line on the screen.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
line = this.prevLine(line);
if (line === false) break;
}
if (i == 0) return false; // Already at first line
select.setCursorPos(this.container, {node: line, offset: 0});
select.scrollToCursor(this.container);
return true;
},
pageDown: function() {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to move to the last line of the current page.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
var nextLine = this.nextLine(line);
if (nextLine === false) break;
line = nextLine;
}
if (i == 0) return false; // Already at last line
select.setCursorPos(this.container, {node: line, offset: 0});
select.scrollToCursor(this.container);
return true;
},
// Delay (or initiate) the next paren highlight event.
scheduleParenHighlight: function() {
if (this.parenEvent) parent.clearTimeout(this.parenEvent);
var self = this;
this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300);
},
// Take the token before the cursor. If it contains a character in
// '()[]{}', search for the matching paren/brace/bracket, and
// highlight them in green for a moment, or red if no proper match
// was found.
highlightParens: function(jump, fromKey) {
var self = this, mark = this.options.markParen;
if (typeof mark == "string") mark = [mark, mark];
// give the relevant nodes a colour.
function highlight(node, ok) {
if (!node) return;
if (!mark) {
node.style.fontWeight = "bold";
node.style.color = ok ? "#8F8" : "#F88";
}
else if (mark.call) mark(node, ok);
else node.className += " " + mark[ok ? 0 : 1];
}
function unhighlight(node) {
if (!node) return;
if (mark && !mark.call)
removeClass(removeClass(node, mark[0]), mark[1]);
else if (self.options.unmarkParen)
self.options.unmarkParen(node);
else {
node.style.fontWeight = "";
node.style.color = "";
}
}
if (!fromKey && self.highlighted) {
unhighlight(self.highlighted[0]);
unhighlight(self.highlighted[1]);
}
if (!window || !window.parent || !window.select) return;
// Clear the event property.
if (this.parenEvent) parent.clearTimeout(this.parenEvent);
this.parenEvent = null;
// Extract a 'paren' from a piece of text.
function paren(node) {
if (node.currentText) {
var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
return match && match[1];
}
}
// Determine the direction a paren is facing.
function forward(ch) {
return /[\(\[\{]/.test(ch);
}
var ch, cursor = select.selectionTopNode(this.container, true);
if (!cursor || !this.highlightAtCursor()) return;
cursor = select.selectionTopNode(this.container, true);
if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
return;
// We only look for tokens with the same className.
var className = cursor.className, dir = forward(ch), match = matching[ch];
// Since parts of the document might not have been properly
// highlighted, and it is hard to know in advance which part we
// have to scan, we just try, and when we find dirty nodes we
// abort, parse them, and re-try.
function tryFindMatch() {
var stack = [], ch, ok = true;
for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
if (forward(ch) == dir)
stack.push(ch);
else if (!stack.length)
ok = false;
else if (stack.pop() != matching[ch])
ok = false;
if (!stack.length) break;
}
else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
return {node: runner, status: "dirty"};
}
}
return {node: runner, status: runner && ok};
}
while (true) {
var found = tryFindMatch();
if (found.status == "dirty") {
this.highlight(found.node, endOfLine(found.node));
// Needed because in some corner cases a highlight does not
// reach a node.
found.node.dirty = false;
continue;
}
else {
highlight(cursor, found.status);
highlight(found.node, found.status);
if (fromKey)
parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500);
else
self.highlighted = [cursor, found.node];
if (jump && found.node)
select.focusAfterNode(found.node.previousSibling, this.container);
break;
}
}
},
// Adjust the amount of whitespace at the start of the line that
// the cursor is on so that it is indented properly.
indentAtCursor: function(direction) {
if (!this.container.firstChild) return;
// The line has to have up-to-date lexical information, so we
// highlight it first.
if (!this.highlightAtCursor()) return;
var cursor = select.selectionTopNode(this.container, false);
// If we couldn't determine the place of the cursor,
// there's nothing to indent.
if (cursor === false)
return;
select.markSelection();
this.indentLineAfter(startOfLine(cursor), direction);
select.selectMarked();
},
// Indent all lines whose start falls inside of the current
// selection.
indentRegion: function(start, end, direction, selectAfter) {
var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
if (!isBR(end)) end = endOfLine(end, this.container);
this.addDirtyNode(start);
do {
var next = endOfLine(current, this.container);
if (current) this.highlight(before, next, true);
this.indentLineAfter(current, direction);
before = current;
current = next;
} while (current != end);
if (selectAfter)
select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
},
// Find the node that the cursor is in, mark it as dirty, and make
// sure a highlight pass is scheduled.
cursorActivity: function(safe) {
// pagehide event hack above
if (this.unloaded) {
window.document.designMode = "off";
window.document.designMode = "on";
this.unloaded = false;
}
if (internetExplorer) {
this.container.createTextRange().execCommand("unlink");
clearTimeout(this.saveSelectionSnapshot);
var self = this;
this.saveSelectionSnapshot = setTimeout(function() {
var snapshot = select.getBookmark(self.container);
if (snapshot) self.selectionSnapshot = snapshot;
}, 200);
}
var activity = this.options.onCursorActivity;
if (!safe || activity) {
var cursor = select.selectionTopNode(this.container, false);
if (cursor === false || !this.container.firstChild) return;
cursor = cursor || this.container.firstChild;
if (activity) activity(cursor);
if (!safe) {
this.scheduleHighlight();
this.addDirtyNode(cursor);
}
}
},
reparseBuffer: function() {
forEach(this.container.childNodes, function(node) {node.dirty = true;});
if (this.container.firstChild)
this.addDirtyNode(this.container.firstChild);
},
// Add a node to the set of dirty nodes, if it isn't already in
// there.
addDirtyNode: function(node) {
node = node || this.container.firstChild;
if (!node) return;
for (var i = 0; i < this.dirty.length; i++)
if (this.dirty[i] == node) return;
if (node.nodeType != 3)
node.dirty = true;
this.dirty.push(node);
},
allClean: function() {
return !this.dirty.length;
},
// Cause a highlight pass to happen in options.passDelay
// milliseconds. Clear the existing timeout, if one exists. This
// way, the passes do not happen while the user is typing, and
// should as unobtrusive as possible.
scheduleHighlight: function() {
// Timeouts are routed through the parent window, because on
// some browsers designMode windows do not fire timeouts.
var self = this;
parent.clearTimeout(this.highlightTimeout);
this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
},
// Fetch one dirty node, and remove it from the dirty set.
getDirtyNode: function() {
while (this.dirty.length > 0) {
var found = this.dirty.pop();
// IE8 sometimes throws an unexplainable 'invalid argument'
// exception for found.parentNode
try {
// If the node has been coloured in the meantime, or is no
// longer in the document, it should not be returned.
while (found && found.parentNode != this.container)
found = found.parentNode;
if (found && (found.dirty || found.nodeType == 3))
return found;
} catch (e) {}
}
return null;
},
// Pick dirty nodes, and highlight them, until options.passTime
// milliseconds have gone by. The highlight method will continue
// to next lines as long as it finds dirty nodes. It returns
// information about the place where it stopped. If there are
// dirty nodes left after this function has spent all its lines,
// it shedules another highlight to finish the job.
highlightDirty: function(force) {
// Prevent FF from raising an error when it is firing timeouts
// on a page that's no longer loaded.
if (!window || !window.parent || !window.select) return false;
if (!this.options.readOnly) select.markSelection();
var start, endTime = force ? null : time() + this.options.passTime;
while ((time() < endTime || force) && (start = this.getDirtyNode())) {
var result = this.highlight(start, endTime);
if (result && result.node && result.dirty)
this.addDirtyNode(result.node.nextSibling);
}
if (!this.options.readOnly) select.selectMarked();
if (start) this.scheduleHighlight();
return this.dirty.length == 0;
},
// Creates a function that, when called through a timeout, will
// continuously re-parse the document.
documentScanner: function(passTime) {
var self = this, pos = null;
return function() {
// FF timeout weirdness workaround.
if (!window || !window.parent || !window.select) return;
// If the current node is no longer in the document... oh
// well, we start over.
if (pos && pos.parentNode != self.container)
pos = null;
select.markSelection();
var result = self.highlight(pos, time() + passTime, true);
select.selectMarked();
var newPos = result ? (result.node && result.node.nextSibling) : null;
pos = (pos == newPos) ? null : newPos;
self.delayScanning();
};
},
// Starts the continuous scanning process for this document after
// a given interval.
delayScanning: function() {
if (this.scanner) {
parent.clearTimeout(this.documentScan);
this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning);
}
},
// The function that does the actual highlighting/colouring (with
// help from the parser and the DOM normalizer). Its interface is
// rather overcomplicated, because it is used in different
// situations: ensuring that a certain line is highlighted, or
// highlighting up to X milliseconds starting from a certain
// point. The 'from' argument gives the node at which it should
// start. If this is null, it will start at the beginning of the
// document. When a timestamp is given with the 'target' argument,
// it will stop highlighting at that time. If this argument holds
// a DOM node, it will highlight until it reaches that node. If at
// any time it comes across two 'clean' lines (no dirty nodes), it
// will stop, except when 'cleanLines' is true. maxBacktrack is
// the maximum number of lines to backtrack to find an existing
// parser instance. This is used to give up in situations where a
// highlight would take too long and freeze the browser interface.
highlight: function(from, target, cleanLines, maxBacktrack){
var container = this.container, self = this, active = this.options.activeTokens;
var endTime = (typeof target == "number" ? target : null);
if (!container.firstChild)
return false;
// Backtrack to the first node before from that has a partial
// parse stored.
while (from && (!from.parserFromHere || from.dirty)) {
if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
return false;
from = from.previousSibling;
}
// If we are at the end of the document, do nothing.
if (from && !from.nextSibling)
return false;
// Check whether a part (<span> node) and the corresponding token
// match.
function correctPart(token, part){
return !part.reduced && part.currentText == token.value && part.className == token.style;
}
// Shorten the text associated with a part by chopping off
// characters from the front. Note that only the currentText
// property gets changed. For efficiency reasons, we leave the
// nodeValue alone -- we set the reduced flag to indicate that
// this part must be replaced.
function shortenPart(part, minus){
part.currentText = part.currentText.substring(minus);
part.reduced = true;
}
// Create a part corresponding to a given token.
function tokenPart(token){
var part = makePartSpan(token.value);
part.className = token.style;
return part;
}
function maybeTouch(node) {
if (node) {
var old = node.oldNextSibling;
if (lineDirty || old === undefined || node.nextSibling != old)
self.history.touch(node);
node.oldNextSibling = node.nextSibling;
}
else {
var old = self.container.oldFirstChild;
if (lineDirty || old === undefined || self.container.firstChild != old)
self.history.touch(null);
self.container.oldFirstChild = self.container.firstChild;
}
}
// Get the token stream. If from is null, we start with a new
// parser from the start of the frame, otherwise a partial parse
// is resumed.
var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
stream = stringStream(traversal),
parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
function surroundedByBRs(node) {
return (node.previousSibling == null || isBR(node.previousSibling)) &&
(node.nextSibling == null || isBR(node.nextSibling));
}
// parts is an interface to make it possible to 'delay' fetching
// the next DOM node until we are completely done with the one
// before it. This is necessary because often the next node is
// not yet available when we want to proceed past the current
// one.
var parts = {
current: null,
// Fetch current node.
get: function(){
if (!this.current)
this.current = traversal.nodes.shift();
return this.current;
},
// Advance to the next part (do not fetch it yet).
next: function(){
this.current = null;
},
// Remove the current part from the DOM tree, and move to the
// next.
remove: function(){
container.removeChild(this.get());
this.current = null;
},
// Advance to the next part that is not empty, discarding empty
// parts.
getNonEmpty: function(){
var part = this.get();
// Allow empty nodes when they are alone on a line, needed
// for the FF cursor bug workaround (see select.js,
// insertNewlineAtCursor).
while (part && isSpan(part) && part.currentText == "") {
// Leave empty nodes that are alone on a line alone in
// Opera, since that browsers doesn't deal well with
// having 2 BRs in a row.
if (window.opera && surroundedByBRs(part)) {
this.next();
part = this.get();
}
else {
var old = part;
this.remove();
part = this.get();
// Adjust selection information, if any. See select.js for details.
select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
}
}
return part;
}
};
var lineDirty = false, prevLineDirty = true, lineNodes = 0;
// This forEach loops over the tokens from the parsed stream, and
// at the same time uses the parts object to proceed through the
// corresponding DOM nodes.
forEach(parsed, function(token){
var part = parts.getNonEmpty();
if (token.value == "\n"){
// The idea of the two streams actually staying synchronized
// is such a long shot that we explicitly check.
if (!isBR(part))
throw "Parser out of sync. Expected BR.";
if (part.dirty || !part.indentation) lineDirty = true;
maybeTouch(from);
from = part;
// Every <br> gets a copy of the parser state and a lexical
// context assigned to it. The first is used to be able to
// later resume parsing from this point, the second is used
// for indentation.
part.parserFromHere = parsed.copy();
part.indentation = token.indentation || alwaysZero;
part.dirty = false;
// If the target argument wasn't an integer, go at least
// until that node.
if (endTime == null && part == target) throw StopIteration;
// A clean line with more than one node means we are done.
// Throwing a StopIteration is the way to break out of a
// MochiKit forEach loop.
if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
throw StopIteration;
prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
parts.next();
}
else {
if (!isSpan(part))
throw "Parser out of sync. Expected SPAN.";
if (part.dirty)
lineDirty = true;
lineNodes++;
// If the part matches the token, we can leave it alone.
if (correctPart(token, part)){
if (active && part.dirty) active(part, token, self);
part.dirty = false;
parts.next();
}
// Otherwise, we have to fix it.
else {
lineDirty = true;
// Insert the correct part.
var newPart = tokenPart(token);
container.insertBefore(newPart, part);
if (active) active(newPart, token, self);
var tokensize = token.value.length;
var offset = 0;
// Eat up parts until the text for this token has been
// removed, adjusting the stored selection info (see
// select.js) in the process.
while (tokensize > 0) {
part = parts.get();
var partsize = part.currentText.length;
select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
if (partsize > tokensize){
shortenPart(part, tokensize);
tokensize = 0;
}
else {
tokensize -= partsize;
offset += partsize;
parts.remove();
}
}
}
}
});
maybeTouch(from);
webkitLastLineHack(this.container);
// The function returns some status information that is used by
// hightlightDirty to determine whether and where it has to
// continue.
return {node: parts.getNonEmpty(),
dirty: lineDirty};
}
};
return Editor;
})();
addEventHandler(window, "load", function() {
var CodeMirror = window.frameElement.CodeMirror;
var e = CodeMirror.editor = new Editor(CodeMirror.options);
parent.setTimeout(method(CodeMirror, "init"), 0);
});
/* Functionality for finding, storing, and restoring selections
*
* This does not provide a generic API, just the minimal functionality
* required by the CodeMirror system.
*/
// Namespace object.
var select = {};
(function() {
select.ie_selection = document.selection && document.selection.createRangeCollection;
// Find the 'top-level' (defined as 'a direct child of the node
// passed as the top argument') node that the given node is
// contained in. Return null if the given node is not inside the top
// node.
function topLevelNodeAt(node, top) {
while (node && node.parentNode != top)
node = node.parentNode;
return node;
}
// Find the top-level node that contains the node before this one.
function topLevelNodeBefore(node, top) {
while (!node.previousSibling && node.parentNode != top)
node = node.parentNode;
return topLevelNodeAt(node.previousSibling, top);
}
var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
select.scrollToNode = function(node, cursor) {
if (!node) return;
var element = node, body = document.body,
html = document.documentElement,
atEnd = !element.nextSibling || !element.nextSibling.nextSibling
|| !element.nextSibling.nextSibling.nextSibling;
// In Opera (and recent Webkit versions), BR elements *always*
// have a offsetTop property of zero.
var compensateHack = 0;
while (element && !element.offsetTop) {
compensateHack++;
element = element.previousSibling;
}
// atEnd is another kludge for these browsers -- if the cursor is
// at the end of the document, and the node doesn't have an
// offset, just scroll to the end.
if (compensateHack == 0) atEnd = false;
// WebKit has a bad habit of (sometimes) happily returning bogus
// offsets when the document has just been changed. This seems to
// always be 5/5, so we don't use those.
if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5)
return;
var y = compensateHack * (element ? element.offsetHeight : 0), x = 0,
width = (node ? node.offsetWidth : 0), pos = element;
while (pos && pos.offsetParent) {
y += pos.offsetTop;
// Don't count X offset for <br> nodes
if (!isBR(pos))
x += pos.offsetLeft;
pos = pos.offsetParent;
}
var scroll_x = body.scrollLeft || html.scrollLeft || 0,
scroll_y = body.scrollTop || html.scrollTop || 0,
scroll = false, screen_width = window.innerWidth || html.clientWidth || 0;
if (cursor || width < screen_width) {
if (cursor) {
var off = select.offsetInNode(node), size = nodeText(node).length;
if (size) x += width * (off / size);
}
var screen_x = x - scroll_x;
if (screen_x < 0 || screen_x > screen_width) {
scroll_x = x;
scroll = true;
}
}
var screen_y = y - scroll_y;
if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) {
scroll_y = atEnd ? 1e6 : y;
scroll = true;
}
if (scroll) window.scrollTo(scroll_x, scroll_y);
};
select.scrollToCursor = function(container) {
select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true);
};
// Used to prevent restoring a selection when we do not need to.
var currentSelection = null;
select.snapshotChanged = function() {
if (currentSelection) currentSelection.changed = true;
};
// Find the 'leaf' node (BR or text) after the given one.
function baseNodeAfter(node) {
var next = node.nextSibling;
if (next) {
while (next.firstChild) next = next.firstChild;
if (next.nodeType == 3 || isBR(next)) return next;
else return baseNodeAfter(next);
}
else {
var parent = node.parentNode;
while (parent && !parent.nextSibling) parent = parent.parentNode;
return parent && baseNodeAfter(parent);
}
}
// This is called by the code in editor.js whenever it is replacing
// a text node. The function sees whether the given oldNode is part
// of the current selection, and updates this selection if it is.
// Because nodes are often only partially replaced, the length of
// the part that gets replaced has to be taken into account -- the
// selection might stay in the oldNode if the newNode is smaller
// than the selection's offset. The offset argument is needed in
// case the selection does move to the new object, and the given
// length is not the whole length of the new node (part of it might
// have been used to replace another node).
select.snapshotReplaceNode = function(from, to, length, offset) {
if (!currentSelection) return;
function replace(point) {
if (from == point.node) {
currentSelection.changed = true;
if (length && point.offset > length) {
point.offset -= length;
}
else {
point.node = to;
point.offset += (offset || 0);
}
}
else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) {
currentSelection.changed = true;
}
}
replace(currentSelection.start);
replace(currentSelection.end);
};
select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
if (!currentSelection) return;
function move(point) {
if (from == point.node && (!ifAtStart || point.offset == 0)) {
currentSelection.changed = true;
point.node = to;
if (relative) point.offset = Math.max(0, point.offset + distance);
else point.offset = distance;
}
}
move(currentSelection.start);
move(currentSelection.end);
};
// Most functions are defined in two ways, one for the IE selection
// model, one for the W3C one.
if (select.ie_selection) {
function selRange() {
var sel = document.selection;
if (!sel) return null;
if (sel.createRange) return sel.createRange();
else return sel.createTextRange();
}
function selectionNode(start) {
var range = selRange();
range.collapse(start);
function nodeAfter(node) {
var found = null;
while (!found && node) {
found = node.nextSibling;
node = node.parentNode;
}
return nodeAtStartOf(found);
}
function nodeAtStartOf(node) {
while (node && node.firstChild) node = node.firstChild;
return {node: node, offset: 0};
}
var containing = range.parentElement();
if (!isAncestor(document.body, containing)) return null;
if (!containing.firstChild) return nodeAtStartOf(containing);
var working = range.duplicate();
working.moveToElementText(containing);
working.collapse(true);
for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
if (cur.nodeType == 3) {
var size = cur.nodeValue.length;
working.move("character", size);
}
else {
working.moveToElementText(cur);
working.collapse(false);
}
var dir = range.compareEndPoints("StartToStart", working);
if (dir == 0) return nodeAfter(cur);
if (dir == 1) continue;
if (cur.nodeType != 3) return nodeAtStartOf(cur);
working.setEndPoint("StartToEnd", range);
return {node: cur, offset: size - working.text.length};
}
return nodeAfter(containing);
}
select.markSelection = function() {
currentSelection = null;
var sel = document.selection;
if (!sel) return;
var start = selectionNode(true),
end = selectionNode(false);
if (!start || !end) return;
currentSelection = {start: start, end: end, changed: false};
};
select.selectMarked = function() {
if (!currentSelection || !currentSelection.changed) return;
function makeRange(point) {
var range = document.body.createTextRange(),
node = point.node;
if (!node) {
range.moveToElementText(document.body);
range.collapse(false);
}
else if (node.nodeType == 3) {
range.moveToElementText(node.parentNode);
var offset = point.offset;
while (node.previousSibling) {
node = node.previousSibling;
offset += (node.innerText || "").length;
}
range.move("character", offset);
}
else {
range.moveToElementText(node);
range.collapse(true);
}
return range;
}
var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
start.setEndPoint("StartToEnd", end);
start.select();
};
select.offsetInNode = function(node) {
var range = selRange();
if (!range) return 0;
var range2 = range.duplicate();
try {range2.moveToElementText(node);} catch(e){return 0;}
range.setEndPoint("StartToStart", range2);
return range.text.length;
};
// Get the top-level node that one end of the cursor is inside or
// after. Note that this returns false for 'no cursor', and null
// for 'start of document'.
select.selectionTopNode = function(container, start) {
var range = selRange();
if (!range) return false;
var range2 = range.duplicate();
range.collapse(start);
var around = range.parentElement();
if (around && isAncestor(container, around)) {
// Only use this node if the selection is not at its start.
range2.moveToElementText(around);
if (range.compareEndPoints("StartToStart", range2) == 1)
return topLevelNodeAt(around, container);
}
// Move the start of a range to the start of a node,
// compensating for the fact that you can't call
// moveToElementText with text nodes.
function moveToNodeStart(range, node) {
if (node.nodeType == 3) {
var count = 0, cur = node.previousSibling;
while (cur && cur.nodeType == 3) {
count += cur.nodeValue.length;
cur = cur.previousSibling;
}
if (cur) {
try{range.moveToElementText(cur);}
catch(e){return false;}
range.collapse(false);
}
else range.moveToElementText(node.parentNode);
if (count) range.move("character", count);
}
else {
try{range.moveToElementText(node);}
catch(e){return false;}
}
return true;
}
// Do a binary search through the container object, comparing
// the start of each node to the selection
var start = 0, end = container.childNodes.length - 1;
while (start < end) {
var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
if (!node) return false; // Don't ask. IE6 manages this sometimes.
if (!moveToNodeStart(range2, node)) return false;
if (range.compareEndPoints("StartToStart", range2) == 1)
start = middle;
else
end = middle - 1;
}
if (start == 0) {
var test1 = selRange(), test2 = test1.duplicate();
try {
test2.moveToElementText(container);
} catch(exception) {
return null;
}
if (test1.compareEndPoints("StartToStart", test2) == 0)
return null;
}
return container.childNodes[start] || null;
};
// Place the cursor after this.start. This is only useful when
// manually moving the cursor instead of restoring it to its old
// position.
select.focusAfterNode = function(node, container) {
var range = document.body.createTextRange();
range.moveToElementText(node || container);
range.collapse(!node);
range.select();
};
select.somethingSelected = function() {
var range = selRange();
return range && (range.text != "");
};
function insertAtCursor(html) {
var range = selRange();
if (range) {
range.pasteHTML(html);
range.collapse(false);
range.select();
}
}
// Used to normalize the effect of the enter key, since browsers
// do widely different things when pressing enter in designMode.
select.insertNewlineAtCursor = function() {
insertAtCursor("<br>");
};
select.insertTabAtCursor = function() {
insertAtCursor(fourSpaces);
};
// Get the BR node at the start of the line on which the cursor
// currently is, and the offset into the line. Returns null as
// node if cursor is on first line.
select.cursorPos = function(container, start) {
var range = selRange();
if (!range) return null;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
var range2 = range.duplicate();
range.collapse(start);
if (topNode) {
range2.moveToElementText(topNode);
range2.collapse(false);
}
else {
// When nothing is selected, we can get all kinds of funky errors here.
try { range2.moveToElementText(container); }
catch (e) { return null; }
range2.collapse(true);
}
range.setEndPoint("StartToStart", range2);
return {node: topNode, offset: range.text.length};
};
select.setCursorPos = function(container, from, to) {
function rangeAt(pos) {
var range = document.body.createTextRange();
if (!pos.node) {
range.moveToElementText(container);
range.collapse(true);
}
else {
range.moveToElementText(pos.node);
range.collapse(false);
}
range.move("character", pos.offset);
return range;
}
var range = rangeAt(from);
if (to && to != from)
range.setEndPoint("EndToEnd", rangeAt(to));
range.select();
}
// Some hacks for storing and re-storing the selection when the editor loses and regains focus.
select.getBookmark = function (container) {
var from = select.cursorPos(container, true), to = select.cursorPos(container, false);
if (from && to) return {from: from, to: to};
};
// Restore a stored selection.
select.setBookmark = function(container, mark) {
if (!mark) return;
select.setCursorPos(container, mark.from, mark.to);
};
}
// W3C model
else {
// Find the node right at the cursor, not one of its
// ancestors with a suitable offset. This goes down the DOM tree
// until a 'leaf' is reached (or is it *up* the DOM tree?).
function innerNode(node, offset) {
while (node.nodeType != 3 && !isBR(node)) {
var newNode = node.childNodes[offset] || node.nextSibling;
offset = 0;
while (!newNode && node.parentNode) {
node = node.parentNode;
newNode = node.nextSibling;
}
node = newNode;
if (!newNode) break;
}
return {node: node, offset: offset};
}
// Store start and end nodes, and offsets within these, and refer
// back to the selection object from those nodes, so that this
// object can be updated when the nodes are replaced before the
// selection is restored.
select.markSelection = function () {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return (currentSelection = null);
var range = selection.getRangeAt(0);
currentSelection = {
start: innerNode(range.startContainer, range.startOffset),
end: innerNode(range.endContainer, range.endOffset),
changed: false
};
};
select.selectMarked = function () {
var cs = currentSelection;
// on webkit-based browsers, it is apparently possible that the
// selection gets reset even when a node that is not one of the
// endpoints get messed with. the most common situation where
// this occurs is when a selection is deleted or overwitten. we
// check for that here.
function focusIssue() {
if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0) return true;
var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset);
return cs.start.node != point.node || cs.start.offset != point.offset;
}
}
if (!cs || !(cs.changed || (webkit && focusIssue()))) return;
var range = document.createRange();
function setPoint(point, which) {
if (point.node) {
// Some magic to generalize the setting of the start and end
// of a range.
if (point.offset == 0)
range["set" + which + "Before"](point.node);
else
range["set" + which](point.node, point.offset);
}
else {
range.setStartAfter(document.body.lastChild || document.body);
}
}
setPoint(cs.end, "End");
setPoint(cs.start, "Start");
selectRange(range);
};
// Helper for selecting a range object.
function selectRange(range) {
var selection = window.getSelection();
if (!selection) return;
selection.removeAllRanges();
selection.addRange(range);
}
function selectionRange() {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return false;
else
return selection.getRangeAt(0);
}
// Finding the top-level node at the cursor in the W3C is, as you
// can see, quite an involved process.
select.selectionTopNode = function(container, start) {
var range = selectionRange();
if (!range) return false;
var node = start ? range.startContainer : range.endContainer;
var offset = start ? range.startOffset : range.endOffset;
// Work around (yet another) bug in Opera's selection model.
if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
offset--;
// For text nodes, we look at the node itself if the cursor is
// inside, or at the node before it if the cursor is at the
// start.
if (node.nodeType == 3){
if (offset > 0)
return topLevelNodeAt(node, container);
else
return topLevelNodeBefore(node, container);
}
// Occasionally, browsers will return the HTML node as
// selection. If the offset is 0, we take the start of the frame
// ('after null'), otherwise, we take the last node.
else if (node.nodeName.toUpperCase() == "HTML") {
return (offset == 1 ? null : container.lastChild);
}
// If the given node is our 'container', we just look up the
// correct node by using the offset.
else if (node == container) {
return (offset == 0) ? null : node.childNodes[offset - 1];
}
// In any other case, we have a regular node. If the cursor is
// at the end of the node, we use the node itself, if it is at
// the start, we use the node before it, and in any other
// case, we look up the child before the cursor and use that.
else {
if (offset == node.childNodes.length)
return topLevelNodeAt(node, container);
else if (offset == 0)
return topLevelNodeBefore(node, container);
else
return topLevelNodeAt(node.childNodes[offset - 1], container);
}
};
select.focusAfterNode = function(node, container) {
var range = document.createRange();
range.setStartBefore(container.firstChild || container);
// In Opera, setting the end of a range at the end of a line
// (before a BR) will cause the cursor to appear on the next
// line, so we set the end inside of the start node when
// possible.
if (node && !node.firstChild)
range.setEndAfter(node);
else if (node)
range.setEnd(node, node.childNodes.length);
else
range.setEndBefore(container.firstChild || container);
range.collapse(false);
selectRange(range);
};
select.somethingSelected = function() {
var range = selectionRange();
return range && !range.collapsed;
};
select.offsetInNode = function(node) {
var range = selectionRange();
if (!range) return 0;
range = range.cloneRange();
range.setStartBefore(node);
return range.toString().length;
};
select.insertNodeAtCursor = function(node) {
var range = selectionRange();
if (!range) return;
range.deleteContents();
range.insertNode(node);
webkitLastLineHack(document.body);
// work around weirdness where Opera will magically insert a new
// BR node when a BR node inside a span is moved around. makes
// sure the BR ends up outside of spans.
if (window.opera && isBR(node) && isSpan(node.parentNode)) {
var next = node.nextSibling, p = node.parentNode, outer = p.parentNode;
outer.insertBefore(node, p.nextSibling);
var textAfter = "";
for (; next && next.nodeType == 3; next = next.nextSibling) {
textAfter += next.nodeValue;
removeElement(next);
}
outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling);
}
range = document.createRange();
range.selectNode(node);
range.collapse(false);
selectRange(range);
}
select.insertNewlineAtCursor = function() {
select.insertNodeAtCursor(document.createElement("BR"));
};
select.insertTabAtCursor = function() {
select.insertNodeAtCursor(document.createTextNode(fourSpaces));
};
select.cursorPos = function(container, start) {
var range = selectionRange();
if (!range) return;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
range = range.cloneRange();
range.collapse(start);
if (topNode)
range.setStartAfter(topNode);
else
range.setStartBefore(container);
var text = range.toString();
return {node: topNode, offset: text.length};
};
select.setCursorPos = function(container, from, to) {
var range = document.createRange();
function setPoint(node, offset, side) {
if (offset == 0 && node && !node.nextSibling) {
range["set" + side + "After"](node);
return true;
}
if (!node)
node = container.firstChild;
else
node = node.nextSibling;
if (!node) return;
if (offset == 0) {
range["set" + side + "Before"](node);
return true;
}
var backlog = []
function decompose(node) {
if (node.nodeType == 3)
backlog.push(node);
else
forEach(node.childNodes, decompose);
}
while (true) {
while (node && !backlog.length) {
decompose(node);
node = node.nextSibling;
}
var cur = backlog.shift();
if (!cur) return false;
var length = cur.nodeValue.length;
if (length >= offset) {
range["set" + side](cur, offset);
return true;
}
offset -= length;
}
}
to = to || from;
if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
selectRange(range);
};
}
})();
/* String streams are the things fed to parsers (which can feed them
* to a tokenizer if they want). They provide peek and next methods
* for looking at the current character (next 'consumes' this
* character, peek does not), and a get method for retrieving all the
* text that was consumed since the last time get was called.
*
* An easy mistake to make is to let a StopIteration exception finish
* the token stream while there are still characters pending in the
* string stream (hitting the end of the buffer while parsing a
* token). To make it easier to detect such errors, the stringstreams
* throw an exception when this happens.
*/
// Make a stringstream stream out of an iterator that returns strings.
// This is applied to the result of traverseDOM (see codemirror.js),
// and the resulting stream is fed to the parser.
var stringStream = function(source){
// String that's currently being iterated over.
var current = "";
// Position in that string.
var pos = 0;
// Accumulator for strings that have been iterated over but not
// get()-ed yet.
var accum = "";
// Make sure there are more characters ready, or throw
// StopIteration.
function ensureChars() {
while (pos == current.length) {
accum += current;
current = ""; // In case source.next() throws
pos = 0;
try {current = source.next();}
catch (e) {
if (e != StopIteration) throw e;
else return false;
}
}
return true;
}
return {
// peek: -> character
// Return the next character in the stream.
peek: function() {
if (!ensureChars()) return null;
return current.charAt(pos);
},
// next: -> character
// Get the next character, throw StopIteration if at end, check
// for unused content.
next: function() {
if (!ensureChars()) {
if (accum.length > 0)
throw "End of stringstream reached without emptying buffer ('" + accum + "').";
else
throw StopIteration;
}
return current.charAt(pos++);
},
// get(): -> string
// Return the characters iterated over since the last call to
// .get().
get: function() {
var temp = accum;
accum = "";
if (pos > 0){
temp += current.slice(0, pos);
current = current.slice(pos);
pos = 0;
}
return temp;
},
// Push a string back into the stream.
push: function(str) {
current = current.slice(0, pos) + str + current.slice(pos);
},
lookAhead: function(str, consume, skipSpaces, caseInsensitive) {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
str = cased(str);
var found = false;
var _accum = accum, _pos = pos;
if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/);
while (true) {
var end = pos + str.length, left = current.length - pos;
if (end <= current.length) {
found = str == cased(current.slice(pos, end));
pos = end;
break;
}
else if (str.slice(0, left) == cased(current.slice(pos))) {
accum += current; current = "";
try {current = source.next();}
catch (e) {if (e != StopIteration) throw e; break;}
pos = 0;
str = str.slice(left);
}
else {
break;
}
}
if (!(found && consume)) {
current = accum.slice(_accum.length) + current;
pos = _pos;
accum = _accum;
}
return found;
},
// Wont't match past end of line.
lookAheadRegex: function(regex, consume) {
if (regex.source.charAt(0) != "^")
throw new Error("Regexps passed to lookAheadRegex must start with ^");
// Fetch the rest of the line
while (current.indexOf("\n", pos) == -1) {
try {current += source.next();}
catch (e) {if (e != StopIteration) throw e; break;}
}
var matched = current.slice(pos).match(regex);
if (matched && consume) pos += matched[0].length;
return matched;
},
// Utils built on top of the above
// more: -> boolean
// Produce true if the stream isn't empty.
more: function() {
return this.peek() !== null;
},
applies: function(test) {
var next = this.peek();
return (next !== null && test(next));
},
nextWhile: function(test) {
var next;
while ((next = this.peek()) !== null && test(next))
this.next();
},
matches: function(re) {
var next = this.peek();
return (next !== null && re.test(next));
},
nextWhileMatches: function(re) {
var next;
while ((next = this.peek()) !== null && re.test(next))
this.next();
},
equals: function(ch) {
return ch === this.peek();
},
endOfLine: function() {
var next = this.peek();
return next == null || next == "\n";
}
};
};
// A framework for simple tokenizers. Takes care of newlines and
// white-space, and of getting the text from the source stream into
// the token object. A state is a function of two arguments -- a
// string stream and a setState function. The second can be used to
// change the tokenizer's state, and can be ignored for stateless
// tokenizers. This function should advance the stream over a token
// and return a string or object containing information about the next
// token, or null to pass and have the (new) state be called to finish
// the token. When a string is given, it is wrapped in a {style, type}
// object. In the resulting object, the characters consumed are stored
// under the content property. Any whitespace following them is also
// automatically consumed, and added to the value property. (Thus,
// content is the actual meaningful part of the token, while value
// contains all the text it spans.)
function tokenizer(source, state) {
// Newlines are always a separate token.
function isWhiteSpace(ch) {
// The messy regexp is because IE's regexp matcher is of the
// opinion that non-breaking spaces are no whitespace.
return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
}
var tokenizer = {
state: state,
take: function(type) {
if (typeof(type) == "string")
type = {style: type, type: type};
type.content = (type.content || "") + source.get();
if (!/\n$/.test(type.content))
source.nextWhile(isWhiteSpace);
type.value = type.content + source.get();
return type;
},
next: function () {
if (!source.more()) throw StopIteration;
var type;
if (source.equals("\n")) {
source.next();
return this.take("whitespace");
}
if (source.applies(isWhiteSpace))
type = "whitespace";
else
while (!type)
type = this.state(source, function(s) {tokenizer.state = s;});
return this.take(type);
}
};
return tokenizer;
}
/**
* Storage and control for undo information within a CodeMirror
* editor. 'Why on earth is such a complicated mess required for
* that?', I hear you ask. The goal, in implementing this, was to make
* the complexity of storing and reverting undo information depend
* only on the size of the edited or restored content, not on the size
* of the whole document. This makes it necessary to use a kind of
* 'diff' system, which, when applied to a DOM tree, causes some
* complexity and hackery.
*
* In short, the editor 'touches' BR elements as it parses them, and
* the UndoHistory stores these. When nothing is touched in commitDelay
* milliseconds, the changes are committed: It goes over all touched
* nodes, throws out the ones that did not change since last commit or
* are no longer in the document, and assembles the rest into zero or
* more 'chains' -- arrays of adjacent lines. Links back to these
* chains are added to the BR nodes, while the chain that previously
* spanned these nodes is added to the undo history. Undoing a change
* means taking such a chain off the undo history, restoring its
* content (text is saved per line) and linking it back into the
* document.
*/
// A history object needs to know about the DOM container holding the
// document, the maximum amount of undo levels it should store, the
// delay (of no input) after which it commits a set of changes, and,
// unfortunately, the 'parent' window -- a window that is not in
// designMode, and on which setTimeout works in every browser.
function UndoHistory(container, maxDepth, commitDelay, editor) {
this.container = container;
this.maxDepth = maxDepth; this.commitDelay = commitDelay;
this.editor = editor;
// This line object represents the initial, empty editor.
var initial = {text: "", from: null, to: null};
// As the borders between lines are represented by BR elements, the
// start of the first line and the end of the last one are
// represented by null. Since you can not store any properties
// (links to line objects) in null, these properties are used in
// those cases.
this.first = initial; this.last = initial;
// Similarly, a 'historyTouched' property is added to the BR in
// front of lines that have already been touched, and 'firstTouched'
// is used for the first line.
this.firstTouched = false;
// History is the set of committed changes, touched is the set of
// nodes touched since the last commit.
this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0;
}
UndoHistory.prototype = {
// Schedule a commit (if no other touches come in for commitDelay
// milliseconds).
scheduleCommit: function() {
var self = this;
parent.clearTimeout(this.commitTimeout);
this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
},
// Mark a node as touched. Null is a valid argument.
touch: function(node) {
this.setTouched(node);
this.scheduleCommit();
},
// Undo the last change.
undo: function() {
// Make sure pending changes have been committed.
this.commit();
if (this.history.length) {
// Take the top diff from the history, apply it, and store its
// shadow in the redo history.
var item = this.history.pop();
this.redoHistory.push(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
// Redo the last undone change.
redo: function() {
this.commit();
if (this.redoHistory.length) {
// The inverse of undo, basically.
var item = this.redoHistory.pop();
this.addUndoLevel(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
clear: function() {
this.history = [];
this.redoHistory = [];
this.lostundo = 0;
},
// Ask for the size of the un/redo histories.
historySize: function() {
return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo};
},
// Push a changeset into the document.
push: function(from, to, lines) {
var chain = [];
for (var i = 0; i < lines.length; i++) {
var end = (i == lines.length - 1) ? to : document.createElement("br");
chain.push({from: from, to: end, text: cleanText(lines[i])});
from = end;
}
this.pushChains([chain], from == null && to == null);
this.notifyEnvironment();
},
pushChains: function(chains, doNotHighlight) {
this.commit(doNotHighlight);
this.addUndoLevel(this.updateTo(chains, "applyChain"));
this.redoHistory = [];
},
// Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
chainNode: function(chains) {
for (var i = 0; i < chains.length; i++) {
var start = chains[i][0], node = start && (start.from || start.to);
if (node) return node;
}
},
// Clear the undo history, make the current document the start
// position.
reset: function() {
this.history = []; this.redoHistory = []; this.lostundo = 0;
},
textAfter: function(br) {
return this.after(br).text;
},
nodeAfter: function(br) {
return this.after(br).to;
},
nodeBefore: function(br) {
return this.before(br).from;
},
// Commit unless there are pending dirty nodes.
tryCommit: function() {
if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded
if (this.editor.highlightDirty()) this.commit(true);
else this.scheduleCommit();
},
// Check whether the touched nodes hold any changes, if so, commit
// them.
commit: function(doNotHighlight) {
parent.clearTimeout(this.commitTimeout);
// Make sure there are no pending dirty nodes.
if (!doNotHighlight) this.editor.highlightDirty(true);
// Build set of chains.
var chains = this.touchedChains(), self = this;
if (chains.length) {
this.addUndoLevel(this.updateTo(chains, "linkChain"));
this.redoHistory = [];
this.notifyEnvironment();
}
},
// [ end of public interface ]
// Update the document with a given set of chains, return its
// shadow. updateFunc should be "applyChain" or "linkChain". In the
// second case, the chains are taken to correspond the the current
// document, and only the state of the line data is updated. In the
// first case, the content of the chains is also pushed iinto the
// document.
updateTo: function(chains, updateFunc) {
var shadows = [], dirty = [];
for (var i = 0; i < chains.length; i++) {
shadows.push(this.shadowChain(chains[i]));
dirty.push(this[updateFunc](chains[i]));
}
if (updateFunc == "applyChain")
this.notifyDirty(dirty);
return shadows;
},
// Notify the editor that some nodes have changed.
notifyDirty: function(nodes) {
forEach(nodes, method(this.editor, "addDirtyNode"))
this.editor.scheduleHighlight();
},
notifyEnvironment: function() {
if (this.onChange) this.onChange(this.editor);
// Used by the line-wrapping line-numbering code.
if (window.frameElement && window.frameElement.CodeMirror.updateNumbers)
window.frameElement.CodeMirror.updateNumbers();
},
// Link a chain into the DOM nodes (or the first/last links for null
// nodes).
linkChain: function(chain) {
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
if (line.from) line.from.historyAfter = line;
else this.first = line;
if (line.to) line.to.historyBefore = line;
else this.last = line;
}
},
// Get the line object after/before a given node.
after: function(node) {
return node ? node.historyAfter : this.first;
},
before: function(node) {
return node ? node.historyBefore : this.last;
},
// Mark a node as touched if it has not already been marked.
setTouched: function(node) {
if (node) {
if (!node.historyTouched) {
this.touched.push(node);
node.historyTouched = true;
}
}
else {
this.firstTouched = true;
}
},
// Store a new set of undo info, throw away info if there is more of
// it than allowed.
addUndoLevel: function(diffs) {
this.history.push(diffs);
if (this.history.length > this.maxDepth) {
this.history.shift();
this.lostundo += 1;
}
},
// Build chains from a set of touched nodes.
touchedChains: function() {
var self = this;
// The temp system is a crummy hack to speed up determining
// whether a (currently touched) node has a line object associated
// with it. nullTemp is used to store the object for the first
// line, other nodes get it stored in their historyTemp property.
var nullTemp = null;
function temp(node) {return node ? node.historyTemp : nullTemp;}
function setTemp(node, line) {
if (node) node.historyTemp = line;
else nullTemp = line;
}
function buildLine(node) {
var text = [];
for (var cur = node ? node.nextSibling : self.container.firstChild;
cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling)
if (!cur.hackBR && cur.currentText) text.push(cur.currentText);
return {from: node, to: cur, text: cleanText(text.join(""))};
}
// Filter out unchanged lines and nodes that are no longer in the
// document. Build up line objects for remaining nodes.
var lines = [];
if (self.firstTouched) self.touched.push(null);
forEach(self.touched, function(node) {
if (node && (node.parentNode != self.container || node.hackBR)) return;
if (node) node.historyTouched = false;
else self.firstTouched = false;
var line = buildLine(node), shadow = self.after(node);
if (!shadow || shadow.text != line.text || shadow.to != line.to) {
lines.push(line);
setTemp(node, line);
}
});
// Get the BR element after/before the given node.
function nextBR(node, dir) {
var link = dir + "Sibling", search = node[link];
while (search && !isBR(search))
search = search[link];
return search;
}
// Assemble line objects into chains by scanning the DOM tree
// around them.
var chains = []; self.touched = [];
forEach(lines, function(line) {
// Note that this makes the loop skip line objects that have
// been pulled into chains by lines before them.
if (!temp(line.from)) return;
var chain = [], curNode = line.from, safe = true;
// Put any line objects (referred to by temp info) before this
// one on the front of the array.
while (true) {
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.unshift(curLine);
setTemp(curNode, null);
if (!curNode) break;
safe = self.after(curNode);
curNode = nextBR(curNode, "previous");
}
curNode = line.to; safe = self.before(line.from);
// Add lines after this one at end of array.
while (true) {
if (!curNode) break;
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.push(curLine);
setTemp(curNode, null);
safe = self.before(curNode);
curNode = nextBR(curNode, "next");
}
chains.push(chain);
});
return chains;
},
// Find the 'shadow' of a given chain by following the links in the
// DOM nodes at its start and end.
shadowChain: function(chain) {
var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
while (true) {
shadows.push(next);
var nextNode = next.to;
if (!nextNode || nextNode == end)
break;
else
next = nextNode.historyAfter || this.before(end);
// (The this.before(end) is a hack -- FF sometimes removes
// properties from BR nodes, in which case the best we can hope
// for is to not break.)
}
return shadows;
},
// Update the DOM tree to contain the lines specified in a given
// chain, link this chain into the DOM nodes.
applyChain: function(chain) {
// Some attempt is made to prevent the cursor from jumping
// randomly when an undo or redo happens. It still behaves a bit
// strange sometimes.
var cursor = select.cursorPos(this.container, false), self = this;
// Remove all nodes in the DOM tree between from and to (null for
// start/end of container).
function removeRange(from, to) {
var pos = from ? from.nextSibling : self.container.firstChild;
while (pos != to) {
var temp = pos.nextSibling;
removeElement(pos);
pos = temp;
}
}
var start = chain[0].from, end = chain[chain.length - 1].to;
// Clear the space where this change has to be made.
removeRange(start, end);
// Insert the content specified by the chain into the DOM tree.
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
// The start and end of the space are already correct, but BR
// tags inside it have to be put back.
if (i > 0)
self.container.insertBefore(line.from, end);
// Add the text.
var node = makePartSpan(fixSpaces(line.text));
self.container.insertBefore(node, end);
// See if the cursor was on this line. Put it back, adjusting
// for changed line length, if it was.
if (cursor && cursor.node == line.from) {
var cursordiff = 0;
var prev = this.after(line.from);
if (prev && i == chain.length - 1) {
// Only adjust if the cursor is after the unchanged part of
// the line.
for (var match = 0; match < cursor.offset &&
line.text.charAt(match) == prev.text.charAt(match); match++){}
if (cursor.offset > match)
cursordiff = line.text.length - prev.text.length;
}
select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
}
// Cursor was in removed line, this is last new line.
else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
}
}
// Anchor the chain in the DOM tree.
this.linkChain(chain);
return start;
}
};
/* A few useful utility functions. */
// Capture a method on an object.
function method(obj, name) {
return function() {obj[name].apply(obj, arguments);};
}
// The value used to signal the end of a sequence in iterators.
var StopIteration = {toString: function() {return "StopIteration"}};
// Apply a function to each element in a sequence.
function forEach(iter, f) {
if (iter.next) {
try {while (true) f(iter.next());}
catch (e) {if (e != StopIteration) throw e;}
}
else {
for (var i = 0; i < iter.length; i++)
f(iter[i]);
}
}
// Map a function over a sequence, producing an array of results.
function map(iter, f) {
var accum = [];
forEach(iter, function(val) {accum.push(f(val));});
return accum;
}
// Create a predicate function that tests a string againsts a given
// regular expression. No longer used but might be used by 3rd party
// parsers.
function matcher(regexp){
return function(value){return regexp.test(value);};
}
// Test whether a DOM node has a certain CSS class.
function hasClass(element, className) {
var classes = element.className;
return classes && new RegExp("(^| )" + className + "($| )").test(classes);
}
function removeClass(element, className) {
element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), "");
return element;
}
// Insert a DOM node after another node.
function insertAfter(newNode, oldNode) {
var parent = oldNode.parentNode;
parent.insertBefore(newNode, oldNode.nextSibling);
return newNode;
}
function removeElement(node) {
if (node.parentNode)
node.parentNode.removeChild(node);
}
function clearElement(node) {
while (node.firstChild)
node.removeChild(node.firstChild);
}
// Check whether a node is contained in another one.
function isAncestor(node, child) {
while (child = child.parentNode) {
if (node == child)
return true;
}
return false;
}
// The non-breaking space character.
var nbsp = "\u00a0";
var matching = {"{": "}", "[": "]", "(": ")",
"}": "{", "]": "[", ")": "("};
// Standardize a few unportable event properties.
function normalizeEvent(event) {
if (!event.stopPropagation) {
event.stopPropagation = function() {this.cancelBubble = true;};
event.preventDefault = function() {this.returnValue = false;};
}
if (!event.stop) {
event.stop = function() {
this.stopPropagation();
this.preventDefault();
};
}
if (event.type == "keypress") {
event.code = (event.charCode == null) ? event.keyCode : event.charCode;
event.character = String.fromCharCode(event.code);
}
return event;
}
// Portably register event handlers.
function addEventHandler(node, type, handler, removeFunc) {
function wrapHandler(event) {
handler(normalizeEvent(event || window.event));
}
if (typeof node.addEventListener == "function") {
node.addEventListener(type, wrapHandler, false);
if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);};
}
else {
node.attachEvent("on" + type, wrapHandler);
if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
function nodeText(node) {
return node.textContent || node.innerText || node.nodeValue || "";
}
function nodeTop(node) {
var top = 0;
while (node.offsetParent) {
top += node.offsetTop;
node = node.offsetParent;
}
return top;
}
function isBR(node) {
var nn = node.nodeName;
return nn == "BR" || nn == "br";
}
function isSpan(node) {
var nn = node.nodeName;
return nn == "SPAN" || nn == "span";
}
| JavaScript |
/* This file defines an XML parser, with a few kludges to make it
* useable for HTML. autoSelfClosers defines a set of tag names that
* are expected to not have a closing tag, and doNotIndent specifies
* the tags inside of which no indentation should happen (see Config
* object). These can be disabled by passing the editor an object like
* {useHTMLKludges: false} as parserConfig option.
*/
var XMLParser = Editor.Parser = (function() {
var Kludges = {
autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
"meta": true, "col": true, "frame": true, "base": true, "area": true},
doNotIndent: {"pre": true, "!cdata": true}
};
var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}};
var UseKludges = Kludges;
var alignCDATA = false;
// Simple stateful tokenizer for XML documents. Returns a
// MochiKit-style iterator, with a state property that contains a
// function encapsulating the current state. See tokenize.js.
var tokenizeXML = (function() {
function inText(source, setState) {
var ch = source.next();
if (ch == "<") {
if (source.equals("!")) {
source.next();
if (source.equals("[")) {
if (source.lookAhead("[CDATA[", true)) {
setState(inBlock("xml-cdata", "]]>"));
return null;
}
else {
return "xml-text";
}
}
else if (source.lookAhead("--", true)) {
setState(inBlock("xml-comment", "-->"));
return null;
}
else if (source.lookAhead("DOCTYPE", true)) {
source.nextWhileMatches(/[\w\._\-]/);
setState(inBlock("xml-doctype", ">"));
return "xml-doctype";
}
else {
return "xml-text";
}
}
else if (source.equals("?")) {
source.next();
source.nextWhileMatches(/[\w\._\-]/);
setState(inBlock("xml-processing", "?>"));
return "xml-processing";
}
else {
if (source.equals("/")) source.next();
setState(inTag);
return "xml-punctuation";
}
}
else if (ch == "&") {
while (!source.endOfLine()) {
if (source.next() == ";")
break;
}
return "xml-entity";
}
else {
source.nextWhileMatches(/[^&<\n]/);
return "xml-text";
}
}
function inTag(source, setState) {
var ch = source.next();
if (ch == ">") {
setState(inText);
return "xml-punctuation";
}
else if (/[?\/]/.test(ch) && source.equals(">")) {
source.next();
setState(inText);
return "xml-punctuation";
}
else if (ch == "=") {
return "xml-punctuation";
}
else if (/[\'\"]/.test(ch)) {
setState(inAttribute(ch));
return null;
}
else {
source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/);
return "xml-name";
}
}
function inAttribute(quote) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.next() == quote) {
setState(inTag);
break;
}
}
return "xml-attribute";
};
}
function inBlock(style, terminator) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.lookAhead(terminator, true)) {
setState(inText);
break;
}
source.next();
}
return style;
};
}
return function(source, startState) {
return tokenizer(source, startState || inText);
};
})();
// The parser. The structure of this function largely follows that of
// parseJavaScript in parsejavascript.js (there is actually a bit more
// shared code than I'd like), but it is quite a bit simpler.
function parseXML(source) {
var tokens = tokenizeXML(source), token;
var cc = [base];
var tokenNr = 0, indented = 0;
var currentTag = null, context = null;
var consume;
function push(fs) {
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
function cont() {
push(arguments);
consume = true;
}
function pass() {
push(arguments);
consume = false;
}
function markErr() {
token.style += " xml-error";
}
function expect(text) {
return function(style, content) {
if (content == text) cont();
else {markErr(); cont(arguments.callee);}
};
}
function pushContext(tagname, startOfLine) {
var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent);
context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent};
}
function popContext() {
context = context.prev;
}
function computeIndentation(baseContext) {
return function(nextChars, current) {
var context = baseContext;
if (context && context.noIndent)
return current;
if (alignCDATA && /<!\[CDATA\[/.test(nextChars))
return 0;
if (context && /^<\//.test(nextChars))
context = context.prev;
while (context && !context.startOfLine)
context = context.prev;
if (context)
return context.indent + indentUnit;
else
return 0;
};
}
function base() {
return pass(element, base);
}
var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true, "xml-doctype": true};
function element(style, content) {
if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1));
else if (content == "</") cont(closetagname, expect(">"));
else if (style == "xml-cdata") {
if (!context || context.name != "!cdata") pushContext("!cdata");
if (/\]\]>$/.test(content)) popContext();
cont();
}
else if (harmlessTokens.hasOwnProperty(style)) cont();
else {markErr(); cont();}
}
function tagname(style, content) {
if (style == "xml-name") {
currentTag = content.toLowerCase();
token.style = "xml-tagname";
cont();
}
else {
currentTag = null;
pass();
}
}
function closetagname(style, content) {
if (style == "xml-name") {
token.style = "xml-tagname";
if (context && content.toLowerCase() == context.name) popContext();
else markErr();
}
cont();
}
function endtag(startOfLine) {
return function(style, content) {
if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont();
else if (content == ">") {pushContext(currentTag, startOfLine); cont();}
else {markErr(); cont(arguments.callee);}
};
}
function attributes(style) {
if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);}
else pass();
}
function attribute(style, content) {
if (content == "=") cont(value);
else if (content == ">" || content == "/>") pass(endtag);
else pass();
}
function value(style) {
if (style == "xml-attribute") cont(value);
else pass();
}
return {
indentation: function() {return indented;},
next: function(){
token = tokens.next();
if (token.style == "whitespace" && tokenNr == 0)
indented = token.value.length;
else
tokenNr++;
if (token.content == "\n") {
indented = tokenNr = 0;
token.indentation = computeIndentation(context);
}
if (token.style == "whitespace" || token.type == "xml-comment")
return token;
while(true){
consume = false;
cc.pop()(token.style, token.content);
if (consume) return token;
}
},
copy: function(){
var _cc = cc.concat([]), _tokenState = tokens.state, _context = context;
var parser = this;
return function(input){
cc = _cc.concat([]);
tokenNr = indented = 0;
context = _context;
tokens = tokenizeXML(input, _tokenState);
return parser;
};
}
};
}
return {
make: parseXML,
electricChars: "/",
configure: function(config) {
if (config.useHTMLKludges != null)
UseKludges = config.useHTMLKludges ? Kludges : NoKludges;
if (config.alignCDATA)
alignCDATA = config.alignCDATA;
}
};
})();
| JavaScript |
/* String streams are the things fed to parsers (which can feed them
* to a tokenizer if they want). They provide peek and next methods
* for looking at the current character (next 'consumes' this
* character, peek does not), and a get method for retrieving all the
* text that was consumed since the last time get was called.
*
* An easy mistake to make is to let a StopIteration exception finish
* the token stream while there are still characters pending in the
* string stream (hitting the end of the buffer while parsing a
* token). To make it easier to detect such errors, the stringstreams
* throw an exception when this happens.
*/
// Make a stringstream stream out of an iterator that returns strings.
// This is applied to the result of traverseDOM (see codemirror.js),
// and the resulting stream is fed to the parser.
var stringStream = function(source){
// String that's currently being iterated over.
var current = "";
// Position in that string.
var pos = 0;
// Accumulator for strings that have been iterated over but not
// get()-ed yet.
var accum = "";
// Make sure there are more characters ready, or throw
// StopIteration.
function ensureChars() {
while (pos == current.length) {
accum += current;
current = ""; // In case source.next() throws
pos = 0;
try {current = source.next();}
catch (e) {
if (e != StopIteration) throw e;
else return false;
}
}
return true;
}
return {
// peek: -> character
// Return the next character in the stream.
peek: function() {
if (!ensureChars()) return null;
return current.charAt(pos);
},
// next: -> character
// Get the next character, throw StopIteration if at end, check
// for unused content.
next: function() {
if (!ensureChars()) {
if (accum.length > 0)
throw "End of stringstream reached without emptying buffer ('" + accum + "').";
else
throw StopIteration;
}
return current.charAt(pos++);
},
// get(): -> string
// Return the characters iterated over since the last call to
// .get().
get: function() {
var temp = accum;
accum = "";
if (pos > 0){
temp += current.slice(0, pos);
current = current.slice(pos);
pos = 0;
}
return temp;
},
// Push a string back into the stream.
push: function(str) {
current = current.slice(0, pos) + str + current.slice(pos);
},
lookAhead: function(str, consume, skipSpaces, caseInsensitive) {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
str = cased(str);
var found = false;
var _accum = accum, _pos = pos;
if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/);
while (true) {
var end = pos + str.length, left = current.length - pos;
if (end <= current.length) {
found = str == cased(current.slice(pos, end));
pos = end;
break;
}
else if (str.slice(0, left) == cased(current.slice(pos))) {
accum += current; current = "";
try {current = source.next();}
catch (e) {if (e != StopIteration) throw e; break;}
pos = 0;
str = str.slice(left);
}
else {
break;
}
}
if (!(found && consume)) {
current = accum.slice(_accum.length) + current;
pos = _pos;
accum = _accum;
}
return found;
},
// Wont't match past end of line.
lookAheadRegex: function(regex, consume) {
if (regex.source.charAt(0) != "^")
throw new Error("Regexps passed to lookAheadRegex must start with ^");
// Fetch the rest of the line
while (current.indexOf("\n", pos) == -1) {
try {current += source.next();}
catch (e) {if (e != StopIteration) throw e; break;}
}
var matched = current.slice(pos).match(regex);
if (matched && consume) pos += matched[0].length;
return matched;
},
// Utils built on top of the above
// more: -> boolean
// Produce true if the stream isn't empty.
more: function() {
return this.peek() !== null;
},
applies: function(test) {
var next = this.peek();
return (next !== null && test(next));
},
nextWhile: function(test) {
var next;
while ((next = this.peek()) !== null && test(next))
this.next();
},
matches: function(re) {
var next = this.peek();
return (next !== null && re.test(next));
},
nextWhileMatches: function(re) {
var next;
while ((next = this.peek()) !== null && re.test(next))
this.next();
},
equals: function(ch) {
return ch === this.peek();
},
endOfLine: function() {
var next = this.peek();
return next == null || next == "\n";
}
};
};
| JavaScript |
/* CodeMirror main module (http://codemirror.net/)
*
* Implements the CodeMirror constructor and prototype, which take care
* of initializing the editor frame, and providing the outside interface.
*/
// The CodeMirrorConfig object is used to specify a default
// configuration. If you specify such an object before loading this
// file, the values you put into it will override the defaults given
// below. You can also assign to it after loading.
var CodeMirrorConfig = window.CodeMirrorConfig || {};
var CodeMirror = (function(){
function setDefaults(object, defaults) {
for (var option in defaults) {
if (!object.hasOwnProperty(option))
object[option] = defaults[option];
}
}
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
function createHTMLElement(el) {
if (document.createElementNS && document.documentElement.namespaceURI !== null)
return document.createElementNS("http://www.w3.org/1999/xhtml", el)
else
return document.createElement(el)
}
// These default options can be overridden by passing a set of
// options to a specific CodeMirror constructor. See manual.html for
// their meaning.
setDefaults(CodeMirrorConfig, {
stylesheet: [],
path: "",
parserfile: [],
basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
iframeClass: null,
passDelay: 200,
passTime: 50,
lineNumberDelay: 200,
lineNumberTime: 50,
continuousScanning: false,
saveFunction: null,
onLoad: null,
onChange: null,
undoDepth: 50,
undoDelay: 800,
disableSpellcheck: true,
textWrapping: true,
readOnly: false,
width: "",
height: "300px",
minHeight: 100,
onDynamicHeightChange: null,
autoMatchParens: false,
markParen: null,
unmarkParen: null,
parserConfig: null,
tabMode: "indent", // or "spaces", "default", "shift"
enterMode: "indent", // or "keep", "flat"
electricChars: true,
reindentOnLoad: false,
activeTokens: null,
onCursorActivity: null,
lineNumbers: false,
firstLineNumber: 1,
onLineNumberClick: null,
indentUnit: 2,
domain: null,
noScriptCaching: false,
incrementalLoading: false
});
function addLineNumberDiv(container, firstNum) {
var nums = createHTMLElement("div"),
scroller = createHTMLElement("div");
nums.style.position = "absolute";
nums.style.height = "100%";
if (nums.style.setExpression) {
try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");}
catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions
}
nums.style.top = "0px";
nums.style.left = "0px";
nums.style.overflow = "hidden";
container.appendChild(nums);
scroller.className = "CodeMirror-line-numbers";
nums.appendChild(scroller);
scroller.innerHTML = "<div>" + firstNum + "</div>";
return nums;
}
function frameHTML(options) {
if (typeof options.parserfile == "string")
options.parserfile = [options.parserfile];
if (typeof options.basefiles == "string")
options.basefiles = [options.basefiles];
if (typeof options.stylesheet == "string")
options.stylesheet = [options.stylesheet];
var sp = " spellcheck=\"" + (options.disableSpellcheck ? "false" : "true") + "\"";
var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html" + sp + "><head>"];
// Hack to work around a bunch of IE8-specific problems.
html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
var queryStr = options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : "";
forEach(options.stylesheet, function(file) {
html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + queryStr + "\"/>");
});
forEach(options.basefiles.concat(options.parserfile), function(file) {
if (!/^https?:/.test(file)) file = options.path + file;
html.push("<script type=\"text/javascript\" src=\"" + file + queryStr + "\"><" + "/script>");
});
html.push("</head><body style=\"border-width: 0;\" class=\"editbox\"" + sp + "></body></html>");
return html.join("");
}
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
function CodeMirror(place, options) {
// Use passed options, if any, to override defaults.
this.options = options = options || {};
setDefaults(options, CodeMirrorConfig);
// Backward compatibility for deprecated options.
if (options.dumbTabs) options.tabMode = "spaces";
else if (options.normalTab) options.tabMode = "default";
if (options.cursorActivity) options.onCursorActivity = options.cursorActivity;
var frame = this.frame = createHTMLElement("iframe");
if (options.iframeClass) frame.className = options.iframeClass;
frame.frameBorder = 0;
frame.style.border = "0";
frame.style.width = '100%';
frame.style.height = '100%';
// display: block occasionally suppresses some Firefox bugs, so we
// always add it, redundant as it sounds.
frame.style.display = "block";
var div = this.wrapping = createHTMLElement("div");
div.style.position = "relative";
div.className = "CodeMirror-wrapping";
div.style.width = options.width;
div.style.height = (options.height == "dynamic") ? options.minHeight + "px" : options.height;
// This is used by Editor.reroutePasteEvent
var teHack = this.textareaHack = createHTMLElement("textarea");
div.appendChild(teHack);
teHack.style.position = "absolute";
teHack.style.left = "-10000px";
teHack.style.width = "10px";
teHack.tabIndex = 100000;
// Link back to this object, so that the editor can fetch options
// and add a reference to itself.
frame.CodeMirror = this;
if (options.domain && internetExplorer) {
this.html = frameHTML(options);
frame.src = "javascript:(function(){document.open();" +
(options.domain ? "document.domain=\"" + options.domain + "\";" : "") +
"document.write(window.frameElement.CodeMirror.html);document.close();})()";
}
else {
frame.src = "javascript:;";
}
if (place.appendChild) place.appendChild(div);
else place(div);
div.appendChild(frame);
if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div, options.firstLineNumber);
this.win = frame.contentWindow;
if (!options.domain || !internetExplorer) {
this.win.document.open();
this.win.document.write(frameHTML(options));
this.win.document.close();
}
}
CodeMirror.prototype = {
init: function() {
// Deprecated, but still supported.
if (this.options.initCallback) this.options.initCallback(this);
if (this.options.onLoad) this.options.onLoad(this);
if (this.options.lineNumbers) this.activateLineNumbers();
if (this.options.reindentOnLoad) this.reindent();
if (this.options.height == "dynamic") this.setDynamicHeight();
},
getCode: function() {return this.editor.getCode();},
setCode: function(code) {this.editor.importCode(code);},
selection: function() {this.focusIfIE(); return this.editor.selectedText();},
reindent: function() {this.editor.reindent();},
reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);},
focusIfIE: function() {
// in IE, a lot of selection-related functionality only works when the frame is focused
if (this.win.select.ie_selection && document.activeElement != this.frame)
this.focus();
},
focus: function() {
this.win.focus();
if (this.editor.selectionSnapshot) // IE hack
this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot);
},
replaceSelection: function(text) {
this.focus();
this.editor.replaceSelection(text);
return true;
},
replaceChars: function(text, start, end) {
this.editor.replaceChars(text, start, end);
},
getSearchCursor: function(string, fromCursor, caseFold) {
return this.editor.getSearchCursor(string, fromCursor, caseFold);
},
undo: function() {this.editor.history.undo();},
redo: function() {this.editor.history.redo();},
historySize: function() {return this.editor.history.historySize();},
clearHistory: function() {this.editor.history.clear();},
grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);},
ungrabKeys: function() {this.editor.ungrabKeys();},
setParser: function(name, parserConfig) {this.editor.setParser(name, parserConfig);},
setSpellcheck: function(on) {this.win.document.body.spellcheck = on;},
setStylesheet: function(names) {
if (typeof names === "string") names = [names];
var activeStylesheets = {};
var matchedNames = {};
var links = this.win.document.getElementsByTagName("link");
// Create hashes of active stylesheets and matched names.
// This is O(n^2) but n is expected to be very small.
for (var x = 0, link; link = links[x]; x++) {
if (link.rel.indexOf("stylesheet") !== -1) {
for (var y = 0; y < names.length; y++) {
var name = names[y];
if (link.href.substring(link.href.length - name.length) === name) {
activeStylesheets[link.href] = true;
matchedNames[name] = true;
}
}
}
}
// Activate the selected stylesheets and disable the rest.
for (var x = 0, link; link = links[x]; x++) {
if (link.rel.indexOf("stylesheet") !== -1) {
link.disabled = !(link.href in activeStylesheets);
}
}
// Create any new stylesheets.
for (var y = 0; y < names.length; y++) {
var name = names[y];
if (!(name in matchedNames)) {
var link = this.win.document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = name;
this.win.document.getElementsByTagName('head')[0].appendChild(link);
}
}
},
setTextWrapping: function(on) {
if (on == this.options.textWrapping) return;
this.win.document.body.style.whiteSpace = on ? "" : "nowrap";
this.options.textWrapping = on;
if (this.lineNumbers) {
this.setLineNumbers(false);
this.setLineNumbers(true);
}
},
setIndentUnit: function(unit) {this.win.indentUnit = unit;},
setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;},
setTabMode: function(mode) {this.options.tabMode = mode;},
setEnterMode: function(mode) {this.options.enterMode = mode;},
setLineNumbers: function(on) {
if (on && !this.lineNumbers) {
this.lineNumbers = addLineNumberDiv(this.wrapping,this.options.firstLineNumber);
this.activateLineNumbers();
}
else if (!on && this.lineNumbers) {
this.wrapping.removeChild(this.lineNumbers);
this.wrapping.style.paddingLeft = "";
this.lineNumbers = null;
}
},
cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);},
firstLine: function() {return this.editor.firstLine();},
lastLine: function() {return this.editor.lastLine();},
nextLine: function(line) {return this.editor.nextLine(line);},
prevLine: function(line) {return this.editor.prevLine(line);},
lineContent: function(line) {return this.editor.lineContent(line);},
setLineContent: function(line, content) {this.editor.setLineContent(line, content);},
removeLine: function(line){this.editor.removeLine(line);},
insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.win.focus();
this.editor.selectLines(startLine, startOffset, endLine, endOffset);
},
nthLine: function(n) {
var line = this.firstLine();
for (; n > 1 && line !== false; n--)
line = this.nextLine(line);
return line;
},
lineNumber: function(line) {
var num = 0;
while (line !== false) {
num++;
line = this.prevLine(line);
}
return num;
},
jumpToLine: function(line) {
if (typeof line == "number") line = this.nthLine(line);
this.selectLines(line, 0);
this.win.focus();
},
currentLine: function() { // Deprecated, but still there for backward compatibility
return this.lineNumber(this.cursorLine());
},
cursorLine: function() {
return this.cursorPosition().line;
},
cursorCoords: function(start) {return this.editor.cursorCoords(start);},
activateLineNumbers: function() {
var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body,
nums = this.lineNumbers, scroller = nums.firstChild, self = this;
var barWidth = null;
nums.onclick = function(e) {
var handler = self.options.onLineNumberClick;
if (handler) {
var div = (e || window.event).target || (e || window.event).srcElement;
var num = div == nums ? NaN : Number(div.innerHTML);
if (!isNaN(num)) handler(num, div);
}
};
function sizeBar() {
if (frame.offsetWidth == 0) return;
for (var root = frame; root.parentNode; root = root.parentNode){}
if (!nums.parentNode || root != document || !win.Editor) {
// Clear event handlers (their nodes might already be collected, so try/catch)
try{clear();}catch(e){}
clearInterval(sizeInterval);
return;
}
if (nums.offsetWidth != barWidth) {
barWidth = nums.offsetWidth;
frame.parentNode.style.paddingLeft = barWidth + "px";
}
}
function doScroll() {
nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0;
}
// Cleanup function, registered by nonWrapping and wrapping.
var clear = function(){};
sizeBar();
var sizeInterval = setInterval(sizeBar, 500);
function ensureEnoughLineNumbers(fill) {
var lineHeight = scroller.firstChild.offsetHeight;
if (lineHeight == 0) return;
var targetHeight = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0)),
lastNumber = Math.ceil(targetHeight / lineHeight);
for (var i = scroller.childNodes.length; i <= lastNumber; i++) {
var div = createHTMLElement("div");
div.appendChild(document.createTextNode(fill ? String(i + self.options.firstLineNumber) : "\u00a0"));
scroller.appendChild(div);
}
}
function nonWrapping() {
function update() {
ensureEnoughLineNumbers(true);
doScroll();
}
self.updateNumbers = update;
var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function(){
onScroll(); onResize();
if (self.updateNumbers == update) self.updateNumbers = null;
};
update();
}
function wrapping() {
var node, lineNum, next, pos, changes = [], styleNums = self.options.styleNumbers;
function setNum(n, node) {
// Does not typically happen (but can, if you mess with the
// document during the numbering)
if (!lineNum) lineNum = scroller.appendChild(createHTMLElement("div"));
if (styleNums) styleNums(lineNum, node, n);
// Changes are accumulated, so that the document layout
// doesn't have to be recomputed during the pass
changes.push(lineNum); changes.push(n);
pos = lineNum.offsetHeight + lineNum.offsetTop;
lineNum = lineNum.nextSibling;
}
function commitChanges() {
for (var i = 0; i < changes.length; i += 2)
changes[i].innerHTML = changes[i + 1];
changes = [];
}
function work() {
if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return;
var endTime = new Date().getTime() + self.options.lineNumberTime;
while (node) {
setNum(next++, node.previousSibling);
for (; node && !win.isBR(node); node = node.nextSibling) {
var bott = node.offsetTop + node.offsetHeight;
while (scroller.offsetHeight && bott - 3 > pos) {
var oldPos = pos;
setNum(" ");
if (pos <= oldPos) break;
}
}
if (node) node = node.nextSibling;
if (new Date().getTime() > endTime) {
commitChanges();
pending = setTimeout(work, self.options.lineNumberDelay);
return;
}
}
while (lineNum) setNum(next++);
commitChanges();
doScroll();
}
function start(firstTime) {
doScroll();
ensureEnoughLineNumbers(firstTime);
node = body.firstChild;
lineNum = scroller.firstChild;
pos = 0;
next = self.options.firstLineNumber;
work();
}
start(true);
var pending = null;
function update() {
if (pending) clearTimeout(pending);
if (self.editor.allClean()) start();
else pending = setTimeout(update, 200);
}
self.updateNumbers = update;
var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function(){
if (pending) clearTimeout(pending);
if (self.updateNumbers == update) self.updateNumbers = null;
onScroll();
onResize();
};
}
(this.options.textWrapping || this.options.styleNumbers ? wrapping : nonWrapping)();
},
setDynamicHeight: function() {
var self = this, activity = self.options.onCursorActivity, win = self.win, body = win.document.body,
lineHeight = null, timeout = null, vmargin = 2 * self.frame.offsetTop;
body.style.overflowY = "hidden";
win.document.documentElement.style.overflowY = "hidden";
this.frame.scrolling = "no";
function updateHeight() {
var trailingLines = 0, node = body.lastChild, computedHeight;
while (node && win.isBR(node)) {
if (!node.hackBR) trailingLines++;
node = node.previousSibling;
}
if (node) {
lineHeight = node.offsetHeight;
computedHeight = node.offsetTop + (1 + trailingLines) * lineHeight;
}
else if (lineHeight) {
computedHeight = trailingLines * lineHeight;
}
if (computedHeight) {
if (self.options.onDynamicHeightChange)
computedHeight = self.options.onDynamicHeightChange(computedHeight);
if (computedHeight)
self.wrapping.style.height = Math.max(vmargin + computedHeight, self.options.minHeight) + "px";
}
}
setTimeout(updateHeight, 300);
self.options.onCursorActivity = function(x) {
if (activity) activity(x);
clearTimeout(timeout);
timeout = setTimeout(updateHeight, 100);
};
}
};
CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}};
CodeMirror.replace = function(element) {
if (typeof element == "string")
element = document.getElementById(element);
return function(newElement) {
element.parentNode.replaceChild(newElement, element);
};
};
CodeMirror.fromTextArea = function(area, options) {
if (typeof area == "string")
area = document.getElementById(area);
options = options || {};
if (area.style.width && options.width == null)
options.width = area.style.width;
if (area.style.height && options.height == null)
options.height = area.style.height;
if (options.content == null) options.content = area.value;
function updateField() {
area.value = mirror.getCode();
}
if (area.form) {
if (typeof area.form.addEventListener == "function")
area.form.addEventListener("submit", updateField, false);
else
area.form.attachEvent("onsubmit", updateField);
if (typeof area.form.submit == "function") {
var realSubmit = area.form.submit;
function wrapSubmit() {
updateField();
// Can't use realSubmit.apply because IE6 is too stupid
area.form.submit = realSubmit;
area.form.submit();
area.form.submit = wrapSubmit;
}
area.form.submit = wrapSubmit;
}
}
function insert(frame) {
if (area.nextSibling)
area.parentNode.insertBefore(frame, area.nextSibling);
else
area.parentNode.appendChild(frame);
}
area.style.display = "none";
var mirror = new CodeMirror(insert, options);
mirror.save = updateField;
mirror.toTextArea = function() {
updateField();
area.parentNode.removeChild(mirror.wrapping);
area.style.display = "";
if (area.form) {
if (typeof area.form.submit == "function")
area.form.submit = realSubmit;
if (typeof area.form.removeEventListener == "function")
area.form.removeEventListener("submit", updateField, false);
else
area.form.detachEvent("onsubmit", updateField);
}
};
return mirror;
};
CodeMirror.isProbablySupported = function() {
// This is rather awful, but can be useful.
var match;
if (window.opera)
return Number(window.opera.version()) >= 9.52;
else if (/Apple Computer, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
return Number(match[1]) >= 3;
else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
return Number(match[1]) >= 6;
else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
return Number(match[1]) >= 20050901;
else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/))
return Number(match[1]) >= 525;
else
return null;
};
return CodeMirror;
})();
| JavaScript |
/*
Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Dan Vlad Dascalescu <dandv@yahoo-inc.com>
Parse function for PHP. Makes use of the tokenizer from tokenizephp.js.
Based on parsejavascript.js by Marijn Haverbeke.
Features:
+ special "deprecated" style for PHP4 keywords like 'var'
+ support for PHP 5.3 keywords: 'namespace', 'use'
+ 911 predefined constants, 1301 predefined functions, 105 predeclared classes
from a typical PHP installation in a LAMP environment
+ new feature: syntax error flagging, thus enabling strict parsing of:
+ function definitions with explicitly or implicitly typed arguments and default values
+ modifiers (public, static etc.) applied to method and member definitions
+ foreach(array_expression as $key [=> $value]) loops
+ differentiation between single-quoted strings and double-quoted interpolating strings
*/
// add the Array.indexOf method for JS engines that don't support it (e.g. IE)
// code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/IndexOf
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
var PHPParser = Editor.Parser = (function() {
// Token types that can be considered to be atoms, part of operator expressions
var atomicTypes = {
"atom": true, "number": true, "variable": true, "string": true
};
// Constructor for the lexical context objects.
function PHPLexical(indented, column, type, align, prev, info) {
// indentation at start of this line
this.indented = indented;
// column at which this scope was opened
this.column = column;
// type of scope ('stat' (statement), 'form' (special form), '[', '{', or '(')
this.type = type;
// '[', '{', or '(' blocks that have any text after their opening
// character are said to be 'aligned' -- any lines below are
// indented all the way to the opening character.
if (align != null)
this.align = align;
// Parent scope, if any.
this.prev = prev;
this.info = info;
}
// PHP indentation rules
function indentPHP(lexical) {
return function(firstChars) {
var firstChar = firstChars && firstChars.charAt(0), type = lexical.type;
var closing = firstChar == type;
if (type == "form" && firstChar == "{")
return lexical.indented;
else if (type == "stat" || type == "form")
return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit);
else if (lexical.align)
return lexical.column - (closing ? 1 : 0);
else
return lexical.indented + (closing ? 0 : indentUnit);
};
}
// The parser-iterator-producing function itself.
function parsePHP(input, basecolumn) {
// Wrap the input in a token stream
var tokens = tokenizePHP(input);
// The parser state. cc is a stack of actions that have to be
// performed to finish the current statement. For example we might
// know that we still need to find a closing parenthesis and a
// semicolon. Actions at the end of the stack go first. It is
// initialized with an infinitely looping action that consumes
// whole statements.
var cc = [statements];
// The lexical scope, used mostly for indentation.
var lexical = new PHPLexical((basecolumn || 0) - indentUnit, 0, "block", false);
// Current column, and the indentation at the start of the current
// line. Used to create lexical scope objects.
var column = 0;
var indented = 0;
// Variables which are used by the mark, cont, and pass functions
// below to communicate with the driver loop in the 'next' function.
var consume, marked;
// The iterator object.
var parser = {next: next, copy: copy};
// parsing is accomplished by calling next() repeatedly
function next(){
// Start by performing any 'lexical' actions (adjusting the
// lexical variable), or the operations below will be working
// with the wrong lexical state.
while(cc[cc.length - 1].lex)
cc.pop()();
// Fetch the next token.
var token = tokens.next();
// Adjust column and indented.
if (token.type == "whitespace" && column == 0)
indented = token.value.length;
column += token.value.length;
if (token.content == "\n"){
indented = column = 0;
// If the lexical scope's align property is still undefined at
// the end of the line, it is an un-aligned scope.
if (!("align" in lexical))
lexical.align = false;
// Newline tokens get an indentation function associated with
// them.
token.indentation = indentPHP(lexical);
}
// No more processing for meaningless tokens.
if (token.type == "whitespace" || token.type == "comment"
|| token.type == "string_not_terminated" )
return token;
// When a meaningful token is found and the lexical scope's
// align is undefined, it is an aligned scope.
if (!("align" in lexical))
lexical.align = true;
// Execute actions until one 'consumes' the token and we can
// return it. 'marked' is used to change the style of the current token.
while(true) {
consume = marked = false;
// Take and execute the topmost action.
var action = cc.pop();
action(token);
if (consume){
if (marked)
token.style = marked;
// Here we differentiate between local and global variables.
return token;
}
}
return 1; // Firebug workaround for http://code.google.com/p/fbug/issues/detail?id=1239#c1
}
// This makes a copy of the parser state. It stores all the
// stateful variables in a closure, and returns a function that
// will restore them when called with a new input stream. Note
// that the cc array has to be copied, because it is contantly
// being modified. Lexical objects are not mutated, so they can
// be shared between runs of the parser.
function copy(){
var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
return function copyParser(input){
lexical = _lexical;
cc = _cc.concat([]); // copies the array
column = indented = 0;
tokens = tokenizePHP(input, _tokenState);
return parser;
};
}
// Helper function for pushing a number of actions onto the cc
// stack in reverse order.
function push(fs){
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
// cont and pass are used by the action functions to add other
// actions to the stack. cont will cause the current token to be
// consumed, pass will leave it for the next action.
function cont(){
push(arguments);
consume = true;
}
function pass(){
push(arguments);
consume = false;
}
// Used to change the style of the current token.
function mark(style){
marked = style;
}
// Add a lyer of style to the current token, for example syntax-error
function mark_add(style){
marked = marked + ' ' + style;
}
// Push a new lexical context of the given type.
function pushlex(type, info) {
var result = function pushlexing() {
lexical = new PHPLexical(indented, column, type, null, lexical, info)
};
result.lex = true;
return result;
}
// Pop off the current lexical context.
function poplex(){
if (lexical.prev)
lexical = lexical.prev;
}
poplex.lex = true;
// The 'lex' flag on these actions is used by the 'next' function
// to know they can (and have to) be ran before moving on to the
// next token.
// Creates an action that discards tokens until it finds one of
// the given type. This will ignore (and recover from) syntax errors.
function expect(wanted){
return function expecting(token){
if (token.type == wanted) cont(); // consume the token
else {
cont(arguments.callee); // continue expecting() - call itself
}
};
}
// Require a specific token type, or one of the tokens passed in the 'wanted' array
// Used to detect blatant syntax errors. 'execute' is used to pass extra code
// to be executed if the token is matched. For example, a '(' match could
// 'execute' a cont( compasep(funcarg), require(")") )
function require(wanted, execute){
return function requiring(token){
var ok;
var type = token.type;
if (typeof(wanted) == "string")
ok = (type == wanted) -1;
else
ok = wanted.indexOf(type);
if (ok >= 0) {
if (execute && typeof(execute[ok]) == "function") pass(execute[ok]);
else cont();
}
else {
if (!marked) mark(token.style);
mark_add("syntax-error");
cont(arguments.callee);
}
};
}
// Looks for a statement, and then calls itself.
function statements(token){
return pass(statement, statements);
}
// Dispatches various types of statements based on the type of the current token.
function statement(token){
var type = token.type;
if (type == "keyword a") cont(pushlex("form"), expression, altsyntax, statement, poplex);
else if (type == "keyword b") cont(pushlex("form"), altsyntax, statement, poplex);
else if (type == "{") cont(pushlex("}"), block, poplex);
else if (type == "function") funcdef();
// technically, "class implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function
else if (type == "class") classdef();
else if (type == "foreach") cont(pushlex("form"), require("("), pushlex(")"), expression, require("as"), require("variable"), /* => $value */ expect(")"), altsyntax, poplex, statement, poplex);
else if (type == "for") cont(pushlex("form"), require("("), pushlex(")"), expression, require(";"), expression, require(";"), expression, require(")"), altsyntax, poplex, statement, poplex);
// public final function foo(), protected static $bar;
else if (type == "modifier") cont(require(["modifier", "variable", "function", "abstract"],
[null, commasep(require("variable")), funcdef, absfun]));
else if (type == "abstract") abs();
else if (type == "switch") cont(pushlex("form"), require("("), expression, require(")"), pushlex("}", "switch"), require([":", "{"]), block, poplex, poplex);
else if (type == "case") cont(expression, require(":"));
else if (type == "default") cont(require(":"));
else if (type == "catch") cont(pushlex("form"), require("("), require("t_string"), require("variable"), require(")"), statement, poplex);
else if (type == "const") cont(require("t_string")); // 'const static x=5' is a syntax error
// technically, "namespace implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function
else if (type == "namespace") cont(namespacedef, require(";"));
// $variables may be followed by operators, () for variable function calls, or [] subscripts
else pass(pushlex("stat"), expression, require(";"), poplex);
}
// Dispatch expression types.
function expression(token){
var type = token.type;
if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
else if (type == "<<<") cont(require("string"), maybeoperator); // heredoc/nowdoc
else if (type == "t_string") cont(maybe_double_colon, maybeoperator);
else if (type == "keyword c" || type == "operator") cont(expression);
// lambda
else if (type == "function") lambdadef();
// function call or parenthesized expression: $a = ($b + 1) * 2;
else if (type == "(") cont(pushlex(")"), commasep(expression), require(")"), poplex, maybeoperator);
}
// Called for places where operators, function calls, or subscripts are
// valid. Will skip on to the next action if none is found.
function maybeoperator(token){
var type = token.type;
if (type == "operator") {
if (token.content == "?") cont(expression, require(":"), expression); // ternary operator
else cont(expression);
}
else if (type == "(") cont(pushlex(")"), expression, commasep(expression), require(")"), poplex, maybeoperator /* $varfunc() + 3 */);
else if (type == "[") cont(pushlex("]"), expression, require("]"), maybeoperator /* for multidimensional arrays, or $func[$i]() */, poplex);
}
// A regular use of the double colon to specify a class, as in self::func() or myclass::$var;
// Differs from `namespace` or `use` in that only one class can be the parent; chains (A::B::$var) are a syntax error.
function maybe_double_colon(token) {
if (token.type == "t_double_colon")
// A::$var, A::func(), A::const
cont(require(["t_string", "variable"]), maybeoperator);
else {
// a t_string wasn't followed by ::, such as in a function call: foo()
pass(expression)
}
}
// the declaration or definition of a function
function funcdef() {
cont(require("t_string"), require("("), pushlex(")"), commasep(funcarg), require(")"), poplex, block);
}
// the declaration or definition of a lambda
function lambdadef() {
cont(require("("), pushlex(")"), commasep(funcarg), require(")"), maybe_lambda_use, poplex, require("{"), pushlex("}"), block, poplex);
}
// optional lambda 'use' statement
function maybe_lambda_use(token) {
if(token.type == "namespace") {
cont(require('('), commasep(funcarg), require(')'));
}
else {
pass(expression);
}
}
// the definition of a class
function classdef() {
cont(require("t_string"), expect("{"), pushlex("}"), block, poplex);
}
// either funcdef if the current token is "function", or the keyword "function" + funcdef
function absfun(token) {
if(token.type == "function") funcdef();
else cont(require(["function"], [funcdef]));
}
// the abstract class or function (with optional modifier)
function abs(token) {
cont(require(["modifier", "function", "class"], [absfun, funcdef, classdef]));
}
// Parses a comma-separated list of the things that are recognized
// by the 'what' argument.
function commasep(what){
function proceed(token) {
if (token.type == ",") cont(what, proceed);
}
return function commaSeparated() {
pass(what, proceed);
};
}
// Look for statements until a closing brace is found.
function block(token) {
if (token.type == "}") cont();
else pass(statement, block);
}
function empty_parens_if_array(token) {
if(token.content == "array")
cont(require("("), require(")"));
}
function maybedefaultparameter(token){
if (token.content == "=") cont(require(["t_string", "string", "number", "atom"], [empty_parens_if_array, null, null]));
}
function var_or_reference(token) {
if(token.type == "variable") cont(maybedefaultparameter);
else if(token.content == "&") cont(require("variable"), maybedefaultparameter);
}
// support for default arguments: http://us.php.net/manual/en/functions.arguments.php#functions.arguments.default
function funcarg(token){
// function foo(myclass $obj) {...} or function foo(myclass &objref) {...}
if (token.type == "t_string") cont(var_or_reference);
// function foo($var) {...} or function foo(&$ref) {...}
else var_or_reference(token);
}
// A namespace definition or use
function maybe_double_colon_def(token) {
if (token.type == "t_double_colon")
cont(namespacedef);
}
function namespacedef(token) {
pass(require("t_string"), maybe_double_colon_def);
}
function altsyntax(token){
if(token.content==':')
cont(altsyntaxBlock,poplex);
}
function altsyntaxBlock(token){
if (token.type == "altsyntaxend") cont(require(';'));
else pass(statement, altsyntaxBlock);
}
return parser;
}
return {make: parsePHP, electricChars: "{}:"};
})();
| JavaScript |
/* Parse function for JavaScript. Makes use of the tokenizer from
* tokenizejavascript.js. Note that your parsers do not have to be
* this complicated -- if you don't want to recognize local variables,
* in many languages it is enough to just look for braces, semicolons,
* parentheses, etc, and know when you are inside a string or comment.
*
* See manual.html for more info about the parser interface.
*/
var JSParser = Editor.Parser = (function() {
// Token types that can be considered to be atoms.
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
// Setting that can be used to have JSON data indent properly.
var json = false;
// Constructor for the lexical context objects.
function JSLexical(indented, column, type, align, prev, info) {
// indentation at start of this line
this.indented = indented;
// column at which this scope was opened
this.column = column;
// type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(')
this.type = type;
// '[', '{', or '(' blocks that have any text after their opening
// character are said to be 'aligned' -- any lines below are
// indented all the way to the opening character.
if (align != null)
this.align = align;
// Parent scope, if any.
this.prev = prev;
this.info = info;
}
// My favourite JavaScript indentation rules.
function indentJS(lexical) {
return function(firstChars) {
var firstChar = firstChars && firstChars.charAt(0), type = lexical.type;
var closing = firstChar == type;
if (type == "vardef")
return lexical.indented + 4;
else if (type == "form" && firstChar == "{")
return lexical.indented;
else if (type == "stat" || type == "form")
return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit);
else if (lexical.align)
return lexical.column - (closing ? 1 : 0);
else
return lexical.indented + (closing ? 0 : indentUnit);
};
}
// The parser-iterator-producing function itself.
function parseJS(input, basecolumn) {
// Wrap the input in a token stream
var tokens = tokenizeJavaScript(input);
// The parser state. cc is a stack of actions that have to be
// performed to finish the current statement. For example we might
// know that we still need to find a closing parenthesis and a
// semicolon. Actions at the end of the stack go first. It is
// initialized with an infinitely looping action that consumes
// whole statements.
var cc = [json ? expressions : statements];
// Context contains information about the current local scope, the
// variables defined in that, and the scopes above it.
var context = null;
// The lexical scope, used mostly for indentation.
var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false);
// Current column, and the indentation at the start of the current
// line. Used to create lexical scope objects.
var column = 0;
var indented = 0;
// Variables which are used by the mark, cont, and pass functions
// below to communicate with the driver loop in the 'next'
// function.
var consume, marked;
// The iterator object.
var parser = {next: next, copy: copy};
function next(){
// Start by performing any 'lexical' actions (adjusting the
// lexical variable), or the operations below will be working
// with the wrong lexical state.
while(cc[cc.length - 1].lex)
cc.pop()();
// Fetch a token.
var token = tokens.next();
// Adjust column and indented.
if (token.type == "whitespace" && column == 0)
indented = token.value.length;
column += token.value.length;
if (token.content == "\n"){
indented = column = 0;
// If the lexical scope's align property is still undefined at
// the end of the line, it is an un-aligned scope.
if (!("align" in lexical))
lexical.align = false;
// Newline tokens get an indentation function associated with
// them.
token.indentation = indentJS(lexical);
}
// No more processing for meaningless tokens.
if (token.type == "whitespace" || token.type == "comment")
return token;
// When a meaningful token is found and the lexical scope's
// align is undefined, it is an aligned scope.
if (!("align" in lexical))
lexical.align = true;
// Execute actions until one 'consumes' the token and we can
// return it.
while(true) {
consume = marked = false;
// Take and execute the topmost action.
cc.pop()(token.type, token.content);
if (consume){
// Marked is used to change the style of the current token.
if (marked)
token.style = marked;
// Here we differentiate between local and global variables.
else if (token.type == "variable" && inScope(token.content))
token.style = "js-localvariable";
return token;
}
}
}
// This makes a copy of the parser state. It stores all the
// stateful variables in a closure, and returns a function that
// will restore them when called with a new input stream. Note
// that the cc array has to be copied, because it is contantly
// being modified. Lexical objects are not mutated, and context
// objects are not mutated in a harmful way, so they can be shared
// between runs of the parser.
function copy(){
var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
return function copyParser(input){
context = _context;
lexical = _lexical;
cc = _cc.concat([]); // copies the array
column = indented = 0;
tokens = tokenizeJavaScript(input, _tokenState);
return parser;
};
}
// Helper function for pushing a number of actions onto the cc
// stack in reverse order.
function push(fs){
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
// cont and pass are used by the action functions to add other
// actions to the stack. cont will cause the current token to be
// consumed, pass will leave it for the next action.
function cont(){
push(arguments);
consume = true;
}
function pass(){
push(arguments);
consume = false;
}
// Used to change the style of the current token.
function mark(style){
marked = style;
}
// Push a new scope. Will automatically link the current scope.
function pushcontext(){
context = {prev: context, vars: {"this": true, "arguments": true}};
}
// Pop off the current scope.
function popcontext(){
context = context.prev;
}
// Register a variable in the current scope.
function register(varname){
if (context){
mark("js-variabledef");
context.vars[varname] = true;
}
}
// Check whether a variable is defined in the current scope.
function inScope(varname){
var cursor = context;
while (cursor) {
if (cursor.vars[varname])
return true;
cursor = cursor.prev;
}
return false;
}
// Push a new lexical context of the given type.
function pushlex(type, info) {
var result = function(){
lexical = new JSLexical(indented, column, type, null, lexical, info)
};
result.lex = true;
return result;
}
// Pop off the current lexical context.
function poplex(){
if (lexical.type == ")")
indented = lexical.indented;
lexical = lexical.prev;
}
poplex.lex = true;
// The 'lex' flag on these actions is used by the 'next' function
// to know they can (and have to) be ran before moving on to the
// next token.
// Creates an action that discards tokens until it finds one of
// the given type.
function expect(wanted){
return function expecting(type){
if (type == wanted) cont();
else if (wanted == ";") pass();
else cont(arguments.callee);
};
}
// Looks for a statement, and then calls itself.
function statements(type){
return pass(statement, statements);
}
function expressions(type){
return pass(expression, expressions);
}
// Dispatches various types of statements based on the type of the
// current token.
function statement(type){
if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex);
else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex);
else if (type == "keyword b") cont(pushlex("form"), statement, poplex);
else if (type == "{") cont(pushlex("}"), block, poplex);
else if (type == ";") cont();
else if (type == "function") cont(functiondef);
else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex);
else if (type == "variable") cont(pushlex("stat"), maybelabel);
else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex);
else if (type == "case") cont(expression, expect(":"));
else if (type == "default") cont(expect(":"));
else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext);
else pass(pushlex("stat"), expression, expect(";"), poplex);
}
// Dispatch expression types.
function expression(type){
if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
else if (type == "function") cont(functiondef);
else if (type == "keyword c") cont(expression);
else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
else if (type == "operator") cont(expression);
else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
else cont();
}
// Called for places where operators, function calls, or
// subscripts are valid. Will skip on to the next action if none
// is found.
function maybeoperator(type, value){
if (type == "operator" && /\+\+|--/.test(value)) cont(maybeoperator);
else if (type == "operator") cont(expression);
else if (type == ";") pass();
else if (type == "(") cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
else if (type == ".") cont(property, maybeoperator);
else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
// When a statement starts with a variable name, it might be a
// label. If no colon follows, it's a regular statement.
function maybelabel(type){
if (type == ":") cont(poplex, statement);
else pass(maybeoperator, expect(";"), poplex);
}
// Property names need to have their style adjusted -- the
// tokenizer thinks they are variables.
function property(type){
if (type == "variable") {mark("js-property"); cont();}
}
// This parses a property and its value in an object literal.
function objprop(type){
if (type == "variable") mark("js-property");
if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression);
}
// Parses a comma-separated list of the things that are recognized
// by the 'what' argument.
function commasep(what, end){
function proceed(type) {
if (type == ",") cont(what, proceed);
else if (type == end) cont();
else cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) cont();
else pass(what, proceed);
};
}
// Look for statements until a closing brace is found.
function block(type){
if (type == "}") cont();
else pass(statement, block);
}
// Variable definitions are split into two actions -- 1 looks for
// a name or the end of the definition, 2 looks for an '=' sign or
// a comma.
function vardef1(type, value){
if (type == "variable"){register(value); cont(vardef2);}
else cont();
}
function vardef2(type, value){
if (value == "=") cont(expression, vardef2);
else if (type == ",") cont(vardef1);
}
// For loops.
function forspec1(type){
if (type == "var") cont(vardef1, forspec2);
else if (type == ";") pass(forspec2);
else if (type == "variable") cont(formaybein);
else pass(forspec2);
}
function formaybein(type, value){
if (value == "in") cont(expression);
else cont(maybeoperator, forspec2);
}
function forspec2(type, value){
if (type == ";") cont(forspec3);
else if (value == "in") cont(expression);
else cont(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type == ")") pass();
else cont(expression);
}
// A function definition creates a new context, and the variables
// in its argument list have to be added to this context.
function functiondef(type, value){
if (type == "variable"){register(value); cont(functiondef);}
else if (type == "(") cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
}
function funarg(type, value){
if (type == "variable"){register(value); cont();}
}
return parser;
}
return {
make: parseJS,
electricChars: "{}:",
configure: function(obj) {
if (obj.json != null) json = obj.json;
}
};
})();
| JavaScript |
/**
* Storage and control for undo information within a CodeMirror
* editor. 'Why on earth is such a complicated mess required for
* that?', I hear you ask. The goal, in implementing this, was to make
* the complexity of storing and reverting undo information depend
* only on the size of the edited or restored content, not on the size
* of the whole document. This makes it necessary to use a kind of
* 'diff' system, which, when applied to a DOM tree, causes some
* complexity and hackery.
*
* In short, the editor 'touches' BR elements as it parses them, and
* the UndoHistory stores these. When nothing is touched in commitDelay
* milliseconds, the changes are committed: It goes over all touched
* nodes, throws out the ones that did not change since last commit or
* are no longer in the document, and assembles the rest into zero or
* more 'chains' -- arrays of adjacent lines. Links back to these
* chains are added to the BR nodes, while the chain that previously
* spanned these nodes is added to the undo history. Undoing a change
* means taking such a chain off the undo history, restoring its
* content (text is saved per line) and linking it back into the
* document.
*/
// A history object needs to know about the DOM container holding the
// document, the maximum amount of undo levels it should store, the
// delay (of no input) after which it commits a set of changes, and,
// unfortunately, the 'parent' window -- a window that is not in
// designMode, and on which setTimeout works in every browser.
function UndoHistory(container, maxDepth, commitDelay, editor) {
this.container = container;
this.maxDepth = maxDepth; this.commitDelay = commitDelay;
this.editor = editor;
// This line object represents the initial, empty editor.
var initial = {text: "", from: null, to: null};
// As the borders between lines are represented by BR elements, the
// start of the first line and the end of the last one are
// represented by null. Since you can not store any properties
// (links to line objects) in null, these properties are used in
// those cases.
this.first = initial; this.last = initial;
// Similarly, a 'historyTouched' property is added to the BR in
// front of lines that have already been touched, and 'firstTouched'
// is used for the first line.
this.firstTouched = false;
// History is the set of committed changes, touched is the set of
// nodes touched since the last commit.
this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0;
}
UndoHistory.prototype = {
// Schedule a commit (if no other touches come in for commitDelay
// milliseconds).
scheduleCommit: function() {
var self = this;
parent.clearTimeout(this.commitTimeout);
this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
},
// Mark a node as touched. Null is a valid argument.
touch: function(node) {
this.setTouched(node);
this.scheduleCommit();
},
// Undo the last change.
undo: function() {
// Make sure pending changes have been committed.
this.commit();
if (this.history.length) {
// Take the top diff from the history, apply it, and store its
// shadow in the redo history.
var item = this.history.pop();
this.redoHistory.push(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
// Redo the last undone change.
redo: function() {
this.commit();
if (this.redoHistory.length) {
// The inverse of undo, basically.
var item = this.redoHistory.pop();
this.addUndoLevel(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
clear: function() {
this.history = [];
this.redoHistory = [];
this.lostundo = 0;
},
// Ask for the size of the un/redo histories.
historySize: function() {
return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo};
},
// Push a changeset into the document.
push: function(from, to, lines) {
var chain = [];
for (var i = 0; i < lines.length; i++) {
var end = (i == lines.length - 1) ? to : document.createElement("br");
chain.push({from: from, to: end, text: cleanText(lines[i])});
from = end;
}
this.pushChains([chain], from == null && to == null);
this.notifyEnvironment();
},
pushChains: function(chains, doNotHighlight) {
this.commit(doNotHighlight);
this.addUndoLevel(this.updateTo(chains, "applyChain"));
this.redoHistory = [];
},
// Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
chainNode: function(chains) {
for (var i = 0; i < chains.length; i++) {
var start = chains[i][0], node = start && (start.from || start.to);
if (node) return node;
}
},
// Clear the undo history, make the current document the start
// position.
reset: function() {
this.history = []; this.redoHistory = []; this.lostundo = 0;
},
textAfter: function(br) {
return this.after(br).text;
},
nodeAfter: function(br) {
return this.after(br).to;
},
nodeBefore: function(br) {
return this.before(br).from;
},
// Commit unless there are pending dirty nodes.
tryCommit: function() {
if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded
if (this.editor.highlightDirty()) this.commit(true);
else this.scheduleCommit();
},
// Check whether the touched nodes hold any changes, if so, commit
// them.
commit: function(doNotHighlight) {
parent.clearTimeout(this.commitTimeout);
// Make sure there are no pending dirty nodes.
if (!doNotHighlight) this.editor.highlightDirty(true);
// Build set of chains.
var chains = this.touchedChains(), self = this;
if (chains.length) {
this.addUndoLevel(this.updateTo(chains, "linkChain"));
this.redoHistory = [];
this.notifyEnvironment();
}
},
// [ end of public interface ]
// Update the document with a given set of chains, return its
// shadow. updateFunc should be "applyChain" or "linkChain". In the
// second case, the chains are taken to correspond the the current
// document, and only the state of the line data is updated. In the
// first case, the content of the chains is also pushed iinto the
// document.
updateTo: function(chains, updateFunc) {
var shadows = [], dirty = [];
for (var i = 0; i < chains.length; i++) {
shadows.push(this.shadowChain(chains[i]));
dirty.push(this[updateFunc](chains[i]));
}
if (updateFunc == "applyChain")
this.notifyDirty(dirty);
return shadows;
},
// Notify the editor that some nodes have changed.
notifyDirty: function(nodes) {
forEach(nodes, method(this.editor, "addDirtyNode"))
this.editor.scheduleHighlight();
},
notifyEnvironment: function() {
if (this.onChange) this.onChange(this.editor);
// Used by the line-wrapping line-numbering code.
if (window.frameElement && window.frameElement.CodeMirror.updateNumbers)
window.frameElement.CodeMirror.updateNumbers();
},
// Link a chain into the DOM nodes (or the first/last links for null
// nodes).
linkChain: function(chain) {
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
if (line.from) line.from.historyAfter = line;
else this.first = line;
if (line.to) line.to.historyBefore = line;
else this.last = line;
}
},
// Get the line object after/before a given node.
after: function(node) {
return node ? node.historyAfter : this.first;
},
before: function(node) {
return node ? node.historyBefore : this.last;
},
// Mark a node as touched if it has not already been marked.
setTouched: function(node) {
if (node) {
if (!node.historyTouched) {
this.touched.push(node);
node.historyTouched = true;
}
}
else {
this.firstTouched = true;
}
},
// Store a new set of undo info, throw away info if there is more of
// it than allowed.
addUndoLevel: function(diffs) {
this.history.push(diffs);
if (this.history.length > this.maxDepth) {
this.history.shift();
this.lostundo += 1;
}
},
// Build chains from a set of touched nodes.
touchedChains: function() {
var self = this;
// The temp system is a crummy hack to speed up determining
// whether a (currently touched) node has a line object associated
// with it. nullTemp is used to store the object for the first
// line, other nodes get it stored in their historyTemp property.
var nullTemp = null;
function temp(node) {return node ? node.historyTemp : nullTemp;}
function setTemp(node, line) {
if (node) node.historyTemp = line;
else nullTemp = line;
}
function buildLine(node) {
var text = [];
for (var cur = node ? node.nextSibling : self.container.firstChild;
cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling)
if (!cur.hackBR && cur.currentText) text.push(cur.currentText);
return {from: node, to: cur, text: cleanText(text.join(""))};
}
// Filter out unchanged lines and nodes that are no longer in the
// document. Build up line objects for remaining nodes.
var lines = [];
if (self.firstTouched) self.touched.push(null);
forEach(self.touched, function(node) {
if (node && (node.parentNode != self.container || node.hackBR)) return;
if (node) node.historyTouched = false;
else self.firstTouched = false;
var line = buildLine(node), shadow = self.after(node);
if (!shadow || shadow.text != line.text || shadow.to != line.to) {
lines.push(line);
setTemp(node, line);
}
});
// Get the BR element after/before the given node.
function nextBR(node, dir) {
var link = dir + "Sibling", search = node[link];
while (search && !isBR(search))
search = search[link];
return search;
}
// Assemble line objects into chains by scanning the DOM tree
// around them.
var chains = []; self.touched = [];
forEach(lines, function(line) {
// Note that this makes the loop skip line objects that have
// been pulled into chains by lines before them.
if (!temp(line.from)) return;
var chain = [], curNode = line.from, safe = true;
// Put any line objects (referred to by temp info) before this
// one on the front of the array.
while (true) {
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.unshift(curLine);
setTemp(curNode, null);
if (!curNode) break;
safe = self.after(curNode);
curNode = nextBR(curNode, "previous");
}
curNode = line.to; safe = self.before(line.from);
// Add lines after this one at end of array.
while (true) {
if (!curNode) break;
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.push(curLine);
setTemp(curNode, null);
safe = self.before(curNode);
curNode = nextBR(curNode, "next");
}
chains.push(chain);
});
return chains;
},
// Find the 'shadow' of a given chain by following the links in the
// DOM nodes at its start and end.
shadowChain: function(chain) {
var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
while (true) {
shadows.push(next);
var nextNode = next.to;
if (!nextNode || nextNode == end)
break;
else
next = nextNode.historyAfter || this.before(end);
// (The this.before(end) is a hack -- FF sometimes removes
// properties from BR nodes, in which case the best we can hope
// for is to not break.)
}
return shadows;
},
// Update the DOM tree to contain the lines specified in a given
// chain, link this chain into the DOM nodes.
applyChain: function(chain) {
// Some attempt is made to prevent the cursor from jumping
// randomly when an undo or redo happens. It still behaves a bit
// strange sometimes.
var cursor = select.cursorPos(this.container, false), self = this;
// Remove all nodes in the DOM tree between from and to (null for
// start/end of container).
function removeRange(from, to) {
var pos = from ? from.nextSibling : self.container.firstChild;
while (pos != to) {
var temp = pos.nextSibling;
removeElement(pos);
pos = temp;
}
}
var start = chain[0].from, end = chain[chain.length - 1].to;
// Clear the space where this change has to be made.
removeRange(start, end);
// Insert the content specified by the chain into the DOM tree.
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
// The start and end of the space are already correct, but BR
// tags inside it have to be put back.
if (i > 0)
self.container.insertBefore(line.from, end);
// Add the text.
var node = makePartSpan(fixSpaces(line.text));
self.container.insertBefore(node, end);
// See if the cursor was on this line. Put it back, adjusting
// for changed line length, if it was.
if (cursor && cursor.node == line.from) {
var cursordiff = 0;
var prev = this.after(line.from);
if (prev && i == chain.length - 1) {
// Only adjust if the cursor is after the unchanged part of
// the line.
for (var match = 0; match < cursor.offset &&
line.text.charAt(match) == prev.text.charAt(match); match++){}
if (cursor.offset > match)
cursordiff = line.text.length - prev.text.length;
}
select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
}
// Cursor was in removed line, this is last new line.
else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
}
}
// Anchor the chain in the DOM tree.
this.linkChain(chain);
return start;
}
};
| JavaScript |
var DummyParser = Editor.Parser = (function() {
function tokenizeDummy(source) {
while (!source.endOfLine()) source.next();
return "text";
}
function parseDummy(source) {
function indentTo(n) {return function() {return n;}}
source = tokenizer(source, tokenizeDummy);
var space = 0;
var iter = {
next: function() {
var tok = source.next();
if (tok.type == "whitespace") {
if (tok.value == "\n") tok.indentation = indentTo(space);
else space = tok.value.length;
}
return tok;
},
copy: function() {
var _space = space;
return function(_source) {
space = _space;
source = tokenizer(_source, tokenizeDummy);
return iter;
};
}
};
return iter;
}
return {make: parseDummy};
})();
| JavaScript |
/* A few useful utility functions. */
// Capture a method on an object.
function method(obj, name) {
return function() {obj[name].apply(obj, arguments);};
}
// The value used to signal the end of a sequence in iterators.
var StopIteration = {toString: function() {return "StopIteration"}};
// Apply a function to each element in a sequence.
function forEach(iter, f) {
if (iter.next) {
try {while (true) f(iter.next());}
catch (e) {if (e != StopIteration) throw e;}
}
else {
for (var i = 0; i < iter.length; i++)
f(iter[i]);
}
}
// Map a function over a sequence, producing an array of results.
function map(iter, f) {
var accum = [];
forEach(iter, function(val) {accum.push(f(val));});
return accum;
}
// Create a predicate function that tests a string againsts a given
// regular expression. No longer used but might be used by 3rd party
// parsers.
function matcher(regexp){
return function(value){return regexp.test(value);};
}
// Test whether a DOM node has a certain CSS class.
function hasClass(element, className) {
var classes = element.className;
return classes && new RegExp("(^| )" + className + "($| )").test(classes);
}
function removeClass(element, className) {
element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), "");
return element;
}
// Insert a DOM node after another node.
function insertAfter(newNode, oldNode) {
var parent = oldNode.parentNode;
parent.insertBefore(newNode, oldNode.nextSibling);
return newNode;
}
function removeElement(node) {
if (node.parentNode)
node.parentNode.removeChild(node);
}
function clearElement(node) {
while (node.firstChild)
node.removeChild(node.firstChild);
}
// Check whether a node is contained in another one.
function isAncestor(node, child) {
while (child = child.parentNode) {
if (node == child)
return true;
}
return false;
}
// The non-breaking space character.
var nbsp = "\u00a0";
var matching = {"{": "}", "[": "]", "(": ")",
"}": "{", "]": "[", ")": "("};
// Standardize a few unportable event properties.
function normalizeEvent(event) {
if (!event.stopPropagation) {
event.stopPropagation = function() {this.cancelBubble = true;};
event.preventDefault = function() {this.returnValue = false;};
}
if (!event.stop) {
event.stop = function() {
this.stopPropagation();
this.preventDefault();
};
}
if (event.type == "keypress") {
event.code = (event.charCode == null) ? event.keyCode : event.charCode;
event.character = String.fromCharCode(event.code);
}
return event;
}
// Portably register event handlers.
function addEventHandler(node, type, handler, removeFunc) {
function wrapHandler(event) {
handler(normalizeEvent(event || window.event));
}
if (typeof node.addEventListener == "function") {
node.addEventListener(type, wrapHandler, false);
if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);};
}
else {
node.attachEvent("on" + type, wrapHandler);
if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
function nodeText(node) {
return node.textContent || node.innerText || node.nodeValue || "";
}
function nodeTop(node) {
var top = 0;
while (node.offsetParent) {
top += node.offsetTop;
node = node.offsetParent;
}
return top;
}
function isBR(node) {
var nn = node.nodeName;
return nn == "BR" || nn == "br";
}
function isSpan(node) {
var nn = node.nodeName;
return nn == "SPAN" || nn == "span";
}
| JavaScript |
/* Functionality for finding, storing, and restoring selections
*
* This does not provide a generic API, just the minimal functionality
* required by the CodeMirror system.
*/
// Namespace object.
var select = {};
(function() {
select.ie_selection = document.selection && document.selection.createRangeCollection;
// Find the 'top-level' (defined as 'a direct child of the node
// passed as the top argument') node that the given node is
// contained in. Return null if the given node is not inside the top
// node.
function topLevelNodeAt(node, top) {
while (node && node.parentNode != top)
node = node.parentNode;
return node;
}
// Find the top-level node that contains the node before this one.
function topLevelNodeBefore(node, top) {
while (!node.previousSibling && node.parentNode != top)
node = node.parentNode;
return topLevelNodeAt(node.previousSibling, top);
}
var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
select.scrollToNode = function(node, cursor) {
if (!node) return;
var element = node, body = document.body,
html = document.documentElement,
atEnd = !element.nextSibling || !element.nextSibling.nextSibling
|| !element.nextSibling.nextSibling.nextSibling;
// In Opera (and recent Webkit versions), BR elements *always*
// have a offsetTop property of zero.
var compensateHack = 0;
while (element && !element.offsetTop) {
compensateHack++;
element = element.previousSibling;
}
// atEnd is another kludge for these browsers -- if the cursor is
// at the end of the document, and the node doesn't have an
// offset, just scroll to the end.
if (compensateHack == 0) atEnd = false;
// WebKit has a bad habit of (sometimes) happily returning bogus
// offsets when the document has just been changed. This seems to
// always be 5/5, so we don't use those.
if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5)
return;
var y = compensateHack * (element ? element.offsetHeight : 0), x = 0,
width = (node ? node.offsetWidth : 0), pos = element;
while (pos && pos.offsetParent) {
y += pos.offsetTop;
// Don't count X offset for <br> nodes
if (!isBR(pos))
x += pos.offsetLeft;
pos = pos.offsetParent;
}
var scroll_x = body.scrollLeft || html.scrollLeft || 0,
scroll_y = body.scrollTop || html.scrollTop || 0,
scroll = false, screen_width = window.innerWidth || html.clientWidth || 0;
if (cursor || width < screen_width) {
if (cursor) {
var off = select.offsetInNode(node), size = nodeText(node).length;
if (size) x += width * (off / size);
}
var screen_x = x - scroll_x;
if (screen_x < 0 || screen_x > screen_width) {
scroll_x = x;
scroll = true;
}
}
var screen_y = y - scroll_y;
if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) {
scroll_y = atEnd ? 1e6 : y;
scroll = true;
}
if (scroll) window.scrollTo(scroll_x, scroll_y);
};
select.scrollToCursor = function(container) {
select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true);
};
// Used to prevent restoring a selection when we do not need to.
var currentSelection = null;
select.snapshotChanged = function() {
if (currentSelection) currentSelection.changed = true;
};
// Find the 'leaf' node (BR or text) after the given one.
function baseNodeAfter(node) {
var next = node.nextSibling;
if (next) {
while (next.firstChild) next = next.firstChild;
if (next.nodeType == 3 || isBR(next)) return next;
else return baseNodeAfter(next);
}
else {
var parent = node.parentNode;
while (parent && !parent.nextSibling) parent = parent.parentNode;
return parent && baseNodeAfter(parent);
}
}
// This is called by the code in editor.js whenever it is replacing
// a text node. The function sees whether the given oldNode is part
// of the current selection, and updates this selection if it is.
// Because nodes are often only partially replaced, the length of
// the part that gets replaced has to be taken into account -- the
// selection might stay in the oldNode if the newNode is smaller
// than the selection's offset. The offset argument is needed in
// case the selection does move to the new object, and the given
// length is not the whole length of the new node (part of it might
// have been used to replace another node).
select.snapshotReplaceNode = function(from, to, length, offset) {
if (!currentSelection) return;
function replace(point) {
if (from == point.node) {
currentSelection.changed = true;
if (length && point.offset > length) {
point.offset -= length;
}
else {
point.node = to;
point.offset += (offset || 0);
}
}
else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) {
currentSelection.changed = true;
}
}
replace(currentSelection.start);
replace(currentSelection.end);
};
select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
if (!currentSelection) return;
function move(point) {
if (from == point.node && (!ifAtStart || point.offset == 0)) {
currentSelection.changed = true;
point.node = to;
if (relative) point.offset = Math.max(0, point.offset + distance);
else point.offset = distance;
}
}
move(currentSelection.start);
move(currentSelection.end);
};
// Most functions are defined in two ways, one for the IE selection
// model, one for the W3C one.
if (select.ie_selection) {
function selRange() {
var sel = document.selection;
if (!sel) return null;
if (sel.createRange) return sel.createRange();
else return sel.createTextRange();
}
function selectionNode(start) {
var range = selRange();
range.collapse(start);
function nodeAfter(node) {
var found = null;
while (!found && node) {
found = node.nextSibling;
node = node.parentNode;
}
return nodeAtStartOf(found);
}
function nodeAtStartOf(node) {
while (node && node.firstChild) node = node.firstChild;
return {node: node, offset: 0};
}
var containing = range.parentElement();
if (!isAncestor(document.body, containing)) return null;
if (!containing.firstChild) return nodeAtStartOf(containing);
var working = range.duplicate();
working.moveToElementText(containing);
working.collapse(true);
for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
if (cur.nodeType == 3) {
var size = cur.nodeValue.length;
working.move("character", size);
}
else {
working.moveToElementText(cur);
working.collapse(false);
}
var dir = range.compareEndPoints("StartToStart", working);
if (dir == 0) return nodeAfter(cur);
if (dir == 1) continue;
if (cur.nodeType != 3) return nodeAtStartOf(cur);
working.setEndPoint("StartToEnd", range);
return {node: cur, offset: size - working.text.length};
}
return nodeAfter(containing);
}
select.markSelection = function() {
currentSelection = null;
var sel = document.selection;
if (!sel) return;
var start = selectionNode(true),
end = selectionNode(false);
if (!start || !end) return;
currentSelection = {start: start, end: end, changed: false};
};
select.selectMarked = function() {
if (!currentSelection || !currentSelection.changed) return;
function makeRange(point) {
var range = document.body.createTextRange(),
node = point.node;
if (!node) {
range.moveToElementText(document.body);
range.collapse(false);
}
else if (node.nodeType == 3) {
range.moveToElementText(node.parentNode);
var offset = point.offset;
while (node.previousSibling) {
node = node.previousSibling;
offset += (node.innerText || "").length;
}
range.move("character", offset);
}
else {
range.moveToElementText(node);
range.collapse(true);
}
return range;
}
var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
start.setEndPoint("StartToEnd", end);
start.select();
};
select.offsetInNode = function(node) {
var range = selRange();
if (!range) return 0;
var range2 = range.duplicate();
try {range2.moveToElementText(node);} catch(e){return 0;}
range.setEndPoint("StartToStart", range2);
return range.text.length;
};
// Get the top-level node that one end of the cursor is inside or
// after. Note that this returns false for 'no cursor', and null
// for 'start of document'.
select.selectionTopNode = function(container, start) {
var range = selRange();
if (!range) return false;
var range2 = range.duplicate();
range.collapse(start);
var around = range.parentElement();
if (around && isAncestor(container, around)) {
// Only use this node if the selection is not at its start.
range2.moveToElementText(around);
if (range.compareEndPoints("StartToStart", range2) == 1)
return topLevelNodeAt(around, container);
}
// Move the start of a range to the start of a node,
// compensating for the fact that you can't call
// moveToElementText with text nodes.
function moveToNodeStart(range, node) {
if (node.nodeType == 3) {
var count = 0, cur = node.previousSibling;
while (cur && cur.nodeType == 3) {
count += cur.nodeValue.length;
cur = cur.previousSibling;
}
if (cur) {
try{range.moveToElementText(cur);}
catch(e){return false;}
range.collapse(false);
}
else range.moveToElementText(node.parentNode);
if (count) range.move("character", count);
}
else {
try{range.moveToElementText(node);}
catch(e){return false;}
}
return true;
}
// Do a binary search through the container object, comparing
// the start of each node to the selection
var start = 0, end = container.childNodes.length - 1;
while (start < end) {
var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
if (!node) return false; // Don't ask. IE6 manages this sometimes.
if (!moveToNodeStart(range2, node)) return false;
if (range.compareEndPoints("StartToStart", range2) == 1)
start = middle;
else
end = middle - 1;
}
if (start == 0) {
var test1 = selRange(), test2 = test1.duplicate();
try {
test2.moveToElementText(container);
} catch(exception) {
return null;
}
if (test1.compareEndPoints("StartToStart", test2) == 0)
return null;
}
return container.childNodes[start] || null;
};
// Place the cursor after this.start. This is only useful when
// manually moving the cursor instead of restoring it to its old
// position.
select.focusAfterNode = function(node, container) {
var range = document.body.createTextRange();
range.moveToElementText(node || container);
range.collapse(!node);
range.select();
};
select.somethingSelected = function() {
var range = selRange();
return range && (range.text != "");
};
function insertAtCursor(html) {
var range = selRange();
if (range) {
range.pasteHTML(html);
range.collapse(false);
range.select();
}
}
// Used to normalize the effect of the enter key, since browsers
// do widely different things when pressing enter in designMode.
select.insertNewlineAtCursor = function() {
insertAtCursor("<br>");
};
select.insertTabAtCursor = function() {
insertAtCursor(fourSpaces);
};
// Get the BR node at the start of the line on which the cursor
// currently is, and the offset into the line. Returns null as
// node if cursor is on first line.
select.cursorPos = function(container, start) {
var range = selRange();
if (!range) return null;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
var range2 = range.duplicate();
range.collapse(start);
if (topNode) {
range2.moveToElementText(topNode);
range2.collapse(false);
}
else {
// When nothing is selected, we can get all kinds of funky errors here.
try { range2.moveToElementText(container); }
catch (e) { return null; }
range2.collapse(true);
}
range.setEndPoint("StartToStart", range2);
return {node: topNode, offset: range.text.length};
};
select.setCursorPos = function(container, from, to) {
function rangeAt(pos) {
var range = document.body.createTextRange();
if (!pos.node) {
range.moveToElementText(container);
range.collapse(true);
}
else {
range.moveToElementText(pos.node);
range.collapse(false);
}
range.move("character", pos.offset);
return range;
}
var range = rangeAt(from);
if (to && to != from)
range.setEndPoint("EndToEnd", rangeAt(to));
range.select();
}
// Some hacks for storing and re-storing the selection when the editor loses and regains focus.
select.getBookmark = function (container) {
var from = select.cursorPos(container, true), to = select.cursorPos(container, false);
if (from && to) return {from: from, to: to};
};
// Restore a stored selection.
select.setBookmark = function(container, mark) {
if (!mark) return;
select.setCursorPos(container, mark.from, mark.to);
};
}
// W3C model
else {
// Find the node right at the cursor, not one of its
// ancestors with a suitable offset. This goes down the DOM tree
// until a 'leaf' is reached (or is it *up* the DOM tree?).
function innerNode(node, offset) {
while (node.nodeType != 3 && !isBR(node)) {
var newNode = node.childNodes[offset] || node.nextSibling;
offset = 0;
while (!newNode && node.parentNode) {
node = node.parentNode;
newNode = node.nextSibling;
}
node = newNode;
if (!newNode) break;
}
return {node: node, offset: offset};
}
// Store start and end nodes, and offsets within these, and refer
// back to the selection object from those nodes, so that this
// object can be updated when the nodes are replaced before the
// selection is restored.
select.markSelection = function () {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return (currentSelection = null);
var range = selection.getRangeAt(0);
currentSelection = {
start: innerNode(range.startContainer, range.startOffset),
end: innerNode(range.endContainer, range.endOffset),
changed: false
};
};
select.selectMarked = function () {
var cs = currentSelection;
// on webkit-based browsers, it is apparently possible that the
// selection gets reset even when a node that is not one of the
// endpoints get messed with. the most common situation where
// this occurs is when a selection is deleted or overwitten. we
// check for that here.
function focusIssue() {
if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0) return true;
var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset);
return cs.start.node != point.node || cs.start.offset != point.offset;
}
}
if (!cs || !(cs.changed || (webkit && focusIssue()))) return;
var range = document.createRange();
function setPoint(point, which) {
if (point.node) {
// Some magic to generalize the setting of the start and end
// of a range.
if (point.offset == 0)
range["set" + which + "Before"](point.node);
else
range["set" + which](point.node, point.offset);
}
else {
range.setStartAfter(document.body.lastChild || document.body);
}
}
setPoint(cs.end, "End");
setPoint(cs.start, "Start");
selectRange(range);
};
// Helper for selecting a range object.
function selectRange(range) {
var selection = window.getSelection();
if (!selection) return;
selection.removeAllRanges();
selection.addRange(range);
}
function selectionRange() {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return false;
else
return selection.getRangeAt(0);
}
// Finding the top-level node at the cursor in the W3C is, as you
// can see, quite an involved process.
select.selectionTopNode = function(container, start) {
var range = selectionRange();
if (!range) return false;
var node = start ? range.startContainer : range.endContainer;
var offset = start ? range.startOffset : range.endOffset;
// Work around (yet another) bug in Opera's selection model.
if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
offset--;
// For text nodes, we look at the node itself if the cursor is
// inside, or at the node before it if the cursor is at the
// start.
if (node.nodeType == 3){
if (offset > 0)
return topLevelNodeAt(node, container);
else
return topLevelNodeBefore(node, container);
}
// Occasionally, browsers will return the HTML node as
// selection. If the offset is 0, we take the start of the frame
// ('after null'), otherwise, we take the last node.
else if (node.nodeName.toUpperCase() == "HTML") {
return (offset == 1 ? null : container.lastChild);
}
// If the given node is our 'container', we just look up the
// correct node by using the offset.
else if (node == container) {
return (offset == 0) ? null : node.childNodes[offset - 1];
}
// In any other case, we have a regular node. If the cursor is
// at the end of the node, we use the node itself, if it is at
// the start, we use the node before it, and in any other
// case, we look up the child before the cursor and use that.
else {
if (offset == node.childNodes.length)
return topLevelNodeAt(node, container);
else if (offset == 0)
return topLevelNodeBefore(node, container);
else
return topLevelNodeAt(node.childNodes[offset - 1], container);
}
};
select.focusAfterNode = function(node, container) {
var range = document.createRange();
range.setStartBefore(container.firstChild || container);
// In Opera, setting the end of a range at the end of a line
// (before a BR) will cause the cursor to appear on the next
// line, so we set the end inside of the start node when
// possible.
if (node && !node.firstChild)
range.setEndAfter(node);
else if (node)
range.setEnd(node, node.childNodes.length);
else
range.setEndBefore(container.firstChild || container);
range.collapse(false);
selectRange(range);
};
select.somethingSelected = function() {
var range = selectionRange();
return range && !range.collapsed;
};
select.offsetInNode = function(node) {
var range = selectionRange();
if (!range) return 0;
range = range.cloneRange();
range.setStartBefore(node);
return range.toString().length;
};
select.insertNodeAtCursor = function(node) {
var range = selectionRange();
if (!range) return;
range.deleteContents();
range.insertNode(node);
webkitLastLineHack(document.body);
// work around weirdness where Opera will magically insert a new
// BR node when a BR node inside a span is moved around. makes
// sure the BR ends up outside of spans.
if (window.opera && isBR(node) && isSpan(node.parentNode)) {
var next = node.nextSibling, p = node.parentNode, outer = p.parentNode;
outer.insertBefore(node, p.nextSibling);
var textAfter = "";
for (; next && next.nodeType == 3; next = next.nextSibling) {
textAfter += next.nodeValue;
removeElement(next);
}
outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling);
}
range = document.createRange();
range.selectNode(node);
range.collapse(false);
selectRange(range);
}
select.insertNewlineAtCursor = function() {
select.insertNodeAtCursor(document.createElement("BR"));
};
select.insertTabAtCursor = function() {
select.insertNodeAtCursor(document.createTextNode(fourSpaces));
};
select.cursorPos = function(container, start) {
var range = selectionRange();
if (!range) return;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
range = range.cloneRange();
range.collapse(start);
if (topNode)
range.setStartAfter(topNode);
else
range.setStartBefore(container);
var text = range.toString();
return {node: topNode, offset: text.length};
};
select.setCursorPos = function(container, from, to) {
var range = document.createRange();
function setPoint(node, offset, side) {
if (offset == 0 && node && !node.nextSibling) {
range["set" + side + "After"](node);
return true;
}
if (!node)
node = container.firstChild;
else
node = node.nextSibling;
if (!node) return;
if (offset == 0) {
range["set" + side + "Before"](node);
return true;
}
var backlog = []
function decompose(node) {
if (node.nodeType == 3)
backlog.push(node);
else
forEach(node.childNodes, decompose);
}
while (true) {
while (node && !backlog.length) {
decompose(node);
node = node.nextSibling;
}
var cur = backlog.shift();
if (!cur) return false;
var length = cur.nodeValue.length;
if (length >= offset) {
range["set" + side](cur, offset);
return true;
}
offset -= length;
}
}
to = to || from;
if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
selectRange(range);
};
}
})();
| JavaScript |
/*
Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Vlad Dan Dascalescu <dandv@yahoo-inc.com>
Tokenizer for PHP code
References:
+ http://php.net/manual/en/reserved.php
+ http://php.net/tokens
+ get_defined_constants(), get_defined_functions(), get_declared_classes()
executed on a realistic (not vanilla) PHP installation with typical LAMP modules.
Specifically, the PHP bundled with the Uniform Web Server (www.uniformserver.com).
*/
// add the forEach method for JS engines that don't support it (e.g. IE)
// code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
var tokenizePHP = (function() {
/* A map of PHP's reserved words (keywords, predefined classes, functions and
constants. Each token has a type ('keyword', 'operator' etc.) and a style.
The style corresponds to the CSS span class in phpcolors.css.
Keywords can be of three types:
a - takes an expression and forms a statement - e.g. if
b - takes just a statement - e.g. else
c - takes an optinoal expression, but no statement - e.g. return
This distinction gives the parser enough information to parse
correct code correctly (we don't care that much how we parse
incorrect code).
Reference: http://us.php.net/manual/en/reserved.php
*/
var keywords = function(){
function token(type, style){
return {type: type, style: style};
}
var result = {};
// for each(var element in ["...", "..."]) can pick up elements added to
// Array.prototype, so we'll use the loop structure below. See also
// http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in
// keywords that take an expression and form a statement
["if", "elseif", "while", "declare"].forEach(function(element, index, array) {
result[element] = token("keyword a", "php-keyword");
});
// keywords that take just a statement
["do", "else", "try" ].forEach(function(element, index, array) {
result[element] = token("keyword b", "php-keyword");
});
// keywords that take an optional expression, but no statement
["return", "break", "continue", // the expression is optional
"new", "clone", "throw" // the expression is mandatory
].forEach(function(element, index, array) {
result[element] = token("keyword c", "php-keyword");
});
["__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__"].forEach(function(element, index, array) {
result[element] = token("atom", "php-compile-time-constant");
});
["true", "false", "null"].forEach(function(element, index, array) {
result[element] = token("atom", "php-atom");
});
["and", "or", "xor", "instanceof"].forEach(function(element, index, array) {
result[element] = token("operator", "php-keyword php-operator");
});
["class", "interface"].forEach(function(element, index, array) {
result[element] = token("class", "php-keyword");
});
["namespace", "use", "extends", "implements"].forEach(function(element, index, array) {
result[element] = token("namespace", "php-keyword");
});
// reserved "language constructs"... http://php.net/manual/en/reserved.php
[ "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset",
"list", "require", "require_once", "return", "print", "unset",
"array" // a keyword rather, but mandates a parenthesized parameter list
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-reserved-language-construct");
});
result["switch"] = token("switch", "php-keyword");
result["case"] = token("case", "php-keyword");
result["default"] = token("default", "php-keyword");
result["catch"] = token("catch", "php-keyword");
result["function"] = token("function", "php-keyword");
// http://php.net/manual/en/control-structures.alternative-syntax.php must be followed by a ':'
["endif", "endwhile", "endfor", "endforeach", "endswitch", "enddeclare"].forEach(function(element, index, array) {
result[element] = token("altsyntaxend", "php-keyword");
});
result["const"] = token("const", "php-keyword");
["final", "private", "protected", "public", "global", "static"].forEach(function(element, index, array) {
result[element] = token("modifier", "php-keyword");
});
result["var"] = token("modifier", "php-keyword deprecated");
result["abstract"] = token("abstract", "php-keyword");
result["foreach"] = token("foreach", "php-keyword");
result["as"] = token("as", "php-keyword");
result["for"] = token("for", "php-keyword");
// PHP built-in functions - output of get_defined_functions()["internal"]
[ "zend_version", "func_num_args", "func_get_arg", "func_get_args", "strlen",
"strcmp", "strncmp", "strcasecmp", "strncasecmp", "each", "error_reporting",
"define", "defined", "get_class", "get_parent_class", "method_exists",
"property_exists", "class_exists", "interface_exists", "function_exists",
"get_included_files", "get_required_files", "is_subclass_of", "is_a",
"get_class_vars", "get_object_vars", "get_class_methods", "trigger_error",
"user_error", "set_error_handler", "restore_error_handler",
"set_exception_handler", "restore_exception_handler", "get_declared_classes",
"get_declared_interfaces", "get_defined_functions", "get_defined_vars",
"create_function", "get_resource_type", "get_loaded_extensions",
"extension_loaded", "get_extension_funcs", "get_defined_constants",
"debug_backtrace", "debug_print_backtrace", "bcadd", "bcsub", "bcmul", "bcdiv",
"bcmod", "bcpow", "bcsqrt", "bcscale", "bccomp", "bcpowmod", "jdtogregorian",
"gregoriantojd", "jdtojulian", "juliantojd", "jdtojewish", "jewishtojd",
"jdtofrench", "frenchtojd", "jddayofweek", "jdmonthname", "easter_date",
"easter_days", "unixtojd", "jdtounix", "cal_to_jd", "cal_from_jd",
"cal_days_in_month", "cal_info", "variant_set", "variant_add", "variant_cat",
"variant_sub", "variant_mul", "variant_and", "variant_div", "variant_eqv",
"variant_idiv", "variant_imp", "variant_mod", "variant_or", "variant_pow",
"variant_xor", "variant_abs", "variant_fix", "variant_int", "variant_neg",
"variant_not", "variant_round", "variant_cmp", "variant_date_to_timestamp",
"variant_date_from_timestamp", "variant_get_type", "variant_set_type",
"variant_cast", "com_create_guid", "com_event_sink", "com_print_typeinfo",
"com_message_pump", "com_load_typelib", "com_get_active_object", "ctype_alnum",
"ctype_alpha", "ctype_cntrl", "ctype_digit", "ctype_lower", "ctype_graph",
"ctype_print", "ctype_punct", "ctype_space", "ctype_upper", "ctype_xdigit",
"strtotime", "date", "idate", "gmdate", "mktime", "gmmktime", "checkdate",
"strftime", "gmstrftime", "time", "localtime", "getdate", "date_create",
"date_parse", "date_format", "date_modify", "date_timezone_get",
"date_timezone_set", "date_offset_get", "date_time_set", "date_date_set",
"date_isodate_set", "timezone_open", "timezone_name_get",
"timezone_name_from_abbr", "timezone_offset_get", "timezone_transitions_get",
"timezone_identifiers_list", "timezone_abbreviations_list",
"date_default_timezone_set", "date_default_timezone_get", "date_sunrise",
"date_sunset", "date_sun_info", "filter_input", "filter_var",
"filter_input_array", "filter_var_array", "filter_list", "filter_has_var",
"filter_id", "ftp_connect", "ftp_login", "ftp_pwd", "ftp_cdup", "ftp_chdir",
"ftp_exec", "ftp_raw", "ftp_mkdir", "ftp_rmdir", "ftp_chmod", "ftp_alloc",
"ftp_nlist", "ftp_rawlist", "ftp_systype", "ftp_pasv", "ftp_get", "ftp_fget",
"ftp_put", "ftp_fput", "ftp_size", "ftp_mdtm", "ftp_rename", "ftp_delete",
"ftp_site", "ftp_close", "ftp_set_option", "ftp_get_option", "ftp_nb_fget",
"ftp_nb_get", "ftp_nb_continue", "ftp_nb_put", "ftp_nb_fput", "ftp_quit",
"hash", "hash_file", "hash_hmac", "hash_hmac_file", "hash_init", "hash_update",
"hash_update_stream", "hash_update_file", "hash_final", "hash_algos", "iconv",
"ob_iconv_handler", "iconv_get_encoding", "iconv_set_encoding", "iconv_strlen",
"iconv_substr", "iconv_strpos", "iconv_strrpos", "iconv_mime_encode",
"iconv_mime_decode", "iconv_mime_decode_headers", "json_encode", "json_decode",
"odbc_autocommit", "odbc_binmode", "odbc_close", "odbc_close_all",
"odbc_columns", "odbc_commit", "odbc_connect", "odbc_cursor",
"odbc_data_source", "odbc_execute", "odbc_error", "odbc_errormsg", "odbc_exec",
"odbc_fetch_array", "odbc_fetch_object", "odbc_fetch_row", "odbc_fetch_into",
"odbc_field_len", "odbc_field_scale", "odbc_field_name", "odbc_field_type",
"odbc_field_num", "odbc_free_result", "odbc_gettypeinfo", "odbc_longreadlen",
"odbc_next_result", "odbc_num_fields", "odbc_num_rows", "odbc_pconnect",
"odbc_prepare", "odbc_result", "odbc_result_all", "odbc_rollback",
"odbc_setoption", "odbc_specialcolumns", "odbc_statistics", "odbc_tables",
"odbc_primarykeys", "odbc_columnprivileges", "odbc_tableprivileges",
"odbc_foreignkeys", "odbc_procedures", "odbc_procedurecolumns", "odbc_do",
"odbc_field_precision", "preg_match", "preg_match_all", "preg_replace",
"preg_replace_callback", "preg_split", "preg_quote", "preg_grep",
"preg_last_error", "session_name", "session_module_name", "session_save_path",
"session_id", "session_regenerate_id", "session_decode", "session_register",
"session_unregister", "session_is_registered", "session_encode",
"session_start", "session_destroy", "session_unset",
"session_set_save_handler", "session_cache_limiter", "session_cache_expire",
"session_set_cookie_params", "session_get_cookie_params",
"session_write_close", "session_commit", "spl_classes", "spl_autoload",
"spl_autoload_extensions", "spl_autoload_register", "spl_autoload_unregister",
"spl_autoload_functions", "spl_autoload_call", "class_parents",
"class_implements", "spl_object_hash", "iterator_to_array", "iterator_count",
"iterator_apply", "constant", "bin2hex", "sleep", "usleep", "flush",
"wordwrap", "htmlspecialchars", "htmlentities", "html_entity_decode",
"htmlspecialchars_decode", "get_html_translation_table", "sha1", "sha1_file",
"md5", "md5_file", "crc32", "iptcparse", "iptcembed", "getimagesize",
"image_type_to_mime_type", "image_type_to_extension", "phpinfo", "phpversion",
"phpcredits", "php_logo_guid", "php_real_logo_guid", "php_egg_logo_guid",
"zend_logo_guid", "php_sapi_name", "php_uname", "php_ini_scanned_files",
"strnatcmp", "strnatcasecmp", "substr_count", "strspn", "strcspn", "strtok",
"strtoupper", "strtolower", "strpos", "stripos", "strrpos", "strripos",
"strrev", "hebrev", "hebrevc", "nl2br", "basename", "dirname", "pathinfo",
"stripslashes", "stripcslashes", "strstr", "stristr", "strrchr", "str_shuffle",
"str_word_count", "str_split", "strpbrk", "substr_compare", "strcoll",
"substr", "substr_replace", "quotemeta", "ucfirst", "ucwords", "strtr",
"addslashes", "addcslashes", "rtrim", "str_replace", "str_ireplace",
"str_repeat", "count_chars", "chunk_split", "trim", "ltrim", "strip_tags",
"similar_text", "explode", "implode", "setlocale", "localeconv", "soundex",
"levenshtein", "chr", "ord", "parse_str", "str_pad", "chop", "strchr",
"sprintf", "printf", "vprintf", "vsprintf", "fprintf", "vfprintf", "sscanf",
"fscanf", "parse_url", "urlencode", "urldecode", "rawurlencode",
"rawurldecode", "http_build_query", "unlink", "exec", "system",
"escapeshellcmd", "escapeshellarg", "passthru", "shell_exec", "proc_open",
"proc_close", "proc_terminate", "proc_get_status", "rand", "srand",
"getrandmax", "mt_rand", "mt_srand", "mt_getrandmax", "getservbyname",
"getservbyport", "getprotobyname", "getprotobynumber", "getmyuid", "getmygid",
"getmypid", "getmyinode", "getlastmod", "base64_decode", "base64_encode",
"convert_uuencode", "convert_uudecode", "abs", "ceil", "floor", "round", "sin",
"cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "pi",
"is_finite", "is_nan", "is_infinite", "pow", "exp", "log", "log10", "sqrt",
"hypot", "deg2rad", "rad2deg", "bindec", "hexdec", "octdec", "decbin",
"decoct", "dechex", "base_convert", "number_format", "fmod", "ip2long",
"long2ip", "getenv", "putenv", "microtime", "gettimeofday", "uniqid",
"quoted_printable_decode", "convert_cyr_string", "get_current_user",
"set_time_limit", "get_cfg_var", "magic_quotes_runtime",
"set_magic_quotes_runtime", "get_magic_quotes_gpc", "get_magic_quotes_runtime",
"import_request_variables", "error_log", "error_get_last", "call_user_func",
"call_user_func_array", "call_user_method", "call_user_method_array",
"serialize", "unserialize", "var_dump", "var_export", "debug_zval_dump",
"print_r", "memory_get_usage", "memory_get_peak_usage",
"register_shutdown_function", "register_tick_function",
"unregister_tick_function", "highlight_file", "show_source",
"highlight_string", "php_strip_whitespace", "ini_get", "ini_get_all",
"ini_set", "ini_alter", "ini_restore", "get_include_path", "set_include_path",
"restore_include_path", "setcookie", "setrawcookie", "header", "headers_sent",
"headers_list", "connection_aborted", "connection_status", "ignore_user_abort",
"parse_ini_file", "is_uploaded_file", "move_uploaded_file", "gethostbyaddr",
"gethostbyname", "gethostbynamel", "intval", "floatval", "doubleval", "strval",
"gettype", "settype", "is_null", "is_resource", "is_bool", "is_long",
"is_float", "is_int", "is_integer", "is_double", "is_real", "is_numeric",
"is_string", "is_array", "is_object", "is_scalar", "is_callable", "ereg",
"ereg_replace", "eregi", "eregi_replace", "split", "spliti", "join",
"sql_regcase", "dl", "pclose", "popen", "readfile", "rewind", "rmdir", "umask",
"fclose", "feof", "fgetc", "fgets", "fgetss", "fread", "fopen", "fpassthru",
"ftruncate", "fstat", "fseek", "ftell", "fflush", "fwrite", "fputs", "mkdir",
"rename", "copy", "tempnam", "tmpfile", "file", "file_get_contents",
"file_put_contents", "stream_select", "stream_context_create",
"stream_context_set_params", "stream_context_set_option",
"stream_context_get_options", "stream_context_get_default",
"stream_filter_prepend", "stream_filter_append", "stream_filter_remove",
"stream_socket_client", "stream_socket_server", "stream_socket_accept",
"stream_socket_get_name", "stream_socket_recvfrom", "stream_socket_sendto",
"stream_socket_enable_crypto", "stream_socket_shutdown",
"stream_copy_to_stream", "stream_get_contents", "fgetcsv", "fputcsv", "flock",
"get_meta_tags", "stream_set_write_buffer", "set_file_buffer",
"set_socket_blocking", "stream_set_blocking", "socket_set_blocking",
"stream_get_meta_data", "stream_get_line", "stream_wrapper_register",
"stream_register_wrapper", "stream_wrapper_unregister",
"stream_wrapper_restore", "stream_get_wrappers", "stream_get_transports",
"get_headers", "stream_set_timeout", "socket_set_timeout", "socket_get_status",
"realpath", "fsockopen", "pfsockopen", "pack", "unpack", "get_browser",
"crypt", "opendir", "closedir", "chdir", "getcwd", "rewinddir", "readdir",
"dir", "scandir", "glob", "fileatime", "filectime", "filegroup", "fileinode",
"filemtime", "fileowner", "fileperms", "filesize", "filetype", "file_exists",
"is_writable", "is_writeable", "is_readable", "is_executable", "is_file",
"is_dir", "is_link", "stat", "lstat", "chown", "chgrp", "chmod", "touch",
"clearstatcache", "disk_total_space", "disk_free_space", "diskfreespace",
"mail", "ezmlm_hash", "openlog", "syslog", "closelog",
"define_syslog_variables", "lcg_value", "metaphone", "ob_start", "ob_flush",
"ob_clean", "ob_end_flush", "ob_end_clean", "ob_get_flush", "ob_get_clean",
"ob_get_length", "ob_get_level", "ob_get_status", "ob_get_contents",
"ob_implicit_flush", "ob_list_handlers", "ksort", "krsort", "natsort",
"natcasesort", "asort", "arsort", "sort", "rsort", "usort", "uasort", "uksort",
"shuffle", "array_walk", "array_walk_recursive", "count", "end", "prev",
"next", "reset", "current", "key", "min", "max", "in_array", "array_search",
"extract", "compact", "array_fill", "array_fill_keys", "range",
"array_multisort", "array_push", "array_pop", "array_shift", "array_unshift",
"array_splice", "array_slice", "array_merge", "array_merge_recursive",
"array_keys", "array_values", "array_count_values", "array_reverse",
"array_reduce", "array_pad", "array_flip", "array_change_key_case",
"array_rand", "array_unique", "array_intersect", "array_intersect_key",
"array_intersect_ukey", "array_uintersect", "array_intersect_assoc",
"array_uintersect_assoc", "array_intersect_uassoc", "array_uintersect_uassoc",
"array_diff", "array_diff_key", "array_diff_ukey", "array_udiff",
"array_diff_assoc", "array_udiff_assoc", "array_diff_uassoc",
"array_udiff_uassoc", "array_sum", "array_product", "array_filter",
"array_map", "array_chunk", "array_combine", "array_key_exists", "pos",
"sizeof", "key_exists", "assert", "assert_options", "version_compare",
"str_rot13", "stream_get_filters", "stream_filter_register",
"stream_bucket_make_writeable", "stream_bucket_prepend",
"stream_bucket_append", "stream_bucket_new", "output_add_rewrite_var",
"output_reset_rewrite_vars", "sys_get_temp_dir", "token_get_all", "token_name",
"readgzfile", "gzrewind", "gzclose", "gzeof", "gzgetc", "gzgets", "gzgetss",
"gzread", "gzopen", "gzpassthru", "gzseek", "gztell", "gzwrite", "gzputs",
"gzfile", "gzcompress", "gzuncompress", "gzdeflate", "gzinflate", "gzencode",
"ob_gzhandler", "zlib_get_coding_type", "libxml_set_streams_context",
"libxml_use_internal_errors", "libxml_get_last_error", "libxml_clear_errors",
"libxml_get_errors", "dom_import_simplexml", "simplexml_load_file",
"simplexml_load_string", "simplexml_import_dom", "wddx_serialize_value",
"wddx_serialize_vars", "wddx_packet_start", "wddx_packet_end", "wddx_add_vars",
"wddx_deserialize", "xml_parser_create", "xml_parser_create_ns",
"xml_set_object", "xml_set_element_handler", "xml_set_character_data_handler",
"xml_set_processing_instruction_handler", "xml_set_default_handler",
"xml_set_unparsed_entity_decl_handler", "xml_set_notation_decl_handler",
"xml_set_external_entity_ref_handler", "xml_set_start_namespace_decl_handler",
"xml_set_end_namespace_decl_handler", "xml_parse", "xml_parse_into_struct",
"xml_get_error_code", "xml_error_string", "xml_get_current_line_number",
"xml_get_current_column_number", "xml_get_current_byte_index",
"xml_parser_free", "xml_parser_set_option", "xml_parser_get_option",
"utf8_encode", "utf8_decode", "xmlwriter_open_uri", "xmlwriter_open_memory",
"xmlwriter_set_indent", "xmlwriter_set_indent_string",
"xmlwriter_start_comment", "xmlwriter_end_comment",
"xmlwriter_start_attribute", "xmlwriter_end_attribute",
"xmlwriter_write_attribute", "xmlwriter_start_attribute_ns",
"xmlwriter_write_attribute_ns", "xmlwriter_start_element",
"xmlwriter_end_element", "xmlwriter_full_end_element",
"xmlwriter_start_element_ns", "xmlwriter_write_element",
"xmlwriter_write_element_ns", "xmlwriter_start_pi", "xmlwriter_end_pi",
"xmlwriter_write_pi", "xmlwriter_start_cdata", "xmlwriter_end_cdata",
"xmlwriter_write_cdata", "xmlwriter_text", "xmlwriter_write_raw",
"xmlwriter_start_document", "xmlwriter_end_document",
"xmlwriter_write_comment", "xmlwriter_start_dtd", "xmlwriter_end_dtd",
"xmlwriter_write_dtd", "xmlwriter_start_dtd_element",
"xmlwriter_end_dtd_element", "xmlwriter_write_dtd_element",
"xmlwriter_start_dtd_attlist", "xmlwriter_end_dtd_attlist",
"xmlwriter_write_dtd_attlist", "xmlwriter_start_dtd_entity",
"xmlwriter_end_dtd_entity", "xmlwriter_write_dtd_entity",
"xmlwriter_output_memory", "xmlwriter_flush", "gd_info", "imagearc",
"imageellipse", "imagechar", "imagecharup", "imagecolorat",
"imagecolorallocate", "imagepalettecopy", "imagecreatefromstring",
"imagecolorclosest", "imagecolordeallocate", "imagecolorresolve",
"imagecolorexact", "imagecolorset", "imagecolortransparent",
"imagecolorstotal", "imagecolorsforindex", "imagecopy", "imagecopymerge",
"imagecopymergegray", "imagecopyresized", "imagecreate",
"imagecreatetruecolor", "imageistruecolor", "imagetruecolortopalette",
"imagesetthickness", "imagefilledarc", "imagefilledellipse",
"imagealphablending", "imagesavealpha", "imagecolorallocatealpha",
"imagecolorresolvealpha", "imagecolorclosestalpha", "imagecolorexactalpha",
"imagecopyresampled", "imagegrabwindow", "imagegrabscreen", "imagerotate",
"imageantialias", "imagesettile", "imagesetbrush", "imagesetstyle",
"imagecreatefrompng", "imagecreatefromgif", "imagecreatefromjpeg",
"imagecreatefromwbmp", "imagecreatefromxbm", "imagecreatefromgd",
"imagecreatefromgd2", "imagecreatefromgd2part", "imagepng", "imagegif",
"imagejpeg", "imagewbmp", "imagegd", "imagegd2", "imagedestroy",
"imagegammacorrect", "imagefill", "imagefilledpolygon", "imagefilledrectangle",
"imagefilltoborder", "imagefontwidth", "imagefontheight", "imageinterlace",
"imageline", "imageloadfont", "imagepolygon", "imagerectangle",
"imagesetpixel", "imagestring", "imagestringup", "imagesx", "imagesy",
"imagedashedline", "imagettfbbox", "imagettftext", "imageftbbox",
"imagefttext", "imagepsloadfont", "imagepsfreefont", "imagepsencodefont",
"imagepsextendfont", "imagepsslantfont", "imagepstext", "imagepsbbox",
"imagetypes", "jpeg2wbmp", "png2wbmp", "image2wbmp", "imagelayereffect",
"imagecolormatch", "imagexbm", "imagefilter", "imageconvolution",
"mb_convert_case", "mb_strtoupper", "mb_strtolower", "mb_language",
"mb_internal_encoding", "mb_http_input", "mb_http_output", "mb_detect_order",
"mb_substitute_character", "mb_parse_str", "mb_output_handler",
"mb_preferred_mime_name", "mb_strlen", "mb_strpos", "mb_strrpos", "mb_stripos",
"mb_strripos", "mb_strstr", "mb_strrchr", "mb_stristr", "mb_strrichr",
"mb_substr_count", "mb_substr", "mb_strcut", "mb_strwidth", "mb_strimwidth",
"mb_convert_encoding", "mb_detect_encoding", "mb_list_encodings",
"mb_convert_kana", "mb_encode_mimeheader", "mb_decode_mimeheader",
"mb_convert_variables", "mb_encode_numericentity", "mb_decode_numericentity",
"mb_send_mail", "mb_get_info", "mb_check_encoding", "mb_regex_encoding",
"mb_regex_set_options", "mb_ereg", "mb_eregi", "mb_ereg_replace",
"mb_eregi_replace", "mb_split", "mb_ereg_match", "mb_ereg_search",
"mb_ereg_search_pos", "mb_ereg_search_regs", "mb_ereg_search_init",
"mb_ereg_search_getregs", "mb_ereg_search_getpos", "mb_ereg_search_setpos",
"mbregex_encoding", "mbereg", "mberegi", "mbereg_replace", "mberegi_replace",
"mbsplit", "mbereg_match", "mbereg_search", "mbereg_search_pos",
"mbereg_search_regs", "mbereg_search_init", "mbereg_search_getregs",
"mbereg_search_getpos", "mbereg_search_setpos", "mysql_connect",
"mysql_pconnect", "mysql_close", "mysql_select_db", "mysql_query",
"mysql_unbuffered_query", "mysql_db_query", "mysql_list_dbs",
"mysql_list_tables", "mysql_list_fields", "mysql_list_processes",
"mysql_error", "mysql_errno", "mysql_affected_rows", "mysql_insert_id",
"mysql_result", "mysql_num_rows", "mysql_num_fields", "mysql_fetch_row",
"mysql_fetch_array", "mysql_fetch_assoc", "mysql_fetch_object",
"mysql_data_seek", "mysql_fetch_lengths", "mysql_fetch_field",
"mysql_field_seek", "mysql_free_result", "mysql_field_name",
"mysql_field_table", "mysql_field_len", "mysql_field_type",
"mysql_field_flags", "mysql_escape_string", "mysql_real_escape_string",
"mysql_stat", "mysql_thread_id", "mysql_client_encoding", "mysql_ping",
"mysql_get_client_info", "mysql_get_host_info", "mysql_get_proto_info",
"mysql_get_server_info", "mysql_info", "mysql_set_charset", "mysql",
"mysql_fieldname", "mysql_fieldtable", "mysql_fieldlen", "mysql_fieldtype",
"mysql_fieldflags", "mysql_selectdb", "mysql_freeresult", "mysql_numfields",
"mysql_numrows", "mysql_listdbs", "mysql_listtables", "mysql_listfields",
"mysql_db_name", "mysql_dbname", "mysql_tablename", "mysql_table_name",
"mysqli_affected_rows", "mysqli_autocommit", "mysqli_change_user",
"mysqli_character_set_name", "mysqli_close", "mysqli_commit", "mysqli_connect",
"mysqli_connect_errno", "mysqli_connect_error", "mysqli_data_seek",
"mysqli_debug", "mysqli_disable_reads_from_master", "mysqli_disable_rpl_parse",
"mysqli_dump_debug_info", "mysqli_enable_reads_from_master",
"mysqli_enable_rpl_parse", "mysqli_embedded_server_end",
"mysqli_embedded_server_start", "mysqli_errno", "mysqli_error",
"mysqli_stmt_execute", "mysqli_execute", "mysqli_fetch_field",
"mysqli_fetch_fields", "mysqli_fetch_field_direct", "mysqli_fetch_lengths",
"mysqli_fetch_array", "mysqli_fetch_assoc", "mysqli_fetch_object",
"mysqli_fetch_row", "mysqli_field_count", "mysqli_field_seek",
"mysqli_field_tell", "mysqli_free_result", "mysqli_get_charset",
"mysqli_get_client_info", "mysqli_get_client_version", "mysqli_get_host_info",
"mysqli_get_proto_info", "mysqli_get_server_info", "mysqli_get_server_version",
"mysqli_get_warnings", "mysqli_init", "mysqli_info", "mysqli_insert_id",
"mysqli_kill", "mysqli_set_local_infile_default",
"mysqli_set_local_infile_handler", "mysqli_master_query",
"mysqli_more_results", "mysqli_multi_query", "mysqli_next_result",
"mysqli_num_fields", "mysqli_num_rows", "mysqli_options", "mysqli_ping",
"mysqli_prepare", "mysqli_report", "mysqli_query", "mysqli_real_connect",
"mysqli_real_escape_string", "mysqli_real_query", "mysqli_rollback",
"mysqli_rpl_parse_enabled", "mysqli_rpl_probe", "mysqli_rpl_query_type",
"mysqli_select_db", "mysqli_set_charset", "mysqli_stmt_attr_get",
"mysqli_stmt_attr_set", "mysqli_stmt_field_count", "mysqli_stmt_init",
"mysqli_stmt_prepare", "mysqli_stmt_result_metadata",
"mysqli_stmt_send_long_data", "mysqli_stmt_bind_param",
"mysqli_stmt_bind_result", "mysqli_stmt_fetch", "mysqli_stmt_free_result",
"mysqli_stmt_get_warnings", "mysqli_stmt_insert_id", "mysqli_stmt_reset",
"mysqli_stmt_param_count", "mysqli_send_query", "mysqli_slave_query",
"mysqli_sqlstate", "mysqli_ssl_set", "mysqli_stat",
"mysqli_stmt_affected_rows", "mysqli_stmt_close", "mysqli_stmt_data_seek",
"mysqli_stmt_errno", "mysqli_stmt_error", "mysqli_stmt_num_rows",
"mysqli_stmt_sqlstate", "mysqli_store_result", "mysqli_stmt_store_result",
"mysqli_thread_id", "mysqli_thread_safe", "mysqli_use_result",
"mysqli_warning_count", "mysqli_bind_param", "mysqli_bind_result",
"mysqli_client_encoding", "mysqli_escape_string", "mysqli_fetch",
"mysqli_param_count", "mysqli_get_metadata", "mysqli_send_long_data",
"mysqli_set_opt", "pdo_drivers", "socket_select", "socket_create",
"socket_create_listen", "socket_accept", "socket_set_nonblock",
"socket_set_block", "socket_listen", "socket_close", "socket_write",
"socket_read", "socket_getsockname", "socket_getpeername", "socket_connect",
"socket_strerror", "socket_bind", "socket_recv", "socket_send",
"socket_recvfrom", "socket_sendto", "socket_get_option", "socket_set_option",
"socket_shutdown", "socket_last_error", "socket_clear_error", "socket_getopt",
"socket_setopt", "eaccelerator_put", "eaccelerator_get", "eaccelerator_rm",
"eaccelerator_gc", "eaccelerator_lock", "eaccelerator_unlock",
"eaccelerator_caching", "eaccelerator_optimizer", "eaccelerator_clear",
"eaccelerator_clean", "eaccelerator_info", "eaccelerator_purge",
"eaccelerator_cached_scripts", "eaccelerator_removed_scripts",
"eaccelerator_list_keys", "eaccelerator_encode", "eaccelerator_load",
"_eaccelerator_loader_file", "_eaccelerator_loader_line",
"eaccelerator_set_session_handlers", "_eaccelerator_output_handler",
"eaccelerator_cache_page", "eaccelerator_rm_page", "eaccelerator_cache_output",
"eaccelerator_cache_result", "xdebug_get_stack_depth",
"xdebug_get_function_stack", "xdebug_print_function_stack",
"xdebug_get_declared_vars", "xdebug_call_class", "xdebug_call_function",
"xdebug_call_file", "xdebug_call_line", "xdebug_var_dump", "xdebug_debug_zval",
"xdebug_debug_zval_stdout", "xdebug_enable", "xdebug_disable",
"xdebug_is_enabled", "xdebug_break", "xdebug_start_trace", "xdebug_stop_trace",
"xdebug_get_tracefile_name", "xdebug_get_profiler_filename",
"xdebug_dump_aggr_profiling_data", "xdebug_clear_aggr_profiling_data",
"xdebug_memory_usage", "xdebug_peak_memory_usage", "xdebug_time_index",
"xdebug_start_error_collection", "xdebug_stop_error_collection",
"xdebug_get_collected_errors", "xdebug_start_code_coverage",
"xdebug_stop_code_coverage", "xdebug_get_code_coverage",
"xdebug_get_function_count", "xdebug_dump_superglobals",
"_", /* alias for gettext()*/
"get_called_class","class_alias","gc_collect_cycles","gc_enabled","gc_enable",
"gc_disable","date_create_from_format","date_parse_from_format",
"date_get_last_errors","date_add","date_sub","date_diff","date_timestamp_set",
"date_timestamp_get","timezone_location_get","timezone_version_get",
"date_interval_create_from_date_string","date_interval_format",
"libxml_disable_entity_loader","openssl_pkey_free","openssl_pkey_new",
"openssl_pkey_export","openssl_pkey_export_to_file","openssl_pkey_get_private",
"openssl_pkey_get_public","openssl_pkey_get_details","openssl_free_key",
"openssl_get_privatekey","openssl_get_publickey","openssl_x509_read",
"openssl_x509_free","openssl_x509_parse","openssl_x509_checkpurpose",
"openssl_x509_check_private_key","openssl_x509_export","openssl_x509_export_to_file",
"openssl_pkcs12_export","openssl_pkcs12_export_to_file","openssl_pkcs12_read",
"openssl_csr_new","openssl_csr_export","openssl_csr_export_to_file",
"openssl_csr_sign","openssl_csr_get_subject","openssl_csr_get_public_key",
"openssl_digest","openssl_encrypt","openssl_decrypt","openssl_cipher_iv_length",
"openssl_sign","openssl_verify","openssl_seal","openssl_open","openssl_pkcs7_verify",
"openssl_pkcs7_decrypt","openssl_pkcs7_sign","openssl_pkcs7_encrypt",
"openssl_private_encrypt","openssl_private_decrypt","openssl_public_encrypt",
"openssl_public_decrypt","openssl_get_md_methods","openssl_get_cipher_methods",
"openssl_dh_compute_key","openssl_random_pseudo_bytes","openssl_error_string",
"preg_filter","bzopen","bzread","bzwrite","bzflush","bzclose","bzerrno",
"bzerrstr","bzerror","bzcompress","bzdecompress","curl_init","curl_copy_handle",
"curl_version","curl_setopt","curl_setopt_array","curl_exec","curl_getinfo",
"curl_error","curl_errno","curl_close","curl_multi_init","curl_multi_add_handle",
"curl_multi_remove_handle","curl_multi_select","curl_multi_exec","curl_multi_getcontent",
"curl_multi_info_read","curl_multi_close","exif_read_data","read_exif_data",
"exif_tagname","exif_thumbnail","exif_imagetype","ftp_ssl_connect",
"imagecolorclosesthwb","imagecreatefromxpm","textdomain","gettext","dgettext",
"dcgettext","bindtextdomain","ngettext","dngettext","dcngettext",
"bind_textdomain_codeset","hash_copy","imap_open","imap_reopen","imap_close",
"imap_num_msg","imap_num_recent","imap_headers","imap_headerinfo",
"imap_rfc822_parse_headers","imap_rfc822_write_address","imap_rfc822_parse_adrlist",
"imap_body","imap_bodystruct","imap_fetchbody","imap_savebody","imap_fetchheader",
"imap_fetchstructure","imap_gc","imap_expunge","imap_delete","imap_undelete",
"imap_check","imap_listscan","imap_mail_copy","imap_mail_move","imap_mail_compose",
"imap_createmailbox","imap_renamemailbox","imap_deletemailbox","imap_subscribe",
"imap_unsubscribe","imap_append","imap_ping","imap_base64","imap_qprint","imap_8bit",
"imap_binary","imap_utf8","imap_status","imap_mailboxmsginfo","imap_setflag_full",
"imap_clearflag_full","imap_sort","imap_uid","imap_msgno","imap_list","imap_lsub",
"imap_fetch_overview","imap_alerts","imap_errors","imap_last_error","imap_search",
"imap_utf7_decode","imap_utf7_encode","imap_mime_header_decode","imap_thread",
"imap_timeout","imap_get_quota","imap_get_quotaroot","imap_set_quota","imap_setacl",
"imap_getacl","imap_mail","imap_header","imap_listmailbox","imap_getmailboxes",
"imap_scanmailbox","imap_listsubscribed","imap_getsubscribed","imap_fetchtext",
"imap_scan","imap_create","imap_rename","json_last_error","mb_encoding_aliases",
"mcrypt_ecb","mcrypt_cbc","mcrypt_cfb","mcrypt_ofb","mcrypt_get_key_size",
"mcrypt_get_block_size","mcrypt_get_cipher_name","mcrypt_create_iv","mcrypt_list_algorithms",
"mcrypt_list_modes","mcrypt_get_iv_size","mcrypt_encrypt","mcrypt_decrypt",
"mcrypt_module_open","mcrypt_generic_init","mcrypt_generic","mdecrypt_generic",
"mcrypt_generic_end","mcrypt_generic_deinit","mcrypt_enc_self_test",
"mcrypt_enc_is_block_algorithm_mode","mcrypt_enc_is_block_algorithm",
"mcrypt_enc_is_block_mode","mcrypt_enc_get_block_size","mcrypt_enc_get_key_size",
"mcrypt_enc_get_supported_key_sizes","mcrypt_enc_get_iv_size",
"mcrypt_enc_get_algorithms_name","mcrypt_enc_get_modes_name","mcrypt_module_self_test",
"mcrypt_module_is_block_algorithm_mode","mcrypt_module_is_block_algorithm",
"mcrypt_module_is_block_mode","mcrypt_module_get_algo_block_size",
"mcrypt_module_get_algo_key_size","mcrypt_module_get_supported_key_sizes",
"mcrypt_module_close","mysqli_refresh","posix_kill","posix_getpid","posix_getppid",
"posix_getuid","posix_setuid","posix_geteuid","posix_seteuid","posix_getgid",
"posix_setgid","posix_getegid","posix_setegid","posix_getgroups","posix_getlogin",
"posix_getpgrp","posix_setsid","posix_setpgid","posix_getpgid","posix_getsid",
"posix_uname","posix_times","posix_ctermid","posix_ttyname","posix_isatty",
"posix_getcwd","posix_mkfifo","posix_mknod","posix_access","posix_getgrnam",
"posix_getgrgid","posix_getpwnam","posix_getpwuid","posix_getrlimit",
"posix_get_last_error","posix_errno","posix_strerror","posix_initgroups",
"pspell_new","pspell_new_personal","pspell_new_config","pspell_check",
"pspell_suggest","pspell_store_replacement","pspell_add_to_personal",
"pspell_add_to_session","pspell_clear_session","pspell_save_wordlist",
"pspell_config_create","pspell_config_runtogether","pspell_config_mode",
"pspell_config_ignore","pspell_config_personal","pspell_config_dict_dir",
"pspell_config_data_dir","pspell_config_repl","pspell_config_save_repl",
"snmpget","snmpgetnext","snmpwalk","snmprealwalk","snmpwalkoid",
"snmp_get_quick_print","snmp_set_quick_print","snmp_set_enum_print",
"snmp_set_oid_output_format","snmp_set_oid_numeric_print","snmpset",
"snmp2_get","snmp2_getnext","snmp2_walk","snmp2_real_walk","snmp2_set",
"snmp3_get","snmp3_getnext","snmp3_walk","snmp3_real_walk","snmp3_set",
"snmp_set_valueretrieval","snmp_get_valueretrieval","snmp_read_mib",
"use_soap_error_handler","is_soap_fault","socket_create_pair","time_nanosleep",
"time_sleep_until","strptime","php_ini_loaded_file","money_format","lcfirst",
"nl_langinfo","str_getcsv","readlink","linkinfo","symlink","link","proc_nice",
"atanh","asinh","acosh","expm1","log1p","inet_ntop","inet_pton","getopt",
"sys_getloadavg","getrusage","quoted_printable_encode","forward_static_call",
"forward_static_call_array","header_remove","parse_ini_string","gethostname",
"dns_check_record","checkdnsrr","dns_get_mx","getmxrr","dns_get_record",
"stream_context_get_params","stream_context_set_default","stream_socket_pair",
"stream_supports_lock","stream_set_read_buffer","stream_resolve_include_path",
"stream_is_local","fnmatch","chroot","lchown","lchgrp","realpath_cache_size",
"realpath_cache_get","array_replace","array_replace_recursive","ftok","xmlrpc_encode",
"xmlrpc_decode","xmlrpc_decode_request","xmlrpc_encode_request","xmlrpc_get_type",
"xmlrpc_set_type","xmlrpc_is_fault","xmlrpc_server_create","xmlrpc_server_destroy",
"xmlrpc_server_register_method","xmlrpc_server_call_method",
"xmlrpc_parse_method_descriptions","xmlrpc_server_add_introspection_data",
"xmlrpc_server_register_introspection_callback","zip_open","zip_close",
"zip_read","zip_entry_open","zip_entry_close","zip_entry_read","zip_entry_filesize",
"zip_entry_name","zip_entry_compressedsize","zip_entry_compressionmethod",
"svn_checkout","svn_cat","svn_ls","svn_log","svn_auth_set_parameter",
"svn_auth_get_parameter","svn_client_version","svn_config_ensure","svn_diff",
"svn_cleanup","svn_revert","svn_resolved","svn_commit","svn_lock","svn_unlock",
"svn_add","svn_status","svn_update","svn_import","svn_info","svn_export",
"svn_copy","svn_switch","svn_blame","svn_delete","svn_mkdir","svn_move",
"svn_proplist","svn_propget","svn_repos_create","svn_repos_recover",
"svn_repos_hotcopy","svn_repos_open","svn_repos_fs",
"svn_repos_fs_begin_txn_for_commit","svn_repos_fs_commit_txn",
"svn_fs_revision_root","svn_fs_check_path","svn_fs_revision_prop",
"svn_fs_dir_entries","svn_fs_node_created_rev","svn_fs_youngest_rev",
"svn_fs_file_contents","svn_fs_file_length","svn_fs_txn_root","svn_fs_make_file",
"svn_fs_make_dir","svn_fs_apply_text","svn_fs_copy","svn_fs_delete",
"svn_fs_begin_txn2","svn_fs_is_dir","svn_fs_is_file","svn_fs_node_prop",
"svn_fs_change_node_prop","svn_fs_contents_changed","svn_fs_props_changed",
"svn_fs_abort_txn","sqlite_open","sqlite_popen","sqlite_close","sqlite_query",
"sqlite_exec","sqlite_array_query","sqlite_single_query","sqlite_fetch_array",
"sqlite_fetch_object","sqlite_fetch_single","sqlite_fetch_string",
"sqlite_fetch_all","sqlite_current","sqlite_column","sqlite_libversion",
"sqlite_libencoding","sqlite_changes","sqlite_last_insert_rowid",
"sqlite_num_rows","sqlite_num_fields","sqlite_field_name","sqlite_seek",
"sqlite_rewind","sqlite_next","sqlite_prev","sqlite_valid","sqlite_has_more",
"sqlite_has_prev","sqlite_escape_string","sqlite_busy_timeout","sqlite_last_error",
"sqlite_error_string","sqlite_unbuffered_query","sqlite_create_aggregate",
"sqlite_create_function","sqlite_factory","sqlite_udf_encode_binary",
"sqlite_udf_decode_binary","sqlite_fetch_column_types"
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-predefined-function");
});
// output of get_defined_constants(). Differs significantly from http://php.net/manual/en/reserved.constants.php
[ "E_ERROR", "E_RECOVERABLE_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE",
"E_STRICT", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR",
"E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE",
"E_ALL", "TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE", "PHP_VERSION", "PHP_OS",
"PHP_SAPI", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR",
"PHP_EXTENSION_DIR", "PHP_PREFIX", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR",
"PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR", "PHP_CONFIG_FILE_PATH",
"PHP_CONFIG_FILE_SCAN_DIR", "PHP_SHLIB_SUFFIX", "PHP_EOL", "PHP_EOL",
"PHP_INT_MAX", "PHP_INT_SIZE", "PHP_OUTPUT_HANDLER_START",
"PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END", "UPLOAD_ERR_OK",
"UPLOAD_ERR_INI_SIZE", "UPLOAD_ERR_FORM_SIZE", "UPLOAD_ERR_PARTIAL",
"UPLOAD_ERR_NO_FILE", "UPLOAD_ERR_NO_TMP_DIR", "UPLOAD_ERR_CANT_WRITE",
"UPLOAD_ERR_EXTENSION", "CAL_GREGORIAN", "CAL_JULIAN", "CAL_JEWISH",
"CAL_FRENCH", "CAL_NUM_CALS", "CAL_DOW_DAYNO", "CAL_DOW_SHORT", "CAL_DOW_LONG",
"CAL_MONTH_GREGORIAN_SHORT", "CAL_MONTH_GREGORIAN_LONG",
"CAL_MONTH_JULIAN_SHORT", "CAL_MONTH_JULIAN_LONG", "CAL_MONTH_JEWISH",
"CAL_MONTH_FRENCH", "CAL_EASTER_DEFAULT", "CAL_EASTER_ROMAN",
"CAL_EASTER_ALWAYS_GREGORIAN", "CAL_EASTER_ALWAYS_JULIAN",
"CAL_JEWISH_ADD_ALAFIM_GERESH", "CAL_JEWISH_ADD_ALAFIM",
"CAL_JEWISH_ADD_GERESHAYIM", "CLSCTX_INPROC_SERVER", "CLSCTX_INPROC_HANDLER",
"CLSCTX_LOCAL_SERVER", "CLSCTX_REMOTE_SERVER", "CLSCTX_SERVER", "CLSCTX_ALL",
"VT_NULL", "VT_EMPTY", "VT_UI1", "VT_I1", "VT_UI2", "VT_I2", "VT_UI4", "VT_I4",
"VT_R4", "VT_R8", "VT_BOOL", "VT_ERROR", "VT_CY", "VT_DATE", "VT_BSTR",
"VT_DECIMAL", "VT_UNKNOWN", "VT_DISPATCH", "VT_VARIANT", "VT_INT", "VT_UINT",
"VT_ARRAY", "VT_BYREF", "CP_ACP", "CP_MACCP", "CP_OEMCP", "CP_UTF7", "CP_UTF8",
"CP_SYMBOL", "CP_THREAD_ACP", "VARCMP_LT", "VARCMP_EQ", "VARCMP_GT",
"VARCMP_NULL", "NORM_IGNORECASE", "NORM_IGNORENONSPACE", "NORM_IGNORESYMBOLS",
"NORM_IGNOREWIDTH", "NORM_IGNOREKANATYPE", "DISP_E_DIVBYZERO",
"DISP_E_OVERFLOW", "DISP_E_BADINDEX", "MK_E_UNAVAILABLE", "INPUT_POST",
"INPUT_GET", "INPUT_COOKIE", "INPUT_ENV", "INPUT_SERVER", "INPUT_SESSION",
"INPUT_REQUEST", "FILTER_FLAG_NONE", "FILTER_REQUIRE_SCALAR",
"FILTER_REQUIRE_ARRAY", "FILTER_FORCE_ARRAY", "FILTER_NULL_ON_FAILURE",
"FILTER_VALIDATE_INT", "FILTER_VALIDATE_BOOLEAN", "FILTER_VALIDATE_FLOAT",
"FILTER_VALIDATE_REGEXP", "FILTER_VALIDATE_URL", "FILTER_VALIDATE_EMAIL",
"FILTER_VALIDATE_IP", "FILTER_DEFAULT", "FILTER_UNSAFE_RAW",
"FILTER_SANITIZE_STRING", "FILTER_SANITIZE_STRIPPED",
"FILTER_SANITIZE_ENCODED", "FILTER_SANITIZE_SPECIAL_CHARS",
"FILTER_SANITIZE_EMAIL", "FILTER_SANITIZE_URL", "FILTER_SANITIZE_NUMBER_INT",
"FILTER_SANITIZE_NUMBER_FLOAT", "FILTER_SANITIZE_MAGIC_QUOTES",
"FILTER_CALLBACK", "FILTER_FLAG_ALLOW_OCTAL", "FILTER_FLAG_ALLOW_HEX",
"FILTER_FLAG_STRIP_LOW", "FILTER_FLAG_STRIP_HIGH", "FILTER_FLAG_ENCODE_LOW",
"FILTER_FLAG_ENCODE_HIGH", "FILTER_FLAG_ENCODE_AMP",
"FILTER_FLAG_NO_ENCODE_QUOTES", "FILTER_FLAG_EMPTY_STRING_NULL",
"FILTER_FLAG_ALLOW_FRACTION", "FILTER_FLAG_ALLOW_THOUSAND",
"FILTER_FLAG_ALLOW_SCIENTIFIC", "FILTER_FLAG_SCHEME_REQUIRED",
"FILTER_FLAG_HOST_REQUIRED", "FILTER_FLAG_PATH_REQUIRED",
"FILTER_FLAG_QUERY_REQUIRED", "FILTER_FLAG_IPV4", "FILTER_FLAG_IPV6",
"FILTER_FLAG_NO_RES_RANGE", "FILTER_FLAG_NO_PRIV_RANGE", "FTP_ASCII",
"FTP_TEXT", "FTP_BINARY", "FTP_IMAGE", "FTP_AUTORESUME", "FTP_TIMEOUT_SEC",
"FTP_AUTOSEEK", "FTP_FAILED", "FTP_FINISHED", "FTP_MOREDATA", "HASH_HMAC",
"ICONV_IMPL", "ICONV_VERSION", "ICONV_MIME_DECODE_STRICT",
"ICONV_MIME_DECODE_CONTINUE_ON_ERROR", "ODBC_TYPE", "ODBC_BINMODE_PASSTHRU",
"ODBC_BINMODE_RETURN", "ODBC_BINMODE_CONVERT", "SQL_ODBC_CURSORS",
"SQL_CUR_USE_DRIVER", "SQL_CUR_USE_IF_NEEDED", "SQL_CUR_USE_ODBC",
"SQL_CONCURRENCY", "SQL_CONCUR_READ_ONLY", "SQL_CONCUR_LOCK",
"SQL_CONCUR_ROWVER", "SQL_CONCUR_VALUES", "SQL_CURSOR_TYPE",
"SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC",
"SQL_CURSOR_STATIC", "SQL_KEYSET_SIZE", "SQL_FETCH_FIRST", "SQL_FETCH_NEXT",
"SQL_CHAR", "SQL_VARCHAR", "SQL_LONGVARCHAR", "SQL_DECIMAL", "SQL_NUMERIC",
"SQL_BIT", "SQL_TINYINT", "SQL_SMALLINT", "SQL_INTEGER", "SQL_BIGINT",
"SQL_REAL", "SQL_FLOAT", "SQL_DOUBLE", "SQL_BINARY", "SQL_VARBINARY",
"SQL_LONGVARBINARY", "SQL_DATE", "SQL_TIME", "SQL_TIMESTAMP",
"PREG_PATTERN_ORDER", "PREG_SET_ORDER", "PREG_OFFSET_CAPTURE",
"PREG_SPLIT_NO_EMPTY", "PREG_SPLIT_DELIM_CAPTURE", "PREG_SPLIT_OFFSET_CAPTURE",
"PREG_GREP_INVERT", "PREG_NO_ERROR", "PREG_INTERNAL_ERROR",
"PREG_BACKTRACK_LIMIT_ERROR", "PREG_RECURSION_LIMIT_ERROR",
"PREG_BAD_UTF8_ERROR", "DATE_ATOM", "DATE_COOKIE", "DATE_ISO8601",
"DATE_RFC822", "DATE_RFC850", "DATE_RFC1036", "DATE_RFC1123", "DATE_RFC2822",
"DATE_RFC3339", "DATE_RSS", "DATE_W3C", "SUNFUNCS_RET_TIMESTAMP",
"SUNFUNCS_RET_STRING", "SUNFUNCS_RET_DOUBLE", "LIBXML_VERSION",
"LIBXML_DOTTED_VERSION", "LIBXML_NOENT", "LIBXML_DTDLOAD", "LIBXML_DTDATTR",
"LIBXML_DTDVALID", "LIBXML_NOERROR", "LIBXML_NOWARNING", "LIBXML_NOBLANKS",
"LIBXML_XINCLUDE", "LIBXML_NSCLEAN", "LIBXML_NOCDATA", "LIBXML_NONET",
"LIBXML_COMPACT", "LIBXML_NOXMLDECL", "LIBXML_NOEMPTYTAG", "LIBXML_ERR_NONE",
"LIBXML_ERR_WARNING", "LIBXML_ERR_ERROR", "LIBXML_ERR_FATAL",
"CONNECTION_ABORTED", "CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER",
"INI_PERDIR", "INI_SYSTEM", "INI_ALL", "PHP_URL_SCHEME", "PHP_URL_HOST",
"PHP_URL_PORT", "PHP_URL_USER", "PHP_URL_PASS", "PHP_URL_PATH",
"PHP_URL_QUERY", "PHP_URL_FRAGMENT", "M_E", "M_LOG2E", "M_LOG10E", "M_LN2",
"M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI", "M_SQRTPI",
"M_2_SQRTPI", "M_LNPI", "M_EULER", "M_SQRT2", "M_SQRT1_2", "M_SQRT3", "INF",
"NAN", "INFO_GENERAL", "INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES",
"INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE", "INFO_ALL",
"CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES",
"CREDITS_DOCS", "CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL",
"HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES",
"ENT_NOQUOTES", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH",
"PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION",
"PATHINFO_FILENAME", "CHAR_MAX", "LC_CTYPE", "LC_NUMERIC", "LC_TIME",
"LC_COLLATE", "LC_MONETARY", "LC_ALL", "SEEK_SET", "SEEK_CUR", "SEEK_END",
"LOCK_SH", "LOCK_EX", "LOCK_UN", "LOCK_NB", "STREAM_NOTIFY_CONNECT",
"STREAM_NOTIFY_AUTH_REQUIRED", "STREAM_NOTIFY_AUTH_RESULT",
"STREAM_NOTIFY_MIME_TYPE_IS", "STREAM_NOTIFY_FILE_SIZE_IS",
"STREAM_NOTIFY_REDIRECTED", "STREAM_NOTIFY_PROGRESS", "STREAM_NOTIFY_FAILURE",
"STREAM_NOTIFY_COMPLETED", "STREAM_NOTIFY_RESOLVE",
"STREAM_NOTIFY_SEVERITY_INFO", "STREAM_NOTIFY_SEVERITY_WARN",
"STREAM_NOTIFY_SEVERITY_ERR", "STREAM_FILTER_READ", "STREAM_FILTER_WRITE",
"STREAM_FILTER_ALL", "STREAM_CLIENT_PERSISTENT", "STREAM_CLIENT_ASYNC_CONNECT",
"STREAM_CLIENT_CONNECT", "STREAM_CRYPTO_METHOD_SSLv2_CLIENT",
"STREAM_CRYPTO_METHOD_SSLv3_CLIENT", "STREAM_CRYPTO_METHOD_SSLv23_CLIENT",
"STREAM_CRYPTO_METHOD_TLS_CLIENT", "STREAM_CRYPTO_METHOD_SSLv2_SERVER",
"STREAM_CRYPTO_METHOD_SSLv3_SERVER", "STREAM_CRYPTO_METHOD_SSLv23_SERVER",
"STREAM_CRYPTO_METHOD_TLS_SERVER", "STREAM_SHUT_RD", "STREAM_SHUT_WR",
"STREAM_SHUT_RDWR", "STREAM_PF_INET", "STREAM_PF_INET6", "STREAM_PF_UNIX",
"STREAM_IPPROTO_IP", "STREAM_IPPROTO_TCP", "STREAM_IPPROTO_UDP",
"STREAM_IPPROTO_ICMP", "STREAM_IPPROTO_RAW", "STREAM_SOCK_STREAM",
"STREAM_SOCK_DGRAM", "STREAM_SOCK_RAW", "STREAM_SOCK_SEQPACKET",
"STREAM_SOCK_RDM", "STREAM_PEEK", "STREAM_OOB", "STREAM_SERVER_BIND",
"STREAM_SERVER_LISTEN", "FILE_USE_INCLUDE_PATH", "FILE_IGNORE_NEW_LINES",
"FILE_SKIP_EMPTY_LINES", "FILE_APPEND", "FILE_NO_DEFAULT_CONTEXT",
"PSFS_PASS_ON", "PSFS_FEED_ME", "PSFS_ERR_FATAL", "PSFS_FLAG_NORMAL",
"PSFS_FLAG_FLUSH_INC", "PSFS_FLAG_FLUSH_CLOSE", "CRYPT_SALT_LENGTH",
"CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5", "CRYPT_BLOWFISH",
"DIRECTORY_SEPARATOR", "PATH_SEPARATOR", "GLOB_BRACE", "GLOB_MARK",
"GLOB_NOSORT", "GLOB_NOCHECK", "GLOB_NOESCAPE", "GLOB_ERR", "GLOB_ONLYDIR",
"LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR", "LOG_WARNING", "LOG_NOTICE",
"LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON",
"LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON",
"LOG_AUTHPRIV", "LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY",
"LOG_NOWAIT", "LOG_PERROR", "EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME",
"EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID", "EXTR_PREFIX_IF_EXISTS",
"EXTR_IF_EXISTS", "EXTR_REFS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR",
"SORT_NUMERIC", "SORT_STRING", "SORT_LOCALE_STRING", "CASE_LOWER",
"CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE",
"ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL",
"STREAM_USE_PATH", "STREAM_IGNORE_URL", "STREAM_ENFORCE_SAFE_MODE",
"STREAM_REPORT_ERRORS", "STREAM_MUST_SEEK", "STREAM_URL_STAT_LINK",
"STREAM_URL_STAT_QUIET", "STREAM_MKDIR_RECURSIVE", "IMAGETYPE_GIF",
"IMAGETYPE_JPEG", "IMAGETYPE_PNG", "IMAGETYPE_SWF", "IMAGETYPE_PSD",
"IMAGETYPE_BMP", "IMAGETYPE_TIFF_II", "IMAGETYPE_TIFF_MM", "IMAGETYPE_JPC",
"IMAGETYPE_JP2", "IMAGETYPE_JPX", "IMAGETYPE_JB2", "IMAGETYPE_SWC",
"IMAGETYPE_IFF", "IMAGETYPE_WBMP", "IMAGETYPE_JPEG2000", "IMAGETYPE_XBM",
"T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE",
"T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "T_PLUS_EQUAL",
"T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL",
"T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL",
"T_BOOLEAN_OR", "T_BOOLEAN_AND", "T_IS_EQUAL", "T_IS_NOT_EQUAL",
"T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "T_IS_SMALLER_OR_EQUAL",
"T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "T_INC", "T_DEC", "T_INT_CAST",
"T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST",
"T_BOOL_CAST", "T_UNSET_CAST", "T_NEW", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE",
"T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME",
"T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_CHARACTER",
"T_BAD_CHARACTER", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING",
"T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH",
"T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH",
"T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_FUNCTION", "T_CONST",
"T_RETURN", "T_USE", "T_GLOBAL", "T_STATIC", "T_VAR", "T_UNSET", "T_ISSET",
"T_EMPTY", "T_CLASS", "T_EXTENDS", "T_INTERFACE", "T_IMPLEMENTS",
"T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CLASS_C",
"T_FUNC_C", "T_METHOD_C", "T_LINE", "T_FILE", "T_COMMENT", "T_DOC_COMMENT",
"T_OPEN_TAG", "T_OPEN_TAG_WITH_ECHO", "T_CLOSE_TAG", "T_WHITESPACE",
"T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES",
"T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_DOUBLE_COLON", "T_ABSTRACT",
"T_CATCH", "T_FINAL", "T_INSTANCEOF", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC",
"T_THROW", "T_TRY", "T_CLONE", "T_HALT_COMPILER", "FORCE_GZIP",
"FORCE_DEFLATE", "XML_ELEMENT_NODE", "XML_ATTRIBUTE_NODE", "XML_TEXT_NODE",
"XML_CDATA_SECTION_NODE", "XML_ENTITY_REF_NODE", "XML_ENTITY_NODE",
"XML_PI_NODE", "XML_COMMENT_NODE", "XML_DOCUMENT_NODE",
"XML_DOCUMENT_TYPE_NODE", "XML_DOCUMENT_FRAG_NODE", "XML_NOTATION_NODE",
"XML_HTML_DOCUMENT_NODE", "XML_DTD_NODE", "XML_ELEMENT_DECL_NODE",
"XML_ATTRIBUTE_DECL_NODE", "XML_ENTITY_DECL_NODE", "XML_NAMESPACE_DECL_NODE",
"XML_LOCAL_NAMESPACE", "XML_ATTRIBUTE_CDATA", "XML_ATTRIBUTE_ID",
"XML_ATTRIBUTE_IDREF", "XML_ATTRIBUTE_IDREFS", "XML_ATTRIBUTE_ENTITY",
"XML_ATTRIBUTE_NMTOKEN", "XML_ATTRIBUTE_NMTOKENS", "XML_ATTRIBUTE_ENUMERATION",
"XML_ATTRIBUTE_NOTATION", "DOM_PHP_ERR", "DOM_INDEX_SIZE_ERR",
"DOMSTRING_SIZE_ERR", "DOM_HIERARCHY_REQUEST_ERR", "DOM_WRONG_DOCUMENT_ERR",
"DOM_INVALID_CHARACTER_ERR", "DOM_NO_DATA_ALLOWED_ERR",
"DOM_NO_MODIFICATION_ALLOWED_ERR", "DOM_NOT_FOUND_ERR",
"DOM_NOT_SUPPORTED_ERR", "DOM_INUSE_ATTRIBUTE_ERR", "DOM_INVALID_STATE_ERR",
"DOM_SYNTAX_ERR", "DOM_INVALID_MODIFICATION_ERR", "DOM_NAMESPACE_ERR",
"DOM_INVALID_ACCESS_ERR", "DOM_VALIDATION_ERR", "XML_ERROR_NONE",
"XML_ERROR_NO_MEMORY", "XML_ERROR_SYNTAX", "XML_ERROR_NO_ELEMENTS",
"XML_ERROR_INVALID_TOKEN", "XML_ERROR_UNCLOSED_TOKEN",
"XML_ERROR_PARTIAL_CHAR", "XML_ERROR_TAG_MISMATCH",
"XML_ERROR_DUPLICATE_ATTRIBUTE", "XML_ERROR_JUNK_AFTER_DOC_ELEMENT",
"XML_ERROR_PARAM_ENTITY_REF", "XML_ERROR_UNDEFINED_ENTITY",
"XML_ERROR_RECURSIVE_ENTITY_REF", "XML_ERROR_ASYNC_ENTITY",
"XML_ERROR_BAD_CHAR_REF", "XML_ERROR_BINARY_ENTITY_REF",
"XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "XML_ERROR_MISPLACED_XML_PI",
"XML_ERROR_UNKNOWN_ENCODING", "XML_ERROR_INCORRECT_ENCODING",
"XML_ERROR_UNCLOSED_CDATA_SECTION", "XML_ERROR_EXTERNAL_ENTITY_HANDLING",
"XML_OPTION_CASE_FOLDING", "XML_OPTION_TARGET_ENCODING",
"XML_OPTION_SKIP_TAGSTART", "XML_OPTION_SKIP_WHITE", "XML_SAX_IMPL", "IMG_GIF",
"IMG_JPG", "IMG_JPEG", "IMG_PNG", "IMG_WBMP", "IMG_XPM", "IMG_COLOR_TILED",
"IMG_COLOR_STYLED", "IMG_COLOR_BRUSHED", "IMG_COLOR_STYLEDBRUSHED",
"IMG_COLOR_TRANSPARENT", "IMG_ARC_ROUNDED", "IMG_ARC_PIE", "IMG_ARC_CHORD",
"IMG_ARC_NOFILL", "IMG_ARC_EDGED", "IMG_GD2_RAW", "IMG_GD2_COMPRESSED",
"IMG_EFFECT_REPLACE", "IMG_EFFECT_ALPHABLEND", "IMG_EFFECT_NORMAL",
"IMG_EFFECT_OVERLAY", "GD_BUNDLED", "IMG_FILTER_NEGATE",
"IMG_FILTER_GRAYSCALE", "IMG_FILTER_BRIGHTNESS", "IMG_FILTER_CONTRAST",
"IMG_FILTER_COLORIZE", "IMG_FILTER_EDGEDETECT", "IMG_FILTER_GAUSSIAN_BLUR",
"IMG_FILTER_SELECTIVE_BLUR", "IMG_FILTER_EMBOSS", "IMG_FILTER_MEAN_REMOVAL",
"IMG_FILTER_SMOOTH", "PNG_NO_FILTER", "PNG_FILTER_NONE", "PNG_FILTER_SUB",
"PNG_FILTER_UP", "PNG_FILTER_AVG", "PNG_FILTER_PAETH", "PNG_ALL_FILTERS",
"MB_OVERLOAD_MAIL", "MB_OVERLOAD_STRING", "MB_OVERLOAD_REGEX", "MB_CASE_UPPER",
"MB_CASE_LOWER", "MB_CASE_TITLE", "MYSQL_ASSOC", "MYSQL_NUM", "MYSQL_BOTH",
"MYSQL_CLIENT_COMPRESS", "MYSQL_CLIENT_SSL", "MYSQL_CLIENT_INTERACTIVE",
"MYSQL_CLIENT_IGNORE_SPACE", "MYSQLI_READ_DEFAULT_GROUP",
"MYSQLI_READ_DEFAULT_FILE", "MYSQLI_OPT_CONNECT_TIMEOUT",
"MYSQLI_OPT_LOCAL_INFILE", "MYSQLI_INIT_COMMAND", "MYSQLI_CLIENT_SSL",
"MYSQLI_CLIENT_COMPRESS", "MYSQLI_CLIENT_INTERACTIVE",
"MYSQLI_CLIENT_IGNORE_SPACE", "MYSQLI_CLIENT_NO_SCHEMA",
"MYSQLI_CLIENT_FOUND_ROWS", "MYSQLI_STORE_RESULT", "MYSQLI_USE_RESULT",
"MYSQLI_ASSOC", "MYSQLI_NUM", "MYSQLI_BOTH",
"MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH", "MYSQLI_STMT_ATTR_CURSOR_TYPE",
"MYSQLI_CURSOR_TYPE_NO_CURSOR", "MYSQLI_CURSOR_TYPE_READ_ONLY",
"MYSQLI_CURSOR_TYPE_FOR_UPDATE", "MYSQLI_CURSOR_TYPE_SCROLLABLE",
"MYSQLI_STMT_ATTR_PREFETCH_ROWS", "MYSQLI_NOT_NULL_FLAG",
"MYSQLI_PRI_KEY_FLAG", "MYSQLI_UNIQUE_KEY_FLAG", "MYSQLI_MULTIPLE_KEY_FLAG",
"MYSQLI_BLOB_FLAG", "MYSQLI_UNSIGNED_FLAG", "MYSQLI_ZEROFILL_FLAG",
"MYSQLI_AUTO_INCREMENT_FLAG", "MYSQLI_TIMESTAMP_FLAG", "MYSQLI_SET_FLAG",
"MYSQLI_NUM_FLAG", "MYSQLI_PART_KEY_FLAG", "MYSQLI_GROUP_FLAG",
"MYSQLI_TYPE_DECIMAL", "MYSQLI_TYPE_TINY", "MYSQLI_TYPE_SHORT",
"MYSQLI_TYPE_LONG", "MYSQLI_TYPE_FLOAT", "MYSQLI_TYPE_DOUBLE",
"MYSQLI_TYPE_NULL", "MYSQLI_TYPE_TIMESTAMP", "MYSQLI_TYPE_LONGLONG",
"MYSQLI_TYPE_INT24", "MYSQLI_TYPE_DATE", "MYSQLI_TYPE_TIME",
"MYSQLI_TYPE_DATETIME", "MYSQLI_TYPE_YEAR", "MYSQLI_TYPE_NEWDATE",
"MYSQLI_TYPE_ENUM", "MYSQLI_TYPE_SET", "MYSQLI_TYPE_TINY_BLOB",
"MYSQLI_TYPE_MEDIUM_BLOB", "MYSQLI_TYPE_LONG_BLOB", "MYSQLI_TYPE_BLOB",
"MYSQLI_TYPE_VAR_STRING", "MYSQLI_TYPE_STRING", "MYSQLI_TYPE_CHAR",
"MYSQLI_TYPE_INTERVAL", "MYSQLI_TYPE_GEOMETRY", "MYSQLI_TYPE_NEWDECIMAL",
"MYSQLI_TYPE_BIT", "MYSQLI_RPL_MASTER", "MYSQLI_RPL_SLAVE", "MYSQLI_RPL_ADMIN",
"MYSQLI_NO_DATA", "MYSQLI_DATA_TRUNCATED", "MYSQLI_REPORT_INDEX",
"MYSQLI_REPORT_ERROR", "MYSQLI_REPORT_STRICT", "MYSQLI_REPORT_ALL",
"MYSQLI_REPORT_OFF", "AF_UNIX", "AF_INET", "AF_INET6", "SOCK_STREAM",
"SOCK_DGRAM", "SOCK_RAW", "SOCK_SEQPACKET", "SOCK_RDM", "MSG_OOB",
"MSG_WAITALL", "MSG_PEEK", "MSG_DONTROUTE", "SO_DEBUG", "SO_REUSEADDR",
"SO_KEEPALIVE", "SO_DONTROUTE", "SO_LINGER", "SO_BROADCAST", "SO_OOBINLINE",
"SO_SNDBUF", "SO_RCVBUF", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO",
"SO_RCVTIMEO", "SO_TYPE", "SO_ERROR", "SOL_SOCKET", "SOMAXCONN",
"PHP_NORMAL_READ", "PHP_BINARY_READ", "SOCKET_EINTR", "SOCKET_EBADF",
"SOCKET_EACCES", "SOCKET_EFAULT", "SOCKET_EINVAL", "SOCKET_EMFILE",
"SOCKET_EWOULDBLOCK", "SOCKET_EINPROGRESS", "SOCKET_EALREADY",
"SOCKET_ENOTSOCK", "SOCKET_EDESTADDRREQ", "SOCKET_EMSGSIZE",
"SOCKET_EPROTOTYPE", "SOCKET_ENOPROTOOPT", "SOCKET_EPROTONOSUPPORT",
"SOCKET_ESOCKTNOSUPPORT", "SOCKET_EOPNOTSUPP", "SOCKET_EPFNOSUPPORT",
"SOCKET_EAFNOSUPPORT", "SOCKET_EADDRINUSE", "SOCKET_EADDRNOTAVAIL",
"SOCKET_ENETDOWN", "SOCKET_ENETUNREACH", "SOCKET_ENETRESET",
"SOCKET_ECONNABORTED", "SOCKET_ECONNRESET", "SOCKET_ENOBUFS", "SOCKET_EISCONN",
"SOCKET_ENOTCONN", "SOCKET_ESHUTDOWN", "SOCKET_ETOOMANYREFS",
"SOCKET_ETIMEDOUT", "SOCKET_ECONNREFUSED", "SOCKET_ELOOP",
"SOCKET_ENAMETOOLONG", "SOCKET_EHOSTDOWN", "SOCKET_EHOSTUNREACH",
"SOCKET_ENOTEMPTY", "SOCKET_EPROCLIM", "SOCKET_EUSERS", "SOCKET_EDQUOT",
"SOCKET_ESTALE", "SOCKET_EREMOTE", "SOCKET_EDISCON", "SOCKET_SYSNOTREADY",
"SOCKET_VERNOTSUPPORTED", "SOCKET_NOTINITIALISED", "SOCKET_HOST_NOT_FOUND",
"SOCKET_TRY_AGAIN", "SOCKET_NO_RECOVERY", "SOCKET_NO_DATA",
"SOCKET_NO_ADDRESS", "SOL_TCP", "SOL_UDP", "EACCELERATOR_VERSION",
"EACCELERATOR_SHM_AND_DISK", "EACCELERATOR_SHM", "EACCELERATOR_SHM_ONLY",
"EACCELERATOR_DISK_ONLY", "EACCELERATOR_NONE", "XDEBUG_TRACE_APPEND",
"XDEBUG_TRACE_COMPUTERIZED", "XDEBUG_TRACE_HTML", "XDEBUG_CC_UNUSED",
"XDEBUG_CC_DEAD_CODE", "STDIN", "STDOUT", "STDERR", "DNS_HINFO",
"DNS_PTR", "SQLITE_EMPTY", "SVN_SHOW_UPDATES", "SVN_NO_IGNORE", "MSG_EOF",
"DNS_MX", "GD_EXTRA_VERSION", "PHP_VERSION_ID", "SQLITE_OK",
"LIBXML_LOADED_VERSION", "RADIXCHAR", "OPENSSL_VERSION_TEXT", "OPENSSL_VERSION_NUMBER",
"PCRE_VERSION", "CURLOPT_FILE", "CURLOPT_INFILE", "CURLOPT_URL", "CURLOPT_PROXY",
"CURLE_FUNCTION_NOT_FOUND", "SOCKET_ENOMSG", "CURLOPT_HTTPHEADER", "SOCKET_EIDRM",
"CURLOPT_PROGRESSFUNCTION", "SOCKET_ECHRNG", "SOCKET_EL2NSYNC", "SOCKET_EL3HLT",
"SOCKET_EL3RST", "SOCKET_ELNRNG", "SOCKET_ENOCSI", "SOCKET_EL2HLT", "SOCKET_EBADE",
"SOCKET_EXFULL", "CURLOPT_USERPWD", "CURLOPT_PROXYUSERPWD", "CURLOPT_RANGE",
"CURLOPT_TIMEOUT_MS", "CURLOPT_POSTFIELDS", "CURLOPT_REFERER", "CURLOPT_USERAGENT",
"CURLOPT_FTPPORT", "SOCKET_ERESTART", "SQLITE_CONSTRAINT", "SQLITE_MISMATCH",
"SQLITE_MISUSE", "CURLOPT_COOKIE", "CURLE_SSL_CERTPROBLEM", "CURLOPT_SSLCERT",
"CURLOPT_KEYPASSWD", "CURLOPT_WRITEHEADER", "CURLOPT_SSL_VERIFYHOST",
"CURLOPT_COOKIEFILE", "CURLE_HTTP_RANGE_ERROR", "CURLE_HTTP_POST_ERROR",
"CURLOPT_CUSTOMREQUEST", "CURLOPT_STDERR", "SOCKET_EBADR", "CURLOPT_RETURNTRANSFER",
"CURLOPT_QUOTE", "CURLOPT_POSTQUOTE", "CURLOPT_INTERFACE", "CURLOPT_KRB4LEVEL",
"SOCKET_ENODATA", "SOCKET_ESRMNT", "CURLOPT_WRITEFUNCTION", "CURLOPT_READFUNCTION",
"CURLOPT_HEADERFUNCTION", "SOCKET_EADV", "SOCKET_EPROTO", "SOCKET_EMULTIHOP",
"SOCKET_EBADMSG", "CURLOPT_FORBID_REUSE", "CURLOPT_RANDOM_FILE", "CURLOPT_EGDSOCKET",
"SOCKET_EREMCHG", "CURLOPT_CONNECTTIMEOUT_MS", "CURLOPT_CAINFO", "CURLOPT_CAPATH",
"CURLOPT_COOKIEJAR", "CURLOPT_SSL_CIPHER_LIST", "CURLOPT_BINARYTRANSFER",
"SQLITE_DONE", "CURLOPT_HTTP_VERSION", "CURLOPT_SSLKEY", "CURLOPT_SSLKEYTYPE",
"CURLOPT_SSLENGINE", "CURLOPT_SSLCERTTYPE", "CURLE_OUT_OF_MEMORY", "CURLOPT_ENCODING",
"CURLE_SSL_CIPHER", "SOCKET_EREMOTEIO", "CURLOPT_HTTP200ALIASES", "CURLAUTH_ANY",
"CURLAUTH_ANYSAFE", "CURLOPT_PRIVATE", "CURLINFO_EFFECTIVE_URL", "CURLINFO_HTTP_CODE",
"CURLINFO_HEADER_SIZE", "CURLINFO_REQUEST_SIZE", "CURLINFO_TOTAL_TIME",
"CURLINFO_NAMELOOKUP_TIME", "CURLINFO_CONNECT_TIME", "CURLINFO_PRETRANSFER_TIME",
"CURLINFO_SIZE_UPLOAD", "CURLINFO_SIZE_DOWNLOAD", "CURLINFO_SPEED_DOWNLOAD",
"CURLINFO_SPEED_UPLOAD", "CURLINFO_FILETIME", "CURLINFO_SSL_VERIFYRESULT",
"CURLINFO_CONTENT_LENGTH_DOWNLOAD", "CURLINFO_CONTENT_LENGTH_UPLOAD",
"CURLINFO_STARTTRANSFER_TIME", "CURLINFO_CONTENT_TYPE", "CURLINFO_REDIRECT_TIME",
"CURLINFO_REDIRECT_COUNT", "CURLINFO_PRIVATE", "CURLINFO_CERTINFO",
"SQLITE_PROTOCOL", "SQLITE_SCHEMA", "SQLITE_TOOBIG", "SQLITE_NOLFS",
"SQLITE_AUTH", "SQLITE_FORMAT", "SOCKET_ENOTTY", "SQLITE_NOTADB",
"SOCKET_ENOSPC", "SOCKET_ESPIPE", "SOCKET_EROFS", "SOCKET_EMLINK", "GD_RELEASE_VERSION",
"SOCKET_ENOLCK", "SOCKET_ENOSYS", "SOCKET_EUNATCH", "SOCKET_ENOANO", "SOCKET_EBADRQC",
"SOCKET_EBADSLT", "SOCKET_ENOSTR", "SOCKET_ETIME", "SOCKET_ENOSR", "SVN_REVISION_HEAD",
"XSD_ENTITY", "XSD_NOTATION", "CURLOPT_CERTINFO", "CURLOPT_POSTREDIR", "CURLOPT_SSH_AUTH_TYPES",
"CURLOPT_SSH_PUBLIC_KEYFILE", "CURLOPT_SSH_PRIVATE_KEYFILE", "CURLOPT_SSH_HOST_PUBLIC_KEY_MD5",
"CURLE_SSH", "CURLOPT_REDIR_PROTOCOLS", "CURLOPT_PROTOCOLS", "XSD_NONNEGATIVEINTEGER",
"XSD_BYTE","DNS_SRV","DNS_A6", "DNS_NAPTR", "DNS_AAAA", "FILTER_SANITIZE_FULL_SPECIAL_CHARS",
"ABDAY_1", "SVN_REVISION_UNSPECIFIED", "SVN_REVISION_BASE", "SVN_REVISION_COMMITTED",
"SVN_REVISION_PREV", "GD_VERSION", "MCRYPT_TRIPLEDES", "MCRYPT_ARCFOUR_IV", "MCRYPT_ARCFOUR",
"MCRYPT_BLOWFISH", "MCRYPT_BLOWFISH_COMPAT", "MCRYPT_CAST_128", "MCRYPT_CAST_256",
"MCRYPT_ENIGNA", "MCRYPT_DES", "MCRYPT_GOST", "MCRYPT_LOKI97", "MCRYPT_PANAMA",
"MCRYPT_RC2", "MCRYPT_RIJNDAEL_128", "MCRYPT_RIJNDAEL_192", "MCRYPT_RIJNDAEL_256",
"MCRYPT_SAFER64", "MCRYPT_SAFER128","MCRYPT_SAFERPLUS", "MCRYPT_SERPENT", "MCRYPT_THREEWAY",
"MCRYPT_TWOFISH", "MCRYPT_WAKE", "MCRYPT_XTEA", "MCRYPT_IDEA", "MCRYPT_MARS",
"MCRYPT_RC6", "MCRYPT_SKIPJACK", "MCRYPT_MODE_CBC", "MCRYPT_MODE_CFB", "MCRYPT_MODE_ECB",
"MCRYPT_MODE_NOFB", "MCRYPT_MODE_OFB", "MCRYPT_MODE_STREAM", "CL_EXPUNGE",
"SQLITE_ROW", "POSIX_S_IFBLK", "POSIX_S_IFSOCK", "XSD_IDREF", "ABDAY_2",
"ABDAY_3", "ABDAY_4", "ABDAY_5", "ABDAY_6", "ABDAY_7", "DAY_1", "DAY_2",
"DAY_3", "DAY_4", "DAY_5", "DAY_6", "DAY_7", "ABMON_1", "ABMON_2", "ABMON_3",
"ABMON_4", "ABMON_5", "ABMON_6", "ABMON_7","ABMON_8", "ABMON_9", "ABMON_10",
"ABMON_11", "ABMON_12", "MON_1", "MON_2", "MON_3", "MON_4", "MON_5", "MON_6",
"MON_7", "MON_8", "MON_9", "MON_10", "MON_11", "MON_12", "AM_STR", "PM_STR",
"D_T_FMT", "D_FMT", "T_FMT", "T_FMT_AMPM", "ERA", "ERA_D_T_FMT", "ERA_D_FMT",
"ERA_T_FMT", "ALT_DIGITS", "CRNCYSTR", "THOUSEP", "YESEXPR", "NOEXPR",
"SOCKET_ENOMEDIUM", "GLOB_AVAILABLE_FLAGS", "XSD_SHORT", "XSD_NMTOKENS",
"LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7",
"DNS_ANY", "DNS_ALL", "SOCKET_ENOLINK", "SOCKET_ECOMM", "SOAP_FUNCTIONS_ALL",
"UNKNOWN_TYPE", "XSD_BASE64BINARY", "XSD_ANYURI", "XSD_QNAME", "SOCKET_EISNAM",
"SOCKET_EMEDIUMTYPE", "XSD_NCNAME", "XSD_ID", "XSD_ENTITIES", "XSD_INTEGER",
"XSD_NONPOSITIVEINTEGER", "XSD_NEGATIVEINTEGER", "XSD_LONG", "XSD_INT",
"XSD_UNSIGNEDLONG", "XSD_UNSIGNEDINT", "XSD_UNSIGNEDSHORT", "XSD_UNSIGNEDBYTE",
"XSD_POSITIVEINTEGER", "XSD_ANYTYPE", "XSD_ANYXML", "APACHE_MAP", "XSD_1999_TIMEINSTANT",
"XSD_NAMESPACE", "XSD_1999_NAMESPACE", "SOCKET_ENOTUNIQ", "SOCKET_EBADFD",
"SOCKET_ESTRPIPE", "T_GOTO", "T_NAMESPACE", "T_NS_C", "T_DIR", "T_NS_SEPARATOR",
"LIBXSLT_VERSION","LIBEXSLT_DOTTED_VERSION", "LIBEXSLT_VERSION", "SVN_AUTH_PARAM_DEFAULT_USERNAME",
"SVN_AUTH_PARAM_DEFAULT_PASSWORD", "SVN_AUTH_PARAM_NON_INTERACTIVE",
"SVN_AUTH_PARAM_DONT_STORE_PASSWORDS", "SVN_AUTH_PARAM_NO_AUTH_CACHE",
"SVN_AUTH_PARAM_SSL_SERVER_FAILURES", "SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO",
"SVN_AUTH_PARAM_CONFIG", "SVN_AUTH_PARAM_SERVER_GROUP",
"SVN_AUTH_PARAM_CONFIG_DIR", "PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS",
"SVN_FS_CONFIG_FS_TYPE", "SVN_FS_TYPE_BDB", "SVN_FS_TYPE_FSFS", "SVN_PROP_REVISION_DATE",
"SVN_PROP_REVISION_ORIG_DATE", "SVN_PROP_REVISION_AUTHOR", "SVN_PROP_REVISION_LOG"
].forEach(function(element, index, array) {
result[element] = token("atom", "php-predefined-constant");
});
// PHP declared classes - output of get_declared_classes(). Differs from http://php.net/manual/en/reserved.classes.php
[ "stdClass", "Exception", "ErrorException", "COMPersistHelper", "com_exception",
"com_safearray_proxy", "variant", "com", "dotnet", "ReflectionException",
"Reflection", "ReflectionFunctionAbstract", "ReflectionFunction",
"ReflectionParameter", "ReflectionMethod", "ReflectionClass",
"ReflectionObject", "ReflectionProperty", "ReflectionExtension", "DateTime",
"DateTimeZone", "LibXMLError", "__PHP_Incomplete_Class", "php_user_filter",
"Directory", "SimpleXMLElement", "DOMException", "DOMStringList",
"DOMNameList", "DOMImplementationList", "DOMImplementationSource",
"DOMImplementation", "DOMNode", "DOMNameSpaceNode", "DOMDocumentFragment",
"DOMDocument", "DOMNodeList", "DOMNamedNodeMap", "DOMCharacterData", "DOMAttr",
"DOMElement", "DOMText", "DOMComment", "DOMTypeinfo", "DOMUserDataHandler",
"DOMDomError", "DOMErrorHandler", "DOMLocator", "DOMConfiguration",
"DOMCdataSection", "DOMDocumentType", "DOMNotation", "DOMEntity",
"DOMEntityReference", "DOMProcessingInstruction", "DOMStringExtend",
"DOMXPath", "RecursiveIteratorIterator", "IteratorIterator", "FilterIterator",
"RecursiveFilterIterator", "ParentIterator", "LimitIterator",
"CachingIterator", "RecursiveCachingIterator", "NoRewindIterator",
"AppendIterator", "InfiniteIterator", "RegexIterator",
"RecursiveRegexIterator", "EmptyIterator", "ArrayObject", "ArrayIterator",
"RecursiveArrayIterator", "SplFileInfo", "DirectoryIterator",
"RecursiveDirectoryIterator", "SplFileObject", "SplTempFileObject",
"SimpleXMLIterator", "LogicException", "BadFunctionCallException",
"BadMethodCallException", "DomainException", "InvalidArgumentException",
"LengthException", "OutOfRangeException", "RuntimeException",
"OutOfBoundsException", "OverflowException", "RangeException",
"UnderflowException", "UnexpectedValueException", "SplObjectStorage",
"XMLReader", "XMLWriter", "mysqli_sql_exception", "mysqli_driver", "mysqli",
"mysqli_warning", "mysqli_result", "mysqli_stmt", "PDOException", "PDO",
"PDOStatement", "PDORow","Closure", "DateInterval", "DatePeriod", "FilesystemIterator",
"GlobIterator", "MultipleIterator", "RecursiveTreeIterator", "SoapClient",
"SoapFault", "SoapHeader", "SoapParam", "SoapServer", "SoapVar", "SplDoublyLinkedList",
"SplFixedArray", "SplHeap", "SplMaxHeap", "SplMinHeap", "SplPriorityQueue",
"SplQueue", "SplStack", "SQLite3", "SQLite3Result", "SQLite3Stmt", "SQLiteDatabase",
"SQLiteException", "SQLiteResult", "SQLiteUnbuffered", "Svn", "SvnNode", "SvnWc",
"SvnWcSchedule", "XSLTProcessor", "ZipArchive"
].forEach(function(element, index, array) {
result[element] = token("t_string", "php-predefined-class");
});
return result;
}();
// Helper regexps
var isOperatorChar = /[+*&%\/=<>!?.|^@-]/;
var isHexDigit = /[0-9A-Fa-f]/;
var isWordChar = /[\w\$_\\]/;
// Wrapper around phpToken that helps maintain parser state (whether
// we are inside of a multi-line comment)
function phpTokenState(inside) {
return function(source, setState) {
var newInside = inside;
var type = phpToken(inside, source, function(c) {newInside = c;});
if (newInside != inside)
setState(phpTokenState(newInside));
return type;
};
}
// The token reader, inteded to be used by the tokenizer from
// tokenize.js (through phpTokenState). Advances the source stream
// over a token, and returns an object containing the type and style
// of that token.
function phpToken(inside, source, setInside) {
function readHexNumber(){
source.next(); // skip the 'x'
source.nextWhileMatches(isHexDigit);
return {type: "number", style: "php-atom"};
}
function readNumber() {
source.nextWhileMatches(/[0-9]/);
if (source.equals(".")){
source.next();
source.nextWhileMatches(/[0-9]/);
}
if (source.equals("e") || source.equals("E")){
source.next();
if (source.equals("-"))
source.next();
source.nextWhileMatches(/[0-9]/);
}
return {type: "number", style: "php-atom"};
}
// Read a word and look it up in the keywords array. If found, it's a
// keyword of that type; otherwise it's a PHP T_STRING.
function readWord() {
source.nextWhileMatches(isWordChar);
var word = source.get();
var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
// since we called get(), tokenize::take won't get() anything. Thus, we must set token.content
return known ? {type: known.type, style: known.style, content: word} :
{type: "t_string", style: "php-t_string", content: word};
}
function readVariable() {
source.nextWhileMatches(isWordChar);
var word = source.get();
// in PHP, '$this' is a reserved word, but 'this' isn't. You can have function this() {...}
if (word == "$this")
return {type: "variable", style: "php-keyword", content: word};
else
return {type: "variable", style: "php-variable", content: word};
}
// Advance the stream until the given character (not preceded by a
// backslash) is encountered, or the end of the line is reached.
function nextUntilUnescaped(source, end) {
var escaped = false;
while(!source.endOfLine()){
var next = source.next();
if (next == end && !escaped)
return false;
escaped = next == "\\" && !escaped;
}
return escaped;
}
function readSingleLineComment() {
// read until the end of the line or until ?>, which terminates single-line comments
// `<?php echo 1; // comment ?> foo` will display "1 foo"
while(!source.lookAhead("?>") && !source.endOfLine())
source.next();
return {type: "comment", style: "php-comment"};
}
/* For multi-line comments, we want to return a comment token for
every line of the comment, but we also want to return the newlines
in them as regular newline tokens. We therefore need to save a
state variable ("inside") to indicate whether we are inside a
multi-line comment.
*/
function readMultilineComment(start){
var newInside = "/*";
var maybeEnd = (start == "*");
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == "/" && maybeEnd){
newInside = null;
break;
}
maybeEnd = (next == "*");
}
setInside(newInside);
return {type: "comment", style: "php-comment"};
}
// similar to readMultilineComment and nextUntilUnescaped
// unlike comments, strings are not stopped by ?>
function readMultilineString(start){
var newInside = start;
var escaped = false;
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == start && !escaped){
newInside = null; // we're outside of the string now
break;
}
escaped = (next == "\\" && !escaped);
}
setInside(newInside);
return {
type: newInside == null? "string" : "string_not_terminated",
style: (start == "'"? "php-string-single-quoted" : "php-string-double-quoted")
};
}
// http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
// See also 'nowdoc' on the page. Heredocs are not interrupted by the '?>' token.
function readHeredoc(identifier){
var token = {};
if (identifier == "<<<") {
// on our first invocation after reading the <<<, we must determine the closing identifier
if (source.equals("'")) {
// nowdoc
source.nextWhileMatches(isWordChar);
identifier = "'" + source.get() + "'";
source.next(); // consume the closing "'"
} else if (source.matches(/[A-Za-z_]/)) {
// heredoc
source.nextWhileMatches(isWordChar);
identifier = source.get();
} else {
// syntax error
setInside(null);
return { type: "error", style: "syntax-error" };
}
setInside(identifier);
token.type = "string_not_terminated";
token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted";
token.content = identifier;
} else {
token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted";
// consume a line of heredoc and check if it equals the closing identifier plus an optional semicolon
if (source.lookAhead(identifier, true) && (source.lookAhead(";\n") || source.endOfLine())) {
// the closing identifier can only appear at the beginning of the line
// note that even whitespace after the ";" is forbidden by the PHP heredoc syntax
token.type = "string";
token.content = source.get(); // don't get the ";" if there is one
setInside(null);
} else {
token.type = "string_not_terminated";
source.nextWhileMatches(/[^\n]/);
token.content = source.get();
}
}
return token;
}
function readOperator() {
source.nextWhileMatches(isOperatorChar);
return {type: "operator", style: "php-operator"};
}
function readStringSingleQuoted() {
var endBackSlash = nextUntilUnescaped(source, "'", false);
setInside(endBackSlash ? "'" : null);
return {type: "string", style: "php-string-single-quoted"};
}
function readStringDoubleQuoted() {
var endBackSlash = nextUntilUnescaped(source, "\"", false);
setInside(endBackSlash ? "\"": null);
return {type: "string", style: "php-string-double-quoted"};
}
// Fetch the next token. Dispatches on first character in the
// stream, or first two characters when the first is a slash.
switch (inside) {
case null:
case false: break;
case "'":
case "\"": return readMultilineString(inside);
case "/*": return readMultilineComment(source.next());
default: return readHeredoc(inside);
}
var ch = source.next();
if (ch == "'" || ch == "\"")
return readMultilineString(ch);
else if (ch == "#")
return readSingleLineComment();
else if (ch == "$")
return readVariable();
else if (ch == ":" && source.equals(":")) {
source.next();
// the T_DOUBLE_COLON can only follow a T_STRING (class name)
return {type: "t_double_colon", style: "php-operator"};
}
// with punctuation, the type of the token is the symbol itself
else if (/[\[\]{}\(\),;:]/.test(ch)) {
return {type: ch, style: "php-punctuation"};
}
else if (ch == "0" && (source.equals("x") || source.equals("X")))
return readHexNumber();
else if (/[0-9]/.test(ch))
return readNumber();
else if (ch == "/") {
if (source.equals("*"))
{ source.next(); return readMultilineComment(ch); }
else if (source.equals("/"))
return readSingleLineComment();
else
return readOperator();
}
else if (ch == "<") {
if (source.lookAhead("<<", true)) {
setInside("<<<");
return {type: "<<<", style: "php-punctuation"};
}
else
return readOperator();
}
else if (isOperatorChar.test(ch))
return readOperator();
else
return readWord();
}
// The external interface to the tokenizer.
return function(source, startState) {
return tokenizer(source, startState || phpTokenState(false, true));
};
})();
| JavaScript |
/* Simple parser for CSS */
var CSSParser = Editor.Parser = (function() {
var tokenizeCSS = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "@") {
source.nextWhileMatches(/\w/);
return "css-at";
}
else if (ch == "/" && source.equals("*")) {
setState(inCComment);
return null;
}
else if (ch == "<" && source.equals("!")) {
setState(inSGMLComment);
return null;
}
else if (ch == "=") {
return "css-compare";
}
else if (source.equals("=") && (ch == "~" || ch == "|")) {
source.next();
return "css-compare";
}
else if (ch == "\"" || ch == "'") {
setState(inString(ch));
return null;
}
else if (ch == "#") {
source.nextWhileMatches(/\w/);
return "css-hash";
}
else if (ch == "!") {
source.nextWhileMatches(/[ \t]/);
source.nextWhileMatches(/\w/);
return "css-important";
}
else if (/\d/.test(ch)) {
source.nextWhileMatches(/[\w.%]/);
return "css-unit";
}
else if (/[,.+>*\/]/.test(ch)) {
return "css-select-op";
}
else if (/[;{}:\[\]]/.test(ch)) {
return "css-punctuation";
}
else {
source.nextWhileMatches(/[\w\\\-_]/);
return "css-identifier";
}
}
function inCComment(source, setState) {
var maybeEnd = false;
while (!source.endOfLine()) {
var ch = source.next();
if (maybeEnd && ch == "/") {
setState(normal);
break;
}
maybeEnd = (ch == "*");
}
return "css-comment";
}
function inSGMLComment(source, setState) {
var dashes = 0;
while (!source.endOfLine()) {
var ch = source.next();
if (dashes >= 2 && ch == ">") {
setState(normal);
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return "css-comment";
}
function inString(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped)
setState(normal);
return "css-string";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentCSS(inBraces, inRule, base) {
return function(nextChars) {
if (!inBraces || /^\}/.test(nextChars)) return base;
else if (inRule) return base + indentUnit * 2;
else return base + indentUnit;
};
}
// This is a very simplistic parser -- since CSS does not really
// nest, it works acceptably well, but some nicer colouroing could
// be provided with a more complicated parser.
function parseCSS(source, basecolumn) {
basecolumn = basecolumn || 0;
var tokens = tokenizeCSS(source);
var inBraces = false, inRule = false, inDecl = false;;
var iter = {
next: function() {
var token = tokens.next(), style = token.style, content = token.content;
if (style == "css-hash")
style = token.style = inRule ? "css-colorcode" : "css-identifier";
if (style == "css-identifier") {
if (inRule) token.style = "css-value";
else if (!inBraces && !inDecl) token.style = "css-selector";
}
if (content == "\n")
token.indentation = indentCSS(inBraces, inRule, basecolumn);
if (content == "{" && inDecl == "@media")
inDecl = false;
else if (content == "{")
inBraces = true;
else if (content == "}")
inBraces = inRule = inDecl = false;
else if (content == ";")
inRule = inDecl = false;
else if (inBraces && style != "css-comment" && style != "whitespace")
inRule = true;
else if (!inBraces && style == "css-at")
inDecl = content;
return token;
},
copy: function() {
var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeCSS(source, _tokenState);
inBraces = _inBraces;
inRule = _inRule;
return iter;
};
}
};
return iter;
}
return {make: parseCSS, electricChars: "}"};
})();
| JavaScript |
/*
Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
The copyrights embodied in the content of this file are licensed by
Yahoo! Inc. under the BSD (revised) open source license
@author Dan Vlad Dascalescu <dandv@yahoo-inc.com>
Based on parsehtmlmixed.js by Marijn Haverbeke.
*/
var PHPHTMLMixedParser = Editor.Parser = (function() {
var processingInstructions = ["<?php"];
if (!(PHPParser && CSSParser && JSParser && XMLParser))
throw new Error("PHP, CSS, JS, and XML parsers must be loaded for PHP+HTML mixed mode to work.");
XMLParser.configure({useHTMLKludges: true});
function parseMixed(stream) {
var htmlParser = XMLParser.make(stream), localParser = null,
inTag = false, lastAtt = null, phpParserState = null;
var iter = {next: top, copy: copy};
function top() {
var token = htmlParser.next();
if (token.content == "<")
inTag = true;
else if (token.style == "xml-tagname" && inTag === true)
inTag = token.content.toLowerCase();
else if (token.style == "xml-attname")
lastAtt = token.content;
else if (token.type == "xml-processing") {
// see if this opens a PHP block
for (var i = 0; i < processingInstructions.length; i++)
if (processingInstructions[i] == token.content) {
iter.next = local(PHPParser, "?>");
break;
}
}
else if (token.style == "xml-attribute" && token.content == "\"php\"" && inTag == "script" && lastAtt == "language")
inTag = "script/php";
// "xml-processing" tokens are ignored, because they should be handled by a specific local parser
else if (token.content == ">") {
if (inTag == "script/php")
iter.next = local(PHPParser, "</script>");
else if (inTag == "script")
iter.next = local(JSParser, "</script");
else if (inTag == "style")
iter.next = local(CSSParser, "</style");
lastAtt = null;
inTag = false;
}
return token;
}
function local(parser, tag) {
var baseIndent = htmlParser.indentation();
if (parser == PHPParser && phpParserState)
localParser = phpParserState(stream);
else
localParser = parser.make(stream, baseIndent + indentUnit);
return function() {
if (stream.lookAhead(tag, false, false, true)) {
if (parser == PHPParser) phpParserState = localParser.copy();
localParser = null;
iter.next = top;
return top(); // pass the ending tag to the enclosing parser
}
var token = localParser.next();
var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) &&
stream.lookAhead(tag.slice(sz), false, false, true)) {
stream.push(token.value.slice(lt));
token.value = token.value.slice(0, lt);
}
if (token.indentation) {
var oldIndent = token.indentation;
token.indentation = function(chars) {
if (chars == "</")
return baseIndent;
else
return oldIndent(chars);
}
}
return token;
};
}
function copy() {
var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
_next = iter.next, _inTag = inTag, _lastAtt = lastAtt, _php = phpParserState;
return function(_stream) {
stream = _stream;
htmlParser = _html(_stream);
localParser = _local && _local(_stream);
phpParserState = _php;
iter.next = _next;
inTag = _inTag;
lastAtt = _lastAtt;
return iter;
};
}
return iter;
}
return {
make: parseMixed,
electricChars: "{}/:",
configure: function(conf) {
if (conf.opening != null) processingInstructions = conf.opening;
}
};
})();
| JavaScript |
// A framework for simple tokenizers. Takes care of newlines and
// white-space, and of getting the text from the source stream into
// the token object. A state is a function of two arguments -- a
// string stream and a setState function. The second can be used to
// change the tokenizer's state, and can be ignored for stateless
// tokenizers. This function should advance the stream over a token
// and return a string or object containing information about the next
// token, or null to pass and have the (new) state be called to finish
// the token. When a string is given, it is wrapped in a {style, type}
// object. In the resulting object, the characters consumed are stored
// under the content property. Any whitespace following them is also
// automatically consumed, and added to the value property. (Thus,
// content is the actual meaningful part of the token, while value
// contains all the text it spans.)
function tokenizer(source, state) {
// Newlines are always a separate token.
function isWhiteSpace(ch) {
// The messy regexp is because IE's regexp matcher is of the
// opinion that non-breaking spaces are no whitespace.
return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
}
var tokenizer = {
state: state,
take: function(type) {
if (typeof(type) == "string")
type = {style: type, type: type};
type.content = (type.content || "") + source.get();
if (!/\n$/.test(type.content))
source.nextWhile(isWhiteSpace);
type.value = type.content + source.get();
return type;
},
next: function () {
if (!source.more()) throw StopIteration;
var type;
if (source.equals("\n")) {
source.next();
return this.take("whitespace");
}
if (source.applies(isWhiteSpace))
type = "whitespace";
else
while (!type)
type = this.state(source, function(s) {tokenizer.state = s;});
return this.take(type);
}
};
return tokenizer;
}
| JavaScript |
var HTMLMixedParser = Editor.Parser = (function() {
// tags that trigger seperate parsers
var triggers = {
"script": "JSParser",
"style": "CSSParser"
};
function checkDependencies() {
var parsers = ['XMLParser'];
for (var p in triggers) parsers.push(triggers[p]);
for (var i in parsers) {
if (!window[parsers[i]]) throw new Error(parsers[i] + " parser must be loaded for HTML mixed mode to work.");
}
XMLParser.configure({useHTMLKludges: true});
}
function parseMixed(stream) {
checkDependencies();
var htmlParser = XMLParser.make(stream), localParser = null, inTag = false;
var iter = {next: top, copy: copy};
function top() {
var token = htmlParser.next();
if (token.content == "<")
inTag = true;
else if (token.style == "xml-tagname" && inTag === true)
inTag = token.content.toLowerCase();
else if (token.content == ">") {
if (triggers[inTag]) {
var parser = window[triggers[inTag]];
iter.next = local(parser, "</" + inTag);
}
inTag = false;
}
return token;
}
function local(parser, tag) {
var baseIndent = htmlParser.indentation();
localParser = parser.make(stream, baseIndent + indentUnit);
return function() {
if (stream.lookAhead(tag, false, false, true)) {
localParser = null;
iter.next = top;
return top();
}
var token = localParser.next();
var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) &&
stream.lookAhead(tag.slice(sz), false, false, true)) {
stream.push(token.value.slice(lt));
token.value = token.value.slice(0, lt);
}
if (token.indentation) {
var oldIndent = token.indentation;
token.indentation = function(chars) {
if (chars == "</")
return baseIndent;
else
return oldIndent(chars);
};
}
return token;
};
}
function copy() {
var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
_next = iter.next, _inTag = inTag;
return function(_stream) {
stream = _stream;
htmlParser = _html(_stream);
localParser = _local && _local(_stream);
iter.next = _next;
inTag = _inTag;
return iter;
};
}
return iter;
}
return {
make: parseMixed,
electricChars: "{}/:",
configure: function(obj) {
if (obj.triggers) triggers = obj.triggers;
}
};
})();
| JavaScript |
/* Demonstration of embedding CodeMirror in a bigger application. The
* interface defined here is a mess of prompts and confirms, and
* should probably not be used in a real project.
*/
function MirrorFrame(place, options) {
this.home = document.createElement("div");
if (place.appendChild)
place.appendChild(this.home);
else
place(this.home);
var self = this;
function makeButton(name, action) {
var button = document.createElement("input");
button.type = "button";
button.value = name;
self.home.appendChild(button);
button.onclick = function(){self[action].call(self);};
}
makeButton("Search", "search");
makeButton("Replace", "replace");
makeButton("Current line", "line");
makeButton("Jump to line", "jump");
makeButton("Insert constructor", "macro");
makeButton("Indent all", "reindent");
this.mirror = new CodeMirror(this.home, options);
}
MirrorFrame.prototype = {
search: function() {
var text = prompt("Enter search term:", "");
if (!text) return;
var first = true;
do {
var cursor = this.mirror.getSearchCursor(text, first);
first = false;
while (cursor.findNext()) {
cursor.select();
if (!confirm("Search again?"))
return;
}
} while (confirm("End of document reached. Start over?"));
},
replace: function() {
// This is a replace-all, but it is possible to implement a
// prompting replace.
var from = prompt("Enter search string:", ""), to;
if (from) to = prompt("What should it be replaced with?", "");
if (to == null) return;
var cursor = this.mirror.getSearchCursor(from, false);
while (cursor.findNext())
cursor.replace(to);
},
jump: function() {
var line = prompt("Jump to line:", "");
if (line && !isNaN(Number(line)))
this.mirror.jumpToLine(Number(line));
},
line: function() {
alert("The cursor is currently at line " + this.mirror.currentLine());
this.mirror.focus();
},
macro: function() {
var name = prompt("Name your constructor:", "");
if (name)
this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n");
},
reindent: function() {
this.mirror.reindent();
}
};
| JavaScript |
/* The Editor object manages the content of the editable frame. It
* catches events, colours nodes, and indents lines. This file also
* holds some functions for transforming arbitrary DOM structures into
* plain sequences of <span> and <br> elements
*/
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
var webkit = /AppleWebKit/.test(navigator.userAgent);
var safari = /Apple Computer, Inc/.test(navigator.vendor);
var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i);
if (gecko) gecko = Number(gecko[1]);
var mac = /Mac/.test(navigator.platform);
// TODO this is related to the backspace-at-end-of-line bug. Remove
// this if Opera gets their act together, make the version check more
// broad if they don't.
var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent);
// TODO remove this once WebKit 533 becomes less common.
var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent);
// Make sure a string does not contain two consecutive 'collapseable'
// whitespace characters.
function makeWhiteSpace(n) {
var buffer = [], nb = true;
for (; n > 0; n--) {
buffer.push((nb || n == 1) ? nbsp : " ");
nb ^= true;
}
return buffer.join("");
}
// Create a set of white-space characters that will not be collapsed
// by the browser, but will not break text-wrapping either.
function fixSpaces(string) {
if (string.charAt(0) == " ") string = nbsp + string.slice(1);
return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);})
.replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
}
function cleanText(text) {
return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
}
// Create a SPAN node with the expected properties for document part
// spans.
function makePartSpan(value) {
var text = value;
if (value.nodeType == 3) text = value.nodeValue;
else value = document.createTextNode(text);
var span = document.createElement("span");
span.isPart = true;
span.appendChild(value);
span.currentText = text;
return span;
}
function alwaysZero() {return 0;}
// On webkit, when the last BR of the document does not have text
// behind it, the cursor can not be put on the line after it. This
// makes pressing enter at the end of the document occasionally do
// nothing (or at least seem to do nothing). To work around it, this
// function makes sure the document ends with a span containing a
// zero-width space character. The traverseDOM iterator filters such
// character out again, so that the parsers won't see them. This
// function is called from a few strategic places to make sure the
// zwsp is restored after the highlighting process eats it.
var webkitLastLineHack = webkit ?
function(container) {
var last = container.lastChild;
if (!last || !last.hackBR) {
var br = document.createElement("br");
br.hackBR = true;
container.appendChild(br);
}
} : function() {};
function asEditorLines(string) {
var tab = makeWhiteSpace(indentUnit);
return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
}
var Editor = (function(){
// The HTML elements whose content should be suffixed by a newline
// when converting them to flat text.
var newlineElements = {"P": true, "DIV": true, "LI": true};
// Helper function for traverseDOM. Flattens an arbitrary DOM node
// into an array of textnodes and <br> tags.
function simplifyDOM(root, atEnd) {
var result = [];
var leaving = true;
function simplifyNode(node, top) {
if (node.nodeType == 3) {
var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
if (text.length) leaving = false;
result.push(node);
}
else if (isBR(node) && node.childNodes.length == 0) {
leaving = true;
result.push(node);
}
else {
for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n);
if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
leaving = true;
if (!atEnd || !top)
result.push(document.createElement("br"));
}
}
}
simplifyNode(root, true);
return result;
}
// Creates a MochiKit-style iterator that goes over a series of DOM
// nodes. The values it yields are strings, the textual content of
// the nodes. It makes sure that all nodes up to and including the
// one whose text is being yielded have been 'normalized' to be just
// <span> and <br> elements.
function traverseDOM(start){
var nodeQueue = [];
// Create a function that can be used to insert nodes after the
// one given as argument.
function pointAt(node){
var parent = node.parentNode;
var next = node.nextSibling;
return function(newnode) {
parent.insertBefore(newnode, next);
};
}
var point = null;
// This an Opera-specific hack -- always insert an empty span
// between two BRs, because Opera's cursor code gets terribly
// confused when the cursor is between two BRs.
var afterBR = true;
// Insert a normalized node at the current point. If it is a text
// node, wrap it in a <span>, and give that span a currentText
// property -- this is used to cache the nodeValue, because
// directly accessing nodeValue is horribly slow on some browsers.
// The dirty property is used by the highlighter to determine
// which parts of the document have to be re-highlighted.
function insertPart(part){
var text = "\n";
if (part.nodeType == 3) {
select.snapshotChanged();
part = makePartSpan(part);
text = part.currentText;
afterBR = false;
}
else {
if (afterBR && window.opera)
point(makePartSpan(""));
afterBR = true;
}
part.dirty = true;
nodeQueue.push(part);
point(part);
return text;
}
// Extract the text and newlines from a DOM node, insert them into
// the document, and return the textual content. Used to replace
// non-normalized nodes.
function writeNode(node, end) {
var simplified = simplifyDOM(node, end);
for (var i = 0; i < simplified.length; i++)
simplified[i] = insertPart(simplified[i]);
return simplified.join("");
}
// Check whether a node is a normalized <span> element.
function partNode(node){
if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
var text = node.firstChild.nodeValue;
node.dirty = node.dirty || text != node.currentText;
node.currentText = text;
return !/[\n\t\r]/.test(node.currentText);
}
return false;
}
// Advance to next node, return string for current node.
function next() {
if (!start) throw StopIteration;
var node = start;
start = node.nextSibling;
if (partNode(node)){
nodeQueue.push(node);
afterBR = false;
return node.currentText;
}
else if (isBR(node)) {
if (afterBR && window.opera)
node.parentNode.insertBefore(makePartSpan(""), node);
nodeQueue.push(node);
afterBR = true;
return "\n";
}
else {
var end = !node.nextSibling;
point = pointAt(node);
removeElement(node);
return writeNode(node, end);
}
}
// MochiKit iterators are objects with a next function that
// returns the next value or throws StopIteration when there are
// no more values.
return {next: next, nodes: nodeQueue};
}
// Determine the text size of a processed node.
function nodeSize(node) {
return isBR(node) ? 1 : node.currentText.length;
}
// Search backwards through the top-level nodes until the next BR or
// the start of the frame.
function startOfLine(node) {
while (node && !isBR(node)) node = node.previousSibling;
return node;
}
function endOfLine(node, container) {
if (!node) node = container.firstChild;
else if (isBR(node)) node = node.nextSibling;
while (node && !isBR(node)) node = node.nextSibling;
return node;
}
function time() {return new Date().getTime();}
// Client interface for searching the content of the editor. Create
// these by calling CodeMirror.getSearchCursor. To use, call
// findNext on the resulting object -- this returns a boolean
// indicating whether anything was found, and can be called again to
// skip to the next find. Use the select and replace methods to
// actually do something with the found locations.
function SearchCursor(editor, pattern, from, caseFold) {
this.editor = editor;
this.history = editor.history;
this.history.commit();
this.valid = !!pattern;
this.atOccurrence = false;
if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase();
function getText(node){
var line = cleanText(editor.history.textAfter(node));
return (caseFold ? line.toLowerCase() : line);
}
var topPos = {node: null, offset: 0}, self = this;
if (from && typeof from == "object" && typeof from.character == "number") {
editor.checkLine(from.line);
var pos = {node: from.line, offset: from.character};
this.pos = {from: pos, to: pos};
}
else if (from) {
this.pos = {from: select.cursorPos(editor.container, true) || topPos,
to: select.cursorPos(editor.container, false) || topPos};
}
else {
this.pos = {from: topPos, to: topPos};
}
if (typeof pattern != "string") { // Regexp match
this.matches = function(reverse, node, offset) {
if (reverse) {
var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0;
while (match) {
var ind = line.indexOf(match[0]);
start += ind;
line = line.slice(ind + 1);
var newmatch = line.match(pattern);
if (newmatch) match = newmatch;
else break;
}
}
else {
var line = getText(node).slice(offset), match = line.match(pattern),
start = match && offset + line.indexOf(match[0]);
}
if (match) {
self.currentMatch = match;
return {from: {node: node, offset: start},
to: {node: node, offset: start + match[0].length}};
}
};
return;
}
if (caseFold) pattern = pattern.toLowerCase();
// Create a matcher function based on the kind of string we have.
var target = pattern.split("\n");
this.matches = (target.length == 1) ?
// For one-line strings, searching can be done simply by calling
// indexOf or lastIndexOf on the current line.
function(reverse, node, offset) {
var line = getText(node), len = pattern.length, match;
if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1)
: (match = line.indexOf(pattern, offset)) != -1)
return {from: {node: node, offset: match},
to: {node: node, offset: match + len}};
} :
// Multi-line strings require internal iteration over lines, and
// some clunky checks to make sure the first match ends at the
// end of the line and the last match starts at the start.
function(reverse, node, offset) {
var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node);
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
if (reverse ? offsetA >= offset || offsetA != match.length
: offsetA <= offset || offsetA != line.length - match.length)
return;
var pos = node;
while (true) {
if (reverse && !pos) return;
pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) );
if (!reverse && !pos) return;
line = getText(pos);
match = target[reverse ? --idx : ++idx];
if (idx > 0 && idx < target.length - 1) {
if (line != match) return;
else continue;
}
var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
return;
return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA},
to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}};
}
};
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
if (!this.valid) return false;
var self = this, pos = reverse ? this.pos.from : this.pos.to,
node = pos.node, offset = pos.offset;
// Reset the cursor if the current line is no longer in the DOM tree.
if (node && !node.parentNode) {
node = null; offset = 0;
}
function savePosAndFail() {
var pos = {node: node, offset: offset};
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
while (true) {
if (this.pos = this.matches(reverse, node, offset)) {
this.atOccurrence = true;
return true;
}
if (reverse) {
if (!node) return savePosAndFail();
node = this.history.nodeBefore(node);
offset = this.history.textAfter(node).length;
}
else {
var next = this.history.nodeAfter(node);
if (!next) {
offset = this.history.textAfter(node).length;
return savePosAndFail();
}
node = next;
offset = 0;
}
}
},
select: function() {
if (this.atOccurrence) {
select.setCursorPos(this.editor.container, this.pos.from, this.pos.to);
select.scrollToCursor(this.editor.container);
}
},
replace: function(string) {
if (this.atOccurrence) {
var fragments = this.currentMatch;
if (fragments)
string = string.replace(/\\(\d)/, function(m, i){return fragments[i];});
var end = this.editor.replaceRange(this.pos.from, this.pos.to, string);
this.pos.to = end;
this.atOccurrence = false;
}
},
position: function() {
if (this.atOccurrence)
return {line: this.pos.from.node, character: this.pos.from.offset};
}
};
// The Editor object is the main inside-the-iframe interface.
function Editor(options) {
this.options = options;
window.indentUnit = options.indentUnit;
var container = this.container = document.body;
this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this);
var self = this;
if (!Editor.Parser)
throw "No parser loaded.";
if (options.parserConfig && Editor.Parser.configure)
Editor.Parser.configure(options.parserConfig);
if (!options.readOnly && !internetExplorer)
select.setCursorPos(container, {node: null, offset: 0});
this.dirty = [];
this.importCode(options.content || "");
this.history.onChange = options.onChange;
if (!options.readOnly) {
if (options.continuousScanning !== false) {
this.scanner = this.documentScanner(options.passTime);
this.delayScanning();
}
function setEditable() {
// Use contentEditable instead of designMode on IE, since designMode frames
// can not run any scripts. It would be nice if we could use contentEditable
// everywhere, but it is significantly flakier than designMode on every
// single non-IE browser.
if (document.body.contentEditable != undefined && internetExplorer)
document.body.contentEditable = "true";
else
document.designMode = "on";
// Work around issue where you have to click on the actual
// body of the document to focus it in IE, making focusing
// hard when the document is small.
if (internetExplorer && options.height != "dynamic")
document.body.style.minHeight = (
window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px";
document.documentElement.style.borderWidth = "0";
if (!options.textWrapping)
container.style.whiteSpace = "nowrap";
}
// If setting the frame editable fails, try again when the user
// focus it (happens when the frame is not visible on
// initialisation, in Firefox).
try {
setEditable();
}
catch(e) {
var focusEvent = addEventHandler(document, "focus", function() {
focusEvent();
setEditable();
}, true);
}
addEventHandler(document, "keydown", method(this, "keyDown"));
addEventHandler(document, "keypress", method(this, "keyPress"));
addEventHandler(document, "keyup", method(this, "keyUp"));
function cursorActivity() {self.cursorActivity(false);}
addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity);
addEventHandler(document.body, "cut", cursorActivity);
// workaround for a gecko bug [?] where going forward and then
// back again breaks designmode (no more cursor)
if (gecko)
addEventHandler(window, "pagehide", function(){self.unloaded = true;});
addEventHandler(document.body, "paste", function(event) {
cursorActivity();
var text = null;
try {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) text = clipboardData.getData('Text');
}
catch(e) {}
if (text !== null) {
event.stop();
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
});
if (this.options.autoMatchParens)
addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
}
else if (!options.textWrapping) {
container.style.whiteSpace = "nowrap";
}
}
function isSafeKey(code) {
return (code >= 16 && code <= 18) || // shift, control, alt
(code >= 33 && code <= 40); // arrows, home, end
}
Editor.prototype = {
// Import a piece of code into the editor.
importCode: function(code) {
var lines = asEditorLines(code), chunk = 1000;
if (!this.options.incrementalLoading || lines.length < chunk) {
this.history.push(null, null, lines);
this.history.reset();
}
else {
var cur = 0, self = this;
function addChunk() {
var chunklines = lines.slice(cur, cur + chunk);
chunklines.push("");
self.history.push(self.history.nodeBefore(null), null, chunklines);
self.history.reset();
cur += chunk;
if (cur < lines.length)
parent.setTimeout(addChunk, 1000);
}
addChunk();
}
},
// Extract the code from the editor.
getCode: function() {
if (!this.container.firstChild)
return "";
var accum = [];
select.markSelection();
forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
select.selectMarked();
// On webkit, don't count last (empty) line if the webkitLastLineHack BR is present
if (webkit && this.container.lastChild.hackBR)
accum.pop();
webkitLastLineHack(this.container);
return cleanText(accum.join(""));
},
checkLine: function(node) {
if (node === false || !(node == null || node.parentNode == this.container || node.hackBR))
throw parent.CodeMirror.InvalidLineHandle;
},
cursorPosition: function(start) {
if (start == null) start = true;
var pos = select.cursorPos(this.container, start);
if (pos) return {line: pos.node, character: pos.offset};
else return {line: null, character: 0};
},
firstLine: function() {
return null;
},
lastLine: function() {
var last = this.container.lastChild;
if (last) last = startOfLine(last);
if (last && last.hackBR) last = startOfLine(last.previousSibling);
return last;
},
nextLine: function(line) {
this.checkLine(line);
var end = endOfLine(line, this.container);
if (!end || end.hackBR) return false;
else return end;
},
prevLine: function(line) {
this.checkLine(line);
if (line == null) return false;
return startOfLine(line.previousSibling);
},
visibleLineCount: function() {
var line = this.container.firstChild;
while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable
if (!line) return false;
var innerHeight = (window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight);
return Math.floor(innerHeight / line.offsetHeight);
},
selectLines: function(startLine, startOffset, endLine, endOffset) {
this.checkLine(startLine);
var start = {node: startLine, offset: startOffset}, end = null;
if (endOffset !== undefined) {
this.checkLine(endLine);
end = {node: endLine, offset: endOffset};
}
select.setCursorPos(this.container, start, end);
select.scrollToCursor(this.container);
},
lineContent: function(line) {
var accum = [];
for (line = line ? line.nextSibling : this.container.firstChild;
line && !isBR(line); line = line.nextSibling)
accum.push(nodeText(line));
return cleanText(accum.join(""));
},
setLineContent: function(line, content) {
this.history.commit();
this.replaceRange({node: line, offset: 0},
{node: line, offset: this.history.textAfter(line).length},
content);
this.addDirtyNode(line);
this.scheduleHighlight();
},
removeLine: function(line) {
var node = line ? line.nextSibling : this.container.firstChild;
while (node) {
var next = node.nextSibling;
removeElement(node);
if (isBR(node)) break;
node = next;
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
insertIntoLine: function(line, position, content) {
var before = null;
if (position == "end") {
before = endOfLine(line, this.container);
}
else {
for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
if (position == 0) {
before = cur;
break;
}
var text = nodeText(cur);
if (text.length > position) {
before = cur.nextSibling;
content = text.slice(0, position) + content + text.slice(position);
removeElement(cur);
break;
}
position -= text.length;
}
}
var lines = asEditorLines(content);
for (var i = 0; i < lines.length; i++) {
if (i > 0) this.container.insertBefore(document.createElement("BR"), before);
this.container.insertBefore(makePartSpan(lines[i]), before);
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
// Retrieve the selected text.
selectedText: function() {
var h = this.history;
h.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return "";
if (start.node == end.node)
return h.textAfter(start.node).slice(start.offset, end.offset);
var text = [h.textAfter(start.node).slice(start.offset)];
for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
text.push(h.textAfter(pos));
text.push(h.textAfter(end.node).slice(0, end.offset));
return cleanText(text.join("\n"));
},
// Replace the selection with another piece of text.
replaceSelection: function(text) {
this.history.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return;
end = this.replaceRange(start, end, text);
select.setCursorPos(this.container, end);
webkitLastLineHack(this.container);
},
cursorCoords: function(start, internal) {
var sel = select.cursorPos(this.container, start);
if (!sel) return null;
var off = sel.offset, node = sel.node, self = this;
function measureFromNode(node, xOffset) {
var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0),
x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset;
forEach([node, internal ? null : window.frameElement], function(n) {
while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;}
});
return {x: x, y: y, yBot: y + node.offsetHeight};
}
function withTempNode(text, f) {
var node = document.createElement("SPAN");
node.appendChild(document.createTextNode(text));
try {return f(node);}
finally {if (node.parentNode) node.parentNode.removeChild(node);}
}
while (off) {
node = node ? node.nextSibling : this.container.firstChild;
var txt = nodeText(node);
if (off < txt.length)
return withTempNode(txt.substr(0, off), function(tmp) {
tmp.style.position = "absolute"; tmp.style.visibility = "hidden";
tmp.className = node.className;
self.container.appendChild(tmp);
return measureFromNode(node, tmp.offsetWidth);
});
off -= txt.length;
}
if (node && isSpan(node))
return measureFromNode(node, node.offsetWidth);
else if (node && node.nextSibling && isSpan(node.nextSibling))
return measureFromNode(node.nextSibling, 0);
else
return withTempNode("\u200b", function(tmp) {
if (node) node.parentNode.insertBefore(tmp, node.nextSibling);
else self.container.insertBefore(tmp, self.container.firstChild);
return measureFromNode(tmp, 0);
});
},
reroutePasteEvent: function() {
if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return;
this.capturingPaste = true;
var te = window.frameElement.CodeMirror.textareaHack;
var coords = this.cursorCoords(true, true);
te.style.top = coords.y + "px";
if (internetExplorer) {
var snapshot = select.getBookmark(this.container);
if (snapshot) this.selectionSnapshot = snapshot;
}
parent.focus();
te.value = "";
te.focus();
var self = this;
parent.setTimeout(function() {
self.capturingPaste = false;
window.focus();
if (self.selectionSnapshot) // IE hack
window.select.setBookmark(self.container, self.selectionSnapshot);
var text = te.value;
if (text) {
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
}, 10);
},
replaceRange: function(from, to, text) {
var lines = asEditorLines(text);
lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
var lastLine = lines[lines.length - 1];
lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
var end = this.history.nodeAfter(to.node);
this.history.push(from.node, end, lines);
return {node: this.history.nodeBefore(end),
offset: lastLine.length};
},
getSearchCursor: function(string, fromCursor, caseFold) {
return new SearchCursor(this, string, fromCursor, caseFold);
},
// Re-indent the whole buffer
reindent: function() {
if (this.container.firstChild)
this.indentRegion(null, this.container.lastChild);
},
reindentSelection: function(direction) {
if (!select.somethingSelected()) {
this.indentAtCursor(direction);
}
else {
var start = select.selectionTopNode(this.container, true),
end = select.selectionTopNode(this.container, false);
if (start === false || end === false) return;
this.indentRegion(start, end, direction, true);
}
},
grabKeys: function(eventHandler, filter) {
this.frozen = eventHandler;
this.keyFilter = filter;
},
ungrabKeys: function() {
this.frozen = "leave";
},
setParser: function(name, parserConfig) {
Editor.Parser = window[name];
parserConfig = parserConfig || this.options.parserConfig;
if (parserConfig && Editor.Parser.configure)
Editor.Parser.configure(parserConfig);
if (this.container.firstChild) {
forEach(this.container.childNodes, function(n) {
if (n.nodeType != 3) n.dirty = true;
});
this.addDirtyNode(this.firstChild);
this.scheduleHighlight();
}
},
// Intercept enter and tab, and assign their new functions.
keyDown: function(event) {
if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;}
if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) {
event.stop();
this.frozen(event);
return;
}
var code = event.keyCode;
// Don't scan when the user is typing.
this.delayScanning();
// Schedule a paren-highlight event, if configured.
if (this.options.autoMatchParens)
this.scheduleParenHighlight();
// The various checks for !altKey are there because AltGr sets both
// ctrlKey and altKey to true, and should not be recognised as
// Control.
if (code == 13) { // enter
if (event.ctrlKey && !event.altKey) {
this.reparseBuffer();
}
else {
select.insertNewlineAtCursor();
var mode = this.options.enterMode;
if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined);
select.scrollToCursor(this.container);
}
event.stop();
}
else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
this.handleTab(!event.shiftKey);
event.stop();
}
else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space
this.handleTab(true);
event.stop();
}
else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
if (this.home()) event.stop();
}
else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
if (this.end()) event.stop();
}
// Only in Firefox is the default behavior for PgUp/PgDn correct.
else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp
if (this.pageUp()) event.stop();
}
else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn
if (this.pageDown()) event.stop();
}
else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
this.highlightParens(event.shiftKey, true);
event.stop();
}
else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
var cursor = select.selectionTopNode(this.container);
if (cursor === false || !this.container.firstChild) return;
if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
else {
var end = endOfLine(cursor, this.container);
select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
}
event.stop();
}
else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
select.scrollToNode(this.history.redo());
event.stop();
}
else if (code == 90 || (safari && code == 8)) { // Z, backspace
select.scrollToNode(this.history.undo());
event.stop();
}
else if (code == 83 && this.options.saveFunction) { // S
this.options.saveFunction();
event.stop();
}
else if (code == 86 && !mac) { // V
this.reroutePasteEvent();
}
}
},
// Check for characters that should re-indent the current line,
// and prevent Opera from handling enter and tab anyway.
keyPress: function(event) {
var electric = this.options.electricChars && Editor.Parser.electricChars, self = this;
// Hack for Opera, and Firefox on OS X, in which stopping a
// keydown event does not prevent the associated keypress event
// from happening, so we have to cancel enter and tab again
// here.
if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) ||
event.code == 13 || (event.code == 9 && this.options.tabMode != "default") ||
(event.code == 32 && event.shiftKey && this.options.tabMode == "default"))
event.stop();
else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") {
this.reroutePasteEvent();
}
else if (electric && electric.indexOf(event.character) != -1)
parent.setTimeout(function(){self.indentAtCursor(null);}, 0);
// Work around a bug where pressing backspace at the end of a
// line, or delete at the start, often causes the cursor to jump
// to the start of the line in Opera 10.60.
else if (brokenOpera) {
if (event.code == 8) { // backspace
var sel = select.selectionTopNode(this.container), self = this,
next = sel ? sel.nextSibling : this.container.firstChild;
if (sel !== false && next && isBR(next))
parent.setTimeout(function(){
if (select.selectionTopNode(self.container) == next)
select.focusAfterNode(next.previousSibling, self.container);
}, 20);
}
else if (event.code == 46) { // delete
var sel = select.selectionTopNode(this.container), self = this;
if (sel && isBR(sel)) {
parent.setTimeout(function(){
if (select.selectionTopNode(self.container) != sel)
select.focusAfterNode(sel, self.container);
}, 20);
}
}
}
// In 533.* WebKit versions, when the document is big, typing
// something at the end of a line causes the browser to do some
// kind of stupid heavy operation, creating delays of several
// seconds before the typed characters appear. This very crude
// hack inserts a temporary zero-width space after the cursor to
// make it not be at the end of the line.
else if (slowWebkit) {
var sel = select.selectionTopNode(this.container),
next = sel ? sel.nextSibling : this.container.firstChild;
// Doesn't work on empty lines, for some reason those always
// trigger the delay.
if (sel && next && isBR(next) && !isBR(sel)) {
var cheat = document.createTextNode("\u200b");
this.container.insertBefore(cheat, next);
parent.setTimeout(function() {
if (cheat.nodeValue == "\u200b") removeElement(cheat);
else cheat.nodeValue = cheat.nodeValue.replace("\u200b", "");
}, 20);
}
}
// Magic incantation that works abound a webkit bug when you
// can't type on a blank line following a line that's wider than
// the window.
if (webkit && !this.options.textWrapping)
setTimeout(function () {
var node = select.selectionTopNode(self.container, true);
if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling)
&& node.nextSibling && isBR(node.nextSibling))
node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling);
}, 50);
},
// Mark the node at the cursor dirty when a non-safe key is
// released.
keyUp: function(event) {
this.cursorActivity(isSafeKey(event.keyCode));
},
// Indent the line following a given <br>, or null for the first
// line. If given a <br> element, this must have been highlighted
// so that it has an indentation method. Returns the whitespace
// element that has been modified or created (if any).
indentLineAfter: function(start, direction) {
function whiteSpaceAfter(node) {
var ws = node ? node.nextSibling : self.container.firstChild;
if (!ws || !hasClass(ws, "whitespace")) return null;
return ws;
}
// whiteSpace is the whitespace span at the start of the line,
// or null if there is no such node.
var self = this, whiteSpace = whiteSpaceAfter(start);
var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
if (direction == "keep") {
if (start) {
var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling))
if (prevWS) newIndent = prevWS.currentText.length;
}
}
else {
// Sometimes the start of the line can influence the correct
// indentation, so we retrieve it.
var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
// Ask the lexical context for the correct indentation, and
// compute how much this differs from the current indentation.
if (direction != null && this.options.tabMode != "indent")
newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
else if (start)
newIndent = start.indentation(nextChars, curIndent, direction, firstText);
else if (Editor.Parser.firstIndentation)
newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText);
}
var indentDiff = newIndent - curIndent;
// If there is too much, this is just a matter of shrinking a span.
if (indentDiff < 0) {
if (newIndent == 0) {
if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0);
removeElement(whiteSpace);
whiteSpace = null;
}
else {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
}
// Not enough...
else if (indentDiff > 0) {
// If there is whitespace, we grow it.
if (whiteSpace) {
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
}
// Otherwise, we have to add a new whitespace node.
else {
whiteSpace = makePartSpan(makeWhiteSpace(newIndent));
whiteSpace.className = "whitespace";
if (start) insertAfter(whiteSpace, start);
else this.container.insertBefore(whiteSpace, this.container.firstChild);
select.snapshotMove(firstText && (firstText.firstChild || firstText),
whiteSpace.firstChild, newIndent, false, true);
}
}
// Make sure cursor ends up after the whitespace
else if (whiteSpace) {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false);
}
if (indentDiff != 0) this.addDirtyNode(start);
},
// Re-highlight the selected part of the document.
highlightAtCursor: function() {
var pos = select.selectionTopNode(this.container, true);
var to = select.selectionTopNode(this.container, false);
if (pos === false || to === false) return false;
select.markSelection();
if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
return false;
select.selectMarked();
return true;
},
// When tab is pressed with text selected, the whole selection is
// re-indented, when nothing is selected, the line with the cursor
// is re-indented.
handleTab: function(direction) {
if (this.options.tabMode == "spaces" && !select.somethingSelected())
select.insertTabAtCursor();
else
this.reindentSelection(direction);
},
// Custom home behaviour that doesn't land the cursor in front of
// leading whitespace unless pressed twice.
home: function() {
var cur = select.selectionTopNode(this.container, true), start = cur;
if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
return false;
while (cur && !isBR(cur)) cur = cur.previousSibling;
var next = cur ? cur.nextSibling : this.container.firstChild;
if (next && next != start && next.isPart && hasClass(next, "whitespace"))
select.focusAfterNode(next, this.container);
else
select.focusAfterNode(cur, this.container);
select.scrollToCursor(this.container);
return true;
},
// Some browsers (Opera) don't manage to handle the end key
// properly in the face of vertical scrolling.
end: function() {
var cur = select.selectionTopNode(this.container, true);
if (cur === false) return false;
cur = endOfLine(cur, this.container);
if (!cur) return false;
select.focusAfterNode(cur.previousSibling, this.container);
select.scrollToCursor(this.container);
return true;
},
pageUp: function() {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to keep one line on the screen.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
line = this.prevLine(line);
if (line === false) break;
}
if (i == 0) return false; // Already at first line
select.setCursorPos(this.container, {node: line, offset: 0});
select.scrollToCursor(this.container);
return true;
},
pageDown: function() {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to move to the last line of the current page.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
var nextLine = this.nextLine(line);
if (nextLine === false) break;
line = nextLine;
}
if (i == 0) return false; // Already at last line
select.setCursorPos(this.container, {node: line, offset: 0});
select.scrollToCursor(this.container);
return true;
},
// Delay (or initiate) the next paren highlight event.
scheduleParenHighlight: function() {
if (this.parenEvent) parent.clearTimeout(this.parenEvent);
var self = this;
this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300);
},
// Take the token before the cursor. If it contains a character in
// '()[]{}', search for the matching paren/brace/bracket, and
// highlight them in green for a moment, or red if no proper match
// was found.
highlightParens: function(jump, fromKey) {
var self = this, mark = this.options.markParen;
if (typeof mark == "string") mark = [mark, mark];
// give the relevant nodes a colour.
function highlight(node, ok) {
if (!node) return;
if (!mark) {
node.style.fontWeight = "bold";
node.style.color = ok ? "#8F8" : "#F88";
}
else if (mark.call) mark(node, ok);
else node.className += " " + mark[ok ? 0 : 1];
}
function unhighlight(node) {
if (!node) return;
if (mark && !mark.call)
removeClass(removeClass(node, mark[0]), mark[1]);
else if (self.options.unmarkParen)
self.options.unmarkParen(node);
else {
node.style.fontWeight = "";
node.style.color = "";
}
}
if (!fromKey && self.highlighted) {
unhighlight(self.highlighted[0]);
unhighlight(self.highlighted[1]);
}
if (!window || !window.parent || !window.select) return;
// Clear the event property.
if (this.parenEvent) parent.clearTimeout(this.parenEvent);
this.parenEvent = null;
// Extract a 'paren' from a piece of text.
function paren(node) {
if (node.currentText) {
var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
return match && match[1];
}
}
// Determine the direction a paren is facing.
function forward(ch) {
return /[\(\[\{]/.test(ch);
}
var ch, cursor = select.selectionTopNode(this.container, true);
if (!cursor || !this.highlightAtCursor()) return;
cursor = select.selectionTopNode(this.container, true);
if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
return;
// We only look for tokens with the same className.
var className = cursor.className, dir = forward(ch), match = matching[ch];
// Since parts of the document might not have been properly
// highlighted, and it is hard to know in advance which part we
// have to scan, we just try, and when we find dirty nodes we
// abort, parse them, and re-try.
function tryFindMatch() {
var stack = [], ch, ok = true;
for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
if (forward(ch) == dir)
stack.push(ch);
else if (!stack.length)
ok = false;
else if (stack.pop() != matching[ch])
ok = false;
if (!stack.length) break;
}
else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
return {node: runner, status: "dirty"};
}
}
return {node: runner, status: runner && ok};
}
while (true) {
var found = tryFindMatch();
if (found.status == "dirty") {
this.highlight(found.node, endOfLine(found.node));
// Needed because in some corner cases a highlight does not
// reach a node.
found.node.dirty = false;
continue;
}
else {
highlight(cursor, found.status);
highlight(found.node, found.status);
if (fromKey)
parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500);
else
self.highlighted = [cursor, found.node];
if (jump && found.node)
select.focusAfterNode(found.node.previousSibling, this.container);
break;
}
}
},
// Adjust the amount of whitespace at the start of the line that
// the cursor is on so that it is indented properly.
indentAtCursor: function(direction) {
if (!this.container.firstChild) return;
// The line has to have up-to-date lexical information, so we
// highlight it first.
if (!this.highlightAtCursor()) return;
var cursor = select.selectionTopNode(this.container, false);
// If we couldn't determine the place of the cursor,
// there's nothing to indent.
if (cursor === false)
return;
select.markSelection();
this.indentLineAfter(startOfLine(cursor), direction);
select.selectMarked();
},
// Indent all lines whose start falls inside of the current
// selection.
indentRegion: function(start, end, direction, selectAfter) {
var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
if (!isBR(end)) end = endOfLine(end, this.container);
this.addDirtyNode(start);
do {
var next = endOfLine(current, this.container);
if (current) this.highlight(before, next, true);
this.indentLineAfter(current, direction);
before = current;
current = next;
} while (current != end);
if (selectAfter)
select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0});
},
// Find the node that the cursor is in, mark it as dirty, and make
// sure a highlight pass is scheduled.
cursorActivity: function(safe) {
// pagehide event hack above
if (this.unloaded) {
window.document.designMode = "off";
window.document.designMode = "on";
this.unloaded = false;
}
if (internetExplorer) {
this.container.createTextRange().execCommand("unlink");
clearTimeout(this.saveSelectionSnapshot);
var self = this;
this.saveSelectionSnapshot = setTimeout(function() {
var snapshot = select.getBookmark(self.container);
if (snapshot) self.selectionSnapshot = snapshot;
}, 200);
}
var activity = this.options.onCursorActivity;
if (!safe || activity) {
var cursor = select.selectionTopNode(this.container, false);
if (cursor === false || !this.container.firstChild) return;
cursor = cursor || this.container.firstChild;
if (activity) activity(cursor);
if (!safe) {
this.scheduleHighlight();
this.addDirtyNode(cursor);
}
}
},
reparseBuffer: function() {
forEach(this.container.childNodes, function(node) {node.dirty = true;});
if (this.container.firstChild)
this.addDirtyNode(this.container.firstChild);
},
// Add a node to the set of dirty nodes, if it isn't already in
// there.
addDirtyNode: function(node) {
node = node || this.container.firstChild;
if (!node) return;
for (var i = 0; i < this.dirty.length; i++)
if (this.dirty[i] == node) return;
if (node.nodeType != 3)
node.dirty = true;
this.dirty.push(node);
},
allClean: function() {
return !this.dirty.length;
},
// Cause a highlight pass to happen in options.passDelay
// milliseconds. Clear the existing timeout, if one exists. This
// way, the passes do not happen while the user is typing, and
// should as unobtrusive as possible.
scheduleHighlight: function() {
// Timeouts are routed through the parent window, because on
// some browsers designMode windows do not fire timeouts.
var self = this;
parent.clearTimeout(this.highlightTimeout);
this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay);
},
// Fetch one dirty node, and remove it from the dirty set.
getDirtyNode: function() {
while (this.dirty.length > 0) {
var found = this.dirty.pop();
// IE8 sometimes throws an unexplainable 'invalid argument'
// exception for found.parentNode
try {
// If the node has been coloured in the meantime, or is no
// longer in the document, it should not be returned.
while (found && found.parentNode != this.container)
found = found.parentNode;
if (found && (found.dirty || found.nodeType == 3))
return found;
} catch (e) {}
}
return null;
},
// Pick dirty nodes, and highlight them, until options.passTime
// milliseconds have gone by. The highlight method will continue
// to next lines as long as it finds dirty nodes. It returns
// information about the place where it stopped. If there are
// dirty nodes left after this function has spent all its lines,
// it shedules another highlight to finish the job.
highlightDirty: function(force) {
// Prevent FF from raising an error when it is firing timeouts
// on a page that's no longer loaded.
if (!window || !window.parent || !window.select) return false;
if (!this.options.readOnly) select.markSelection();
var start, endTime = force ? null : time() + this.options.passTime;
while ((time() < endTime || force) && (start = this.getDirtyNode())) {
var result = this.highlight(start, endTime);
if (result && result.node && result.dirty)
this.addDirtyNode(result.node.nextSibling);
}
if (!this.options.readOnly) select.selectMarked();
if (start) this.scheduleHighlight();
return this.dirty.length == 0;
},
// Creates a function that, when called through a timeout, will
// continuously re-parse the document.
documentScanner: function(passTime) {
var self = this, pos = null;
return function() {
// FF timeout weirdness workaround.
if (!window || !window.parent || !window.select) return;
// If the current node is no longer in the document... oh
// well, we start over.
if (pos && pos.parentNode != self.container)
pos = null;
select.markSelection();
var result = self.highlight(pos, time() + passTime, true);
select.selectMarked();
var newPos = result ? (result.node && result.node.nextSibling) : null;
pos = (pos == newPos) ? null : newPos;
self.delayScanning();
};
},
// Starts the continuous scanning process for this document after
// a given interval.
delayScanning: function() {
if (this.scanner) {
parent.clearTimeout(this.documentScan);
this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning);
}
},
// The function that does the actual highlighting/colouring (with
// help from the parser and the DOM normalizer). Its interface is
// rather overcomplicated, because it is used in different
// situations: ensuring that a certain line is highlighted, or
// highlighting up to X milliseconds starting from a certain
// point. The 'from' argument gives the node at which it should
// start. If this is null, it will start at the beginning of the
// document. When a timestamp is given with the 'target' argument,
// it will stop highlighting at that time. If this argument holds
// a DOM node, it will highlight until it reaches that node. If at
// any time it comes across two 'clean' lines (no dirty nodes), it
// will stop, except when 'cleanLines' is true. maxBacktrack is
// the maximum number of lines to backtrack to find an existing
// parser instance. This is used to give up in situations where a
// highlight would take too long and freeze the browser interface.
highlight: function(from, target, cleanLines, maxBacktrack){
var container = this.container, self = this, active = this.options.activeTokens;
var endTime = (typeof target == "number" ? target : null);
if (!container.firstChild)
return false;
// Backtrack to the first node before from that has a partial
// parse stored.
while (from && (!from.parserFromHere || from.dirty)) {
if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
return false;
from = from.previousSibling;
}
// If we are at the end of the document, do nothing.
if (from && !from.nextSibling)
return false;
// Check whether a part (<span> node) and the corresponding token
// match.
function correctPart(token, part){
return !part.reduced && part.currentText == token.value && part.className == token.style;
}
// Shorten the text associated with a part by chopping off
// characters from the front. Note that only the currentText
// property gets changed. For efficiency reasons, we leave the
// nodeValue alone -- we set the reduced flag to indicate that
// this part must be replaced.
function shortenPart(part, minus){
part.currentText = part.currentText.substring(minus);
part.reduced = true;
}
// Create a part corresponding to a given token.
function tokenPart(token){
var part = makePartSpan(token.value);
part.className = token.style;
return part;
}
function maybeTouch(node) {
if (node) {
var old = node.oldNextSibling;
if (lineDirty || old === undefined || node.nextSibling != old)
self.history.touch(node);
node.oldNextSibling = node.nextSibling;
}
else {
var old = self.container.oldFirstChild;
if (lineDirty || old === undefined || self.container.firstChild != old)
self.history.touch(null);
self.container.oldFirstChild = self.container.firstChild;
}
}
// Get the token stream. If from is null, we start with a new
// parser from the start of the frame, otherwise a partial parse
// is resumed.
var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
stream = stringStream(traversal),
parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
function surroundedByBRs(node) {
return (node.previousSibling == null || isBR(node.previousSibling)) &&
(node.nextSibling == null || isBR(node.nextSibling));
}
// parts is an interface to make it possible to 'delay' fetching
// the next DOM node until we are completely done with the one
// before it. This is necessary because often the next node is
// not yet available when we want to proceed past the current
// one.
var parts = {
current: null,
// Fetch current node.
get: function(){
if (!this.current)
this.current = traversal.nodes.shift();
return this.current;
},
// Advance to the next part (do not fetch it yet).
next: function(){
this.current = null;
},
// Remove the current part from the DOM tree, and move to the
// next.
remove: function(){
container.removeChild(this.get());
this.current = null;
},
// Advance to the next part that is not empty, discarding empty
// parts.
getNonEmpty: function(){
var part = this.get();
// Allow empty nodes when they are alone on a line, needed
// for the FF cursor bug workaround (see select.js,
// insertNewlineAtCursor).
while (part && isSpan(part) && part.currentText == "") {
// Leave empty nodes that are alone on a line alone in
// Opera, since that browsers doesn't deal well with
// having 2 BRs in a row.
if (window.opera && surroundedByBRs(part)) {
this.next();
part = this.get();
}
else {
var old = part;
this.remove();
part = this.get();
// Adjust selection information, if any. See select.js for details.
select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
}
}
return part;
}
};
var lineDirty = false, prevLineDirty = true, lineNodes = 0;
// This forEach loops over the tokens from the parsed stream, and
// at the same time uses the parts object to proceed through the
// corresponding DOM nodes.
forEach(parsed, function(token){
var part = parts.getNonEmpty();
if (token.value == "\n"){
// The idea of the two streams actually staying synchronized
// is such a long shot that we explicitly check.
if (!isBR(part))
throw "Parser out of sync. Expected BR.";
if (part.dirty || !part.indentation) lineDirty = true;
maybeTouch(from);
from = part;
// Every <br> gets a copy of the parser state and a lexical
// context assigned to it. The first is used to be able to
// later resume parsing from this point, the second is used
// for indentation.
part.parserFromHere = parsed.copy();
part.indentation = token.indentation || alwaysZero;
part.dirty = false;
// If the target argument wasn't an integer, go at least
// until that node.
if (endTime == null && part == target) throw StopIteration;
// A clean line with more than one node means we are done.
// Throwing a StopIteration is the way to break out of a
// MochiKit forEach loop.
if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
throw StopIteration;
prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
parts.next();
}
else {
if (!isSpan(part))
throw "Parser out of sync. Expected SPAN.";
if (part.dirty)
lineDirty = true;
lineNodes++;
// If the part matches the token, we can leave it alone.
if (correctPart(token, part)){
if (active && part.dirty) active(part, token, self);
part.dirty = false;
parts.next();
}
// Otherwise, we have to fix it.
else {
lineDirty = true;
// Insert the correct part.
var newPart = tokenPart(token);
container.insertBefore(newPart, part);
if (active) active(newPart, token, self);
var tokensize = token.value.length;
var offset = 0;
// Eat up parts until the text for this token has been
// removed, adjusting the stored selection info (see
// select.js) in the process.
while (tokensize > 0) {
part = parts.get();
var partsize = part.currentText.length;
select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
if (partsize > tokensize){
shortenPart(part, tokensize);
tokensize = 0;
}
else {
tokensize -= partsize;
offset += partsize;
parts.remove();
}
}
}
}
});
maybeTouch(from);
webkitLastLineHack(this.container);
// The function returns some status information that is used by
// hightlightDirty to determine whether and where it has to
// continue.
return {node: parts.getNonEmpty(),
dirty: lineDirty};
}
};
return Editor;
})();
addEventHandler(window, "load", function() {
var CodeMirror = window.frameElement.CodeMirror;
var e = CodeMirror.editor = new Editor(CodeMirror.options);
parent.setTimeout(method(CodeMirror, "init"), 0);
});
| JavaScript |
/**
* Tinymce template_list.js sample file
* @version tinymce 3.3.9
* @package Joomla
* @copyright Copyright (C) 2005 - 2012 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system.
// There templates will be displayed as a dropdown in all media dialog if the "template_external_list_url"
// option is defined in TinyMCE init.
var tinyMCETemplateList = [
// Name, URL, Description
["Simple snippet", "media/editors/tinymce/templates/snippet1.html", "Simple HTML snippet."],
["Layout", "media/editors/tinymce/templates/layout1.html", "HTMLLayout."]
];
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Some state variables for the overrider
*/
Joomla.overrider = {
states : {
refreshing: false,
refreshed: false,
counter: 0,
searchstring: '',
searchtype: 'value'
}
};
/**
* Method for refreshing the database cache of known language strings via Ajax
*
* @return void
*
* @since 2.5
*/
Joomla.overrider.refreshCache = function()
{
var req = new Request.JSON({
method: 'post',
url: 'index.php?option=com_languages&task=strings.refresh&format=json',
onRequest: function()
{
this.states.refreshing = true;
document.id('refresh-status').reveal();
}.bind(this),
onSuccess: function(r)
{
if (r.error && r.message)
{
alert(r.message);
}
if (r.messages)
{
Joomla.renderMessages(r.messages);
}
document.id('refresh-status').dissolve();
this.states.refreshing = false;
}.bind(this),
onFailure: function(xhr)
{
alert(Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_REQUEST_ERROR'));
document.id('refresh-status').dissolve();
}.bind(this),
onError: function(text, error)
{
alert(error + "\n\n" + text);
document.id('refresh-status').dissolve();
}.bind(this)
});
req.post();
};
/**
* Method for searching known language strings via Ajax
*
* @param int more Determines the limit start of the results
*
* @return void
*
* @since 2.5
*/
Joomla.overrider.searchStrings = function(more)
{
// Prevent searching if the cache is refreshed at the moment
if (this.states.refreshing)
{
return;
}
// Only update the used searchstring and searchtype if the search button
// was used to start the search (that will be the case if 'more' is null)
if (!more)
{
this.states.searchstring = document.id('jform_searchstring').value;
this.states.searchtype = 'value';
if (document.id('jform_searchtype0').checked)
{
this.states.searchtype = 'constant';
}
}
if (!this.states.searchstring)
{
document.id('jform_searchstring').addClass('invalid');
return;
}
var req = new Request.JSON({
method: 'post',
url: 'index.php?option=com_languages&task=strings.search&format=json',
onRequest: function()
{
if (more)
{
// If 'more' is greater than 0 we have already displayed some results for
// the current searchstring, so display the spinner at the more link
document.id('more-results').addClass('overrider-spinner');
}
else
{
// Otherwise it is a new searchstring and we have to remove all previous results first
document.id('more-results').set('style', 'display:none;');
var children = $$('#results-container div.language-results');
children.destroy();
document.id('results-container').addClass('overrider-spinner').reveal();
}
}.bind(this),
onSuccess: function(r) {
if (r.error && r.message)
{
alert(r.message);
}
if (r.messages)
{
Joomla.renderMessages(r.messages);
}
if(r.data)
{
if(r.data.results)
{
this.insertResults(r.data.results);
}
if(r.data.more)
{
// If there are more results than the sent ones
// display the more link
this.states.more = r.data.more;
document.id('more-results').reveal();
}
else
{
document.id('more-results').set('style', 'display:none;');
}
}
document.id('results-container').removeClass('overrider-spinner');
document.id('more-results').removeClass('overrider-spinner');
}.bind(this),
onFailure: function(xhr)
{
alert(Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_REQUEST_ERROR'));
document.id('results-container').removeClass('overrider-spinner');
document.id('more-results').removeClass('overrider-spinner');
}.bind(this),
onError: function(text, error)
{
alert(error + "\n\n" + text);
document.id('results-container').removeClass('overrider-spinner');
document.id('more-results').removeClass('overrider-spinner');
}.bind(this)
});
req.post('searchstring=' + this.states.searchstring + '&searchtype=' + this.states.searchtype + '&more=' + more);
};
/**
* Method inserting the received results into the results container
*
* @param array results An array of search result objects
*
* @return void
*
* @since 2.5
*/
Joomla.overrider.insertResults = function(results)
{
// For creating an individual ID for each result we use a counter
this.states.counter = this.states.counter + 1;
// Create a container into which all the results will be inserted
var results_div = new Element('div', {
id: 'language-results' + this.states.counter,
'class': 'language-results',
style: 'display:none;'
});
// Create some elements for each result and insert it into the container
Array.each(results, function (item, index) {
var div = new Element('div', {
'class': 'result row' + index%2,
onclick: 'Joomla.overrider.selectString(' + this.states.counter + index + ');',
});
var key = new Element('div', {
id: 'override_key' + this.states.counter + index,
'class': 'result-key',
html: item.constant,
title: item.file
});
key.inject(div);
var string = new Element('div', {
id: 'override_string' + this.states.counter + index,
'class': 'result-string',
html: item.string
});
string.inject(div);
div.inject(results_div);
}, this);
// If there aren't any results display an appropriate message
if(!results.length)
{
var noresult = new Element('div', {
html: Joomla.JText._('COM_LANGUAGES_VIEW_OVERRIDE_NO_RESULTS')
});
noresult.inject(results_div);
}
// Finally insert the container afore the more link and reveal it
results_div.inject(document.id('more-results'), 'before');
document.id('language-results' + this.states.counter).reveal();
};
/**
* Inserts a specific constant/value pair into the form and scrolls the page back to the top
*
* @param int id The ID of the element which was selected for insertion
*
* @return void
*
* @since 2.5
*/
Joomla.overrider.selectString = function(id)
{
document.id('jform_key').value = document.id('override_key' + id).get('html');
document.id('jform_override').value = document.id('override_string' + id).get('html');
new Fx.Scroll(window).toTop();
}; | JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
var plg_quickicon_jupdatecheck_ajax_structure = {};
window.addEvent('domready', function(){
plg_quickicon_jupdatecheck_ajax_structure = {
onSuccess: function(msg, responseXML)
{
try {
var updateInfoList = JSON.decode(msg, true);
} catch(e) {
// An error occured
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR);
}
if (updateInfoList instanceof Array) {
if (updateInfoList.length < 1) {
// No updates
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPTODATE);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.UPTODATE);
} else {
var updateInfo = updateInfoList.shift();
if (updateInfo.version != plg_quickicon_jupdatecheck_jversion) {
var updateString = plg_quickicon_joomlaupdate_text.UPDATEFOUND.replace("%s", updateInfo.version+"");
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPDATEFOUND);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', updateString);
} else {
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.UPTODATE);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.UPTODATE);
}
}
} else {
// An error occured
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR);
}
},
onFailure: function(req) {
// An error occured
document.id('plg_quickicon_joomlaupdate').getElements('img').setProperty('src',plg_quickicon_joomlaupdate_img.ERROR);
document.id('plg_quickicon_joomlaupdate').getElements('span').set('html', plg_quickicon_joomlaupdate_text.ERROR);
},
url: plg_quickicon_joomlaupdate_ajax_url
};
setTimeout("ajax_object = new Request(plg_quickicon_jupdatecheck_ajax_structure); ajax_object.send('eid=700&cache_timeout=3600');", 2000);
}); | JavaScript |
/**
* @package Joomla.JavaScript
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// Only define the Joomla namespace if not defined.
if (typeof(Joomla) === 'undefined') {
var Joomla = {};
}
/**
* JCombobox JavaScript behavior.
*
* Inspired by: Subrata Chakrabarty <http://chakrabarty.com/editable_dropdown_samplecode.html>
*
* @package Joomla.JavaScript
* @since 1.6
*/
Joomla.combobox = {};
Joomla.combobox.transform = function(el, options)
{
// Add the editable option to the select.
var o = new Element('option', {'class':'custom'}).set('text', Joomla.JText._('ComboBoxInitString', 'type custom...'));
o.inject(el, 'top');
document.id(el).set('changeType', 'manual');
// Add a key press event handler.
el.addEvent('keypress', function(e){
// The change in selected option was browser behavior.
if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto'))
{
this.options.selectedIndex = 0;
this.set('changeType', 'manual');
}
// Check to see if the character is valid.
if ((e.code > 47 && e.code < 59) || (e.code > 62 && e.code < 127) || (e.code == 32)) {
var validChar = true;
} else {
var validChar = false;
}
// If the editable option is selected, proceed.
if (this.options.selectedIndex == 0)
{
// Get the custom string for editing.
var customString = this.options[0].value;
// If the string is being edited for the first time, nullify it.
if ((validChar == true) || (e.key == 'backspace'))
{
if (customString == Joomla.JText._('ComboBoxInitString', 'type custom...')) {
customString = '';
}
}
// If the backspace key was used, remove a character from the end of the string.
if (e.key == 'backspace')
{
customString = customString.substring(0, customString.length - 1);
if (customString == '') {
customString = Joomla.JText._('ComboBoxInitString', 'type custom...');
}
// Indicate that the change event was manually initiated.
this.set('changeType', 'manual');
}
// Handle valid characters to add to the editable option.
if (validChar == true)
{
// Concatenate the new character to the custom string.
customString += String.fromCharCode(e.code);
}
// Set the new custom string into the editable select option.
this.options.selectedIndex = 0;
this.options[0].text = customString;
this.options[0].value = customString;
e.stop();
}
});
// Add a change event handler.
el.addEvent('change', function(e){
// The change in selected option was browser behavior.
if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto'))
{
this.options.selectedIndex = 0;
this.set('changeType', 'manual');
}
});
// Add a keydown event handler.
el.addEvent('keydown', function(e){
// Stop the backspace key from firing the back button of the browser.
if (e.code == 8 || e.code == 127) {
e.stop();
// Stopping the keydown event in WebKit stops the keypress event as well.
if (Browser.Engine.webkit || Browser.Engine.trident) {
this.fireEvent('keypress', e);
}
}
if (this.options.selectedIndex == 0)
{
/*
* In some browsers a feature exists to automatically jump to select options which
* have the same letter typed as the first letter of the option. The following
* section is designed to mitigate this issue when editing the custom option.
*
* Compare the entered character with the first character of all non-editable
* select options. If they match, then we assume the change happened because of
* the browser trying to auto-change for the given character.
*/
var character = String.fromCharCode(e.code).toLowerCase();
for (var i = 1; i < this.options.length; i++)
{
// Get the first character from the select option.
var FirstChar = this.options[i].value.charAt(0).toLowerCase();
// If the first character matches the entered character, the change was automatic.
if ((FirstChar == character)) {
this.options.selectedIndex = 0;
this.set('changeType', 'auto');
}
}
}
});
// Add a keyup event handler.
el.addEvent('keyup', function(e){
// If the left or right arrow keys are pressed, return to the editable option.
if ((e.key == 'left') || (e.key == 'right')) {
this.options.selectedIndex = 0;
}
// The change in selected option was browser behavior.
if ((this.options.selectedIndex != 0) && (this.get('changeType') == 'auto'))
{
this.options.selectedIndex = 0;
this.set('changeType', 'manual');
}
});
};
// Load the combobox behavior into the Joomla namespace when the document is ready.
window.addEvent('domready', function(){
$$('select.combobox').each(function(el){
Joomla.combobox.transform(el);
});
});
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
Object.append(Browser.Features, {
localstorage: (function() {
return ('localStorage' in window) && window.localStorage !== null;
})()
});
/**
* Tabs behavior
*
* @package Joomla!
* @subpackage JavaScript
* @since 1.5
*/
var JTabs = new Class({
Implements: [Options, Events],
options : {
display: 0,
useStorage: true,
onActive: function(title, description) {
description.setStyle('display', 'block');
title.addClass('open').removeClass('closed');
},
onBackground: function(title, description){
description.setStyle('display', 'none');
title.addClass('closed').removeClass('open');
},
titleSelector: 'dt',
descriptionSelector: 'dd'
},
initialize: function(dlist, options){
this.setOptions(options);
this.dlist = document.id(dlist);
this.titles = this.dlist.getChildren(this.options.titleSelector);
this.descriptions = this.dlist.getChildren(this.options.descriptionSelector);
this.content = new Element('div').inject(this.dlist, 'after').addClass('current');
this.storageName = 'jpanetabs_'+this.dlist.id;
if (this.options.useStorage) {
if (Browser.Features.localstorage) {
this.options.display = localStorage[this.storageName];
} else {
this.options.display = Cookie.read(this.storageName);
}
}
if (this.options.display === null || this.options.display === undefined) {
this.options.display = 0;
}
this.options.display = this.options.display.toInt().limit(0, this.titles.length-1);
for (var i = 0, l = this.titles.length; i < l; i++)
{
var title = this.titles[i];
var description = this.descriptions[i];
title.setStyle('cursor', 'pointer');
title.addEvent('click', this.display.bind(this, i));
description.inject(this.content);
}
this.display(this.options.display);
if (this.options.initialize) this.options.initialize.call(this);
},
hideAllBut: function(but) {
for (var i = 0, l = this.titles.length; i < l; i++)
{
if (i != but) this.fireEvent('onBackground', [this.titles[i], this.descriptions[i]]);
}
},
display: function(i) {
this.hideAllBut(i);
this.fireEvent('onActive', [this.titles[i], this.descriptions[i]]);
if (this.options.useStorage) {
if (Browser.Features.localstorage) {
localStorage[this.storageName] = i;
} else {
Cookie.write(this.storageName, i);
}
}
}
});
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* JCaption javascript behavior
*
* Used for displaying image captions
*
* @package Joomla
* @since 1.5
* @version 1.0
*/
var JCaption = new Class({
initialize: function(selector)
{
this.selector = selector;
var images = $$(selector);
images.each(function(image){ this.createCaption(image); }, this);
},
createCaption: function(element)
{
var caption = document.createTextNode(element.title);
var container = document.createElement("div");
var text = document.createElement("p");
var width = element.getAttribute("width");
var align = element.getAttribute("align");
if(!width) {
width = element.width;
}
//Windows fix
if (!align)
align = element.getStyle("float"); // Rest of the world fix
if (!align) // IE DOM Fix
align = element.style.styleFloat;
if (align=="" || !align) {
align="none";
}
text.appendChild(caption);
text.className = this.selector.replace('.', '_');
element.parentNode.insertBefore(container, element);
container.appendChild(element);
if (element.title != "") {
container.appendChild(text);
}
container.className = this.selector.replace('.', '_');
container.className = container.className + " " + align;
container.setAttribute("style","float:"+align);
container.style.width = width + "px";
}
});
| JavaScript |
/* Copyright Mihai Bazon, 2002, 2003 | http://dynarch.com/mishoo/
* ---------------------------------------------------------------------------
*
* The DHTML Calendar
*
* Details and latest version at:
* http://dynarch.com/mishoo/calendar.epl
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*
* This file defines helper functions for setting up the calendar. They are
* intended to help non-programmers get a working calendar on their site
* quickly. This script should not be seen as part of the calendar. It just
* shows you what one can do with the calendar, while in the same time
* providing a quick and simple method for setting it up. If you need
* exhaustive customization of the calendar creation process feel free to
* modify this code to suit your needs (this is recommended and much better
* than modifying calendar.js itself).
*/
/**
* This function "patches" an input field (or other element) to use a calendar
* widget for date selection.
*
* The "params" is a single object that can have the following properties:
*
* prop. name | description
* -------------------------------------------------------------------------------------------------
* inputField | the ID of an input field to store the date
* displayArea | the ID of a DIV or other element to show the date
* button | ID of a button or other element that will trigger the calendar
* eventName | event that will trigger the calendar, without the "on" prefix (default: "click")
* ifFormat | date format that will be stored in the input field
* daFormat | the date format that will be used to display the date in displayArea
* singleClick | (true/false) wether the calendar is in single click mode or not (default: true)
* firstDay | numeric: 0 to 6. "0" means display Sunday first, "1" means display Monday first, etc.
* align | alignment (default: "Br"); if you don't know what's this see the calendar documentation
* range | array with 2 elements. Default: [1900, 2999] -- the range of years available
* weekNumbers | (true/false) if it's true (default) the calendar will display week numbers
* flat | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
* flatCallback | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
* disableFunc | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
* onSelect | function that gets called when a date is selected. You don't _have_ to supply this (the default is generally okay)
* onClose | function that gets called when the calendar is closed. [default]
* onUpdate | function that gets called after the date is updated in the input field. Receives a reference to the calendar.
* date | the date that the calendar will be initially displayed to
* showsTime | default: false; if true the calendar will include a time selector
* timeFormat | the time format; can be "12" or "24", default is "12"
* electric | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
* step | configures the step of the years in drop-down boxes; default: 2
* position | configures the calendar absolute position; default: null
* cache | if "true" (but default: "false") it will reuse the same calendar object, where possible
* showOthers | if "true" (but default: "false") it will show days from other months too
*
* None of them is required, they all have default values. However, if you
* pass none of "inputField", "displayArea" or "button" you'll get a warning
* saying "nothing to setup".
*/
Calendar.setup = function (params) {
function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
param_default("inputField", null);
param_default("displayArea", null);
param_default("button", null);
param_default("eventName", "click");
param_default("ifFormat", "%Y/%m/%d");
param_default("daFormat", "%Y/%m/%d");
param_default("singleClick", true);
param_default("disableFunc", null);
param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
param_default("dateTooltipFunc", null);
param_default("dateText", null);
param_default("firstDay", null);
param_default("align", "Br");
param_default("range", [1900, 2999]);
param_default("weekNumbers", true);
param_default("flat", null);
param_default("flatCallback", null);
param_default("onSelect", null);
param_default("onClose", null);
param_default("onUpdate", null);
param_default("date", null);
param_default("showsTime", false);
param_default("timeFormat", "24");
param_default("electric", true);
param_default("step", 2);
param_default("position", null);
param_default("cache", false);
param_default("showOthers", false);
param_default("multiple", null);
var tmp = ["inputField", "displayArea", "button"];
for (var i in tmp) {
if (typeof params[tmp[i]] == "string") {
params[tmp[i]] = document.getElementById(params[tmp[i]]);
}
}
if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code");
return false;
}
function onSelect(cal) {
var p = cal.params;
var update = (cal.dateClicked || p.electric);
if (update && p.inputField) {
p.inputField.value = cal.date.print(p.ifFormat);
if (typeof p.inputField.onchange == "function")
p.inputField.onchange();
}
if (update && p.displayArea)
p.displayArea.innerHTML = cal.date.print(p.daFormat);
if (update && typeof p.onUpdate == "function")
p.onUpdate(cal);
if (update && p.flat) {
if (typeof p.flatCallback == "function")
p.flatCallback(cal);
}
if (update && p.singleClick && cal.dateClicked)
cal.callCloseHandler();
};
if (params.flat != null) {
if (typeof params.flat == "string")
params.flat = document.getElementById(params.flat);
if (!params.flat) {
alert("Calendar.setup:\n Flat specified but can't find parent.");
return false;
}
var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
cal.setDateToolTipHandler(params.dateTooltipFunc);
cal.showsOtherMonths = params.showOthers;
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.params = params;
cal.weekNumbers = params.weekNumbers;
cal.setRange(params.range[0], params.range[1]);
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
if (params.ifFormat) {
cal.setDateFormat(params.ifFormat);
}
if (params.inputField && typeof params.inputField.value == "string") {
cal.parseDate(params.inputField.value);
}
cal.create(params.flat);
cal.show();
return false;
}
var triggerEl = params.button || params.displayArea || params.inputField;
triggerEl["on" + params.eventName] = function() {
var dateEl = params.inputField || params.displayArea;
var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
var mustCreate = false;
var cal = window.calendar;
if (dateEl)
params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
if (!(cal && params.cache)) {
window.calendar = cal = new Calendar(params.firstDay,
params.date,
params.onSelect || onSelect,
params.onClose || function(cal) { cal.hide(); });
cal.setDateToolTipHandler(params.dateTooltipFunc);
cal.showsTime = params.showsTime;
cal.time24 = (params.timeFormat == "24");
cal.weekNumbers = params.weekNumbers;
mustCreate = true;
} else {
if (params.date)
cal.setDate(params.date);
cal.hide();
}
if (params.multiple) {
cal.multiple = {};
for (var i = params.multiple.length; --i >= 0;) {
var d = params.multiple[i];
var ds = d.print("%Y%m%d");
cal.multiple[ds] = d;
}
}
cal.showsOtherMonths = params.showOthers;
cal.yearStep = params.step;
cal.setRange(params.range[0], params.range[1]);
cal.params = params;
cal.setDateStatusHandler(params.dateStatusFunc);
cal.getDateText = params.dateText;
cal.setDateFormat(dateFmt);
if (mustCreate)
cal.create();
cal.refresh();
if (!params.position)
cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
else
cal.showAt(params.position[0], params.position[1]);
return false;
};
return cal;
};
| JavaScript |
/**
* SqueezeBox - Expandable Lightbox
*
* Allows to open various content as modal,
* centered and animated box.
*
* Dependencies: MooTools 1.4 or newer
*
* Inspired by
* ... Lokesh Dhakar - The original Lightbox v2
*
* @version 1.3
*
* @license MIT-style license
* @author Harald Kirschner <mail [at] digitarald.de>
* @author Rouven Weßling <me [at] rouvenwessling.de>
* @copyright Author
*/
var SqueezeBox = {
presets: {
onOpen: function(){},
onClose: function(){},
onUpdate: function(){},
onResize: function(){},
onMove: function(){},
onShow: function(){},
onHide: function(){},
size: {x: 600, y: 450},
sizeLoading: {x: 200, y: 150},
marginInner: {x: 20, y: 20},
marginImage: {x: 50, y: 75},
handler: false,
target: null,
closable: true,
closeBtn: true,
zIndex: 65555,
overlayOpacity: 0.7,
classWindow: '',
classOverlay: '',
overlayFx: {},
resizeFx: {},
contentFx: {},
parse: false, // 'rel'
parseSecure: false,
shadow: true,
overlay: true,
document: null,
ajaxOptions: {}
},
initialize: function(presets) {
if (this.options) return this;
this.presets = Object.merge(this.presets, presets);
this.doc = this.presets.document || document;
this.options = {};
this.setOptions(this.presets).build();
this.bound = {
window: this.reposition.bind(this, [null]),
scroll: this.checkTarget.bind(this),
close: this.close.bind(this),
key: this.onKey.bind(this)
};
this.isOpen = this.isLoading = false;
return this;
},
build: function() {
this.overlay = new Element('div', {
id: 'sbox-overlay',
'aria-hidden': 'true',
styles: { zIndex: this.options.zIndex},
tabindex: -1
});
this.win = new Element('div', {
id: 'sbox-window',
role: 'dialog',
'aria-hidden': 'true',
styles: {zIndex: this.options.zIndex + 2}
});
if (this.options.shadow) {
if (Browser.chrome
|| (Browser.safari && Browser.version >= 3)
|| (Browser.opera && Browser.version >= 10.5)
|| (Browser.firefox && Browser.version >= 3.5)
|| (Browser.ie && Browser.version >= 9)) {
this.win.addClass('shadow');
} else if (!Browser.ie6) {
var shadow = new Element('div', {'class': 'sbox-bg-wrap'}).inject(this.win);
var relay = function(e) {
this.overlay.fireEvent('click', [e]);
}.bind(this);
['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
new Element('div', {'class': 'sbox-bg sbox-bg-' + dir}).inject(shadow).addEvent('click', relay);
});
}
}
this.content = new Element('div', {id: 'sbox-content'}).inject(this.win);
this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#', role: 'button'}).inject(this.win);
this.closeBtn.setProperty('aria-controls', 'sbox-window');
this.fx = {
overlay: new Fx.Tween(this.overlay, Object.merge({
property: 'opacity',
onStart: Events.prototype.clearChain,
duration: 250,
link: 'cancel'
}, this.options.overlayFx)).set(0),
win: new Fx.Morph(this.win, Object.merge({
onStart: Events.prototype.clearChain,
unit: 'px',
duration: 750,
transition: Fx.Transitions.Quint.easeOut,
link: 'cancel',
unit: 'px'
}, this.options.resizeFx)),
content: new Fx.Tween(this.content, Object.merge({
property: 'opacity',
duration: 250,
link: 'cancel'
}, this.options.contentFx)).set(0)
};
document.id(this.doc.body).adopt(this.overlay, this.win);
},
assign: function(to, options) {
return (document.id(to) || $$(to)).addEvent('click', function() {
return !SqueezeBox.fromElement(this, options);
});
},
open: function(subject, options) {
this.initialize();
if (this.element != null) this.trash();
this.element = document.id(subject) || false;
this.setOptions(Object.merge(this.presets, options || {}));
if (this.element && this.options.parse) {
var obj = this.element.getProperty(this.options.parse);
if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
}
this.url = ((this.element) ? (this.element.get('href')) : subject) || this.options.url || '';
this.assignOptions();
var handler = handler || this.options.handler;
if (handler) return this.setContent(handler, this.parsers[handler].call(this, true));
var ret = false;
return this.parsers.some(function(parser, key) {
var content = parser.call(this);
if (content) {
ret = this.setContent(key, content);
return true;
}
return false;
}, this);
},
fromElement: function(from, options) {
return this.open(from, options);
},
assignOptions: function() {
this.overlay.addClass(this.options.classOverlay);
this.win.addClass(this.options.classWindow);
},
close: function(e) {
var stoppable = (typeOf(e) == 'domevent');
if (stoppable) e.stop();
if (!this.isOpen || (stoppable && !Function.from(this.options.closable).call(this, e))) return this;
this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
this.win.setProperty('aria-hidden', 'true');
this.fireEvent('onClose', [this.content]);
this.trash();
this.toggleListeners();
this.isOpen = false;
return this;
},
trash: function() {
this.element = this.asset = null;
this.content.empty();
this.options = {};
this.removeEvents().setOptions(this.presets).callChain();
},
onError: function() {
this.asset = null;
this.setContent('string', this.options.errorMsg || 'An error occurred');
},
setContent: function(handler, content) {
if (!this.handlers[handler]) return false;
this.content.className = 'sbox-content-' + handler;
this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
if (this.overlay.retrieve('opacity')) return this;
this.toggleOverlay(true);
this.fx.overlay.start(this.options.overlayOpacity);
return this.reposition();
},
applyContent: function(content, size) {
if (!this.isOpen && !this.applyTimer) return;
this.applyTimer = clearTimeout(this.applyTimer);
this.hideContent();
if (!content) {
this.toggleLoading(true);
} else {
if (this.isLoading) this.toggleLoading(false);
this.fireEvent('onUpdate', [this.content], 20);
}
if (content) {
if (['string', 'array'].contains(typeOf(content))) {
this.content.set('html', content);
} else if (!(content !== this.content && this.content.contains(content))) {
this.content.adopt(content);
}
}
this.callChain();
if (!this.isOpen) {
this.toggleListeners(true);
this.resize(size, true);
this.isOpen = true;
this.win.setProperty('aria-hidden', 'false');
this.fireEvent('onOpen', [this.content]);
} else {
this.resize(size);
}
},
resize: function(size, instantly) {
this.showTimer = clearTimeout(this.showTimer || null);
var box = this.doc.getSize(), scroll = this.doc.getScroll();
this.size = Object.merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size);
var parentSize = self.getSize();
if (this.size.x == parentSize.x) {
this.size.y = this.size.y - 50;
this.size.x = this.size.x - 20;
}
var to = {
width: this.size.x,
height: this.size.y,
left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt()
};
this.hideContent();
if (!instantly) {
this.fx.win.start(to).chain(this.showContent.bind(this));
} else {
this.win.setStyles(to);
this.showTimer = this.showContent.delay(50, this);
}
return this.reposition();
},
toggleListeners: function(state) {
var fn = (state) ? 'addEvent' : 'removeEvent';
this.closeBtn[fn]('click', this.bound.close);
this.overlay[fn]('click', this.bound.close);
this.doc[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll);
this.doc.getWindow()[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window);
},
toggleLoading: function(state) {
this.isLoading = state;
this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading');
if (state) {
this.win.setProperty('aria-busy', state);
this.fireEvent('onLoading', [this.win]);
}
},
toggleOverlay: function(state) {
if (this.options.overlay) {
var full = this.doc.getSize().x;
this.overlay.set('aria-hidden', (state) ? 'false' : 'true');
this.doc.body[(state) ? 'addClass' : 'removeClass']('body-overlayed');
if (state) {
this.scrollOffset = this.doc.getWindow().getSize().x - full;
} else {
this.doc.body.setStyle('margin-right', '');
}
}
},
showContent: function() {
if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]);
this.fx.content.start(1);
},
hideContent: function() {
if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]);
this.fx.content.cancel().set(0);
},
onKey: function(e) {
switch (e.key) {
case 'esc': this.close(e);
case 'up': case 'down': return false;
}
},
checkTarget: function(e) {
return e.target !== this.content && this.content.contains(e.target);
},
reposition: function() {
var size = this.doc.getSize(), scroll = this.doc.getScroll(), ssize = this.doc.getScrollSize();
var over = this.overlay.getStyles('height');
var j = parseInt(over.height);
if (ssize.y > j && size.y >= j) {
this.overlay.setStyles({
width: ssize.x + 'px',
height: ssize.y + 'px'
});
this.win.setStyles({
left: (scroll.x + (size.x - this.win.offsetWidth) / 2 - this.scrollOffset).toInt() + 'px',
top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px'
});
}
return this.fireEvent('onMove', [this.overlay, this.win]);
},
removeEvents: function(type){
if (!this.$events) return this;
if (!type) this.$events = null;
else if (this.$events[type]) this.$events[type] = null;
return this;
},
extend: function(properties) {
return Object.append(this, properties);
},
handlers: new Hash(),
parsers: new Hash()
};
SqueezeBox.extend(new Events(function(){})).extend(new Options(function(){})).extend(new Chain(function(){}));
SqueezeBox.parsers.extend({
image: function(preset) {
return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false;
},
clone: function(preset) {
if (document.id(this.options.target)) return document.id(this.options.target);
if (this.element && !this.element.parentNode) return this.element;
var bits = this.url.match(/#([\w-]+)$/);
return (bits) ? document.id(bits[1]) : (preset ? this.element : false);
},
ajax: function(preset) {
return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false;
},
iframe: function(preset) {
return (preset || this.url) ? this.url : false;
},
string: function(preset) {
return true;
}
});
SqueezeBox.handlers.extend({
image: function(url) {
var size, tmp = new Image();
this.asset = null;
tmp.onload = tmp.onabort = tmp.onerror = (function() {
tmp.onload = tmp.onabort = tmp.onerror = null;
if (!tmp.width) {
this.onError.delay(10, this);
return;
}
var box = this.doc.getSize();
box.x -= this.options.marginImage.x;
box.y -= this.options.marginImage.y;
size = {x: tmp.width, y: tmp.height};
for (var i = 2; i--;) {
if (size.x > box.x) {
size.y *= box.x / size.x;
size.x = box.x;
} else if (size.y > box.y) {
size.x *= box.y / size.y;
size.y = box.y;
}
}
size.x = size.x.toInt();
size.y = size.y.toInt();
this.asset = document.id(tmp);
tmp = null;
this.asset.width = size.x;
this.asset.height = size.y;
this.applyContent(this.asset, size);
}).bind(this);
tmp.src = url;
if (tmp && tmp.onload && tmp.complete) tmp.onload();
return (this.asset) ? [this.asset, size] : null;
},
clone: function(el) {
if (el) return el.clone();
return this.onError();
},
adopt: function(el) {
if (el) return el;
return this.onError();
},
ajax: function(url) {
var options = this.options.ajaxOptions || {};
this.asset = new Request.HTML(Object.merge({
method: 'get',
evalScripts: false
}, this.options.ajaxOptions)).addEvents({
onSuccess: function(resp) {
this.applyContent(resp);
if (options.evalScripts !== null && !options.evalScripts) Browser.exec(this.asset.response.javascript);
this.fireEvent('onAjax', [resp, this.asset]);
this.asset = null;
}.bind(this),
onFailure: this.onError.bind(this)
});
this.asset.send.delay(10, this.asset, [{url: url}]);
},
iframe: function(url) {
this.asset = new Element('iframe', Object.merge({
src: url,
frameBorder: 0,
width: this.options.size.x,
height: this.options.size.y
}, this.options.iframeOptions));
if (this.options.iframePreload) {
this.asset.addEvent('load', function() {
this.applyContent(this.asset.setStyle('display', ''));
}.bind(this));
this.asset.setStyle('display', 'none').inject(this.content);
return false;
}
return this.asset;
},
string: function(str) {
return str;
}
});
SqueezeBox.handlers.url = SqueezeBox.handlers.ajax;
SqueezeBox.parsers.url = SqueezeBox.parsers.ajax;
SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone; | JavaScript |
/*
name: Fx.ProgressBar
description: Creates a progressbar with WAI-ARIA and optional HTML5 support.
license: MIT-style
authors:
- Harald Kirschner <mail [at] digitarald [dot] de>
- Rouven Weßling <me [at] rouvenwessling [dot] de>
requires: [Core/Fx, Core/Class, Core/Element]
provides: Fx.ProgressBar
*/
Fx.ProgressBar = new Class({
Extends: Fx,
options: {
text: null,
url: null,
transition: Fx.Transitions.Circ.easeOut,
fit: true,
link: 'cancel',
html5: true
},
initialize: function(element, options) {
this.element = document.id(element);
this.parent(options);
var url = this.options.url;
this.useHtml5 = this.options.html5 && this.supportsHtml5();
if (this.useHtml5) {
this.progressElement = new Element('progress').replaces(this.element);
this.progressElement.max = 100;
this.progressElement.value = 0;
} else {
//WAI-ARIA
this.element.set('role', 'progressbar');
this.element.set('aria-valuenow', '0');
this.element.set('aria-valuemin', '0');
this.element.set('aria-valuemax', '100');
if (url) {
this.element.setStyles({
'background-image': 'url(' + url + ')',
'background-repeat': 'no-repeat'
});
}
}
if (this.options.fit && !this.useHtml5) {
url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, '');
if (url) {
var fill = new Image();
fill.onload = function() {
this.fill = fill.width;
fill = fill.onload = null;
this.set(this.now || 0);
}.bind(this);
fill.src = url;
if (!this.fill && fill.width) fill.onload();
}
} else {
this.set(0);
}
},
supportsHtml5: function () {
return 'value' in document.createElement('progress');
},
start: function(to, total) {
return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
},
set: function(to) {
this.now = to;
if (this.useHtml5) {
this.progressElement.value = to;
} else {
var css = (this.fill)
? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px')
: ((100 - to) + '%');
this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%';
this.element.set('aria-valuenow', to);
}
var text = document.id(this.options.text);
if (text) text.set('text', Math.round(to) + '%');
return this;
}
});
| JavaScript |
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* -----------------------------------------------------------
*
* The DHTML Calendar, version 1.0 "It is happening again"
*
* Details and latest version at:
* www.dynarch.com/projects/calendar
*
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*/
/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
// member variables
this.activeDiv = null;
this.currentDateEl = null;
this.getDateStatus = null;
this.getDateToolTip = null;
this.getDateText = null;
this.timeout = null;
this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;
// HTML elements
this.table = null;
this.element = null;
this.tbody = null;
this.firstdayname = null;
// Combo boxes
this.monthsCombo = null;
this.yearsCombo = null;
this.hilitedMonth = null;
this.activeMonth = null;
this.hilitedYear = null;
this.activeYear = null;
// Information
this.dateClicked = false;
// one-time initializations
if (typeof Calendar._SDN == "undefined") {
// table of short day names
if (typeof Calendar._SDN_len == "undefined")
Calendar._SDN_len = 3;
var ar = new Array();
for (var i = 8; i > 0;) {
ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
}
Calendar._SDN = ar;
// table of short month names
if (typeof Calendar._SMN_len == "undefined")
Calendar._SMN_len = 3;
ar = new Array();
for (var i = 12; i > 0;) {
ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
}
Calendar._SMN = ar;
}
};
// ** constants
/// "static", needed for event handlers.
Calendar._C = null;
/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent) );
Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );
/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
// library, at some point.
Calendar.getAbsolutePos = function(el) {
var SL = 0, ST = 0;
var is_div = /^div$/i.test(el.tagName);
if (is_div && el.scrollLeft)
SL = el.scrollLeft;
if (is_div && el.scrollTop)
ST = el.scrollTop;
var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
if (el.offsetParent) {
var tmp = this.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
Calendar.isRelated = function (el, evt) {
var related = evt.relatedTarget;
if (!related) {
var type = evt.type;
if (type == "mouseover") {
related = evt.fromElement;
} else if (type == "mouseout") {
related = evt.toElement;
}
}
while (related) {
if (related == el) {
return true;
}
related = related.parentNode;
}
return false;
};
Calendar.removeClass = function(el, className) {
if (!(el && el.className)) {
return;
}
var cls = el.className.split(" ");
var ar = new Array();
for (var i = cls.length; i > 0;) {
if (cls[--i] != className) {
ar[ar.length] = cls[i];
}
}
el.className = ar.join(" ");
};
Calendar.addClass = function(el, className) {
Calendar.removeClass(el, className);
el.className += " " + className;
};
// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
while (f.nodeType != 1 || /^div$/i.test(f.tagName))
f = f.parentNode;
return f;
};
Calendar.getTargetElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.target;
while (f.nodeType != 1)
f = f.parentNode;
return f;
};
Calendar.stopEvent = function(ev) {
ev || (ev = window.event);
if (Calendar.is_ie) {
ev.cancelBubble = true;
ev.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
return false;
};
Calendar.addEvent = function(el, evname, func) {
if (el.attachEvent) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
};
Calendar.removeEvent = function(el, evname, func) {
if (el.detachEvent) { // IE
el.detachEvent("on" + evname, func);
} else if (el.removeEventListener) { // Gecko / W3C
el.removeEventListener(evname, func, true);
} else {
el["on" + evname] = null;
}
};
Calendar.createElement = function(type, parent) {
var el = null;
if (document.createElementNS) {
// use the XHTML namespace; IE won't normally get here unless
// _they_ "fix" the DOM2 implementation.
el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
} else {
el = document.createElement(type);
}
if (typeof parent != "undefined") {
parent.appendChild(el);
}
return el;
};
// END: UTILITY FUNCTIONS
// BEGIN: CALENDAR STATIC FUNCTIONS
/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
with (Calendar) {
addEvent(el, "mouseover", dayMouseOver);
addEvent(el, "mousedown", dayMouseDown);
addEvent(el, "mouseout", dayMouseOut);
if (is_ie) {
addEvent(el, "dblclick", dayMouseDblClick);
el.setAttribute("unselectable", true);
}
}
};
Calendar.findMonth = function(el) {
if (typeof el.month != "undefined") {
return el;
} else if (typeof el.parentNode.month != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.findYear = function(el) {
if (typeof el.year != "undefined") {
return el;
} else if (typeof el.parentNode.year != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.showMonthsCombo = function () {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var mc = cal.monthsCombo;
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
if (cal.activeMonth) {
Calendar.removeClass(cal.activeMonth, "active");
}
var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
Calendar.addClass(mon, "active");
cal.activeMonth = mon;
var s = mc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var mcw = mc.offsetWidth;
if (typeof mcw == "undefined")
// Konqueror brain-dead techniques
mcw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};
Calendar.showYearsCombo = function (fwd) {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var yc = cal.yearsCombo;
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
if (cal.activeYear) {
Calendar.removeClass(cal.activeYear, "active");
}
cal.activeYear = null;
var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
var yr = yc.firstChild;
var show = false;
for (var i = 12; i > 0; --i) {
if (Y >= cal.minYear && Y <= cal.maxYear) {
yr.innerHTML = Y;
yr.year = Y;
yr.style.display = "block";
show = true;
} else {
yr.style.display = "none";
}
yr = yr.nextSibling;
Y += fwd ? cal.yearStep : -cal.yearStep;
}
if (show) {
var s = yc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var ycw = yc.offsetWidth;
if (typeof ycw == "undefined")
// Konqueror brain-dead techniques
ycw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
}
};
// event handlers
Calendar.tableMouseUp = function(ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
if (cal.timeout) {
clearTimeout(cal.timeout);
}
var el = cal.activeDiv;
if (!el) {
return false;
}
var target = Calendar.getTargetElement(ev);
ev || (ev = window.event);
Calendar.removeClass(el, "active");
if (target == el || target.parentNode == el) {
Calendar.cellClick(el, ev);
}
var mon = Calendar.findMonth(target);
var date = null;
if (mon) {
date = new Date(cal.date);
if (mon.month != date.getMonth()) {
date.setMonth(mon.month);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
} else {
var year = Calendar.findYear(target);
if (year) {
date = new Date(cal.date);
if (year.year != date.getFullYear()) {
date.setFullYear(year.year);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
}
}
with (Calendar) {
removeEvent(document, "mouseup", tableMouseUp);
removeEvent(document, "mouseover", tableMouseOver);
removeEvent(document, "mousemove", tableMouseOver);
cal._hideCombos();
_C = null;
return stopEvent(ev);
}
};
Calendar.tableMouseOver = function (ev) {
var cal = Calendar._C;
if (!cal) {
return;
}
var el = cal.activeDiv;
var target = Calendar.getTargetElement(ev);
if (target == el || target.parentNode == el) {
Calendar.addClass(el, "hilite active");
Calendar.addClass(el.parentNode, "rowhilite");
} else {
if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
Calendar.removeClass(el, "active");
Calendar.removeClass(el, "hilite");
Calendar.removeClass(el.parentNode, "rowhilite");
}
ev || (ev = window.event);
if (el.navtype == 50 && target != el) {
var pos = Calendar.getAbsolutePos(el);
var w = el.offsetWidth;
var x = ev.clientX;
var dx;
var decrease = true;
if (x > pos.x + w) {
dx = x - pos.x - w;
decrease = false;
} else
dx = pos.x - x;
if (dx < 0) dx = 0;
var range = el._range;
var current = el._current;
var count = Math.floor(dx / 10) % range.length;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
var year = Calendar.findYear(target);
if (year) {
if (year.year != cal.date.getFullYear()) {
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
Calendar.addClass(year, "hilite");
cal.hilitedYear = year;
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.tableMouseDown = function (ev) {
if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
return Calendar.stopEvent(ev);
}
};
Calendar.calDragIt = function (ev) {
var cal = Calendar._C;
if (!(cal && cal.dragging)) {
return false;
}
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posX = ev.pageX;
posY = ev.pageY;
}
cal.hideShowCovered();
var st = cal.element.style;
st.left = (posX - cal.xOffs) + "px";
st.top = (posY - cal.yOffs) + "px";
return Calendar.stopEvent(ev);
};
Calendar.calDragEnd = function (ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
cal.dragging = false;
with (Calendar) {
removeEvent(document, "mousemove", calDragIt);
removeEvent(document, "mouseup", calDragEnd);
tableMouseUp(ev);
}
cal.hideShowCovered();
};
Calendar.dayMouseDown = function(ev) {
var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};
Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
var cal = el.calendar;
if (cal && cal.getDateToolTip) {
var d = el.caldate;
window.status = d;
el.title = cal.getDateToolTip(d, d.getFullYear(), d.getMonth(), d.getDate());
}
}
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
// return stopEvent(ev);
}
};
/**
* A generic "click" handler :) handles all types of buttons defined in this
* calendar.
*/
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl && cal.multiple)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;
// a date was clicked
if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date()); // TODAY
// unless "today" was clicked, we assume no date was clicked so
// the selected handler will know not to close the calenar when
// in single-click mode.
// cal.dateClicked = (el.navtype == 0);
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {
// FIXME: this should be removed as soon as lang files get updated!
text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:
// TODAY will bring us here
if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
// END: CALENDAR STATIC FUNCTIONS
// BEGIN: CALENDAR OBJECT FUNCTIONS
/**
* This function creates the calendar inside the given parent. If _par is
* null than it creates a popup calendar inside the BODY element. If _par is
* an element, be it BODY, then it creates a non-popup calendar (still
* hidden). Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
// default parent is the document body, in which case we create
// a popup calendar.
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();
var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
div.appendChild(table);
var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;
var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};
row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;
hh("?", 1, 400).ttip = Calendar._TT["INFO"];
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}
row = Calendar.createElement("tr", thead);
row.className = "headrow";
this._nav_py = hh("«", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
this._nav_pm = hh("‹", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];
this._nav_nm = hh("›", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
this._nav_ny = hh("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
// day names
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = Calendar._TT["WK"];
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();
var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;
for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}
if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || " ";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;
(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = " ";
cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};
cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}
var tfoot = Calendar.createElement("tfoot", table);
row = Calendar.createElement("tr", tfoot);
row.className = "footrow";
cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;
div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}
div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}
this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37: // KEY left
act && Calendar.cellClick(cal._nav_pm);
break;
case 38: // KEY up
act && Calendar.cellClick(cal._nav_py);
break;
case 39: // KEY right
act && Calendar.cellClick(cal._nav_nm);
break;
case 40: // KEY down
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32: // KEY space (now)
Calendar.cellClick(cal._nav_now);
break;
case 27: // KEY esc
act && cal.callCloseHandler();
break;
case 37: // KEY left
case 38: // KEY up
case 39: // KEY right
case 40: // KEY down
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37: // KEY left
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38: // KEY up
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39: // KEY right
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40: // KEY down
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13: // KEY enter
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
/**
* (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
// calendar voodoo for computing the first day that would actually be
// displayed in the calendar, even if it's from the previous month.
// WARNING: this is magic. ;-)
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);
var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = date.getWeekNumber();
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
// PROFILE
// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};
Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};
Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};
Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
/**
* Calls _init function above for going to a certain date (but only if the
* date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
/**
* Refreshes the calendar. Useful if the "disabledHandler" function is
* dynamic, meaning that the list of disabled date can change at runtime.
* Just * call this function if you think that the list of disabled dates
* should * change.
*/
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
/**
* Allows customization of what dates are enabled. The "unaryFunction"
* parameter must be a function object that receives the date (as a JS Date
* object) and returns a boolean value. If the returned value is true then
* the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
/**
* Moves the calendar element to a different section in the DOM tree (changes
* its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {
// calls closeHandler which should hide the calendar.
window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
/** Shows the calendar. */
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
/**
* Hides the calendar. Also removes any "hilite" from the class of any TD
* element.
*/
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};
/**
* Shows the calendar at a given absolute position (beware that, depending on
* the calendar element style -- position property -- this might be relative
* to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}
// vertical alignment
switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break; // already there
}
// horizontal alignment
switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break; // already there
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_khtml_browser()", 10);
else
Calendar.continuation_for_the_khtml_browser();
};
/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
/**
* Tries to identify the date represented in a string. If successful it also
* calls this.setDate which moves the calendar to the given date.
*/
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) { // IE
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};
var tags = new Array("applet", "iframe", "select");
var el = this.element;
var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;
for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;
for (var i = ar.length; i > 0;) {
cc = ar[--i];
p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;
if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
/** Internal function. Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
/** Internal function. Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
// BEGIN: DATE OBJECT PATCHES
/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;
Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break;
case "%m":
m = parseInt(a[i], 10) - 1;
break;
case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break;
case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break;
case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break;
case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break;
case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
var ms = d.valueOf(); // GMT
d.setMonth(0);
d.setDate(4); // Thu in Week 1
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
s["%A"] = Calendar._DN[w]; // full weekday name
s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = Calendar._MN[m]; // full month name
// FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
s["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr; // hour, range 0 to 23 (24h format)
s["%l"] = ir; // hour, range 1 to 12 (12h format)
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = y; // year with the century
s["%%"] = "%"; // a literal '%' character
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });
var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}
return str;
};
Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};
// END: DATE OBJECT PATCHES
// global object that remembers the calendar
window._dynarch_popupCalendar = null;
| JavaScript |
/**
* FancyUpload - Flash meets Ajax for powerful and elegant uploads.
*
* Updated to latest 3.0 API. Hopefully 100% compat!
*
* @version 3.0
*
* @license MIT License
*
* @author Harald Kirschner <http://digitarald.de>
* @copyright Authors
*/
var FancyUpload2 = new Class({
Extends: Swiff.Uploader,
options: {
queued: 1,
// compat
limitSize: 0,
limitFiles: 0,
validateFile: Function.from(true)
},
initialize: function(status, list, options) {
this.status = document.id(status);
this.list = document.id(list);
// compat
options.fileClass = options.fileClass || FancyUpload2.File;
options.fileSizeMax = options.limitSize || options.fileSizeMax;
options.fileListMax = options.limitFiles || options.fileListMax;
options.url = options.url + '&format=json';
this.parent(options);
this.addEvents({
'load': this.render,
'select': this.onSelect,
'cancel': this.onCancel,
'start': this.onStart,
'queue': this.onQueue,
'complete': this.onComplete
});
},
render: function() {
this.overallTitle = this.status.getElement('.overall-title');
this.currentTitle = this.status.getElement('.current-title');
this.currentText = this.status.getElement('.current-text');
var progress = this.status.getElement('.overall-progress');
this.overallProgress = new Fx.ProgressBar(progress, {
text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
});
progress = this.status.getElement('.current-progress')
this.currentProgress = new Fx.ProgressBar(progress, {
text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
});
this.updateOverall();
},
onSelect: function() {
this.status.removeClass('status-browsing');
},
onCancel: function() {
this.status.removeClass('file-browsing');
},
onStart: function() {
this.status.addClass('file-uploading');
this.overallProgress.set(0);
},
onQueue: function() {
this.updateOverall();
},
onComplete: function() {
this.status.removeClass('file-uploading');
if (this.size) {
this.overallProgress.start(100);
} else {
this.overallProgress.set(0);
this.currentProgress.set(0);
}
},
updateOverall: function() {
this.overallTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_PROGRESS_OVERALL', 'Overall Progress').substitute({
total: Swiff.Uploader.formatUnit(this.size, 'b')
}));
if (!this.size) {
this.currentTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_TITLE', 'Current Title'));
this.currentText.set('html', '');
}
},
/**
* compat
*/
upload: function() {
this.start();
},
removeFile: function() {
return this.remove();
}
});
FancyUpload2.File = new Class({
Extends: Swiff.Uploader.File,
render: function() {
if (this.invalid) {
if (this.validationError) {
var msg = Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_VALIDATION_ERROR_'+this.validationError, this.validationError);
this.validationErrorMessage = msg.substitute({
name: this.name,
size: Swiff.Uploader.formatUnit(this.size, 'b'),
fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
fileListMax: this.base.options.fileListMax || 0,
fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
});
}
this.remove();
return;
}
this.addEvents({
'start': this.onStart,
'progress': this.onProgress,
'complete': this.onComplete,
'error': this.onError,
'remove': this.onRemove
});
this.info = new Element('span', {'class': 'file-info'});
this.element = new Element('li', {'class': 'file'}).adopt(
new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}),
new Element('a', {
'class': 'file-remove',
href: '#',
html: Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_REMOVE', 'Remove'),
title: Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_REMOVE_TITLE', 'Remove Title'),
events: {
click: function() {
this.remove();
return false;
}.bind(this)
}
}),
new Element('span', {'class': 'file-name', 'html': Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_FILENAME', 'Filename').substitute(this)}),
this.info
).inject(this.base.list);
},
validate: function() {
return (this.parent() && this.base.options.validateFile(this));
},
onStart: function() {
this.element.addClass('file-uploading');
this.base.currentProgress.cancel().set(0);
this.base.currentTitle.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_FILE', 'Current File').substitute(this));
},
onProgress: function() {
this.base.overallProgress.start(this.base.percentLoaded);
this.base.currentText.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_CURRENT_PROGRESS', 'Current Progress').substitute({
rate: (this.progress.rate) ? Swiff.Uploader.formatUnit(this.progress.rate, 'bps') : '- B',
bytesLoaded: Swiff.Uploader.formatUnit(this.progress.bytesLoaded, 'b'),
timeRemaining: (this.progress.timeRemaining) ? Swiff.Uploader.formatUnit(this.progress.timeRemaining, 's') : '-'
}));
this.base.currentProgress.start(this.progress.percentLoaded);
},
onComplete: function() {
this.element.removeClass('file-uploading');
this.base.currentText.set('html', Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_UPLOAD_COMPLETED', 'Upload Completed'));
this.base.currentProgress.start(100);
if (this.response.error) {
var msg = this.response.error;
this.errorMessage = msg;
var args = [this, this.errorMessage, this.response];
this.fireEvent('error', args).base.fireEvent('fileError', args);
} else {
this.base.fireEvent('fileSuccess', [this, this.response.text || '']);
}
},
onError: function() {
this.element.addClass('file-failed');
var error = Joomla.JText._('JLIB_HTML_BEHAVIOR_UPLOADER_FILE_ERROR', 'File Error').substitute(this);
this.info.set('html', '<strong>' + error + ':</strong> ' + this.errorMessage);
},
onRemove: function() {
this.element.getElements('a').setStyle('visibility', 'hidden');
this.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, this.element));
}
});
| JavaScript |
/*
---
MooTools: the javascript framework
web build:
- http://mootools.net/core/76bf47062d6c1983d66ce47ad66aa0e0
packager build:
- packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady Core/Swiff
...
*/
/*
---
name: Core
description: The heart of MooTools.
license: MIT-style license.
copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/).
authors: The MooTools production team (http://mootools.net/developers/)
inspiration:
- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
...
*/
(function(){
this.MooTools = {
version: '1.4.5',
build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0'
};
// typeOf, instanceOf
var typeOf = this.typeOf = function(item){
if (item == null) return 'null';
if (item.$family != null) return item.$family();
if (item.nodeName){
if (item.nodeType == 1) return 'element';
if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
} else if (typeof item.length == 'number'){
if (item.callee) return 'arguments';
if ('item' in item) return 'collection';
}
return typeof item;
};
var instanceOf = this.instanceOf = function(item, object){
if (item == null) return false;
var constructor = item.$constructor || item.constructor;
while (constructor){
if (constructor === object) return true;
constructor = constructor.parent;
}
/*<ltIE8>*/
if (!item.hasOwnProperty) return false;
/*</ltIE8>*/
return item instanceof object;
};
// Function overloading
var Function = this.Function;
var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
Function.prototype.overloadSetter = function(usePlural){
var self = this;
return function(a, b){
if (a == null) return this;
if (usePlural || typeof a != 'string'){
for (var k in a) self.call(this, k, a[k]);
if (enumerables) for (var i = enumerables.length; i--;){
k = enumerables[i];
if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
}
} else {
self.call(this, a, b);
}
return this;
};
};
Function.prototype.overloadGetter = function(usePlural){
var self = this;
return function(a){
var args, result;
if (typeof a != 'string') args = a;
else if (arguments.length > 1) args = arguments;
else if (usePlural) args = [a];
if (args){
result = {};
for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
} else {
result = self.call(this, a);
}
return result;
};
};
Function.prototype.extend = function(key, value){
this[key] = value;
}.overloadSetter();
Function.prototype.implement = function(key, value){
this.prototype[key] = value;
}.overloadSetter();
// From
var slice = Array.prototype.slice;
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
// hide, protect
Function.implement({
hide: function(){
this.$hidden = true;
return this;
},
protect: function(){
this.$protected = true;
return this;
}
});
// Type
var Type = this.Type = function(name, object){
if (name){
var lower = name.toLowerCase();
var typeCheck = function(item){
return (typeOf(item) == lower);
};
Type['is' + name] = typeCheck;
if (object != null){
object.prototype.$family = (function(){
return lower;
}).hide();
//<1.2compat>
object.type = typeCheck;
//</1.2compat>
}
}
if (object == null) return null;
object.extend(this);
object.$constructor = Type;
object.prototype.$constructor = object;
return object;
};
var toString = Object.prototype.toString;
Type.isEnumerable = function(item){
return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
};
var hooks = {};
var hooksOf = function(object){
var type = typeOf(object.prototype);
return hooks[type] || (hooks[type] = []);
};
var implement = function(name, method){
if (method && method.$hidden) return;
var hooks = hooksOf(this);
for (var i = 0; i < hooks.length; i++){
var hook = hooks[i];
if (typeOf(hook) == 'type') implement.call(hook, name, method);
else hook.call(this, name, method);
}
var previous = this.prototype[name];
if (previous == null || !previous.$protected) this.prototype[name] = method;
if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
return method.apply(item, slice.call(arguments, 1));
});
};
var extend = function(name, method){
if (method && method.$hidden) return;
var previous = this[name];
if (previous == null || !previous.$protected) this[name] = method;
};
Type.implement({
implement: implement.overloadSetter(),
extend: extend.overloadSetter(),
alias: function(name, existing){
implement.call(this, name, this.prototype[existing]);
}.overloadSetter(),
mirror: function(hook){
hooksOf(this).push(hook);
return this;
}
});
new Type('Type', Type);
// Default Types
var force = function(name, object, methods){
var isType = (object != Object),
prototype = object.prototype;
if (isType) object = new Type(name, object);
for (var i = 0, l = methods.length; i < l; i++){
var key = methods[i],
generic = object[key],
proto = prototype[key];
if (generic) generic.protect();
if (isType && proto) object.implement(key, proto.protect());
}
if (isType){
var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
object.forEachMethod = function(fn){
if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
fn.call(prototype, prototype[methods[i]], methods[i]);
}
for (var key in prototype) fn.call(prototype, prototype[key], key)
};
}
return force;
};
force('String', String, [
'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
])('Array', Array, [
'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
])('Number', Number, [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
])('Function', Function, [
'apply', 'call', 'bind'
])('RegExp', RegExp, [
'exec', 'test'
])('Object', Object, [
'create', 'defineProperty', 'defineProperties', 'keys',
'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
])('Date', Date, ['now']);
Object.extend = extend.overloadSetter();
Date.extend('now', function(){
return +(new Date);
});
new Type('Boolean', Boolean);
// fixes NaN returning as Number
Number.prototype.$family = function(){
return isFinite(this) ? 'number' : 'null';
}.hide();
// Number.random
Number.extend('random', function(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
});
// forEach, each
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend('forEach', function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
}
});
Object.each = Object.forEach;
Array.implement({
forEach: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if (i in this) fn.call(bind, this[i], i, this);
}
},
each: function(fn, bind){
Array.forEach(this, fn, bind);
return this;
}
});
// Array & Object cloning, Object merging and appending
var cloneOf = function(item){
switch (typeOf(item)){
case 'array': return item.clone();
case 'object': return Object.clone(item);
default: return item;
}
};
Array.implement('clone', function(){
var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
});
var mergeOne = function(source, key, current){
switch (typeOf(current)){
case 'object':
if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
else source[key] = Object.clone(current);
break;
case 'array': source[key] = current.clone(); break;
default: source[key] = current;
}
return source;
};
Object.extend({
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
clone: function(object){
var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
},
append: function(original){
for (var i = 1, l = arguments.length; i < l; i++){
var extended = arguments[i] || {};
for (var key in extended) original[key] = extended[key];
}
return original;
}
});
// Object-less types
['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
new Type(name);
});
// Unique ID
var UID = Date.now();
String.extend('uniqueID', function(){
return (UID++).toString(36);
});
//<1.2compat>
var Hash = this.Hash = new Type('Hash', function(object){
if (typeOf(object) == 'hash') object = Object.clone(object.getClean());
for (var key in object) this[key] = object[key];
return this;
});
Hash.implement({
forEach: function(fn, bind){
Object.forEach(this, fn, bind);
},
getClean: function(){
var clean = {};
for (var key in this){
if (this.hasOwnProperty(key)) clean[key] = this[key];
}
return clean;
},
getLength: function(){
var length = 0;
for (var key in this){
if (this.hasOwnProperty(key)) length++;
}
return length;
}
});
Hash.alias('each', 'forEach');
Object.type = Type.isObject;
var Native = this.Native = function(properties){
return new Type(properties.name, properties.initialize);
};
Native.type = Type.type;
Native.implement = function(objects, methods){
for (var i = 0; i < objects.length; i++) objects[i].implement(methods);
return Native;
};
var arrayType = Array.type;
Array.type = function(item){
return instanceOf(item, Array) || arrayType(item);
};
this.$A = function(item){
return Array.from(item).slice();
};
this.$arguments = function(i){
return function(){
return arguments[i];
};
};
this.$chk = function(obj){
return !!(obj || obj === 0);
};
this.$clear = function(timer){
clearTimeout(timer);
clearInterval(timer);
return null;
};
this.$defined = function(obj){
return (obj != null);
};
this.$each = function(iterable, fn, bind){
var type = typeOf(iterable);
((type == 'arguments' || type == 'collection' || type == 'array' || type == 'elements') ? Array : Object).each(iterable, fn, bind);
};
this.$empty = function(){};
this.$extend = function(original, extended){
return Object.append(original, extended);
};
this.$H = function(object){
return new Hash(object);
};
this.$merge = function(){
var args = Array.slice(arguments);
args.unshift({});
return Object.merge.apply(null, args);
};
this.$lambda = Function.from;
this.$mixin = Object.merge;
this.$random = Number.random;
this.$splat = Array.from;
this.$time = Date.now;
this.$type = function(object){
var type = typeOf(object);
if (type == 'elements') return 'array';
return (type == 'null') ? false : type;
};
this.$unlink = function(object){
switch (typeOf(object)){
case 'object': return Object.clone(object);
case 'array': return Array.clone(object);
case 'hash': return new Hash(object);
default: return object;
}
};
//</1.2compat>
})();
/*
---
name: Array
description: Contains Array Prototypes like each, contains, and erase.
license: MIT-style license.
requires: Type
provides: Array
...
*/
Array.implement({
/*<!ES5>*/
every: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
}
return true;
},
filter: function(fn, bind){
var results = [];
for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){
value = this[i];
if (fn.call(bind, value, i, this)) results.push(value);
}
return results;
},
indexOf: function(item, from){
var length = this.length >>> 0;
for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){
if (this[i] === item) return i;
}
return -1;
},
map: function(fn, bind){
var length = this.length >>> 0, results = Array(length);
for (var i = 0; i < length; i++){
if (i in this) results[i] = fn.call(bind, this[i], i, this);
}
return results;
},
some: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*</!ES5>*/
clean: function(){
return this.filter(function(item){
return item != null;
});
},
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
link: function(object){
var result = {};
for (var i = 0, l = this.length; i < l; i++){
for (var key in object){
if (object[key](this[i])){
result[key] = this[i];
delete object[key];
break;
}
}
}
return result;
},
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
append: function(array){
this.push.apply(this, array);
return this;
},
getLast: function(){
return (this.length) ? this[this.length - 1] : null;
},
getRandom: function(){
return (this.length) ? this[Number.random(0, this.length - 1)] : null;
},
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
combine: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
erase: function(item){
for (var i = this.length; i--;){
if (this[i] === item) this.splice(i, 1);
}
return this;
},
empty: function(){
this.length = 0;
return this;
},
flatten: function(){
var array = [];
for (var i = 0, l = this.length; i < l; i++){
var type = typeOf(this[i]);
if (type == 'null') continue;
array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
}
return array;
},
pick: function(){
for (var i = 0, l = this.length; i < l; i++){
if (this[i] != null) return this[i];
}
return null;
},
hexToRgb: function(array){
if (this.length != 3) return null;
var rgb = this.map(function(value){
if (value.length == 1) value += value;
return value.toInt(16);
});
return (array) ? rgb : 'rgb(' + rgb + ')';
},
rgbToHex: function(array){
if (this.length < 3) return null;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return (array) ? hex : '#' + hex.join('');
}
});
//<1.2compat>
Array.alias('extend', 'append');
var $pick = function(){
return Array.from(arguments).pick();
};
//</1.2compat>
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
license: MIT-style license.
requires: Type
provides: String
...
*/
String.implement({
test: function(regex, params){
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
contains: function(string, separator){
return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1;
},
trim: function(){
return String(this).replace(/^\s+|\s+$/g, '');
},
clean: function(){
return String(this).replace(/\s+/g, ' ').trim();
},
camelCase: function(){
return String(this).replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
hyphenate: function(){
return String(this).replace(/[A-Z]/g, function(match){
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function(){
return String(this).replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
escapeRegExp: function(){
return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base){
return parseInt(this, base || 10);
},
toFloat: function(){
return parseFloat(this);
},
hexToRgb: function(array){
var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array){
var rgb = String(this).match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp){
return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
});
/*
---
name: Number
description: Contains Number Prototypes like limit, round, times, and ceil.
license: MIT-style license.
requires: Type
provides: Number
...
*/
Number.implement({
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
round: function(precision){
precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
return Math.round(this * precision) / precision;
},
times: function(fn, bind){
for (var i = 0; i < this; i++) fn.call(bind, i, this);
},
toFloat: function(){
return parseFloat(this);
},
toInt: function(base){
return parseInt(this, base || 10);
}
});
Number.alias('each', 'times');
(function(math){
var methods = {};
math.each(function(name){
if (!Number[name]) methods[name] = function(){
return Math[name].apply(null, [this].concat(Array.from(arguments)));
};
});
Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
/*
---
name: Function
description: Contains Function Prototypes like create, bind, pass, and delay.
license: MIT-style license.
requires: Type
provides: Function
...
*/
Function.extend({
attempt: function(){
for (var i = 0, l = arguments.length; i < l; i++){
try {
return arguments[i]();
} catch (e){}
}
return null;
}
});
Function.implement({
attempt: function(args, bind){
try {
return this.apply(bind, Array.from(args));
} catch (e){}
return null;
},
/*<!ES5-bind>*/
bind: function(that){
var self = this,
args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
F = function(){};
var bound = function(){
var context = that, length = arguments.length;
if (this instanceof bound){
F.prototype = self.prototype;
context = new F;
}
var result = (!args && !length)
? self.call(context)
: self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
return context == that ? result : context;
};
return bound;
},
/*</!ES5-bind>*/
pass: function(args, bind){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
delay: function(delay, bind, args){
return setTimeout(this.pass((args == null ? [] : args), bind), delay);
},
periodical: function(periodical, bind, args){
return setInterval(this.pass((args == null ? [] : args), bind), periodical);
}
});
//<1.2compat>
delete Function.prototype.bind;
Function.implement({
create: function(options){
var self = this;
options = options || {};
return function(event){
var args = options.arguments;
args = (args != null) ? Array.from(args) : Array.slice(arguments, (options.event) ? 1 : 0);
if (options.event) args = [event || window.event].extend(args);
var returns = function(){
return self.apply(options.bind || null, args);
};
if (options.delay) return setTimeout(returns, options.delay);
if (options.periodical) return setInterval(returns, options.periodical);
if (options.attempt) return Function.attempt(returns);
return returns();
};
},
bind: function(bind, args){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
bindWithEvent: function(bind, args){
var self = this;
if (args != null) args = Array.from(args);
return function(event){
return self.apply(bind, (args == null) ? arguments : [event].concat(args));
};
},
run: function(args, bind){
return this.apply(bind, Array.from(args));
}
});
if (Object.create == Function.prototype.create) Object.create = null;
var $try = Function.attempt;
//</1.2compat>
/*
---
name: Object
description: Object generic methods
license: MIT-style license.
requires: Type
provides: [Object, Hash]
...
*/
(function(){
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend({
subset: function(object, keys){
var results = {};
for (var i = 0, l = keys.length; i < l; i++){
var k = keys[i];
if (k in object) results[k] = object[k];
}
return results;
},
map: function(object, fn, bind){
var results = {};
for (var key in object){
if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
}
return results;
},
filter: function(object, fn, bind){
var results = {};
for (var key in object){
var value = object[key];
if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
}
return results;
},
every: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
}
return true;
},
some: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
}
return false;
},
keys: function(object){
var keys = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) keys.push(key);
}
return keys;
},
values: function(object){
var values = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) values.push(object[key]);
}
return values;
},
getLength: function(object){
return Object.keys(object).length;
},
keyOf: function(object, value){
for (var key in object){
if (hasOwnProperty.call(object, key) && object[key] === value) return key;
}
return null;
},
contains: function(object, value){
return Object.keyOf(object, value) != null;
},
toQueryString: function(object, base){
var queryString = [];
Object.each(object, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch (typeOf(value)){
case 'object': result = Object.toQueryString(value, key); break;
case 'array':
var qs = {};
value.each(function(val, i){
qs[i] = val;
});
result = Object.toQueryString(qs, key);
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != null) queryString.push(result);
});
return queryString.join('&');
}
});
})();
//<1.2compat>
Hash.implement({
has: Object.prototype.hasOwnProperty,
keyOf: function(value){
return Object.keyOf(this, value);
},
hasValue: function(value){
return Object.contains(this, value);
},
extend: function(properties){
Hash.each(properties || {}, function(value, key){
Hash.set(this, key, value);
}, this);
return this;
},
combine: function(properties){
Hash.each(properties || {}, function(value, key){
Hash.include(this, key, value);
}, this);
return this;
},
erase: function(key){
if (this.hasOwnProperty(key)) delete this[key];
return this;
},
get: function(key){
return (this.hasOwnProperty(key)) ? this[key] : null;
},
set: function(key, value){
if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
return this;
},
empty: function(){
Hash.each(this, function(value, key){
delete this[key];
}, this);
return this;
},
include: function(key, value){
if (this[key] == null) this[key] = value;
return this;
},
map: function(fn, bind){
return new Hash(Object.map(this, fn, bind));
},
filter: function(fn, bind){
return new Hash(Object.filter(this, fn, bind));
},
every: function(fn, bind){
return Object.every(this, fn, bind);
},
some: function(fn, bind){
return Object.some(this, fn, bind);
},
getKeys: function(){
return Object.keys(this);
},
getValues: function(){
return Object.values(this);
},
toQueryString: function(base){
return Object.toQueryString(this, base);
}
});
Hash.extend = Object.append;
Hash.alias({indexOf: 'keyOf', contains: 'hasValue'});
//</1.2compat>
/*
---
name: Browser
description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
license: MIT-style license.
requires: [Array, Function, Number, String]
provides: [Browser, Window, Document]
...
*/
(function(){
var document = this.document;
var window = document.window = this;
var ua = navigator.userAgent.toLowerCase(),
platform = navigator.platform.toLowerCase(),
UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
mode = UA[1] == 'ie' && document.documentMode;
var Browser = this.Browser = {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : UA[1],
version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
Platform: {
name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0]
},
Features: {
xpath: !!(document.evaluate),
air: !!(window.runtime),
query: !!(document.querySelector),
json: !!(window.JSON)
},
Plugins: {}
};
Browser[Browser.name] = true;
Browser[Browser.name + parseInt(Browser.version, 10)] = true;
Browser.Platform[Browser.Platform.name] = true;
// Request
Browser.Request = (function(){
var XMLHTTP = function(){
return new XMLHttpRequest();
};
var MSXML2 = function(){
return new ActiveXObject('MSXML2.XMLHTTP');
};
var MSXML = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
};
return Function.attempt(function(){
XMLHTTP();
return XMLHTTP;
}, function(){
MSXML2();
return MSXML2;
}, function(){
MSXML();
return MSXML;
});
})();
Browser.Features.xhr = !!(Browser.Request);
// Flash detection
var version = (Function.attempt(function(){
return navigator.plugins['Shockwave Flash'].description;
}, function(){
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
}) || '0 r0').match(/\d+/g);
Browser.Plugins.Flash = {
version: Number(version[0] || '0.' + version[1]) || 0,
build: Number(version[2]) || 0
};
// String scripts
Browser.exec = function(text){
if (!text) return text;
if (window.execScript){
window.execScript(text);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = text;
document.head.appendChild(script);
document.head.removeChild(script);
}
return text;
};
String.implement('stripScripts', function(exec){
var scripts = '';
var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
if (exec === true) Browser.exec(scripts);
else if (typeOf(exec) == 'function') exec(scripts, text);
return text;
});
// Window, Document
Browser.extend({
Document: this.Document,
Window: this.Window,
Element: this.Element,
Event: this.Event
});
this.Window = this.$constructor = new Type('Window', function(){});
this.$family = Function.from('window').hide();
Window.mirror(function(name, method){
window[name] = method;
});
this.Document = document.$constructor = new Type('Document', function(){});
document.$family = Function.from('document').hide();
Document.mirror(function(name, method){
document[name] = method;
});
document.html = document.documentElement;
if (!document.head) document.head = document.getElementsByTagName('head')[0];
if (document.execCommand) try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e){}
/*<ltIE9>*/
if (this.attachEvent && !this.addEventListener){
var unloadEvent = function(){
this.detachEvent('onunload', unloadEvent);
document.head = document.html = document.window = null;
};
this.attachEvent('onunload', unloadEvent);
}
// IE fails on collections and <select>.options (refers to <select>)
var arrayFrom = Array.from;
try {
arrayFrom(document.html.childNodes);
} catch(e){
Array.from = function(item){
if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
var i = item.length, array = new Array(i);
while (i--) array[i] = item[i];
return array;
}
return arrayFrom(item);
};
var prototype = Array.prototype,
slice = prototype.slice;
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
var method = prototype[name];
Array[name] = function(item){
return method.apply(Array.from(item), slice.call(arguments, 1));
};
});
}
/*</ltIE9>*/
//<1.2compat>
if (Browser.Platform.ios) Browser.Platform.ipod = true;
Browser.Engine = {};
var setEngine = function(name, version){
Browser.Engine.name = name;
Browser.Engine[name + version] = true;
Browser.Engine.version = version;
};
if (Browser.ie){
Browser.Engine.trident = true;
switch (Browser.version){
case 6: setEngine('trident', 4); break;
case 7: setEngine('trident', 5); break;
case 8: setEngine('trident', 6);
}
}
if (Browser.firefox){
Browser.Engine.gecko = true;
if (Browser.version >= 3) setEngine('gecko', 19);
else setEngine('gecko', 18);
}
if (Browser.safari || Browser.chrome){
Browser.Engine.webkit = true;
switch (Browser.version){
case 2: setEngine('webkit', 419); break;
case 3: setEngine('webkit', 420); break;
case 4: setEngine('webkit', 525);
}
}
if (Browser.opera){
Browser.Engine.presto = true;
if (Browser.version >= 9.6) setEngine('presto', 960);
else if (Browser.version >= 9.5) setEngine('presto', 950);
else setEngine('presto', 925);
}
if (Browser.name == 'unknown'){
switch ((ua.match(/(?:webkit|khtml|gecko)/) || [])[0]){
case 'webkit':
case 'khtml':
Browser.Engine.webkit = true;
break;
case 'gecko':
Browser.Engine.gecko = true;
}
}
this.$exec = Browser.exec;
//</1.2compat>
})();
/*
---
name: Event
description: Contains the Event Type, to make the event object cross-browser.
license: MIT-style license.
requires: [Window, Document, Array, Function, String, Object]
provides: Event
...
*/
(function() {
var _keys = {};
var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){
if (!win) win = window;
event = event || win.event;
if (event.$extended) return event;
this.event = event;
this.$extended = true;
this.shift = event.shiftKey;
this.control = event.ctrlKey;
this.alt = event.altKey;
this.meta = event.metaKey;
var type = this.type = event.type;
var target = event.target || event.srcElement;
while (target && target.nodeType == 3) target = target.parentNode;
this.target = document.id(target);
if (type.indexOf('key') == 0){
var code = this.code = (event.which || event.keyCode);
this.key = _keys[code]/*<1.3compat>*/ || Object.keyOf(Event.Keys, code)/*</1.3compat>*/;
if (type == 'keydown'){
if (code > 111 && code < 124) this.key = 'f' + (code - 111);
else if (code > 95 && code < 106) this.key = code - 96;
}
if (this.key == null) this.key = String.fromCharCode(code).toLowerCase();
} else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){
var doc = win.document;
doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
this.page = {
x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft,
y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop
};
this.client = {
x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX,
y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY
};
if (type == 'DOMMouseScroll' || type == 'mousewheel')
this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
this.rightClick = (event.which == 3 || event.button == 2);
if (type == 'mouseover' || type == 'mouseout'){
var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element'];
while (related && related.nodeType == 3) related = related.parentNode;
this.relatedTarget = document.id(related);
}
} else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){
this.rotation = event.rotation;
this.scale = event.scale;
this.targetTouches = event.targetTouches;
this.changedTouches = event.changedTouches;
var touches = this.touches = event.touches;
if (touches && touches[0]){
var touch = touches[0];
this.page = {x: touch.pageX, y: touch.pageY};
this.client = {x: touch.clientX, y: touch.clientY};
}
}
if (!this.client) this.client = {};
if (!this.page) this.page = {};
});
DOMEvent.implement({
stop: function(){
return this.preventDefault().stopPropagation();
},
stopPropagation: function(){
if (this.event.stopPropagation) this.event.stopPropagation();
else this.event.cancelBubble = true;
return this;
},
preventDefault: function(){
if (this.event.preventDefault) this.event.preventDefault();
else this.event.returnValue = false;
return this;
}
});
DOMEvent.defineKey = function(code, key){
_keys[code] = key;
return this;
};
DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true);
DOMEvent.defineKeys({
'38': 'up', '40': 'down', '37': 'left', '39': 'right',
'27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab',
'46': 'delete', '13': 'enter'
});
})();
/*<1.3compat>*/
var Event = DOMEvent;
Event.Keys = {};
/*</1.3compat>*/
/*<1.2compat>*/
Event.Keys = new Hash(Event.Keys);
/*</1.2compat>*/
/*
---
name: Class
description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
license: MIT-style license.
requires: [Array, String, Function, Number]
provides: Class
...
*/
(function(){
var Class = this.Class = new Type('Class', function(params){
if (instanceOf(params, Function)) params = {initialize: params};
var newClass = function(){
reset(this);
if (newClass.$prototyping) return this;
this.$caller = null;
var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
this.$caller = this.caller = null;
return value;
}.extend(this).implement(params);
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
return newClass;
});
var parent = function(){
if (!this.$caller) throw new Error('The method "parent" cannot be called.');
var name = this.$caller.$name,
parent = this.$caller.$owner.parent,
previous = (parent) ? parent.prototype[name] : null;
if (!previous) throw new Error('The method "' + name + '" has no parent.');
return previous.apply(this, arguments);
};
var reset = function(object){
for (var key in object){
var value = object[key];
switch (typeOf(value)){
case 'object':
var F = function(){};
F.prototype = value;
object[key] = reset(new F);
break;
case 'array': object[key] = value.clone(); break;
}
}
return object;
};
var wrap = function(self, key, method){
if (method.$origin) method = method.$origin;
var wrapper = function(){
if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
var caller = this.caller, current = this.$caller;
this.caller = current; this.$caller = wrapper;
var result = method.apply(this, arguments);
this.$caller = current; this.caller = caller;
return result;
}.extend({$owner: self, $origin: method, $name: key});
return wrapper;
};
var implement = function(key, value, retain){
if (Class.Mutators.hasOwnProperty(key)){
value = Class.Mutators[key].call(this, value);
if (value == null) return this;
}
if (typeOf(value) == 'function'){
if (value.$hidden) return this;
this.prototype[key] = (retain) ? value : wrap(this, key, value);
} else {
Object.merge(this.prototype, key, value);
}
return this;
};
var getInstance = function(klass){
klass.$prototyping = true;
var proto = new klass;
delete klass.$prototyping;
return proto;
};
Class.implement('implement', implement.overloadSetter());
Class.Mutators = {
Extends: function(parent){
this.parent = parent;
this.prototype = getInstance(parent);
},
Implements: function(items){
Array.from(items).each(function(item){
var instance = new item;
for (var key in instance) implement.call(this, key, instance[key], true);
}, this);
}
};
})();
/*
---
name: Class.Extras
description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
license: MIT-style license.
requires: Class
provides: [Class.Extras, Chain, Events, Options]
...
*/
(function(){
this.Chain = new Class({
$chain: [],
chain: function(){
this.$chain.append(Array.flatten(arguments));
return this;
},
callChain: function(){
return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
},
clearChain: function(){
this.$chain.empty();
return this;
}
});
var removeOn = function(string){
return string.replace(/^on([A-Z])/, function(full, first){
return first.toLowerCase();
});
};
this.Events = new Class({
$events: {},
addEvent: function(type, fn, internal){
type = removeOn(type);
/*<1.2compat>*/
if (fn == $empty) return this;
/*</1.2compat>*/
this.$events[type] = (this.$events[type] || []).include(fn);
if (internal) fn.internal = true;
return this;
},
addEvents: function(events){
for (var type in events) this.addEvent(type, events[type]);
return this;
},
fireEvent: function(type, args, delay){
type = removeOn(type);
var events = this.$events[type];
if (!events) return this;
args = Array.from(args);
events.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
removeEvent: function(type, fn){
type = removeOn(type);
var events = this.$events[type];
if (events && !fn.internal){
var index = events.indexOf(fn);
if (index != -1) delete events[index];
}
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
if (events) events = removeOn(events);
for (type in this.$events){
if (events && events != type) continue;
var fns = this.$events[type];
for (var i = fns.length; i--;) if (i in fns){
this.removeEvent(type, fns[i]);
}
}
return this;
}
});
this.Options = new Class({
setOptions: function(){
var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments));
if (this.addEvent) for (var option in options){
if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
this.addEvent(option, options[option]);
delete options[option];
}
return this;
}
});
})();
/*
---
name: Slick.Parser
description: Standalone CSS3 Selector parser
provides: Slick.Parser
...
*/
;(function(){
var parsed,
separatorIndex,
combinatorIndex,
reversed,
cache = {},
reverseCache = {},
reUnescape = /\\/g;
var parse = function(expression, isReversed){
if (expression == null) return null;
if (expression.Slick === true) return expression;
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
reversed = !!isReversed;
var currentCache = (reversed) ? reverseCache : cache;
if (currentCache[expression]) return currentCache[expression];
parsed = {
Slick: true,
expressions: [],
raw: expression,
reverse: function(){
return parse(this.raw, true);
}
};
separatorIndex = -1;
while (expression != (expression = expression.replace(regexp, parser)));
parsed.length = parsed.expressions.length;
return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
};
var reverseCombinator = function(combinator){
if (combinator === '!') return ' ';
else if (combinator === ' ') return '!';
else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
else return '!' + combinator;
};
var reverse = function(expression){
var expressions = expression.expressions;
for (var i = 0; i < expressions.length; i++){
var exp = expressions[i];
var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
for (var j = 0; j < exp.length; j++){
var cexp = exp[j];
if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
cexp.combinator = cexp.reverseCombinator;
delete cexp.reverseCombinator;
}
exp.reverse().push(last);
}
return expression;
};
var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
return '\\' + match;
});
};
var regexp = new RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
function parser(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
if (separator || separatorIndex === -1){
parsed.expressions[++separatorIndex] = [];
combinatorIndex = -1;
if (separator) return '';
}
if (combinator || combinatorChildren || combinatorIndex === -1){
combinator = combinator || ' ';
var currentSeparator = parsed.expressions[separatorIndex];
if (reversed && currentSeparator[combinatorIndex])
currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
}
var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
if (tagName){
currentParsed.tag = tagName.replace(reUnescape, '');
} else if (id){
currentParsed.id = id.replace(reUnescape, '');
} else if (className){
className = className.replace(reUnescape, '');
if (!currentParsed.classList) currentParsed.classList = [];
if (!currentParsed.classes) currentParsed.classes = [];
currentParsed.classList.push(className);
currentParsed.classes.push({
value: className,
regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
});
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
if (!currentParsed.pseudos) currentParsed.pseudos = [];
currentParsed.pseudos.push({
key: pseudoClass.replace(reUnescape, ''),
value: pseudoClassValue,
type: pseudoMarker.length == 1 ? 'class' : 'element'
});
} else if (attributeKey){
attributeKey = attributeKey.replace(reUnescape, '');
attributeValue = (attributeValue || '').replace(reUnescape, '');
var test, regexp;
switch (attributeOperator){
case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break;
case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break;
case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break;
case '=' : test = function(value){
return attributeValue == value;
}; break;
case '*=' : test = function(value){
return value && value.indexOf(attributeValue) > -1;
}; break;
case '!=' : test = function(value){
return attributeValue != value;
}; break;
default : test = function(value){
return !!value;
};
}
if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
return false;
};
if (!test) test = function(value){
return value && regexp.test(value);
};
if (!currentParsed.attributes) currentParsed.attributes = [];
currentParsed.attributes.push({
key: attributeKey,
operator: attributeOperator,
value: attributeValue,
test: test
});
}
return '';
};
// Slick NS
var Slick = (this.Slick || {});
Slick.parse = function(expression){
return parse(expression);
};
Slick.escapeRegExp = escapeRegExp;
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Slick.Finder
description: The new, superfast css selector engine.
provides: Slick.Finder
requires: Slick.Parser
...
*/
;(function(){
var local = {},
featuresCache = {},
toString = Object.prototype.toString;
// Feature / Bug detection
local.isNativeCode = function(fn){
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
};
local.isXML = function(document){
return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
(document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
};
local.setDocument = function(document){
// convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
var nodeType = document.nodeType;
if (nodeType == 9); // document
else if (nodeType) document = document.ownerDocument; // node
else if (document.navigator) document = document.document; // window
else return;
// check if it's the old document
if (this.document === document) return;
this.document = document;
// check if we have done feature detection on this document before
var root = document.documentElement,
rootUid = this.getUIDXML(root),
features = featuresCache[rootUid],
feature;
if (features){
for (feature in features){
this[feature] = features[feature];
}
return;
}
features = featuresCache[rootUid] = {};
features.root = root;
features.isXMLDocument = this.isXML(document);
features.brokenStarGEBTN
= features.starSelectsClosedQSA
= features.idGetsName
= features.brokenMixedCaseQSA
= features.brokenGEBCN
= features.brokenCheckedQSA
= features.brokenEmptyAttributeQSA
= features.isHTMLDocument
= features.nativeMatchesSelector
= false;
var starSelectsClosed, starSelectsComments,
brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
brokenFormAttributeGetter;
var selected, id = 'slick_uniqueid';
var testNode = document.createElement('div');
var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
testRoot.appendChild(testNode);
// on non-HTML documents innerHTML and getElementsById doesnt work properly
try {
testNode.innerHTML = '<a id="'+id+'"></a>';
features.isHTMLDocument = !!document.getElementById(id);
} catch(e){};
if (features.isHTMLDocument){
testNode.style.display = 'none';
// IE returns comment nodes for getElementsByTagName('*') for some documents
testNode.appendChild(document.createComment(''));
starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
// IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.getElementsByTagName('*');
starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
// IE returns elements with the name instead of just id for getElementsById for some documents
try {
testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
features.idGetsName = document.getElementById(id) === testNode.firstChild;
} catch(e){};
if (testNode.getElementsByClassName){
// Safari 3.2 getElementsByClassName caches results
try {
testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
testNode.getElementsByClassName('b').length;
testNode.firstChild.className = 'b';
cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
} catch(e){};
// Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
try {
testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
} catch(e){};
features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
}
if (testNode.querySelectorAll){
// IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.querySelectorAll('*');
features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
// Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
try {
testNode.innerHTML = '<a class="MiX"></a>';
features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
} catch(e){};
// Webkit and Opera dont return selected options on querySelectorAll
try {
testNode.innerHTML = '<select><option selected="selected">a</option></select>';
features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
} catch(e){};
// IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
try {
testNode.innerHTML = '<a class=""></a>';
features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
} catch(e){};
}
// IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
try {
testNode.innerHTML = '<form action="s"><input id="action"/></form>';
brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
} catch(e){};
// native matchesSelector function
features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
if (features.nativeMatchesSelector) try {
// if matchesSelector trows errors on incorrect sintaxes we can use it
features.nativeMatchesSelector.call(root, ':slick');
features.nativeMatchesSelector = null;
} catch(e){};
}
try {
root.slick_expando = 1;
delete root.slick_expando;
features.getUID = this.getUIDHTML;
} catch(e) {
features.getUID = this.getUIDXML;
}
testRoot.removeChild(testNode);
testNode = selected = testRoot = null;
// getAttribute
features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
var method = this.attributeGetters[name];
if (method) return method.call(node);
var attributeNode = node.getAttributeNode(name);
return (attributeNode) ? attributeNode.nodeValue : null;
} : function(node, name){
var method = this.attributeGetters[name];
return (method) ? method.call(node) : node.getAttribute(name);
};
// hasAttribute
features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) {
return node.hasAttribute(attribute);
} : function(node, attribute) {
node = node.getAttributeNode(attribute);
return !!(node && (node.specified || node.nodeValue));
};
// contains
// FIXME: Add specs: local.contains should be different for xml and html documents?
var nativeRootContains = root && this.isNativeCode(root.contains),
nativeDocumentContains = document && this.isNativeCode(document.contains);
features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){
return context.contains(node);
} : (nativeRootContains && !nativeDocumentContains) ? function(context, node){
// IE8 does not have .contains on document.
return context === node || ((context === document) ? document.documentElement : context).contains(node);
} : (root && root.compareDocumentPosition) ? function(context, node){
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function(context, node){
if (node) do {
if (node === context) return true;
} while ((node = node.parentNode));
return false;
};
// document order sorting
// credits to Sizzle (http://sizzlejs.com/)
features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
} : ('sourceIndex' in root) ? function(a, b){
if (!a.sourceIndex || !b.sourceIndex) return 0;
return a.sourceIndex - b.sourceIndex;
} : (document.createRange) ? function(a, b){
if (!a.ownerDocument || !b.ownerDocument) return 0;
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
} : null ;
root = null;
for (feature in features){
this[feature] = features[feature];
}
};
// Main Method
var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
qsaFailExpCache = {};
local.search = function(context, expression, append, first){
var found = this.found = (first) ? null : (append || []);
if (!context) return found;
else if (context.navigator) context = context.document; // Convert the node from a window to a document
else if (!context.nodeType) return found;
// setup
var parsed, i,
uniques = this.uniques = {},
hasOthers = !!(append && append.length),
contextIsDocument = (context.nodeType == 9);
if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
// avoid duplicating items already in the append array
if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
// expression checks
if (typeof expression == 'string'){ // expression is a string
/*<simple-selectors-override>*/
var simpleSelector = expression.match(reSimpleSelector);
simpleSelectors: if (simpleSelector) {
var symbol = simpleSelector[1],
name = simpleSelector[2],
node, nodes;
if (!symbol){
if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
nodes = context.getElementsByTagName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else if (symbol == '#'){
if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
node = context.getElementById(name);
if (!node) return found;
if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
if (first) return node || null;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else if (symbol == '.'){
if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
if (context.getElementsByClassName && !this.brokenGEBCN){
nodes = context.getElementsByClassName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else {
var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
nodes = context.getElementsByTagName('*');
for (i = 0; node = nodes[i++];){
className = node.className;
if (!(className && matchClass.test(className))) continue;
if (first) return node;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
}
}
if (hasOthers) this.sort(found);
return (first) ? null : found;
}
/*</simple-selectors-override>*/
/*<query-selector-override>*/
querySelector: if (context.querySelectorAll) {
if (!this.isHTMLDocument
|| qsaFailExpCache[expression]
//TODO: only skip when expression is actually mixed case
|| this.brokenMixedCaseQSA
|| (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
|| (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
|| (!contextIsDocument //Abort when !contextIsDocument and...
// there are multiple expressions in the selector
// since we currently only fix non-document rooted QSA for single expression selectors
&& expression.indexOf(',') > -1
)
|| Slick.disableQSA
) break querySelector;
var _expression = expression, _context = context;
if (!contextIsDocument){
// non-document rooted QSA
// credits to Andrew Dupont
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
}
try {
if (first) return context.querySelector(_expression) || null;
else nodes = context.querySelectorAll(_expression);
} catch(e) {
qsaFailExpCache[expression] = 1;
break querySelector;
} finally {
if (!contextIsDocument){
if (currentId) _context.setAttribute('id', currentId);
else _context.removeAttribute('id');
context = _context;
}
}
if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
if (hasOthers) this.sort(found);
return found;
}
/*</query-selector-override>*/
parsed = this.Slick.parse(expression);
if (!parsed.length) return found;
} else if (expression == null){ // there is no expression
return found;
} else if (expression.Slick){ // expression is a parsed Slick object
parsed = expression;
} else if (this.contains(context.documentElement || context, expression)){ // expression is a node
(found) ? found.push(expression) : found = expression;
return found;
} else { // other junk
return found;
}
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
// cache elements for the nth selectors
this.posNTH = {};
this.posNTHLast = {};
this.posNTHType = {};
this.posNTHTypeLast = {};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
// if append is null and there is only a single selector with one expression use pushArray, else use pushUID
this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
if (found == null) found = [];
// default engine
var j, m, n;
var combinator, tag, id, classList, classes, attributes, pseudos;
var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
combinator = 'combinator:' + currentBit.combinator;
if (!this[combinator]) continue search;
tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
id = currentBit.id;
classList = currentBit.classList;
classes = currentBit.classes;
attributes = currentBit.attributes;
pseudos = currentBit.pseudos;
lastBit = (j === (currentExpression.length - 1));
this.bitUniques = {};
if (lastBit){
this.uniques = uniques;
this.found = found;
} else {
this.uniques = {};
this.found = [];
}
if (j === 0){
this[combinator](context, tag, id, classes, attributes, pseudos, classList);
if (first && lastBit && found.length) break search;
} else {
if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
if (found.length) break search;
} else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
}
currentItems = this.found;
}
// should sort if there are nodes in append and if you pass multiple expressions.
if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
return (first) ? (found[0] || null) : found;
};
// Utils
local.uidx = 1;
local.uidk = 'slick-uniqueid';
local.getUIDXML = function(node){
var uid = node.getAttribute(this.uidk);
if (!uid){
uid = this.uidx++;
node.setAttribute(this.uidk, uid);
}
return uid;
};
local.getUIDHTML = function(node){
return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
};
// sort based on the setDocument documentSorter method.
local.sort = function(results){
if (!this.documentSorter) return results;
results.sort(this.documentSorter);
return results;
};
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
local.cacheNTH = {};
local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
local.parseNTHArgument = function(argument){
var parsed = argument.match(this.matchNTH);
if (!parsed) return false;
var special = parsed[2] || false;
var a = parsed[1] || 1;
if (a == '-') a = -1;
var b = +parsed[3] || 0;
parsed =
(special == 'n') ? {a: a, b: b} :
(special == 'odd') ? {a: 2, b: 1} :
(special == 'even') ? {a: 2, b: 0} : {a: 0, b: a};
return (this.cacheNTH[argument] = parsed);
};
local.createNTHPseudo = function(child, sibling, positions, ofType){
return function(node, argument){
var uid = this.getUID(node);
if (!this[positions][uid]){
var parent = node.parentNode;
if (!parent) return false;
var el = parent[child], count = 1;
if (ofType){
var nodeName = node.nodeName;
do {
if (el.nodeName != nodeName) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
} else {
do {
if (el.nodeType != 1) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
}
}
argument = argument || 'n';
var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
if (!parsed) return false;
var a = parsed.a, b = parsed.b, pos = this[positions][uid];
if (a == 0) return b == pos;
if (a > 0){
if (pos < b) return false;
} else {
if (b < pos) return false;
}
return ((pos - b) % a) == 0;
};
};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
local.pushArray = function(node, tag, id, classes, attributes, pseudos){
if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
};
local.pushUID = function(node, tag, id, classes, attributes, pseudos){
var uid = this.getUID(node);
if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
this.uniques[uid] = true;
this.found.push(node);
}
};
local.matchNode = function(node, selector){
if (this.isHTMLDocument && this.nativeMatchesSelector){
try {
return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
} catch(matchError) {}
}
var parsed = this.Slick.parse(selector);
if (!parsed) return true;
// simple (single) selectors
var expressions = parsed.expressions, simpleExpCounter = 0, i;
for (i = 0; (currentExpression = expressions[i]); i++){
if (currentExpression.length == 1){
var exp = currentExpression[0];
if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
simpleExpCounter++;
}
}
if (simpleExpCounter == parsed.length) return false;
var nodes = this.search(this.document, parsed), item;
for (i = 0; item = nodes[i++];){
if (item === node) return true;
}
return false;
};
local.matchPseudo = function(node, name, argument){
var pseudoName = 'pseudo:' + name;
if (this[pseudoName]) return this[pseudoName](node, argument);
var attribute = this.getAttribute(node, name);
return (argument) ? argument == attribute : !!attribute;
};
local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
if (tag){
var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
if (tag == '*'){
if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
} else {
if (nodeName != tag) return false;
}
}
if (id && node.getAttribute('id') != id) return false;
var i, part, cls;
if (classes) for (i = classes.length; i--;){
cls = this.getAttribute(node, 'class');
if (!(cls && classes[i].regexp.test(cls))) return false;
}
if (attributes) for (i = attributes.length; i--;){
part = attributes[i];
if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
}
if (pseudos) for (i = pseudos.length; i--;){
part = pseudos[i];
if (!this.matchPseudo(node, part.key, part.value)) return false;
}
return true;
};
var combinators = {
' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
var i, item, children;
if (this.isHTMLDocument){
getById: if (id){
item = this.document.getElementById(id);
if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
// all[id] returns all the elements with that name or id inside node
// if theres just one it will return the element, else it will be a collection
children = node.all[id];
if (!children) return;
if (!children[0]) children = [children];
for (i = 0; item = children[i++];){
var idNode = item.getAttributeNode('id');
if (idNode && idNode.nodeValue == id){
this.push(item, tag, null, classes, attributes, pseudos);
break;
}
}
return;
}
if (!item){
// if the context is in the dom we return, else we will try GEBTN, breaking the getById label
if (this.contains(this.root, node)) return;
else break getById;
} else if (this.document !== node && !this.contains(node, item)) return;
this.push(item, tag, null, classes, attributes, pseudos);
return;
}
getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
children = node.getElementsByClassName(classList.join(' '));
if (!(children && children.length)) break getByClass;
for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
return;
}
}
getByTag: {
children = node.getElementsByTagName(tag);
if (!(children && children.length)) break getByTag;
if (!this.brokenStarGEBTN) tag = null;
for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
}
},
'>': function(node, tag, id, classes, attributes, pseudos){ // direct children
if ((node = node.firstChild)) do {
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
} while ((node = node.nextSibling));
},
'+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
while ((node = node.nextSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'^': function(node, tag, id, classes, attributes, pseudos){ // first child
node = node.firstChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
}
},
'~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
while ((node = node.nextSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
},
'++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
this['combinator:+'](node, tag, id, classes, attributes, pseudos);
this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
},
'~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
this['combinator:~'](node, tag, id, classes, attributes, pseudos);
this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
},
'!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
node = node.parentNode;
if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
while ((node = node.previousSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'!^': function(node, tag, id, classes, attributes, pseudos){ // last child
node = node.lastChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
}
},
'!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
while ((node = node.previousSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
}
};
for (var c in combinators) local['combinator:' + c] = combinators[c];
var pseudos = {
/*<pseudo-selectors>*/
'empty': function(node){
var child = node.firstChild;
return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
},
'not': function(node, expression){
return !this.matchNode(node, expression);
},
'contains': function(node, text){
return (node.innerText || node.textContent || '').indexOf(text) > -1;
},
'first-child': function(node){
while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
return true;
},
'last-child': function(node){
while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
return true;
},
'only-child': function(node){
var prev = node;
while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
return true;
},
/*<nth-pseudo-selectors>*/
'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
'index': function(node, index){
return this['pseudo:nth-child'](node, '' + (index + 1));
},
'even': function(node){
return this['pseudo:nth-child'](node, '2n');
},
'odd': function(node){
return this['pseudo:nth-child'](node, '2n+1');
},
/*</nth-pseudo-selectors>*/
/*<of-type-pseudo-selectors>*/
'first-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'last-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'only-of-type': function(node){
var prev = node, nodeName = node.nodeName;
while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
return true;
},
/*</of-type-pseudo-selectors>*/
// custom pseudos
'enabled': function(node){
return !node.disabled;
},
'disabled': function(node){
return node.disabled;
},
'checked': function(node){
return node.checked || node.selected;
},
'focus': function(node){
return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
},
'root': function(node){
return (node === this.root);
},
'selected': function(node){
return node.selected;
}
/*</pseudo-selectors>*/
};
for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
// attributes methods
var attributeGetters = local.attributeGetters = {
'for': function(){
return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
},
'href': function(){
return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
},
'style': function(){
return (this.style) ? this.style.cssText : this.getAttribute('style');
},
'tabindex': function(){
var attributeNode = this.getAttributeNode('tabindex');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
},
'type': function(){
return this.getAttribute('type');
},
'maxlength': function(){
var attributeNode = this.getAttributeNode('maxLength');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
}
};
attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength;
// Slick
var Slick = local.Slick = (this.Slick || {});
Slick.version = '1.1.7';
// Slick finder
Slick.search = function(context, expression, append){
return local.search(context, expression, append);
};
Slick.find = function(context, expression){
return local.search(context, expression, null, true);
};
// Slick containment checker
Slick.contains = function(container, node){
local.setDocument(container);
return local.contains(container, node);
};
// Slick attribute getter
Slick.getAttribute = function(node, name){
local.setDocument(node);
return local.getAttribute(node, name);
};
Slick.hasAttribute = function(node, name){
local.setDocument(node);
return local.hasAttribute(node, name);
};
// Slick matcher
Slick.match = function(node, selector){
if (!(node && selector)) return false;
if (!selector || selector === node) return true;
local.setDocument(node);
return local.matchNode(node, selector);
};
// Slick attribute accessor
Slick.defineAttributeGetter = function(name, fn){
local.attributeGetters[name] = fn;
return this;
};
Slick.lookupAttributeGetter = function(name){
return local.attributeGetters[name];
};
// Slick pseudo accessor
Slick.definePseudo = function(name, fn){
local['pseudo:' + name] = function(node, argument){
return fn.call(node, argument);
};
return this;
};
Slick.lookupPseudo = function(name){
var pseudo = local['pseudo:' + name];
if (pseudo) return function(argument){
return pseudo.call(this, argument);
};
return null;
};
// Slick overrides accessor
Slick.override = function(regexp, fn){
local.override(regexp, fn);
return this;
};
Slick.isXML = local.isXML;
Slick.uidOf = function(node){
return local.getUIDHTML(node);
};
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Element
description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
license: MIT-style license.
requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder]
provides: [Element, Elements, $, $$, Iframe, Selectors]
...
*/
var Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
new Type('Element', Element).mirror(function(name){
if (Array.prototype[name]) return;
var obj = {};
obj[name] = function(){
var results = [], args = arguments, elements = true;
for (var i = 0, l = this.length; i < l; i++){
var element = this[i], result = results[i] = element[name].apply(element, args);
elements = (elements && typeOf(result) == 'element');
}
return (elements) ? new Elements(results) : results;
};
Elements.implement(obj);
});
if (!Browser.Element){
Element.parent = Object;
Element.Prototype = {
'$constructor': Element,
'$family': Function.from('element').hide()
};
Element.mirror(function(name, method){
Element.Prototype[name] = method;
});
}
Element.Constructors = {};
//<1.2compat>
Element.Constructors = new Hash;
//</1.2compat>
var IFrame = new Type('IFrame', function(){
var params = Array.link(arguments, {
properties: Type.isObject,
iframe: function(obj){
return (obj != null);
}
});
var props = params.properties || {}, iframe;
if (params.iframe) iframe = document.id(params.iframe);
var onload = props.onload || function(){};
delete props.onload;
props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
iframe = new Element(iframe || 'iframe', props);
var onLoad = function(){
onload.call(iframe.contentWindow);
};
if (window.frames[props.id]) onLoad();
else iframe.addListener('load', onLoad);
return iframe;
});
var Elements = this.Elements = function(nodes){
if (nodes && nodes.length){
var uniques = {}, node;
for (var i = 0; node = nodes[i++];){
var uid = Slick.uidOf(node);
if (!uniques[uid]){
uniques[uid] = true;
this.push(node);
}
}
}
};
Elements.prototype = {length: 0};
Elements.parent = Array;
new Type('Elements', Elements).implement({
filter: function(filter, bind){
if (!filter) return this;
return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
return item.match(filter);
} : filter, bind));
}.protect(),
push: function(){
var length = this.length;
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) this[length++] = item;
}
return (this.length = length);
}.protect(),
unshift: function(){
var items = [];
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) items.push(item);
}
return Array.prototype.unshift.apply(this, items);
}.protect(),
concat: function(){
var newElements = new Elements(this);
for (var i = 0, l = arguments.length; i < l; i++){
var item = arguments[i];
if (Type.isEnumerable(item)) newElements.append(item);
else newElements.push(item);
}
return newElements;
}.protect(),
append: function(collection){
for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
return this;
}.protect(),
empty: function(){
while (this.length) delete this[--this.length];
return this;
}.protect()
});
//<1.2compat>
Elements.alias('extend', 'append');
//</1.2compat>
(function(){
// FF, IE
var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
splice.call(object, 1, 1);
if (object[1] == 1) Elements.implement('splice', function(){
var length = this.length;
var result = splice.apply(this, arguments);
while (length >= this.length) delete this[length--];
return result;
}.protect());
Array.forEachMethod(function(method, name){
Elements.implement(name, method);
});
Array.mirror(Elements);
/*<ltIE8>*/
var createElementAcceptsHTML;
try {
createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x');
} catch (e){}
var escapeQuotes = function(html){
return ('' + html).replace(/&/g, '&').replace(/"/g, '"');
};
/*</ltIE8>*/
Document.implement({
newElement: function(tag, props){
if (props && props.checked != null) props.defaultChecked = props.checked;
/*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
if (createElementAcceptsHTML && props){
tag = '<' + tag;
if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
tag += '>';
delete props.name;
delete props.type;
}
/*</ltIE8>*/
return this.id(this.createElement(tag)).set(props);
}
});
})();
(function(){
Slick.uidOf(window);
Slick.uidOf(document);
Document.implement({
newTextNode: function(text){
return this.createTextNode(text);
},
getDocument: function(){
return this;
},
getWindow: function(){
return this.window;
},
id: (function(){
var types = {
string: function(id, nocash, doc){
id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
return (id) ? types.element(id, nocash) : null;
},
element: function(el, nocash){
Slick.uidOf(el);
if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
var fireEvent = el.fireEvent;
// wrapping needed in IE7, or else crash
el._fireEvent = function(type, event){
return fireEvent(type, event);
};
Object.append(el, Element.Prototype);
}
return el;
},
object: function(obj, nocash, doc){
if (obj.toElement) return types.element(obj.toElement(doc), nocash);
return null;
}
};
types.textnode = types.whitespace = types.window = types.document = function(zero){
return zero;
};
return function(el, nocash, doc){
if (el && el.$family && el.uniqueNumber) return el;
var type = typeOf(el);
return (types[type]) ? types[type](el, nocash, doc || document) : null;
};
})()
});
if (window.$ == null) Window.implement('$', function(el, nc){
return document.id(el, nc, this.document);
});
Window.implement({
getDocument: function(){
return this.document;
},
getWindow: function(){
return this;
}
});
[Document, Element].invoke('implement', {
getElements: function(expression){
return Slick.search(this, expression, new Elements);
},
getElement: function(expression){
return document.id(Slick.find(this, expression));
}
});
var contains = {contains: function(element){
return Slick.contains(this, element);
}};
if (!document.contains) Document.implement(contains);
if (!document.createElement('div').contains) Element.implement(contains);
//<1.2compat>
Element.implement('hasChild', function(element){
return this !== element && this.contains(element);
});
(function(search, find, match){
this.Selectors = {};
var pseudos = this.Selectors.Pseudo = new Hash();
var addSlickPseudos = function(){
for (var name in pseudos) if (pseudos.hasOwnProperty(name)){
Slick.definePseudo(name, pseudos[name]);
delete pseudos[name];
}
};
Slick.search = function(context, expression, append){
addSlickPseudos();
return search.call(this, context, expression, append);
};
Slick.find = function(context, expression){
addSlickPseudos();
return find.call(this, context, expression);
};
Slick.match = function(node, selector){
addSlickPseudos();
return match.call(this, node, selector);
};
})(Slick.search, Slick.find, Slick.match);
//</1.2compat>
// tree walking
var injectCombinator = function(expression, combinator){
if (!expression) return combinator;
expression = Object.clone(Slick.parse(expression));
var expressions = expression.expressions;
for (var i = expressions.length; i--;)
expressions[i][0].combinator = combinator;
return expression;
};
Object.forEach({
getNext: '~',
getPrevious: '!~',
getParent: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElement(injectCombinator(expression, combinator));
});
});
Object.forEach({
getAllNext: '~',
getAllPrevious: '!~',
getSiblings: '~~',
getChildren: '>',
getParents: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElements(injectCombinator(expression, combinator));
});
});
Element.implement({
getFirst: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
},
getLast: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
},
getWindow: function(){
return this.ownerDocument.window;
},
getDocument: function(){
return this.ownerDocument;
},
getElementById: function(id){
return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
},
match: function(expression){
return !expression || Slick.match(this, expression);
}
});
//<1.2compat>
if (window.$$ == null) Window.implement('$$', function(selector){
var elements = new Elements;
if (arguments.length == 1 && typeof selector == 'string') return Slick.search(this.document, selector, elements);
var args = Array.flatten(arguments);
for (var i = 0, l = args.length; i < l; i++){
var item = args[i];
switch (typeOf(item)){
case 'element': elements.push(item); break;
case 'string': Slick.search(this.document, item, elements);
}
}
return elements;
});
//</1.2compat>
if (window.$$ == null) Window.implement('$$', function(selector){
if (arguments.length == 1){
if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
else if (Type.isEnumerable(selector)) return new Elements(selector);
}
return new Elements(arguments);
});
// Inserters
var inserters = {
before: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element);
},
after: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element.nextSibling);
},
bottom: function(context, element){
element.appendChild(context);
},
top: function(context, element){
element.insertBefore(context, element.firstChild);
}
};
inserters.inside = inserters.bottom;
//<1.2compat>
Object.each(inserters, function(inserter, where){
where = where.capitalize();
var methods = {};
methods['inject' + where] = function(el){
inserter(this, document.id(el, true));
return this;
};
methods['grab' + where] = function(el){
inserter(document.id(el, true), this);
return this;
};
Element.implement(methods);
});
//</1.2compat>
// getProperty / setProperty
var propertyGetters = {}, propertySetters = {};
// properties
var properties = {};
Array.forEach([
'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan',
'frameBorder', 'rowSpan', 'tabIndex', 'useMap'
], function(property){
properties[property.toLowerCase()] = property;
});
properties.html = 'innerHTML';
properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
Object.forEach(properties, function(real, key){
propertySetters[key] = function(node, value){
node[real] = value;
};
propertyGetters[key] = function(node){
return node[real];
};
});
// Booleans
var bools = [
'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked',
'disabled', 'readOnly', 'multiple', 'selected', 'noresize',
'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay',
'loop'
];
var booleans = {};
Array.forEach(bools, function(bool){
var lower = bool.toLowerCase();
booleans[lower] = bool;
propertySetters[lower] = function(node, value){
node[bool] = !!value;
};
propertyGetters[lower] = function(node){
return !!node[bool];
};
});
// Special cases
Object.append(propertySetters, {
'class': function(node, value){
('className' in node) ? node.className = (value || '') : node.setAttribute('class', value);
},
'for': function(node, value){
('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value);
},
'style': function(node, value){
(node.style) ? node.style.cssText = value : node.setAttribute('style', value);
},
'value': function(node, value){
node.value = (value != null) ? value : '';
}
});
propertyGetters['class'] = function(node){
return ('className' in node) ? node.className || null : node.getAttribute('class');
};
/* <webkit> */
var el = document.createElement('button');
// IE sets type as readonly and throws
try { el.type = 'button'; } catch(e){}
if (el.type != 'button') propertySetters.type = function(node, value){
node.setAttribute('type', value);
};
el = null;
/* </webkit> */
/*<IE>*/
var input = document.createElement('input');
input.value = 't';
input.type = 'submit';
if (input.value != 't') propertySetters.type = function(node, type){
var value = node.value;
node.type = type;
node.value = value;
};
input = null;
/*</IE>*/
/* getProperty, setProperty */
/* <ltIE9> */
var pollutesGetAttribute = (function(div){
div.random = 'attribute';
return (div.getAttribute('random') == 'attribute');
})(document.createElement('div'));
/* <ltIE9> */
Element.implement({
setProperty: function(name, value){
var setter = propertySetters[name.toLowerCase()];
if (setter){
setter(this, value);
} else {
/* <ltIE9> */
if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {});
/* </ltIE9> */
if (value == null){
this.removeAttribute(name);
/* <ltIE9> */
if (pollutesGetAttribute) delete attributeWhiteList[name];
/* </ltIE9> */
} else {
this.setAttribute(name, '' + value);
/* <ltIE9> */
if (pollutesGetAttribute) attributeWhiteList[name] = true;
/* </ltIE9> */
}
}
return this;
},
setProperties: function(attributes){
for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
return this;
},
getProperty: function(name){
var getter = propertyGetters[name.toLowerCase()];
if (getter) return getter(this);
/* <ltIE9> */
if (pollutesGetAttribute){
var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {});
if (!attr) return null;
if (attr.expando && !attributeWhiteList[name]){
var outer = this.outerHTML;
// segment by the opening tag and find mention of attribute name
if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null;
attributeWhiteList[name] = true;
}
}
/* </ltIE9> */
var result = Slick.getAttribute(this, name);
return (!result && !Slick.hasAttribute(this, name)) ? null : result;
},
getProperties: function(){
var args = Array.from(arguments);
return args.map(this.getProperty, this).associate(args);
},
removeProperty: function(name){
return this.setProperty(name, null);
},
removeProperties: function(){
Array.each(arguments, this.removeProperty, this);
return this;
},
set: function(prop, value){
var property = Element.Properties[prop];
(property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
}.overloadSetter(),
get: function(prop){
var property = Element.Properties[prop];
return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
}.overloadGetter(),
erase: function(prop){
var property = Element.Properties[prop];
(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
return this;
},
hasClass: function(className){
return this.className.clean().contains(className, ' ');
},
addClass: function(className){
if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
return this;
},
removeClass: function(className){
this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
return this;
},
toggleClass: function(className, force){
if (force == null) force = !this.hasClass(className);
return (force) ? this.addClass(className) : this.removeClass(className);
},
adopt: function(){
var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
if (length > 1) parent = fragment = document.createDocumentFragment();
for (var i = 0; i < length; i++){
var element = document.id(elements[i], true);
if (element) parent.appendChild(element);
}
if (fragment) this.appendChild(fragment);
return this;
},
appendText: function(text, where){
return this.grab(this.getDocument().newTextNode(text), where);
},
grab: function(el, where){
inserters[where || 'bottom'](document.id(el, true), this);
return this;
},
inject: function(el, where){
inserters[where || 'bottom'](this, document.id(el, true));
return this;
},
replaces: function(el){
el = document.id(el, true);
el.parentNode.replaceChild(this, el);
return this;
},
wraps: function(el, where){
el = document.id(el, true);
return this.replaces(el).grab(el, where);
},
getSelected: function(){
this.selectedIndex; // Safari 3.2.1
return new Elements(Array.from(this.options).filter(function(option){
return option.selected;
}));
},
toQueryString: function(){
var queryString = [];
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
});
});
return queryString.join('&');
}
});
var collected = {}, storage = {};
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
var clean = function(item){
var uid = item.uniqueNumber;
if (item.removeEvents) item.removeEvents();
if (item.clearAttributes) item.clearAttributes();
if (uid != null){
delete collected[uid];
delete storage[uid];
}
return item;
};
var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
Element.implement({
destroy: function(){
var children = clean(this).getElementsByTagName('*');
Array.each(children, clean);
Element.dispose(this);
return null;
},
empty: function(){
Array.from(this.childNodes).each(Element.dispose);
return this;
},
dispose: function(){
return (this.parentNode) ? this.parentNode.removeChild(this) : this;
},
clone: function(contents, keepid){
contents = contents !== false;
var clone = this.cloneNode(contents), ce = [clone], te = [this], i;
if (contents){
ce.append(Array.from(clone.getElementsByTagName('*')));
te.append(Array.from(this.getElementsByTagName('*')));
}
for (i = ce.length; i--;){
var node = ce[i], element = te[i];
if (!keepid) node.removeAttribute('id');
/*<ltIE9>*/
if (node.clearAttributes){
node.clearAttributes();
node.mergeAttributes(element);
node.removeAttribute('uniqueNumber');
if (node.options){
var no = node.options, eo = element.options;
for (var j = no.length; j--;) no[j].selected = eo[j].selected;
}
}
/*</ltIE9>*/
var prop = formProps[element.tagName.toLowerCase()];
if (prop && element[prop]) node[prop] = element[prop];
}
/*<ltIE9>*/
if (Browser.ie){
var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
}
/*</ltIE9>*/
return document.id(clone);
}
});
[Element, Window, Document].invoke('implement', {
addListener: function(type, fn){
if (type == 'unload'){
var old = fn, self = this;
fn = function(){
self.removeListener('unload', fn);
old();
};
} else {
collected[Slick.uidOf(this)] = this;
}
if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
else this.detachEvent('on' + type, fn);
return this;
},
retrieve: function(property, dflt){
var storage = get(Slick.uidOf(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get(Slick.uidOf(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get(Slick.uidOf(this));
delete storage[property];
return this;
}
});
/*<ltIE9>*/
if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){
Object.each(collected, clean);
if (window.CollectGarbage) CollectGarbage();
});
/*</ltIE9>*/
Element.Properties = {};
//<1.2compat>
Element.Properties = new Hash;
//</1.2compat>
Element.Properties.style = {
set: function(style){
this.style.cssText = style;
},
get: function(){
return this.style.cssText;
},
erase: function(){
this.style.cssText = '';
}
};
Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
Element.Properties.html = {
set: function(html){
if (html == null) html = '';
else if (typeOf(html) == 'array') html = html.join('');
this.innerHTML = html;
},
erase: function(){
this.innerHTML = '';
}
};
/*<ltIE9>*/
// technique by jdbarlett - http://jdbartlett.com/innershiv/
var div = document.createElement('div');
div.innerHTML = '<nav></nav>';
var supportsHTML5Elements = (div.childNodes.length == 1);
if (!supportsHTML5Elements){
var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '),
fragment = document.createDocumentFragment(), l = tags.length;
while (l--) fragment.createElement(tags[l]);
}
div = null;
/*</ltIE9>*/
/*<IE>*/
var supportsTableInnerHTML = Function.attempt(function(){
var table = document.createElement('table');
table.innerHTML = '<tr><td></td></tr>';
return true;
});
/*<ltFF4>*/
var tr = document.createElement('tr'), html = '<td></td>';
tr.innerHTML = html;
var supportsTRInnerHTML = (tr.innerHTML == html);
tr = null;
/*</ltFF4>*/
if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){
Element.Properties.html.set = (function(set){
var translations = {
table: [1, '<table>', '</table>'],
select: [1, '<select>', '</select>'],
tbody: [2, '<table><tbody>', '</tbody></table>'],
tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.thead = translations.tfoot = translations.tbody;
return function(html){
var wrap = translations[this.get('tag')];
if (!wrap && !supportsHTML5Elements) wrap = [0, '', ''];
if (!wrap) return set.call(this, html);
var level = wrap[0], wrapper = document.createElement('div'), target = wrapper;
if (!supportsHTML5Elements) fragment.appendChild(wrapper);
wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join('');
while (level--) target = target.firstChild;
this.empty().adopt(target.childNodes);
if (!supportsHTML5Elements) fragment.removeChild(wrapper);
wrapper = null;
};
})(Element.Properties.html.set);
}
/*</IE>*/
/*<ltIE9>*/
var testForm = document.createElement('form');
testForm.innerHTML = '<select><option>s</option></select>';
if (testForm.firstChild.value != 's') Element.Properties.value = {
set: function(value){
var tag = this.get('tag');
if (tag != 'select') return this.setProperty('value', value);
var options = this.getElements('option');
for (var i = 0; i < options.length; i++){
var option = options[i],
attr = option.getAttributeNode('value'),
optionValue = (attr && attr.specified) ? option.value : option.get('text');
if (optionValue == value) return option.selected = true;
}
},
get: function(){
var option = this, tag = option.get('tag');
if (tag != 'select' && tag != 'option') return this.getProperty('value');
if (tag == 'select' && !(option = option.getSelected()[0])) return '';
var attr = option.getAttributeNode('value');
return (attr && attr.specified) ? option.value : option.get('text');
}
};
testForm = null;
/*</ltIE9>*/
/*<IE>*/
if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = {
set: function(id){
this.id = this.getAttributeNode('id').value = id;
},
get: function(){
return this.id || null;
},
erase: function(){
this.id = this.getAttributeNode('id').value = '';
}
};
/*</IE>*/
})();
/*
---
name: Element.Style
description: Contains methods for interacting with the styles of Elements in a fashionable way.
license: MIT-style license.
requires: Element
provides: Element.Style
...
*/
(function(){
var html = document.html;
//<ltIE9>
// Check for oldIE, which does not remove styles when they're set to null
var el = document.createElement('div');
el.style.color = 'red';
el.style.color = null;
var doesNotRemoveStyles = el.style.color == 'red';
el = null;
//</ltIE9>
Element.Properties.styles = {set: function(styles){
this.setStyles(styles);
}};
var hasOpacity = (html.style.opacity != null),
hasFilter = (html.style.filter != null),
reAlpha = /alpha\(opacity=([\d.]+)\)/i;
var setVisibility = function(element, opacity){
element.store('$opacity', opacity);
element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden';
};
var setOpacity = (hasOpacity ? function(element, opacity){
element.style.opacity = opacity;
} : (hasFilter ? function(element, opacity){
var style = element.style;
if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1;
if (opacity == null || opacity == 1) opacity = '';
else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')';
var filter = style.filter || element.getComputedStyle('filter') || '';
style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity;
if (!style.filter) style.removeAttribute('filter');
} : setVisibility));
var getOpacity = (hasOpacity ? function(element){
var opacity = element.style.opacity || element.getComputedStyle('opacity');
return (opacity == '') ? 1 : opacity.toFloat();
} : (hasFilter ? function(element){
var filter = (element.style.filter || element.getComputedStyle('filter')),
opacity;
if (filter) opacity = filter.match(reAlpha);
return (opacity == null || filter == null) ? 1 : (opacity[1] / 100);
} : function(element){
var opacity = element.retrieve('$opacity');
if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1);
return opacity;
}));
var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat';
Element.implement({
getComputedStyle: function(property){
if (this.currentStyle) return this.currentStyle[property.camelCase()];
var defaultView = Element.getDocument(this).defaultView,
computed = defaultView ? defaultView.getComputedStyle(this, null) : null;
return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
},
setStyle: function(property, value){
if (property == 'opacity'){
if (value != null) value = parseFloat(value);
setOpacity(this, value);
return this;
}
property = (property == 'float' ? floatName : property).camelCase();
if (typeOf(value) != 'string'){
var map = (Element.Styles[property] || '@').split(' ');
value = Array.from(value).map(function(val, i){
if (!map[i]) return '';
return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
}).join(' ');
} else if (value == String(Number(value))){
value = Math.round(value);
}
this.style[property] = value;
//<ltIE9>
if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){
this.style.removeAttribute(property);
}
//</ltIE9>
return this;
},
getStyle: function(property){
if (property == 'opacity') return getOpacity(this);
property = (property == 'float' ? floatName : property).camelCase();
var result = this.style[property];
if (!result || property == 'zIndex'){
result = [];
for (var style in Element.ShortStyles){
if (property != style) continue;
for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
return result.join(' ');
}
result = this.getComputedStyle(property);
}
if (result){
result = String(result);
var color = result.match(/rgba?\([\d\s,]+\)/);
if (color) result = result.replace(color[0], color[0].rgbToHex());
}
if (Browser.opera || Browser.ie){
if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){
var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
values.each(function(value){
size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
}, this);
return this['offset' + property.capitalize()] - size + 'px';
}
if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){
return '0px';
}
}
return result;
},
setStyles: function(styles){
for (var style in styles) this.setStyle(style, styles[style]);
return this;
},
getStyles: function(){
var result = {};
Array.flatten(arguments).each(function(key){
result[key] = this.getStyle(key);
}, this);
return result;
}
});
Element.Styles = {
left: '@px', top: '@px', bottom: '@px', right: '@px',
width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
};
//<1.3compat>
Element.implement({
setOpacity: function(value){
setOpacity(this, value);
return this;
},
getOpacity: function(){
return getOpacity(this);
}
});
Element.Properties.opacity = {
set: function(opacity){
setOpacity(this, opacity);
setVisibility(this, opacity);
},
get: function(){
return getOpacity(this);
}
};
//</1.3compat>
//<1.2compat>
Element.Styles = new Hash(Element.Styles);
//</1.2compat>
Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
var Short = Element.ShortStyles;
var All = Element.Styles;
['margin', 'padding'].each(function(style){
var sd = style + direction;
Short[style][sd] = All[sd] = '@px';
});
var bd = 'border' + direction;
Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
Short[bd] = {};
Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
});
})();
/*
---
name: Element.Event
description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary.
license: MIT-style license.
requires: [Element, Event]
provides: Element.Event
...
*/
(function(){
Element.Properties.events = {set: function(events){
this.addEvents(events);
}};
[Element, Window, Document].invoke('implement', {
addEvent: function(type, fn){
var events = this.retrieve('events', {});
if (!events[type]) events[type] = {keys: [], values: []};
if (events[type].keys.contains(fn)) return this;
events[type].keys.push(fn);
var realType = type,
custom = Element.Events[type],
condition = fn,
self = this;
if (custom){
if (custom.onAdd) custom.onAdd.call(this, fn, type);
if (custom.condition){
condition = function(event){
if (custom.condition.call(this, event, type)) return fn.call(this, event);
return true;
};
}
if (custom.base) realType = Function.from(custom.base).call(this, type);
}
var defn = function(){
return fn.call(self);
};
var nativeEvent = Element.NativeEvents[realType];
if (nativeEvent){
if (nativeEvent == 2){
defn = function(event){
event = new DOMEvent(event, self.getWindow());
if (condition.call(self, event) === false) event.stop();
};
}
this.addListener(realType, defn, arguments[2]);
}
events[type].values.push(defn);
return this;
},
removeEvent: function(type, fn){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
var list = events[type];
var index = list.keys.indexOf(fn);
if (index == -1) return this;
var value = list.values[index];
delete list.keys[index];
delete list.values[index];
var custom = Element.Events[type];
if (custom){
if (custom.onRemove) custom.onRemove.call(this, fn, type);
if (custom.base) type = Function.from(custom.base).call(this, type);
}
return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this;
},
addEvents: function(events){
for (var event in events) this.addEvent(event, events[event]);
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
var attached = this.retrieve('events');
if (!attached) return this;
if (!events){
for (type in attached) this.removeEvents(type);
this.eliminate('events');
} else if (attached[events]){
attached[events].keys.each(function(fn){
this.removeEvent(events, fn);
}, this);
delete attached[events];
}
return this;
},
fireEvent: function(type, args, delay){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
args = Array.from(args);
events[type].keys.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
cloneEvents: function(from, type){
from = document.id(from);
var events = from.retrieve('events');
if (!events) return this;
if (!type){
for (var eventType in events) this.cloneEvents(from, eventType);
} else if (events[type]){
events[type].keys.each(function(fn){
this.addEvent(type, fn);
}, this);
}
return this;
}
});
Element.NativeEvents = {
click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
keydown: 2, keypress: 2, keyup: 2, //keyboard
orientationchange: 2, // mobile
touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch
gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture
focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements
load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
error: 1, abort: 1, scroll: 1 //misc
};
Element.Events = {mousewheel: {
base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel'
}};
if ('onmouseenter' in document.documentElement){
Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2;
} else {
var check = function(event){
var related = event.relatedTarget;
if (related == null) return true;
if (!related) return false;
return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related));
};
Element.Events.mouseenter = {
base: 'mouseover',
condition: check
};
Element.Events.mouseleave = {
base: 'mouseout',
condition: check
};
}
/*<ltIE9>*/
if (!window.addEventListener){
Element.NativeEvents.propertychange = 2;
Element.Events.change = {
base: function(){
var type = this.type;
return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change'
},
condition: function(event){
return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked);
}
}
}
/*</ltIE9>*/
//<1.2compat>
Element.Events = new Hash(Element.Events);
//</1.2compat>
})();
/*
---
name: Element.Delegation
description: Extends the Element native object to include the delegate method for more efficient event management.
license: MIT-style license.
requires: [Element.Event]
provides: [Element.Delegation]
...
*/
(function(){
var eventListenerSupport = !!window.addEventListener;
Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2;
var bubbleUp = function(self, match, fn, event, target){
while (target && target != self){
if (match(target, event)) return fn.call(target, event, target);
target = document.id(target.parentNode);
}
};
var map = {
mouseenter: {
base: 'mouseover'
},
mouseleave: {
base: 'mouseout'
},
focus: {
base: 'focus' + (eventListenerSupport ? '' : 'in'),
capture: true
},
blur: {
base: eventListenerSupport ? 'blur' : 'focusout',
capture: true
}
};
/*<ltIE9>*/
var _key = '$delegation:';
var formObserver = function(type){
return {
base: 'focusin',
remove: function(self, uid){
var list = self.retrieve(_key + type + 'listeners', {})[uid];
if (list && list.forms) for (var i = list.forms.length; i--;){
list.forms[i].removeEvent(type, list.fns[i]);
}
},
listen: function(self, match, fn, event, target, uid){
var form = (target.get('tag') == 'form') ? target : event.target.getParent('form');
if (!form) return;
var listeners = self.retrieve(_key + type + 'listeners', {}),
listener = listeners[uid] || {forms: [], fns: []},
forms = listener.forms, fns = listener.fns;
if (forms.indexOf(form) != -1) return;
forms.push(form);
var _fn = function(event){
bubbleUp(self, match, fn, event, target);
};
form.addEvent(type, _fn);
fns.push(_fn);
listeners[uid] = listener;
self.store(_key + type + 'listeners', listeners);
}
};
};
var inputObserver = function(type){
return {
base: 'focusin',
listen: function(self, match, fn, event, target){
var events = {blur: function(){
this.removeEvents(events);
}};
events[type] = function(event){
bubbleUp(self, match, fn, event, target);
};
event.target.addEvents(events);
}
};
};
if (!eventListenerSupport) Object.append(map, {
submit: formObserver('submit'),
reset: formObserver('reset'),
change: inputObserver('change'),
select: inputObserver('select')
});
/*</ltIE9>*/
var proto = Element.prototype,
addEvent = proto.addEvent,
removeEvent = proto.removeEvent;
var relay = function(old, method){
return function(type, fn, useCapture){
if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture);
var parsed = Slick.parse(type).expressions[0][0];
if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture);
var newType = parsed.tag;
parsed.pseudos.slice(1).each(function(pseudo){
newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : '');
});
old.call(this, type, fn);
return method.call(this, newType, parsed.pseudos[0].value, fn);
};
};
var delegation = {
addEvent: function(type, match, fn){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (stored) for (var _uid in stored){
if (stored[_uid].fn == fn && stored[_uid].match == match) return this;
}
var _type = type, _match = match, _fn = fn, _map = map[type] || {};
type = _map.base || _type;
match = function(target){
return Slick.match(target, _match);
};
var elementEvent = Element.Events[_type];
if (elementEvent && elementEvent.condition){
var __match = match, condition = elementEvent.condition;
match = function(target, event){
return __match(target, event) && condition.call(target, event, type);
};
}
var self = this, uid = String.uniqueID();
var delegator = _map.listen ? function(event, target){
if (!target && event && event.target) target = event.target;
if (target) _map.listen(self, match, fn, event, target, uid);
} : function(event, target){
if (!target && event && event.target) target = event.target;
if (target) bubbleUp(self, match, fn, event, target);
};
if (!stored) stored = {};
stored[uid] = {
match: _match,
fn: _fn,
delegator: delegator
};
storage[_type] = stored;
return addEvent.call(this, type, delegator, _map.capture);
},
removeEvent: function(type, match, fn, _uid){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (!stored) return this;
if (_uid){
var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {};
type = _map.base || _type;
if (_map.remove) _map.remove(this, _uid);
delete stored[_uid];
storage[_type] = stored;
return removeEvent.call(this, type, delegator);
}
var __uid, s;
if (fn) for (__uid in stored){
s = stored[__uid];
if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid);
} else for (__uid in stored){
s = stored[__uid];
if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid);
}
return this;
}
};
[Element, Window, Document].invoke('implement', {
addEvent: relay(addEvent, delegation.addEvent),
removeEvent: relay(removeEvent, delegation.removeEvent)
});
})();
/*
---
name: Element.Dimensions
description: Contains methods to work with size, scroll, or positioning of Elements and the window object.
license: MIT-style license.
credits:
- Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
- Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
requires: [Element, Element.Style]
provides: [Element.Dimensions]
...
*/
(function(){
var element = document.createElement('div'),
child = document.createElement('div');
element.style.height = '0';
element.appendChild(child);
var brokenOffsetParent = (child.offsetParent === element);
element = child = null;
var isOffset = function(el){
return styleString(el, 'position') != 'static' || isBody(el);
};
var isOffsetStatic = function(el){
return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
};
Element.implement({
scrollTo: function(x, y){
if (isBody(this)){
this.getWindow().scrollTo(x, y);
} else {
this.scrollLeft = x;
this.scrollTop = y;
}
return this;
},
getSize: function(){
if (isBody(this)) return this.getWindow().getSize();
return {x: this.offsetWidth, y: this.offsetHeight};
},
getScrollSize: function(){
if (isBody(this)) return this.getWindow().getScrollSize();
return {x: this.scrollWidth, y: this.scrollHeight};
},
getScroll: function(){
if (isBody(this)) return this.getWindow().getScroll();
return {x: this.scrollLeft, y: this.scrollTop};
},
getScrolls: function(){
var element = this.parentNode, position = {x: 0, y: 0};
while (element && !isBody(element)){
position.x += element.scrollLeft;
position.y += element.scrollTop;
element = element.parentNode;
}
return position;
},
getOffsetParent: brokenOffsetParent ? function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset;
while ((element = element.parentNode)){
if (isOffsetCheck(element)) return element;
}
return null;
} : function(){
var element = this;
if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
try {
return element.offsetParent;
} catch(e) {}
return null;
},
getOffsets: function(){
if (this.getBoundingClientRect && !Browser.Platform.ios){
var bound = this.getBoundingClientRect(),
html = document.id(this.getDocument().documentElement),
htmlScroll = html.getScroll(),
elemScrolls = this.getScrolls(),
isFixed = (styleString(this, 'position') == 'fixed');
return {
x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
};
}
var element = this, position = {x: 0, y: 0};
if (isBody(this)) return position;
while (element && !isBody(element)){
position.x += element.offsetLeft;
position.y += element.offsetTop;
if (Browser.firefox){
if (!borderBox(element)){
position.x += leftBorder(element);
position.y += topBorder(element);
}
var parent = element.parentNode;
if (parent && styleString(parent, 'overflow') != 'visible'){
position.x += leftBorder(parent);
position.y += topBorder(parent);
}
} else if (element != this && Browser.safari){
position.x += leftBorder(element);
position.y += topBorder(element);
}
element = element.offsetParent;
}
if (Browser.firefox && !borderBox(this)){
position.x -= leftBorder(this);
position.y -= topBorder(this);
}
return position;
},
getPosition: function(relative){
var offset = this.getOffsets(),
scroll = this.getScrolls();
var position = {
x: offset.x - scroll.x,
y: offset.y - scroll.y
};
if (relative && (relative = document.id(relative))){
var relativePosition = relative.getPosition();
return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)};
}
return position;
},
getCoordinates: function(element){
if (isBody(this)) return this.getWindow().getCoordinates();
var position = this.getPosition(element),
size = this.getSize();
var obj = {
left: position.x,
top: position.y,
width: size.x,
height: size.y
};
obj.right = obj.left + obj.width;
obj.bottom = obj.top + obj.height;
return obj;
},
computePosition: function(obj){
return {
left: obj.x - styleNumber(this, 'margin-left'),
top: obj.y - styleNumber(this, 'margin-top')
};
},
setPosition: function(obj){
return this.setStyles(this.computePosition(obj));
}
});
[Document, Window].invoke('implement', {
getSize: function(){
var doc = getCompatElement(this);
return {x: doc.clientWidth, y: doc.clientHeight};
},
getScroll: function(){
var win = this.getWindow(), doc = getCompatElement(this);
return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
},
getScrollSize: function(){
var doc = getCompatElement(this),
min = this.getSize(),
body = this.getDocument().body;
return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)};
},
getPosition: function(){
return {x: 0, y: 0};
},
getCoordinates: function(){
var size = this.getSize();
return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
}
});
// private methods
var styleString = Element.getComputedStyle;
function styleNumber(element, style){
return styleString(element, style).toInt() || 0;
}
function borderBox(element){
return styleString(element, '-moz-box-sizing') == 'border-box';
}
function topBorder(element){
return styleNumber(element, 'border-top-width');
}
function leftBorder(element){
return styleNumber(element, 'border-left-width');
}
function isBody(element){
return (/^(?:body|html)$/i).test(element.tagName);
}
function getCompatElement(element){
var doc = element.getDocument();
return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
}
})();
//aliases
Element.alias({position: 'setPosition'}); //compatability
[Window, Document, Element].invoke('implement', {
getHeight: function(){
return this.getSize().y;
},
getWidth: function(){
return this.getSize().x;
},
getScrollTop: function(){
return this.getScroll().y;
},
getScrollLeft: function(){
return this.getScroll().x;
},
getScrollHeight: function(){
return this.getScrollSize().y;
},
getScrollWidth: function(){
return this.getScrollSize().x;
},
getTop: function(){
return this.getPosition().y;
},
getLeft: function(){
return this.getPosition().x;
}
});
/*
---
name: Fx
description: Contains the basic animation logic to be extended by all other Fx Classes.
license: MIT-style license.
requires: [Chain, Events, Options]
provides: Fx
...
*/
(function(){
var Fx = this.Fx = new Class({
Implements: [Chain, Events, Options],
options: {
/*
onStart: nil,
onCancel: nil,
onComplete: nil,
*/
fps: 60,
unit: false,
duration: 500,
frames: null,
frameSkip: true,
link: 'ignore'
},
initialize: function(options){
this.subject = this.subject || this;
this.setOptions(options);
},
getTransition: function(){
return function(p){
return -(Math.cos(Math.PI * p) - 1) / 2;
};
},
step: function(now){
if (this.options.frameSkip){
var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval;
this.time = now;
this.frame += frames;
} else {
this.frame++;
}
if (this.frame < this.frames){
var delta = this.transition(this.frame / this.frames);
this.set(this.compute(this.from, this.to, delta));
} else {
this.frame = this.frames;
this.set(this.compute(this.from, this.to, 1));
this.stop();
}
},
set: function(now){
return now;
},
compute: function(from, to, delta){
return Fx.compute(from, to, delta);
},
check: function(){
if (!this.isRunning()) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
start: function(from, to){
if (!this.check(from, to)) return this;
this.from = from;
this.to = to;
this.frame = (this.options.frameSkip) ? 0 : -1;
this.time = null;
this.transition = this.getTransition();
var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration;
this.duration = Fx.Durations[duration] || duration.toInt();
this.frameInterval = 1000 / fps;
this.frames = frames || Math.round(this.duration / this.frameInterval);
this.fireEvent('start', this.subject);
pushInstance.call(this, fps);
return this;
},
stop: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
if (this.frames == this.frame){
this.fireEvent('complete', this.subject);
if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
} else {
this.fireEvent('stop', this.subject);
}
}
return this;
},
cancel: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
this.frame = this.frames;
this.fireEvent('cancel', this.subject).clearChain();
}
return this;
},
pause: function(){
if (this.isRunning()){
this.time = null;
pullInstance.call(this, this.options.fps);
}
return this;
},
resume: function(){
if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps);
return this;
},
isRunning: function(){
var list = instances[this.options.fps];
return list && list.contains(this);
}
});
Fx.compute = function(from, to, delta){
return (to - from) * delta + from;
};
Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};
// global timers
var instances = {}, timers = {};
var loop = function(){
var now = Date.now();
for (var i = this.length; i--;){
var instance = this[i];
if (instance) instance.step(now);
}
};
var pushInstance = function(fps){
var list = instances[fps] || (instances[fps] = []);
list.push(this);
if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list);
};
var pullInstance = function(fps){
var list = instances[fps];
if (list){
list.erase(this);
if (!list.length && timers[fps]){
delete instances[fps];
timers[fps] = clearInterval(timers[fps]);
}
}
};
})();
/*
---
name: Fx.CSS
description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.
license: MIT-style license.
requires: [Fx, Element.Style]
provides: Fx.CSS
...
*/
Fx.CSS = new Class({
Extends: Fx,
//prepares the base from/to object
prepare: function(element, property, values){
values = Array.from(values);
var from = values[0], to = values[1];
if (to == null){
to = from;
from = element.getStyle(property);
var unit = this.options.unit;
// adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299
if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){
element.setStyle(property, to + unit);
var value = element.getComputedStyle(property);
// IE and Opera support pixelLeft or pixelWidth
if (!(/px$/.test(value))){
value = element.style[('pixel-' + property).camelCase()];
if (value == null){
// adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
var left = element.style.left;
element.style.left = to + unit;
value = element.style.pixelLeft;
element.style.left = left;
}
}
from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0);
element.setStyle(property, from + unit);
}
}
return {from: this.parse(from), to: this.parse(to)};
},
//parses a value into an array
parse: function(value){
value = Function.from(value)();
value = (typeof value == 'string') ? value.split(' ') : Array.from(value);
return value.map(function(val){
val = String(val);
var found = false;
Object.each(Fx.CSS.Parsers, function(parser, key){
if (found) return;
var parsed = parser.parse(val);
if (parsed || parsed === 0) found = {value: parsed, parser: parser};
});
found = found || {value: val, parser: Fx.CSS.Parsers.String};
return found;
});
},
//computes by a from and to prepared objects, using their parsers.
compute: function(from, to, delta){
var computed = [];
(Math.min(from.length, to.length)).times(function(i){
computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
});
computed.$family = Function.from('fx:css:value');
return computed;
},
//serves the value as settable
serve: function(value, unit){
if (typeOf(value) != 'fx:css:value') value = this.parse(value);
var returned = [];
value.each(function(bit){
returned = returned.concat(bit.parser.serve(bit.value, unit));
});
return returned;
},
//renders the change to an element
render: function(element, property, value, unit){
element.setStyle(property, this.serve(value, unit));
},
//searches inside the page css to find the values for a selector
search: function(selector){
if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$');
Array.each(document.styleSheets, function(sheet, j){
var href = sheet.href;
if (href && href.contains('://') && !href.contains(document.domain)) return;
var rules = sheet.rules || sheet.cssRules;
Array.each(rules, function(rule, i){
if (!rule.style) return;
var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
return m.toLowerCase();
}) : null;
if (!selectorText || !selectorTest.test(selectorText)) return;
Object.each(Element.Styles, function(value, style){
if (!rule.style[style] || Element.ShortStyles[style]) return;
value = String(rule.style[style]);
to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value;
});
});
});
return Fx.CSS.Cache[selector] = to;
}
});
Fx.CSS.Cache = {};
Fx.CSS.Parsers = {
Color: {
parse: function(value){
if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
},
compute: function(from, to, delta){
return from.map(function(value, i){
return Math.round(Fx.compute(from[i], to[i], delta));
});
},
serve: function(value){
return value.map(Number);
}
},
Number: {
parse: parseFloat,
compute: Fx.compute,
serve: function(value, unit){
return (unit) ? value + unit : value;
}
},
String: {
parse: Function.from(false),
compute: function(zero, one){
return one;
},
serve: function(zero){
return zero;
}
}
};
//<1.2compat>
Fx.CSS.Parsers = new Hash(Fx.CSS.Parsers);
//</1.2compat>
/*
---
name: Fx.Tween
description: Formerly Fx.Style, effect to transition any CSS property for an element.
license: MIT-style license.
requires: Fx.CSS
provides: [Fx.Tween, Element.fade, Element.highlight]
...
*/
Fx.Tween = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(property, now){
if (arguments.length == 1){
now = property;
property = this.property || this.options.property;
}
this.render(this.element, property, now, this.options.unit);
return this;
},
start: function(property, from, to){
if (!this.check(property, from, to)) return this;
var args = Array.flatten(arguments);
this.property = this.options.property || args.shift();
var parsed = this.prepare(this.element, this.property, args);
return this.parent(parsed.from, parsed.to);
}
});
Element.Properties.tween = {
set: function(options){
this.get('tween').cancel().setOptions(options);
return this;
},
get: function(){
var tween = this.retrieve('tween');
if (!tween){
tween = new Fx.Tween(this, {link: 'cancel'});
this.store('tween', tween);
}
return tween;
}
};
Element.implement({
tween: function(property, from, to){
this.get('tween').start(property, from, to);
return this;
},
fade: function(how){
var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle;
if (args[1] == null) args[1] = 'toggle';
switch (args[1]){
case 'in': method = 'start'; args[1] = 1; break;
case 'out': method = 'start'; args[1] = 0; break;
case 'show': method = 'set'; args[1] = 1; break;
case 'hide': method = 'set'; args[1] = 0; break;
case 'toggle':
var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1);
method = 'start';
args[1] = flag ? 0 : 1;
this.store('fade:flag', !flag);
toggle = true;
break;
default: method = 'start';
}
if (!toggle) this.eliminate('fade:flag');
fade[method].apply(fade, args);
var to = args[args.length - 1];
if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible');
else fade.chain(function(){
this.element.setStyle('visibility', 'hidden');
this.callChain();
});
return this;
},
highlight: function(start, end){
if (!end){
end = this.retrieve('highlight:original', this.getStyle('background-color'));
end = (end == 'transparent') ? '#fff' : end;
}
var tween = this.get('tween');
tween.start('background-color', start || '#ffff88', end).chain(function(){
this.setStyle('background-color', this.retrieve('highlight:original'));
tween.callChain();
}.bind(this));
return this;
}
});
/*
---
name: Fx.Morph
description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.
license: MIT-style license.
requires: Fx.CSS
provides: Fx.Morph
...
*/
Fx.Morph = new Class({
Extends: Fx.CSS,
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
},
set: function(now){
if (typeof now == 'string') now = this.search(now);
for (var p in now) this.render(this.element, p, now[p], this.options.unit);
return this;
},
compute: function(from, to, delta){
var now = {};
for (var p in from) now[p] = this.parent(from[p], to[p], delta);
return now;
},
start: function(properties){
if (!this.check(properties)) return this;
if (typeof properties == 'string') properties = this.search(properties);
var from = {}, to = {};
for (var p in properties){
var parsed = this.prepare(this.element, p, properties[p]);
from[p] = parsed.from;
to[p] = parsed.to;
}
return this.parent(from, to);
}
});
Element.Properties.morph = {
set: function(options){
this.get('morph').cancel().setOptions(options);
return this;
},
get: function(){
var morph = this.retrieve('morph');
if (!morph){
morph = new Fx.Morph(this, {link: 'cancel'});
this.store('morph', morph);
}
return morph;
}
};
Element.implement({
morph: function(props){
this.get('morph').start(props);
return this;
}
});
/*
---
name: Fx.Transitions
description: Contains a set of advanced transitions to be used with any of the Fx Classes.
license: MIT-style license.
credits:
- Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
requires: Fx
provides: Fx.Transitions
...
*/
Fx.implement({
getTransition: function(){
var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
if (typeof trans == 'string'){
var data = trans.split(':');
trans = Fx.Transitions;
trans = trans[data[0]] || trans[data[0].capitalize()];
if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
}
return trans;
}
});
Fx.Transition = function(transition, params){
params = Array.from(params);
var easeIn = function(pos){
return transition(pos, params);
};
return Object.append(easeIn, {
easeIn: easeIn,
easeOut: function(pos){
return 1 - transition(1 - pos, params);
},
easeInOut: function(pos){
return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2;
}
});
};
Fx.Transitions = {
linear: function(zero){
return zero;
}
};
//<1.2compat>
Fx.Transitions = new Hash(Fx.Transitions);
//</1.2compat>
Fx.Transitions.extend = function(transitions){
for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
};
Fx.Transitions.extend({
Pow: function(p, x){
return Math.pow(p, x && x[0] || 6);
},
Expo: function(p){
return Math.pow(2, 8 * (p - 1));
},
Circ: function(p){
return 1 - Math.sin(Math.acos(p));
},
Sine: function(p){
return 1 - Math.cos(p * Math.PI / 2);
},
Back: function(p, x){
x = x && x[0] || 1.618;
return Math.pow(p, 2) * ((x + 1) * p - x);
},
Bounce: function(p){
var value;
for (var a = 0, b = 1; 1; a += b, b /= 2){
if (p >= (7 - 4 * a) / 11){
value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
break;
}
}
return value;
},
Elastic: function(p, x){
return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3);
}
});
['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
Fx.Transitions[transition] = new Fx.Transition(function(p){
return Math.pow(p, i + 2);
});
});
/*
---
name: Request
description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
license: MIT-style license.
requires: [Object, Element, Chain, Events, Options, Browser]
provides: Request
...
*/
(function(){
var empty = function(){},
progressSupport = ('onprogress' in new Browser.Request);
var Request = this.Request = new Class({
Implements: [Chain, Events, Options],
options: {/*
onRequest: function(){},
onLoadstart: function(event, xhr){},
onProgress: function(event, xhr){},
onComplete: function(){},
onCancel: function(){},
onSuccess: function(responseText, responseXML){},
onFailure: function(xhr){},
onException: function(headerName, value){},
onTimeout: function(){},
user: '',
password: '',*/
url: '',
data: '',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
},
async: true,
format: false,
method: 'post',
link: 'ignore',
isSuccess: null,
emulation: true,
urlEncoded: true,
encoding: 'utf-8',
evalScripts: false,
evalResponse: false,
timeout: 0,
noCache: false
},
initialize: function(options){
this.xhr = new Browser.Request();
this.setOptions(options);
this.headers = this.options.headers;
},
onStateChange: function(){
var xhr = this.xhr;
if (xhr.readyState != 4 || !this.running) return;
this.running = false;
this.status = 0;
Function.attempt(function(){
var status = xhr.status;
this.status = (status == 1223) ? 204 : status;
}.bind(this));
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
clearTimeout(this.timer);
this.response = {text: this.xhr.responseText || '', xml: this.xhr.responseXML};
if (this.options.isSuccess.call(this, this.status))
this.success(this.response.text, this.response.xml);
else
this.failure();
},
isSuccess: function(){
var status = this.status;
return (status >= 200 && status < 300);
},
isRunning: function(){
return !!this.running;
},
processScripts: function(text){
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text);
return text.stripScripts(this.options.evalScripts);
},
success: function(text, xml){
this.onSuccess(this.processScripts(text), xml);
},
onSuccess: function(){
this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
},
failure: function(){
this.onFailure();
},
onFailure: function(){
this.fireEvent('complete').fireEvent('failure', this.xhr);
},
loadstart: function(event){
this.fireEvent('loadstart', [event, this.xhr]);
},
progress: function(event){
this.fireEvent('progress', [event, this.xhr]);
},
timeout: function(){
this.fireEvent('timeout', this.xhr);
},
setHeader: function(name, value){
this.headers[name] = value;
return this;
},
getHeader: function(name){
return Function.attempt(function(){
return this.xhr.getResponseHeader(name);
}.bind(this));
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
send: function(options){
if (!this.check(options)) return this;
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.running = true;
var type = typeOf(options);
if (type == 'string' || type == 'element') options = {data: options};
var old = this.options;
options = Object.append({data: old.data, url: old.url, method: old.method}, options);
var data = options.data, url = String(options.url), method = options.method.toLowerCase();
switch (typeOf(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Object.toQueryString(data);
}
if (this.options.format){
var format = 'format=' + this.options.format;
data = (data) ? format + '&' + data : format;
}
if (this.options.emulation && !['get', 'post'].contains(method)){
var _method = '_method=' + method;
data = (data) ? _method + '&' + data : _method;
method = 'post';
}
if (this.options.urlEncoded && ['post', 'put'].contains(method)){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
}
if (!url) url = document.location.pathname;
var trimPosition = url.lastIndexOf('/');
if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
if (this.options.noCache)
url += (url.contains('?') ? '&' : '?') + String.uniqueID();
if (data && method == 'get'){
url += (url.contains('?') ? '&' : '?') + data;
data = null;
}
var xhr = this.xhr;
if (progressSupport){
xhr.onloadstart = this.loadstart.bind(this);
xhr.onprogress = this.progress.bind(this);
}
xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;
xhr.onreadystatechange = this.onStateChange.bind(this);
Object.each(this.headers, function(value, key){
try {
xhr.setRequestHeader(key, value);
} catch (e){
this.fireEvent('exception', [key, value]);
}
}, this);
this.fireEvent('request');
xhr.send(data);
if (!this.options.async) this.onStateChange();
else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
var xhr = this.xhr;
xhr.abort();
clearTimeout(this.timer);
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
this.xhr = new Browser.Request();
this.fireEvent('cancel');
return this;
}
});
var methods = {};
['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
methods[method] = function(data){
var object = {
method: method
};
if (data != null) object.data = data;
return this.send(object);
};
});
Request.implement(methods);
Element.Properties.send = {
set: function(options){
var send = this.get('send').cancel();
send.setOptions(options);
return this;
},
get: function(){
var send = this.retrieve('send');
if (!send){
send = new Request({
data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
});
this.store('send', send);
}
return send;
}
};
Element.implement({
send: function(url){
var sender = this.get('send');
sender.send({data: this, url: url || sender.options.url});
return this;
}
});
})();
/*
---
name: Request.HTML
description: Extends the basic Request Class with additional methods for interacting with HTML responses.
license: MIT-style license.
requires: [Element, Request]
provides: Request.HTML
...
*/
Request.HTML = new Class({
Extends: Request,
options: {
update: false,
append: false,
evalScripts: true,
filter: false,
headers: {
Accept: 'text/html, application/xml, text/xml, */*'
}
},
success: function(text){
var options = this.options, response = this.response;
response.html = text.stripScripts(function(script){
response.javascript = script;
});
var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
if (match) response.html = match[1];
var temp = new Element('div').set('html', response.html);
response.tree = temp.childNodes;
response.elements = temp.getElements(options.filter || '*');
if (options.filter) response.tree = response.elements;
if (options.update){
var update = document.id(options.update).empty();
if (options.filter) update.adopt(response.elements);
else update.set('html', response.html);
} else if (options.append){
var append = document.id(options.append);
if (options.filter) response.elements.reverse().inject(append);
else append.adopt(temp.getChildren());
}
if (options.evalScripts) Browser.exec(response.javascript);
this.onSuccess(response.tree, response.elements, response.html, response.javascript);
}
});
Element.Properties.load = {
set: function(options){
var load = this.get('load').cancel();
load.setOptions(options);
return this;
},
get: function(){
var load = this.retrieve('load');
if (!load){
load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'});
this.store('load', load);
}
return load;
}
};
Element.implement({
load: function(){
this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString}));
return this;
}
});
/*
---
name: JSON
description: JSON encoder and decoder.
license: MIT-style license.
SeeAlso: <http://www.json.org/>
requires: [Array, String, Number, Function]
provides: JSON
...
*/
if (typeof JSON == 'undefined') this.JSON = {};
//<1.2compat>
JSON = new Hash({
stringify: JSON.stringify,
parse: JSON.parse
});
//</1.2compat>
(function(){
var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
var escape = function(chr){
return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
};
JSON.validate = function(string){
string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(string);
};
JSON.encode = JSON.stringify ? function(obj){
return JSON.stringify(obj);
} : function(obj){
if (obj && obj.toJSON) obj = obj.toJSON();
switch (typeOf(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
case 'array':
return '[' + obj.map(JSON.encode).clean() + ']';
case 'object': case 'hash':
var string = [];
Object.each(obj, function(value, key){
var json = JSON.encode(value);
if (json) string.push(JSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return '' + obj;
case 'null': return 'null';
}
return null;
};
JSON.decode = function(string, secure){
if (!string || typeOf(string) != 'string') return null;
if (secure || JSON.secure){
if (JSON.parse) return JSON.parse(string);
if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
}
return eval('(' + string + ')');
};
})();
/*
---
name: Request.JSON
description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
license: MIT-style license.
requires: [Request, JSON]
provides: Request.JSON
...
*/
Request.JSON = new Class({
Extends: Request,
options: {
/*onError: function(text, error){},*/
secure: true
},
initialize: function(options){
this.parent(options);
Object.append(this.headers, {
'Accept': 'application/json',
'X-Request': 'JSON'
});
},
success: function(text){
var json;
try {
json = this.response.json = JSON.decode(text, this.options.secure);
} catch (error){
this.fireEvent('error', [text, error]);
return;
}
if (json == null) this.onFailure();
else this.onSuccess(json, text);
}
});
/*
---
name: Cookie
description: Class for creating, reading, and deleting browser Cookies.
license: MIT-style license.
credits:
- Based on the functions by Peter-Paul Koch (http://quirksmode.org).
requires: [Options, Browser]
provides: Cookie
...
*/
var Cookie = new Class({
Implements: Options,
options: {
path: '/',
domain: false,
duration: false,
secure: false,
document: document,
encode: true
},
initialize: function(key, options){
this.key = key;
this.setOptions(options);
},
write: function(value){
if (this.options.encode) value = encodeURIComponent(value);
if (this.options.domain) value += '; domain=' + this.options.domain;
if (this.options.path) value += '; path=' + this.options.path;
if (this.options.duration){
var date = new Date();
date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
value += '; expires=' + date.toGMTString();
}
if (this.options.secure) value += '; secure';
this.options.document.cookie = this.key + '=' + value;
return this;
},
read: function(){
var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
return (value) ? decodeURIComponent(value[1]) : null;
},
dispose: function(){
new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write('');
return this;
}
});
Cookie.write = function(key, value, options){
return new Cookie(key, options).write(value);
};
Cookie.read = function(key){
return new Cookie(key).read();
};
Cookie.dispose = function(key, options){
return new Cookie(key, options).dispose();
};
/*
---
name: DOMReady
description: Contains the custom event domready.
license: MIT-style license.
requires: [Browser, Element, Element.Event]
provides: [DOMReady, DomReady]
...
*/
(function(window, document){
var ready,
loaded,
checks = [],
shouldPoll,
timer,
testElement = document.createElement('div');
var domready = function(){
clearTimeout(timer);
if (ready) return;
Browser.loaded = ready = true;
document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
document.fireEvent('domready');
window.fireEvent('domready');
};
var check = function(){
for (var i = checks.length; i--;) if (checks[i]()){
domready();
return true;
}
return false;
};
var poll = function(){
clearTimeout(timer);
if (!check()) timer = setTimeout(poll, 10);
};
document.addListener('DOMContentLoaded', domready);
/*<ltIE8>*/
// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
// testElement.doScroll() throws when the DOM is not ready, only in the top window
var doScrollWorks = function(){
try {
testElement.doScroll();
return true;
} catch (e){}
return false;
};
// If doScroll works already, it can't be used to determine domready
// e.g. in an iframe
if (testElement.doScroll && !doScrollWorks()){
checks.push(doScrollWorks);
shouldPoll = true;
}
/*</ltIE8>*/
if (document.readyState) checks.push(function(){
var state = document.readyState;
return (state == 'loaded' || state == 'complete');
});
if ('onreadystatechange' in document) document.addListener('readystatechange', check);
else shouldPoll = true;
if (shouldPoll) poll();
Element.Events.domready = {
onAdd: function(fn){
if (ready) fn.call(this);
}
};
// Make sure that domready fires before load
Element.Events.load = {
base: 'load',
onAdd: function(fn){
if (loaded && this == window) fn.call(this);
},
condition: function(){
if (this == window){
domready();
delete Element.Events.load;
}
return true;
}
};
// This is based on the custom load event
window.addEvent('load', function(){
loaded = true;
});
})(window, document);
/*
---
name: Swiff
description: Wrapper for embedding SWF movies. Supports External Interface Communication.
license: MIT-style license.
credits:
- Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject.
requires: [Options, Object, Element]
provides: Swiff
...
*/
(function(){
var Swiff = this.Swiff = new Class({
Implements: Options,
options: {
id: null,
height: 1,
width: 1,
container: null,
properties: {},
params: {
quality: 'high',
allowScriptAccess: 'always',
wMode: 'window',
swLiveConnect: true
},
callBacks: {},
vars: {}
},
toElement: function(){
return this.object;
},
initialize: function(path, options){
this.instance = 'Swiff_' + String.uniqueID();
this.setOptions(options);
options = this.options;
var id = this.id = options.id || this.instance;
var container = document.id(options.container);
Swiff.CallBacks[this.instance] = {};
var params = options.params, vars = options.vars, callBacks = options.callBacks;
var properties = Object.append({height: options.height, width: options.width}, options.properties);
var self = this;
for (var callBack in callBacks){
Swiff.CallBacks[this.instance][callBack] = (function(option){
return function(){
return option.apply(self.object, arguments);
};
})(callBacks[callBack]);
vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
}
params.flashVars = Object.toQueryString(vars);
if (Browser.ie){
properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
params.movie = path;
} else {
properties.type = 'application/x-shockwave-flash';
}
properties.data = path;
var build = '<object id="' + id + '"';
for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
build += '>';
for (var param in params){
if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
}
build += '</object>';
this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild;
},
replaces: function(element){
element = document.id(element, true);
element.parentNode.replaceChild(this.toElement(), element);
return this;
},
inject: function(element){
document.id(element, true).appendChild(this.toElement());
return this;
},
remote: function(){
return Swiff.remote.apply(Swiff, [this.toElement()].append(arguments));
}
});
Swiff.CallBacks = {};
Swiff.remote = function(obj, fn){
var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
return eval(rs);
};
})();
| JavaScript |
/*
---
script: mooRainbow.js
version: 1.3
description: MooRainbow is a ColorPicker for MooTools 1.3
license: MIT-Style
authors:
- Djamil Legato (w00fz)
- Christopher Beloch
requires: [Core/*, More/Slider, More/Drag, More/Color]
provides: [mooRainbow]
...
*/
var MooRainbow = new Class({
options: {
id: 'mooRainbow',
prefix: 'moor-',
imgPath: 'images/',
startColor: [255, 0, 0],
wheel: false,
onComplete: Class.empty,
onChange: Class.empty
},
initialize: function(el, options) {
this.element = document.id(el); if (!this.element) return;
this.setOptions(options);
this.sliderPos = 0;
this.pickerPos = {x: 0, y: 0};
this.backupColor = this.options.startColor;
this.currentColor = this.options.startColor;
this.sets = {
rgb: [],
hsb: [],
hex: []
};
this.pickerClick = this.sliderClick = false;
if (!this.layout) this.doLayout();
this.OverlayEvents();
this.sliderEvents();
this.backupEvent();
if (this.options.wheel) this.wheelEvents();
this.element.addEvent('click', function(e) { this.toggle(e); }.bind(this));
this.layout.overlay.setStyle('background-color', this.options.startColor.rgbToHex());
this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex());
this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w;
this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h;
this.manualSet(this.options.startColor);
this.pickerPos.x = this.snippet('curPos').l + this.snippet('curSize', 'int').w;
this.pickerPos.y = this.snippet('curPos').t + this.snippet('curSize', 'int').h;
this.sliderPos = this.snippet('arrPos') - this.snippet('arrSize', 'int');
if (window.khtml) this.hide();
},
toggle: function() {
this[this.visible ? 'hide' : 'show']()
},
show: function() {
this.rePosition();
this.layout.setStyle('display', 'block');
this.layout.set('aria-hidden', 'false');
this.visible = true;
},
hide: function() {
this.layout.setStyles({'display': 'none'});
this.layout.set('aria-hidden', 'true');
this.visible = false;
},
manualSet: function(color, type) {
if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb';
var rgb, hsb, hex;
if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); }
else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); }
else { hex = color; rgb = color.hexToRgb(true); hsb = rgb.rgbToHsb(); }
this.setMooRainbow(rgb);
this.autoSet(hsb);
},
autoSet: function(hsb) {
var curH = this.snippet('curSize', 'int').h;
var curW = this.snippet('curSize', 'int').w;
var oveH = this.layout.overlay.height;
var oveW = this.layout.overlay.width;
var sliH = this.layout.slider.height;
var arwH = this.snippet('arrSize', 'int');
var hue;
var posx = Math.round(((oveW * hsb[1]) / 100) - curW);
var posy = Math.round(- ((oveH * hsb[2]) / 100) + oveH - curH);
var c = Math.round(((sliH * hsb[0]) / 360)); c = (c == 360) ? 0 : c;
var position = sliH - c + this.snippet('slider') - arwH;
hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex();
this.layout.cursor.setStyles({'top': posy, 'left': posx});
this.layout.arrows.setStyle('top', position);
this.layout.overlay.setStyle('background-color', hue);
this.sliderPos = this.snippet('arrPos') - arwH;
this.pickerPos.x = this.snippet('curPos').l + curW;
this.pickerPos.y = this.snippet('curPos').t + curH;
},
setMooRainbow: function(color, type) {
if (!type || (type != 'hsb' && type != 'hex')) type = 'rgb';
var rgb, hsb, hex;
if (type == 'rgb') { rgb = color; hsb = color.rgbToHsb(); hex = color.rgbToHex(); }
else if (type == 'hsb') { hsb = color; rgb = color.hsbToRgb(); hex = rgb.rgbToHex(); }
else { hex = color; rgb = color.hexToRgb(); hsb = rgb.rgbToHsb(); }
this.sets = {
rgb: rgb,
hsb: hsb,
hex: hex
};
if (!this.pickerPos.x)
this.autoSet(hsb);
this.RedInput.value = rgb[0];
this.GreenInput.value = rgb[1];
this.BlueInput.value = rgb[2];
this.HueInput.value = hsb[0];
this.SatuInput.value = hsb[1];
this.BrighInput.value = hsb[2];
this.hexInput.value = hex;
this.currentColor = rgb;
this.chooseColor.setStyle('background-color', rgb.rgbToHex());
this.fireEvent('onChange', [this.sets, this]);
},
parseColors: function(x, y, z) {
var s = Math.round((x * 100) / this.layout.overlay.width);
var b = 100 - Math.round((y * 100) / this.layout.overlay.height);
var h = 360 - Math.round((z * 360) / this.layout.slider.height) + this.snippet('slider') - this.snippet('arrSize', 'int');
h -= this.snippet('arrSize', 'int');
h = (h >= 360) ? 0 : (h < 0) ? 0 : h;
s = (s > 100) ? 100 : (s < 0) ? 0 : s;
b = (b > 100) ? 100 : (b < 0) ? 0 : b;
return [h, s, b];
},
OverlayEvents: function() {
var lim, curH, curW, inputs;
curH = this.snippet('curSize', 'int').h;
curW = this.snippet('curSize', 'int').w;
inputs = this.arrRGB.concat(this.arrHSB, this.hexInput);
document.addEvent('click', function() {
if(this.visible) this.hide(this.layout);
}.bind(this));
inputs.each(function(el) {
el.addEvent('keydown', this.eventKeydown.bind(this, el));
el.addEvent('keyup', this.eventKeyup.bind(this, el));
}, this);
[this.element, this.layout].each(function(el) {
el.addEvents({
'click': function(e) { new Event(e).stop(); },
'keyup': function(e) {
e = new Event(e);
if(e.key == 'esc' && this.visible) this.hide(this.layout);
}.bind(this)
}, this);
}, this);
lim = {
x: [0 - curW, (this.layout.overlay.width - curW)],
y: [0 - curH, (this.layout.overlay.height - curH)]
};
this.layout.drag = new Drag(this.layout.cursor, {
onStart: this.overlayDrag.bind(this),
onDrag: this.overlayDrag.bind(this),
snap: 0
});
this.layout.overlay2.addEvent('mousedown', function(e){
e = new Event(e);
this.layout.cursor.setStyles({
'top': e.page.y - this.layout.overlay.getTop() - curH,
'left': e.page.x - this.layout.overlay.getLeft() - curW
});
this.overlayDrag.call(this);
this.layout.drag.start(e);
}.bind(this));
this.okButton.addEvent('click', function() {
if(this.currentColor == this.options.startColor) {
this.hide();
this.fireEvent('onComplete', [this.sets, this]);
}
else {
this.backupColor = this.currentColor;
this.layout.backup.setStyle('background-color', this.backupColor.rgbToHex());
this.hide();
this.fireEvent('onComplete', [this.sets, this]);
}
}.bind(this));
},
overlayDrag: function() {
var curH = this.snippet('curSize', 'int').h;
var curW = this.snippet('curSize', 'int').w;
this.pickerPos.x = this.snippet('curPos').l + curW;
this.pickerPos.y = this.snippet('curPos').t + curH;
this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb');
this.fireEvent('onChange', [this.sets, this]);
},
sliderEvents: function() {
var arwH = this.snippet('arrSize', 'int'), lim;
lim = [0 + this.snippet('slider') - arwH, this.layout.slider.height - arwH + this.snippet('slider')];
this.layout.sliderDrag = new Drag(this.layout.arrows, {
limit: {y: lim},
modifiers: {x: false},
onStart: this.sliderDrag.bind(this),
onDrag: this.sliderDrag.bind(this),
snap: 0
});
this.layout.slider.addEvent('mousedown', function(e){
e = new Event(e);
this.layout.arrows.setStyle(
'top', e.page.y - this.layout.slider.getTop() + this.snippet('slider') - arwH
);
this.sliderDrag.call(this);
this.layout.sliderDrag.start(e);
}.bind(this));
},
sliderDrag: function() {
var arwH = this.snippet('arrSize', 'int'), hue;
this.sliderPos = this.snippet('arrPos') - arwH;
this.setMooRainbow(this.parseColors(this.pickerPos.x, this.pickerPos.y, this.sliderPos), 'hsb');
hue = [this.sets.hsb[0], 100, 100].hsbToRgb().rgbToHex();
this.layout.overlay.setStyle('background-color', hue);
this.fireEvent('onChange', [this.sets, this]);
},
backupEvent: function() {
this.layout.backup.addEvent('click', function() {
this.manualSet(this.backupColor);
this.fireEvent('onChange', [this.sets, this]);
}.bind(this));
},
wheelEvents: function() {
var arrColors = this.arrRGB.copy().extend(this.arrHSB);
arrColors.each(function(el) {
el.addEvents({
'mousewheel': this.eventKeys.bindWithEvent(this, el),
'keydown': this.eventKeys.bindWithEvent(this, el)
});
}, this);
[this.layout.arrows, this.layout.slider].each(function(el) {
el.addEvents({
'mousewheel': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider']),
'keydown': this.eventKeys.bindWithEvent(this, [this.arrHSB[0], 'slider'])
});
}, this);
},
eventKeys: function(e, el, id) {
var wheel, type;
id = (!id) ? el.id : this.arrHSB[0];
if (e.type == 'keydown') {
if (e.key == 'up') wheel = 1;
else if (e.key == 'down') wheel = -1;
else return;
} else if (e.type == Element.Events.mousewheel.type) wheel = (e.wheel > 0) ? 1 : -1;
if (this.arrRGB.test(el)) type = 'rgb';
else if (this.arrHSB.test(el)) type = 'hsb';
else type = 'hsb';
if (type == 'rgb') {
var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass;
var value = el.value.toInt() + wheel;
value = (value > 255) ? 255 : (value < 0) ? 0 : value;
switch(el.className) {
case prefix + 'rInput': pass = [value, rgb[1], rgb[2]]; break;
case prefix + 'gInput': pass = [rgb[0], value, rgb[2]]; break;
case prefix + 'bInput': pass = [rgb[0], rgb[1], value]; break;
default : pass = rgb;
}
this.manualSet(pass);
this.fireEvent('onChange', [this.sets, this]);
} else {
var rgb = this.sets.rgb, hsb = this.sets.hsb, prefix = this.options.prefix, pass;
var value = el.value.toInt() + wheel;
if (el.className.test(/(HueInput)/)) value = (value > 359) ? 0 : (value < 0) ? 0 : value;
else value = (value > 100) ? 100 : (value < 0) ? 0 : value;
switch(el.className) {
case prefix + 'HueInput': pass = [value, hsb[1], hsb[2]]; break;
case prefix + 'SatuInput': pass = [hsb[0], value, hsb[2]]; break;
case prefix + 'BrighInput': pass = [hsb[0], hsb[1], value]; break;
default : pass = hsb;
}
this.manualSet(pass, 'hsb');
this.fireEvent('onChange', [this.sets, this]);
}
e.stop();
},
eventKeydown: function(el, e) {
var n = e.code, k = e.key;
if ((!el.className.test(/hexInput/) && !(n >= 48 && n <= 57)) &&
(k!='backspace' && k!='tab' && k !='delete' && k!='left' && k!='right'))
e.stop();
},
eventKeyup: function(el, e) {
var n = e.code, k = e.key, pass, prefix, chr = el.value.charAt(0);
if (!(el.value || el.value === 0)) return;
if (el.className.test(/hexInput/)) {
if (chr != "#" && el.value.length != 6) return;
if (chr == '#' && el.value.length != 7) return;
} else {
if (!(n >= 48 && n <= 57) && (!['backspace', 'tab', 'delete', 'left', 'right'].test(k)) && el.value.length > 3) return;
}
prefix = this.options.prefix;
if (el.className.test(/(rInput|gInput|bInput)/)) {
if (el.value < 0 || el.value > 255) return;
switch(el.className){
case prefix + 'rInput': pass = [el.value, this.sets.rgb[1], this.sets.rgb[2]]; break;
case prefix + 'gInput': pass = [this.sets.rgb[0], el.value, this.sets.rgb[2]]; break;
case prefix + 'bInput': pass = [this.sets.rgb[0], this.sets.rgb[1], el.value]; break;
default : pass = this.sets.rgb;
}
this.manualSet(pass);
this.fireEvent('onChange', [this.sets, this]);
}
else if (!el.className.test(/hexInput/)) {
if (el.className.test(/HueInput/) && el.value < 0 || el.value > 360) return;
else if (el.className.test(/HueInput/) && el.value == 360) el.value = 0;
else if (el.className.test(/(SatuInput|BrighInput)/) && el.value < 0 || el.value > 100) return;
switch(el.className){
case prefix + 'HueInput': pass = [el.value, this.sets.hsb[1], this.sets.hsb[2]]; break;
case prefix + 'SatuInput': pass = [this.sets.hsb[0], el.value, this.sets.hsb[2]]; break;
case prefix + 'BrighInput': pass = [this.sets.hsb[0], this.sets.hsb[1], el.value]; break;
default : pass = this.sets.hsb;
}
this.manualSet(pass, 'hsb');
this.fireEvent('onChange', [this.sets, this]);
} else {
pass = el.value.hexToRgb(true);
if (isNaN(pass[0])||isNaN(pass[1])||isNaN(pass[2])) return;
if (pass || pass === 0) {
this.manualSet(pass);
this.fireEvent('onChange', [this.sets, this]);
}
}
},
doLayout: function() {
var id = this.options.id, prefix = this.options.prefix;
var idPrefix = id + ' .' + prefix;
this.layout = new Element('div', {
'styles': {'display': 'block', 'position': 'absolute'},
'id': id
}).inject(document.body);
var box = new Element('div', {
'styles': {'position': 'relative'},
'class': prefix + 'box'
}).inject(this.layout);
var div = new Element('div', {
'styles': {'position': 'absolute', 'overflow': 'hidden'},
'class': prefix + 'overlayBox'
}).inject(box);
var ar = new Element('div', {
'styles': {'position': 'absolute', 'zIndex': 1},
'class': prefix + 'arrows'
}).inject(box);
ar.width = ar.getStyle('width').toInt();
ar.height = ar.getStyle('height').toInt();
var ov = new Element('img', {
'styles': {'background-color': '#fff', 'position': 'relative', 'zIndex': 2},
'src': this.options.imgPath + 'moor_woverlay.png',
'class': prefix + 'overlay'
}).inject(div);
var ov2 = new Element('img', {
'styles': {'position': 'absolute', 'top': 0, 'left': 0, 'zIndex': 2},
'src': this.options.imgPath + 'moor_boverlay.png',
'class': prefix + 'overlay'
}).inject(div);
if (window.ie6) {
div.setStyle('overflow', '');
var src = ov.src;
ov.src = this.options.imgPath + 'blank.gif';
ov.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
src = ov2.src;
ov2.src = this.options.imgPath + 'blank.gif';
ov2.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
}
ov.width = ov2.width = div.getStyle('width').toInt();
ov.height = ov2.height = div.getStyle('height').toInt();
var cr = new Element('div', {
'styles': {'overflow': 'hidden', 'position': 'absolute', 'zIndex': 2},
'class': prefix + 'cursor'
}).inject(div);
cr.width = cr.getStyle('width').toInt();
cr.height = cr.getStyle('height').toInt();
var sl = new Element('img', {
'styles': {'position': 'absolute', 'z-index': 2},
'src': this.options.imgPath + 'moor_slider.png',
'class': prefix + 'slider'
}).inject(box);
this.layout.slider = Slick.find(document, '#' + idPrefix + 'slider');
sl.width = sl.getStyle('width').toInt();
sl.height = sl.getStyle('height').toInt();
new Element('div', {
'styles': {'position': 'absolute'},
'class': prefix + 'colorBox'
}).inject(box);
new Element('div', {
'styles': {'zIndex': 2, 'position': 'absolute'},
'class': prefix + 'chooseColor'
}).inject(box);
this.layout.backup = new Element('div', {
'styles': {'zIndex': 2, 'position': 'absolute', 'cursor': 'pointer'},
'class': prefix + 'currentColor'
}).inject(box);
var R = new Element('label').inject(box).setStyle('position', 'absolute');
var G = R.clone().inject(box).addClass(prefix + 'gLabel').appendText('G: ');
var B = R.clone().inject(box).addClass(prefix + 'bLabel').appendText('B: ');
R.appendText('R: ').addClass(prefix + 'rLabel');
var inputR = new Element('input');
var inputG = inputR.clone().inject(G).addClass(prefix + 'gInput');
var inputB = inputR.clone().inject(B).addClass(prefix + 'bInput');
inputR.inject(R).addClass(prefix + 'rInput');
var HU = new Element('label').inject(box).setStyle('position', 'absolute');
var SA = HU.clone().inject(box).addClass(prefix + 'SatuLabel').appendText('S: ');
var BR = HU.clone().inject(box).addClass(prefix + 'BrighLabel').appendText('B: ');
HU.appendText('H: ').addClass(prefix + 'HueLabel');
var inputHU = new Element('input');
var inputSA = inputHU.clone().inject(SA).addClass(prefix + 'SatuInput');
var inputBR = inputHU.clone().inject(BR).addClass(prefix + 'BrighInput');
inputHU.inject(HU).addClass(prefix + 'HueInput');
SA.appendText(' %'); BR.appendText(' %');
(new Element('span', {'styles': {'position': 'absolute'}, 'class': prefix + 'ballino'}).set('html', " °").inject(HU, 'after'));
var hex = new Element('label').inject(box).setStyle('position', 'absolute').addClass(prefix + 'hexLabel').appendText('#hex: ').adopt(new Element('input').addClass(prefix + 'hexInput'));
var ok = new Element('input', {
'styles': {'position': 'absolute'},
'type': 'button',
'value': 'Select',
'class': prefix + 'okButton'
}).inject(box);
this.rePosition();
var overlays = $$('#' + idPrefix + 'overlay');
this.layout.overlay = overlays[0];
this.layout.overlay2 = overlays[1];
this.layout.cursor = Slick.find(document, '#' + idPrefix + 'cursor');
this.layout.arrows = Slick.find(document, '#' + idPrefix + 'arrows');
this.chooseColor = Slick.find(document, '#' + idPrefix + 'chooseColor');
this.layout.backup = Slick.find(document, '#' + idPrefix + 'currentColor');
this.RedInput = Slick.find(document, '#' + idPrefix + 'rInput');
this.GreenInput = Slick.find(document, '#' + idPrefix + 'gInput');
this.BlueInput = Slick.find(document, '#' + idPrefix + 'bInput');
this.HueInput = Slick.find(document, '#' + idPrefix + 'HueInput');
this.SatuInput = Slick.find(document, '#' + idPrefix + 'SatuInput');
this.BrighInput = Slick.find(document, '#' + idPrefix + 'BrighInput');
this.hexInput = Slick.find(document, '#' + idPrefix + 'hexInput');
this.arrRGB = [this.RedInput, this.GreenInput, this.BlueInput];
this.arrHSB = [this.HueInput, this.SatuInput, this.BrighInput];
this.okButton = Slick.find(document, '#' + idPrefix + 'okButton');
this.layout.cursor.setStyle('background-image', 'url(' + this.options.imgPath + 'moor_cursor.gif)');
if (!window.khtml) this.hide();
},
rePosition: function() {
var coords = this.element.getCoordinates();
this.layout.setStyles({
'left': coords.left,
'top': coords.top + coords.height + 1
});
},
snippet: function(mode, type) {
var size; type = (type) ? type : 'none';
switch(mode) {
case 'arrPos':
var t = this.layout.arrows.getStyle('top').toInt();
size = t;
break;
case 'arrSize':
var h = this.layout.arrows.height;
h = (type == 'int') ? (h/2).toInt() : h;
size = h;
break;
case 'curPos':
var l = this.layout.cursor.getStyle('left').toInt();
var t = this.layout.cursor.getStyle('top').toInt();
size = {'l': l, 't': t};
break;
case 'slider':
var t = this.layout.slider.getStyle('marginTop').toInt();
size = t;
break;
default :
var h = this.layout.cursor.height;
var w = this.layout.cursor.width;
h = (type == 'int') ? (h/2).toInt() : h;
w = (type == 'int') ? (w/2).toInt() : w;
size = {w: w, h: h};
};
return size;
}
});
MooRainbow.implement(new Options);
MooRainbow.implement(new Events); | JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* JavaScript behavior to allow shift select in administrator grids
*/
(function() {
Joomla = Joomla || {};
Joomla.JMultiSelect = new Class({
initialize : function(table) {
this.table = document.id(table);
if (this.table) {
this.boxes = this.table.getElements('input[type=checkbox]');
this.boxes.addEvent('click', function(e){
this.doselect(e);
}.bind(this));
}
},
doselect: function(e) {
var current = document.id(e.target);
if (e.shift && typeOf(this.last) !== 'null') {
var checked = current.getProperty('checked') ? 'checked' : '';
var range = [this.boxes.indexOf(current), this.boxes.indexOf(this.last)].sort(function(a, b) {
//Shorthand to make sort() sort numerical instead of lexicographic
return a-b;
});
for (var i=range[0]; i <= range[1]; i++) {
this.boxes[i].setProperty('checked', checked);
}
}
this.last = current;
}
});
})();
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
Object.append(Browser.Features, {
inputemail: (function() {
var i = document.createElement("input");
i.setAttribute("type", "email");
return i.type !== "text";
})()
});
/**
* Unobtrusive Form Validation library
*
* Inspired by: Chris Campbell <www.particletree.com>
*
* @package Joomla.Framework
* @subpackage Forms
* @since 1.5
*/
var JFormValidator = new Class({
initialize: function()
{
// Initialize variables
this.handlers = Object();
this.custom = Object();
// Default handlers
this.setHandler('username',
function (value) {
regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
return !regex.test(value);
}
);
this.setHandler('password',
function (value) {
regex=/^\S[\S ]{2,98}\S$/;
return regex.test(value);
}
);
this.setHandler('numeric',
function (value) {
regex=/^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(value);
}
);
this.setHandler('email',
function (value) {
regex=/^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(value);
}
);
// Attach to forms with class 'form-validate'
var forms = $$('form.form-validate');
forms.each(function(form){ this.attachToForm(form); }, this);
},
setHandler: function(name, fn, en)
{
en = (en == '') ? true : en;
this.handlers[name] = { enabled: en, exec: fn };
},
attachToForm: function(form)
{
// Iterate through the form object and attach the validate method to all input fields.
form.getElements('input,textarea,select,button').each(function(el){
if (el.hasClass('required')) {
el.set('aria-required', 'true');
el.set('required', 'required');
}
if ((document.id(el).get('tag') == 'input' || document.id(el).get('tag') == 'button') && document.id(el).get('type') == 'submit') {
if (el.hasClass('validate')) {
el.onclick = function(){return document.formvalidator.isValid(this.form);};
}
} else {
el.addEvent('blur', function(){return document.formvalidator.validate(this);});
if (el.hasClass('validate-email') && Browser.Features.inputemail) {
el.type = 'email';
}
}
});
},
validate: function(el)
{
el = document.id(el);
// Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true.
if(el.get('disabled')) {
this.handleResponse(true, el);
return true;
}
// If the field is required make sure it has a value
if (el.hasClass('required')) {
if (el.get('tag')=='fieldset' && (el.hasClass('radio') || el.hasClass('checkboxes'))) {
for(var i=0;;i++) {
if (document.id(el.get('id')+i)) {
if (document.id(el.get('id')+i).checked) {
break;
}
}
else {
this.handleResponse(false, el);
return false;
}
}
}
else if (!(el.get('value'))) {
this.handleResponse(false, el);
return false;
}
}
// Only validate the field if the validate class is set
var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
if (handler == '') {
this.handleResponse(true, el);
return true;
}
// Check the additional validation types
if ((handler) && (handler != 'none') && (this.handlers[handler]) && el.get('value')) {
// Execute the validation handler and return result
if (this.handlers[handler].exec(el.get('value')) != true) {
this.handleResponse(false, el);
return false;
}
}
// Return validation state
this.handleResponse(true, el);
return true;
},
isValid: function(form)
{
var valid = true;
// Validate form fields
var elements = form.getElements('fieldset').concat(Array.from(form.elements));
for (var i=0;i < elements.length; i++) {
if (this.validate(elements[i]) == false) {
valid = false;
}
}
// Run custom form validators if present
new Hash(this.custom).each(function(validator){
if (validator.exec() != true) {
valid = false;
}
});
return valid;
},
handleResponse: function(state, el)
{
// Find the label object for the given field if it exists
if (!(el.labelref)) {
var labels = $$('label');
labels.each(function(label){
if (label.get('for') == el.get('id')) {
el.labelref = label;
}
});
}
// Set the element and its label (if exists) invalid state
if (state == false) {
el.addClass('invalid');
el.set('aria-invalid', 'true');
if (el.labelref) {
document.id(el.labelref).addClass('invalid');
document.id(el.labelref).set('aria-invalid', 'true');
}
} else {
el.removeClass('invalid');
el.set('aria-invalid', 'false');
if (el.labelref) {
document.id(el.labelref).removeClass('invalid');
document.id(el.labelref).set('aria-invalid', 'false');
}
}
}
});
document.formvalidator = null;
window.addEvent('domready', function(){
document.formvalidator = new JFormValidator();
});
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Switcher behavior
*
* @package Joomla
* @since 1.5
*/
var JSwitcher = new Class({
Implements: [Options, Events],
togglers: null,
elements: null,
current: null,
options : {
onShow: function(){},
onHide: function(){},
cookieName: 'switcher',
togglerSelector: 'a',
elementSelector: 'div.tab',
elementPrefix: 'page-'
},
initialize: function(toggler, element, options) {
this.setOptions(options);
this.togglers = document.id(toggler).getElements(this.options.togglerSelector);
this.elements = document.id(element).getElements(this.options.elementSelector);
if ((this.togglers.length == 0) || (this.togglers.length != this.elements.length)) {
return;
}
this.hideAll();
this.togglers.each(function(el) {
el.addEvent('click', this.display.bind(this, el.id));
}.bind(this));
var first = [Cookie.read(this.options.cookieName), this.togglers[0].id].pick();
this.display(first);
},
display: function(togglerID) {
var toggler = document.id(togglerID);
var element = document.id(this.options.elementPrefix+togglerID);
if (toggler == null || element == null || toggler == this.current) {
return this;
}
if (this.current != null) {
this.hide(document.id(this.options.elementPrefix+this.current));
document.id(this.current).removeClass('active');
}
this.show(element);
toggler.addClass('active');
this.current = toggler.id;
Cookie.write(this.options.cookieName, this.current);
},
hide: function(element) {
this.fireEvent('hide', element);
element.setStyle('display', 'none');
},
hideAll: function() {
this.elements.setStyle('display', 'none');
this.togglers.removeClass('active');
},
show: function (element) {
this.fireEvent('show', element);
element.setStyle('display', 'block');
}
});
| JavaScript |
/*
Script: mootree.js
My Object Oriented Tree
- Developed by Rasmus Schultz, <http://www.mindplay.dk>
- Tested with MooTools release 1.2, under Firefox 2, Opera 9 and Internet Explorer 6 and 7.
License:
MIT-style license.
Credits:
Inspired by:
- WebFX xTree, <http://webfx.eae.net/dhtml/xtree/>
- Destroydrop dTree, <http://www.destroydrop.com/javascripts/tree/>
Changes:
rev.12:
- load() only worked once on the same node, fixed.
- the script would sometimes try to get 'R' from the server, fixed.
- the 'load' attribute is now supported in XML files (see example_5.html).
rev.13:
- enable() and disable() added - the adopt() and load() methods use these to improve performance by minimizing the number of visual updates.
rev.14:
- toggle() was using enable() and disable() which actually caused it to do extra work - fixed.
rev.15:
- adopt() now picks up 'href', 'target', 'title' and 'name' attributes of the a-tag, and stores them in the data object.
- adopt() now picks up additional constructor arguments from embedded comments, e.g. icons, colors, etc.
- documentation now generates properly with NaturalDocs, <http://www.naturaldocs.org/>
rev.16:
- onClick events added to MooTreeControl and MooTreeNode
- nodes can now have id's - <MooTreeControl.get> method can be used to find a node with a given id
rev.17:
- changed icon rendering to use innerHTML, making the control faster (and code size slightly smaller).
rev.18:
- migrated to MooTools 1.2 (previous versions no longer supported)
*/
var MooTreeIcon = ['I','L','Lminus','Lplus','Rminus','Rplus','T','Tminus','Tplus','_closed','_doc','_open','minus','plus'];
/*
Class: MooTreeControl
This class implements a tree control.
Properties:
root - returns the root <MooTreeNode> object.
selected - returns the currently selected <MooTreeNode> object, or null if nothing is currently selected.
Events:
onExpand - called when a node is expanded or collapsed: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:expanded or false:collapsed.
onSelect - called when a node is selected or deselected: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:selected or false:deselected.
onClick - called when a node is clicked: function(node) - where node is the <MooTreeNode> object that fired the event.
Parameters:
The constructor takes two object parameters: config and options.
The first, config, contains global settings for the tree control - you can use the configuration options listed below.
The second, options, should contain options for the <MooTreeNode> constructor - please refer to the options listed in the <MooTreeNode> documentation.
Config:
div - a string representing the div Element inside which to build the tree control.
mode - optional string, defaults to 'files' - specifies default icon behavior. In 'files' mode, empty nodes have a document icon - whereas, in 'folders' mode, all nodes are displayed as folders (a'la explorer).
grid - boolean, defaults to false. If set to true, a grid is drawn to outline the structure of the tree.
theme - string, optional, defaults to 'mootree.gif' - specifies the 'theme' GIF to use.
loader - optional, an options object for the <MooTreeNode> constructor - defaults to {icon:'mootree_loader.gif', text:'Loading...', color:'a0a0a0'}
onExpand - optional function (see Events above)
onSelect - optional function (see Events above)
*/
var MooTreeControl = new Class({
initialize: function(config, options) {
options.control = this; // make sure our new MooTreeNode knows who it's owner control is
options.div = config.div; // tells the root node which div to insert itself into
this.root = new MooTreeNode(options); // create the root node of this tree control
this.index = new Object(); // used by the get() method
this.enabled = true; // enable visual updates of the control
this.theme = config.theme || 'mootree.gif';
this.loader = config.loader || {icon:'mootree_loader.gif', text:'Loading...', color:'#a0a0a0'};
this.selected = null; // set the currently selected node to nothing
this.mode = config.mode; // mode can be "folders" or "files", and affects the default icons
this.grid = config.grid; // grid can be turned on (true) or off (false)
this.onExpand = config.onExpand || new Function(); // called when any node in the tree is expanded/collapsed
this.onSelect = config.onSelect || new Function(); // called when any node in the tree is selected/deselected
this.onClick = config.onClick || new Function(); // called when any node in the tree is clicked
this.root.update(true);
},
/*
Property: insert
Creates a new node under the root node of this tree.
Parameters:
options - an object containing the same options available to the <MooTreeNode> constructor.
Returns:
A new <MooTreeNode> instance.
*/
insert: function(options) {
options.control = this;
return this.root.insert(options);
},
/*
Property: select
Sets the currently selected node.
This is called by <MooTreeNode> when a node is selected (e.g. by clicking it's title with the mouse).
Parameters:
node - the <MooTreeNode> object to select.
*/
select: function(node) {
this.onClick(node); node.onClick(); // fire click events
if (this.selected === node) return; // already selected
if (this.selected) {
// deselect previously selected node:
this.selected.select(false);
this.onSelect(this.selected, false);
}
// select new node:
this.selected = node;
node.select(true);
this.onSelect(node, true);
},
/*
Property: expand
Expands the entire tree, recursively.
*/
expand: function() {
this.root.toggle(true, true);
},
/*
Property: collapse
Collapses the entire tree, recursively.
*/
collapse: function() {
this.root.toggle(true, false);
},
/*
Property: get
Retrieves the node with the given id - or null, if no node with the given id exists.
Parameters:
id - a string, the id of the node you wish to retrieve.
Note:
Node id can be assigned via the <MooTreeNode> constructor, e.g. using the <MooTreeNode.insert> method.
*/
get: function(id) {
return this.index[id] || null;
},
/*
Property: adopt
Adopts a structure of nested ul/li/a elements as tree nodes, then removes the original elements.
Parameters:
id - a string representing the ul element to be adopted, or an element reference.
parentNode - optional, a <MooTreeNode> object under which to import the specified ul element. Defaults to the root node of the parent control.
Note:
The ul/li structure must be properly nested, and each li-element must contain one a-element, e.g.:
><ul id="mytree">
> <li><a href="test.html">Item One</a></li>
> <li><a href="test.html">Item Two</a>
> <ul>
> <li><a href="test.html">Item Two Point One</a></li>
> <li><a href="test.html">Item Two Point Two</a></li>
> </ul>
> </li>
> <li><a href="test.html"><!-- icon:_doc; color:#ff0000 -->Item Three</a></li>
></ul>
The "href", "target", "title" and "name" attributes of the a-tags are picked up and stored in the
data property of the node.
CSS-style comments inside a-tags are parsed, and treated as arguments for <MooTreeNode> constructor,
e.g. "icon", "openicon", "color", etc.
*/
adopt: function(id, parentNode) {
if (parentNode === undefined) parentNode = this.root;
this.disable();
this._adopt(id, parentNode);
parentNode.update(true);
document.id(id).destroy();
this.enable();
},
_adopt: function(id, parentNode) {
/* adopts a structure of ul/li elements into this tree */
e = document.id(id);
var i=0, c = e.getChildren();
for (i=0; i<c.length; i++) {
if (c[i].nodeName == 'LI') {
var con={text:''}, comment='', node=null, subul=null;
var n=0, z=0, se=null, s = c[i].getChildren();
for (n=0; n<s.length; n++) {
switch (s[n].nodeName) {
case 'A':
for (z=0; z<s[n].childNodes.length; z++) {
se = s[n].childNodes[z];
switch (se.nodeName) {
case '#text': con.text += se.nodeValue; break;
case '#comment': comment += se.nodeValue; break;
}
}
con.data = s[n].getProperties('href','target','title','name');
break;
case 'UL':
subul = s[n];
break;
}
}
if (con.label != '') {
con.data.url = con.data['href']; // (for backwards compatibility)
if (comment != '') {
var bits = comment.split(';');
for (z=0; z<bits.length; z++) {
var pcs = bits[z].trim().split(':');
if (pcs.length == 2) con[pcs[0].trim()] = pcs[1].trim();
}
}
if (c[i].id != null) {
con.id = 'node_'+c[i].id;
}
node = parentNode.insert(con);
if (subul) this._adopt(subul, node);
}
}
}
},
/*
Property: disable
Call this to temporarily disable visual updates -- if you need to insert/remove many nodes
at a time, many visual updates would normally occur. By temporarily disabling the control,
these visual updates will be skipped.
When you're done making changes, call <MooTreeControl.enable> to turn on visual updates
again, and automatically repaint all nodes that were changed.
*/
disable: function() {
this.enabled = false;
},
/*
Property: enable
Enables visual updates again after a call to <MooTreeControl.disable>
*/
enable: function() {
this.enabled = true;
this.root.update(true, true);
}
});
/*
Class: MooTreeNode
This class implements the functionality of a single node in a <MooTreeControl>.
Note:
You should not manually create objects of this class -- rather, you should use
<MooTreeControl.insert> to create nodes in the root of the tree, and then use
the similar function <MooTreeNode.insert> to create subnodes.
Both insert methods have a similar syntax, and both return the newly created
<MooTreeNode> object.
Parameters:
options - an object. See options below.
Options:
text - this is the displayed text of the node, and as such as is the only required parameter.
id - string, optional - if specified, must be a unique node identifier. Nodes with id can be retrieved using the <MooTreeControl.get> method.
color - string, optional - if specified, must be a six-digit hexadecimal RGB color code.
open - boolean value, defaults to false. Use true if you want the node open from the start.
icon - use this to customize the icon of the node. The following predefined values may be used: '_open', '_closed' and '_doc'. Alternatively, specify the URL of a GIF or PNG image to use - this should be exactly 18x18 pixels in size. If you have a strip of images, you can specify an image number (e.g. 'my_icons.gif#4' for icon number 4).
openicon - use this to customize the icon of the node when it's open.
data - an object containing whatever data you wish to associate with this node (such as an url and/or an id, etc.)
Events:
onExpand - called when the node is expanded or collapsed: function(state) - where state is a boolean meaning true:expanded or false:collapsed.
onSelect - called when the node is selected or deselected: function(state) - where state is a boolean meaning true:selected or false:deselected.
onClick - called when the node is clicked (no arguments).
*/
var MooTreeNode = new Class({
initialize: function(options) {
this.text = options.text; // the text displayed by this node
this.id = options.id || null; // the node's unique id
this.nodes = new Array(); // subnodes nested beneath this node (MooTreeNode objects)
this.parent = null; // this node's parent node (another MooTreeNode object)
this.last = true; // a flag telling whether this node is the last (bottom) node of it's parent
this.control = options.control; // owner control of this node's tree
this.selected = false; // a flag telling whether this node is the currently selected node in it's tree
this.color = options.color || null; // text color of this node
this.data = options.data || {}; // optional object containing whatever data you wish to associate with the node (typically an url or an id)
this.onExpand = options.onExpand || new Function(); // called when the individual node is expanded/collapsed
this.onSelect = options.onSelect || new Function(); // called when the individual node is selected/deselected
this.onClick = options.onClick || new Function(); // called when the individual node is clicked
this.open = options.open ? true : false; // flag: node open or closed?
this.icon = options.icon;
this.openicon = options.openicon || this.icon;
// add the node to the control's node index:
if (this.id) this.control.index[this.id] = this;
// create the necessary divs:
this.div = {
main: new Element('div').addClass('mooTree_node'),
indent: new Element('div'),
gadget: new Element('div'),
icon: new Element('div'),
text: new Element('div').addClass('mooTree_text'),
sub: new Element('div')
}
// put the other divs under the main div:
this.div.main.adopt(this.div.indent);
this.div.main.adopt(this.div.gadget);
this.div.main.adopt(this.div.icon);
this.div.main.adopt(this.div.text);
// put the main and sub divs in the specified parent div:
document.id(options.div).adopt(this.div.main);
document.id(options.div).adopt(this.div.sub);
// attach event handler to gadget:
this.div.gadget._node = this;
this.div.gadget.onclick = this.div.gadget.ondblclick = function() {
this._node.toggle();
}
// attach event handler to icon/text:
this.div.icon._node = this.div.text._node = this;
this.div.icon.onclick = this.div.icon.ondblclick = this.div.text.onclick = this.div.text.ondblclick = function() {
this._node.control.select(this._node);
}
},
/*
Property: insert
Creates a new node, nested inside this one.
Parameters:
options - an object containing the same options available to the <MooTreeNode> constructor.
Returns:
A new <MooTreeNode> instance.
*/
insert: function(options) {
// set the parent div and create the node:
options.div = this.div.sub;
options.control = this.control;
var node = new MooTreeNode(options);
// set the new node's parent:
node.parent = this;
// mark this node's last node as no longer being the last, then add the new last node:
var n = this.nodes;
if (n.length) n[n.length-1].last = false;
n.push(node);
// repaint the new node:
node.update();
// repaint the new node's parent (this node):
if (n.length == 1) this.update();
// recursively repaint the new node's previous sibling node:
if (n.length > 1) n[n.length-2].update(true);
return node;
},
/*
Property: remove
Removes this node, and all of it's child nodes. If you want to remove all the childnodes without removing the node itself, use <MooTreeNode.clear>
*/
remove: function() {
var p = this.parent;
this._remove();
p.update(true);
},
_remove: function() {
// recursively remove this node's subnodes:
var n = this.nodes;
while (n.length) n[n.length-1]._remove();
// remove the node id from the control's index:
delete this.control.index[this.id];
// remove this node's divs:
this.div.main.destroy();
this.div.sub.destroy();
if (this.parent) {
// remove this node from the parent's collection of nodes:
var p = this.parent.nodes;
p.erase(this);
// in case we removed the parent's last node, flag it's current last node as being the last:
if (p.length) p[p.length-1].last = true;
}
},
/*
Property: clear
Removes all child nodes under this node, without removing the node itself.
To remove all nodes including this one, use <MooTreeNode.remove>
*/
clear: function() {
this.control.disable();
while (this.nodes.length) this.nodes[this.nodes.length-1].remove();
this.control.enable();
},
/*
Property: update
Update the tree node's visual appearance.
Parameters:
recursive - boolean, defaults to false. If true, recursively updates all nodes beneath this one.
invalidated - boolean, defaults to false. If true, updates only nodes that have been invalidated while the control has been disabled.
*/
update: function(recursive, invalidated) {
var draw = true;
if (!this.control.enabled) {
// control is currently disabled, so we don't do any visual updates
this.invalidated = true;
draw = false;
}
if (invalidated) {
if (!this.invalidated) {
draw = false; // this one is still valid, don't draw
} else {
this.invalidated = false; // we're drawing this item now
}
}
if (draw) {
var x;
// make selected, or not:
this.div.main.className = 'mooTree_node' + (this.selected ? ' mooTree_selected' : '');
// update indentations:
var p = this, i = '';
while (p.parent) {
p = p.parent;
i = this.getImg(p.last || !this.control.grid ? '' : 'I') + i;
}
this.div.indent.innerHTML = i;
// update the text:
x = this.div.text;
x.empty();
x.appendText(this.text);
if (this.color) x.style.color = this.color;
// update the icon:
this.div.icon.innerHTML = this.getImg( this.nodes.length ? ( this.open ? (this.openicon || this.icon || '_open') : (this.icon || '_closed') ) : ( this.icon || (this.control.mode == 'folders' ? '_closed' : '_doc') ) );
// update the plus/minus gadget:
this.div.gadget.innerHTML = this.getImg( ( this.control.grid ? ( this.control.root == this ? (this.nodes.length ? 'R' : '') : (this.last?'L':'T') ) : '') + (this.nodes.length ? (this.open?'minus':'plus') : '') );
// show/hide subnodes:
this.div.sub.style.display = this.open ? 'block' : 'none';
}
// if recursively updating, update all child nodes:
if (recursive) this.nodes.forEach( function(node) {
node.update(true, invalidated);
});
},
/*
Property: getImg
Creates a new image, in the form of HTML for a DIV element with appropriate style.
You should not need to manually call this method. (though if for some reason you want to, you can)
Parameters:
name - the name of new image to create, defined by <MooTreeIcon> or located in an external file.
Returns:
The HTML for a new div Element.
*/
getImg: function(name) {
var html = '<div class="mooTree_img"';
if (name != '') {
var img = this.control.theme;
var i = MooTreeIcon.indexOf(name);
if (i == -1) {
// custom (external) icon:
var x = name.split('#');
img = x[0];
i = (x.length == 2 ? parseInt(x[1])-1 : 0);
}
html += ' style="background-image:url(' + img + '); background-position:-' + (i*18) + 'px 0px;"';
}
html += "></div>";
return html;
},
/*
Property: toggle
By default (with no arguments) this function toggles the node between expanded/collapsed.
Can also be used to recursively expand/collapse all or part of the tree.
Parameters:
recursive - boolean, defaults to false. With recursive set to true, all child nodes are recursively toggle to this node's new state.
state - boolean. If undefined, the node's state is toggled. If true or false, the node can be explicitly opened or closed.
*/
toggle: function(recursive, state) {
this.open = (state === undefined ? !this.open : state);
this.update();
this.onExpand(this.open);
this.control.onExpand(this, this.open);
if (recursive) this.nodes.forEach( function(node) {
node.toggle(true, this.open);
}, this);
},
/*
Property: select
Called by <MooTreeControl> when the selection changes.
You should not manually call this method - to set the selection, use the <MooTreeControl.select> method.
*/
select: function(state) {
this.selected = state;
this.update();
this.onSelect(state);
},
/*
Property: load
Asynchronously load an XML structure into a node of this tree.
Parameters:
url - string, required, specifies the URL from which to load the XML document.
vars - query string, optional.
*/
load: function(url, vars) {
if (this.loading) return; // if this node is already loading, return
this.loading = true; // flag this node as loading
this.toggle(false, true); // expand the node to make the loader visible
this.clear();
this.insert(this.control.loader);
var f = function() {
new Request({
method: 'GET',
url: url,
onSuccess: this._loaded.bind(this),
onFailure: this._load_err.bind(this)
}).send(vars || '');
}.bind(this).delay(20);
//window.setTimeout(f.bind(this), 20); // allowing a small delay for the browser to draw the loader-icon.
},
_loaded: function(text, xml) {
// called on success - import nodes from the root element:
this.control.disable();
this.clear();
this._import(xml.documentElement);
this.control.enable();
this.loading = false;
},
_import: function(e) {
// import childnodes from an xml element:
var n = e.childNodes;
for (var i=0; i<n.length; i++) if (n[i].tagName == 'node') {
var opt = {data:{}};
var a = n[i].attributes;
for (var t=0; t<a.length; t++) {
switch (a[t].name) {
case 'text':
case 'id':
case 'icon':
case 'openicon':
case 'color':
case 'open':
opt[a[t].name] = a[t].value;
break;
default:
opt.data[a[t].name] = a[t].value;
}
}
var node = this.insert(opt);
if (node.data.load) {
node.open = false; // can't have a dynamically loading node that's already open!
node.insert(this.control.loader);
node.onExpand = function(state) {
this.load(this.data.load);
this.onExpand = new Function();
}
}
// recursively import subnodes of this node:
if (n[i].childNodes.length) node._import(n[i]);
}
},
_load_err: function(req) {
window.alert('Error loading: ' + this.text);
}
});
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// Only define the Joomla namespace if not defined.
if (typeof(Joomla) === 'undefined') {
var Joomla = {};
}
Joomla.editors = {};
// An object to hold each editor instance on page
Joomla.editors.instances = {};
/**
* Generic submit form
*/
Joomla.submitform = function(task, form) {
if (typeof(form) === 'undefined') {
form = document.getElementById('adminForm');
/**
* Added to ensure Joomla 1.5 compatibility
*/
if(!form){
form = document.adminForm;
}
}
if (typeof(task) !== 'undefined' && '' !== task) {
form.task.value = task;
}
// Submit the form.
if (typeof form.onsubmit == 'function') {
form.onsubmit();
}
if (typeof form.fireEvent == "function") {
form.fireEvent('submit');
}
form.submit();
};
/**
* Default function. Usually would be overriden by the component
*/
Joomla.submitbutton = function(pressbutton) {
Joomla.submitform(pressbutton);
}
/**
* Custom behavior for JavaScript I18N in Joomla! 1.6
*
* Allows you to call Joomla.JText._() to get a translated JavaScript string pushed in with JText::script() in Joomla.
*/
Joomla.JText = {
strings: {},
'_': function(key, def) {
return typeof this.strings[key.toUpperCase()] !== 'undefined' ? this.strings[key.toUpperCase()] : def;
},
load: function(object) {
for (var key in object) {
this.strings[key.toUpperCase()] = object[key];
}
return this;
}
};
/**
* Method to replace all request tokens on the page with a new one.
*/
Joomla.replaceTokens = function(n) {
var els = document.getElementsByTagName('input');
for (var i = 0; i < els.length; i++) {
if ((els[i].type == 'hidden') && (els[i].name.length == 32) && els[i].value == '1') {
els[i].name = n;
}
}
};
/**
* USED IN: administrator/components/com_banners/views/client/tmpl/default.php
*
* Verifies if the string is in a valid email format
*
* @param string
* @return boolean
*/
Joomla.isEmail = function(text) {
var regex = new RegExp("^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$");
return regex.test(text);
};
/**
* USED IN: all list forms.
*
* Toggles the check state of a group of boxes
*
* Checkboxes must have an id attribute in the form cb0, cb1...
*
* @param mixed The number of box to 'check', for a checkbox element
* @param string An alternative field name
*/
Joomla.checkAll = function(checkbox, stub) {
if (!stub) {
stub = 'cb';
}
if (checkbox.form) {
var c = 0;
for (var i = 0, n = checkbox.form.elements.length; i < n; i++) {
var e = checkbox.form.elements[i];
if (e.type == checkbox.type) {
if ((stub && e.id.indexOf(stub) == 0) || !stub) {
e.checked = checkbox.checked;
c += (e.checked == true ? 1 : 0);
}
}
}
if (checkbox.form.boxchecked) {
checkbox.form.boxchecked.value = c;
}
return true;
}
return false;
}
/**
* Render messages send via JSON
*
* @param object messages JavaScript object containing the messages to render
* @return void
*/
Joomla.renderMessages = function(messages) {
Joomla.removeMessages();
var container = document.id('system-message-container');
var dl = new Element('dl', {
id: 'system-message',
role: 'alert'
});
Object.each(messages, function (item, type) {
var dt = new Element('dt', {
'class': type,
html: type
});
dt.inject(dl);
var dd = new Element('dd', {
'class': type
});
dd.addClass('message');
var list = new Element('ul');
Array.each(item, function (item, index, object) {
var li = new Element('li', {
html: item
});
li.inject(list);
}, this);
list.inject(dd);
dd.inject(dl);
}, this);
dl.inject(container);
};
/**
* Remove messages
*
* @return void
*/
Joomla.removeMessages = function() {
var children = $$('#system-message-container > *');
children.destroy();
}
/**
* USED IN: administrator/components/com_cache/views/cache/tmpl/default.php
* administrator/components/com_installer/views/discover/tmpl/default_item.php
* administrator/components/com_installer/views/update/tmpl/default_item.php
* administrator/components/com_languages/helpers/html/languages.php
* libraries/joomla/html/html/grid.php
*
* @param isitchecked
* @param form
* @return
*/
Joomla.isChecked = function(isitchecked, form) {
if (typeof(form) === 'undefined') {
form = document.getElementById('adminForm');
/**
* Added to ensure Joomla 1.5 compatibility
*/
if(!form){
form = document.adminForm;
}
}
if (isitchecked == true) {
form.boxchecked.value++;
} else {
form.boxchecked.value--;
}
}
/**
* USED IN: libraries/joomla/html/toolbar/button/help.php
*
* Pops up a new window in the middle of the screen
*/
Joomla.popupWindow = function(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
var winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl
+ ',scrollbars=' + scroll + ',resizable'
var win = window.open(mypage, myname, winprops)
win.window.focus();
}
/**
* USED IN: libraries/joomla/html/html/grid.php
*/
Joomla.tableOrdering = function(order, dir, task, form) {
if (typeof(form) === 'undefined') {
form = document.getElementById('adminForm');
/**
* Added to ensure Joomla 1.5 compatibility
*/
if(!form){
form = document.adminForm;
}
}
form.filter_order.value = order;
form.filter_order_Dir.value = dir;
Joomla.submitform(task, form);
}
/**
* USED IN: administrator/components/com_modules/views/module/tmpl/default.php
*
* Writes a dynamically generated list
*
* @param string
* The parameters to insert into the <select> tag
* @param array
* A javascript array of list options in the form [key,value,text]
* @param string
* The key to display for the initial state of the list
* @param string
* The original key that was selected
* @param string
* The original item value that was selected
*/
function writeDynaList(selectParams, source, key, orig_key, orig_val) {
var html = '\n <select ' + selectParams + '>';
var i = 0;
for (x in source) {
if (source[x][0] == key) {
var selected = '';
if ((orig_key == key && orig_val == source[x][1])
|| (i == 0 && orig_key != key)) {
selected = 'selected="selected"';
}
html += '\n <option value="' + source[x][1] + '" ' + selected
+ '>' + source[x][2] + '</option>';
}
i++;
}
html += '\n </select>';
document.writeln(html);
}
/**
* USED IN: administrator/components/com_content/views/article/view.html.php
*
* Changes a dynamically generated list
*
* @param string
* The name of the list to change
* @param array
* A javascript array of list options in the form [key,value,text]
* @param string
* The key to display
* @param string
* The original key that was selected
* @param string
* The original item value that was selected
*/
function changeDynaList(listname, source, key, orig_key, orig_val) {
var list = document.adminForm[listname];
// empty the list
for (i in list.options.length) {
list.options[i] = null;
}
i = 0;
for (x in source) {
if (source[x][0] == key) {
opt = new Option();
opt.value = source[x][1];
opt.text = source[x][2];
if ((orig_key == key && orig_val == opt.value) || i == 0) {
opt.selected = true;
}
list.options[i++] = opt;
}
}
list.length = i;
}
/**
* USED IN: administrator/components/com_menus/views/menus/tmpl/default.php
*
* @param radioObj
* @return
*/
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function radioGetCheckedValue(radioObj) {
if (!radioObj) {
return '';
}
var n = radioObj.length;
if (n == undefined) {
if (radioObj.checked) {
return radioObj.value;
} else {
return '';
}
}
for ( var i = 0; i < n; i++) {
if (radioObj[i].checked) {
return radioObj[i].value;
}
}
return '';
}
/**
* USED IN: administrator/components/com_banners/views/banner/tmpl/default/php
* administrator/components/com_categories/views/category/tmpl/default.php
* administrator/components/com_categories/views/copyselect/tmpl/default.php
* administrator/components/com_content/views/copyselect/tmpl/default.php
* administrator/components/com_massmail/views/massmail/tmpl/default.php
* administrator/components/com_menus/views/list/tmpl/copy.php
* administrator/components/com_menus/views/list/tmpl/move.php
* administrator/components/com_messages/views/message/tmpl/default_form.php
* administrator/components/com_newsfeeds/views/newsfeed/tmpl/default.php
* components/com_content/views/article/tmpl/form.php
* templates/beez/html/com_content/article/form.php
*
* @param frmName
* @param srcListName
* @return
*/
function getSelectedValue(frmName, srcListName) {
var form = document[frmName];
var srcList = form[srcListName];
i = srcList.selectedIndex;
if (i != null && i > -1) {
return srcList.options[i].value;
} else {
return null;
}
}
/**
* USED IN: all list forms.
*
* Toggles the check state of a group of boxes
*
* Checkboxes must have an id attribute in the form cb0, cb1...
*
* @param mixed The number of box to 'check', for a checkbox element
* @param string An alternative field name
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.checkAll() instead.
*/
function checkAll(checkbox, stub) {
if (!stub) {
stub = 'cb';
}
if (checkbox.form) {
var c = 0;
for (var i = 0, n = checkbox.form.elements.length; i < n; i++) {
var e = checkbox.form.elements[i];
if (e.type == checkbox.type) {
if ((stub && e.id.indexOf(stub) == 0) || !stub) {
e.checked = checkbox.checked;
c += (e.checked == true ? 1 : 0);
}
}
}
if (checkbox.form.boxchecked) {
checkbox.form.boxchecked.value = c;
}
return true;
} else {
// The old way of doing it
var f = document.adminForm;
var c = f.toggle.checked;
var n = checkbox;
var n2 = 0;
for (var i = 0; i < n; i++) {
var cb = f[stub+''+i];
if (cb) {
cb.checked = c;
n2++;
}
}
if (c) {
document.adminForm.boxchecked.value = n2;
} else {
document.adminForm.boxchecked.value = 0;
}
}
}
/**
* USED IN: all over :)
*
* @param id
* @param task
* @return
*/
function listItemTask(id, task) {
var f = document.adminForm;
var cb = f[id];
if (cb) {
for (var i = 0; true; i++) {
var cbx = f['cb'+i];
if (!cbx)
break;
cbx.checked = false;
} // for
cb.checked = true;
f.boxchecked.value = 1;
submitbutton(task);
}
return false;
}
/**
* USED IN: administrator/components/com_cache/views/cache/tmpl/default.php
* administrator/components/com_installer/views/discover/tmpl/default_item.php
* administrator/components/com_installer/views/update/tmpl/default_item.php
* administrator/components/com_languages/helpers/html/languages.php
* libraries/joomla/html/html/grid.php
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.isChecked() instead.
*
* @param isitchecked
* @return
*
*/
function isChecked(isitchecked) {
if (isitchecked == true) {
document.adminForm.boxchecked.value++;
} else {
document.adminForm.boxchecked.value--;
}
}
/**
* Default function. Usually would be overriden by the component
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.submitbutton() instead.
*/
function submitbutton(pressbutton) {
submitform(pressbutton);
}
/**
* Submit the admin form
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.submitform() instead.
*/
function submitform(pressbutton) {
if (pressbutton) {
document.adminForm.task.value = pressbutton;
}
if (typeof document.adminForm.onsubmit == "function") {
document.adminForm.onsubmit();
}
if (typeof document.adminForm.fireEvent == "function") {
document.adminForm.fireEvent('submit');
}
document.adminForm.submit();
}
/**
* USED IN: libraries/joomla/html/toolbar/button/help.php
*
* Pops up a new window in the middle of the screen
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.popupWindow() instead.
*/
function popupWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl
+ ',scrollbars=' + scroll + ',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) {
win.window.focus();
}
}
// needed for Table Column ordering
/**
* USED IN: libraries/joomla/html/html/grid.php
*
* @deprecated 12.1 This function will be removed in a future version. Use Joomla.tableOrdering() instead.
*/
function tableOrdering(order, dir, task) {
var form = document.adminForm;
form.filter_order.value = order;
form.filter_order_Dir.value = dir;
submitform(task);
}
/**
* USED IN: libraries/joomla/html/html/grid.php
*/
function saveorder(n, task) {
checkAll_button(n, task);
}
function checkAll_button(n, task) {
if (!task) {
task = 'saveorder';
}
for (var j = 0; j <= n; j++) {
var box = document.adminForm['cb'+j];
if (box) {
if (box.checked == false) {
box.checked = true;
}
} else {
alert("You cannot change the order of items, as an item in the list is `Checked Out`");
return;
}
}
submitform(task);
}
| JavaScript |
/**
* @package Joomla.JavaScript
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// Only define the Joomla namespace if not defined.
if (typeof(Joomla) === 'undefined') {
var Joomla = {};
}
Joomla.Highlighter = new Class({
Implements: Options,
options: {
autoUnhighlight: true,
caseSensitive: false,
startElement: false,
endElement: false,
elements: new Array(),
className: 'highlight',
onlyWords: true,
tag: 'span'
},
initialize: function (options) {
this.setOptions(options);
this.getElements(this.options.startElement, this.options.endElement);
this.words = [];
},
highlight: function (words) {
if (words.constructor === String) {
words = [words];
}
if (this.options.autoUnhighlight) {
this.unhighlight(words);
}
var pattern = this.options.onlyWords ? '\b' + pattern + '\b' : '(' + words.join('\\b|\\b') + ')';
var regex = new RegExp(pattern, this.options.caseSensitive ? '' : 'i');
this.options.elements.each(function (el) {
this.recurse(el, regex, this.options.className);
}, this);
return this;
},
unhighlight: function (words) {
if (words.constructor === String) {
words = [words];
}
words.each(function (word) {
word = (this.options.caseSensitive ? word : word.toUpperCase());
if (this.words[word]) {
var elements = $$(this.words[word]);
elements.setProperty('class', '');
elements.each(function (el) {
var tn = document.createTextNode(el.getText());
el.getParent().replaceChild(tn, el);
});
}
}, this);
return this;
},
recurse: function (node, regex, klass) {
if (node.nodeType === 3) {
var match = node.data.match(regex);
if (match) {
var highlight = new Element(this.options.tag);
highlight.addClass(klass);
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
highlight.setProperty('rel', highlight.get('text'));
var comparer = highlight.get('text');
if (!this.options.caseSensitive) {
comparer = highlight.get('text').toUpperCase();
}
if (!this.words[comparer]) {
this.words[comparer] = [];
}
this.words[comparer].push(highlight);
return 1;
}
} else if ((node.nodeType === 1 && node.childNodes) && !/(script|style|textarea|iframe)/i.test(node.tagName) && !(node.tagName === this.options.tag.toUpperCase() && node.className === klass)) {
for (var i = 0; i < node.childNodes.length; i++) {
i += this.recurse(node.childNodes[i], regex, klass);
}
}
return 0;
},
getElements: function (start, end) {
var next = start.getNext();
if (next.id != end.id) {
this.options.elements.include(next);
this.getElements(next, end);
}
}
});
| JavaScript |
/*
---
description: Form.PasswordStrength class, and basic dom methods
license: MIT-style
authors:
- Al Kent
requires:
- core/1.3.1: '*'
provides:
- Form.PasswordStrength
- Element.Events.keyupandchange
- String.strength
...
*/
if (!this.Form) this.Form = {};
Form.PasswordStrength = new Class({
Implements: [Options, Events],
options: {
//onUpdate: $empty,
threshold: 66,
primer: '',
height: 5,
opacity: 1,
bgcolor: 'transparent'
},
element: null,
fx: null,
initialize: function(el, options){
this.element = document.id(el);
this.setOptions(options);
if (this.options.primer) this.options.threshold = this.options.primer.strength();
var coord = this.element.getCoordinates();
var bar = new Element('div', {
styles: {
'position': 'absolute',
'top': coord.top + coord.height,
'left': coord.left,
'width': coord.width,
'height': this.options.height,
'opacity': this.options.opacity,
'background-color': this.options.bgcolor
}
}).inject(document.body, 'bottom');
var meter = new Element('div', {
styles: {
'width': 0,
'height': '100%'
}
}).inject(bar);
this.fx = new Fx.Morph(meter, {
duration: 'short',
link: 'cancel',
unit: '%'
});
this.element.addEvent('keyupandchange', this.animate.bind(this));
if (this.element.get('value')) this.animate();
},
animate: function(){
var value = this.element.get('value');
var color, strength = value.strength(), ratio = (strength / this.options.threshold).round(2).limit(0, 1);
if (ratio < 0.5) color = ('rgb(255, ' + (255 * ratio * 2).round() + ', 0)').rgbToHex();
else color = ('rgb(' + (255 * (1 - ratio) * 2).round() + ', 255, 0)').rgbToHex();
this.fx.start({
'width': 100 * ratio,
'background-color': color
});
this.fireEvent('update', [this.element, strength, this.options.threshold]);
}
});
Element.Events.keyupandchange = {
base: 'keyup',
condition: function(event){
var prev = this.retrieve('prev', null);
var cur = this.get('value');
if (typeOf(prev) != 'null' && prev == cur) return false;
this.store('prev', cur);
return true;
}
};
String.implement({
strength: function(){
var n = 0;
if (this.match(/\d/)) n += 10;
if (this.match(/[a-z]+/)) n += 26;
if (this.match(/[A-Z]+/)) n += 26;
if (this.match(/[^\da-zA-Z]/)) n += 33;
return (n == 0) ? 0 : (this.length * n.log() / (2).log()).round();
}
});
| JavaScript |
/**
* Swiff.Uploader - Flash FileReference Control
*
* @version 3.0
*
* @license MIT License
*
* @author Harald Kirschner <http://digitarald.de>
* @author Valerio Proietti, <http://mad4milk.net>
* @copyright Authors
*/
Swiff.Uploader = new Class({
Extends: Swiff,
Implements: Events,
options: {
path: 'Swiff.Uploader.swf',
target: null,
zIndex: 9999,
callBacks: null,
params: {
wMode: 'opaque',
menu: 'false',
allowScriptAccess: 'always'
},
typeFilter: null,
multiple: true,
queued: true,
verbose: false,
height: 30,
width: 100,
passStatus: null,
url: null,
method: null,
data: null,
mergeData: true,
fieldName: null,
fileSizeMin: 1,
fileSizeMax: null, // Official limit is 100 MB for FileReference, but I tested up to 2Gb!
allowDuplicates: false,
timeLimit: (Browser.Platform.linux) ? 0 : 30,
policyFile: null,
buttonImage: null,
fileListMax: 0,
fileListSizeMax: 0,
instantStart: false,
appendCookieData: false,
fileClass: null
/*
onLoad: $empty,
onFail: $empty,
onStart: $empty,
onQueue: $empty,
onComplete: $empty,
onBrowse: $empty,
onDisabledBrowse: $empty,
onCancel: $empty,
onSelect: $empty,
onSelectSuccess: $empty,
onSelectFail: $empty,
onButtonEnter: $empty,
onButtonLeave: $empty,
onButtonDown: $empty,
onButtonDisable: $empty,
onFileStart: $empty,
onFileStop: $empty,
onFileRequeue: $empty,
onFileOpen: $empty,
onFileProgress: $empty,
onFileComplete: $empty,
onFileRemove: $empty,
onBeforeStart: $empty,
onBeforeStop: $empty,
onBeforeRemove: $empty
*/
},
initialize: function(options) {
// protected events to control the class, added
// before setting options (which adds own events)
this.addEvent('load', this.initializeSwiff, true)
.addEvent('select', this.processFiles, true)
.addEvent('complete', this.update, true)
.addEvent('fileRemove', function(file) {
this.fileList.erase(file);
}.bind(this), true);
this.setOptions(options);
// callbacks are no longer in the options, every callback
// is fired as event, this is just compat
if (this.options.callBacks) {
Hash.each(this.options.callBacks, function(fn, name) {
this.addEvent(name, fn);
}, this);
}
this.options.callBacks = {
fireCallback: this.fireCallback.bind(this)
};
var path = this.options.path;
if (!path.contains('?')) path += '?noCache=' + Date.now; // cache in IE
// container options for Swiff class
this.options.container = this.box = new Element('span', {'class': 'swiff-uploader-box'}).inject(document.id(this.options.container) || document.body);
// target
this.target = document.id(this.options.target);
if (this.target) {
var scroll = window.getScroll();
this.box.setStyles({
position: 'absolute',
visibility: 'visible',
zIndex: this.options.zIndex,
overflow: 'hidden',
height: 1, width: 1,
top: scroll.y, left: scroll.x
});
// we force wMode to transparent for the overlay effect
this.parent(path, {
params: {
wMode: 'transparent'
},
height: '100%',
width: '100%'
});
this.target.addEvent('mouseenter', this.reposition.bind(this, []));
// button interactions, relayed to to the target
this.addEvents({
buttonEnter: this.targetRelay.bind(this, ['mouseenter']),
buttonLeave: this.targetRelay.bind(this, ['mouseleave']),
buttonDown: this.targetRelay.bind(this, ['mousedown']),
buttonDisable: this.targetRelay.bind(this, ['disable'])
});
this.reposition();
window.addEvent('resize', this.reposition.bind(this, []));
} else {
this.parent(path);
}
this.inject(this.box);
this.fileList = [];
this.size = this.uploading = this.bytesLoaded = this.percentLoaded = 0;
if (Browser.Plugins.Flash.version < 9) {
this.fireEvent('fail', ['flash']);
} else {
this.verifyLoad.delay(1000, this);
}
},
verifyLoad: function() {
if (this.loaded) return;
if (!this.object.parentNode) {
this.fireEvent('fail', ['disabled']);
} else if (this.object.style.display == 'none') {
this.fireEvent('fail', ['hidden']);
} else if (!this.object.offsetWidth) {
this.fireEvent('fail', ['empty']);
}
},
fireCallback: function(name, args) {
// file* callbacks are relayed to the specific file
if (name.substr(0, 4) == 'file') {
// updated queue data is the second argument
if (args.length > 1) this.update(args[1]);
var data = args[0];
var file = this.findFile(data.id);
this.fireEvent(name, file || data, 5);
if (file) {
var fire = name.replace(/^file([A-Z])/, function($0, $1) {
return $1.toLowerCase();
});
file.update(data).fireEvent(fire, [data], 10);
}
} else {
this.fireEvent(name, args, 5);
}
},
update: function(data) {
// the data is saved right to the instance
Object.append(this, data);
this.fireEvent('queue', [this], 10);
return this;
},
findFile: function(id) {
for (var i = 0; i < this.fileList.length; i++) {
if (this.fileList[i].id == id) return this.fileList[i];
}
return null;
},
initializeSwiff: function() {
// extracted options for the swf
this.remote('xInitialize', {
typeFilter: this.options.typeFilter,
multiple: this.options.multiple,
queued: this.options.queued,
verbose: this.options.verbose,
width: this.options.width,
height: this.options.height,
passStatus: this.options.passStatus,
url: this.options.url,
method: this.options.method,
data: this.options.data,
mergeData: this.options.mergeData,
fieldName: this.options.fieldName,
fileSizeMin: this.options.fileSizeMin,
fileSizeMax: this.options.fileSizeMax,
allowDuplicates: this.options.allowDuplicates,
timeLimit: this.options.timeLimit,
policyFile: this.options.policyFile,
buttonImage: this.options.buttonImage
});
this.loaded = true;
this.appendCookieData();
},
targetRelay: function(name) {
if (this.target) this.target.fireEvent(name);
},
reposition: function(coords) {
// update coordinates, manual or automatically
coords = coords || (this.target && this.target.offsetHeight)
? this.target.getCoordinates(this.box.getOffsetParent())
: {top: window.getScrollTop(), left: 0, width: 40, height: 40}
this.box.setStyles(coords);
this.fireEvent('reposition', [coords, this.box, this.target]);
},
setOptions: function(options) {
if (options) {
if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
if (options.buttonImage) options.buttonImage = Swiff.Uploader.qualifyPath(options.buttonImage);
this.parent(options);
if (this.loaded) this.remote('xSetOptions', options);
}
return this;
},
setEnabled: function(status) {
this.remote('xSetEnabled', status);
},
start: function() {
this.fireEvent('beforeStart');
this.remote('xStart');
},
stop: function() {
this.fireEvent('beforeStop');
this.remote('xStop');
},
remove: function() {
this.fireEvent('beforeRemove');
this.remote('xRemove');
},
fileStart: function(file) {
this.remote('xFileStart', file.id);
},
fileStop: function(file) {
this.remote('xFileStop', file.id);
},
fileRemove: function(file) {
this.remote('xFileRemove', file.id);
},
fileRequeue: function(file) {
this.remote('xFileRequeue', file.id);
},
appendCookieData: function() {
var append = this.options.appendCookieData;
if (!append) return;
var hash = {};
document.cookie.split(/;\s*/).each(function(cookie) {
cookie = cookie.split('=');
if (cookie.length == 2) {
hash[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]);
}
});
var data = this.options.data || {};
if ($type(append) == 'string') data[append] = hash;
else Object.append(data, hash);
this.setOptions({data: data});
},
processFiles: function(successraw, failraw, queue) {
var cls = this.options.fileClass || Swiff.Uploader.File;
var fail = [], success = [];
if (successraw) {
successraw.each(function(data) {
var ret = new cls(this, data);
if (!ret.validate()) {
ret.remove.delay(10, ret);
fail.push(ret);
} else {
this.size += data.size;
this.fileList.push(ret);
success.push(ret);
ret.render();
}
}, this);
this.fireEvent('selectSuccess', [success], 10);
}
if (failraw || fail.length) {
fail.extend((failraw) ? failraw.map(function(data) {
return new cls(this, data);
}, this) : []).each(function(file) {
file.invalidate().render();
});
this.fireEvent('selectFail', [fail], 10);
}
this.update(queue);
if (this.options.instantStart && success.length) this.start();
}
});
Object.append(Swiff.Uploader, {
STATUS_QUEUED: 0,
STATUS_RUNNING: 1,
STATUS_ERROR: 2,
STATUS_COMPLETE: 3,
STATUS_STOPPED: 4,
log: function() {
if (window.console && console.info) console.info.apply(console, arguments);
},
unitLabels: {
b: [{min: 1, unit: 'B'}, {min: 1024, unit: 'kB'}, {min: 1048576, unit: 'MB'}, {min: 1073741824, unit: 'GB'}],
s: [{min: 1, unit: 's'}, {min: 60, unit: 'm'}, {min: 3600, unit: 'h'}, {min: 86400, unit: 'd'}]
},
formatUnit: function(base, type, join) {
var labels = Swiff.Uploader.unitLabels[(type == 'bps') ? 'b' : type];
var append = (type == 'bps') ? '/s' : '';
var i, l = labels.length, value;
if (base < 1) return '0 ' + labels[0].unit + append;
if (type == 's') {
var units = [];
for (i = l - 1; i >= 0; i--) {
value = Math.floor(base / labels[i].min);
if (value) {
units.push(value + ' ' + labels[i].unit);
base -= value * labels[i].min;
if (!base) break;
}
}
return (join === false) ? units : units.join(join || ', ');
}
for (i = l - 1; i >= 0; i--) {
value = labels[i].min;
if (base >= value) break;
}
return (base / value).toFixed(1) + ' ' + labels[i].unit + append;
}
});
Swiff.Uploader.qualifyPath = (function() {
var anchor;
return function(path) {
(anchor || (anchor = new Element('a'))).href = path;
return anchor.href;
};
})();
Swiff.Uploader.File = new Class({
Implements: Events,
initialize: function(base, data) {
this.base = base;
this.update(data);
},
update: function(data) {
return Object.append(this, data);
},
validate: function() {
var options = this.base.options;
if (options.fileListMax && this.base.fileList.length >= options.fileListMax) {
this.validationError = 'fileListMax';
return false;
}
if (options.fileListSizeMax && (this.base.size + this.size) > options.fileListSizeMax) {
this.validationError = 'fileListSizeMax';
return false;
}
return true;
},
invalidate: function() {
this.invalid = true;
this.base.fireEvent('fileInvalid', this, 10);
return this.fireEvent('invalid', this, 10);
},
render: function() {
return this;
},
setOptions: function(options) {
if (options) {
if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
this.base.remote('xFileSetOptions', this.id, options);
this.options = $merge(this.options, options);
}
return this;
},
start: function() {
this.base.fileStart(this);
return this;
},
stop: function() {
this.base.fileStop(this);
return this;
},
remove: function() {
this.base.fileRemove(this);
return this;
},
requeue: function() {
this.base.fileRequeue(this);
}
}); | JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* JImageManager behavior for media component
*
* @package Joomla.Extensions
* @subpackage Media
* @since 1.5
*/
(function() {
var ImageManager = this.ImageManager = {
initialize: function()
{
o = this._getUriObject(window.self.location.href);
//console.log(o);
q = new Hash(this._getQueryObject(o.query));
this.editor = decodeURIComponent(q.get('e_name'));
// Setup image manager fields object
this.fields = new Object();
this.fields.url = document.id("f_url");
this.fields.alt = document.id("f_alt");
this.fields.align = document.id("f_align");
this.fields.title = document.id("f_title");
this.fields.caption = document.id("f_caption");
// Setup image listing objects
this.folderlist = document.id('folderlist');
this.frame = window.frames['imageframe'];
this.frameurl = this.frame.location.href;
// Setup imave listing frame
this.imageframe = document.id('imageframe');
this.imageframe.manager = this;
this.imageframe.addEvent('load', function(){ ImageManager.onloadimageview(); });
// Setup folder up button
this.upbutton = document.id('upbutton');
this.upbutton.removeEvents('click');
this.upbutton.addEvent('click', function(){ ImageManager.upFolder(); });
},
onloadimageview: function()
{
// Update the frame url
this.frameurl = this.frame.location.href;
var folder = this.getImageFolder();
for(var i = 0; i < this.folderlist.length; i++)
{
if(folder == this.folderlist.options[i].value) {
this.folderlist.selectedIndex = i;
break;
}
}
a = this._getUriObject(document.id('uploadForm').getProperty('action'));
//console.log(a);
q = new Hash(this._getQueryObject(a.query));
q.set('folder', folder);
var query = [];
q.each(function(v, k){
if (v !== null) {
this.push(k+'='+v);
}
}, query);
a.query = query.join('&');
var portString = '';
if (typeof(a.port) !== 'undefined' && a.port != 80) {
portString = ':'+a.port;
}
document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+portString+a.path+'?'+a.query);
},
getImageFolder: function()
{
var url = this.frame.location.search.substring(1);
var args = this.parseQuery(url);
return args['folder'];
},
onok: function()
{
extra = '';
// Get the image tag field information
var url = this.fields.url.get('value');
var alt = this.fields.alt.get('value');
var align = this.fields.align.get('value');
var title = this.fields.title.get('value');
var caption = this.fields.caption.get('value');
if (url != '') {
// Set alt attribute
if (alt != '') {
extra = extra + 'alt="'+alt+'" ';
} else {
extra = extra + 'alt="" ';
}
// Set align attribute
if (align != '') {
extra = extra + 'align="'+align+'" ';
}
// Set align attribute
if (title != '') {
extra = extra + 'title="'+title+'" ';
}
// Set align attribute
if (caption != '') {
extra = extra + 'class="caption" ';
}
var tag = "<img src=\""+url+"\" "+extra+"/>";
}
window.parent.jInsertEditorText(tag, this.editor);
return false;
},
setFolder: function(folder,asset,author)
{
//this.showMessage('Loading');
for(var i = 0; i < this.folderlist.length; i++)
{
if(folder == this.folderlist.options[i].value) {
this.folderlist.selectedIndex = i;
break;
}
}
this.frame.location.href='index.php?option=com_media&view=imagesList&tmpl=component&folder=' + folder + '&asset=' + asset + '&author=' + author;
},
getFolder: function() {
return this.folderlist.get('value');
},
upFolder: function()
{
var currentFolder = this.getFolder();
if(currentFolder.length < 2) {
return false;
}
var folders = currentFolder.split('/');
var search = '';
for(var i = 0; i < folders.length - 1; i++) {
search += folders[i];
search += '/';
}
// remove the trailing slash
search = search.substring(0, search.length - 1);
for(var i = 0; i < this.folderlist.length; i++)
{
var thisFolder = this.folderlist.options[i].value;
if(thisFolder == search)
{
this.folderlist.selectedIndex = i;
var newFolder = this.folderlist.options[i].value;
this.setFolder(newFolder);
break;
}
}
},
populateFields: function(file)
{
document.id("f_url").value = image_base_path+file;
},
showMessage: function(text)
{
var message = document.id('message');
var messages = document.id('messages');
if(message.firstChild)
message.removeChild(message.firstChild);
message.appendChild(document.createTextNode(text));
messages.style.display = "block";
},
parseQuery: function(query)
{
var params = new Object();
if (!query) {
return params;
}
var pairs = query.split(/[;&]/);
for ( var i = 0; i < pairs.length; i++ )
{
var KeyVal = pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {
continue;
}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] ).replace(/\+ /g, ' ');
params[key] = val;
}
return params;
},
refreshFrame: function()
{
this._setFrameUrl();
},
_setFrameUrl: function(url)
{
if (url != null) {
this.frameurl = url;
}
this.frame.location.href = this.frameurl;
},
_getQueryObject: function(q) {
var vars = q.split(/[&;]/);
var rs = {};
if (vars.length) vars.each(function(val) {
var keys = val.split('=');
if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
});
return rs;
},
_getUriObject: function(u){
var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/);
return (bits)
? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment'])
: null;
}
};
})(document.id);
window.addEvent('domready', function(){
ImageManager.initialize();
});
| JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* JMediaManager behavior for media component
*
* @package Joomla.Extensions
* @subpackage Media
* @since 1.5
*/
(function() {
var MediaManager = this.MediaManager = {
initialize: function()
{
this.folderframe = document.id('folderframe');
this.folderpath = document.id('folderpath');
this.updatepaths = $$('input.update-folder');
this.frame = window.frames['folderframe'];
this.frameurl = this.frame.location.href;
//this.frameurl = window.frames['folderframe'].location.href;
this.tree = new MooTreeControl({ div: 'media-tree_tree', mode: 'folders', grid: true, theme: '../media/system/images/mootree.gif', onClick:
function(node){
target = node.data.target != null ? node.data.target : '_self';
// Get the current URL.
uri = this._getUriObject(this.frameurl);
current = uri.file+'?'+uri.query;
if (current != 'undefined?undefined' && current != node.data.url) {
window.frames[target].location.href = node.data.url;
}
}.bind(this)
},{ text: '', open: true, data: { url: 'index.php?option=com_media&view=mediaList&tmpl=component', target: 'folderframe'}});
this.tree.adopt('media-tree');
},
submit: function(task)
{
form = window.frames['folderframe'].document.id('mediamanager-form');
form.task.value = task;
if (document.id('username')) {
form.username.value = document.id('username').value;
form.password.value = document.id('password').value;
}
form.submit();
},
onloadframe: function()
{
// Update the frame url
this.frameurl = this.frame.location.href;
var folder = this.getFolder();
if (folder) {
this.updatepaths.each(function(path){ path.value =folder; });
this.folderpath.value = basepath+'/'+folder;
node = this.tree.get('node_'+folder);
node.toggle(false, true);
} else {
this.updatepaths.each(function(path){ path.value = ''; });
this.folderpath.value = basepath;
node = this.tree.root;
}
if (node) {
this.tree.select(node, true);
}
document.id(viewstyle).addClass('active');
a = this._getUriObject(document.id('uploadForm').getProperty('action'));
q = new Hash(this._getQueryObject(a.query));
q.set('folder', folder);
var query = [];
q.each(function(v, k){
if (v != null) {
this.push(k+'='+v);
}
}, query);
a.query = query.join('&');
if (a.port) {
document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+':'+a.port+a.path+'?'+a.query);
} else {
document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query);
}
},
oncreatefolder: function()
{
if (document.id('foldername').value.length) {
document.id('dirpath').value = this.getFolder();
Joomla.submitbutton('createfolder');
}
},
setViewType: function(type)
{
document.id(type).addClass('active');
document.id(viewstyle).removeClass('active');
viewstyle = type;
var folder = this.getFolder();
this._setFrameUrl('index.php?option=com_media&view=mediaList&tmpl=component&folder='+folder+'&layout='+type);
},
refreshFrame: function()
{
this._setFrameUrl();
},
getFolder: function()
{
var url = this.frame.location.search.substring(1);
var args = this.parseQuery(url);
if (args['folder'] == "undefined") {
args['folder'] = "";
}
return args['folder'];
},
parseQuery: function(query)
{
var params = new Object();
if (!query) {
return params;
}
var pairs = query.split(/[;&]/);
for ( var i = 0; i < pairs.length; i++ )
{
var KeyVal = pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {
continue;
}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] ).replace(/\+ /g, ' ');
params[key] = val;
}
return params;
},
_setFrameUrl: function(url)
{
if (url != null) {
this.frameurl = url;
}
this.frame.location.href = this.frameurl;
},
_getQueryObject: function(q) {
var vars = q.split(/[&;]/);
var rs = {};
if (vars.length) vars.each(function(val) {
var keys = val.split('=');
if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
});
return rs;
},
_getUriObject: function(u){
var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/);
return (bits)
? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment'])
: null;
}
};
})(document.id);
window.addEvent('domready', function(){
// Added to populate data on iframe load
MediaManager.initialize();
MediaManager.trace = 'start';
document.updateUploader = function() { MediaManager.onloadframe(); };
MediaManager.onloadframe();
});
| JavaScript |
/**
* @version $Id: k2.noconflict.js 1812 2013-01-14 18:45:06Z lefteris.kavadas $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
var $K2 = jQuery.noConflict();
| JavaScript |
/**
* @version $Id: k2.js 1965 2013-04-29 16:01:44Z lefteris.kavadas $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
var K2JVersion;
var selectsInstance;
$K2(document).ready(function() {
// Set the selects instance to allow inheritance of jQuery chosen bindings
if ( typeof (K2JVersion) !== 'undefined' && K2JVersion === '30') {
selectsInstance = jQuery;
} else {
selectsInstance = $K2;
}
// Generic function to get URL params passed in .js script include
function getUrlParams(targetScript, varName) {
var scripts = document.getElementsByTagName('script');
var scriptCount = scripts.length;
for (var a = 0; a < scriptCount; a++) {
var scriptSrc = scripts[a].src;
if (scriptSrc.indexOf(targetScript) >= 0) {
varName = varName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var re = new RegExp("[\\?&]" + varName + "=([^&#]*)");
var parsedVariables = re.exec(scriptSrc);
if (parsedVariables !== null) {
return parsedVariables[1];
}
}
}
}
// Set the site root path
var K2SitePath = getUrlParams('k2.js', 'sitepath');
// Common functions
$K2('#jToggler').click(function() {
if ($K2(this).attr('checked')) {
$K2('input[id^=cb]').attr('checked', true);
$K2('input[name=boxchecked]').val($K2('input[id^=cb]:checked').length);
} else {
$K2('input[id^=cb]').attr('checked', false);
$K2('input[name=boxchecked]').val('0');
}
});
$K2('#k2SubmitButton').click(function() {
this.form.submit();
});
$K2('#k2ResetButton').click(function(event) {
event.preventDefault();
$K2('.k2AdminTableFilters input').val('');
$K2('.k2AdminTableFilters option').removeAttr('selected');
this.form.submit();
});
selectsInstance('.k2AdminTableFilters select').change(function() {
this.form.submit();
});
// View specific functions
if ($K2('#k2AdminContainer').length > 0) {
var view = $K2('#k2AdminContainer input[name=view]').val();
} else {
var view = $K2('#k2FrontendContainer input[name=view]').val();
}
$K2('.k2ReportUserButton').click(function(event) {
event.preventDefault();
if (view == 'comments') {
var alert = K2Language[2];
} else {
var alert = K2Language[0];
}
if (confirm(alert)) {
window.location.href = $K2(this).attr('href');
}
});
switch(view) {
case 'comments':
var flag = false;
$K2('.editComment').click(function(event) {
event.preventDefault();
if (flag) {
alert(K2Language[0]);
return;
}
flag = true;
var commentID = $K2(this).attr('rel');
var target = $K2('#k2Comment' + commentID + ' .commentText');
var value = target.text();
$K2('#k2Comment' + commentID + ' input').val(value);
target.empty();
var textarea = $K2('<textarea/>', {
name : 'comment',
rows : '5',
cols : '40'
});
textarea.html(value).appendTo(target);
textarea.focus();
$K2('#k2Comment' + commentID + ' .commentToolbar a').css('display', 'inline');
$K2(this).css('display', 'none');
});
$K2('.closeComment').click(function(event) {
event.preventDefault();
flag = false;
var commentID = $K2(this).attr('rel');
var target = $K2('#k2Comment' + commentID + ' .commentText');
var value = $K2('#k2Comment' + commentID + ' input').val();
target.html(value);
$K2('#k2Comment' + commentID + ' .commentToolbar a').css('display', 'none');
$K2('#k2Comment' + commentID + ' .commentToolbar a.editComment').css('display', 'inline');
});
$K2('.saveComment').click(function(event) {
event.preventDefault();
flag = false;
var commentID = $K2(this).attr('rel');
var target = $K2('#k2Comment' + commentID + ' .commentText');
var value = $K2('#k2Comment' + commentID + ' .commentText textarea').val();
$K2('#task').val('saveComment');
$K2('#commentID').val(commentID);
$K2('#commentText').val(value);
var log = $K2('#k2Comment' + commentID + ' .k2CommentsLog');
log.addClass('k2CommentsLoader');
$K2.ajax({
url : 'index.php',
type : 'post',
dataType : 'json',
data : $K2('#adminForm').serialize(),
success : function(result) {
target.html(result.comment);
$K2('#k2Comment' + commentID + ' input').val(result.comment);
$K2('#task').val('');
log.removeClass('k2CommentsLoader').html(result.message).delay(3000).fadeOut();
}
});
$K2('#k2Comment' + commentID + ' .commentToolbar a').css('display', 'none');
$K2('#k2Comment' + commentID + ' .commentToolbar a.editComment').css('display', 'inline');
});
if ($K2('input[name=isSite]').val() == 1) {
$K2('.k2CommentsPagination a').click(function(event) {
var url = $K2(this).attr('href').split('limitstart=');
event.preventDefault();
$K2('input[name=limitstart]').val(url[1]);
Joomla.submitform();
});
}
break;
case 'extrafield':
if ($K2('#groups').val() > 0) {
$K2('#groupContainer').fadeOut(0);
}
selectsInstance('#groups').change(function() {
var selectedValue = selectsInstance(this).val();
if (selectedValue == 0) {
$K2('#group').val('');
$K2('#isNew').val('1');
$K2('#groupContainer').fadeIn('slow');
} else {
$K2('#groupContainer').fadeOut('slow', function() {
$K2('#group').val(selectedValue);
$K2('#isNew').val('0');
});
}
});
if ($K2('input[name=id]').val()) {
newField = 0;
} else {
newField = 1;
}
if (!newField) {
var values = $K2.parseJSON($K2('#value').val());
} else {
var values = new Array();
values[0] = " ";
}
renderExtraFields($K2('#type').val(), values, newField);
selectsInstance('#type').change(function() {
var selectedType = selectsInstance(this).val();
$K2('#k2ExtraFieldsShowNullFlag').fadeOut('slow');
$K2('#k2ExtraFieldsDisplayInFrontEndFlag').fadeOut('slow');
$K2('#k2ExtraFieldsRequiredFlag').fadeOut('slow');
$K2('#exFieldsTypesDiv').fadeOut('slow', function() {
$K2('#exFieldsTypesDiv').empty();
renderExtraFields(selectedType, values, newField);
$K2('#exFieldsTypesDiv').fadeIn('slow');
if(selectedType === 'select' || selectedType === 'multipleSelect') {
$K2('#k2ExtraFieldsShowNullFlag').fadeIn('slow');
}
if(selectedType !== 'header') {
$K2('#k2ExtraFieldsRequiredFlag').fadeIn('slow');
}
if(selectedType === 'header') {
$K2('#k2ExtraFieldsDisplayInFrontEndFlag').fadeIn('slow');
}
});
});
extraFieldsImage();
break;
case 'usergroup':
var value = $K2('input[name=categories]:checked').val();
if (value == 'all') {
selectsInstance('#paramscategories').attr('disabled', 'disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).attr('disabled', 'disabled');
selectsInstance(this).attr('selected', 'selected');
});
} else if (value == 'none') {
selectsInstance('#paramscategories').attr('disabled', 'disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).attr('disabled', 'disabled');
selectsInstance(this).removeAttr('selected');
});
} else {
selectsInstance('#paramscategories').removeAttr('disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).removeAttr('disabled');
});
}
selectsInstance('#categories-all').click(function() {
selectsInstance('#paramscategories').attr('disabled', 'disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).attr('disabled', 'disabled');
selectsInstance(this).attr('selected', 'selected');
});
selectsInstance("#paramscategories").trigger("liszt:updated");
});
selectsInstance('#categories-none').click(function() {
selectsInstance('#paramscategories').attr('disabled', 'disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).attr('disabled', 'disabled');
selectsInstance(this).removeAttr('selected');
});
selectsInstance("#paramscategories").trigger("liszt:updated");
});
selectsInstance('#categories-select').click(function() {
selectsInstance('#paramscategories').removeAttr('disabled');
selectsInstance('#paramscategories option').each(function() {
selectsInstance(this).removeAttr('disabled');
});
selectsInstance("#paramscategories").trigger("liszt:updated");
});
break;
case 'category':
$K2('#k2Accordion').accordion({
collapsible : true,
autoHeight : false
});
$K2('#k2Tabs').tabs();
$K2('#k2ImageBrowseServer').click(function(event) {
event.preventDefault();
SqueezeBox.initialize();
SqueezeBox.fromElement(this, {
handler : 'iframe',
url : K2BasePath + 'index.php?option=com_k2&view=media&type=image&tmpl=component&fieldID=existingImageValue',
size : {
x : 800,
y : 434
}
});
});
break;
case 'item':
$K2('#k2Accordion').accordion({
collapsible : true,
autoHeight : false
});
$K2('#k2Tabs').tabs();
if ( typeof (K2ActiveVideoTab) === 'undefined') {
$K2('#k2VideoTabs').tabs();
} else {
$K2('#k2VideoTabs').tabs({
selected : K2ActiveVideoTab
});
}
$K2('#k2ToggleSidebar').click(function(event) {
event.preventDefault();
$K2('#adminFormK2Sidebar').toggle();
});
$K2('#catid option[disabled]').css('color', '#808080');
setTimeout(function() {
initExtraFieldsEditor();
}, 1000);
$K2('.deleteAttachmentButton').click(function(event) {
event.preventDefault();
if (confirm(K2Language[3])) {
var element = $K2(this).parent().parent();
var url = $K2(this).attr('href');
$K2.ajax({
url : url,
type : 'get',
success : function() {
$K2(element).fadeOut('fast', function() {
$K2(element).remove();
});
}
});
}
});
$K2('#resetHitsButton').click(function(event) {
event.preventDefault();
Joomla.submitbutton('resetHits');
});
$K2('#resetRatingButton').click(function(event) {
event.preventDefault();
Joomla.submitbutton('resetRating');
});
$K2('#addAttachmentButton').click(function(event) {
event.preventDefault();
addAttachment();
});
$K2('#newTagButton').click(function() {
var log = $K2('#tagsLog');
log.empty().addClass('tagsLoading');
var tag = $K2('#tag').val();
var url = 'index.php?option=com_k2&view=item&task=tag&tag=' + tag;
$K2.ajax({
url : url,
type : 'get',
dataType : 'json',
success : function(response) {
if (response.status == 'success') {
var option = $K2('<option/>', {
value : response.id
}).html(response.name).appendTo($K2('#tags'));
}
log.html(response.msg);
log.removeClass('tagsLoading');
}
});
});
$K2('#addTagButton').click(function() {
$K2('#tags option:selected').each(function() {
$K2(this).appendTo($K2('#selectedTags'));
});
});
$K2('#removeTagButton').click(function() {
$K2('#selectedTags option:selected').each(function(el) {
$K2(this).appendTo($K2('#tags'));
});
});
selectsInstance('#catid').change(function() {
if (selectsInstance(this).find('option:selected').attr('disabled')) {
alert(K2Language[4]);
selectsInstance(this).val('0');
return;
}
var selectedValue = $K2(this).val();
var url = K2BasePath + 'index.php?option=com_k2&view=item&task=extraFields&cid=' + selectedValue + '&id=' + $K2('input[name=id]').val();
$K2('#extraFieldsContainer').fadeOut('slow', function() {
$K2.ajax({
url : url,
type : 'get',
success : function(response) {
$K2('#extraFieldsContainer').html(response);
initExtraFieldsEditor();
$K2('img.calendar').each(function() {
inputFieldID = $K2(this).prev().attr('id');
imgFieldID = $K2(this).attr('id');
Calendar.setup({
inputField : inputFieldID,
ifFormat : "%Y-%m-%d",
button : imgFieldID,
align : "Tl",
singleClick : true
});
});
$K2('#extraFieldsContainer').fadeIn('slow');
}
});
});
});
$K2('#k2ImageBrowseServer').click(function(event) {
event.preventDefault();
SqueezeBox.initialize();
SqueezeBox.fromElement(this, {
handler : 'iframe',
url : K2BasePath + 'index.php?option=com_k2&view=media&type=image&tmpl=component&fieldID=existingImageValue',
size : {
x : 800,
y : 434
}
});
});
$K2('#k2MediaBrowseServer').click(function(event) {
event.preventDefault();
SqueezeBox.initialize();
SqueezeBox.fromElement(this, {
handler : 'iframe',
url : K2BasePath + 'index.php?option=com_k2&view=media&type=video&tmpl=component&fieldID=remoteVideo',
size : {
x : 800,
y : 434
}
});
});
$K2('#itemAttachments').on('click', '.k2AttachmentBrowseServer', function(event) {
event.preventDefault();
var k2ActiveAttachmentField = $K2(this).next();
k2ActiveAttachmentField.attr('id', 'k2ActiveAttachment');
SqueezeBox.initialize();
SqueezeBox.fromElement(this, {
handler : 'iframe',
url : K2BasePath + 'index.php?option=com_k2&view=media&type=attachment&tmpl=component&fieldID=k2ActiveAttachment',
size : {
x : 800,
y : 434
},
onClose : function() {
k2ActiveAttachmentField.removeAttr('id');
}
});
});
$K2('.tagRemove').click(function(event) {
event.preventDefault();
$K2(this).parent().remove();
});
$K2('ul.tags').click(function() {
$K2('#search-field').focus();
});
$K2('#search-field').keypress(function(event) {
if (event.which == '13') {
if ($K2(this).val() != '') {
$K2('<li class="addedTag">' + $K2(this).val() + '<span class="tagRemove" onclick="$K2(this).parent().remove();">x</span><input type="hidden" value="' + $K2(this).val() + '" name="tags[]"></li>').insertBefore('.tags .tagAdd');
$K2(this).val('');
}
}
});
$K2('#search-field').autocomplete({
source : function(request, response) {
$K2.ajax({
type : 'post',
url : K2SitePath + 'index.php?option=com_k2&view=item&task=tags',
data : 'q=' + request.term,
dataType : 'json',
success : function(data) {
$K2('#search-field').removeClass('tagsLoading');
response($K2.map(data, function(item) {
return item;
}));
}
});
},
minLength : 3,
select : function(event, ui) {
$K2('<li class="addedTag">' + ui.item.label + '<span class="tagRemove" onclick="$K2(this).parent().remove();">x</span><input type="hidden" value="' + ui.item.value + '" name="tags[]"></li>').insertBefore('.tags .tagAdd');
this.value = '';
return false;
},
search : function(event, ui) {
$K2('#search-field').addClass('tagsLoading');
}
});
if ($K2('input[name=isSite]').val() == 1) {
parent.$('sbox-overlay').removeEvents('click');
parent.$('sbox-btn-close').removeEvents('click');
var elements = [parent.$K2('#sbox-btn-close'), $K2('#toolbar-cancel a')];
$K2.each(elements, function(index, element) {
element.unbind();
element.click(function(event) {
event.preventDefault();
if ($K2('input[name=id]').val()) {
$K2.ajax({
type : 'get',
cache : false,
url : K2SitePath + 'index.php?option=com_k2&view=item&task=checkin&cid=' + $K2('input[name=id]').val() + '&lang=' + $K2('input[name=lang]').val(),
success : function() {
if (window.opener) {
window.opener.location.reload();
} else {
parent.window.location.reload();
}
if ( typeof (window.parent.SqueezeBox.close == 'function')) {
window.parent.SqueezeBox.close();
} else {
parent.$K2('#sbox-window').close();
}
if (window.opener) {
window.close();
}
}
});
} else {
if ( typeof (window.parent.SqueezeBox.close == 'function')) {
window.parent.SqueezeBox.close();
} else {
parent.$K2('#sbox-window').close();
}
if (window.opener) {
window.close();
}
}
});
});
}
extraFieldsImage();
break;
}
});
// Extra fields validation
function validateExtraFields() {
$K2('.k2Required').removeClass('k2Invalid');
$K2('#tabExtraFields a').removeClass('k2Invalid');
var response = new Object();
var efResults = [];
response.isValid = true;
response.errorFields = new Array();
$K2('.k2Required').each(function() {
var id = $K2(this).attr('id');
var value;
if ($K2(this).hasClass('k2ExtraFieldEditor')) {
if ( typeof tinymce != 'undefined') {
var value = tinyMCE.get(id).getContent()
}
} else {
var value = $K2(this).val();
}
if (($K2.trim(value) === '') || ($K2(this).hasClass('k2ExtraFieldEditor') && $K2.trim(value) === '<p></p>')) {
$K2(this).addClass('k2Invalid');
response.isValid = false;
var label = $K2('label[for="' + id + '"]').text();
response.errorFields.push(label);
}
});
$K2.each(response.errorFields, function(key, value) {
efResults.push('<li>' + value + '</li>');
});
if(response.isValid === false) {
$K2('#k2ExtraFieldsMissing').html(efResults);
$K2('#k2ExtraFieldsValidationResults').css('display','block');
$K2('#tabExtraFields a').addClass('k2Invalid');
}
return response.isValid;
}
// Extra Fields image field
function extraFieldsImage() {
$K2('#extraFieldsContainer').on('click', '.k2ExtraFieldImageButton', function(event) {
event.preventDefault();
var href = $K2(this).attr('href');
SqueezeBox.initialize();
SqueezeBox.fromElement(this, {
handler : 'iframe',
url : K2BasePath + href,
size : {
x : 800,
y : 434
}
});
});
}
// If we are in Joomla! 1.5 define the functions for validation
if ( typeof (Joomla) === 'undefined') {
var Joomla = {};
Joomla.submitbutton = function(pressbutton) {
submitform(pressbutton);
};
function submitbutton(pressbutton) {
Joomla.submitbutton(pressbutton);
}
}
// Media manager
function elFinderUpdate(fieldID, value) {
$K2('#' + fieldID).val(value);
if ( typeof (window.parent.SqueezeBox.close == 'function')) {
SqueezeBox.close();
} else {
parent.$K2('#sbox-window').close();
}
}
// Extra fields
function addOption() {
var div = $K2('<div/>').appendTo($K2('#select_dd_options'));
var input = $K2('<input/>', {
name : 'option_name[]',
type : 'text'
}).appendTo(div);
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'hidden'
}).appendTo(div);
var input = $K2('<input/>', {
value : K2Language[0],
type : 'button'
}).appendTo(div);
input.click(function() {
$K2(this).parent().remove();
})
}
function renderExtraFields(fieldType, fieldValues, isNewField) {
var target = $K2('#exFieldsTypesDiv');
var currentType = $K2('#type').val();
switch (fieldType) {
case 'textfield':
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'text'
}).appendTo(target);
var notice = $K2('<span/>').html('(' + K2Language[1] + ')').appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].value);
}
break;
case 'labels':
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'text'
}).appendTo(target);
var notice = $K2('<span/>').html(K2Language[2] + ' (' + K2Language[1] + ')').appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].value);
}
break;
case 'textarea':
var textarea = $K2('<textarea/>', {
name : 'option_value[]',
cols : '40',
rows : '10'
}).appendTo(target);
var br = $K2('<br/>').appendTo(target);
var label = $K2('<label/>').html(K2Language[17]).appendTo(target);
var input = $K2('<input/>', {
name : 'option_rows[]',
type : 'text'
}).appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].rows);
}
var br = $K2('<br/>').appendTo(target);
var label = $K2('<label/>').html(K2Language[16]).appendTo(target);
var input = $K2('<input/>', {
name : 'option_cols[]',
type : 'text'
}).appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].cols);
}
var br = $K2('<br/>').appendTo(target);
var label = $K2('<label/>').html(K2Language[3]).appendTo(target);
var input = $K2('<input/>', {
name : 'option_editor[]',
type : 'checkbox',
value : '1'
}).appendTo(target);
var br = $K2('<br/>').appendTo(target);
var br = $K2('<br/>').appendTo(target);
var notice = $K2('<span/>').html('(' + K2Language[4] + ')').appendTo(target);
if (!isNewField && currentType == fieldType) {
textarea.val(fieldValues[0].value);
if (fieldValues[0].editor) {
input.attr('checked', true);
} else {
input.attr('checked', false);
}
}
break;
case 'select':
case 'multipleSelect':
case 'radio':
var input = $K2('<input/>', {
value : K2Language[5],
type : 'button'
}).appendTo(target);
input.click(function() {
addOption();
});
var br = $K2('<br/>').appendTo(target);
var div = $K2('<div/>', {
id : 'select_dd_options'
}).appendTo(target);
if (isNewField || currentType != fieldType) {
addOption();
} else {
$K2.each(fieldValues, function(index, value) {
var div = $K2('<div/>').appendTo($K2('#select_dd_options'));
var input = $K2('<input/>', {
name : 'option_name[]',
type : 'text',
value : value.name
}).appendTo(div);
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'hidden',
value : value.value
}).appendTo(div);
var input = $K2('<input/>', {
value : K2Language[0],
type : 'button'
}).appendTo(div);
input.click(function() {
$K2(this).parent().remove();
})
});
}
break;
case 'link':
var label = $K2('<label/>').html(K2Language[6]).appendTo(target);
var inputName = $K2('<input/>', {
name : 'option_name[]',
type : 'text'
}).appendTo(target);
var br = $K2('<br/>').appendTo(target);
var label = $K2('<label/>').html(K2Language[7]).appendTo(target);
var inputValue = $K2('<input/>', {
name : 'option_value[]',
type : 'text'
}).appendTo(target);
var br = $K2('<br/>').appendTo(target);
var label = $K2('<label/>').html(K2Language[8]).appendTo(target);
var select = $K2('<select/>', {
name : 'option_target[]'
}).appendTo(target);
var option = $K2('<option/>', {
value : 'same'
}).html(K2Language[9]).appendTo(select);
var option = $K2('<option/>', {
value : 'new'
}).html(K2Language[10]).appendTo(select);
var option = $K2('<option/>', {
value : 'popup'
}).html(K2Language[11]).appendTo(select);
var option = $K2('<option/>', {
value : 'lightbox'
}).html(K2Language[12]).appendTo(select);
var br = $K2('<br/>').appendTo(target);
var br = $K2('<br/>').appendTo(target);
var notice = $K2('<span/>').html('(' + K2Language[4] + ')').appendTo(target);
if (!isNewField && currentType == fieldType) {
inputName.val(fieldValues[0].name);
inputValue.val(fieldValues[0].value);
select.children().each(function() {
if ($K2(this).val() == fieldValues[0].target) {
$K2(this).attr('selected', 'selected');
}
});
}
break;
case 'csv':
var input = $K2('<input/>', {
name : 'csv_file',
type : 'file'
}).appendTo(target);
var inputValue = $K2('<input/>', {
name : 'option_value[]',
type : 'hidden'
}).appendTo(target);
if (!isNewField && currentType == fieldType) {
inputValue.val($K2.parseJSON(fieldValues[0].value));
var table = $K2('<table/>', {
'class' : 'csvTable'
}).appendTo(target);
fieldValues[0].value.each(function(row, index) {
var tr = $K2('<tr/>').appendTo(table);
row.each(function(cell) {
if (index > 0) {
var td = $K2('<td/>').html(cell).appendTo(tr);
} else {
var th = $K2('<th/>').html(cell).appendTo(tr);
}
})
});
var label = $K2('<label/>').html(K2Language[13]).appendTo(target);
var input = $K2('<input/>', {
name : 'K2ResetCSV',
type : 'checkbox'
}).appendTo(target);
var br = $K2('<br/>', {
'class' : 'clr'
}).appendTo(target);
}
var notice = $K2('<span/>').html('(' + K2Language[1] + ')').appendTo(target);
break;
case 'date':
var id = 'k2DateField' + $K2.now();
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'text',
id : id,
value : fieldValues[0].value,
readonly : 'readonly'
}).appendTo(target);
var img = $K2('<img/>', {
id : id + '_img',
'class' : 'calendar',
src : 'templates/system/images/calendar.png',
alt : K2Language[14]
}).appendTo(target);
Calendar.setup({
inputField : id,
ifFormat : "%Y-%m-%d",
button : id + '_img',
align : "Tl",
singleClick : true
});
var notice = $K2('<span/>').html('(' + K2Language[1] + ')').appendTo(target);
break;
case 'image':
var id = 'K2ExtraFieldImage_'+new Date().getTime();
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'text',
id: id
}).appendTo(target);
var a = $K2('<a/>', {
'href' : 'index.php?option=com_k2&view=media&type=image&tmpl=component&fieldID='+id,
'class' : 'k2ExtraFieldImageButton'
}).html('Select').appendTo(target);
var notice = $K2('<span/>').html('(' + K2Language[1] + ')').appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].value);
}
break;
case 'header':
target.html(' - ');
var input = $K2('<input/>', {
name : 'option_value[]',
type : 'hidden'
}).appendTo(target);
if (!isNewField && currentType == fieldType) {
input.val(fieldValues[0].value);
}
break;
default:
var title = $K2('<span/>', {
'class' : 'notice'
}).html(K2Language[15]).appendTo(target);
break;
}
}
function initExtraFieldsEditor() {
$K2('.k2ExtraFieldEditor').each(function() {
var id = $K2(this).attr('id');
if ( typeof tinymce != 'undefined') {
if (tinyMCE.get(id)) {
tinymce.EditorManager.remove(tinyMCE.get(id));
}
tinyMCE.execCommand('mceAddControl', false, id);
} else {
new nicEditor({
fullPanel : true,
maxHeight : 180,
iconsPath : K2SitePath + 'media/k2/assets/images/system/nicEditorIcons.gif'
}).panelInstance($K2(this).attr('id'));
}
});
}
function syncExtraFieldsEditor() {
$K2('.k2ExtraFieldEditor').each(function() {
editor = nicEditors.findEditor($K2(this).attr('id'));
var content = editor && editor.getContent();
if ( typeof editor != 'undefined') {
if (content == '<br>' || content == '<br />') {
editor.setContent('');
}
editor.saveContent();
}
});
if(K2JVersion === '30') {
onK2EditorSave();
}
}
function addAttachment() {
var div = $K2('<div/>', {
style : 'border-top: 1px dotted #ccc; margin: 4px; padding: 10px;'
}).appendTo($K2('#itemAttachments'));
var input = $K2('<input/>', {
name : 'attachment_file[]',
type : 'file'
}).appendTo(div);
var label = $K2('<a/>', {
href : 'index.php?option=com_k2&view=media&type=attachment&tmpl=component&fieldID=k2ActiveAttachment',
'class' : 'k2AttachmentBrowseServer'
}).html(K2Language[5]).appendTo(div);
var input = $K2('<input/>', {
name : 'attachment_existing_file[]',
type : 'text'
}).appendTo(div);
var input = $K2('<input/>', {
value : K2Language[0],
type : 'button'
}).appendTo(div);
input.click(function() {
$K2(this).parent().remove();
});
var br = $K2('<br/>').appendTo(div);
var label = $K2('<label/>').html(K2Language[1]).appendTo(div);
var input = $K2('<input/>', {
name : 'attachment_title[]',
type : 'text',
'class' : 'linkTitle'
}).appendTo(div);
var br = $K2('<br/>').appendTo(div);
var label = $K2('<label/>').html(K2Language[2]).appendTo(div);
var textarea = $K2('<textarea/>', {
name : 'attachment_title_attribute[]',
cols : '30',
rows : '3'
}).appendTo(div);
}
function jSelectUser(id, name) {
$K2('#k2Author').html(name);
$K2('input[name=created_by]').val(id);
if ( typeof (window.parent.SqueezeBox.close == 'function')) {
SqueezeBox.close();
} else {
parent.$K2('#sbox-window').close();
}
} | JavaScript |
/**
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
window.addEvent('domready', function(){
var ajax_structure = {
onSuccess: function(msg, responseXML)
{
try {
var updateInfoList = JSON.decode(msg, true);
} catch(e) {
// An error occured
document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR);
}
if (updateInfoList instanceof Array) {
if (updateInfoList.length < 1) {
// No updates
document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.UPTODATE);
} else {
var updateString = plg_quickicon_extensionupdate_text.UPDATEFOUND.replace("%s", updateInfoList.length);
document.id('plg_quickicon_extensionupdate').getElements('span').set('html', updateString);
}
} else {
// An error occured
document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR);
}
},
onFailure: function(req) {
// An error occured
document.id('plg_quickicon_extensionupdate').getElements('span').set('html', plg_quickicon_extensionupdate_text.ERROR);
},
url: plg_quickicon_extensionupdate_ajax_url
};
ajax_object = new Request(ajax_structure);
ajax_object.send('eid=0&skip=700');
}); | JavaScript |
var Observer = new Class({
Implements: [Options, Events],
options: {
periodical: false,
delay: 1000
},
initialize: function (el, onFired, options) {
this.element = document.id(el) || $document.id(el);
this.addEvent('onFired', onFired);
this.setOptions(options);
this.bound = this.changed.bind(this);
this.resume();
},
changed: function () {
var value = this.element.get('value');
if ($equals(this.value, value)) return;
this.clear();
this.value = value;
this.timeout = this.onFired.delay(this.options.delay, this);
},
setValue: function (value) {
this.value = value;
this.element.set('value', value);
return this.clear();
},
onFired: function () {
this.fireEvent('onFired', [this.value, this.element]);
},
clear: function () {
clearTimeout(this.timeout || null);
return this;
},
pause: function () {
if (this.timer) clearTimeout(this.timer);
else this.element.removeEvent('keyup', this.bound);
return this.clear();
},
resume: function () {
this.value = this.element.get('value');
if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
else this.element.addEvent('keyup', this.bound);
return this;
}
});
var $equals = function (obj1, obj2) {
return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2));
};
var Autocompleter = new Class({
Implements: [Options, Events],
options: {
minLength: 1,
markQuery: true,
width: 'inherit',
maxChoices: 10,
injectChoice: null,
customChoices: null,
emptyChoices: null,
visibleChoices: true,
className: 'autocompleter-choices',
zIndex: 1000,
delay: 400,
observerOptions: {},
fxOptions: {},
autoSubmit: false,
overflow: false,
overflowMargin: 25,
selectFirst: false,
filter: null,
filterCase: false,
filterSubset: false,
forceSelect: false,
selectMode: true,
choicesMatch: null,
multiple: false,
separator: ', ',
separatorSplit: /\s*[,;]\s*/,
autoTrim: false,
allowDupes: false,
cache: true,
relative: false
},
initialize: function (element, options) {
this.element = document.id(element);
this.setOptions(options);
this.build();
this.observer = new Observer(this.element, this.prefetch.bind(this), Object.merge({}, {
'delay': this.options.delay
}, this.options.observerOptions));
this.queryValue = null;
if (this.options.filter) this.filter = this.options.filter.bind(this);
var mode = this.options.selectMode;
this.typeAhead = (mode == 'type-ahead');
this.selectMode = (mode === true) ? 'selection' : mode;
this.cached = [];
},
build: function () {
if (document.id(this.options.customChoices)) {
this.choices = this.options.customChoices;
} else {
this.choices = new Element('ul', {
'class': this.options.className,
'styles': {
'zIndex': this.options.zIndex
}
}).inject(document.body);
this.relative = false;
if (this.options.relative) {
this.choices.inject(this.element, 'after');
this.relative = this.element.getOffsetParent();
}
this.fix = new OverlayFix(this.choices);
}
if (!this.options.separator.test(this.options.separatorSplit)) {
this.options.separatorSplit = this.options.separator;
}
this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, Object.merge({}, {
'property': 'opacity',
'link': 'cancel',
'duration': 200
}, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
this.element.setProperty('autocomplete', 'off').addEvent((Browser.ie || Browser.safari || Browser.chrome) ? 'keydown' : 'keypress', this.onCommand.bind(this)).addEvent('click', this.onCommand.bind(this, [false])).addEvent('focus', this.toggleFocus.create({
bind: this,
arguments: true,
delay: 100
})).addEvent('blur', this.toggleFocus.create({
bind: this,
arguments: false,
delay: 100
}));
},
destroy: function () {
if (this.fix) this.fix.destroy();
this.choices = this.selected = this.choices.destroy();
},
toggleFocus: function (state) {
this.focussed = state;
if (!state) this.hideChoices(true);
this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element]);
},
onCommand: function (e) {
if (!e && this.focussed) return this.prefetch();
if (e && e.key && !e.shift) {
switch (e.key) {
case 'enter':
if (this.element.value != this.opted) return true;
if (this.selected && this.visible) {
this.choiceSelect(this.selected);
return !!(this.options.autoSubmit);
}
break;
case 'up':
case 'down':
if (!this.prefetch() && this.queryValue !== null) {
var up = (e.key == 'up');
this.choiceOver((this.selected || this.choices)[(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')](this.options.choicesMatch), true);
}
return false;
case 'esc':
case 'tab':
this.hideChoices(true);
break;
}
}
return true;
},
setSelection: function (finish) {
var input = this.selected.inputValue,
value = input;
var start = this.queryValue.length,
end = input.length;
if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
if (this.options.multiple) {
var split = this.options.separatorSplit;
value = this.element.value;
start += this.queryIndex;
end += this.queryIndex;
var old = value.substr(this.queryIndex).split(split, 1)[0];
value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
if (finish) {
var tokens = value.split(this.options.separatorSplit).filter(function (entry) {
return this.test(entry);
}, /[^\s,]+/);
if (!this.options.allowDupes) tokens = [].combine(tokens);
var sep = this.options.separator;
value = tokens.join(sep) + sep;
end = value.length;
}
}
this.observer.setValue(value);
this.opted = value;
if (finish || this.selectMode == 'pick') start = end;
this.element.selectRange(start, end);
this.fireEvent('onSelection', [this.element, this.selected, value, input]);
},
showChoices: function () {
var match = this.options.choicesMatch,
first = this.choices.getFirst(match);
this.selected = this.selectedValue = null;
if (this.fix) {
var pos = this.element.getCoordinates(this.relative),
width = this.options.width || 'auto';
this.choices.setStyles({
'left': pos.left,
'top': pos.bottom,
'width': (width === true || width == 'inherit') ? pos.width : width
});
}
if (!first) return;
if (!this.visible) {
this.visible = true;
this.choices.setStyle('display', '');
if (this.fx) this.fx.start(1);
this.fireEvent('onShow', [this.element, this.choices]);
}
if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
var items = this.choices.getChildren(match),
max = this.options.maxChoices;
var styles = {
'overflowY': 'hidden',
'height': ''
};
this.overflown = false;
if (items.length > max) {
var item = items[max - 1];
styles.overflowY = 'scroll';
styles.height = item.getCoordinates(this.choices).bottom;
this.overflown = true;
};
this.choices.setStyles(styles);
this.fix.show();
if (this.options.visibleChoices) {
var scroll = document.getScroll(),
size = document.getSize(),
coords = this.choices.getCoordinates();
if (coords.right > scroll.x + size.x) scroll.x = coords.right - size.x;
if (coords.bottom > scroll.y + size.y) scroll.y = coords.bottom - size.y;
window.scrollTo(Math.min(scroll.x, coords.left), Math.min(scroll.y, coords.top));
}
},
// TODO: No $arguments in MT 1.3
hideChoices: function (clear) {
if (clear) {
var value = this.element.value;
if (this.options.forceSelect) value = this.opted;
if (this.options.autoTrim) {
value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator);
}
this.observer.setValue(value);
}
if (!this.visible) return;
this.visible = false;
if (this.selected) this.selected.removeClass('autocompleter-selected');
this.observer.clear();
var hide = function () {
this.choices.setStyle('display', 'none');
this.fix.hide();
}.bind(this);
if (this.fx) this.fx.start(0).chain(hide);
else hide();
this.fireEvent('onHide', [this.element, this.choices]);
},
prefetch: function () {
var value = this.element.value,
query = value;
if (this.options.multiple) {
var split = this.options.separatorSplit;
var values = value.split(split);
var index = this.element.getSelectedRange().start;
var toIndex = value.substr(0, index).split(split);
var last = toIndex.length - 1;
index -= toIndex[last].length;
query = values[last];
}
if (query.length < this.options.minLength) {
this.hideChoices();
} else {
if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
if (this.visible) return false;
this.showChoices();
} else {
this.queryValue = query;
this.queryIndex = index;
if (!this.fetchCached()) this.query();
}
}
return true;
},
fetchCached: function () {
return false;
if (!this.options.cache || !this.cached || !this.cached.length || this.cached.length >= this.options.maxChoices || this.queryValue) return false;
this.update(this.filter(this.cached));
return true;
},
update: function (tokens) {
this.choices.empty();
this.cached = tokens;
var type = tokens && typeOf(tokens);
if (!type || (type == 'array' && !tokens.length) || (type == 'hash' && !tokens.getLength())) {
(this.options.emptyChoices || this.hideChoices).call(this);
} else {
if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
tokens.each(this.options.injectChoice ||
function (token) {
var choice = new Element('li', {
'html': this.markQueryValue(token)
});
choice.inputValue = token;
this.addChoiceEvents(choice).inject(this.choices);
}, this);
this.showChoices();
}
},
choiceOver: function (choice, selection) {
if (!choice || choice == this.selected) return;
if (this.selected) this.selected.removeClass('autocompleter-selected');
this.selected = choice.addClass('autocompleter-selected');
this.fireEvent('onSelect', [this.element, this.selected, selection]);
if (!this.selectMode) this.opted = this.element.value;
if (!selection) return;
this.selectedValue = this.selected.inputValue;
if (this.overflown) {
var coords = this.selected.getCoordinates(this.choices),
margin = this.options.overflowMargin,
top = this.choices.scrollTop,
height = this.choices.offsetHeight,
bottom = top + height;
if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom);
}
if (this.selectMode) this.setSelection();
},
choiceSelect: function (choice) {
if (choice) this.choiceOver(choice);
this.setSelection(true);
this.queryValue = false;
this.hideChoices();
},
filter: function (tokens) {
return (tokens || this.tokens).filter(function (token) {
return this.test(token);
}, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'));
},
markQueryValue: function (str) {
return (!this.options.markQuery || !this.queryValue) ? str : str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>');
},
addChoiceEvents: function (el) {
return el.addEvents({
'mouseover': this.choiceOver.bind(this, el),
'click': this.choiceSelect.bind(this, el)
});
}
});
var OverlayFix = new Class({
initialize: function (el) {
if (Browser.ie) {
this.element = document.id(el);
this.relative = this.element.getOffsetParent();
this.fix = new Element('iframe', {
'frameborder': '0',
'scrolling': 'no',
'src': 'javascript:false;',
'styles': {
'position': 'absolute',
'border': 'none',
'display': 'none',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
}
}).inject(this.element, 'after');
}
},
show: function () {
if (this.fix) {
var coords = this.element.getCoordinates(this.relative);
delete coords.right;
delete coords.bottom;
this.fix.setStyles(Object.append(coords, {
'display': '',
'zIndex': (this.element.getStyle('zIndex') || 1) - 1
}));
}
return this;
},
hide: function () {
if (this.fix) this.fix.setStyle('display', 'none');
return this;
},
destroy: function () {
if (this.fix) this.fix = this.fix.destroy();
}
});
Element.implement({
getSelectedRange: function () {
if (!Browser.ie) return {
start: this.selectionStart,
end: this.selectionEnd
};
var pos = {
start: 0,
end: 0
};
var range = this.getDocument().selection.createRange();
if (!range || range.parentElement() != this) return pos;
var dup = range.duplicate();
if (this.type == 'text') {
pos.start = 0 - dup.moveStart('character', -100000);
pos.end = pos.start + range.text.length;
} else {
var value = this.value;
var offset = value.length - value.match(/[\n\r]*$/)[0].length;
dup.moveToElementText(this);
dup.setEndPoint('StartToEnd', range);
pos.end = offset - dup.text.length;
dup.setEndPoint('StartToStart', range);
pos.start = offset - dup.text.length;
}
return pos;
},
selectRange: function (start, end) {
if (Browser.ie) {
var diff = this.value.substr(start, end - start).replace(/\r/g, '').length;
start = this.value.substr(0, start).replace(/\r/g, '').length;
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', start + diff);
range.moveStart('character', start);
range.select();
} else {
this.focus();
this.setSelectionRange(start, end);
}
return this;
}
});
Autocompleter.Base = Autocompleter;
Autocompleter.Request = new Class({
Extends: Autocompleter,
options: {
postData: {},
ajaxOptions: {},
postVar: 'value'
},
query: function () {
var data = this.options.postData.unlink || {};
data[this.options.postVar] = this.queryValue;
var indicator = document.id(this.options.indicator);
if (indicator) indicator.setStyle('display', '');
var cls = this.options.indicatorClass;
if (cls) this.element.addClass(cls);
this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
this.request.send({
'data': data
});
},
queryResponse: function () {
var indicator = document.id(this.options.indicator);
if (indicator) indicator.setStyle('display', 'none');
var cls = this.options.indicatorClass;
if (cls) this.element.removeClass(cls);
return this.fireEvent('onComplete', [this.element, this.request]);
}
});
Autocompleter.Request.JSON = new Class({
Extends: Autocompleter.Request,
initialize: function (el, url, options) {
this.parent(el, options);
this.request = new Request.JSON(Object.merge({}, {
'url': url,
'link': 'cancel'
}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
},
queryResponse: function (response) {
this.parent();
this.update(response);
}
});
Autocompleter.Request.HTML = new Class({
Extends: Autocompleter.Request,
initialize: function (el, url, options) {
this.parent(el, options);
this.request = new Request.HTML(Object.merge({}, {
'url': url,
'link': 'cancel',
'update': this.choices
}, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this));
},
queryResponse: function (tree, elements) {
this.parent();
if (!elements || !elements.length) {
this.hideChoices();
} else {
this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice ||
function (choice) {
var value = choice.innerHTML;
choice.inputValue = value;
this.addChoiceEvents(choice.set('html', this.markQueryValue(value)));
}, this);
this.showChoices();
}
}
});
Autocompleter.Ajax = {
Base: Autocompleter.Request,
Json: Autocompleter.Request.JSON,
Xhtml: Autocompleter.Request.HTML
};
| JavaScript |
var FinderProgressBar = new Class({
Implements: [Events, Options],
options: {
container: document.body,
boxID: 'progress-bar-box-id',
percentageID: 'progress-bar-percentage-id',
displayID: 'progress-bar-display-id',
startPercentage: 0,
displayText: false,
speed: 10,
step: 1,
allowMore: false,
onComplete: function () {},
onChange: function () {}
},
initialize: function (options) {
this.setOptions(options);
this.options.container = document.id(this.options.container);
this.createElements();
},
createElements: function () {
var box = new Element('div', {
id: this.options.boxID
});
var perc = new Element('div', {
id: this.options.percentageID,
'style': 'width:0px;'
});
perc.inject(box);
box.inject(this.options.container);
if (this.options.displayText) {
var text = new Element('div', {
id: this.options.displayID
});
text.inject(this.options.container);
}
this.set(this.options.startPercentage);
},
calculate: function (percentage) {
return (document.id(this.options.boxID).getStyle('width').replace('px', '') * (percentage / 100)).toInt();
},
animate: function (go) {
var run = false;
var self = this;
if (!self.options.allowMore && go > 100) {
go = 100;
}
self.to = go.toInt();
document.id(self.options.percentageID).set('morph', {
duration: this.options.speed,
link: 'cancel',
onComplete: function () {
self.fireEvent('change', [self.to]);
if (go >= 100) {
self.fireEvent('complete', [self.to]);
}
}
}).morph({
width: self.calculate(go)
});
if (self.options.displayText) {
document.id(self.options.displayID).set('text', self.to + '%');
}
},
set: function (to) {
this.animate(to);
},
step: function () {
this.set(this.to + this.options.step);
}
});
var FinderIndexer = new Class({
totalItems: null,
batchSize: null,
offset: null,
progress: null,
optimized: false,
path: 'index.php?option=com_finder&tmpl=component&format=json',
initialize: function () {
this.offset = 0;
this.progress = 0;
this.pb = new FinderProgressBar({
container: document.id('finder-progress-container'),
startPercentage: 0,
speed: 600,
boxID: 'finder-progress-box',
percentageID: 'finder-progress-perc',
displayID: 'finder-progress-status',
displayText: true
});
this.path = this.path + '&' + document.id('finder-indexer-token').get('name') + '=1';
this.getRequest('indexer.start').send()
},
getRequest: function (task) {
return new Request.JSON({
url: this.path,
method: 'get',
data: 'task=' + task,
onSuccess: this.handleResponse.bind(this),
onFailure: this.handleFailure.bind(this)
});
},
handleResponse: function (json, resp) {
try {
if (json === null) {
throw resp;
}
if (json.error) {
throw json;
}
if (json.start) this.totalItems = json.totalItems;
this.offset += json.batchOffset;
this.updateProgress(json.header, json.message);
if (this.offset < this.totalItems) {
this.getRequest('indexer.batch').send();
} else if (!this.optimized) {
this.optimized = true;
this.getRequest('indexer.optimize').send();
}
} catch (error) {
if (this.pb) document.id(this.pb.options.container).dispose();
try {
if (json.error) {
document.id('finder-progress-header').set('text', json.header).addClass('finder-error');
document.id('finder-progress-message').set('html', json.message).addClass('finder-error');
}
} catch (ignore) {
if (error == '') {
error = Joomla.JText._('COM_FINDER_NO_ERROR_RETURNED');
}
document.id('finder-progress-header').set('text', Joomla.JText._('COM_FINDER_AN_ERROR_HAS_OCCURRED')).addClass('finder-error');
document.id('finder-progress-message').set('html', error).addClass('finder-error');
}
}
return true;
},
handleFailure: function (xhr) {
json = (typeof xhr == 'object' && xhr.responseText) ? xhr.responseText : null;
json = json ? JSON.decode(json, true) : null;
if (this.pb) document.id(this.pb.options.container).dispose();
if (json) {
json = json.responseText != null ? Json.evaluate(json.responseText, true) : json;
}
var header = json ? json.header : Joomla.JText._('COM_FINDER_AN_ERROR_HAS_OCCURRED');
var message = json ? json.message : Joomla.JText._('COM_FINDER_MESSAGE_RETURNED') + ' <br />' + json
document.id('finder-progress-header').set('text', header).addClass('finder-error');
document.id('finder-progress-message').set('html', message).addClass('finder-error');
},
updateProgress: function (header, message) {
this.progress = (this.offset / this.totalItems) * 100;
document.id('finder-progress-header').set('text', header);
document.id('finder-progress-message').set('html', message);
if (this.pb && this.progress < 100) {
this.pb.set(this.progress);
} else if (this.pb) {
document.id(this.pb.options.container).dispose();
this.pb = false;
}
}
});
window.addEvent('domready', function () {
Indexer = new FinderIndexer();
if (typeof window.parent.SqueezeBox == 'object') {
window.parent.SqueezeBox.addEvent('onClose', function () {
window.parent.location.reload(true);
});
}
});
| JavaScript |
var Highlighter = new Class({
options: {
autoUnhighlight: true,
caseSensitive: false,
startElement: false,
endElement: false,
elements: new Array(),
className: 'highlight',
onlyWords: true,
tag: 'span'
},
initialize: function (options) {
this.setOptions(options);
this.getElements(this.options.startElement, this.options.endElement);
this.words = [];
},
highlight: function (words) {
if (words.constructor === String) {
words = [words];
}
if (this.options.autoUnhighlight) {
this.unhighlight(words);
}
var pattern = this.options.onlyWords ? '\b' + pattern + '\b' : '(' + words.join('\\b|\\b') + ')';
var regex = new RegExp(pattern, this.options.caseSensitive ? '' : 'i');
this.options.elements.each(function (el) {
this.recurse(el, regex, this.options.className);
}, this);
return this;
},
unhighlight: function (words) {
if (words.constructor === String) {
words = [words];
}
words.each(function (word) {
word = (this.options.caseSensitive ? word : word.toUpperCase());
if (this.words[word]) {
var elements = $$(this.words[word]);
elements.setProperty('class', '');
elements.each(function (el) {
var tn = document.createTextNode(el.getText());
el.getParent().replaceChild(tn, el);
});
}
}, this);
return this;
},
recurse: function (node, regex, klass) {
if (node.nodeType === 3) {
var match = node.data.match(regex);
if (match) {
var highlight = new Element(this.options.tag);
highlight.addClass(klass);
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
highlight.setProperty('rel', highlight.get('text'));
var comparer = highlight.get('text');
if (!this.options.caseSensitive) {
comparer = highlight.get('text').toUpperCase();
}
if (!this.words[comparer]) {
this.words[comparer] = [];
}
this.words[comparer].push(highlight);
return 1;
}
} else if ((node.nodeType === 1 && node.childNodes) && !/(script|style|textarea|iframe)/i.test(node.tagName) && !(node.tagName === this.options.tag.toUpperCase() && node.className === klass)) {
for (var i = 0; i < node.childNodes.length; i++) {
i += this.recurse(node.childNodes[i], regex, klass);
}
}
return 0;
},
getElements: function (start, end) {
var next = start.getNext();
if (next.id != end.id) {
this.options.elements.include(next);
this.getElements(next, end);
}
}
});
Highlighter.implement(new Options);
window.addEvent('domready', function () {
var start = document.id('highlighter-start');
var end = document.id('highlighter-end');
if (!start || !end || !window.highlight) {
return true;
}
highlighter = new Highlighter({
startElement: start,
endElement: end,
autoUnhighlight: true,
onlyWords: false
}).highlight(window.highlight);
start.dispose();
end.dispose();
}); | JavaScript |
FinderFilter = new Class({
Extends: Fx.Elements,
options: {
onActive: Class.empty,
onBackground: Class.empty,
height: false,
width: true,
opacity: true,
fixedHeight: false,
fixedWidth: 220,
wait: true
},
initialize: function (togglers, elements, container, frame) {
this.togglers = togglers || [];
this.elements = elements || [];
this.container = document.id(container);
this.frame = document.id(frame);
this.effects = {};
if (this.options.opacity) this.effects.opacity = 'fullOpacity';
if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
this.container.setStyle('width', '230px');
this.addEvent('onActive', function (toggler, element) {
element.set('styles', {
'border-top': '1px solid #ccc',
'border-right': '1px solid #ccc',
'border-bottom': '1px solid #ccc',
'overflow': 'auto'
});
this.container.set('styles', {
width: this.container.getStyle('width').toInt() + element.fullWidth
});
coord = element.getCoordinates([this.frame]);
scroller = new Fx.Scroll(frame);
scroller.start(coord.top, coord.left);
});
this.addEvent('onBackground', function () {
el = this.elements[this.active];
el.getElements('input').each(function (n) {
n.removeProperty('checked');
});
});
this.addEvent('onComplete', function () {
el = this.elements[this.active];
if (!el.getStyle('width').toInt()) {
this.container.set('styles', {
'width': this.container.getStyle('width').toInt() - el.fullWidth
});
}
this.active = null;
});
for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
this.elements.each(function (el, i) {
var cbs = el.getElements('input.selector').length;
var cba = 0;
el.getElements('input.selector').each(function (n) {
if (n.getProperty('checked')) {
this.togglers[i].setProperty('checked', 'checked');
cba += 1;
}
}, this);
if (cbs > 0 && cbs === cba && el.getElement('input.branch-selector') != null) {
el.getElement('input.branch-selector').setProperty('checked', 'checked');
}
if (cba) {
this.fireEvent('onActive', [this.togglers[i], el]);
} else {
for (var fx in this.effects) el.setStyle(fx, 0);
}
el.getElement('dt').getElement('input').addEvent('change', function (e) {
if (e.target.getProperty('checked')) {
el.getElements('dd').each(function (dd) {
dd.getElement('input').setProperty('checked', 'checked');
});
} else {
el.getElements('dd').each(function (dd) {
dd.getElement('input').removeProperty('checked');
});
}
});
}, this);
},
addSection: function (toggler, element, pos) {
toggler = document.id(toggler);
element = document.id(element);
var test = this.togglers.contains(toggler);
var len = this.togglers.length;
this.togglers.include(toggler);
this.elements.include(element);
if (len && (!test || pos)) {
pos = Array.pick(pos, len - 1);
toggler.inject(this.togglers[pos], 'before');
element.inject(toggler, 'after');
} else if (this.container && !test) {
toggler.inject(this.container);
element.inject(this.container);
}
var idx = this.togglers.indexOf(toggler);
toggler.addEvent('click', this.toggle.bind(this, idx));
if (this.options.width) element.set('styles', {
'padding-left': 0,
'border-left': 'none',
'padding-right': 0,
'border-right': 'none'
});
element.fullOpacity = 1;
if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
element.set('styles', {'overflow': 'hidden'});
return this;
},
toggle: function (index) {
index = (typeOf(index) == 'element') ? this.elements.indexOf(index) : index;
if (this.timer && this.options.wait) return this;
this.active = index;
var obj = {};
obj[index] = {};
var el = this.elements[index];
if (this.togglers[index].getProperty('checked')) {
for (var fx in this.effects) obj[index][fx] = el[this.effects[fx]];
this.start(obj);
this.fireEvent('onActive', [this.togglers[index], el]);
} else {
for (var fx in this.effects) obj[index][fx] = 0;
this.start(obj);
this.fireEvent('onBackground', [this.togglers[index], el]);
}
return this;
}
});
window.addEvent('domready', function () {
Filter = new FinderFilter(document.getElements('input.toggler'), document.getElements('dl.checklist'), document.id('finder-filter-container'), document.id('finder-filter-window'));
document.id('tax-select-all').addEvent('change', function () {
if (document.id('tax-select-all').getProperty('checked')) {
document.id('finder-filter-window').getElements('input').each(function (input) {
if (input.getProperty('id') != 'tax-select-all') {
input.removeProperty('checked');
}
});
}
});
}); | JavaScript |
window.addEvent('domready', function () {
sm = document.id('system-message');
if (sm) {
sm.addEvent('check', function () {
open = 0;
messages = this.getElements('li');
for (i = 0, n = messages.length; i < n; i++) {
if (messages[i].getProperty('hidden') != 'hidden') {
open++;
}
}
if (open < 1) {
this.remove();
}
});
}
function hideWarning(e) {
new Json.Remote(this.getProperty('link') + '&format=json', {
linkId: this.getProperty('id'),
onComplete: function (response) {
if (response.error == false) {
document.id(this.options.linkId).fireEvent('hide');
document.id('system-message').fireEvent('check');
} else {
alert(response.message);
}
}
}).send();
}
document.id('a.hide-warning').each(function (a) {
a.setProperty('link', a.getProperty('href'));
a.setProperty('href', 'javascript: void(0);');
a.addEvent('hide', function () {
this.getParent().setProperty('hidden', 'hidden');
var mySlider = new Fx.Slide(this.getParent(), {
duration: 300
});
mySlider.slideOut();
});
// TODO: bindWithEvent deprecated in MT 1.3
a.addEvent('click', hideWarning.bindWithEvent(a));
});
});
| JavaScript |
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES implementation in JavaScript (c) Chris Veness 2005-2010 */
/* - see http://csrc.nist.gov/publications/PubsFIPS.html#197 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Aes = {}; // Aes namespace
/**
* AES Cipher function: encrypt 'input' state with Rijndael algorithm
* applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
*
* @param {Number[]} input 16-byte (128-bit) input state array
* @param {Number[][]} w Key schedule as 2D byte-array (Nr+1 x Nb bytes)
* @returns {Number[]} Encrypted output state array
*/
Aes.Cipher = function(input, w) { // main Cipher function [§5.1]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
var state = [[],[],[],[]]; // initialise 4xNb byte-array 'state' with input [§3.4]
for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i];
state = Aes.AddRoundKey(state, w, 0, Nb);
for (var round=1; round<Nr; round++) {
state = Aes.SubBytes(state, Nb);
state = Aes.ShiftRows(state, Nb);
state = Aes.MixColumns(state, Nb);
state = Aes.AddRoundKey(state, w, round, Nb);
}
state = Aes.SubBytes(state, Nb);
state = Aes.ShiftRows(state, Nb);
state = Aes.AddRoundKey(state, w, Nr, Nb);
var output = new Array(4*Nb); // convert state to 1-d array before returning [§3.4]
for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)];
return output;
}
/**
* Perform Key Expansion to generate a Key Schedule
*
* @param {Number[]} key Key as 16/24/32-byte array
* @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes)
*/
Aes.KeyExpansion = function(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nk = key.length/4 // key length (in words): 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
var w = new Array(Nb*(Nr+1));
var temp = new Array(4);
for (var i=0; i<Nk; i++) {
var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
w[i] = r;
}
for (var i=Nk; i<(Nb*(Nr+1)); i++) {
w[i] = new Array(4);
for (var t=0; t<4; t++) temp[t] = w[i-1][t];
if (i % Nk == 0) {
temp = Aes.SubWord(Aes.RotWord(temp));
for (var t=0; t<4; t++) temp[t] ^= Aes.Rcon[i/Nk][t];
} else if (Nk > 6 && i%Nk == 4) {
temp = Aes.SubWord(temp);
}
for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t];
}
return w;
}
/*
* ---- remaining routines are private, not called externally ----
*/
Aes.SubBytes = function(s, Nb) { // apply SBox to state S [§5.1.1]
for (var r=0; r<4; r++) {
for (var c=0; c<Nb; c++) s[r][c] = Aes.Sbox[s[r][c]];
}
return s;
}
Aes.ShiftRows = function(s, Nb) { // shift row r of state S left by r bytes [§5.1.2]
var t = new Array(4);
for (var r=1; r<4; r++) {
for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb]; // shift into temp copy
for (var c=0; c<4; c++) s[r][c] = t[c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
}
Aes.MixColumns = function(s, Nb) { // combine bytes of each col of state S [§5.1.3]
for (var c=0; c<4; c++) {
var a = new Array(4); // 'a' is a copy of the current column from 's'
var b = new Array(4); // 'b' is a•{02} in GF(2^8)
for (var i=0; i<4; i++) {
a[i] = s[i][c];
b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
}
return s;
}
Aes.AddRoundKey = function(state, w, rnd, Nb) { // xor Round Key into state S [§5.1.4]
for (var r=0; r<4; r++) {
for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r];
}
return state;
}
Aes.SubWord = function(w) { // apply SBox to 4-byte word w
for (var i=0; i<4; i++) w[i] = Aes.Sbox[w[i]];
return w;
}
Aes.RotWord = function(w) { // rotate 4-byte word w left by one byte
var tmp = w[0];
for (var i=0; i<3; i++) w[i] = w[i+1];
w[3] = tmp;
return w;
}
// Sbox is pre-computed multiplicative inverse in GF(2^8) used in SubBytes and KeyExpansion [§5.1.1]
Aes.Sbox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16];
// Rcon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
Aes.Rcon = [ [0x00, 0x00, 0x00, 0x00],
[0x01, 0x00, 0x00, 0x00],
[0x02, 0x00, 0x00, 0x00],
[0x04, 0x00, 0x00, 0x00],
[0x08, 0x00, 0x00, 0x00],
[0x10, 0x00, 0x00, 0x00],
[0x20, 0x00, 0x00, 0x00],
[0x40, 0x00, 0x00, 0x00],
[0x80, 0x00, 0x00, 0x00],
[0x1b, 0x00, 0x00, 0x00],
[0x36, 0x00, 0x00, 0x00] ];
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES Counter-mode implementation in JavaScript (c) Chris Veness 2005-2010 */
/* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var AesCtr = {}; // AesCtr namespace
/**
* Encrypt a text using AES encryption in Counter mode of operation
*
* Unicode multi-byte character safe
*
* @param {String} plaintext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {string} Encrypted text
*/
AesCtr.encrypt = function(plaintext, password, nBits) {
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
plaintext = Utf8.encode(plaintext);
password = Utf8.encode(password);
//var t = new Date(); // timer
// use AES itself to encrypt password to get cipher key (using plain password as source for key
// expansion) - gives us well encrypted key
var nBytes = nBits/8; // no bytes in key
var pwBytes = new Array(nBytes);
for (var i=0; i<nBytes; i++) {
pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
}
var key = Aes.Cipher(pwBytes, Aes.KeyExpansion(pwBytes)); // gives us 16-byte key
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
// initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for nonce in 1st 8 bytes,
// block counter in 2nd 8 bytes
var counterBlock = new Array(blockSize);
var nonce = (new Date()).getTime(); // timestamp: milliseconds since 1-Jan-1970
var nonceSec = Math.floor(nonce/1000);
var nonceMs = nonce%1000;
// encode nonce with seconds in 1st 4 bytes, and (repeated) ms part filling 2nd 4 bytes
for (var i=0; i<4; i++) counterBlock[i] = (nonceSec >>> i*8) & 0xff;
for (var i=0; i<4; i++) counterBlock[i+4] = nonceMs & 0xff;
// and convert it to a string to go on the front of the ciphertext
var ctrTxt = '';
for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]);
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
var keySchedule = Aes.KeyExpansion(key);
var blockCount = Math.ceil(plaintext.length/blockSize);
var ciphertxt = new Array(blockCount); // ciphertext as array of strings
for (var b=0; b<blockCount; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff;
for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8)
var cipherCntr = Aes.Cipher(counterBlock, keySchedule); // -- encrypt counter block --
// block size is reduced on final block
var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1;
var cipherChar = new Array(blockLength);
for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] = cipherCntr[i] ^ plaintext.charCodeAt(b*blockSize+i);
cipherChar[i] = String.fromCharCode(cipherChar[i]);
}
ciphertxt[b] = cipherChar.join('');
}
// Array.join is more efficient than repeated string concatenation in IE
var ciphertext = ctrTxt + ciphertxt.join('');
ciphertext = Base64.encode(ciphertext); // encode in base64
//alert((new Date()) - t);
return ciphertext;
}
/**
* Decrypt a text encrypted by AES in counter mode of operation
*
* @param {String} ciphertext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {String} Decrypted text
*/
AesCtr.decrypt = function(ciphertext, password, nBits) {
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
ciphertext = Base64.decode(ciphertext);
password = Utf8.encode(password);
//var t = new Date(); // timer
// use AES to encrypt password (mirroring encrypt routine)
var nBytes = nBits/8; // no bytes in key
var pwBytes = new Array(nBytes);
for (var i=0; i<nBytes; i++) {
pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
}
var key = Aes.Cipher(pwBytes, Aes.KeyExpansion(pwBytes));
key = key.concat(key.slice(0, nBytes-16)); // expand key to 16/24/32 bytes long
// recover nonce from 1st 8 bytes of ciphertext
var counterBlock = new Array(8);
ctrTxt = ciphertext.slice(0, 8);
for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);
// generate key schedule
var keySchedule = Aes.KeyExpansion(key);
// separate ciphertext into blocks (skipping past initial 8 bytes)
var nBlocks = Math.ceil((ciphertext.length-8) / blockSize);
var ct = new Array(nBlocks);
for (var b=0; b<nBlocks; b++) ct[b] = ciphertext.slice(8+b*blockSize, 8+b*blockSize+blockSize);
ciphertext = ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
var plaintxt = new Array(ciphertext.length);
for (var b=0; b<nBlocks; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for (var c=0; c<4; c++) counterBlock[15-c] = ((b) >>> c*8) & 0xff;
for (var c=0; c<4; c++) counterBlock[15-c-4] = (((b+1)/0x100000000-1) >>> c*8) & 0xff;
var cipherCntr = Aes.Cipher(counterBlock, keySchedule); // encrypt counter block
var plaintxtByte = new Array(ciphertext[b].length);
for (var i=0; i<ciphertext[b].length; i++) {
// -- xor plaintxt with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt(i);
plaintxtByte[i] = String.fromCharCode(plaintxtByte[i]);
}
plaintxt[b] = plaintxtByte.join('');
}
// join array of blocks into single plaintext string
var plaintext = plaintxt.join('');
plaintext = Utf8.decode(plaintext); // decode from UTF8 back to Unicode multi-byte chars
//alert((new Date()) - t);
return plaintext;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2010 */
/* note: depends on Utf8 class */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, no newlines are added.
*
* @param {String} str The string to be encoded as base-64
* @param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded
* to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters
* @returns {String} Base64-encoded string
*/
Base64.encode = function(str, utf8encode) { // http://tools.ietf.org/html/rfc4648
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? str.encodeUTF8() : str;
c = plain.length % 3; // pad string to length of multiple of 3
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for (c=0; c<plain.length; c+=3) { // pack three octets into four hexets
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join(''); // join() is far faster than repeated string concatenation in IE
// replace 'A's from padded nulls with '='s
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
/**
* Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, newlines are not catered for.
*
* @param {String} str The string to be decoded from base-64
* @param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded
* from UTF8 after conversion from base64
* @returns {String} decoded string
*/
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? str.decodeUTF8() : str;
for (var c=0; c<coded.length; c+=4) { // unpack four hexets into three octets
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? plain.decodeUTF8() : plain;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */
/* single-byte character encoding (c) Chris Veness 2002-2010 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Utf8 = {}; // Utf8 namespace
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* @param {String} strUni Unicode string to be encoded as UTF-8
* @returns {String} encoded string
*/
Utf8.encode = function(strUni) {
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f); }
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f); }
);
return strUtf;
}
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* @param {String} strUtf UTF-8 string to be decoded back to Unicode
* @returns {String} decoded string
*/
Utf8.decode = function(strUtf) {
var strUni = strUtf.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function(c) { // (note parentheses for precence)
var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f;
return String.fromCharCode(cc); }
);
strUni = strUni.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function(c) { // (note parentheses for precence)
var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f);
return String.fromCharCode(cc); }
);
return strUni;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ | JavaScript |
window.addEvent('domready', function () {
em = document.id('extraction_method');
if (em) {
em.addEvent('change', function () {
if(em.value == 'direct') {
document.id('row_ftp_hostname').style.display = 'none';
document.id('row_ftp_port').style.display = 'none';
document.id('row_ftp_username').style.display = 'none';
document.id('row_ftp_password').style.display = 'none';
document.id('row_ftp_directory').style.display = 'none';
} else {
document.id('row_ftp_hostname').style.display = 'table-row';
document.id('row_ftp_port').style.display = 'table-row';
document.id('row_ftp_username').style.display = 'table-row';
document.id('row_ftp_password').style.display = 'table-row';
document.id('row_ftp_directory').style.display = 'table-row';
}
});
}
$$('button.submit').addEvent('click', function() {
$$('div.download_message').setStyle('display', 'block');
var el = $$('div.joomlaupdate_spinner');
el.set('spinner', {class: 'joomlaupdate_spinner'});
el.spin();
})
});
| JavaScript |
var joomlaupdate_error_callback = dummy_error_handler;
var joomlaupdate_stat_inbytes = 0;
var joomlaupdate_stat_outbytes = 0;
var joomlaupdate_stat_files = 0;
var joomlaupdate_stat_percent = 0;
var joomlaupdate_factory = null;
var joomlaupdate_progress_bar = null;
/**
* An extremely simple error handler, dumping error messages to screen
*
* @param error The error message string
*/
function dummy_error_handler(error)
{
alert("ERROR:\n"+error);
}
/**
* Performs an AJAX request and returns the parsed JSON output.
*
* @param data An object with the query data, e.g. a serialized form
* @param successCallback A function accepting a single object parameter, called on success
* @param errorCallback A function accepting a single string parameter, called on failure
*/
function doAjax(data, successCallback, errorCallback)
{
var json = JSON.stringify(data);
if( joomlaupdate_password.length > 0 )
{
json = AesCtr.encrypt( json, joomlaupdate_password, 128 );
}
var post_data = 'json='+encodeURIComponent(json);
var structure =
{
onSuccess: function(msg, responseXML)
{
// Initialize
var junk = null;
var message = "";
// Get rid of junk before the data
var valid_pos = msg.indexOf('###');
if( valid_pos == -1 ) {
// Valid data not found in the response
msg = 'Invalid AJAX data:\n' + msg;
if(joomlaupdate_error_callback != null)
{
joomlaupdate_error_callback(msg);
}
return;
} else if( valid_pos != 0 ) {
// Data is prefixed with junk
junk = msg.substr(0, valid_pos);
message = msg.substr(valid_pos);
}
else
{
message = msg;
}
message = message.substr(3); // Remove triple hash in the beginning
// Get of rid of junk after the data
var valid_pos = message.lastIndexOf('###');
message = message.substr(0, valid_pos); // Remove triple hash in the end
// Decrypt if required
if( joomlaupdate_password.length > 0 )
{
try {
var data = JSON.parse(message);
} catch(err) {
message = AesCtr.decrypt(message, joomlaupdate_password, 128);
}
}
try {
var data = JSON.parse(message);
} catch(err) {
var msg = err.message + "\n<br/>\n<pre>\n" + message + "\n</pre>";
if(joomlaupdate_error_callback != null)
{
joomlaupdate_error_callback(msg);
}
return;
}
// Call the callback function
successCallback(data);
},
onFailure: function(req) {
var message = 'AJAX Loading Error: '+req.statusText;
if(joomlaupdate_error_callback != null)
{
joomlaupdate_error_callback(msg);
}
}
};
var ajax_object = null;
structure.url = joomlaupdate_ajax_url;
ajax_object = new Request(structure);
ajax_object.send(post_data);
}
/**
* Pings the update script (making sure its executable!!)
* @return
*/
function pingUpdate()
{
// Reset variables
joomlaupdate_stat_files = 0;
joomlaupdate_stat_inbytes = 0;
joomlaupdate_stat_outbytes = 0;
// Do AJAX post
var post = {task : 'ping'};
doAjax(post, function(data){
startUpdate(data);
});
}
/**
* Starts the update
* @return
*/
function startUpdate()
{
// Reset variables
joomlaupdate_stat_files = 0;
joomlaupdate_stat_inbytes = 0;
joomlaupdate_stat_outbytes = 0;
var post = { task : 'startRestore' };
doAjax(post, function(data){
processUpdateStep(data);
});
}
/**
* Steps through the update
* @param data
* @return
*/
function processUpdateStep(data)
{
if(data.status == false)
{
if(joomlaupdate_error_callback != null)
{
joomlaupdate_error_callback(data.message);
}
}
else
{
if(data.done)
{
joomlaupdate_factory = data.factory;
window.location = joomlaupdate_return_url;
}
else
{
// Add data to variables
joomlaupdate_stat_inbytes += data.bytesIn;
joomlaupdate_stat_percent = (joomlaupdate_stat_inbytes * 100) / joomlaupdate_totalsize;
// Create progress bar once
if (joomlaupdate_progress_bar == null)
{
joomlaupdate_progress_bar = new Fx.ProgressBar(document.id('progress'));
}
joomlaupdate_progress_bar.set(joomlaupdate_stat_percent);
joomlaupdate_stat_outbytes += data.bytesOut;
joomlaupdate_stat_files += data.files;
// Display data
document.getElementById('extpercent').innerHTML = new Number(joomlaupdate_stat_percent).formatPercentage(1);
document.getElementById('extbytesin').innerHTML = new Number(joomlaupdate_stat_inbytes).format();
document.getElementById('extbytesout').innerHTML = new Number(joomlaupdate_stat_outbytes).format();
document.getElementById('extfiles').innerHTML = new Number(joomlaupdate_stat_files).format();
// Do AJAX post
post = {
task: 'stepRestore',
factory: data.factory
};
doAjax(post, function(data){
processUpdateStep(data);
});
}
}
}
window.addEvent('domready', function() {
pingUpdate();
var el = $$('div.joomlaupdate_spinner');
el.set('spinner', {class: 'joomlaupdate_spinner'});
el.spin();
}); | JavaScript |
/*
* http://www.JSON.org/json2.js
* 2009-09-29
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
* See http://www.JSON.org/js.html
*/
if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}()); | JavaScript |
// Angie Radtke 2009 //
/*global window, localStorage, Cookie, altopen, altclose, big, small, rightopen, rightclose, bildauf, bildzu */
Object.append(Browser.Features, {
localstorage: (function() {
return ('localStorage' in window) && window.localStorage !== null;
})()
});
function saveIt(name) {
var x = document.id(name).style.display;
if (!x) {
alert('No cookie available');
} else {
if (Browser.Features.localstorage) {
try {
localStorage[name] = x;
}
catch (e) {
// Most likely the storage is full or deactivated
}
} else {
Cookie.write(name, x, {duration: 7});
}
}
}
function readIt(name) {
if (Browser.Features.localstorage) {
return localStorage[name];
} else {
return Cookie.read(name);
}
}
function wrapperwidth(width) {
document.id('wrapper').setStyle('width', width);
}
// add Wai-Aria landmark-roles
window.addEvent('domready', function () {
if (document.id('nav')) {
document.id('nav').setProperties( {
role : 'navigation'
});
}
if (document.id('mod-search-searchword')) {
document.id(document.id('mod-search-searchword').form).set( {
role : 'search'
});
}
if (document.id('main')) {
document.id('main').setProperties( {
role : 'main'
});
}
if (document.id('right')) {
document.id('right').setProperties( {
role : 'contentinfo'
});
}
});
window.addEvent('domready', function() {
// get ankers
var myankers = document.id(document.body).getElements('a.opencloselink');
myankers.each(function(element) {
element.setProperty('role', 'tab');
var myid = element.getProperty('id');
myid = myid.split('_');
myid = 'module_' + myid[1];
document.id(element).setProperty('aria-controls', myid);
});
var list = document.id(document.body).getElements('div.moduletable_js');
list.each(function(element) {
if (element.getElement('div.module_content')) {
var el = element.getElement('div.module_content');
el.setProperty('role', 'tabpanel');
var myid = el.getProperty('id');
myid = myid.split('_');
myid = 'link_' + myid[1];
el.setProperty('aria-labelledby', myid);
var myclass = el.get('class');
var one = myclass.split(' ');
// search for active menu-item
var listelement = el.getElement('a.active');
var unique = el.id;
var nocookieset = readIt(unique);
if ((listelement) ||
((one[1] == 'open') && (nocookieset == null))) {
el.setStyle('display', 'block');
var eltern = el.getParent();
var elternh = eltern.getElement('h3');
var elternbild = eltern.getElement('img');
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
elternbild.focus();
} else {
el.setStyle('display', 'none');
el.setProperty('aria-expanded', 'false');
}
unique = el.id;
var cookieset = readIt(unique);
if (cookieset == 'block') {
el.setStyle('display', 'block');
el.setProperty('aria-expanded', 'true');
el.slide('show');//.slide('hide').slide('in');
el.getParent().setProperty('class', 'slide');
var eltern = el.getParent().getParent();
var elternh = eltern.getElement('h3');
var elternbild = eltern.getElement('img');
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
}
}
});
});
window.addEvent('domready', function() {
var what = document.id('right');
// if rightcolumn
if (what != null) {
var whatid = what.id;
var rightcookie = readIt(whatid);
if (rightcookie == 'none') {
what.setStyle('display', 'none');
document.id('nav').addClass('leftbigger');
wrapperwidth(big);
var grafik = document.id('bild');
grafik.innerHTML = rightopen;
grafik.focus();
}
}
});
function auf(key) {
var el = document.id(key);
if (el.style.display == 'none') {
el.setStyle('display', 'block');
el.setProperty('aria-expanded', 'true');
if (key != 'right') {
el.slide('hide').slide('in');
el.getParent().setProperty('class', 'slide');
eltern = el.getParent().getParent();
elternh = eltern.getElement('h3');
elternh.addClass('high');
elternbild = eltern.getElement('img');
// elternbild.focus();
el.focus();
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
}
if (key == 'right') {
document.id('right').setStyle('display', 'block');
wrapperwidth(small);
document.id('nav').removeClass('leftbigger');
grafik = document.id('bild');
document.id('bild').innerHTML = rightclose;
grafik.focus();
}
} else {
el.setStyle('display', 'none');
el.setProperty('aria-expanded', 'false');
el.removeClass('open');
if (key != 'right') {
eltern = el.getParent().getParent();
elternh = eltern.getElement('h3');
elternh.removeClass('high');
elternbild = eltern.getElement('img');
// alert(bildauf);
elternbild.setProperties( {
alt : altclose,
src : bildauf
});
elternbild.focus();
}
if (key == 'right') {
document.id('right').setStyle('display', 'none');
wrapperwidth(big);
document.id('nav').addClass('leftbigger');
grafik = document.id('bild');
grafik.innerHTML = rightopen;
grafik.focus();
}
}
// write cookie
saveIt(key);
}
// ########### Tabfunctions ####################
window.addEvent('domready', function() {
var alldivs = document.id(document.body).getElements('div.tabcontent');
var outerdivs = document.id(document.body).getElements('div.tabouter');
outerdivs = outerdivs.getProperty('id');
for (var i = 0; i < outerdivs.length; i++) {
alldivs = document.id(outerdivs[i]).getElements('div.tabcontent');
count = 0;
alldivs.each(function(element) {
count++;
var el = document.id(element);
el.setProperty('role', 'tabpanel');
el.setProperty('aria-hidden', 'false');
el.setProperty('aria-expanded', 'true');
elid = el.getProperty('id');
elid = elid.split('_');
elid = 'link_' + elid[1];
el.setProperty('aria-labelledby', elid);
if (count != 1) {
el.addClass('tabclosed').removeClass('tabopen');
el.setProperty('aria-hidden', 'true');
el.setProperty('aria-expanded', 'false');
}
});
countankers = 0;
allankers = document.id(outerdivs[i]).getElement('ul.tabs').getElements('a');
allankers.each(function(element) {
countankers++;
var el = document.id(element);
el.setProperty('aria-selected', 'true');
el.setProperty('role', 'tab');
linkid = el.getProperty('id');
moduleid = linkid.split('_');
moduleid = 'module_' + moduleid[1];
el.setProperty('aria-controls', moduleid);
if (countankers != 1) {
el.addClass('linkclosed').removeClass('linkopen');
el.setProperty('aria-selected', 'false');
}
});
}
});
function tabshow(elid) {
var el = document.id(elid);
var outerdiv = el.getParent();
outerdiv = outerdiv.getProperty('id');
var alldivs = document.id(outerdiv).getElements('div.tabcontent');
var liste = document.id(outerdiv).getElement('ul.tabs');
liste.getElements('a').setProperty('aria-selected', 'false');
alldivs.each(function(element) {
element.addClass('tabclosed').removeClass('tabopen');
element.setProperty('aria-hidden', 'true');
element.setProperty('aria-expanded', 'false');
});
el.addClass('tabopen').removeClass('tabclosed');
el.setProperty('aria-hidden', 'false');
el.setProperty('aria-expanded', 'true');
el.focus();
var getid = elid.split('_');
var activelink = 'link_' + getid[1];
document.id(activelink).setProperty('aria-selected', 'true');
liste.getElements('a').addClass('linkclosed').removeClass('linkopen');
document.id(activelink).addClass('linkopen').removeClass('linkclosed');
}
function nexttab(el) {
var outerdiv = document.id(el).getParent();
var liste = outerdiv.getElement('ul.tabs');
var getid = el.split('_');
var activelink = 'link_' + getid[1];
var aktiverlink = document.id(activelink).getProperty('aria-selected');
var tablinks = liste.getElements('a').getProperty('id');
for ( var i = 0; i < tablinks.length; i++) {
if (tablinks[i] == activelink) {
if (document.id(tablinks[i + 1]) != null) {
document.id(tablinks[i + 1]).onclick();
break;
}
}
}
} | JavaScript |
/*global window, localStorage, fontSizeTitle, bigger, reset, smaller, biggerTitle, resetTitle, smallerTitle, Cookie */
var prefsLoaded = false;
var defaultFontSize = 100;
var currentFontSize = defaultFontSize;
var fontSizeTitle;
var bigger;
var smaller;
var reset;
var biggerTitle;
var smallerTitle;
var resetTitle;
Object.append(Browser.Features, {
localstorage: (function() {
return ('localStorage' in window) && window.localStorage !== null;
})()
});
function setFontSize(fontSize) {
document.body.style.fontSize = fontSize + '%';
}
function changeFontSize(sizeDifference) {
currentFontSize = parseInt(currentFontSize, 10) + parseInt(sizeDifference * 5, 10);
if (currentFontSize > 180) {
currentFontSize = 180;
} else if (currentFontSize < 60) {
currentFontSize = 60;
}
setFontSize(currentFontSize);
}
function revertStyles() {
currentFontSize = defaultFontSize;
changeFontSize(0);
}
function writeFontSize(value) {
if (Browser.Features.localstorage) {
localStorage.fontSize = value;
} else {
Cookie.write("fontSize", value, {duration: 180});
}
}
function readFontSize() {
if (Browser.Features.localstorage) {
return localStorage.fontSize;
} else {
return Cookie.read("fontSize");
}
}
function setUserOptions() {
if (!prefsLoaded) {
var size = readFontSize();
currentFontSize = size ? size : defaultFontSize;
setFontSize(currentFontSize);
prefsLoaded = true;
}
}
function addControls() {
var container = document.id('fontsize');
var content = '<h3>'+ fontSizeTitle +'</h3><p><a title="'+ biggerTitle +'" href="#" onclick="changeFontSize(2); return false">'+ bigger +'</a><span class="unseen">.</span><a href="#" title="'+resetTitle+'" onclick="revertStyles(); return false">'+ reset +'</a><span class="unseen">.</span><a href="#" title="'+ smallerTitle +'" onclick="changeFontSize(-2); return false">'+ smaller +'</a></p>';
container.set('html', content);
}
function saveSettings() {
writeFontSize(currentFontSize);
}
window.addEvent('domready', setUserOptions);
window.addEvent('domready', addControls);
window.addEvent('unload', saveSettings); | JavaScript |
/* Javscript Document */
| JavaScript |
// Angie Radtke 2009 //
/*global window, localStorage, Cookie, altopen, altclose, big, small, rightopen, rightclose, bildauf, bildzu */
Object.append(Browser.Features, {
localstorage: (function() {
return ('localStorage' in window) && window.localStorage !== null;
})()
});
function saveIt(name) {
var x = document.id(name).style.display;
if (!x) {
alert('No cookie available');
} else {
if (Browser.Features.localstorage) {
try {
localStorage[name] = x;
}
catch (e) {
// Most likely the storage is full or deactivated
}
} else {
Cookie.write(name, x, {duration: 7});
}
}
}
function readIt(name) {
if (Browser.Features.localstorage) {
return localStorage[name];
} else {
return Cookie.read(name);
}
}
function wrapperwidth(width) {
document.id('wrapper').setStyle('width', width);
}
// add Wai-Aria landmark-roles
window.addEvent('domready', function () {
if (document.id('nav')) {
document.id('nav').setProperties( {
role : 'navigation'
});
}
if (document.id('mod-search-searchword')) {
document.id(document.id('mod-search-searchword').form).set( {
role : 'search'
});
}
if (document.id('main')) {
document.id('main').setProperties( {
role : 'main'
});
}
if (document.id('right')) {
document.id('right').setProperties( {
role : 'contentinfo'
});
}
});
window.addEvent('domready', function() {
// get ankers
var myankers = document.id(document.body).getElements('a.opencloselink');
myankers.each(function(element) {
element.setProperty('role', 'tab');
var myid = element.getProperty('id');
myid = myid.split('_');
myid = 'module_' + myid[1];
document.id(element).setProperty('aria-controls', myid);
});
var list = document.id(document.body).getElements('div.moduletable_js');
list.each(function(element) {
if (element.getElement('div.module_content')) {
var el = element.getElement('div.module_content');
el.setProperty('role', 'tabpanel');
var myid = el.getProperty('id');
myid = myid.split('_');
myid = 'link_' + myid[1];
el.setProperty('aria-labelledby', myid);
var myclass = el.get('class');
var one = myclass.split(' ');
// search for active menu-item
var listelement = el.getElement('a.active');
var unique = el.id;
var nocookieset = readIt(unique);
if ((listelement) ||
((one[1] == 'open') && (nocookieset == null))) {
el.setStyle('display', 'block');
var eltern = el.getParent();
var elternh = eltern.getElement('h3');
var elternbild = eltern.getElement('img');
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
elternbild.focus();
} else {
el.setStyle('display', 'none');
el.setProperty('aria-expanded', 'false');
}
unique = el.id;
var cookieset = readIt(unique);
if (cookieset == 'block') {
el.setStyle('display', 'block');
el.setProperty('aria-expanded', 'true');
el.slide('show');//.slide('hide').slide('in');
el.getParent().setProperty('class', 'slide');
var eltern = el.getParent().getParent();
var elternh = eltern.getElement('h3');
var elternbild = eltern.getElement('img');
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
}
}
});
});
window.addEvent('domready', function() {
var what = document.id('right');
// if rightcolumn
if (what != null) {
var whatid = what.id;
var rightcookie = readIt(whatid);
if (rightcookie == 'none') {
what.setStyle('display', 'none');
document.id('nav').addClass('leftbigger');
wrapperwidth(big);
var grafik = document.id('bild');
grafik.innerHTML = rightopen;
grafik.focus();
}
}
});
function auf(key) {
var el = document.id(key);
if (el.style.display == 'none') {
el.setStyle('display', 'block');
el.setProperty('aria-expanded', 'true');
if (key != 'right') {
el.slide('hide').slide('in');
el.getParent().setProperty('class', 'slide');
eltern = el.getParent().getParent();
elternh = eltern.getElement('h3');
elternh.addClass('high');
elternbild = eltern.getElement('img');
// elternbild.focus();
el.focus();
elternbild.setProperties( {
alt : altopen,
src : bildzu
});
}
if (key == 'right') {
document.id('right').setStyle('display', 'block');
wrapperwidth(small);
document.id('nav').removeClass('leftbigger');
grafik = document.id('bild');
document.id('bild').innerHTML = rightclose;
grafik.focus();
}
} else {
el.setStyle('display', 'none');
el.setProperty('aria-expanded', 'false');
el.removeClass('open');
if (key != 'right') {
eltern = el.getParent().getParent();
elternh = eltern.getElement('h3');
elternh.removeClass('high');
elternbild = eltern.getElement('img');
// alert(bildauf);
elternbild.setProperties( {
alt : altclose,
src : bildauf
});
elternbild.focus();
}
if (key == 'right') {
document.id('right').setStyle('display', 'none');
wrapperwidth(big);
document.id('nav').addClass('leftbigger');
grafik = document.id('bild');
grafik.innerHTML = rightopen;
grafik.focus();
}
}
// write cookie
saveIt(key);
}
// ########### Tabfunctions ####################
window.addEvent('domready', function() {
var alldivs = document.id(document.body).getElements('div.tabcontent');
var outerdivs = document.id(document.body).getElements('div.tabouter');
outerdivs = outerdivs.getProperty('id');
for (var i = 0; i < outerdivs.length; i++) {
alldivs = document.id(outerdivs[i]).getElements('div.tabcontent');
count = 0;
alldivs.each(function(element) {
count++;
var el = document.id(element);
el.setProperty('role', 'tabpanel');
el.setProperty('aria-hidden', 'false');
el.setProperty('aria-expanded', 'true');
elid = el.getProperty('id');
elid = elid.split('_');
elid = 'link_' + elid[1];
el.setProperty('aria-labelledby', elid);
if (count != 1) {
el.addClass('tabclosed').removeClass('tabopen');
el.setProperty('aria-hidden', 'true');
el.setProperty('aria-expanded', 'false');
}
});
countankers = 0;
allankers = document.id(outerdivs[i]).getElement('ul.tabs').getElements('a');
allankers.each(function(element) {
countankers++;
var el = document.id(element);
el.setProperty('aria-selected', 'true');
el.setProperty('role', 'tab');
linkid = el.getProperty('id');
moduleid = linkid.split('_');
moduleid = 'module_' + moduleid[1];
el.setProperty('aria-controls', moduleid);
if (countankers != 1) {
el.addClass('linkclosed').removeClass('linkopen');
el.setProperty('aria-selected', 'false');
}
});
}
});
function tabshow(elid) {
var el = document.id(elid);
var outerdiv = el.getParent();
outerdiv = outerdiv.getProperty('id');
var alldivs = document.id(outerdiv).getElements('div.tabcontent');
var liste = document.id(outerdiv).getElement('ul.tabs');
liste.getElements('a').setProperty('aria-selected', 'false');
alldivs.each(function(element) {
element.addClass('tabclosed').removeClass('tabopen');
element.setProperty('aria-hidden', 'true');
element.setProperty('aria-expanded', 'false');
});
el.addClass('tabopen').removeClass('tabclosed');
el.setProperty('aria-hidden', 'false');
el.setProperty('aria-expanded', 'true');
el.focus();
var getid = elid.split('_');
var activelink = 'link_' + getid[1];
document.id(activelink).setProperty('aria-selected', 'true');
liste.getElements('a').addClass('linkclosed').removeClass('linkopen');
document.id(activelink).addClass('linkopen').removeClass('linkclosed');
}
function nexttab(el) {
var outerdiv = document.id(el).getParent();
var liste = outerdiv.getElement('ul.tabs');
var getid = el.split('_');
var activelink = 'link_' + getid[1];
var aktiverlink = document.id(activelink).getProperty('aria-selected');
var tablinks = liste.getElements('a').getProperty('id');
for ( var i = 0; i < tablinks.length; i++) {
if (tablinks[i] == activelink) {
if (document.id(tablinks[i + 1]) != null) {
document.id(tablinks[i + 1]).onclick();
break;
}
}
}
} | JavaScript |
/*global window, localStorage, fontSizeTitle, bigger, reset, smaller, biggerTitle, resetTitle, smallerTitle, Cookie */
var prefsLoaded = false;
var defaultFontSize = 100;
var currentFontSize = defaultFontSize;
var fontSizeTitle;
var bigger;
var smaller;
var reset;
var biggerTitle;
var smallerTitle;
var resetTitle;
Object.append(Browser.Features, {
localstorage: (function() {
return ('localStorage' in window) && window.localStorage !== null;
})()
});
function setFontSize(fontSize) {
document.body.style.fontSize = fontSize + '%';
}
function changeFontSize(sizeDifference) {
currentFontSize = parseInt(currentFontSize, 10) + parseInt(sizeDifference * 5, 10);
if (currentFontSize > 180) {
currentFontSize = 180;
} else if (currentFontSize < 60) {
currentFontSize = 60;
}
setFontSize(currentFontSize);
}
function revertStyles() {
currentFontSize = defaultFontSize;
changeFontSize(0);
}
function writeFontSize(value) {
if (Browser.Features.localstorage) {
localStorage.fontSize = value;
} else {
Cookie.write("fontSize", value, {duration: 180});
}
}
function readFontSize() {
if (Browser.Features.localstorage) {
return localStorage.fontSize;
} else {
return Cookie.read("fontSize");
}
}
function setUserOptions() {
if (!prefsLoaded) {
var size = readFontSize();
currentFontSize = size ? size : defaultFontSize;
setFontSize(currentFontSize);
prefsLoaded = true;
}
}
function addControls() {
var container = document.id('fontsize');
var content = '<h3>'+ fontSizeTitle +'</h3><p><a title="'+ biggerTitle +'" href="#" onclick="changeFontSize(2); return false">'+ bigger +'</a><span class="unseen">.</span><a href="#" title="'+resetTitle+'" onclick="revertStyles(); return false">'+ reset +'</a><span class="unseen">.</span><a href="#" title="'+ smallerTitle +'" onclick="changeFontSize(-2); return false">'+ smaller +'</a></p>';
container.set('html', content);
}
function saveSettings() {
writeFontSize(currentFontSize);
}
window.addEvent('domready', setUserOptions);
window.addEvent('domready', addControls);
window.addEvent('unload', saveSettings); | JavaScript |
/**
* @package Hathor
* @copyright Copyright (C) 2005 - 2009 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Functions
*/
/**
* Set focus to username on the login screen
*/
function setFocus() {
if (document.id("login-page")) {
document.id("form-login").username.select();
document.id("form-login").username.focus();
}
}
/**
* Change the skip nav target to work with webkit browsers (Safari/Chrome) and
* Opera
*/
function setSkip() {
if (Browser.Engine.webkit || Browser.opera) {
var target = document.id('skiptarget');
target.href = "#skiptarget";
target.innerText = "Start of main content";
target.setAttribute("tabindex", "0");
document.id('skiplink').setAttribute("onclick",
"document.id('skiptarget').focus();");
}
}
/**
* Set the Aria Role based on the id
*
* @param id
* @param rolevalue
* @return
*/
function setRoleAttribute(id, rolevalue) {
if (document.id(id)) {
document.id(id).setAttribute("role", rolevalue);
}
}
/**
* Set the WAI-ARIA Roles Specify the html id then aria role
*
* @return
*/
function setAriaRoleElementsById() {
setRoleAttribute("header", "banner");
setRoleAttribute("element-box", "main");
setRoleAttribute("footer", "contentinfo");
setRoleAttribute("nav", "navigation");
setRoleAttribute("submenu", "navigation");
setRoleAttribute("system-message", "alert");
}
/**
* This sets the given Aria Property state to true for the given element
*
* @param el
* The element (tag.class)
* @param prop
* The property to set to true
* @return
*/
function setPropertyAttribute(el, prop) {
if (document.getElements(el)) {
document.getElements(el).set(prop, "true");
}
}
/**
* Set the WAI-ARIA Properties Specify the tag.class then the aria property to
* set to true If classes are changed on the fly (i.e. aria-invalid) they need
* to be changed there instead of here.
*
* @return
*/
function setAriaProperties() {
setPropertyAttribute("input.required", "aria-required");
setPropertyAttribute("textarea.required", "aria-required");
setPropertyAttribute("input.readonly", "aria-readonly");
setPropertyAttribute("input.invalid", "aria-invalid");
setPropertyAttribute("textarea.invalid", "aria-invalid");
}
/**
* Process file
*/
/** from accessible suckerfish menu by Matt Carroll,
* mootooled by Bill Tomczak
*/
window.addEvent('domready', function(){
var menu = document.id('menu');
if (menu && !menu.hasClass('disabled')) {
menu.getElements('li').each(function(cel){
cel.addEvent('mouseenter', function(){
this.addClass('sfhover');
});
cel.addEvent('mouseleave', function() {
this.removeClass('sfhover');
});
});
menu.getElements('a').each(function(ael) {
ael.addEvent('focus', function() {
this.addClass('sffocus');
this.getParents('li').addClass('sfhover');
});
ael.addEvent('blur', function() {
this.removeClass('sffocus');
this.getParents('li').removeClass('sfhover');
});
});
}
});
window.addEvent('domready', function() {
setFocus();
setSkip();
setAriaRoleElementsById();
setAriaProperties();
});
/**
* For IE6 - Background flicker fix
*/
try {
document.execCommand('BackgroundImageCache', false, true);
} catch (e) {
}
| JavaScript |
/**
* @package Joomla.Administrator
* @subpackage templates.bluestork
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
var Joomla = Joomla || {};
/**
* Joomla Menu javascript behavior
*/
Joomla.Menu = new Class({
Implements: [Options],
options: {
disabled: false
},
initialize: function(element, options) {
this.setOptions(options);
this.element = document.id(element);
// equalize width of the child LI elements
this.element.getElements('li').filter('.node').getElement('ul').each(this._equalizeWidths);
if (!this.options.disabled) {
this._addMouseEvents();
}
this.element.store('menu', this);
},
disable: function() {
var elements = this.element.getElements('li');
$$(this.element, elements).addClass('disabled');
elements.removeEvents('mouseenter').removeEvents('mouseleave');
},
enable: function() {
$$(this.element, this.element.getElements('li')).removeClass('disabled');
this._addMouseEvents();
},
_addMouseEvents: function() {
this.element.getElements('li')
.removeEvents('mouseenter')
.removeEvents('mouseleave')
.addEvents({
'mouseenter': function() {
var ul = this.getElement('ul');
if (ul) { ul.fireEvent('show'); }
this.addClass('hover');
},
'mouseleave': function() {
var ul = this.getElement('ul');
if (ul) { ul.fireEvent('hide'); }
this.removeClass('hover');
}
});
},
_equalizeWidths: function(el) {
var offsetWidth = 0;
var children = el.getElements('li');
//find longest child
children.each(function(node) {
offsetWidth = (offsetWidth >= node.offsetWidth) ? offsetWidth : node.offsetWidth;
});
$$(children, el).setStyle('width', offsetWidth);
}
});
window.addEvent('domready', function() {
var el = document.id('menu');
new Joomla.Menu(el, (el.hasClass('disabled') ? {disabled: true} : {}));
}); | JavaScript |
/**
* jQuery.Rule - Css Rules manipulation, the jQuery way.
* Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 02/27/2008
* Compatible with jQuery 1.2.x, tested on FF 2, Opera 9, Safari 3, and IE 6, on Windows.
*
* @author Ariel Flesler
* @version 1.0.1
*
* @id jQuery.rule
* @param {Undefined|String|jQuery.Rule} The rules, can be a selector, or literal CSS rules. Many can be given, comma separated.
* @param {Undefined|String|DOMElement|jQuery) The context stylesheets, all of them by default.
* @return {jQuery.Rule} Returns a jQuery.Rule object.
*
* @example $.rule('p,div').filter(function(){ return this.style.display != 'block'; }).remove();
*
* @example $.rule('div{ padding:20px;background:#CCC}, p{ border:1px red solid; }').appendTo('style');
*
* @example $.rule('div{}').append('margin:40px').css('margin-left',0).appendTo('link:eq(1)');
*
* @example $.rule().not('div, p.magic').fadeOut('slow');
*
* @example var text = $.rule('#screen h2').add('h4').end().eq(4).text();
*/
;(function( $ ){
/**
* Notes
* Some styles and animations might fail, please report it.
* The plugin needs a style node to stay in the DOM all along to temporarily hold rules. DON'T TOUCH IT.
* Opera requires this style to have alternate in the rel to allow disabling it.
* Rules in IE don't have .parentStylesheet. We need to find it each time(slow).
* Animations need close attention. Programatically knowing which rule has precedence, would require a LOT of work.
* This plugin adds $.rule and also 4 methods to $.fn: ownerNode, sheet, cssRules and cssText
* Note that rules are not directly inside nodes, you need to do: $('style').sheet().cssRules().
*/
var storageNode = $('<style rel="alternate stylesheet" type="text/css" />').appendTo('head')[0],//we must append to get a stylesheet
sheet = storageNode.sheet ? 'sheet' : 'styleSheet',
storage = storageNode[sheet],//css rules must remain in a stylesheet for IE and FF
rules = storage.rules ? 'rules' : 'cssRules',
remove = storage.deleteRule ? 'deleteRule' : 'removeRule',
owner = storage.ownerNode ? 'ownerNode' : 'owningElement',
reRule = /^([^{]+)\{([^}]*)\}/m,
reStyle = /([^:]+):([^;}]+)/;
storage.disabled = true;//let's ignore your rules
var $rule = $.rule = function( r, c ){
if(!(this instanceof $rule))
return new $rule( r, c );
this.sheets = $rule.sheets(c);
if( r && reRule.test(r) )
r = $rule.clean( r );
if( typeof r == 'object' && !r.exec )
return this.setArray( r.get ? r.get() : r.splice ? r : [r] );
this.setArray( this.sheets.cssRules().get() );
return r ? this.filter( r ) : this;
};
$.extend( $rule, {
sheets:function( c ){
var o = c;
if( typeof o != 'object' )
o = $.makeArray(document.styleSheets);
o = $(o).not(storage);//skip our stylesheet
if( typeof c == 'string' )
o = o.ownerNode().filter(c).sheet();
return o;
},
rule:function( str ){
if( str.selectorText )/* * */
return [ '', str.selectorText, str.style.cssText ];
return reRule.exec( str );
},
appendTo:function( r, ss, skip ){
switch( typeof ss ){//find the desired stylesheet
case 'string': ss = this.sheets(ss);
case 'object':
if( ss[0] ) ss = ss[0];
if( ss[sheet] ) ss = ss[sheet];
if( ss[rules] ) break;//only if the stylesheet is valid
default:
if( typeof r == 'object' ) return r;//let's not waist time, it is parsed
ss = storage;
}
var p;
if( !skip && (p = this.parent(r)) )//if this is an actual rule, and it's appended.
r = this.remove( r, p );
var rule = this.rule( r );
if( ss.addRule )
ss.addRule( rule[1], rule[2]||';' );//IE won't allow empty rules
else if( ss.insertRule )
ss.insertRule( rule[1] + '{'+ rule[2] +'}', ss[rules].length );
return ss[rules][ ss[rules].length - 1 ];//return the added/parsed rule
},
remove:function( r, p ){
p = p || this.parent(r);
if( p != storage ){//let's save some unnecesary cycles.
var i = p ? $.inArray( r, p[rules] ) : -1;
if( i != -1 ){//if not stored before removal, IE will crash eventually, and some rules in FF get messed up
r = this.appendTo( r, 0 /*storage*/, true );//is faster and shorter to imply storage
p[remove](i);
}
}
return r;
},
clean:function( r ){
return $.map( r.split('}'), function( txt ){
if( txt )
return $rule.appendTo( txt + '}' /*, storage*/ );//parse the string, storage implied
});
},
parent:function( r ){//CSS rules in IE don't have parentStyleSheet attribute
if( typeof r == 'string' || !$.browser.msie )//if it's a string, just return undefined.
return r.parentStyleSheet;
var par;
this.sheets().each(function(){
if( $.inArray(r, this[rules]) != -1 ){
par = this;
return false;
}
});
return par;
},
outerText:function( rule ){
return !rule ? '' : [rule.selectorText+'{', '\t'+rule.style.cssText,'}'].join('\n').toLowerCase();
},
text:function( rule, txt ){
if( txt !== undefined )
rule.style.cssText = txt;
return !rule ? '' : rule.style.cssText.toLowerCase();
}
});
$rule.fn = $rule.prototype = {
pushStack:function( rs, sh ){
var ret = $rule( rs, sh || this.sheets );
ret.prevObject = this;
return ret;
},
end:function(){
return this.prevObject || $rule(0,[]);
},
filter:function( s ){
var o;
if( !s ) s = /./;//just keep them all.
if( s.split ){
o = $.trim(s).toLowerCase().split(/\s*,\s*/);
s = function(){
return !!$.grep( this.selectorText.toLowerCase().split(/\s*,\s*/), function( sel ){
return $.inArray( sel, o ) != -1;
}).length;
};
}else if( s.exec ){//string regex, or actual regex
o = s;
s = function(){ return o.test(this.selectorText); };
}
return this.pushStack($.grep( this, function( e, i ){
return s.call( e, i );
}));
},
add:function( rs, c ){
return this.pushStack( $.merge(this.get(), $rule(rs, c)) );
},
is:function( s ){
return !!(s && this.filter( s ).length);
},
not:function( n, c ){
n = $rule( n, c );
return this.filter(function(){
return $.inArray( this, n ) == -1;
});
},
append:function( s ){
var rules = this, rule;
$.each( s.split(/\s*;\s*/),function(i,v){
if(( rule = reStyle.exec( v ) ))
rules.css( rule[1], rule[2] );
});
return this;
},
text:function( txt ){
return !arguments.length ? $rule.text( this[0] )
: this.each(function(){ $rule.text( this, txt ); });
},
outerText:function(){
return $rule.outerText(this[0]);
}
};
// hack for jQuery 1.4.2
$rule.fn.setArray = function( elems ) {
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
};
$.each({
ownerNode:owner,//when having the stylesheet, get the node that contains it
sheet:sheet, //get the stylesheet from the node
cssRules:rules //get the rules from the stylesheet.
},function( m, a ){
var many = a == rules;//the rules need some more processing
$.fn[m] = function(){
return this.map(function(){
return many ? $.makeArray(this[a]) : this[a];
});
};
});
$.fn.cssText = function(){
return this.filter('link,style').eq(0).sheet().cssRules().map(function(){
return $rule.outerText(this);
}).get().join('\n');
};
$.each('remove,appendTo,parent'.split(','),function( k, f ){
$rule.fn[f] = function(){
var args = $.makeArray(arguments), that = this;
args.unshift(0);
return this.each(function( i ){
args[0] = this;
that[i] = $rule[f].apply( $rule, args ) || that[i];
});
};
});
$.each(('each,index,get,size,eq,slice,map,attr,andSelf,css,show,hide,toggle,'+
'queue,dequeue,stop,animate,fadeIn,fadeOut,fadeTo').split(','),function( k, f ){
$rule.fn[f] = $.fn[f];
});
var curCSS = $.curCSS;
$.curCSS = function( e, a ){//this hack is still quite exprimental
return ('selectorText' in e ) ?
e.style[a] || $.prop( e, a=='opacity'? 1 : 0,'curCSS', 0, a )//TODO: improve these defaults
: curCSS.apply(this,arguments);
};
/**
* Time to hack jQuery.data for animations.
* Only IE really needs this, but to keep the behavior consistent, I'll hack it for all browsers.
* TODO: This kind of id doesn't seem to be good enough
* TODO: Avoid animating similar rules simultaneously
* TODO: Avoid rules' precedence from interfering on animations ?
*/
$rule.cache = {};
var mediator = function( original ){
return function( elm ){
var id = elm.selectorText;
if( id )
arguments[0] = $rule.cache[id] = $rule.cache[id] || {};
return original.apply( $, arguments );
};
};
$.data = mediator( $.data );
$.removeData = mediator( $.removeData );
$(window).unload(function(){
$(storage).cssRules().remove();//empty our rules bin
});
})( jQuery ); | JavaScript |
/*
jQuery TextAreaResizer plugin
Created on 17th January 2008 by Ryan O'Dell
Version 1.0.4
Converted from Drupal -> textarea.js
Found source: http://plugins.jquery.com/misc/textarea.js
$Id: textarea.js,v 1.11.2.1 2007/04/18 02:41:19 drumm Exp $
1.0.1 Updates to missing global 'var', added extra global variables, fixed multiple instances, improved iFrame support
1.0.2 Updates according to textarea.focus
1.0.3 Further updates including removing the textarea.focus and moving private variables to top
1.0.4 Re-instated the blur/focus events, according to information supplied by dec
*/
(function ($) {
/* private variable "oHover" used to determine if you're still hovering over the same element */
var wrapperDiv, staticOffset; // added the var declaration for 'staticOffset' thanks to issue logged by dec.
var resizable;
var iLastMousePos = 0;
var iMin = 32;
var grip;
var callback;
var ovarlay; // very hacky used so it works with iframes
/* TextAreaResizer plugin */
$.fn.TextAreaResizer = function (cb) {
callback = cb;
return this.each(function () {
wrapperDiv = $(this).addClass('processed'), staticOffset = null;
// 18-01-08 jQuery bind to pass data element rather than direct mousedown - Ryan O'Dell
// When wrapping the text area, work around an IE margin bug. See:
// http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout
//$(this).wrap('<div class="resizable-textarea"><span></span></div>')
// .parent().append($('<div class="grippie"></div>').bind("mousedown", { el: this }, startDrag));
$(this).append($('<div class="grippie"></div>').bind("mousedown", { el: this }, startDrag));
var grippie = $('div.grippie', $(this).parent())[0];
resizable = $($(this).children(':visible')[0]);
//grippie.style.marginRight = "-6px";
grippie.style.marginRight = (grippie.offsetWidth - resizable[0].offsetWidth) + 'px';
});
};
/* private functions */
function startDrag(e) {
wrapperDiv = $(e.data.el);
wrapperDiv.blur();
iLastMousePos = mousePosition(e).y;
staticOffset = wrapperDiv.height() - iLastMousePos;
resizable.css('opacity', 0.25);
// hack so it works with iframes
overlay = wrapperDiv.append("<div id='overlay' style='position: absolute; zindex: 99; background-color: white; opacity:0.01; filter: alpha(opacity = 1); left:0; top:0;'> </div>").find("#overlay");
overlay.width(wrapperDiv.width());
overlay.height(wrapperDiv.height());
$(document).mousemove(performDrag).mouseup(endDrag);
if (callback != null) callback();
return false;
}
function performDrag(e) {
var iThisMousePos = mousePosition(e).y;
var iMousePos = staticOffset + iThisMousePos;
if (iLastMousePos >= (iThisMousePos)) {
iMousePos -= 5;
}
iLastMousePos = iThisMousePos;
iMousePos = Math.max(iMin, iMousePos);
//wrapperDiv.height(iMousePos + 'px');
resizable.height(iMousePos + 'px');
overlay.height(wrapperDiv.height());
if (iMousePos < iMin) {
endDrag(e);
}
if (callback != null) callback();
return false;
}
function endDrag(e) {
$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
resizable.css('opacity', 1);
//resizable.css('filter', 'alpha(opacity = 100)');
wrapperDiv.focus();
wrapperDiv = null;
staticOffset = null;
iLastMousePos = 0;
if (callback != null) callback();
overlay.remove();
}
function mousePosition(e) {
return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
};
})(jQuery);
| JavaScript |
// TODO: Proper use of namespaces
if (typeof (QP) == "undefined" || !QP) {
var QP = {}
};
(function() {
/* Draws the lines linking nodes in query plan diagram.
root - The document element in which the diagram is contained. */
QP.drawLines = function(root) {
if (root === null || root === undefined) {
// Try and find it ourselves
root = $(".qp-root:parent");
} else {
// Make sure the object passed is jQuery wrapped
root = $(root);
}
internalDrawLines(root);
};
/* Internal implementaiton of drawLines. */
function internalDrawLines(root) {
var canvas = getCanvas(root);
var canvasElm = canvas[0];
// Check for browser compatability
if (canvasElm.getContext !== null && canvasElm.getContext !== undefined) {
// Chrome is usually too quick with document.ready
window.setTimeout(function() {
var context = canvasElm.getContext("2d");
canvasElm.width = root.outerWidth(true);
canvasElm.height = root.outerHeight(true);
var offset = canvas.offset();
$(".qp-tr", root).each(function() {
var from = $("> * > .qp-node", $(this));
$("> * > .qp-tr > * > .qp-node", $(this)).each(function() {
drawLine(context, offset, from, $(this));
});
});
context.stroke();
}, 1);
}
}
/* Locates or creates the canvas element to use to draw lines for a given root element. */
function getCanvas(root) {
var returnValue = $("canvas", root);
if (returnValue.length == 0) {
root.prepend($("<canvas></canvas>")
.css("position", "absolute")
.css("top", 0).css("left", 0)
);
returnValue = $("canvas", root);
}
return returnValue;
}
/* Draws a line between two nodes.
context - The canvas context with which to draw.
offset - Canvas offset in the document.
from - The document jQuery object from which to draw the line.
to - The document jQuery object to which to draw the line. */
function drawLine(context, offset, from, to) {
var fromOffset = from.offset();
fromOffset.top += from.outerHeight() / 2;
fromOffset.left += from.outerWidth();
var toOffset = to.offset();
toOffset.top += to.outerHeight() / 2;
var midOffsetLeft = fromOffset.left / 2 + toOffset.left / 2;
context.moveTo(fromOffset.left - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, fromOffset.top - offset.top);
context.lineTo(midOffsetLeft - offset.left, toOffset.top - offset.top);
context.lineTo(toOffset.left - offset.left, toOffset.top - offset.top);
}
})(); | JavaScript |
/*
Simple OpenID Plugin
http://code.google.com/p/openid-selector/
This code is licenced under the New BSD License.
*/
var providers_large = {
google: {
name: 'Google',
url: 'https://www.google.com/accounts/o8/id',
x: -1,
y: -1
},
yahoo: {
name: 'Yahoo',
url: 'http://yahoo.com/',
x: -1,
y: -63
},
myopenid: {
name: 'MyOpenID',
url: 'http://myopenid.com/',
x: -1,
y: -187
},
aol: {
name: 'AOL',
label: 'Enter your AOL screenname',
url: 'http://openid.aol.com/{username}',
x: -1,
y: -125
}
};
var providers_small = {
livejournal: {
name: 'LiveJournal',
label: 'Enter your Livejournal username',
url: 'http://{username}.livejournal.com/',
x: -1,
y: -352
},
wordpress: {
name: 'Wordpress',
label: 'Enter your Wordpress.com username',
url: 'http://{username}.wordpress.com/',
x: -1,
y: -404
},
blogger: {
name: 'Blogger',
label: 'Enter your Blogger account',
url: 'http://{username}.blogspot.com/',
x: -1,
y: -249
},
verisign: {
name: 'Verisign',
label: 'Enter your Verisign username',
url: 'http://{username}.pip.verisignlabs.com/',
x: -1,
y: -378
},
claimid: {
name: 'ClaimID',
label: 'Enter your ClaimID username',
url: 'http://openid.claimid.com/{username}',
x: -1,
y: -326
},
clickpass: {
name: 'ClickPass',
label: 'Enter your ClickPass username',
url: 'http://clickpass.com/public/{username}',
x: -1,
y: -274
},
google_profile: {
name: 'Google_Profile',
label: 'Enter your Google Profile username',
url: 'http://www.google.com/profiles/{username}',
x: -1,
y: -300
}
};
var providers = $.extend({}, providers_large, providers_small);
var openid = {
cookie_expires: 6 * 30, // 6 months.
cookie_name: 'openid_provider',
cookie_path: '/',
img_path: '/Content/Img/openid/openid-logos.png?v=3',
input_id: null,
provider_url: null,
init: function (input_id) {
// turn off hourglass
$('body').css('cursor', 'default');
$('#openid_submit').css('cursor', 'default');
// enable submit button on form
$('input[type=submit]').removeAttr('disabled');
var openid_btns = $('#openid_btns');
this.input_id = input_id;
$('#openid_choice').show();
$('#openid_input_area').empty();
// add box for each provider
for (id in providers_large) {
openid_btns.append(this.getBoxHTML(providers_large[id], 'large'));
}
if (providers_small) {
openid_btns.append('<br>');
for (id in providers_small) {
openid_btns.append(this.getBoxHTML(providers_small[id], 'small'));
}
}
$('#openid_form').submit(this.submitx);
},
getBoxHTML: function (provider, box_size) {
var box_id = provider["name"].toLowerCase();
return '<a title="log in with ' + provider["name"] + '" href="javascript:openid.signin(\'' + box_id + '\');"' +
' style="background: #fff url(' + this.img_path + '); background-position: ' + provider["x"] + 'px ' + provider["y"] + 'px"' +
' class="' + box_id + ' openid_' + box_size + '_btn"></a>';
},
/* provider image click */
signin: function (box_id, onload) {
var provider = providers[box_id];
if (!provider) { return; }
this.highlight(box_id);
if (box_id == 'openid') {
$('#openid_input_area').empty();
this.setOpenIdUrl("");
$("#openid_identifier").focus();
return;
}
// prompt user for input?
if (provider['label']) {
this.useInputBox(provider);
this.provider_url = provider['url'];
} else {
$('.' + box_id).css('cursor', 'wait');
if (provider['oauth_version']) {
this.setOAuthInfo(provider['oauth_version'], provider['oauth_server']);
} else {
this.setOpenIdUrl(provider['url']);
}
this.provider_url = null;
if (!onload) {
$('#openid_form').submit();
}
}
},
/* Sign-in button click */
submitx: function () {
if ($('#openid_username').val() == "") return true;
// set up hourglass on body
$('body').css('cursor', 'wait');
$('#openid_submit').css('cursor', 'wait');
// disable submit button on form
$('input[type=submit]', this).attr('disabled', 'disabled');
var url = openid.provider_url;
if (url) {
url = url.replace('{username}', $('#openid_username').val());
openid.setOpenIdUrl(url);
}
return true;
},
setOpenIdUrl: function (url) {
var hidden = $('#' + this.input_id);
hidden.val(url);
// Clear OAuth credentials
$('#oauth_version').val('');
$('#oauth_server').val('');
},
setOAuthInfo: function (version, server) {
var ver = $('#oauth_version');
ver.val(version);
var serv = $('#oauth_server');
serv.val(server);
// Clear OpenId credentials
$('#' + this.input_id).val('');
},
highlight: function (box_id) {
// remove previous highlight.
var highlight = $('#openid_highlight');
if (highlight) {
highlight.replaceWith($('#openid_highlight a')[0]);
}
// add new highlight.
$('.' + box_id).wrap('<div id="openid_highlight"></div>');
},
useInputBox: function (provider) {
var input_area = $('#openid_input_area');
var html = '';
var id = 'openid_username';
var value = '';
var label = provider['label'];
var style = '';
if (label) {
html = '<p>' + label + '</p>';
}
html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />' +
'<input id="openid_submit" type="submit" value="Sign In"/>';
input_area.empty();
input_area.append(html);
$('#' + id).focus();
}
}; | JavaScript |
/* Demonstration of embedding CodeMirror in a bigger application. The
* interface defined here is a mess of prompts and confirms, and
* should probably not be used in a real project.
*/
function MirrorFrame(place, options) {
this.home = document.createElement("DIV");
if (place.appendChild)
place.appendChild(this.home);
else
place(this.home);
var self = this;
function makeButton(name, action) {
var button = document.createElement("INPUT");
button.type = "button";
button.value = name;
self.home.appendChild(button);
button.onclick = function(){self[action].call(self);};
}
makeButton("Search", "search");
makeButton("Replace", "replace");
makeButton("Current line", "line");
makeButton("Jump to line", "jump");
makeButton("Insert constructor", "macro");
makeButton("Indent all", "reindent");
this.mirror = new CodeMirror(this.home, options);
}
MirrorFrame.prototype = {
search: function() {
var text = prompt("Enter search term:", "");
if (!text) return;
var first = true;
do {
var cursor = this.mirror.getSearchCursor(text, first, true);
first = false;
while (cursor.findNext()) {
cursor.select();
if (!confirm("Search again?"))
return;
}
} while (confirm("End of document reached. Start over?"));
},
replace: function() {
// This is a replace-all, but it is possible to implement a
// prompting replace.
var from = prompt("Enter search string:", ""), to;
if (from) to = prompt("What should it be replaced with?", "");
if (to == null) return;
var cursor = this.mirror.getSearchCursor(from, false);
while (cursor.findNext())
cursor.replace(to);
},
jump: function() {
var line = prompt("Jump to line:", "");
if (line && !isNaN(Number(line)))
this.mirror.jumpToLine(Number(line));
},
line: function() {
alert("The cursor is currently at line " + this.mirror.currentLine());
this.mirror.focus();
},
macro: function() {
var name = prompt("Name your constructor:", "");
if (name)
this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n");
},
reindent: function() {
this.mirror.reindent();
}
};
| JavaScript |
var HTMLMixedParser = Editor.Parser = (function() {
if (!(CSSParser && JSParser && XMLParser))
throw new Error("CSS, JS, and XML parsers must be loaded for HTML mixed mode to work.");
XMLParser.configure({useHTMLKludges: true});
function parseMixed(stream) {
var htmlParser = XMLParser.make(stream), localParser = null, inTag = false;
var iter = {next: top, copy: copy};
function top() {
var token = htmlParser.next();
if (token.content == "<")
inTag = true;
else if (token.style == "xml-tagname" && inTag === true)
inTag = token.content.toLowerCase();
else if (token.content == ">") {
if (inTag == "script")
iter.next = local(JSParser, "</script");
else if (inTag == "style")
iter.next = local(CSSParser, "</style");
inTag = false;
}
return token;
}
function local(parser, tag) {
var baseIndent = htmlParser.indentation();
localParser = parser.make(stream, baseIndent + indentUnit);
return function() {
if (stream.lookAhead(tag, false, false, true)) {
localParser = null;
iter.next = top;
return top();
}
var token = localParser.next();
var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length);
if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) &&
stream.lookAhead(tag.slice(sz), false, false, true)) {
stream.push(token.value.slice(lt));
token.value = token.value.slice(0, lt);
}
if (token.indentation) {
var oldIndent = token.indentation;
token.indentation = function(chars) {
if (chars == "</")
return baseIndent;
else
return oldIndent(chars);
}
}
return token;
};
}
function copy() {
var _html = htmlParser.copy(), _local = localParser && localParser.copy(),
_next = iter.next, _inTag = inTag;
return function(_stream) {
stream = _stream;
htmlParser = _html(_stream);
localParser = _local && _local(_stream);
iter.next = _next;
inTag = _inTag;
return iter;
};
}
return iter;
}
return {make: parseMixed, electricChars: "{}/:"};
})();
| JavaScript |
/* Simple parser for CSS */
var CSSParser = Editor.Parser = (function() {
var tokenizeCSS = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "@") {
source.nextWhileMatches(/\w/);
return "css-at";
}
else if (ch == "/" && source.equals("*")) {
setState(inCComment);
return null;
}
else if (ch == "<" && source.equals("!")) {
setState(inSGMLComment);
return null;
}
else if (ch == "=") {
return "css-compare";
}
else if (source.equals("=") && (ch == "~" || ch == "|")) {
source.next();
return "css-compare";
}
else if (ch == "\"" || ch == "'") {
setState(inString(ch));
return null;
}
else if (ch == "#") {
source.nextWhileMatches(/\w/);
return "css-hash";
}
else if (ch == "!") {
source.nextWhileMatches(/[ \t]/);
source.nextWhileMatches(/\w/);
return "css-important";
}
else if (/\d/.test(ch)) {
source.nextWhileMatches(/[\w.%]/);
return "css-unit";
}
else if (/[,.+>*\/]/.test(ch)) {
return "css-select-op";
}
else if (/[;{}:\[\]]/.test(ch)) {
return "css-punctuation";
}
else {
source.nextWhileMatches(/[\w\\\-_]/);
return "css-identifier";
}
}
function inCComment(source, setState) {
var maybeEnd = false;
while (!source.endOfLine()) {
var ch = source.next();
if (maybeEnd && ch == "/") {
setState(normal);
break;
}
maybeEnd = (ch == "*");
}
return "css-comment";
}
function inSGMLComment(source, setState) {
var dashes = 0;
while (!source.endOfLine()) {
var ch = source.next();
if (dashes >= 2 && ch == ">") {
setState(normal);
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return "css-comment";
}
function inString(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped)
setState(normal);
return "css-string";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentCSS(inBraces, inRule, base) {
return function(nextChars) {
if (!inBraces || /^\}/.test(nextChars)) return base;
else if (inRule) return base + indentUnit * 2;
else return base + indentUnit;
};
}
// This is a very simplistic parser -- since CSS does not really
// nest, it works acceptably well, but some nicer colouroing could
// be provided with a more complicated parser.
function parseCSS(source, basecolumn) {
basecolumn = basecolumn || 0;
var tokens = tokenizeCSS(source);
var inBraces = false, inRule = false;
var iter = {
next: function() {
var token = tokens.next(), style = token.style, content = token.content;
if (style == "css-identifier" && inRule)
token.style = "css-value";
if (style == "css-hash")
token.style = inRule ? "css-colorcode" : "css-identifier";
if (content == "\n")
token.indentation = indentCSS(inBraces, inRule, basecolumn);
if (content == "{")
inBraces = true;
else if (content == "}")
inBraces = inRule = false;
else if (inBraces && content == ";")
inRule = false;
else if (inBraces && style != "css-comment" && style != "whitespace")
inRule = true;
return token;
},
copy: function() {
var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeCSS(source, _tokenState);
inBraces = _inBraces;
inRule = _inRule;
return iter;
};
}
};
return iter;
}
return {make: parseCSS, electricChars: "}"};
})();
| JavaScript |
/* Functionality for finding, storing, and restoring selections
*
* This does not provide a generic API, just the minimal functionality
* required by the CodeMirror system.
*/
// Namespace object.
var select = {};
(function() {
select.ie_selection = document.selection && document.selection.createRangeCollection;
// Find the 'top-level' (defined as 'a direct child of the node
// passed as the top argument') node that the given node is
// contained in. Return null if the given node is not inside the top
// node.
function topLevelNodeAt(node, top) {
while (node && node.parentNode != top)
node = node.parentNode;
return node;
}
// Find the top-level node that contains the node before this one.
function topLevelNodeBefore(node, top) {
while (!node.previousSibling && node.parentNode != top)
node = node.parentNode;
return topLevelNodeAt(node.previousSibling, top);
}
var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
select.scrollToNode = function(element) {
if (!element) return;
var doc = element.ownerDocument, body = doc.body,
win = (doc.defaultView || doc.parentWindow),
html = doc.documentElement,
atEnd = !element.nextSibling || !element.nextSibling.nextSibling
|| !element.nextSibling.nextSibling.nextSibling;
// In Opera (and recent Webkit versions), BR elements *always*
// have a offsetTop property of zero.
var compensateHack = 0;
while (element && !element.offsetTop) {
compensateHack++;
element = element.previousSibling;
}
// atEnd is another kludge for these browsers -- if the cursor is
// at the end of the document, and the node doesn't have an
// offset, just scroll to the end.
if (compensateHack == 0) atEnd = false;
var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, pos = element;
while (pos && pos.offsetParent) {
y += pos.offsetTop;
// Don't count X offset for <br> nodes
if (!isBR(pos))
x += pos.offsetLeft;
pos = pos.offsetParent;
}
var scroll_x = body.scrollLeft || html.scrollLeft || 0,
scroll_y = body.scrollTop || html.scrollTop || 0,
screen_x = x - scroll_x, screen_y = y - scroll_y, scroll = false;
if (screen_x < 0 || screen_x > (win.innerWidth || html.clientWidth || 0)) {
scroll_x = x;
scroll = true;
}
if (screen_y < 0 || atEnd || screen_y > (win.innerHeight || html.clientHeight || 0) - 50) {
scroll_y = atEnd ? 1e6 : y;
scroll = true;
}
if (scroll) win.scrollTo(scroll_x, scroll_y);
};
select.scrollToCursor = function(container) {
select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild);
};
// Used to prevent restoring a selection when we do not need to.
var currentSelection = null;
select.snapshotChanged = function() {
if (currentSelection) currentSelection.changed = true;
};
// This is called by the code in editor.js whenever it is replacing
// a text node. The function sees whether the given oldNode is part
// of the current selection, and updates this selection if it is.
// Because nodes are often only partially replaced, the length of
// the part that gets replaced has to be taken into account -- the
// selection might stay in the oldNode if the newNode is smaller
// than the selection's offset. The offset argument is needed in
// case the selection does move to the new object, and the given
// length is not the whole length of the new node (part of it might
// have been used to replace another node).
select.snapshotReplaceNode = function(from, to, length, offset) {
if (!currentSelection) return;
function replace(point) {
if (from == point.node) {
currentSelection.changed = true;
if (length && point.offset > length) {
point.offset -= length;
}
else {
point.node = to;
point.offset += (offset || 0);
}
}
}
replace(currentSelection.start);
replace(currentSelection.end);
};
select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
if (!currentSelection) return;
function move(point) {
if (from == point.node && (!ifAtStart || point.offset == 0)) {
currentSelection.changed = true;
point.node = to;
if (relative) point.offset = Math.max(0, point.offset + distance);
else point.offset = distance;
}
}
move(currentSelection.start);
move(currentSelection.end);
};
// Most functions are defined in two ways, one for the IE selection
// model, one for the W3C one.
if (select.ie_selection) {
function selectionNode(win, start) {
var range = win.document.selection.createRange();
range.collapse(start);
function nodeAfter(node) {
var found = null;
while (!found && node) {
found = node.nextSibling;
node = node.parentNode;
}
return nodeAtStartOf(found);
}
function nodeAtStartOf(node) {
while (node && node.firstChild) node = node.firstChild;
return {node: node, offset: 0};
}
var containing = range.parentElement();
if (!isAncestor(win.document.body, containing)) return null;
if (!containing.firstChild) return nodeAtStartOf(containing);
var working = range.duplicate();
working.moveToElementText(containing);
working.collapse(true);
for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
if (cur.nodeType == 3) {
var size = cur.nodeValue.length;
working.move("character", size);
}
else {
working.moveToElementText(cur);
working.collapse(false);
}
var dir = range.compareEndPoints("StartToStart", working);
if (dir == 0) return nodeAfter(cur);
if (dir == 1) continue;
if (cur.nodeType != 3) return nodeAtStartOf(cur);
working.setEndPoint("StartToEnd", range);
return {node: cur, offset: size - working.text.length};
}
return nodeAfter(containing);
}
select.markSelection = function(win) {
currentSelection = null;
var sel = win.document.selection;
if (!sel) return;
var start = selectionNode(win, true),
end = selectionNode(win, false);
if (!start || !end) return;
currentSelection = {start: start, end: end, window: win, changed: false};
};
select.selectMarked = function() {
if (!currentSelection || !currentSelection.changed) return;
var win = currentSelection.window, doc = win.document;
function makeRange(point) {
var range = doc.body.createTextRange(),
node = point.node;
if (!node) {
range.moveToElementText(currentSelection.window.document.body);
range.collapse(false);
}
else if (node.nodeType == 3) {
range.moveToElementText(node.parentNode);
var offset = point.offset;
while (node.previousSibling) {
node = node.previousSibling;
offset += (node.innerText || "").length;
}
range.move("character", offset);
}
else {
range.moveToElementText(node);
range.collapse(true);
}
return range;
}
var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
start.setEndPoint("StartToEnd", end);
start.select();
};
// Get the top-level node that one end of the cursor is inside or
// after. Note that this returns false for 'no cursor', and null
// for 'start of document'.
select.selectionTopNode = function(container, start) {
var selection = container.ownerDocument.selection;
if (!selection) return false;
var range = selection.createRange(), range2 = range.duplicate();
range.collapse(start);
var around = range.parentElement();
if (around && isAncestor(container, around)) {
// Only use this node if the selection is not at its start.
range2.moveToElementText(around);
if (range.compareEndPoints("StartToStart", range2) == 1)
return topLevelNodeAt(around, container);
}
// Move the start of a range to the start of a node,
// compensating for the fact that you can't call
// moveToElementText with text nodes.
function moveToNodeStart(range, node) {
if (node.nodeType == 3) {
var count = 0, cur = node.previousSibling;
while (cur && cur.nodeType == 3) {
count += cur.nodeValue.length;
cur = cur.previousSibling;
}
if (cur) {
try{range.moveToElementText(cur);}
catch(e){return false;}
range.collapse(false);
}
else range.moveToElementText(node.parentNode);
if (count) range.move("character", count);
}
else {
try{range.moveToElementText(node);}
catch(e){return false;}
}
return true;
}
// Do a binary search through the container object, comparing
// the start of each node to the selection
var start = 0, end = container.childNodes.length - 1;
while (start < end) {
var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
if (!node) return false; // Don't ask. IE6 manages this sometimes.
if (!moveToNodeStart(range2, node)) return false;
if (range.compareEndPoints("StartToStart", range2) == 1)
start = middle;
else
end = middle - 1;
}
return container.childNodes[start] || null;
};
// Place the cursor after this.start. This is only useful when
// manually moving the cursor instead of restoring it to its old
// position.
select.focusAfterNode = function(node, container) {
var range = container.ownerDocument.body.createTextRange();
range.moveToElementText(node || container);
range.collapse(!node);
range.select();
};
select.somethingSelected = function(win) {
var sel = win.document.selection;
return sel && (sel.createRange().text != "");
};
function insertAtCursor(window, html) {
var selection = window.document.selection;
if (selection) {
var range = selection.createRange();
range.pasteHTML(html);
range.collapse(false);
range.select();
}
}
// Used to normalize the effect of the enter key, since browsers
// do widely different things when pressing enter in designMode.
select.insertNewlineAtCursor = function(window) {
insertAtCursor(window, "<br>");
};
select.insertTabAtCursor = function(window) {
insertAtCursor(window, fourSpaces);
};
// Get the BR node at the start of the line on which the cursor
// currently is, and the offset into the line. Returns null as
// node if cursor is on first line.
select.cursorPos = function(container, start) {
var selection = container.ownerDocument.selection;
if (!selection) return null;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
var range = selection.createRange(), range2 = range.duplicate();
range.collapse(start);
if (topNode) {
range2.moveToElementText(topNode);
range2.collapse(false);
}
else {
// When nothing is selected, we can get all kinds of funky errors here.
try { range2.moveToElementText(container); }
catch (e) { return null; }
range2.collapse(true);
}
range.setEndPoint("StartToStart", range2);
return {node: topNode, offset: range.text.length};
};
select.setCursorPos = function(container, from, to) {
function rangeAt(pos) {
var range = container.ownerDocument.body.createTextRange();
if (!pos.node) {
range.moveToElementText(container);
range.collapse(true);
}
else {
range.moveToElementText(pos.node);
range.collapse(false);
}
range.move("character", pos.offset);
return range;
}
var range = rangeAt(from);
if (to && to != from)
range.setEndPoint("EndToEnd", rangeAt(to));
range.select();
}
// Some hacks for storing and re-storing the selection when the editor loses and regains focus.
select.getBookmark = function (container) {
var from = select.cursorPos(container, true), to = select.cursorPos(container, false);
if (from && to) return {from: from, to: to};
};
// Restore a stored selection.
select.setBookmark = function(container, mark) {
if (!mark) return;
select.setCursorPos(container, mark.from, mark.to);
};
}
// W3C model
else {
// Store start and end nodes, and offsets within these, and refer
// back to the selection object from those nodes, so that this
// object can be updated when the nodes are replaced before the
// selection is restored.
select.markSelection = function (win) {
var selection = win.getSelection();
if (!selection || selection.rangeCount == 0)
return (currentSelection = null);
var range = selection.getRangeAt(0);
currentSelection = {
start: {node: range.startContainer, offset: range.startOffset},
end: {node: range.endContainer, offset: range.endOffset},
window: win,
changed: false
};
// We want the nodes right at the cursor, not one of their
// ancestors with a suitable offset. This goes down the DOM tree
// until a 'leaf' is reached (or is it *up* the DOM tree?).
function normalize(point){
while (point.node.nodeType != 3 && !isBR(point.node)) {
var newNode = point.node.childNodes[point.offset] || point.node.nextSibling;
point.offset = 0;
while (!newNode && point.node.parentNode) {
point.node = point.node.parentNode;
newNode = point.node.nextSibling;
}
point.node = newNode;
if (!newNode)
break;
}
}
normalize(currentSelection.start);
normalize(currentSelection.end);
};
select.selectMarked = function () {
var cs = currentSelection;
// on webkit-based browsers, it is apparently possible that the
// selection gets reset even when a node that is not one of the
// endpoints get messed with. the most common situation where
// this occurs is when a selection is deleted or overwitten. we
// check for that here.
function focusIssue() {
return cs.start.node == cs.end.node && cs.start.offset == 0 && cs.end.offset == 0;
}
if (!cs || !(cs.changed || (webkit && focusIssue()))) return;
var win = cs.window, range = win.document.createRange();
function setPoint(point, which) {
if (point.node) {
// Some magic to generalize the setting of the start and end
// of a range.
if (point.offset == 0)
range["set" + which + "Before"](point.node);
else
range["set" + which](point.node, point.offset);
}
else {
range.setStartAfter(win.document.body.lastChild || win.document.body);
}
}
setPoint(cs.end, "End");
setPoint(cs.start, "Start");
selectRange(range, win);
};
// Helper for selecting a range object.
function selectRange(range, window) {
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
function selectionRange(window) {
var selection = window.getSelection();
if (!selection || selection.rangeCount == 0)
return false;
else
return selection.getRangeAt(0);
}
// Finding the top-level node at the cursor in the W3C is, as you
// can see, quite an involved process.
select.selectionTopNode = function(container, start) {
var range = selectionRange(container.ownerDocument.defaultView);
if (!range) return false;
var node = start ? range.startContainer : range.endContainer;
var offset = start ? range.startOffset : range.endOffset;
// Work around (yet another) bug in Opera's selection model.
if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
offset--;
// For text nodes, we look at the node itself if the cursor is
// inside, or at the node before it if the cursor is at the
// start.
if (node.nodeType == 3){
if (offset > 0)
return topLevelNodeAt(node, container);
else
return topLevelNodeBefore(node, container);
}
// Occasionally, browsers will return the HTML node as
// selection. If the offset is 0, we take the start of the frame
// ('after null'), otherwise, we take the last node.
else if (node.nodeName.toUpperCase() == "HTML") {
return (offset == 1 ? null : container.lastChild);
}
// If the given node is our 'container', we just look up the
// correct node by using the offset.
else if (node == container) {
return (offset == 0) ? null : node.childNodes[offset - 1];
}
// In any other case, we have a regular node. If the cursor is
// at the end of the node, we use the node itself, if it is at
// the start, we use the node before it, and in any other
// case, we look up the child before the cursor and use that.
else {
if (offset == node.childNodes.length)
return topLevelNodeAt(node, container);
else if (offset == 0)
return topLevelNodeBefore(node, container);
else
return topLevelNodeAt(node.childNodes[offset - 1], container);
}
};
select.focusAfterNode = function(node, container) {
var win = container.ownerDocument.defaultView,
range = win.document.createRange();
range.setStartBefore(container.firstChild || container);
// In Opera, setting the end of a range at the end of a line
// (before a BR) will cause the cursor to appear on the next
// line, so we set the end inside of the start node when
// possible.
if (node && !node.firstChild)
range.setEndAfter(node);
else if (node)
range.setEnd(node, node.childNodes.length);
else
range.setEndBefore(container.firstChild || container);
range.collapse(false);
selectRange(range, win);
};
select.somethingSelected = function(win) {
var range = selectionRange(win);
return range && !range.collapsed;
};
function insertNodeAtCursor(window, node) {
var range = selectionRange(window);
if (!range) return;
range.deleteContents();
range.insertNode(node);
webkitLastLineHack(window.document.body);
range = window.document.createRange();
range.selectNode(node);
range.collapse(false);
selectRange(range, window);
}
select.insertNewlineAtCursor = function(window) {
insertNodeAtCursor(window, window.document.createElement("BR"));
};
select.insertTabAtCursor = function(window) {
insertNodeAtCursor(window, window.document.createTextNode(fourSpaces));
};
select.cursorPos = function(container, start) {
var range = selectionRange(window);
if (!range) return;
var topNode = select.selectionTopNode(container, start);
while (topNode && !isBR(topNode))
topNode = topNode.previousSibling;
range = range.cloneRange();
range.collapse(start);
if (topNode)
range.setStartAfter(topNode);
else
range.setStartBefore(container);
return {node: topNode, offset: range.toString().length};
};
select.setCursorPos = function(container, from, to) {
var win = container.ownerDocument.defaultView,
range = win.document.createRange();
function setPoint(node, offset, side) {
if (offset == 0 && node && !node.nextSibling) {
range["set" + side + "After"](node);
return true;
}
if (!node)
node = container.firstChild;
else
node = node.nextSibling;
if (!node) return;
if (offset == 0) {
range["set" + side + "Before"](node);
return true;
}
var backlog = []
function decompose(node) {
if (node.nodeType == 3)
backlog.push(node);
else
forEach(node.childNodes, decompose);
}
while (true) {
while (node && !backlog.length) {
decompose(node);
node = node.nextSibling;
}
var cur = backlog.shift();
if (!cur) return false;
var length = cur.nodeValue.length;
if (length >= offset) {
range["set" + side](cur, offset);
return true;
}
offset -= length;
}
}
to = to || from;
if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
selectRange(range, win);
};
}
})();
| JavaScript |
/* A few useful utility functions. */
// Capture a method on an object.
function method(obj, name) {
return function() {obj[name].apply(obj, arguments);};
}
// The value used to signal the end of a sequence in iterators.
var StopIteration = {toString: function() {return "StopIteration"}};
// Apply a function to each element in a sequence.
function forEach(iter, f) {
if (iter.next) {
try {while (true) f(iter.next());}
catch (e) {if (e != StopIteration) throw e;}
}
else {
for (var i = 0; i < iter.length; i++)
f(iter[i]);
}
}
// Map a function over a sequence, producing an array of results.
function map(iter, f) {
var accum = [];
forEach(iter, function(val) {accum.push(f(val));});
return accum;
}
// Create a predicate function that tests a string againsts a given
// regular expression. No longer used but might be used by 3rd party
// parsers.
function matcher(regexp){
return function(value){return regexp.test(value);};
}
// Test whether a DOM node has a certain CSS class. Much faster than
// the MochiKit equivalent, for some reason.
function hasClass(element, className){
var classes = element.className;
return classes && new RegExp("(^| )" + className + "($| )").test(classes);
}
// Insert a DOM node after another node.
function insertAfter(newNode, oldNode) {
var parent = oldNode.parentNode;
parent.insertBefore(newNode, oldNode.nextSibling);
return newNode;
}
function removeElement(node) {
if (node.parentNode)
node.parentNode.removeChild(node);
}
function clearElement(node) {
while (node.firstChild)
node.removeChild(node.firstChild);
}
// Check whether a node is contained in another one.
function isAncestor(node, child) {
while (child = child.parentNode) {
if (node == child)
return true;
}
return false;
}
// The non-breaking space character.
var nbsp = "\u00a0";
var matching = {"{": "}", "[": "]", "(": ")",
"}": "{", "]": "[", ")": "("};
// Standardize a few unportable event properties.
function normalizeEvent(event) {
if (!event.stopPropagation) {
event.stopPropagation = function() {this.cancelBubble = true;};
event.preventDefault = function() {this.returnValue = false;};
}
if (!event.stop) {
event.stop = function() {
this.stopPropagation();
this.preventDefault();
};
}
if (event.type == "keypress") {
event.code = (event.charCode == null) ? event.keyCode : event.charCode;
event.character = String.fromCharCode(event.code);
}
return event;
}
// Portably register event handlers.
function addEventHandler(node, type, handler, removeFunc) {
function wrapHandler(event) {
handler(normalizeEvent(event || window.event));
}
if (typeof node.addEventListener == "function") {
node.addEventListener(type, wrapHandler, false);
if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);};
}
else {
node.attachEvent("on" + type, wrapHandler);
if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);};
}
}
function nodeText(node) {
return node.textContent || node.innerText || node.nodeValue || "";
}
function nodeTop(node) {
var top = 0;
while (node.offsetParent) {
top += node.offsetTop;
node = node.offsetParent;
}
return top;
}
function isBR(node) {
var nn = node.nodeName;
return nn == "BR" || nn == "br";
}
function isSpan(node) {
var nn = node.nodeName;
return nn == "SPAN" || nn == "span";
}
| JavaScript |
var SparqlParser = Editor.Parser = (function() {
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
"isblank", "isliteral", "union", "a"]);
var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
"ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
"graph", "by", "asc", "desc", ]);
var operatorChars = /[*+\-<>=&|]/;
var tokenizeSparql = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "$" || ch == "?") {
source.nextWhileMatches(/[\w\d]/);
return "sp-var";
}
else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) {
source.nextWhileMatches(/[^\s\u00a0>]/);
if (source.equals(">")) source.next();
return "sp-uri";
}
else if (ch == "\"" || ch == "'") {
setState(inLiteral(ch));
return null;
}
else if (/[{}\(\),\.;\[\]]/.test(ch)) {
return "sp-punc";
}
else if (ch == "#") {
while (!source.endOfLine()) source.next();
return "sp-comment";
}
else if (operatorChars.test(ch)) {
source.nextWhileMatches(operatorChars);
return "sp-operator";
}
else if (ch == ":") {
source.nextWhileMatches(/[\w\d\._\-]/);
return "sp-prefixed";
}
else {
source.nextWhileMatches(/[_\w\d]/);
if (source.equals(":")) {
source.next();
source.nextWhileMatches(/[\w\d_\-]/);
return "sp-prefixed";
}
var word = source.get(), type;
if (ops.test(word))
type = "sp-operator";
else if (keywords.test(word))
type = "sp-keyword";
else
type = "sp-word";
return {style: type, content: word};
}
}
function inLiteral(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped) {
setState(normal);
break;
}
escaped = !escaped && ch == "\\";
}
return "sp-literal";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentSparql(context) {
return function(nextChars) {
var firstChar = nextChars && nextChars.charAt(0);
if (/[\]\}]/.test(firstChar))
while (context && context.type == "pattern") context = context.prev;
var closing = context && firstChar == matching[context.type];
if (!context)
return 0;
else if (context.type == "pattern")
return context.col;
else if (context.align)
return context.col - (closing ? context.width : 0);
else
return context.indent + (closing ? 0 : indentUnit);
}
}
function parseSparql(source) {
var tokens = tokenizeSparql(source);
var context = null, indent = 0, col = 0;
function pushContext(type, width) {
context = {prev: context, indent: indent, col: col, type: type, width: width};
}
function popContext() {
context = context.prev;
}
var iter = {
next: function() {
var token = tokens.next(), type = token.style, content = token.content, width = token.value.length;
if (content == "\n") {
token.indentation = indentSparql(context);
indent = col = 0;
if (context && context.align == null) context.align = false;
}
else if (type == "whitespace" && col == 0) {
indent = width;
}
else if (type != "sp-comment" && context && context.align == null) {
context.align = true;
}
if (content != "\n") col += width;
if (/[\[\{\(]/.test(content)) {
pushContext(content, width);
}
else if (/[\]\}\)]/.test(content)) {
while (context && context.type == "pattern")
popContext();
if (context && content == matching[context.type])
popContext();
}
else if (content == "." && context && context.type == "pattern") {
popContext();
}
else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") &&
context && /[\{\[]/.test(context.type)) {
pushContext("pattern", width);
}
return token;
},
copy: function() {
var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeSparql(source, _tokenState);
context = _context;
indent = _indent;
col = _col;
return iter;
};
}
};
return iter;
}
return {make: parseSparql, electricChars: "}]"};
})();
| JavaScript |
var SqlParser = Editor.Parser = (function() {
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var functions = wordRegexp([
"abs", "acos", "adddate", "aes_encrypt", "aes_decrypt", "ascii",
"asin", "atan", "atan2", "avg", "benchmark", "bin", "bit_and",
"bit_count", "bit_length", "bit_or", "cast", "ceil", "ceiling",
"char_length", "character_length", "checksum_agg", "coalesce", "concat", "concat_ws",
"connection_id", "conv", "convert", "cos", "cot", "count", "curdate",
"current_date", "current_time", "current_timestamp", "current_user",
"curtime", "database", "dateadd", "datediff", "datename", "datepart",
"day", "dayofmonth", "dayofweek", "dayofyear", "decode", "degrees", "dense_rank",
"des_encrypt", "des_decrypt", "elt", "encode", "encrypt", "exp",
"export_set", "extract", "field", "find_in_set", "floor", "format",
"found_rows", "from_days", "from_unixtime", "get_lock", "getdate", "getutcdate", "greatest",
"group_unique_users", "grouping", "hex", "ifnull", "inet_aton", "inet_ntoa", "instr",
"interval", "is_free_lock", "isnull", "last_insert_id", "lcase", "least",
"left", "length", "ln", "load_file", "locate", "log", "log2", "log10",
"lower", "lpad", "ltrim", "make_set", "master_pos_wait", "max", "md5",
"mid", "min", "mod", "month", "now", "ntile", "nullif", "oct", "octet_length",
"ord", "password", "period_add", "period_diff", "pi", "position",
"pow", "power", "quarter", "quote", "radians", "rand", "rank", "release_lock",
"repeat", "reverse", "right", "round", "row_number", "rpad", "rtrim", "sec_to_time",
"session_user", "sha", "sha1", "sign", "sin", "soundex", "space", "sqrt",
"std", "stdev", "stdevp", "strcmp", "subdate", "substring", "substring_index",
"sum", "sysdate", "system_user", "tan", "time_format", "time_to_sec",
"to_days", "trim", "ucase", "unique_users", "unix_timestamp", "upper",
"user", "var", "varp", "version", "week", "weekday", "year", "yearweek"
]);
var keywords = wordRegexp([
"alter", "grant", "revoke", "primary", "key", "clustered", "nonclustered", "table", "start", "top",
"begin", "tran", "transaction", "select", "update", "insert", "delete", "merge", "create", "describe", "declare",
"from", "into", "values", "where", "join", "inner", "left", "outer", "natural", "cross", "apply", "except", "and",
"or", "in", "not", "xor", "like", "using", "on", "order", "group", "by",
"case", "when", "then", "else", "end", "with", "rollup", "cube", "over", "partition",
"asc", "desc", "limit", "offset", "union", "all", "as", "distinct", "set",
"commit", "rollback", "replace", "view", "database", "separator", "if", "for", "while",
"exists", "null", "truncate", "status", "show", "lock", "unique", "having"
]);
var types = wordRegexp([
"bigint", "binary", "bit", "blob", "bool", "char", "character", "date",
"datetime", "dec", "decimal", "double", "enum", "float", "float4", "float8",
"int", "int1", "int2", "int3", "int4", "int8", "integer", "long", "longblob",
"longtext", "mediumblob", "mediumint", "mediumtext", "middleint", "nchar",
"numeric", "real", "set", "smallint", "text", "time", "timestamp", "tinyblob",
"tinyint", "tinytext", "varbinary", "varchar", "nvarchar", "xml", "string" // <- this is an SEDE hack
]);
var operators = wordRegexp([
":=", "<", "<=", "==", "<>", ">", ">=", "like", "rlike", "in", "xor", "between"
]);
var operatorChars = /[*+\-<>=&|:\/]/;
var tokenizeSql = (function() {
function normal(source, setState) {
var ch = source.next();
if (ch == "@" || ch == "$") {
source.nextWhileMatches(/[\w\d]/);
return "sql-var";
}
else if (ch == "["){
setState(inAlias(ch))
return null;
}
else if (ch == "\"" || ch == "'" || ch == "`") {
setState(inLiteral(ch));
return null;
}
else if (ch == "," || ch == ";") {
return "sql-separator"
}
else if (ch == '-') {
if (source.peek() == "-") {
while (!source.endOfLine()) source.next();
return "sql-comment";
}
else if (/\d/.test(source.peek())) {
source.nextWhileMatches(/\d/);
if (source.peek() == '.') {
source.next();
source.nextWhileMatches(/\d/);
}
return "sql-number";
}
else
return "sql-operator";
}
else if (operatorChars.test(ch)) {
source.nextWhileMatches(operatorChars);
return "sql-operator";
}
else if (/\d/.test(ch)) {
source.nextWhileMatches(/\d/);
if (source.peek() == '.') {
source.next();
source.nextWhileMatches(/\d/);
}
return "sql-number";
}
else if (/[()]/.test(ch)) {
return "sql-punctuation";
}
else {
source.nextWhileMatches(/[_\w\d]/);
var word = source.get(), type;
if (operators.test(word))
type = "sql-operator";
else if (keywords.test(word))
type = "sql-keyword";
else if (functions.test(word))
type = "sql-function";
else if (types.test(word))
type = "sql-type";
else
type = "sql-word";
return {style: type, content: word};
}
}
function inAlias(quote) {
return function(source, setState) {
while (!source.endOfLine()) {
var ch = source.next();
if (ch == ']') {
setState(normal);
break;
}
}
return "sql-word";
}
}
function inLiteral(quote) {
return function(source, setState) {
var escaped = false;
while (!source.endOfLine()) {
var ch = source.next();
if (ch == quote && !escaped) {
setState(normal);
break;
}
escaped = !escaped && ch == "\\";
}
return quote == "`" ? "sql-word" : "sql-literal";
};
}
return function(source, startState) {
return tokenizer(source, startState || normal);
};
})();
function indentSql(context) {
return function(nextChars) {
var firstChar = nextChars && nextChars.charAt(0);
var closing = context && firstChar == context.type;
if (!context)
return 0;
else if (context.align)
return context.col - (closing ? context.width : 0);
else
return context.indent + (closing ? 0 : indentUnit);
}
}
function parseSql(source) {
var tokens = tokenizeSql(source);
var context = null, indent = 0, col = 0;
function pushContext(type, width, align) {
context = {prev: context, indent: indent, col: col, type: type, width: width, align: align};
}
function popContext() {
context = context.prev;
}
var iter = {
next: function() {
var token = tokens.next();
var type = token.style, content = token.content, width = token.value.length;
if (content == "\n") {
// token.indentation = indentSql(context);
indent = col = 0;
if (context && context.align == null) context.align = false;
}
else if (type == "whitespace" && col == 0) {
indent = width;
}
else if (!context && type != "sql-comment") {
pushContext(";", 0, false);
}
if (content != "\n") col += width;
if (type == "sql-punctuation") {
if (content == "(")
pushContext(")", width);
else if (content == ")")
popContext();
}
else if (type == "sql-separator" && content == ";" && context && !context.prev) {
popContext();
}
return token;
},
copy: function() {
var _context = context, _indent = indent, _col = col, _tokenState = tokens.state;
return function(source) {
tokens = tokenizeSql(source, _tokenState);
context = _context;
indent = _indent;
col = _col;
return iter;
};
}
};
return iter;
}
// electric chars are just confusing
return {make: parseSql, electricChars: ""};
})();
| JavaScript |
/* This file defines an XML parser, with a few kludges to make it
* useable for HTML. autoSelfClosers defines a set of tag names that
* are expected to not have a closing tag, and doNotIndent specifies
* the tags inside of which no indentation should happen (see Config
* object). These can be disabled by passing the editor an object like
* {useHTMLKludges: false} as parserConfig option.
*/
var XMLParser = Editor.Parser = (function() {
var Kludges = {
autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
"meta": true, "col": true, "frame": true, "base": true, "area": true},
doNotIndent: {"pre": true, "!cdata": true}
};
var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}};
var UseKludges = Kludges;
var alignCDATA = false;
// Simple stateful tokenizer for XML documents. Returns a
// MochiKit-style iterator, with a state property that contains a
// function encapsulating the current state. See tokenize.js.
var tokenizeXML = (function() {
function inText(source, setState) {
var ch = source.next();
if (ch == "<") {
if (source.equals("!")) {
source.next();
if (source.equals("[")) {
if (source.lookAhead("[CDATA[", true)) {
setState(inBlock("xml-cdata", "]]>"));
return null;
}
else {
return "xml-text";
}
}
else if (source.lookAhead("--", true)) {
setState(inBlock("xml-comment", "-->"));
return null;
}
else {
return "xml-text";
}
}
else if (source.equals("?")) {
source.next();
source.nextWhileMatches(/[\w\._\-]/);
setState(inBlock("xml-processing", "?>"));
return "xml-processing";
}
else {
if (source.equals("/")) source.next();
setState(inTag);
return "xml-punctuation";
}
}
else if (ch == "&") {
while (!source.endOfLine()) {
if (source.next() == ";")
break;
}
return "xml-entity";
}
else {
source.nextWhileMatches(/[^&<\n]/);
return "xml-text";
}
}
function inTag(source, setState) {
var ch = source.next();
if (ch == ">") {
setState(inText);
return "xml-punctuation";
}
else if (/[?\/]/.test(ch) && source.equals(">")) {
source.next();
setState(inText);
return "xml-punctuation";
}
else if (ch == "=") {
return "xml-punctuation";
}
else if (/[\'\"]/.test(ch)) {
setState(inAttribute(ch));
return null;
}
else {
source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/);
return "xml-name";
}
}
function inAttribute(quote) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.next() == quote) {
setState(inTag);
break;
}
}
return "xml-attribute";
};
}
function inBlock(style, terminator) {
return function(source, setState) {
while (!source.endOfLine()) {
if (source.lookAhead(terminator, true)) {
setState(inText);
break;
}
source.next();
}
return style;
};
}
return function(source, startState) {
return tokenizer(source, startState || inText);
};
})();
// The parser. The structure of this function largely follows that of
// parseJavaScript in parsejavascript.js (there is actually a bit more
// shared code than I'd like), but it is quite a bit simpler.
function parseXML(source) {
var tokens = tokenizeXML(source), token;
var cc = [base];
var tokenNr = 0, indented = 0;
var currentTag = null, context = null;
var consume;
function push(fs) {
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
function cont() {
push(arguments);
consume = true;
}
function pass() {
push(arguments);
consume = false;
}
function markErr() {
token.style += " xml-error";
}
function expect(text) {
return function(style, content) {
if (content == text) cont();
else {markErr(); cont(arguments.callee);}
};
}
function pushContext(tagname, startOfLine) {
var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent);
context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent};
}
function popContext() {
context = context.prev;
}
function computeIndentation(baseContext) {
return function(nextChars, current) {
var context = baseContext;
if (context && context.noIndent)
return current;
if (alignCDATA && /<!\[CDATA\[/.test(nextChars))
return 0;
if (context && /^<\//.test(nextChars))
context = context.prev;
while (context && !context.startOfLine)
context = context.prev;
if (context)
return context.indent + indentUnit;
else
return 0;
};
}
function base() {
return pass(element, base);
}
var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true};
function element(style, content) {
if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1));
else if (content == "</") cont(closetagname, expect(">"));
else if (style == "xml-cdata") {
if (!context || context.name != "!cdata") pushContext("!cdata");
if (/\]\]>$/.test(content)) popContext();
cont();
}
else if (harmlessTokens.hasOwnProperty(style)) cont();
else {markErr(); cont();}
}
function tagname(style, content) {
if (style == "xml-name") {
currentTag = content.toLowerCase();
token.style = "xml-tagname";
cont();
}
else {
currentTag = null;
pass();
}
}
function closetagname(style, content) {
if (style == "xml-name") {
token.style = "xml-tagname";
if (context && content.toLowerCase() == context.name) popContext();
else markErr();
}
cont();
}
function endtag(startOfLine) {
return function(style, content) {
if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont();
else if (content == ">") {pushContext(currentTag, startOfLine); cont();}
else {markErr(); cont(arguments.callee);}
};
}
function attributes(style) {
if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);}
else pass();
}
function attribute(style, content) {
if (content == "=") cont(value);
else if (content == ">" || content == "/>") pass(endtag);
else pass();
}
function value(style) {
if (style == "xml-attribute") cont(value);
else pass();
}
return {
indentation: function() {return indented;},
next: function(){
token = tokens.next();
if (token.style == "whitespace" && tokenNr == 0)
indented = token.value.length;
else
tokenNr++;
if (token.content == "\n") {
indented = tokenNr = 0;
token.indentation = computeIndentation(context);
}
if (token.style == "whitespace" || token.type == "xml-comment")
return token;
while(true){
consume = false;
cc.pop()(token.style, token.content);
if (consume) return token;
}
},
copy: function(){
var _cc = cc.concat([]), _tokenState = tokens.state, _context = context;
var parser = this;
return function(input){
cc = _cc.concat([]);
tokenNr = indented = 0;
context = _context;
tokens = tokenizeXML(input, _tokenState);
return parser;
};
}
};
}
return {
make: parseXML,
electricChars: "/",
configure: function(config) {
if (config.useHTMLKludges != null)
UseKludges = config.useHTMLKludges ? Kludges : NoKludges;
if (config.alignCDATA)
alignCDATA = config.alignCDATA;
}
};
})();
| JavaScript |
/* Tokenizer for JavaScript code */
var tokenizeJavaScript = (function() {
// Advance the stream until the given character (not preceded by a
// backslash) is encountered, or the end of the line is reached.
function nextUntilUnescaped(source, end) {
var escaped = false;
while (!source.endOfLine()) {
var next = source.next();
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// A map of JavaScript's keywords. The a/b/c keyword distinction is
// very rough, but it gives the parser enough information to parse
// correct code correctly (we don't care that much how we parse
// incorrect code). The style information included in these objects
// is used by the highlighter to pick the correct CSS style for a
// token.
var keywords = function(){
function result(type, style){
return {type: type, style: "js-" + style};
}
// keywords that take a parenthised expression, and then a
// statement (if)
var keywordA = result("keyword a", "keyword");
// keywords that take just a statement (else)
var keywordB = result("keyword b", "keyword");
// keywords that optionally take an expression, and form a
// statement (return)
var keywordC = result("keyword c", "keyword");
var operator = result("operator", "keyword");
var atom = result("atom", "atom");
return {
"if": keywordA, "while": keywordA, "with": keywordA,
"else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB,
"return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC,
"in": operator, "typeof": operator, "instanceof": operator,
"var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"),
"for": result("for", "keyword"), "switch": result("switch", "keyword"),
"case": result("case", "keyword"), "default": result("default", "keyword"),
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
};
}();
// Some helper regexps
var isOperatorChar = /[+\-*&%=<>!?|]/;
var isHexDigit = /[0-9A-Fa-f]/;
var isWordChar = /[\w\$_]/;
// Wrapper around jsToken that helps maintain parser state (whether
// we are inside of a multi-line comment and whether the next token
// could be a regular expression).
function jsTokenState(inside, regexp) {
return function(source, setState) {
var newInside = inside;
var type = jsToken(inside, regexp, source, function(c) {newInside = c;});
var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/);
if (newRegexp != regexp || newInside != inside)
setState(jsTokenState(newInside, newRegexp));
return type;
};
}
// The token reader, intended to be used by the tokenizer from
// tokenize.js (through jsTokenState). Advances the source stream
// over a token, and returns an object containing the type and style
// of that token.
function jsToken(inside, regexp, source, setInside) {
function readHexNumber(){
source.next(); // skip the 'x'
source.nextWhileMatches(isHexDigit);
return {type: "number", style: "js-atom"};
}
function readNumber() {
source.nextWhileMatches(/[0-9]/);
if (source.equals(".")){
source.next();
source.nextWhileMatches(/[0-9]/);
}
if (source.equals("e") || source.equals("E")){
source.next();
if (source.equals("-"))
source.next();
source.nextWhileMatches(/[0-9]/);
}
return {type: "number", style: "js-atom"};
}
// Read a word, look it up in keywords. If not found, it is a
// variable, otherwise it is a keyword of the type found.
function readWord() {
source.nextWhileMatches(isWordChar);
var word = source.get();
var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word];
return known ? {type: known.type, style: known.style, content: word} :
{type: "variable", style: "js-variable", content: word};
}
function readRegexp() {
nextUntilUnescaped(source, "/");
source.nextWhileMatches(/[gi]/);
return {type: "regexp", style: "js-string"};
}
// Mutli-line comments are tricky. We want to return the newlines
// embedded in them as regular newline tokens, and then continue
// returning a comment token for every line of the comment. So
// some state has to be saved (inside) to indicate whether we are
// inside a /* */ sequence.
function readMultilineComment(start){
var newInside = "/*";
var maybeEnd = (start == "*");
while (true) {
if (source.endOfLine())
break;
var next = source.next();
if (next == "/" && maybeEnd){
newInside = null;
break;
}
maybeEnd = (next == "*");
}
setInside(newInside);
return {type: "comment", style: "js-comment"};
}
function readOperator() {
source.nextWhileMatches(isOperatorChar);
return {type: "operator", style: "js-operator"};
}
function readString(quote) {
var endBackSlash = nextUntilUnescaped(source, quote);
setInside(endBackSlash ? quote : null);
return {type: "string", style: "js-string"};
}
// Fetch the next token. Dispatches on first character in the
// stream, or first two characters when the first is a slash.
if (inside == "\"" || inside == "'")
return readString(inside);
var ch = source.next();
if (inside == "/*")
return readMultilineComment(ch);
else if (ch == "\"" || ch == "'")
return readString(ch);
// with punctuation, the type of the token is the symbol itself
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return {type: ch, style: "js-punctuation"};
else if (ch == "0" && (source.equals("x") || source.equals("X")))
return readHexNumber();
else if (/[0-9]/.test(ch))
return readNumber();
else if (ch == "/"){
if (source.equals("*"))
{ source.next(); return readMultilineComment(ch); }
else if (source.equals("/"))
{ nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};}
else if (regexp)
return readRegexp();
else
return readOperator();
}
else if (isOperatorChar.test(ch))
return readOperator();
else
return readWord();
}
// The external interface to the tokenizer.
return function(source, startState) {
return tokenizer(source, startState || jsTokenState(false, true));
};
})();
| JavaScript |
// A framework for simple tokenizers. Takes care of newlines and
// white-space, and of getting the text from the source stream into
// the token object. A state is a function of two arguments -- a
// string stream and a setState function. The second can be used to
// change the tokenizer's state, and can be ignored for stateless
// tokenizers. This function should advance the stream over a token
// and return a string or object containing information about the next
// token, or null to pass and have the (new) state be called to finish
// the token. When a string is given, it is wrapped in a {style, type}
// object. In the resulting object, the characters consumed are stored
// under the content property. Any whitespace following them is also
// automatically consumed, and added to the value property. (Thus,
// content is the actual meaningful part of the token, while value
// contains all the text it spans.)
function tokenizer(source, state) {
// Newlines are always a separate token.
function isWhiteSpace(ch) {
// The messy regexp is because IE's regexp matcher is of the
// opinion that non-breaking spaces are no whitespace.
return ch != "\n" && /^[\s\u00a0]*$/.test(ch);
}
var tokenizer = {
state: state,
take: function(type) {
if (typeof(type) == "string")
type = {style: type, type: type};
type.content = (type.content || "") + source.get();
if (!/\n$/.test(type.content))
source.nextWhile(isWhiteSpace);
type.value = type.content + source.get();
return type;
},
next: function () {
if (!source.more()) throw StopIteration;
var type;
if (source.equals("\n")) {
source.next();
return this.take("whitespace");
}
if (source.applies(isWhiteSpace))
type = "whitespace";
else
while (!type)
type = this.state(source, function(s) {tokenizer.state = s;});
return this.take(type);
}
};
return tokenizer;
}
| JavaScript |
/* CodeMirror main module
*
* Implements the CodeMirror constructor and prototype, which take care
* of initializing the editor frame, and providing the outside interface.
*/
// The CodeMirrorConfig object is used to specify a default
// configuration. If you specify such an object before loading this
// file, the values you put into it will override the defaults given
// below. You can also assign to it after loading.
var CodeMirrorConfig = window.CodeMirrorConfig || {};
var CodeMirror = (function () {
function setDefaults(object, defaults) {
for (var option in defaults) {
if (!object.hasOwnProperty(option))
object[option] = defaults[option];
}
}
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
// These default options can be overridden by passing a set of
// options to a specific CodeMirror constructor. See manual.html for
// their meaning.
setDefaults(CodeMirrorConfig, {
stylesheet: "",
path: "",
parserfile: [],
basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
iframeClass: null,
passDelay: 200,
passTime: 50,
lineNumberDelay: 200,
lineNumberTime: 50,
continuousScanning: false,
saveFunction: null,
onChange: null,
undoDepth: 50,
undoDelay: 800,
disableSpellcheck: true,
textWrapping: true,
readOnly: false,
width: "",
height: "300px",
autoMatchParens: false,
parserConfig: null,
tabMode: "indent", // or "spaces", "default", "shift"
reindentOnLoad: false,
activeTokens: null,
cursorActivity: null,
lineNumbers: false,
indentUnit: 2,
domain: null
});
function addLineNumberDiv(container) {
var nums = document.createElement("DIV"),
scroller = document.createElement("DIV");
nums.style.position = "absolute";
nums.style.height = "100%";
if (nums.style.setExpression) {
try { nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'"); }
catch (e) { } // Seems to throw 'Not Implemented' on some IE8 versions
}
nums.style.top = "0px";
nums.style.overflow = "hidden";
container.appendChild(nums);
scroller.className = "CodeMirror-line-numbers";
nums.appendChild(scroller);
return nums;
}
function frameHTML(options) {
if (typeof options.parserfile == "string")
options.parserfile = [options.parserfile];
if (typeof options.stylesheet == "string")
options.stylesheet = [options.stylesheet];
var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];
// Hack to work around a bunch of IE8-specific problems.
html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
forEach(options.stylesheet, function (file) {
html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
});
//html.push("<script type=\"text/javascript\" src=\"/Scripts/jquery-1.4.2.js\"><" + "/script>");
forEach(options.basefiles.concat(options.parserfile), function (file) {
html.push("<script type=\"text/javascript\" src=\"" + options.path + file + "\"><" + "/script>");
});
html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
(options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
return html.join("");
}
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
function CodeMirror(place, options) {
// Backward compatibility for deprecated options.
if (options.dumbTabs) options.tabMode = "spaces";
else if (options.normalTab) options.tabMode = "default";
// Use passed options, if any, to override defaults.
this.options = options = options || {};
setDefaults(options, CodeMirrorConfig);
var frame = this.frame = document.createElement("IFRAME");
if (options.iframeClass) frame.className = options.iframeClass;
frame.frameBorder = 0;
frame.style.border = "0";
frame.style.width = '100%';
frame.style.height = '100%';
// display: block occasionally suppresses some Firefox bugs, so we
// always add it, redundant as it sounds.
frame.style.display = "block";
var div = this.wrapping = document.createElement("DIV");
div.style.position = "relative";
div.className = "CodeMirror-wrapping";
div.style.width = options.width;
div.style.height = options.height;
// This is used by Editor.reroutePasteEvent
var teHack = this.textareaHack = document.createElement("TEXTAREA");
div.appendChild(teHack);
teHack.style.position = "absolute";
teHack.style.left = "-10000px";
teHack.style.width = "10px";
// Link back to this object, so that the editor can fetch options
// and add a reference to itself.
frame.CodeMirror = this;
if (options.domain && internetExplorer) {
this.html = frameHTML(options);
frame.src = "javascript:(function(){document.open();" +
(options.domain ? "document.domain=\"" + options.domain + "\";" : "") +
"document.write(window.frameElement.CodeMirror.html);document.close();})()";
}
else {
frame.src = "javascript:false";
}
if (place.appendChild) place.appendChild(div);
else place(div);
div.appendChild(frame);
if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div);
this.win = frame.contentWindow;
if (!options.domain || !internetExplorer) {
this.win.document.open();
this.win.document.write(frameHTML(options));
this.win.document.close();
}
}
CodeMirror.prototype = {
init: function () {
if (this.options.initCallback) this.options.initCallback(this);
if (this.options.lineNumbers) this.activateLineNumbers();
if (this.options.reindentOnLoad) this.reindent();
},
getCode: function () { return this.editor.getCode(); },
setCode: function (code) { this.editor.importCode(code); },
selection: function () { this.focusIfIE(); return this.editor.selectedText(); },
reindent: function () { this.editor.reindent(); },
reindentSelection: function () { this.focusIfIE(); this.editor.reindentSelection(null); },
focusIfIE: function () {
// in IE, a lot of selection-related functionality only works when the frame is focused
if (this.win.select.ie_selection) this.focus();
},
focus: function () {
this.win.focus();
if (this.editor.selectionSnapshot) // IE hack
this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot);
},
replaceSelection: function (text) {
this.focus();
this.editor.replaceSelection(text);
return true;
},
replaceChars: function (text, start, end) {
this.editor.replaceChars(text, start, end);
},
getSearchCursor: function (string, fromCursor, caseFold) {
return this.editor.getSearchCursor(string, fromCursor, caseFold);
},
undo: function () { this.editor.history.undo(); },
redo: function () { this.editor.history.redo(); },
historySize: function () { return this.editor.history.historySize(); },
clearHistory: function () { this.editor.history.clear(); },
grabKeys: function (callback, filter) { this.editor.grabKeys(callback, filter); },
ungrabKeys: function () { this.editor.ungrabKeys(); },
setParser: function (name) { this.editor.setParser(name); },
setSpellcheck: function (on) { this.win.document.body.spellcheck = on; },
setStylesheet: function (names) {
if (typeof names === "string") names = [names];
var activeStylesheets = {};
var matchedNames = {};
var links = this.win.document.getElementsByTagName("link");
// Create hashes of active stylesheets and matched names.
// This is O(n^2) but n is expected to be very small.
for (var x = 0, link; link = links[x]; x++) {
if (link.rel.indexOf("stylesheet") !== -1) {
for (var y = 0; y < names.length; y++) {
var name = names[y];
if (link.href.substring(link.href.length - name.length) === name) {
activeStylesheets[link.href] = true;
matchedNames[name] = true;
}
}
}
}
// Activate the selected stylesheets and disable the rest.
for (var x = 0, link; link = links[x]; x++) {
if (link.rel.indexOf("stylesheet") !== -1) {
link.disabled = !(link.href in activeStylesheets);
}
}
// Create any new stylesheets.
for (var y = 0; y < names.length; y++) {
var name = names[y];
if (!(name in matchedNames)) {
var link = this.win.document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = name;
this.win.document.getElementsByTagName('head')[0].appendChild(link);
}
}
},
setTextWrapping: function (on) {
if (on == this.options.textWrapping) return;
this.win.document.body.style.whiteSpace = on ? "" : "nowrap";
this.options.textWrapping = on;
if (this.lineNumbers) {
this.setLineNumbers(false);
this.setLineNumbers(true);
}
},
setIndentUnit: function (unit) { this.win.indentUnit = unit; },
setUndoDepth: function (depth) { this.editor.history.maxDepth = depth; },
setTabMode: function (mode) { this.options.tabMode = mode; },
setLineNumbers: function (on) {
if (on && !this.lineNumbers) {
this.lineNumbers = addLineNumberDiv(this.wrapping);
this.activateLineNumbers();
}
else if (!on && this.lineNumbers) {
this.wrapping.removeChild(this.lineNumbers);
this.wrapping.style.marginLeft = "";
this.lineNumbers = null;
}
},
cursorPosition: function (start) { this.focusIfIE(); return this.editor.cursorPosition(start); },
firstLine: function () { return this.editor.firstLine(); },
lastLine: function () { return this.editor.lastLine(); },
nextLine: function (line) { return this.editor.nextLine(line); },
prevLine: function (line) { return this.editor.prevLine(line); },
lineContent: function (line) { return this.editor.lineContent(line); },
setLineContent: function (line, content) { this.editor.setLineContent(line, content); },
removeLine: function (line) { this.editor.removeLine(line); },
insertIntoLine: function (line, position, content) { this.editor.insertIntoLine(line, position, content); },
selectLines: function (startLine, startOffset, endLine, endOffset) {
this.win.focus();
this.editor.selectLines(startLine, startOffset, endLine, endOffset);
},
nthLine: function (n) {
var line = this.firstLine();
for (; n > 1 && line !== false; n--)
line = this.nextLine(line);
return line;
},
lineNumber: function (line) {
var num = 0;
while (line !== false) {
num++;
line = this.prevLine(line);
}
return num;
},
jumpToLine: function (line) {
if (typeof line == "number") line = this.nthLine(line);
this.selectLines(line, 0);
this.win.focus();
},
currentLine: function () { // Deprecated, but still there for backward compatibility
return this.lineNumber(this.cursorLine());
},
cursorLine: function () {
return this.cursorPosition().line;
},
activateLineNumbers: function () {
var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body,
nums = this.lineNumbers, scroller = nums.firstChild, self = this;
var barWidth = null;
function sizeBar() {
if (frame.offsetWidth == 0) return;
for (var root = frame; root.parentNode; root = root.parentNode);
if (!nums.parentNode || root != document || !win.Editor) {
// Clear event handlers (their nodes might already be collected, so try/catch)
try { clear(); } catch (e) { }
clearInterval(sizeInterval);
return;
}
if (nums.offsetWidth != barWidth) {
barWidth = nums.offsetWidth;
nums.style.left = "-" + (frame.parentNode.style.marginLeft = barWidth + "px");
}
}
function doScroll() {
nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0;
}
// Cleanup function, registered by nonWrapping and wrapping.
var clear = function () { };
sizeBar();
var sizeInterval = setInterval(sizeBar, 500);
function nonWrapping() {
var nextNum = 1, pending;
function update() {
var target = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0));
var endTime = new Date().getTime() + self.options.lineNumberTime;
while (scroller.offsetHeight < target && (!scroller.firstChild || scroller.offsetHeight)) {
scroller.appendChild(document.createElement("DIV"));
scroller.lastChild.innerHTML = nextNum++;
if (new Date().getTime() > endTime) {
if (pending) clearTimeout(pending);
pending = setTimeout(update, self.options.lineNumberDelay);
break;
}
}
doScroll();
}
var onScroll = win.addEventHandler(win, "scroll", update, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function () { onScroll(); onResize(); if (pending) clearTimeout(pending); };
update();
}
function wrapping() {
var node, lineNum, next, pos;
function addNum(n) {
if (!lineNum) lineNum = scroller.appendChild(document.createElement("DIV"));
lineNum.innerHTML = n;
pos = lineNum.offsetHeight + lineNum.offsetTop;
lineNum = lineNum.nextSibling;
}
function work() {
if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return;
var endTime = new Date().getTime() + self.options.lineNumberTime;
while (node) {
addNum(next++);
for (; node && !win.isBR(node); node = node.nextSibling) {
var bott = node.offsetTop + node.offsetHeight;
while (scroller.offsetHeight && bott - 3 > pos) addNum(" ");
}
if (node) node = node.nextSibling;
if (new Date().getTime() > endTime) {
pending = setTimeout(work, self.options.lineNumberDelay);
return;
}
}
// While there are un-processed number DIVs, or the scroller is smaller than the frame...
var target = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0));
while (lineNum || (scroller.offsetHeight < target && (!scroller.firstChild || scroller.offsetHeight)))
addNum(next++);
doScroll();
}
function start() {
doScroll();
node = body.firstChild;
lineNum = scroller.firstChild;
pos = 0;
next = 1;
work();
}
start();
var pending = null;
function update() {
if (pending) clearTimeout(pending);
if (self.editor.allClean()) start();
else pending = setTimeout(update, 200);
}
self.updateNumbers = update;
var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
onResize = win.addEventHandler(win, "resize", update, true);
clear = function () {
if (pending) clearTimeout(pending);
if (self.updateNumbers == update) self.updateNumbers = null;
onScroll();
onResize();
};
}
(this.options.textWrapping ? wrapping : nonWrapping)();
}
};
CodeMirror.InvalidLineHandle = { toString: function () { return "CodeMirror.InvalidLineHandle"; } };
CodeMirror.replace = function (element) {
if (typeof element == "string")
element = document.getElementById(element);
return function (newElement) {
element.parentNode.replaceChild(newElement, element);
};
};
CodeMirror.fromTextArea = function (area, options) {
if (typeof area == "string")
area = document.getElementById(area);
options = options || {};
if (area.style.width && options.width == null)
options.width = area.style.width;
if (area.style.height && options.height == null)
options.height = area.style.height;
if (options.content == null) options.content = area.value;
if (area.form) {
function updateField() {
area.value = mirror.getCode();
}
if (typeof area.form.addEventListener == "function")
area.form.addEventListener("submit", updateField, false);
else
area.form.attachEvent("onsubmit", updateField);
}
function insert(frame) {
if (area.nextSibling)
area.parentNode.insertBefore(frame, area.nextSibling);
else
area.parentNode.appendChild(frame);
}
area.style.display = "none";
var mirror = new CodeMirror(insert, options);
return mirror;
};
CodeMirror.isProbablySupported = function () {
// This is rather awful, but can be useful.
var match;
if (window.opera)
return Number(window.opera.version()) >= 9.52;
else if (/Apple Computers, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
return Number(match[1]) >= 3;
else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
return Number(match[1]) >= 6;
else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
return Number(match[1]) >= 20050901;
else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/)) {
var isiPad = navigator.userAgent.match(/iPad/i);
var isiPhone = navigator.userAgent.match(/iPhone/i);
var isiPod = navigator.userAgent.match(/iPod/i);
return !isiPad && !isiPhone && !isiPod && Number(match[1]) >= 525;
}
else
return null;
};
return CodeMirror;
})();
| JavaScript |
// Minimal framing needed to use CodeMirror-style parsers to highlight
// code. Load this along with tokenize.js, stringstream.js, and your
// parser. Then call highlightText, passing a string as the first
// argument, and as the second argument either a callback function
// that will be called with an array of SPAN nodes for every line in
// the code, or a DOM node to which to append these spans, and
// optionally (not needed if you only loaded one parser) a parser
// object.
// Stuff from util.js that the parsers are using.
var StopIteration = {toString: function() {return "StopIteration"}};
var Editor = {};
var indentUnit = 2;
(function(){
function normaliseString(string) {
var tab = "";
for (var i = 0; i < indentUnit; i++) tab += " ";
string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n");
var pos = 0, parts = [], lines = string.split("\n");
for (var line = 0; line < lines.length; line++) {
if (line != 0) parts.push("\n");
parts.push(lines[line]);
}
return {
next: function() {
if (pos < parts.length) return parts[pos++];
else throw StopIteration;
}
};
}
window.highlightText = function(string, callback, parser) {
parser = (parser || Editor.Parser).make(stringStream(normaliseString(string)));
var line = [];
if (callback.nodeType == 1) {
var node = callback;
callback = function(line) {
for (var i = 0; i < line.length; i++)
node.appendChild(line[i]);
node.appendChild(document.createElement("BR"));
};
}
try {
while (true) {
var token = parser.next();
if (token.value == "\n") {
callback(line);
line = [];
}
else {
var span = document.createElement("SPAN");
span.className = token.style;
span.appendChild(document.createTextNode(token.value));
line.push(span);
}
}
}
catch (e) {
if (e != StopIteration) throw e;
}
if (line.length) callback(line);
}
})();
| JavaScript |
/* The Editor object manages the content of the editable frame. It
* catches events, colours nodes, and indents lines. This file also
* holds some functions for transforming arbitrary DOM structures into
* plain sequences of <span> and <br> elements
*/
var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
var webkit = /AppleWebKit/.test(navigator.userAgent);
var safari = /Apple Computers, Inc/.test(navigator.vendor);
var gecko = /gecko\/(\d{8})/i.test(navigator.userAgent);
// Make sure a string does not contain two consecutive 'collapseable'
// whitespace characters.
function makeWhiteSpace(n) {
var buffer = [], nb = true;
for (; n > 0; n--) {
buffer.push((nb || n == 1) ? nbsp : " ");
nb = !nb;
}
return buffer.join("");
}
// Create a set of white-space characters that will not be collapsed
// by the browser, but will not break text-wrapping either.
function fixSpaces(string) {
if (string.charAt(0) == " ") string = nbsp + string.slice(1);
return string.replace(/\t/g, function(){return makeWhiteSpace(indentUnit);})
.replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);});
}
function cleanText(text) {
return text.replace(/\u00a0/g, " ").replace(/\u200b/g, "");
}
// Create a SPAN node with the expected properties for document part
// spans.
function makePartSpan(value, doc) {
var text = value;
if (value.nodeType == 3) text = value.nodeValue;
else value = doc.createTextNode(text);
var span = doc.createElement("SPAN");
span.isPart = true;
span.appendChild(value);
span.currentText = text;
return span;
}
// On webkit, when the last BR of the document does not have text
// behind it, the cursor can not be put on the line after it. This
// makes pressing enter at the end of the document occasionally do
// nothing (or at least seem to do nothing). To work around it, this
// function makes sure the document ends with a span containing a
// zero-width space character. The traverseDOM iterator filters such
// character out again, so that the parsers won't see them. This
// function is called from a few strategic places to make sure the
// zwsp is restored after the highlighting process eats it.
var webkitLastLineHack = webkit ?
function(container) {
var last = container.lastChild;
if (!last || !last.isPart || last.textContent != "\u200b")
container.appendChild(makePartSpan("\u200b", container.ownerDocument));
} : function() {};
var Editor = (function () {
// The HTML elements whose content should be suffixed by a newline
// when converting them to flat text.
var newlineElements = { "P": true, "DIV": true, "LI": true };
function asEditorLines(string) {
var tab = makeWhiteSpace(indentUnit);
return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces);
}
// Helper function for traverseDOM. Flattens an arbitrary DOM node
// into an array of textnodes and <br> tags.
function simplifyDOM(root, atEnd) {
var doc = root.ownerDocument;
var result = [];
var leaving = true;
function simplifyNode(node, top) {
if (node.nodeType == 3) {
var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " "));
if (text.length) leaving = false;
result.push(node);
}
else if (isBR(node) && node.childNodes.length == 0) {
leaving = true;
result.push(node);
}
else {
forEach(node.childNodes, simplifyNode);
if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) {
leaving = true;
if (!atEnd || !top)
result.push(doc.createElement("BR"));
}
}
}
simplifyNode(root, true);
return result;
}
// Creates a MochiKit-style iterator that goes over a series of DOM
// nodes. The values it yields are strings, the textual content of
// the nodes. It makes sure that all nodes up to and including the
// one whose text is being yielded have been 'normalized' to be just
// <span> and <br> elements.
// See the story.html file for some short remarks about the use of
// continuation-passing style in this iterator.
function traverseDOM(start) {
function _yield(value, c) { cc = c; return value; }
function push(fun, arg, c) { return function () { return fun(arg, c); }; }
function stop() { cc = stop; throw StopIteration; };
var cc = push(scanNode, start, stop);
var owner = start.ownerDocument;
var nodeQueue = [];
// Create a function that can be used to insert nodes after the
// one given as argument.
function pointAt(node) {
var parent = node.parentNode;
var next = node.nextSibling;
return function (newnode) {
parent.insertBefore(newnode, next);
};
}
var point = null;
// This an Opera-specific hack -- always insert an empty span
// between two BRs, because Opera's cursor code gets terribly
// confused when the cursor is between two BRs.
var afterBR = true;
// Insert a normalized node at the current point. If it is a text
// node, wrap it in a <span>, and give that span a currentText
// property -- this is used to cache the nodeValue, because
// directly accessing nodeValue is horribly slow on some browsers.
// The dirty property is used by the highlighter to determine
// which parts of the document have to be re-highlighted.
function insertPart(part) {
var text = "\n";
if (part.nodeType == 3) {
select.snapshotChanged();
part = makePartSpan(part, owner);
text = part.currentText;
afterBR = false;
}
else {
if (afterBR && window.opera)
point(makePartSpan("", owner));
afterBR = true;
}
part.dirty = true;
nodeQueue.push(part);
point(part);
return text;
}
// Extract the text and newlines from a DOM node, insert them into
// the document, and yield the textual content. Used to replace
// non-normalized nodes.
function writeNode(node, c, end) {
var toYield = [];
forEach(simplifyDOM(node, end), function (part) {
toYield.push(insertPart(part));
});
return _yield(toYield.join(""), c);
}
// Check whether a node is a normalized <span> element.
function partNode(node) {
if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
node.currentText = node.firstChild.nodeValue;
return !/[\n\t\r]/.test(node.currentText);
}
return false;
}
// Handle a node. Add its successor to the continuation if there
// is one, find out whether the node is normalized. If it is,
// yield its content, otherwise, normalize it (writeNode will take
// care of yielding).
function scanNode(node, c) {
if (node.nextSibling)
c = push(scanNode, node.nextSibling, c);
if (partNode(node)) {
nodeQueue.push(node);
afterBR = false;
return _yield(node.currentText, c);
}
else if (isBR(node)) {
if (afterBR && window.opera)
node.parentNode.insertBefore(makePartSpan("", owner), node);
nodeQueue.push(node);
afterBR = true;
return _yield("\n", c);
}
else {
var end = !node.nextSibling;
point = pointAt(node);
removeElement(node);
return writeNode(node, c, end);
}
}
// MochiKit iterators are objects with a next function that
// returns the next value or throws StopIteration when there are
// no more values.
return { next: function () { return cc(); }, nodes: nodeQueue };
}
// Determine the text size of a processed node.
function nodeSize(node) {
return isBR(node) ? 1 : node.currentText.length;
}
// Search backwards through the top-level nodes until the next BR or
// the start of the frame.
function startOfLine(node) {
while (node && !isBR(node)) node = node.previousSibling;
return node;
}
function endOfLine(node, container) {
if (!node) node = container.firstChild;
else if (isBR(node)) node = node.nextSibling;
while (node && !isBR(node)) node = node.nextSibling;
return node;
}
function time() { return new Date().getTime(); }
// Client interface for searching the content of the editor. Create
// these by calling CodeMirror.getSearchCursor. To use, call
// findNext on the resulting object -- this returns a boolean
// indicating whether anything was found, and can be called again to
// skip to the next find. Use the select and replace methods to
// actually do something with the found locations.
function SearchCursor(editor, string, fromCursor, caseFold) {
this.editor = editor;
this.caseFold = caseFold;
if (caseFold) string = string.toLowerCase();
this.history = editor.history;
this.history.commit();
// Are we currently at an occurrence of the search string?
this.atOccurrence = false;
// The object stores a set of nodes coming after its current
// position, so that when the current point is taken out of the
// DOM tree, we can still try to continue.
this.fallbackSize = 15;
var cursor;
// Start from the cursor when specified and a cursor can be found.
if (fromCursor && (cursor = select.cursorPos(this.editor.container))) {
this.line = cursor.node;
this.offset = cursor.offset;
}
else {
this.line = null;
this.offset = 0;
}
this.valid = !!string;
// Create a matcher function based on the kind of string we have.
var target = string.split("\n"), self = this;
this.matches = (target.length == 1) ?
// For one-line strings, searching can be done simply by calling
// indexOf on the current line.
function () {
var line = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? line.toLowerCase() : line).indexOf(string);
if (match > -1)
return { from: { node: self.line, offset: self.offset + match },
to: { node: self.line, offset: self.offset + match + string.length }
};
} :
// Multi-line strings require internal iteration over lines, and
// some clunky checks to make sure the first match ends at the
// end of the line and the last match starts at the start.
function () {
var firstLine = cleanText(self.history.textAfter(self.line).slice(self.offset));
var match = (self.caseFold ? firstLine.toLowerCase() : firstLine).lastIndexOf(target[0]);
if (match == -1 || match != firstLine.length - target[0].length)
return false;
var startOffset = self.offset + match;
var line = self.history.nodeAfter(self.line);
for (var i = 1; i < target.length - 1; i++) {
var lineText = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lineText.toLowerCase() : lineText) != target[i])
return false;
line = self.history.nodeAfter(line);
}
var lastLine = cleanText(self.history.textAfter(line));
if ((self.caseFold ? lastLine.toLowerCase() : lastLine).indexOf(target[target.length - 1]) != 0)
return false;
return { from: { node: self.line, offset: startOffset },
to: { node: line, offset: target[target.length - 1].length }
};
};
}
SearchCursor.prototype = {
findNext: function () {
if (!this.valid) return false;
this.atOccurrence = false;
var self = this;
// Go back to the start of the document if the current line is
// no longer in the DOM tree.
if (this.line && !this.line.parentNode) {
this.line = null;
this.offset = 0;
}
// Set the cursor's position one character after the given
// position.
function saveAfter(pos) {
if (self.history.textAfter(pos.node).length > pos.offset) {
self.line = pos.node;
self.offset = pos.offset + 1;
}
else {
self.line = self.history.nodeAfter(pos.node);
self.offset = 0;
}
}
while (true) {
var match = this.matches();
// Found the search string.
if (match) {
this.atOccurrence = match;
saveAfter(match.from);
return true;
}
this.line = this.history.nodeAfter(this.line);
this.offset = 0;
// End of document.
if (!this.line) {
this.valid = false;
return false;
}
}
},
select: function () {
if (this.atOccurrence) {
select.setCursorPos(this.editor.container, this.atOccurrence.from, this.atOccurrence.to);
select.scrollToCursor(this.editor.container);
}
},
replace: function (string) {
if (this.atOccurrence) {
var end = this.editor.replaceRange(this.atOccurrence.from, this.atOccurrence.to, string);
this.line = end.node;
this.offset = end.offset;
this.atOccurrence = false;
}
}
};
// The Editor object is the main inside-the-iframe interface.
function Editor(options) {
this.options = options;
window.indentUnit = options.indentUnit;
this.parent = parent;
this.doc = document;
var container = this.container = this.doc.body;
this.win = window;
this.history = new History(container, options.undoDepth, options.undoDelay, this);
var self = this;
if (!Editor.Parser)
throw "No parser loaded.";
if (options.parserConfig && Editor.Parser.configure)
Editor.Parser.configure(options.parserConfig);
if (!options.readOnly)
select.setCursorPos(container, { node: null, offset: 0 });
this.dirty = [];
this.importCode(options.content || "");
this.history.onChange = options.onChange;
if (!options.readOnly) {
if (options.continuousScanning !== false) {
this.scanner = this.documentScanner(options.passTime);
this.delayScanning();
}
function setEditable() {
// In IE, designMode frames can not run any scripts, so we use
// contentEditable instead.
if (document.body.contentEditable != undefined && internetExplorer)
document.body.contentEditable = "true";
else
document.designMode = "on";
document.documentElement.style.borderWidth = "0";
if (!options.textWrapping)
container.style.whiteSpace = "nowrap";
}
// If setting the frame editable fails, try again when the user
// focus it (happens when the frame is not visible on
// initialisation, in Firefox).
try {
setEditable();
}
catch (e) {
var focusEvent = addEventHandler(document, "focus", function () {
focusEvent();
setEditable();
}, true);
}
// forward focus if we can
if (parent.forwardEvent) {
addEventHandler(this.win, "focus", function () {
parent.forwardEvent("focus", this);
});
addEventHandler(this.win, "blur", function () {
parent.forwardEvent("blur", this);
});
}
/*
addEventHandler(document, "mousedown", function () {
//parent.focus();
self.win.frameElement.CodeMirror.focus();
self.win.focus();
self.cursorPosition(1);
//window.frameElement.CodeMirror.textareaHack.focus();
//myWin.focus();
//parent.forwardEvent("focus", this);
});
*/
addEventHandler(document, "keydown", method(this, "keyDown"));
addEventHandler(document, "keypress", method(this, "keyPress"));
addEventHandler(document, "keyup", method(this, "keyUp"));
function cursorActivity() { self.cursorActivity(false); }
addEventHandler(document.body, "mouseup", cursorActivity);
addEventHandler(document.body, "cut", cursorActivity);
// workaround for a gecko bug [?] where going forward and then
// back again breaks designmode (no more cursor)
if (gecko)
addEventHandler(this.win, "pagehide", function () { self.unloaded = true; });
addEventHandler(document.body, "paste", function (event) {
cursorActivity();
var text = null;
try {
var clipboardData = event.clipboardData || window.clipboardData;
if (clipboardData) text = clipboardData.getData('Text');
}
catch (e) { }
if (text !== null) {
event.stop();
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
});
if (this.options.autoMatchParens)
addEventHandler(document.body, "click", method(this, "scheduleParenHighlight"));
}
else if (!options.textWrapping) {
container.style.whiteSpace = "nowrap";
}
}
function isSafeKey(code) {
return (code >= 16 && code <= 18) || // shift, control, alt
(code >= 33 && code <= 40); // arrows, home, end
}
Editor.prototype = {
// Import a piece of code into the editor.
importCode: function (code) {
this.history.push(null, null, asEditorLines(code));
this.history.reset();
},
// Extract the code from the editor.
getCode: function () {
if (!this.container.firstChild)
return "";
var accum = [];
select.markSelection(this.win);
forEach(traverseDOM(this.container.firstChild), method(accum, "push"));
webkitLastLineHack(this.container);
select.selectMarked();
return cleanText(accum.join(""));
},
checkLine: function (node) {
if (node === false || !(node == null || node.parentNode == this.container))
throw parent.CodeMirror.InvalidLineHandle;
},
cursorPosition: function (start) {
if (start == null) start = true;
var pos = select.cursorPos(this.container, start);
if (pos) return { line: pos.node, character: pos.offset };
else return { line: null, character: 0 };
},
firstLine: function () {
return null;
},
lastLine: function () {
if (this.container.lastChild) return startOfLine(this.container.lastChild);
else return null;
},
nextLine: function (line) {
this.checkLine(line);
var end = endOfLine(line, this.container);
return end || false;
},
prevLine: function (line) {
this.checkLine(line);
if (line == null) return false;
return startOfLine(line.previousSibling);
},
visibleLineCount: function () {
var line = this.container.firstChild;
while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable
if (!line) return false;
var innerHeight = (window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight);
return Math.floor(innerHeight / line.offsetHeight);
},
selectLines: function (startLine, startOffset, endLine, endOffset) {
this.checkLine(startLine);
var start = { node: startLine, offset: startOffset }, end = null;
if (endOffset !== undefined) {
this.checkLine(endLine);
end = { node: endLine, offset: endOffset };
}
select.setCursorPos(this.container, start, end);
select.scrollToCursor(this.container);
},
lineContent: function (line) {
var accum = [];
for (line = line ? line.nextSibling : this.container.firstChild;
line && !isBR(line); line = line.nextSibling)
accum.push(nodeText(line));
return cleanText(accum.join(""));
},
setLineContent: function (line, content) {
this.history.commit();
this.replaceRange({ node: line, offset: 0 },
{ node: line, offset: this.history.textAfter(line).length },
content);
this.addDirtyNode(line);
this.scheduleHighlight();
},
removeLine: function (line) {
var node = line ? line.nextSibling : this.container.firstChild;
while (node) {
var next = node.nextSibling;
removeElement(node);
if (isBR(node)) break;
node = next;
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
insertIntoLine: function (line, position, content) {
var before = null;
if (position == "end") {
before = endOfLine(line, this.container);
}
else {
for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) {
if (position == 0) {
before = cur;
break;
}
var text = nodeText(cur);
if (text.length > position) {
before = cur.nextSibling;
content = text.slice(0, position) + content + text.slice(position);
removeElement(cur);
break;
}
position -= text.length;
}
}
var lines = asEditorLines(content), doc = this.container.ownerDocument;
for (var i = 0; i < lines.length; i++) {
if (i > 0) this.container.insertBefore(doc.createElement("BR"), before);
this.container.insertBefore(makePartSpan(lines[i], doc), before);
}
this.addDirtyNode(line);
this.scheduleHighlight();
},
// Retrieve the selected text.
selectedText: function () {
var h = this.history;
h.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return "";
if (start.node == end.node)
return h.textAfter(start.node).slice(start.offset, end.offset);
var text = [h.textAfter(start.node).slice(start.offset)];
for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos))
text.push(h.textAfter(pos));
text.push(h.textAfter(end.node).slice(0, end.offset));
return cleanText(text.join("\n"));
},
// Replace the selection with another piece of text.
replaceSelection: function (text) {
this.history.commit();
var start = select.cursorPos(this.container, true),
end = select.cursorPos(this.container, false);
if (!start || !end) return;
end = this.replaceRange(start, end, text);
select.setCursorPos(this.container, end);
webkitLastLineHack(this.container);
},
reroutePasteEvent: function () {
if (this.capturingPaste || window.opera) return;
this.capturingPaste = true;
var te = window.frameElement.CodeMirror.textareaHack;
parent.focus();
te.value = "";
te.focus();
var self = this;
this.parent.setTimeout(function () {
self.capturingPaste = false;
self.win.focus();
if (self.selectionSnapshot) // IE hack
self.win.select.setBookmark(self.container, self.selectionSnapshot);
var text = te.value;
if (text) {
self.replaceSelection(text);
select.scrollToCursor(self.container);
}
}, 10);
},
replaceRange: function (from, to, text) {
var lines = asEditorLines(text);
lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0];
var lastLine = lines[lines.length - 1];
lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset);
var end = this.history.nodeAfter(to.node);
this.history.push(from.node, end, lines);
return { node: this.history.nodeBefore(end),
offset: lastLine.length
};
},
getSearchCursor: function (string, fromCursor, caseFold) {
return new SearchCursor(this, string, fromCursor, caseFold);
},
// Re-indent the whole buffer
reindent: function () {
if (this.container.firstChild)
this.indentRegion(null, this.container.lastChild);
},
reindentSelection: function (direction) {
if (!select.somethingSelected(this.win)) {
this.indentAtCursor(direction);
}
else {
var start = select.selectionTopNode(this.container, true),
end = select.selectionTopNode(this.container, false);
if (start === false || end === false) return;
this.indentRegion(start, end, direction);
}
},
grabKeys: function (eventHandler, filter) {
this.frozen = eventHandler;
this.keyFilter = filter;
},
ungrabKeys: function () {
this.frozen = "leave";
this.keyFilter = null;
},
setParser: function (name) {
Editor.Parser = window[name];
if (this.container.firstChild) {
forEach(this.container.childNodes, function (n) {
if (n.nodeType != 3) n.dirty = true;
});
this.addDirtyNode(this.firstChild);
this.scheduleHighlight();
}
},
// Intercept enter and tab, and assign their new functions.
keyDown: function (event) {
if (this.frozen == "leave") this.frozen = null;
if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) {
event.stop();
this.frozen(event);
return;
}
var code = event.keyCode;
// Don't scan when the user is typing.
this.delayScanning();
// Schedule a paren-highlight event, if configured.
if (this.options.autoMatchParens)
this.scheduleParenHighlight();
// The various checks for !altKey are there because AltGr sets both
// ctrlKey and altKey to true, and should not be recognised as
// Control.
if (code == 13) { // enter
if (event.ctrlKey && !event.altKey) {
this.reparseBuffer();
}
else {
select.insertNewlineAtCursor(this.win);
this.indentAtCursor();
select.scrollToCursor(this.container);
}
event.stop();
}
else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab
this.handleTab(!event.shiftKey);
event.stop();
}
else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home
if (this.home()) event.stop();
}
else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end
if (this.end()) event.stop();
}
// Only in Firefox is the default behavior for PgUp/PgDn correct.
else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp
if (this.pageUp()) event.stop();
}
else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn
if (this.pageDown()) event.stop();
}
else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ]
this.highlightParens(event.shiftKey, true);
event.stop();
}
else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right
var cursor = select.selectionTopNode(this.container);
if (cursor === false || !this.container.firstChild) return;
if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container);
else {
var end = endOfLine(cursor, this.container);
select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container);
}
event.stop();
}
else if ((event.ctrlKey || event.metaKey) && !event.altKey) {
if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y
select.scrollToNode(this.history.redo());
event.stop();
}
else if (code == 90 || (safari && code == 8)) { // Z, backspace
select.scrollToNode(this.history.undo());
event.stop();
}
else if (code == 83 && this.options.saveFunction) { // S
this.options.saveFunction();
event.stop();
}
else if (internetExplorer && code == 86) {
this.reroutePasteEvent();
}
}
},
// Check for characters that should re-indent the current line,
// and prevent Opera from handling enter and tab anyway.
keyPress: function (event) {
var electric = Editor.Parser.electricChars, self = this;
// Hack for Opera, and Firefox on OS X, in which stopping a
// keydown event does not prevent the associated keypress event
// from happening, so we have to cancel enter and tab again
// here.
if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) ||
event.code == 13 || (event.code == 9 && this.options.tabMode != "default"))
event.stop();
else if (electric && electric.indexOf(event.character) != -1)
this.parent.setTimeout(function () { self.indentAtCursor(null); }, 0);
else if ((event.character == "v" || event.character == "V")
&& (event.ctrlKey || event.metaKey) && !event.altKey) // ctrl-V
this.reroutePasteEvent();
},
// Mark the node at the cursor dirty when a non-safe key is
// released.
keyUp: function (event) {
this.cursorActivity(isSafeKey(event.keyCode));
},
// Indent the line following a given <br>, or null for the first
// line. If given a <br> element, this must have been highlighted
// so that it has an indentation method. Returns the whitespace
// element that has been modified or created (if any).
indentLineAfter: function (start, direction) {
// whiteSpace is the whitespace span at the start of the line,
// or null if there is no such node.
var whiteSpace = start ? start.nextSibling : this.container.firstChild;
if (whiteSpace && !hasClass(whiteSpace, "whitespace"))
whiteSpace = null;
// Sometimes the start of the line can influence the correct
// indentation, so we retrieve it.
var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild);
var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : "";
// Ask the lexical context for the correct indentation, and
// compute how much this differs from the current indentation.
var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0;
if (direction != null && this.options.tabMode == "shift")
newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit)
else if (start && start.indentation)
newIndent = start.indentation(nextChars, curIndent, direction);
else if (Editor.Parser.firstIndentation)
newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction);
var indentDiff = newIndent - curIndent;
// If there is too much, this is just a matter of shrinking a span.
if (indentDiff < 0) {
if (newIndent == 0) {
if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild, 0);
removeElement(whiteSpace);
whiteSpace = null;
}
else {
select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true);
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
}
// Not enough...
else if (indentDiff > 0) {
// If there is whitespace, we grow it.
if (whiteSpace) {
whiteSpace.currentText = makeWhiteSpace(newIndent);
whiteSpace.firstChild.nodeValue = whiteSpace.currentText;
}
// Otherwise, we have to add a new whitespace node.
else {
whiteSpace = makePartSpan(makeWhiteSpace(newIndent), this.doc);
whiteSpace.className = "whitespace";
if (start) insertAfter(whiteSpace, start);
else this.container.insertBefore(whiteSpace, this.container.firstChild);
}
var fromNode = firstText && (firstText.firstChild || firstText);
select.snapshotMove(fromNode, whiteSpace.firstChild, newIndent, false, true);
}
if (indentDiff != 0) this.addDirtyNode(start);
},
// Re-highlight the selected part of the document.
highlightAtCursor: function () {
var pos = select.selectionTopNode(this.container, true);
var to = select.selectionTopNode(this.container, false);
if (pos === false || to === false) return false;
select.markSelection(this.win);
if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false)
return false;
select.selectMarked();
return true;
},
// When tab is pressed with text selected, the whole selection is
// re-indented, when nothing is selected, the line with the cursor
// is re-indented.
handleTab: function (direction) {
if (this.options.tabMode == "spaces")
select.insertTabAtCursor(this.win);
else
this.reindentSelection(direction);
},
// Custom home behaviour that doesn't land the cursor in front of
// leading whitespace unless pressed twice.
home: function () {
var cur = select.selectionTopNode(this.container, true), start = cur;
if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild)
return false;
while (cur && !isBR(cur)) cur = cur.previousSibling;
var next = cur ? cur.nextSibling : this.container.firstChild;
if (next && next != start && next.isPart && hasClass(next, "whitespace"))
select.focusAfterNode(next, this.container);
else
select.focusAfterNode(cur, this.container);
select.scrollToCursor(this.container);
return true;
},
// Some browsers (Opera) don't manage to handle the end key
// properly in the face of vertical scrolling.
end: function () {
var cur = select.selectionTopNode(this.container, true);
if (cur === false) return false;
cur = endOfLine(cur, this.container);
if (!cur) return false;
select.focusAfterNode(cur.previousSibling, this.container);
select.scrollToCursor(this.container);
return true;
},
pageUp: function () {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to keep one line on the screen.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
line = this.prevLine(line);
if (line === false) break;
}
if (i == 0) return false; // Already at first line
select.setCursorPos(this.container, { node: line, offset: 0 });
select.scrollToCursor(this.container);
return true;
},
pageDown: function () {
var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount();
if (line === false || scrollAmount === false) return false;
// Try to move to the last line of the current page.
scrollAmount -= 2;
for (var i = 0; i < scrollAmount; i++) {
var nextLine = this.nextLine(line);
if (nextLine === false) break;
line = nextLine;
}
if (i == 0) return false; // Already at last line
select.setCursorPos(this.container, { node: line, offset: 0 });
select.scrollToCursor(this.container);
return true;
},
// Delay (or initiate) the next paren highlight event.
scheduleParenHighlight: function () {
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
var self = this;
this.parenEvent = this.parent.setTimeout(function () { self.highlightParens(); }, 300);
},
// Take the token before the cursor. If it contains a character in
// '()[]{}', search for the matching paren/brace/bracket, and
// highlight them in green for a moment, or red if no proper match
// was found.
highlightParens: function (jump, fromKey) {
var self = this;
// give the relevant nodes a colour.
function highlight(node, ok) {
if (!node) return;
if (self.options.markParen) {
self.options.markParen(node, ok);
}
else {
node.style.fontWeight = "bold";
node.style.color = ok ? "#8F8" : "#F88";
}
}
function unhighlight(node) {
if (!node) return;
if (self.options.unmarkParen) {
self.options.unmarkParen(node);
}
else {
node.style.fontWeight = "";
node.style.color = "";
}
}
if (!fromKey && self.highlighted) {
unhighlight(self.highlighted[0]);
unhighlight(self.highlighted[1]);
}
if (!window.select) return;
// Clear the event property.
if (this.parenEvent) this.parent.clearTimeout(this.parenEvent);
this.parenEvent = null;
// Extract a 'paren' from a piece of text.
function paren(node) {
if (node.currentText) {
var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/);
return match && match[1];
}
}
// Determine the direction a paren is facing.
function forward(ch) {
return /[\(\[\{]/.test(ch);
}
var ch, cursor = select.selectionTopNode(this.container, true);
if (!cursor || !this.highlightAtCursor()) return;
cursor = select.selectionTopNode(this.container, true);
if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor)))))
return;
// We only look for tokens with the same className.
var className = cursor.className, dir = forward(ch), match = matching[ch];
// Since parts of the document might not have been properly
// highlighted, and it is hard to know in advance which part we
// have to scan, we just try, and when we find dirty nodes we
// abort, parse them, and re-try.
function tryFindMatch() {
var stack = [], ch, ok = true;
for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) {
if (runner.className == className && isSpan(runner) && (ch = paren(runner))) {
if (forward(ch) == dir)
stack.push(ch);
else if (!stack.length)
ok = false;
else if (stack.pop() != matching[ch])
ok = false;
if (!stack.length) break;
}
else if (runner.dirty || !isSpan(runner) && !isBR(runner)) {
return { node: runner, status: "dirty" };
}
}
return { node: runner, status: runner && ok };
}
while (true) {
var found = tryFindMatch();
if (found.status == "dirty") {
this.highlight(found.node, endOfLine(found.node));
// Needed because in some corner cases a highlight does not
// reach a node.
found.node.dirty = false;
continue;
}
else {
highlight(cursor, found.status);
highlight(found.node, found.status);
if (fromKey)
self.parent.setTimeout(function () { unhighlight(cursor); unhighlight(found.node); }, 500);
else
self.highlighted = [cursor, found.node];
if (jump && found.node)
select.focusAfterNode(found.node.previousSibling, this.container);
break;
}
}
},
// Adjust the amount of whitespace at the start of the line that
// the cursor is on so that it is indented properly.
indentAtCursor: function (direction) {
if (!this.container.firstChild) return;
// The line has to have up-to-date lexical information, so we
// highlight it first.
if (!this.highlightAtCursor()) return;
var cursor = select.selectionTopNode(this.container, false);
// If we couldn't determine the place of the cursor,
// there's nothing to indent.
if (cursor === false)
return;
select.markSelection(this.win);
this.indentLineAfter(startOfLine(cursor), direction);
select.selectMarked();
},
// Indent all lines whose start falls inside of the current
// selection.
indentRegion: function (start, end, direction) {
var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling);
if (!isBR(end)) end = endOfLine(end, this.container);
this.addDirtyNode(start);
do {
var next = endOfLine(current, this.container);
if (current) this.highlight(before, next, true);
this.indentLineAfter(current, direction);
before = current;
current = next;
} while (current != end);
select.setCursorPos(this.container, { node: start, offset: 0 }, { node: end, offset: 0 });
},
// Find the node that the cursor is in, mark it as dirty, and make
// sure a highlight pass is scheduled.
cursorActivity: function (safe) {
// pagehide event hack above
if (this.unloaded) {
this.win.document.designMode = "off";
this.win.document.designMode = "on";
this.unloaded = false;
}
if (internetExplorer) {
this.container.createTextRange().execCommand("unlink");
this.selectionSnapshot = select.getBookmark(this.container);
}
var activity = this.options.cursorActivity;
if (!safe || activity) {
var cursor = select.selectionTopNode(this.container, false);
if (cursor === false || !this.container.firstChild) return;
cursor = cursor || this.container.firstChild;
if (activity) activity(cursor);
if (!safe) {
this.scheduleHighlight();
this.addDirtyNode(cursor);
}
}
},
reparseBuffer: function () {
forEach(this.container.childNodes, function (node) { node.dirty = true; });
if (this.container.firstChild)
this.addDirtyNode(this.container.firstChild);
},
// Add a node to the set of dirty nodes, if it isn't already in
// there.
addDirtyNode: function (node) {
node = node || this.container.firstChild;
if (!node) return;
for (var i = 0; i < this.dirty.length; i++)
if (this.dirty[i] == node) return;
if (node.nodeType != 3)
node.dirty = true;
this.dirty.push(node);
},
allClean: function () {
return !this.dirty.length;
},
// Cause a highlight pass to happen in options.passDelay
// milliseconds. Clear the existing timeout, if one exists. This
// way, the passes do not happen while the user is typing, and
// should as unobtrusive as possible.
scheduleHighlight: function () {
// Timeouts are routed through the parent window, because on
// some browsers designMode windows do not fire timeouts.
var self = this;
this.parent.clearTimeout(this.highlightTimeout);
this.highlightTimeout = this.parent.setTimeout(function () { self.highlightDirty(); }, this.options.passDelay);
},
// Fetch one dirty node, and remove it from the dirty set.
getDirtyNode: function () {
while (this.dirty.length > 0) {
var found = this.dirty.pop();
// IE8 sometimes throws an unexplainable 'invalid argument'
// exception for found.parentNode
try {
// If the node has been coloured in the meantime, or is no
// longer in the document, it should not be returned.
while (found && found.parentNode != this.container)
found = found.parentNode;
if (found && (found.dirty || found.nodeType == 3))
return found;
} catch (e) { }
}
return null;
},
// Pick dirty nodes, and highlight them, until options.passTime
// milliseconds have gone by. The highlight method will continue
// to next lines as long as it finds dirty nodes. It returns
// information about the place where it stopped. If there are
// dirty nodes left after this function has spent all its lines,
// it shedules another highlight to finish the job.
highlightDirty: function (force) {
// Prevent FF from raising an error when it is firing timeouts
// on a page that's no longer loaded.
if (!window.select) return false;
if (!this.options.readOnly) select.markSelection(this.win);
var start, endTime = force ? null : time() + this.options.passTime;
while ((time() < endTime || force) && (start = this.getDirtyNode())) {
var result = this.highlight(start, endTime);
if (result && result.node && result.dirty)
this.addDirtyNode(result.node);
}
if (!this.options.readOnly) select.selectMarked();
if (start) this.scheduleHighlight();
return this.dirty.length == 0;
},
// Creates a function that, when called through a timeout, will
// continuously re-parse the document.
documentScanner: function (passTime) {
var self = this, pos = null;
return function () {
// FF timeout weirdness workaround.
if (!window.select) return;
// If the current node is no longer in the document... oh
// well, we start over.
if (pos && pos.parentNode != self.container)
pos = null;
select.markSelection(self.win);
var result = self.highlight(pos, time() + passTime, true);
select.selectMarked();
var newPos = result ? (result.node && result.node.nextSibling) : null;
pos = (pos == newPos) ? null : newPos;
self.delayScanning();
};
},
// Starts the continuous scanning process for this document after
// a given interval.
delayScanning: function () {
if (this.scanner) {
this.parent.clearTimeout(this.documentScan);
this.documentScan = this.parent.setTimeout(this.scanner, this.options.continuousScanning);
}
},
// The function that does the actual highlighting/colouring (with
// help from the parser and the DOM normalizer). Its interface is
// rather overcomplicated, because it is used in different
// situations: ensuring that a certain line is highlighted, or
// highlighting up to X milliseconds starting from a certain
// point. The 'from' argument gives the node at which it should
// start. If this is null, it will start at the beginning of the
// document. When a timestamp is given with the 'target' argument,
// it will stop highlighting at that time. If this argument holds
// a DOM node, it will highlight until it reaches that node. If at
// any time it comes across two 'clean' lines (no dirty nodes), it
// will stop, except when 'cleanLines' is true. maxBacktrack is
// the maximum number of lines to backtrack to find an existing
// parser instance. This is used to give up in situations where a
// highlight would take too long and freeze the browser interface.
highlight: function (from, target, cleanLines, maxBacktrack) {
var container = this.container, self = this, active = this.options.activeTokens;
var endTime = (typeof target == "number" ? target : null);
if (!container.firstChild)
return false;
// Backtrack to the first node before from that has a partial
// parse stored.
while (from && (!from.parserFromHere || from.dirty)) {
if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0)
return false;
from = from.previousSibling;
}
// If we are at the end of the document, do nothing.
if (from && !from.nextSibling)
return false;
// Check whether a part (<span> node) and the corresponding token
// match.
function correctPart(token, part) {
return !part.reduced && part.currentText == token.value && part.className == token.style;
}
// Shorten the text associated with a part by chopping off
// characters from the front. Note that only the currentText
// property gets changed. For efficiency reasons, we leave the
// nodeValue alone -- we set the reduced flag to indicate that
// this part must be replaced.
function shortenPart(part, minus) {
part.currentText = part.currentText.substring(minus);
part.reduced = true;
}
// Create a part corresponding to a given token.
function tokenPart(token) {
var part = makePartSpan(token.value, self.doc);
part.className = token.style;
return part;
}
function maybeTouch(node) {
if (node) {
var old = node.oldNextSibling;
if (lineDirty || old === undefined || node.nextSibling != old)
self.history.touch(node);
node.oldNextSibling = node.nextSibling;
}
else {
var old = self.container.oldFirstChild;
if (lineDirty || old === undefined || self.container.firstChild != old)
self.history.touch(null);
self.container.oldFirstChild = self.container.firstChild;
}
}
// Get the token stream. If from is null, we start with a new
// parser from the start of the frame, otherwise a partial parse
// is resumed.
var traversal = traverseDOM(from ? from.nextSibling : container.firstChild),
stream = stringStream(traversal),
parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream);
function surroundedByBRs(node) {
return (node.previousSibling == null || isBR(node.previousSibling)) &&
(node.nextSibling == null || isBR(node.nextSibling));
}
// parts is an interface to make it possible to 'delay' fetching
// the next DOM node until we are completely done with the one
// before it. This is necessary because often the next node is
// not yet available when we want to proceed past the current
// one.
var parts = {
current: null,
// Fetch current node.
get: function () {
if (!this.current)
this.current = traversal.nodes.shift();
return this.current;
},
// Advance to the next part (do not fetch it yet).
next: function () {
this.current = null;
},
// Remove the current part from the DOM tree, and move to the
// next.
remove: function () {
container.removeChild(this.get());
this.current = null;
},
// Advance to the next part that is not empty, discarding empty
// parts.
getNonEmpty: function () {
var part = this.get();
// Allow empty nodes when they are alone on a line, needed
// for the FF cursor bug workaround (see select.js,
// insertNewlineAtCursor).
while (part && isSpan(part) && part.currentText == "") {
// Leave empty nodes that are alone on a line alone in
// Opera, since that browsers doesn't deal well with
// having 2 BRs in a row.
if (window.opera && surroundedByBRs(part)) {
this.next();
part = this.get();
}
else {
var old = part;
this.remove();
part = this.get();
// Adjust selection information, if any. See select.js for details.
select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0);
}
}
return part;
}
};
var lineDirty = false, prevLineDirty = true, lineNodes = 0;
// This forEach loops over the tokens from the parsed stream, and
// at the same time uses the parts object to proceed through the
// corresponding DOM nodes.
forEach(parsed, function (token) {
var part = parts.getNonEmpty();
if (token.value == "\n") {
// The idea of the two streams actually staying synchronized
// is such a long shot that we explicitly check.
if (!isBR(part))
throw "Parser out of sync. Expected BR.";
if (part.dirty || !part.indentation) lineDirty = true;
maybeTouch(from);
from = part;
// Every <br> gets a copy of the parser state and a lexical
// context assigned to it. The first is used to be able to
// later resume parsing from this point, the second is used
// for indentation.
part.parserFromHere = parsed.copy();
part.indentation = token.indentation;
part.dirty = false;
// If the target argument wasn't an integer, go at least
// until that node.
if (endTime == null && part == target) throw StopIteration;
// A clean line with more than one node means we are done.
// Throwing a StopIteration is the way to break out of a
// MochiKit forEach loop.
if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines))
throw StopIteration;
prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0;
parts.next();
}
else {
if (!isSpan(part))
throw "Parser out of sync. Expected SPAN.";
if (part.dirty)
lineDirty = true;
lineNodes++;
// If the part matches the token, we can leave it alone.
if (correctPart(token, part)) {
part.dirty = false;
parts.next();
}
// Otherwise, we have to fix it.
else {
lineDirty = true;
// Insert the correct part.
var newPart = tokenPart(token);
container.insertBefore(newPart, part);
if (active) active(newPart, token, self);
var tokensize = token.value.length;
var offset = 0;
// Eat up parts until the text for this token has been
// removed, adjusting the stored selection info (see
// select.js) in the process.
while (tokensize > 0) {
part = parts.get();
var partsize = part.currentText.length;
select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset);
if (partsize > tokensize) {
shortenPart(part, tokensize);
tokensize = 0;
}
else {
tokensize -= partsize;
offset += partsize;
parts.remove();
}
}
}
}
});
maybeTouch(from);
webkitLastLineHack(this.container);
// The function returns some status information that is used by
// hightlightDirty to determine whether and where it has to
// continue.
return { node: parts.getNonEmpty(),
dirty: lineDirty
};
}
};
return Editor;
})();
addEventHandler(window, "load", function() {
var CodeMirror = window.frameElement.CodeMirror;
var e = CodeMirror.editor = new Editor(CodeMirror.options);
this.parent.setTimeout(method(CodeMirror, "init"), 0);
});
| JavaScript |
/* String streams are the things fed to parsers (which can feed them
* to a tokenizer if they want). They provide peek and next methods
* for looking at the current character (next 'consumes' this
* character, peek does not), and a get method for retrieving all the
* text that was consumed since the last time get was called.
*
* An easy mistake to make is to let a StopIteration exception finish
* the token stream while there are still characters pending in the
* string stream (hitting the end of the buffer while parsing a
* token). To make it easier to detect such errors, the stringstreams
* throw an exception when this happens.
*/
// Make a stringstream stream out of an iterator that returns strings.
// This is applied to the result of traverseDOM (see codemirror.js),
// and the resulting stream is fed to the parser.
var stringStream = function(source){
// String that's currently being iterated over.
var current = "";
// Position in that string.
var pos = 0;
// Accumulator for strings that have been iterated over but not
// get()-ed yet.
var accum = "";
// Make sure there are more characters ready, or throw
// StopIteration.
function ensureChars() {
while (pos == current.length) {
accum += current;
current = ""; // In case source.next() throws
pos = 0;
try {current = source.next();}
catch (e) {
if (e != StopIteration) throw e;
else return false;
}
}
return true;
}
return {
// Return the next character in the stream.
peek: function() {
if (!ensureChars()) return null;
return current.charAt(pos);
},
// Get the next character, throw StopIteration if at end, check
// for unused content.
next: function() {
if (!ensureChars()) {
if (accum.length > 0)
throw "End of stringstream reached without emptying buffer ('" + accum + "').";
else
throw StopIteration;
}
return current.charAt(pos++);
},
// Return the characters iterated over since the last call to
// .get().
get: function() {
var temp = accum;
accum = "";
if (pos > 0){
temp += current.slice(0, pos);
current = current.slice(pos);
pos = 0;
}
return temp;
},
// Push a string back into the stream.
push: function(str) {
current = current.slice(0, pos) + str + current.slice(pos);
},
lookAhead: function(str, consume, skipSpaces, caseInsensitive) {
function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
str = cased(str);
var found = false;
var _accum = accum, _pos = pos;
if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/);
while (true) {
var end = pos + str.length, left = current.length - pos;
if (end <= current.length) {
found = str == cased(current.slice(pos, end));
pos = end;
break;
}
else if (str.slice(0, left) == cased(current.slice(pos))) {
accum += current; current = "";
try {current = source.next();}
catch (e) {break;}
pos = 0;
str = str.slice(left);
}
else {
break;
}
}
if (!(found && consume)) {
current = accum.slice(_accum.length) + current;
pos = _pos;
accum = _accum;
}
return found;
},
// Utils built on top of the above
more: function() {
return this.peek() !== null;
},
applies: function(test) {
var next = this.peek();
return (next !== null && test(next));
},
nextWhile: function(test) {
var next;
while ((next = this.peek()) !== null && test(next))
this.next();
},
matches: function(re) {
var next = this.peek();
return (next !== null && re.test(next));
},
nextWhileMatches: function(re) {
var next;
while ((next = this.peek()) !== null && re.test(next))
this.next();
},
equals: function(ch) {
return ch === this.peek();
},
endOfLine: function() {
var next = this.peek();
return next == null || next == "\n";
}
};
};
| JavaScript |
/**
* Storage and control for undo information within a CodeMirror
* editor. 'Why on earth is such a complicated mess required for
* that?', I hear you ask. The goal, in implementing this, was to make
* the complexity of storing and reverting undo information depend
* only on the size of the edited or restored content, not on the size
* of the whole document. This makes it necessary to use a kind of
* 'diff' system, which, when applied to a DOM tree, causes some
* complexity and hackery.
*
* In short, the editor 'touches' BR elements as it parses them, and
* the History stores these. When nothing is touched in commitDelay
* milliseconds, the changes are committed: It goes over all touched
* nodes, throws out the ones that did not change since last commit or
* are no longer in the document, and assembles the rest into zero or
* more 'chains' -- arrays of adjacent lines. Links back to these
* chains are added to the BR nodes, while the chain that previously
* spanned these nodes is added to the undo history. Undoing a change
* means taking such a chain off the undo history, restoring its
* content (text is saved per line) and linking it back into the
* document.
*/
// A history object needs to know about the DOM container holding the
// document, the maximum amount of undo levels it should store, the
// delay (of no input) after which it commits a set of changes, and,
// unfortunately, the 'parent' window -- a window that is not in
// designMode, and on which setTimeout works in every browser.
function History(container, maxDepth, commitDelay, editor) {
this.container = container;
this.maxDepth = maxDepth; this.commitDelay = commitDelay;
this.editor = editor; this.parent = editor.parent;
// This line object represents the initial, empty editor.
var initial = {text: "", from: null, to: null};
// As the borders between lines are represented by BR elements, the
// start of the first line and the end of the last one are
// represented by null. Since you can not store any properties
// (links to line objects) in null, these properties are used in
// those cases.
this.first = initial; this.last = initial;
// Similarly, a 'historyTouched' property is added to the BR in
// front of lines that have already been touched, and 'firstTouched'
// is used for the first line.
this.firstTouched = false;
// History is the set of committed changes, touched is the set of
// nodes touched since the last commit.
this.history = []; this.redoHistory = []; this.touched = [];
}
History.prototype = {
// Schedule a commit (if no other touches come in for commitDelay
// milliseconds).
scheduleCommit: function() {
var self = this;
this.parent.clearTimeout(this.commitTimeout);
this.commitTimeout = this.parent.setTimeout(function(){self.tryCommit();}, this.commitDelay);
},
// Mark a node as touched. Null is a valid argument.
touch: function(node) {
this.setTouched(node);
this.scheduleCommit();
},
// Undo the last change.
undo: function() {
// Make sure pending changes have been committed.
this.commit();
if (this.history.length) {
// Take the top diff from the history, apply it, and store its
// shadow in the redo history.
var item = this.history.pop();
this.redoHistory.push(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
// Redo the last undone change.
redo: function() {
this.commit();
if (this.redoHistory.length) {
// The inverse of undo, basically.
var item = this.redoHistory.pop();
this.addUndoLevel(this.updateTo(item, "applyChain"));
this.notifyEnvironment();
return this.chainNode(item);
}
},
clear: function() {
this.history = [];
this.redoHistory = [];
},
// Ask for the size of the un/redo histories.
historySize: function() {
return {undo: this.history.length, redo: this.redoHistory.length};
},
// Push a changeset into the document.
push: function(from, to, lines) {
var chain = [];
for (var i = 0; i < lines.length; i++) {
var end = (i == lines.length - 1) ? to : this.container.ownerDocument.createElement("BR");
chain.push({from: from, to: end, text: cleanText(lines[i])});
from = end;
}
this.pushChains([chain], from == null && to == null);
this.notifyEnvironment();
},
pushChains: function(chains, doNotHighlight) {
this.commit(doNotHighlight);
this.addUndoLevel(this.updateTo(chains, "applyChain"));
this.redoHistory = [];
},
// Retrieve a DOM node from a chain (for scrolling to it after undo/redo).
chainNode: function(chains) {
for (var i = 0; i < chains.length; i++) {
var start = chains[i][0], node = start && (start.from || start.to);
if (node) return node;
}
},
// Clear the undo history, make the current document the start
// position.
reset: function() {
this.history = []; this.redoHistory = [];
},
textAfter: function(br) {
return this.after(br).text;
},
nodeAfter: function(br) {
return this.after(br).to;
},
nodeBefore: function(br) {
return this.before(br).from;
},
// Commit unless there are pending dirty nodes.
tryCommit: function() {
if (!window.History) return; // Stop when frame has been unloaded
if (this.editor.highlightDirty()) this.commit(true);
else this.scheduleCommit();
},
// Check whether the touched nodes hold any changes, if so, commit
// them.
commit: function(doNotHighlight) {
this.parent.clearTimeout(this.commitTimeout);
// Make sure there are no pending dirty nodes.
if (!doNotHighlight) this.editor.highlightDirty(true);
// Build set of chains.
var chains = this.touchedChains(), self = this;
if (chains.length) {
this.addUndoLevel(this.updateTo(chains, "linkChain"));
this.redoHistory = [];
this.notifyEnvironment();
}
},
// [ end of public interface ]
// Update the document with a given set of chains, return its
// shadow. updateFunc should be "applyChain" or "linkChain". In the
// second case, the chains are taken to correspond the the current
// document, and only the state of the line data is updated. In the
// first case, the content of the chains is also pushed iinto the
// document.
updateTo: function(chains, updateFunc) {
var shadows = [], dirty = [];
for (var i = 0; i < chains.length; i++) {
shadows.push(this.shadowChain(chains[i]));
dirty.push(this[updateFunc](chains[i]));
}
if (updateFunc == "applyChain")
this.notifyDirty(dirty);
return shadows;
},
// Notify the editor that some nodes have changed.
notifyDirty: function(nodes) {
forEach(nodes, method(this.editor, "addDirtyNode"))
this.editor.scheduleHighlight();
},
notifyEnvironment: function() {
// Used by the line-wrapping line-numbering code.
if (window.frameElement && window.frameElement.CodeMirror.updateNumbers)
window.frameElement.CodeMirror.updateNumbers();
if (this.onChange) this.onChange();
},
// Link a chain into the DOM nodes (or the first/last links for null
// nodes).
linkChain: function(chain) {
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
if (line.from) line.from.historyAfter = line;
else this.first = line;
if (line.to) line.to.historyBefore = line;
else this.last = line;
}
},
// Get the line object after/before a given node.
after: function(node) {
return node ? node.historyAfter : this.first;
},
before: function(node) {
return node ? node.historyBefore : this.last;
},
// Mark a node as touched if it has not already been marked.
setTouched: function(node) {
if (node) {
if (!node.historyTouched) {
this.touched.push(node);
node.historyTouched = true;
}
}
else {
this.firstTouched = true;
}
},
// Store a new set of undo info, throw away info if there is more of
// it than allowed.
addUndoLevel: function(diffs) {
this.history.push(diffs);
if (this.history.length > this.maxDepth)
this.history.shift();
},
// Build chains from a set of touched nodes.
touchedChains: function() {
var self = this;
// The temp system is a crummy hack to speed up determining
// whether a (currently touched) node has a line object associated
// with it. nullTemp is used to store the object for the first
// line, other nodes get it stored in their historyTemp property.
var nullTemp = null;
function temp(node) {return node ? node.historyTemp : nullTemp;}
function setTemp(node, line) {
if (node) node.historyTemp = line;
else nullTemp = line;
}
function buildLine(node) {
var text = [];
for (var cur = node ? node.nextSibling : self.container.firstChild;
cur && !isBR(cur); cur = cur.nextSibling)
if (cur.currentText) text.push(cur.currentText);
return {from: node, to: cur, text: cleanText(text.join(""))};
}
// Filter out unchanged lines and nodes that are no longer in the
// document. Build up line objects for remaining nodes.
var lines = [];
if (self.firstTouched) self.touched.push(null);
forEach(self.touched, function(node) {
if (node && node.parentNode != self.container) return;
if (node) node.historyTouched = false;
else self.firstTouched = false;
var line = buildLine(node), shadow = self.after(node);
if (!shadow || shadow.text != line.text || shadow.to != line.to) {
lines.push(line);
setTemp(node, line);
}
});
// Get the BR element after/before the given node.
function nextBR(node, dir) {
var link = dir + "Sibling", search = node[link];
while (search && !isBR(search))
search = search[link];
return search;
}
// Assemble line objects into chains by scanning the DOM tree
// around them.
var chains = []; self.touched = [];
forEach(lines, function(line) {
// Note that this makes the loop skip line objects that have
// been pulled into chains by lines before them.
if (!temp(line.from)) return;
var chain = [], curNode = line.from, safe = true;
// Put any line objects (referred to by temp info) before this
// one on the front of the array.
while (true) {
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.unshift(curLine);
setTemp(curNode, null);
if (!curNode) break;
safe = self.after(curNode);
curNode = nextBR(curNode, "previous");
}
curNode = line.to; safe = self.before(line.from);
// Add lines after this one at end of array.
while (true) {
if (!curNode) break;
var curLine = temp(curNode);
if (!curLine) {
if (safe) break;
else curLine = buildLine(curNode);
}
chain.push(curLine);
setTemp(curNode, null);
safe = self.before(curNode);
curNode = nextBR(curNode, "next");
}
chains.push(chain);
});
return chains;
},
// Find the 'shadow' of a given chain by following the links in the
// DOM nodes at its start and end.
shadowChain: function(chain) {
var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to;
while (true) {
shadows.push(next);
var nextNode = next.to;
if (!nextNode || nextNode == end)
break;
else
next = nextNode.historyAfter || this.before(end);
// (The this.before(end) is a hack -- FF sometimes removes
// properties from BR nodes, in which case the best we can hope
// for is to not break.)
}
return shadows;
},
// Update the DOM tree to contain the lines specified in a given
// chain, link this chain into the DOM nodes.
applyChain: function(chain) {
// Some attempt is made to prevent the cursor from jumping
// randomly when an undo or redo happens. It still behaves a bit
// strange sometimes.
var cursor = select.cursorPos(this.container, false), self = this;
// Remove all nodes in the DOM tree between from and to (null for
// start/end of container).
function removeRange(from, to) {
var pos = from ? from.nextSibling : self.container.firstChild;
while (pos != to) {
var temp = pos.nextSibling;
removeElement(pos);
pos = temp;
}
}
var start = chain[0].from, end = chain[chain.length - 1].to;
// Clear the space where this change has to be made.
removeRange(start, end);
// Insert the content specified by the chain into the DOM tree.
for (var i = 0; i < chain.length; i++) {
var line = chain[i];
// The start and end of the space are already correct, but BR
// tags inside it have to be put back.
if (i > 0)
self.container.insertBefore(line.from, end);
// Add the text.
var node = makePartSpan(fixSpaces(line.text), this.container.ownerDocument);
self.container.insertBefore(node, end);
// See if the cursor was on this line. Put it back, adjusting
// for changed line length, if it was.
if (cursor && cursor.node == line.from) {
var cursordiff = 0;
var prev = this.after(line.from);
if (prev && i == chain.length - 1) {
// Only adjust if the cursor is after the unchanged part of
// the line.
for (var match = 0; match < cursor.offset &&
line.text.charAt(match) == prev.text.charAt(match); match++);
if (cursor.offset > match)
cursordiff = line.text.length - prev.text.length;
}
select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)});
}
// Cursor was in removed line, this is last new line.
else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) {
select.setCursorPos(this.container, {node: line.from, offset: line.text.length});
}
}
// Anchor the chain in the DOM tree.
this.linkChain(chain);
return start;
}
};
| JavaScript |
/* Parse function for JavaScript. Makes use of the tokenizer from
* tokenizejavascript.js. Note that your parsers do not have to be
* this complicated -- if you don't want to recognize local variables,
* in many languages it is enough to just look for braces, semicolons,
* parentheses, etc, and know when you are inside a string or comment.
*
* See manual.html for more info about the parser interface.
*/
var JSParser = Editor.Parser = (function() {
// Token types that can be considered to be atoms.
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
// Setting that can be used to have JSON data indent properly.
var json = false;
// Constructor for the lexical context objects.
function JSLexical(indented, column, type, align, prev, info) {
// indentation at start of this line
this.indented = indented;
// column at which this scope was opened
this.column = column;
// type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(')
this.type = type;
// '[', '{', or '(' blocks that have any text after their opening
// character are said to be 'aligned' -- any lines below are
// indented all the way to the opening character.
if (align != null)
this.align = align;
// Parent scope, if any.
this.prev = prev;
this.info = info;
}
// My favourite JavaScript indentation rules.
function indentJS(lexical) {
return function(firstChars) {
var firstChar = firstChars && firstChars.charAt(0), type = lexical.type;
var closing = firstChar == type;
if (type == "vardef")
return lexical.indented + 4;
else if (type == "form" && firstChar == "{")
return lexical.indented;
else if (type == "stat" || type == "form")
return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit);
else if (lexical.align)
return lexical.column - (closing ? 1 : 0);
else
return lexical.indented + (closing ? 0 : indentUnit);
};
}
// The parser-iterator-producing function itself.
function parseJS(input, basecolumn) {
// Wrap the input in a token stream
var tokens = tokenizeJavaScript(input);
// The parser state. cc is a stack of actions that have to be
// performed to finish the current statement. For example we might
// know that we still need to find a closing parenthesis and a
// semicolon. Actions at the end of the stack go first. It is
// initialized with an infinitely looping action that consumes
// whole statements.
var cc = [json ? singleExpr : statements];
// Context contains information about the current local scope, the
// variables defined in that, and the scopes above it.
var context = null;
// The lexical scope, used mostly for indentation.
var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false);
// Current column, and the indentation at the start of the current
// line. Used to create lexical scope objects.
var column = 0;
var indented = 0;
// Variables which are used by the mark, cont, and pass functions
// below to communicate with the driver loop in the 'next'
// function.
var consume, marked;
// The iterator object.
var parser = {next: next, copy: copy};
function next(){
// Start by performing any 'lexical' actions (adjusting the
// lexical variable), or the operations below will be working
// with the wrong lexical state.
while(cc[cc.length - 1].lex)
cc.pop()();
// Fetch a token.
var token = tokens.next();
// Adjust column and indented.
if (token.type == "whitespace" && column == 0)
indented = token.value.length;
column += token.value.length;
if (token.content == "\n"){
indented = column = 0;
// If the lexical scope's align property is still undefined at
// the end of the line, it is an un-aligned scope.
if (!("align" in lexical))
lexical.align = false;
// Newline tokens get an indentation function associated with
// them.
token.indentation = indentJS(lexical);
}
// No more processing for meaningless tokens.
if (token.type == "whitespace" || token.type == "comment")
return token;
// When a meaningful token is found and the lexical scope's
// align is undefined, it is an aligned scope.
if (!("align" in lexical))
lexical.align = true;
// Execute actions until one 'consumes' the token and we can
// return it.
while(true) {
consume = marked = false;
// Take and execute the topmost action.
cc.pop()(token.type, token.content);
if (consume){
// Marked is used to change the style of the current token.
if (marked)
token.style = marked;
// Here we differentiate between local and global variables.
else if (token.type == "variable" && inScope(token.content))
token.style = "js-localvariable";
return token;
}
}
}
// This makes a copy of the parser state. It stores all the
// stateful variables in a closure, and returns a function that
// will restore them when called with a new input stream. Note
// that the cc array has to be copied, because it is contantly
// being modified. Lexical objects are not mutated, and context
// objects are not mutated in a harmful way, so they can be shared
// between runs of the parser.
function copy(){
var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;
return function copyParser(input){
context = _context;
lexical = _lexical;
cc = _cc.concat([]); // copies the array
column = indented = 0;
tokens = tokenizeJavaScript(input, _tokenState);
return parser;
};
}
// Helper function for pushing a number of actions onto the cc
// stack in reverse order.
function push(fs){
for (var i = fs.length - 1; i >= 0; i--)
cc.push(fs[i]);
}
// cont and pass are used by the action functions to add other
// actions to the stack. cont will cause the current token to be
// consumed, pass will leave it for the next action.
function cont(){
push(arguments);
consume = true;
}
function pass(){
push(arguments);
consume = false;
}
// Used to change the style of the current token.
function mark(style){
marked = style;
}
// Push a new scope. Will automatically link the current scope.
function pushcontext(){
context = {prev: context, vars: {"this": true, "arguments": true}};
}
// Pop off the current scope.
function popcontext(){
context = context.prev;
}
// Register a variable in the current scope.
function register(varname){
if (context){
mark("js-variabledef");
context.vars[varname] = true;
}
}
// Check whether a variable is defined in the current scope.
function inScope(varname){
var cursor = context;
while (cursor) {
if (cursor.vars[varname])
return true;
cursor = cursor.prev;
}
return false;
}
// Push a new lexical context of the given type.
function pushlex(type, info) {
var result = function(){
lexical = new JSLexical(indented, column, type, null, lexical, info)
};
result.lex = true;
return result;
}
// Pop off the current lexical context.
function poplex(){
lexical = lexical.prev;
}
poplex.lex = true;
// The 'lex' flag on these actions is used by the 'next' function
// to know they can (and have to) be ran before moving on to the
// next token.
// Creates an action that discards tokens until it finds one of
// the given type.
function expect(wanted){
return function expecting(type){
if (type == wanted) cont();
else cont(arguments.callee);
};
}
// Looks for a statement, and then calls itself.
function statements(type){
return pass(statement, statements);
}
function singleExpr(type){
return pass(expression, statements);
}
// Dispatches various types of statements based on the type of the
// current token.
function statement(type){
if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex);
else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex);
else if (type == "keyword b") cont(pushlex("form"), statement, poplex);
else if (type == "{") cont(pushlex("}"), block, poplex);
else if (type == "function") cont(functiondef);
else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex);
else if (type == "variable") cont(pushlex("stat"), maybelabel);
else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex);
else if (type == "case") cont(expression, expect(":"));
else if (type == "default") cont(expect(":"));
else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext);
else pass(pushlex("stat"), expression, expect(";"), poplex);
}
// Dispatch expression types.
function expression(type){
if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator);
else if (type == "function") cont(functiondef);
else if (type == "keyword c") cont(expression);
else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
else if (type == "operator") cont(expression);
else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
}
// Called for places where operators, function calls, or
// subscripts are valid. Will skip on to the next action if none
// is found.
function maybeoperator(type){
if (type == "operator") cont(expression);
else if (type == "(") cont(pushlex(")"), expression, commasep(expression, ")"), poplex, maybeoperator);
else if (type == ".") cont(property, maybeoperator);
else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
// When a statement starts with a variable name, it might be a
// label. If no colon follows, it's a regular statement.
function maybelabel(type){
if (type == ":") cont(poplex, statement);
else pass(maybeoperator, expect(";"), poplex);
}
// Property names need to have their style adjusted -- the
// tokenizer thinks they are variables.
function property(type){
if (type == "variable") {mark("js-property"); cont();}
}
// This parses a property and its value in an object literal.
function objprop(type){
if (type == "variable") mark("js-property");
if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression);
}
// Parses a comma-separated list of the things that are recognized
// by the 'what' argument.
function commasep(what, end){
function proceed(type) {
if (type == ",") cont(what, proceed);
else if (type == end) cont();
else cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) cont();
else pass(what, proceed);
};
}
// Look for statements until a closing brace is found.
function block(type){
if (type == "}") cont();
else pass(statement, block);
}
// Variable definitions are split into two actions -- 1 looks for
// a name or the end of the definition, 2 looks for an '=' sign or
// a comma.
function vardef1(type, value){
if (type == "variable"){register(value); cont(vardef2);}
else cont();
}
function vardef2(type, value){
if (value == "=") cont(expression, vardef2);
else if (type == ",") cont(vardef1);
}
// For loops.
function forspec1(type){
if (type == "var") cont(vardef1, forspec2);
else if (type == ";") pass(forspec2);
else if (type == "variable") cont(formaybein);
else pass(forspec2);
}
function formaybein(type, value){
if (value == "in") cont(expression);
else cont(maybeoperator, forspec2);
}
function forspec2(type, value){
if (type == ";") cont(forspec3);
else if (value == "in") cont(expression);
else cont(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type == ")") pass();
else cont(expression);
}
// A function definition creates a new context, and the variables
// in its argument list have to be added to this context.
function functiondef(type, value){
if (type == "variable"){register(value); cont(functiondef);}
else if (type == "(") cont(pushcontext, commasep(funarg, ")"), statement, popcontext);
}
function funarg(type, value){
if (type == "variable"){register(value); cont();}
}
return parser;
}
return {
make: parseJS,
electricChars: "{}:",
configure: function(obj) {
if (obj.json != null) json = obj.json;
}
};
})();
| JavaScript |
var DummyParser = Editor.Parser = (function() {
function tokenizeDummy(source) {
while (!source.endOfLine()) source.next();
return "text";
}
function parseDummy(source) {
function indentTo(n) {return function() {return n;}}
source = tokenizer(source, tokenizeDummy);
var space = 0;
var iter = {
next: function() {
var tok = source.next();
if (tok.type == "whitespace") {
if (tok.value == "\n") tok.indentation = indentTo(space);
else space = tok.value.length;
}
return tok;
},
copy: function() {
var _space = space;
return function(_source) {
space = _space;
source = tokenizer(_source, tokenizeDummy);
return iter;
};
}
};
return iter;
}
return {make: parseDummy};
})();
| JavaScript |
$.fn.tabs = function () {
$(this).delegate("a:not(.youarehere)", "click", function () {
$(this.hash).show();
$(this).addClass("youarehere")
.siblings(".youarehere")
.removeClass("youarehere").each(function () {
$(this.hash).hide();
});
}).delegate("a", "click", function () {
return false;
});
};
function encodeColumn(s) {
if (s != null && s.replace != null) {
s = s.replace(/[\n\r]/g, " ")
.replace(/&(?!\w+([;\s]|$))/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.substring(0, 400);
return s;
} else {
return s;
}
}
function splitTags(s) {
if (s == null) return [];
var tmp = s.split("<");
var rval = [];
for (var i = 0; i < tmp.length; i++) {
if (tmp[i] != "") {
rval.push(tmp[i].replace(">", ""));
}
}
return rval;
}
var current_results;
function scrollToResults() {
var target_offset = $("#toolbar").offset();
var target_top = target_offset.top - 10;
$('html, body').animate({ scrollTop: target_top }, 500);
}
// this is from SO 901115
function getParameterByName(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 decodeURIComponent(results[1].replace(/\+/g, " "));
}
function populateParamsFromUrl() {
$('#queryParams').find("p input").each(function () {
var val = getParameterByName(this.name);
if (val != null && val.length > 0) {
$(this).val(getParameterByName(this.name));
}
});
}
function displayCaptcha() {
$('form input[type=submit]').hide();
$('#captcha').show();
$("#recaptcha_response_field").keydown(function (key) {
if (key.keyCode == 13) {
$("#btn-captcha").click();
return false;
}
return true;
}).focus();
var captcha = function () {
$(this).unbind("click");
$.ajax({
url: '/captcha',
data: $('#captcha').closest('form').serialize(),
type: 'POST',
success: function (data) {
if (data.success) {
$('form input[type=submit]').show();
$('#captcha').hide();
$('#captcha').closest('form').submit();
} else {
$("#captcha-error").fadeIn();
$("#btn-captcha").click(captcha);
var text = $("#recaptcha_response_field");
var once = function () { $("#captcha-error").fadeOut(); text.unbind("keydown", once) };
text.keydown(once);
}
},
dataType: "json"
});
};
$("#btn-captcha").click(captcha);
}
function gotResults(results) {
$(".loading").hide();
$('form input[type=submit]').attr('disabled', null);
if (results && results.captcha) {
displayCaptcha();
return;
}
current_results = results;
if (results.error != null) {
$("#queryErrorBox").show();
$("#queryError").html(results.error);
return;
}
if (results.truncated == true) {
$("#queryErrorBox").show();
$("#queryError").html("Your query was truncated, only " + results.maxResults + " results are allowed");
}
$("#messages pre code").text(results.messages);
var currentParams = "?";
currentParams += $('#queryParams').find("p input").serialize();
if (currentParams == "?") {
currentParams = "";
}
$("#permalinks").show();
var currentLink = $("#permalink")[0];
var linkId = results.queryId;
var slug = results.slug == null ? "/" : "/" + results.slug;
var linkPath = results.textOnly ? "qt" : "q";
if (window.queryId !== undefined) {
linkId = queryId;
slug = "/" + querySlug;
linkPath = results.textOnly ? "st" : "s";
}
currentLink.href = "/" + results.siteName + "/"+ linkPath + "/" + linkId + slug + currentParams;
$("#downloadCsv")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "csv/" + results.queryId + currentParams;
$(".otherPermalink").each(function () {
// slug
this.href = this.href.substring(0, this.href.lastIndexOf("/"));
// query id
this.href = this.href.substring(0, this.href.lastIndexOf("/"));
// type
this.href = this.href.substring(0, this.href.lastIndexOf("/") + 1) + linkPath + "/" + linkId + slug;
});
$("#gridStats .duration").text("Duration: " + results.executionTime + "ms");
if (results.executionPlan && results.executionPlan.length > 0) {
$("#planTabButton").show();
$("#executionPlan").html(results.executionPlan);
QP.drawLines();
$("#downloadPlan")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "plan/" + results.queryId + currentParams;
$("#downloadPlan").show();
}
else {
$("#planTabButton").hide();
$("#downloadPlan").hide();
}
if (results.textOnly || results.resultSets.length == 0) {
$("#messagesTabButton").click();
$("#resultsTabButton").hide();
$("#queryResults").show();
return;
}
$("#resultsTabButton").show();
$("#resultsTabButton").click();
$("#grid").show();
$("#messages").hide();
var model = [];
var maxWidths = [];
for (var c = 0; c < results.resultSets[0].columns.length; c++) {
model.push({
width: 60,
cssClass: (results.resultSets[0].columns[c].type == "Number" ? "number" : "text"),
id: results.resultSets[0].columns[c].name,
name: results.resultSets[0].columns[c].name,
field: c
});
maxWidths.push(results.resultSets[0].columns[c].name.length);
}
var rows = [];
var hasTags = false;
for (var i = 0; i < results.resultSets[0].rows.length; i++) {
var row = {};
for (var c = 0; c < results.resultSets[0].columns.length; c++) {
var data = null;
var col = results.resultSets[0].rows[i][c];
if (col != null && col.title != null && col.id != null) {
var isUser = (results.resultSets[0].columns[c].type == "User");
data = ("<a href=\"" + results.url + (isUser ? "/users/" : "/questions/") +
col.id + "\">" + encodeColumn(col.title) + "</a>");
if (col.title.length > maxWidths[c]) maxWidths[c] = col.title.length;
} else if (model[c].field == "Tags" || model[c].field == "TagName") {
// smart rendering of tags
var tags = splitTags(col);
var tmpLength = tags.join(" ").length;
if (col != null && tmpLength > maxWidths[c]) maxWidths[c] = tmpLength;
for (var tagIndex = 0; tagIndex < tags.length; tagIndex++) {
tags[tagIndex] = "<a class=\"post-tag\" href=\"" + results.url + "/tags/" + tags[tagIndex] + "\">" + tags[tagIndex] + "</a>";
};
data = tags.join(" ");
hasTags = true;
} else {
data = (encodeColumn(col));
if (col != null && col.toString().length > maxWidths[c]) maxWidths[c] = col.toString().length;
}
row[c] = data;
}
rows.push(row);
}
for (var i = 0; i < model.length; i++) {
model[i].width = maxWidths[i] * 12 > 250 ? 300 : 8 + maxWidths[i] * 12;
}
$("#queryResults").show();
$("#gridStats .rows").text("" + rows.length + " row" + (rows.length == 1 ? "" : "s"));
var options = {
enableCellNavigation: false,
enableColumnReorder: false,
rowHeight: hasTags ? 35 : 25
};
var grid = new Slick.Grid($("#grid"), rows, model, options);
grid.onColumnsResized = function () { $("#grid").resize() };
scrollToResults();
$("#queryResults").insertAfter('.page:first').css({ 'padding': '0 30px', 'margin': '0 auto' });
$("#grid").resize();
}
function executeQuery(sql) {
$("#permalinks, #queryResults, #queryErrorBox").hide();
if (!ensureAllParamsEntered(sql)) {
return false;
}
$(".loading").show();
$('#runQueryForm input[type=submit]', this).attr('disabled', 'disabled');
$.ajax({
cache: false,
url: $('#runQueryForm')[0].action,
type: "POST",
data: $("#runQueryForm").serialize(),
error: function () {
alert("Something is wrong with the server!");
},
success: gotResults
});
return false;
}
function ensureAllParamsEntered(query) {
var pattern = /##([a-zA-Z0-9]+):?([a-zA-Z]+)?##/g;
var params = query.match(pattern);
if (params == null) params = [];
var div = $('#queryParams');
var allParamsHaveValues = true;
for (var i = 0; i < params.length; i++) {
params[i] = params[i].substring(2, params[i].length - 2);
var colonPos = params[i].indexOf(":");
if (colonPos > 0) {
params[i] = params[i].substring(0, colonPos);
}
var currentParam = div.find("input[name=" + params[i] + "]");
if (currentParam.length == 0) {
div.append("<p><label>" + params[i] + "</label>\n" +
"<input type=\"text\" name=\"" + params[i] + "\" value=\"\" /><div class='clear'></div></p>");
allParamsHaveValues = false;
} else {
if (currentParam.val().length == 0) {
allParamsHaveValues = false;
}
}
}
// remove extra params
div.children("p").each(function () {
var name = $(this).find('input').attr('name');
var found = false;
for (var i = 0; i < params.length; i++) {
found = params[i] == name;
if (found) break;
}
if (!found) {
$(this).remove();
} else {
// auto param
if ($(this).find('input').val().length == 0 && name == "UserId") {
$(this).find('input').val(guessedUserId);
}
}
});
div.toggle(params.length > 0);
if (params.length > 0 && !allParamsHaveValues) {
div.find('input:first').focus();
}
return allParamsHaveValues;
}
function forwardEvent(event, element) {
if (event == "focus") {
$(".CodeMirror-wrapping").addClass("focus");
}
if (event == "blur") {
$(".CodeMirror-wrapping").removeClass("focus");
}
}
$(function () {
$("#grid").resize(function () {
var width = 0;
$(".slick-header-column").each(function () { width += $(this).outerWidth(); });
$.data(this, "width", width)
}).add(window).resize(function () {
var width = $("#grid").data("width"), docWidth = document.documentElement.clientWidth - 80;
if(width > docWidth) width = docWidth - 80;
if(width < 950) width = 950;
$("#queryResults").width(width + 20);
$("#gridStats").width(width + 10);
});
}); | JavaScript |
/// <reference path="third-party/jquery-1.3.2-vsdoc2.js"/>
$(function() {
var loader = '<img class="ajax-loader" src="http://sstatic.net/img/progress-dots.gif" title="loading..." alt="loading..." width="11" height="11" />';
var removeLoader = function() { $('.ajax-loader').fadeOut('fast'); };
// update title on main error log page to show count
$('#errorcount').each(function() { // when count > 1, #errorcount is a div; when 0, it's a span
var count = $('table#ErrorLog td.type-col').length;
document.title = count + ' Error' + (Math.abs(count) == 1 ? '' : 's');
});
// ajax the error deletion
$('table#ErrorLog a.delete-link').click(function() {
var jThis = $(this);
// if we've "protected" this error, confirm the deletion
if (jThis.parent().find('a.protect-link').length == 0 && !confirm('Really delete this protected error?')) return false;
var jRow = jThis.closest('tr');
var href = jThis.attr('href');
jThis.attr('href', 'javascript:void(0)');
jThis.parent().prepend(loader);
jThis.remove();
$.ajax({
type: 'GET',
url: href,
dataType: 'html',
success: function(result) {
jRow.remove();
removeLoader();
},
error: function(res, textStatus, errorThrown) {
removeLoader();
alert('Error occurred when trying to delete');
}
});
});
// ajax the protection
$('table#ErrorLog a.protect-link').click(function() {
var jThis = $(this);
var href = jThis.attr('href');
jThis.attr('href', 'javascript:void(0)');
jThis.parent().append(loader);
jThis.remove();
$.ajax({
type: 'GET',
url: href,
dataType: 'html',
success: function(result) {
removeLoader();
},
error: function(res, textStatus, errorThrown) {
removeLoader();
alert('Error occurred when trying to delete');
}
});
});
// allow clicks to finding users based on cookies and ips
$('td.ip-address, div#ServerVariables td:contains("REMOTE_ADDR") + td').each(function() {
var jThis = $(this);
jThis.wrap('<a href="/admin/users-with-ip/' + jThis.text() + '" target="_blank"></a>');
});
$('div#Cookies td:contains("user") + td').each(function() {
var jThis = $(this);
var series = jThis.text().match(/s=(.*)/);
if (series.length > 0) {
jThis.wrap('<a href="/admin/users-with-cookie-series/' + series[1] + '" target="_blank"></a>');
}
});
}); | JavaScript |
function save() {
$.ajax({
url: './ajax/get_json.php',
type: 'GET',
data: {controller: 'MapController', method: 'saveMapToFile', fileName: 'map.txt'},
dataType: 'json',
success: function(data){
console.log(data);
}
});
} | JavaScript |
/** Socket.IO - Built with build.bat */
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
this.io = {
version: '0.6',
setPath: function(path){
if (window.console && console.error) console.error('io.setPath will be removed. Please set the variable WEB_SOCKET_SWF_LOCATION pointing to WebSocketMain.swf');
this.path = /\/$/.test(path) ? path : path + '/';
WEB_SOCKET_SWF_LOCATION = path + 'flashsocket/WebSocketMain.swf';
}
};
if ('jQuery' in this) jQuery.io = this.io;
if (typeof window != 'undefined'){
// WEB_SOCKET_SWF_LOCATION = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cdn.socket.io/' + this.io.version + '/WebSocketMain.swf';
WEB_SOCKET_SWF_LOCATION = '/socket.io/flashsocket/WebSocketMain.swf';
}
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var _pageLoaded = false;
io.util = {
ios: false,
load: function(fn){
if (document.readyState == 'complete' || _pageLoaded) return fn();
if ('attachEvent' in window){
window.attachEvent('onload', fn);
} else {
window.addEventListener('load', fn, false);
}
},
inherit: function(ctor, superCtor){
// no support for `instanceof` for now
for (var i in superCtor.prototype){
ctor.prototype[i] = superCtor.prototype[i];
}
},
indexOf: function(arr, item, from){
for (var l = arr.length, i = (from < 0) ? Math.max(0, l + from) : from || 0; i < l; i++){
if (arr[i] === item) return i;
}
return -1;
},
isArray: function(obj){
return Object.prototype.toString.call(obj) === '[object Array]';
},
merge: function(target, additional){
for (var i in additional)
if (additional.hasOwnProperty(i))
target[i] = additional[i];
}
};
io.util.ios = /iphone|ipad/i.test(navigator.userAgent);
io.util.android = /android/i.test(navigator.userAgent);
io.util.opera = /opera/i.test(navigator.userAgent);
io.util.load(function(){
_pageLoaded = true;
});
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
// abstract
(function(){
var Frame = {
//
FRAME_CHAR: '~',
// Control Codes
CLOSE_CODE: 0,
SESSION_ID_CODE: 1,
TIMEOUT_CODE: 2,
PING_CODE: 3,
PONG_CODE: 4,
DATA_CODE: 0xE,
FRAGMENT_CODE: 0xF,
// Core Message Types
TEXT_MESSAGE_TYPE: 0,
JSON_MESSAGE_TYPE: 1,
// Methods
encode: function(ftype, mtype, data) {
if (!!mtype) {
return this.FRAME_CHAR + ftype.toString(16) + mtype.toString(16)
+ this.FRAME_CHAR + data.length.toString(16)
+ this.FRAME_CHAR + data;
} else {
return this.FRAME_CHAR + ftype.toString(16)
+ this.FRAME_CHAR + data.length.toString(16)
+ this.FRAME_CHAR + data;
}
},
decode: function(data) {
var frames = [];
var idx = 0;
var start = 0;
var end = 0;
var ftype = 0;
var mtype = 0;
var size = 0;
// Parse the data and silently ignore any part that fails to parse properly.
while (data.length > idx && data.charAt(idx) == this.FRAME_CHAR) {
ftype = 0;
mtype = 0;
start = idx + 1;
end = data.indexOf(this.FRAME_CHAR, start);
if (-1 == end || start == end ||
!/[0-9A-Fa-f]+/.test(data.substring(start, end))) {
break;
}
ftype = parseInt(data.substring(start, start+1), 16);
if (end-start > 1) {
if (ftype == this.DATA_CODE || ftype == this.FRAGEMENT_CODE) {
mtype = parseInt(data.substring(start+1, end), 16);
} else {
break;
}
}
start = end + 1;
end = data.indexOf(this.FRAME_CHAR, start);
if (-1 == end || start == end ||
!/[0-9A-Fa-f]+/.test(data.substring(start, end))) {
break;
}
var size = parseInt(data.substring(start, end), 16);
start = end + 1;
end = start + size;
if (data.length < end) {
break;
}
frames.push({ftype: ftype, mtype: mtype, data: data.substring(start, end)});
idx = end;
}
return frames;
}
};
Transport = io.Transport = function(base, options){
this.base = base;
this.options = {
timeout: 15000 // based on heartbeat interval default
};
io.util.merge(this.options, options);
this.message_id = 0;
};
Transport.prototype.send = function(mtype, data){
this.message_id++;
this.rawsend(Frame.encode(Frame.DATA_CODE, mtype, data));
};
Transport.prototype.rawsend = function(){
throw new Error('Missing send() implementation');
};
Transport.prototype._destroy = function(){
throw new Error('Missing _destroy() implementation');
};
Transport.prototype.connect = function(){
throw new Error('Missing connect() implementation');
};
Transport.prototype.disconnect = function(){
throw new Error('Missing disconnect() implementation');
};
Transport.prototype.close = function() {
this.close_id = 'client';
this.rawsend(Frame.encode(Frame.CLOSE_CODE, null, this.close_id));
};
Transport.prototype._onData = function(data){
this._setTimeout();
var msgs = Frame.decode(data);
if (msgs && msgs.length){
for (var i = 0, l = msgs.length; i < l; i++){
this._onMessage(msgs[i]);
}
}
};
Transport.prototype._setTimeout = function(){
var self = this;
if (this._timeout) clearTimeout(this._timeout);
this._timeout = setTimeout(function(){
self._onTimeout();
}, this.options.timeout);
};
Transport.prototype._onTimeout = function(){
this._timedout = true;
if (!!this._interval) {
clearInterval(this._interval);
this._interval = null;
}
this.disconnect();
};
Transport.prototype._onMessage = function(message){
if (!this.sessionid){
if (message.ftype == Frame.SESSION_ID_CODE) {
this.sessionid = message.data;
this._onConnect();
} else {
this._onDisconnect(this.base.DR_ERROR, "First frame wasn't the sesion ID!");
}
} else if (message.ftype == Frame.TIMEOUT_CODE) {
hg_interval = Number(message.data);
if (message.data == hg_interval) {
this.options.timeout = hg_interval*2; // Set timeout to twice the new heartbeat interval
this._setTimeout();
}
} else if (message.ftype == Frame.CLOSE_CODE) {
this._onCloseFrame(message.data);
} else if (message.ftype == Frame.PING_CODE) {
this._onPingFrame(message.data);
} else if (message.ftype == Frame.DATA_CODE) {
this.base._onMessage(message.mtype, message.data);
} else {
// For now we'll ignore other frame types.
}
},
Transport.prototype._onPingFrame = function(data){
this.rawsend(Frame.encode(Frame.PONG_CODE, null, data));
};
Transport.prototype._onConnect = function(){
this.base._onConnect();
this._setTimeout();
};
Transport.prototype._onCloseFrame = function(data){
if (this.base.socketState == this.base.CLOSING) {
if (!!this.close_id && this.close_id == data) {
this.base.socketState = this.base.CLOSED;
this.disconnect();
} else {
/*
* It's possible the server initiated a close at the same time we did and our
* initial close messages passed each other like ships in the night. So, to be nice
* we'll send an acknowledge of the server's close message.
*/
this.rawsend(Frame.encode(Frame.CLOSE_CODE, null, data));
}
} else {
this.base.socketState = this.base.CLOSING;
this.disconnectWhenEmpty = true;
this.rawsend(Frame.encode(Frame.CLOSE_CODE, null, data));
}
};
Transport.prototype._onDisconnect = function(reason, error){
if (this._timeout) clearTimeout(this._timeout);
this.sessionid = null;
this.disconnectWhenEmpty = false;
if (this._timedout) {
reason = this.base.DR_TIMEOUT;
error = null;
}
this.base._onDisconnect(reason, error);
};
Transport.prototype._prepareUrl = function(){
return (this.base.options.secure ? 'https' : 'http')
+ '://' + this.base.host
+ ':' + this.base.options.port
+ '/' + this.base.options.resource
+ '/' + this.type
+ (this.sessionid ? ('/' + this.sessionid) : '/');
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var empty = new Function,
XMLHttpRequestCORS = (function(){
if (!('XMLHttpRequest' in window)) return false;
// CORS feature detection
var a = new XMLHttpRequest();
return a.withCredentials != undefined;
})(),
request = function(xdomain){
if ('XDomainRequest' in window && xdomain) return new XDomainRequest();
if ('XMLHttpRequest' in window && (!xdomain || XMLHttpRequestCORS)) return new XMLHttpRequest();
if (!xdomain){
try {
var a = new ActiveXObject('MSXML2.XMLHTTP');
return a;
} catch(e){}
try {
var b = new ActiveXObject('Microsoft.XMLHTTP');
return b;
} catch(e){}
}
return false;
},
XHR = io.Transport.XHR = function(){
io.Transport.apply(this, arguments);
this._sendBuffer = [];
};
io.util.inherit(XHR, io.Transport);
XHR.prototype.connect = function(){
this._get();
return this;
};
XHR.prototype._checkSend = function(){
if (!this._posting && this._sendBuffer.length){
var data = '';
for (var i = 0, l = this._sendBuffer.length; i < l; i++){
data += this._sendBuffer[i];
}
this._sendBuffer = [];
this._send(data);
} else if (!!this.disconnectWhenEmpty) {
this.disconnect();
}
};
XHR.prototype.rawsend = function(data){
if (io.util.isArray(data)){
this._sendBuffer.push.apply(this._sendBuffer, data);
} else {
this._sendBuffer.push(data);
}
this._checkSend();
return this;
};
XHR.prototype._send = function(data){
var self = this;
this._posting = true;
this._sendXhr = this._request('send', 'POST');
this._sendXhr.onreadystatechange = function(){
var status;
if (self._sendXhr.readyState == 4){
self._sendXhr.onreadystatechange = empty;
try { status = self._sendXhr.status; } catch(e){}
self._posting = false;
if (status == 200){
self._checkSend();
} else {
self._onDisconnect(self.base.DR_ERROR, "POST failed!");
}
}
};
this._sendXhr.send(data);
};
XHR.prototype.disconnect = function(){
// send disconnection signal
this._onDisconnect();
return this;
};
XHR.prototype._destroy = function(){
if (this._xhr){
this._xhr.onreadystatechange = this._xhr.onload = empty;
this._xhr.abort();
this._xhr = null;
}
if (this._sendXhr){
this._sendXhr.onreadystatechange = this._sendXhr.onload = empty;
this._sendXhr.abort();
this._sendXhr = null;
}
this._sendBuffer = [];
};
XHR.prototype._onDisconnect = function(reason, error){
this._destroy();
io.Transport.prototype._onDisconnect.call(this, reason, error);
};
XHR.prototype._request = function(url, method, multipart){
var req = request(this.base._isXDomain());
if (multipart) req.multipart = true;
req.open(method || 'GET', this._prepareUrl() + (url ? '/' + url : ''));
if (method == 'POST' && 'setRequestHeader' in req){
req.setRequestHeader('Content-type', 'text/plain; charset=utf-8');
}
return req;
};
XHR.check = function(xdomain){
try {
if (request(xdomain)) return true;
} catch(e){}
return false;
};
XHR.xdomainCheck = function(){
return XHR.check(true);
};
XHR.request = request;
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var WS = io.Transport.websocket = function(){
io.Transport.apply(this, arguments);
};
io.util.inherit(WS, io.Transport);
WS.prototype.type = 'websocket';
WS.prototype.connect = function(){
var self = this;
this.socket = new WebSocket(this._prepareUrl());
this.socket.onmessage = function(ev){ self._onData(ev.data); };
this.socket.onopen = function(ev){ self._onOpen(); };
this.socket.onclose = function(ev){ self._onClose(); };
return this;
};
WS.prototype.rawsend = function(data){
if (this.socket) this.socket.send(data);
/*
* This rigmarole is required because the WebSockets specification doesn't say what happens
* to buffered data when close() is called. It cannot be assumed that buffered data is
* transmitted before the connection is close.
*/
if (!!this.disconnectWhenEmpty && !this._interval) {
var self = this;
self._interval = setInterval(function() {
if (self.socket.bufferedAmount == 0) {
self.disconnect();
clearInterval(self._interval);
} else if (!self.disconnectWhenEmpty ||
self.socket.readyState == self.socket.CLOSED) {
clearInterval(self._interval);
}
}, 50);
}
return this;
};
WS.prototype.disconnect = function(){
this.disconnectCalled = true;
if (this.socket) this.socket.close();
return this;
};
WS.prototype._destroy = function(){
if (this.socket) {
this.socket.onclose = null;
this.socket.onopen = null;
this.socket.onmessage = null;
this.socket.close();
this.socket = null;
}
return this;
};
WS.prototype._onOpen = function(){
// This is needed because the 7.1.6 version of jetty's WebSocket fails if messages are
// sent from inside WebSocket.onConnect() method.
this.socket.send('OPEN');
return this;
};
WS.prototype._onClose = function(){
if (!!this.disconnectCalled || this.base.socketState == this.base.CLOSED) {
this.disconnectCalled = false;
this._onDisconnect();
} else {
this._onDisconnect(this.base.DR_ERROR, "WebSocket closed unexpectedly");
}
return this;
};
WS.prototype._prepareUrl = function(){
return (this.base.options.secure ? 'wss' : 'ws')
+ '://' + this.base.host
+ ':' + this.base.options.port
+ '/' + this.base.options.resource
+ '/' + this.type
+ (this.sessionid ? ('/' + this.sessionid) : '');
};
WS.check = function(){
// we make sure WebSocket is not confounded with a previously loaded flash WebSocket
return 'WebSocket' in window && WebSocket.prototype && ( WebSocket.prototype.send && !!WebSocket.prototype.send.toString().match(/native/i)) && typeof WebSocket !== "undefined";
};
WS.xdomainCheck = function(){
return true;
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var Flashsocket = io.Transport.flashsocket = function(){
io.Transport.websocket.apply(this, arguments);
};
io.util.inherit(Flashsocket, io.Transport.websocket);
Flashsocket.prototype.type = 'flashsocket';
Flashsocket.prototype.connect = function(){
var self = this, args = arguments;
WebSocket.__addTask(function(){
io.Transport.websocket.prototype.connect.apply(self, args);
});
return this;
};
Flashsocket.prototype.send = function(){
var self = this, args = arguments;
WebSocket.__addTask(function(){
io.Transport.websocket.prototype.send.apply(self, args);
});
return this;
};
Flashsocket.check = function(){
if (typeof WebSocket == 'undefined' || !('__addTask' in WebSocket)) return false;
if (io.util.opera) return false; // opera is buggy with this transport
if ('navigator' in window && 'plugins' in navigator && navigator.plugins['Shockwave Flash']){
return !!navigator.plugins['Shockwave Flash'].description;
}
if ('ActiveXObject' in window) {
try {
return !!new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
} catch (e) {}
}
return false;
};
Flashsocket.xdomainCheck = function(){
return true;
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var HTMLFile = io.Transport.htmlfile = function(){
io.Transport.XHR.apply(this, arguments);
};
io.util.inherit(HTMLFile, io.Transport.XHR);
HTMLFile.prototype.type = 'htmlfile';
HTMLFile.prototype._get = function(){
var self = this;
this._open();
window.attachEvent('onunload', function(){ self._destroy(); });
};
HTMLFile.prototype._open = function(){
this._doc = new ActiveXObject('htmlfile');
this._doc.open();
this._doc.write('<html></html>');
this._doc.parentWindow.s = this;
this._doc.close();
var _iframeC = this._doc.createElement('div');
this._doc.body.appendChild(_iframeC);
this._iframe = this._doc.createElement('iframe');
_iframeC.appendChild(this._iframe);
this._iframe.src = this._prepareUrl() + '/' + (+ new Date);
};
HTMLFile.prototype._ = function(data, doc){
this._onData(data);
var script = doc.getElementsByTagName('script')[0];
script.parentNode.removeChild(script);
};
HTMLFile.prototype._destroy = function(){
if (this._iframe){
this._iframe.src = 'about:blank';
this._doc = null;
CollectGarbage();
}
};
HTMLFile.prototype.disconnect = function(){
this._destroy();
return io.Transport.XHR.prototype.disconnect.call(this);
};
HTMLFile.check = function(){
if ('ActiveXObject' in window){
try {
var a = new ActiveXObject('htmlfile');
return a && io.Transport.XHR.check();
} catch(e){}
}
return false;
};
HTMLFile.xdomainCheck = function(){
// we can probably do handling for sub-domains, we should test that it's cross domain but a subdomain here
return false;
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var XHRMultipart = io.Transport['xhr-multipart'] = function(){
io.Transport.XHR.apply(this, arguments);
};
io.util.inherit(XHRMultipart, io.Transport.XHR);
XHRMultipart.prototype.type = 'xhr-multipart';
XHRMultipart.prototype._get = function(){
var self = this;
var lastReadyState = 4;
this._xhr = this._request('', 'GET', true);
this._xhr.onreadystatechange = function(){
// Normally the readyState will progress from 1-4 (e.g. 1,2,3,4) for a normal part.
// But on disconnect, the readyState will go from 1 to 4 skipping 2 and 3.
// Thanks to Wilfred Nilsen (http://www.mail-archive.com/mozilla-xpcom@mozilla.org/msg04845.html) for discovering this.
// So, if the readyState skips a step and equals 4, then the connection has dropped.
if (self._xhr.readyState - lastReadyState > 1 && self._xhr.readyState == 4) {
self._onDisconnect(self.base.DR_ERROR, "XHR Connection dropped unexpectedly");
} else {
lastReadyState = self._xhr.readyState;
if (self._xhr.readyState == 3) {
self._onData(self._xhr.responseText);
}
}
};
this._xhr.send();
};
XHRMultipart.check = function(){
return 'XMLHttpRequest' in window && 'prototype' in XMLHttpRequest && 'multipart' in XMLHttpRequest.prototype;
};
XHRMultipart.xdomainCheck = function(){
return true;
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var empty = new Function(),
XHRPolling = io.Transport['xhr-polling'] = function(){
io.Transport.XHR.apply(this, arguments);
};
io.util.inherit(XHRPolling, io.Transport.XHR);
XHRPolling.prototype.type = 'xhr-polling';
XHRPolling.prototype.connect = function(){
if (io.util.ios || io.util.android){
var self = this;
io.util.load(function(){
setTimeout(function(){
io.Transport.XHR.prototype.connect.call(self);
}, 10);
});
} else {
io.Transport.XHR.prototype.connect.call(this);
}
};
XHRPolling.prototype._get = function(){
var self = this;
this._xhr = this._request(+ new Date, 'GET');
if ('onload' in this._xhr){
this._xhr.onload = function(){
self._onData(this.responseText);
self._get();
};
this._xhr.onerror = function(){
self._onDisconnect();
};
} else {
this._xhr.onreadystatechange = function(){
var status;
if (self._xhr.readyState == 4){
self._xhr.onreadystatechange = empty;
try { status = self._xhr.status; } catch(e){}
if (status == 200){
self._onData(self._xhr.responseText);
self._get();
} else {
self._onDisconnect();
}
}
};
}
this._xhr.send();
};
XHRPolling.check = function(){
return io.Transport.XHR.check();
};
XHRPolling.xdomainCheck = function(){
return io.Transport.XHR.xdomainCheck();
};
})();
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
io.JSONP = [];
JSONPPolling = io.Transport['jsonp-polling'] = function(){
io.Transport.XHR.apply(this, arguments);
this._insertAt = document.getElementsByTagName('script')[0];
this._index = io.JSONP.length;
io.JSONP.push(this);
};
io.util.inherit(JSONPPolling, io.Transport['xhr-polling']);
JSONPPolling.prototype.type = 'jsonp-polling';
JSONPPolling.prototype._send = function(data){
var self = this;
if (!('_form' in this)){
var form = document.createElement('FORM'),
area = document.createElement('TEXTAREA'),
id = this._iframeId = 'socket_io_iframe_' + this._index,
iframe;
form.style.position = 'absolute';
form.style.top = '-1000px';
form.style.left = '-1000px';
form.target = id;
form.method = 'POST';
form.action = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
area.name = 'data';
form.appendChild(area);
this._insertAt.parentNode.insertBefore(form, this._insertAt);
document.body.appendChild(form);
this._form = form;
this._area = area;
}
function complete(){
initIframe();
self._posting = false;
self._checkSend();
};
function initIframe(){
if (self._iframe){
self._form.removeChild(self._iframe);
}
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
iframe = document.createElement('<iframe name="'+ self._iframeId +'">');
} catch(e){
iframe = document.createElement('iframe');
iframe.name = self._iframeId;
}
iframe.id = self._iframeId;
self._form.appendChild(iframe);
self._iframe = iframe;
};
initIframe();
this._posting = true;
this._area.value = data;
try {
this._form.submit();
} catch(e){}
if (this._iframe.attachEvent){
iframe.onreadystatechange = function(){
if (self._iframe.readyState == 'complete') complete();
};
} else {
this._iframe.onload = complete;
}
};
JSONPPolling.prototype._get = function(){
var self = this,
script = document.createElement('SCRIPT');
if (this._script){
this._script.parentNode.removeChild(this._script);
this._script = null;
}
script.async = true;
script.src = this._prepareUrl() + '/' + (+new Date) + '/' + this._index;
script.onerror = function(){
self._onDisconnect();
};
this._insertAt.parentNode.insertBefore(script, this._insertAt);
this._script = script;
};
JSONPPolling.prototype._ = function(){
this._onData.apply(this, arguments);
this._get();
return this;
};
JSONPPolling.check = function(){
return true;
};
JSONPPolling.xdomainCheck = function(){
return true;
};
/**
* Socket.IO client
*
* @author Guillermo Rauch <guillermo@learnboost.com>
* @license The MIT license.
* @copyright Copyright (c) 2010 LearnBoost <dev@learnboost.com>
*/
(function(){
var Socket = io.Socket = function(host, options){
this.host = host || document.domain;
io.util.merge(this.options, options);
this.transport = this.getTransport();
if (!this.transport && 'console' in window) console.error('No transport available');
};
// Constants
// Socket state
Socket.prototype.CONNECTING = 0;
Socket.prototype.CONNECTED = 1;
Socket.prototype.CLOSING = 2;
Socket.prototype.CLOSED = 3;
// Disconnect Reason
Socket.prototype.DR_CONNECT_FAILED = 1;
Socket.prototype.DR_DISCONNECT = 2;
Socket.prototype.DR_TIMEOUT = 3;
Socket.prototype.DR_CLOSE_FAILED = 4;
Socket.prototype.DR_ERROR = 5;
Socket.prototype.DR_CLOSED_REMOTELY = 6;
Socket.prototype.DR_CLOSED = 7;
// Event Types
Socket.prototype.CONNECT_EVENT = 'connect';
Socket.prototype.DISCONNECT_EVENT = 'disconnect';
Socket.prototype.MESSAGE_EVENT = 'message';
// Message Types
Socket.prototype.TEXT_MESSAGE = 0;
Socket.prototype.JSON_MESSAGE = 1;
Socket.prototype.options = {
secure: false,
document: document,
port: document.location.port || 80,
resource: 'socket.io',
transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
transportOptions: {
'xhr-polling': {
timeout: 25000 // based on polling duration default
},
'jsonp-polling': {
timeout: 25000
}
},
connectTimeout: 5000,
tryTransportsOnConnectTimeout: true,
rememberTransport: false
};
Socket.prototype.socketState = Socket.prototype.CLOSED;
Socket.prototype._events = {};
Socket.prototype._parsers = {};
Socket.prototype.getTransport = function(override){
var transports = override || this.options.transports, match;
if (this.options.rememberTransport && !override){
match = this.options.document.cookie.match('(?:^|;)\\s*socketio=([^;]*)');
if (match){
this._rememberedTransport = true;
transports = [decodeURIComponent(match[1])];
}
}
for (var i = 0, transport; transport = transports[i]; i++){
if (io.Transport[transport]
&& io.Transport[transport].check()
&& (!this._isXDomain() || io.Transport[transport].xdomainCheck())){
return new io.Transport[transport](this, this.options.transportOptions[transport] || {});
}
}
return null;
};
Socket.prototype.connect = function(){
if (this.socketState != this.CLOSED) throw ("Socket not closed!");
if (!this.transport) throw ("No available transports!");
var self = this;
var _connect = function() {
if (self.transport) {
if (self.socketState == self.CONNECTING) self.transport._destroy();
self.socketState = self.CONNECTING;
self.transport.connect();
if (self.options.connectTimeout){
setTimeout(function(){
if (self.socketState == self.CONNECTING){
self.transport._destroy();
if (self.options.tryTransportsOnConnectTimeout && !self._rememberedTransport){
var remainingTransports = [], transports = self.options.transports;
for (var i = 0, transport; transport = transports[i]; i++){
if (transport != self.transport.type) remainingTransports.push(transport);
}
if (remainingTransports.length){
self.transport = self.getTransport(remainingTransports);
_connect();
} else {
self.onDisconnect(self.DR_CONNECT_FAILED, "All transports failed");
}
} else {
self.onDisconnect(self.DR_CONNECT_FAILED, "Connection attempt timed out");
}
}
}, self.options.connectTimeout);
}
} else {
self.onDisconnect(self.DR_CONNECT_FAILED, "All transports failed");
}
};
_connect();
return this;
};
Socket.prototype.send = function(){
if (this.socketState == this.CLOSING) throw ("Socket is closing!");
if (this.socketState != this.CONNECTED) throw ("Socket not connected!");
var mtype = 0;
var data;
if (arguments.length == 1) {
data = arguments[0];
} else if (arguments.length >= 2) {
mtype = Number(arguments[0]);
data = arguments[1];
} else {
throw "Socket.send() requires at least one argument";
}
if (isNaN(mtype)) {
throw "Invalid message type, must be a number!";
}
if (mtype < 0 || mtype > 2147483648) {
throw "Invalid message type, must be greater than 0 and less than 2^31!";
}
var parser = this._parsers[mtype];
if (parser) {
data = String(parser.encode(data));
}
this.transport.send(mtype, data);
return this;
};
Socket.prototype.close = function() {
this.socketState = this.CLOSING;
this.transport.close();
return this;
};
Socket.prototype.disconnect = function(){
this.transport.disconnect();
return this;
};
Socket.prototype.setMessageParser = function(messageType, parser) {
var mtype = Number(messageType);
if (mtype != messageType) {
throw "Invalid message type, it must be a number!";
}
if (!parser) {
delete this._parsers[mtype];
} else {
if (typeof parser.encode != 'function' || typeof parser.decode != 'function') {
throw "Invalid parser!";
}
this._parsers[mtype] = parser;
}
};
Socket.prototype.on = function(name, fn){
if (!(name in this._events)) this._events[name] = [];
this._events[name].push(fn);
return this;
};
Socket.prototype.fire = function(name, args){
if (name in this._events){
for (var i = 0, ii = this._events[name].length; i < ii; i++)
this._events[name][i].apply(this, args === undefined ? [] : args);
}
return this;
};
Socket.prototype.removeEvent = function(name, fn){
if (name in this._events){
for (var a = 0, l = this._events[name].length; a < l; a++)
if (this._events[name][a] == fn) this._events[name].splice(a, 1);
}
return this;
};
Socket.prototype._isXDomain = function(){
return this.host !== document.domain;
};
Socket.prototype._onConnect = function(){
this.socketState = this.CONNECTED;
if (this.options.rememberTransport) this.options.document.cookie = 'socketio=' + encodeURIComponent(this.transport.type);
this.fire(this.CONNECT_EVENT);
};
Socket.prototype._onMessage = function(mtype, data){
var parser = this._parsers[mtype];
var obj = data;
var error = null;
if (parser) {
try {
obj = parser.decode(data);
} catch (e) {
error = e;
}
}
this.fire(this.MESSAGE_EVENT, [mtype, obj, error]);
};
Socket.prototype._onDisconnect = function(disconnectReason, errorMessage){
var state = this.socketState;
this.socketState = this.CLOSED;
if (state == this.CLOSED) {
this.fire(this.DISCONNECT_EVENT, [this.DR_CLOSED, errorMessage]);
} else if (state == this.CLOSING) {
if (!!this.closeId) {
this.fire(this.DISCONNECT_EVENT, [this.DR_CLOSE_FAILED, errorMessage]);
} else {
this.fire(this.DISCONNECT_EVENT, [this.DR_CLOSED_REMOTELY, errorMessage]);
}
} else if (state == this.CONNECTING) {
this.fire(this.DISCONNECT_EVENT, [this.DR_CONNECT_FAILED, errorMessage]);
} else if (!disconnectReason) {
this.fire(this.DISCONNECT_EVENT, [this.DR_DISCONNECT, errorMessage]);
} else {
this.fire(this.DISCONNECT_EVENT, [disconnectReason, errorMessage]);
}
};
Socket.prototype.addListener = Socket.prototype.addEvent = Socket.prototype.addEventListener = Socket.prototype.on;
})();
/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
/*
/*
Copyright 2006 Adobe Systems Incorporated
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The Bridge class, responsible for navigating AS instances
*/
function FABridge(target,bridgeName)
{
this.target = target;
this.remoteTypeCache = {};
this.remoteInstanceCache = {};
this.remoteFunctionCache = {};
this.localFunctionCache = {};
this.bridgeID = FABridge.nextBridgeID++;
this.name = bridgeName;
this.nextLocalFuncID = 0;
FABridge.instances[this.name] = this;
FABridge.idMap[this.bridgeID] = this;
return this;
}
// type codes for packed values
FABridge.TYPE_ASINSTANCE = 1;
FABridge.TYPE_ASFUNCTION = 2;
FABridge.TYPE_JSFUNCTION = 3;
FABridge.TYPE_ANONYMOUS = 4;
FABridge.initCallbacks = {};
FABridge.userTypes = {};
FABridge.addToUserTypes = function()
{
for (var i = 0; i < arguments.length; i++)
{
FABridge.userTypes[arguments[i]] = {
'typeName': arguments[i],
'enriched': false
};
}
}
FABridge.argsToArray = function(args)
{
var result = [];
for (var i = 0; i < args.length; i++)
{
result[i] = args[i];
}
return result;
}
function instanceFactory(objID)
{
this.fb_instance_id = objID;
return this;
}
function FABridge__invokeJSFunction(args)
{
var funcID = args[0];
var throughArgs = args.concat();//FABridge.argsToArray(arguments);
throughArgs.shift();
var bridge = FABridge.extractBridgeFromID(funcID);
return bridge.invokeLocalFunction(funcID, throughArgs);
}
FABridge.addInitializationCallback = function(bridgeName, callback)
{
var inst = FABridge.instances[bridgeName];
if (inst != undefined)
{
callback.call(inst);
return;
}
var callbackList = FABridge.initCallbacks[bridgeName];
if(callbackList == null)
{
FABridge.initCallbacks[bridgeName] = callbackList = [];
}
callbackList.push(callback);
}
// updated for changes to SWFObject2
function FABridge__bridgeInitialized(bridgeName) {
var objects = document.getElementsByTagName("object");
var ol = objects.length;
var activeObjects = [];
if (ol > 0) {
for (var i = 0; i < ol; i++) {
if (typeof objects[i].SetVariable != "undefined") {
activeObjects[activeObjects.length] = objects[i];
}
}
}
var embeds = document.getElementsByTagName("embed");
var el = embeds.length;
var activeEmbeds = [];
if (el > 0) {
for (var j = 0; j < el; j++) {
if (typeof embeds[j].SetVariable != "undefined") {
activeEmbeds[activeEmbeds.length] = embeds[j];
}
}
}
var aol = activeObjects.length;
var ael = activeEmbeds.length;
var searchStr = "bridgeName="+ bridgeName;
if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
FABridge.attachBridge(activeObjects[0], bridgeName);
}
else if (ael == 1 && !aol) {
FABridge.attachBridge(activeEmbeds[0], bridgeName);
}
else {
var flash_found = false;
if (aol > 1) {
for (var k = 0; k < aol; k++) {
var params = activeObjects[k].childNodes;
for (var l = 0; l < params.length; l++) {
var param = params[l];
if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
FABridge.attachBridge(activeObjects[k], bridgeName);
flash_found = true;
break;
}
}
if (flash_found) {
break;
}
}
}
if (!flash_found && ael > 1) {
for (var m = 0; m < ael; m++) {
var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
if (flashVars.indexOf(searchStr) >= 0) {
FABridge.attachBridge(activeEmbeds[m], bridgeName);
break;
}
}
}
}
return true;
}
// used to track multiple bridge instances, since callbacks from AS are global across the page.
FABridge.nextBridgeID = 0;
FABridge.instances = {};
FABridge.idMap = {};
FABridge.refCount = 0;
FABridge.extractBridgeFromID = function(id)
{
var bridgeID = (id >> 16);
return FABridge.idMap[bridgeID];
}
FABridge.attachBridge = function(instance, bridgeName)
{
var newBridgeInstance = new FABridge(instance, bridgeName);
FABridge[bridgeName] = newBridgeInstance;
/* FABridge[bridgeName] = function() {
return newBridgeInstance.root();
}
*/
var callbacks = FABridge.initCallbacks[bridgeName];
if (callbacks == null)
{
return;
}
for (var i = 0; i < callbacks.length; i++)
{
callbacks[i].call(newBridgeInstance);
}
delete FABridge.initCallbacks[bridgeName]
}
// some methods can't be proxied. You can use the explicit get,set, and call methods if necessary.
FABridge.blockedMethods =
{
toString: true,
get: true,
set: true,
call: true
};
FABridge.prototype =
{
// bootstrapping
root: function()
{
return this.deserialize(this.target.getRoot());
},
//clears all of the AS objects in the cache maps
releaseASObjects: function()
{
return this.target.releaseASObjects();
},
//clears a specific object in AS from the type maps
releaseNamedASObject: function(value)
{
if(typeof(value) != "object")
{
return false;
}
else
{
var ret = this.target.releaseNamedASObject(value.fb_instance_id);
return ret;
}
},
//create a new AS Object
create: function(className)
{
return this.deserialize(this.target.create(className));
},
// utilities
makeID: function(token)
{
return (this.bridgeID << 16) + token;
},
// low level access to the flash object
//get a named property from an AS object
getPropertyFromAS: function(objRef, propName)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.getPropFromAS(objRef, propName);
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
},
//set a named property on an AS object
setPropertyInAS: function(objRef,propName, value)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
},
//call an AS function
callASFunction: function(funcID, args)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
retVal = this.target.invokeASFunction(funcID, this.serialize(args));
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
},
//call a method on an AS object
callASMethod: function(objID, funcName, args)
{
if (FABridge.refCount > 0)
{
throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
}
else
{
FABridge.refCount++;
args = this.serialize(args);
retVal = this.target.invokeASMethod(objID, funcName, args);
retVal = this.handleError(retVal);
FABridge.refCount--;
return retVal;
}
},
// responders to remote calls from flash
//callback from flash that executes a local JS function
//used mostly when setting js functions as callbacks on events
invokeLocalFunction: function(funcID, args)
{
var result;
var func = this.localFunctionCache[funcID];
if(func != undefined)
{
result = this.serialize(func.apply(null, this.deserialize(args)));
}
return result;
},
// Object Types and Proxies
// accepts an object reference, returns a type object matching the obj reference.
getTypeFromName: function(objTypeName)
{
return this.remoteTypeCache[objTypeName];
},
//create an AS proxy for the given object ID and type
createProxy: function(objID, typeName)
{
var objType = this.getTypeFromName(typeName);
instanceFactory.prototype = objType;
var instance = new instanceFactory(objID);
this.remoteInstanceCache[objID] = instance;
return instance;
},
//return the proxy associated with the given object ID
getProxy: function(objID)
{
return this.remoteInstanceCache[objID];
},
// accepts a type structure, returns a constructed type
addTypeDataToCache: function(typeData)
{
var newType = new ASProxy(this, typeData.name);
var accessors = typeData.accessors;
for (var i = 0; i < accessors.length; i++)
{
this.addPropertyToType(newType, accessors[i]);
}
var methods = typeData.methods;
for (var i = 0; i < methods.length; i++)
{
if (FABridge.blockedMethods[methods[i]] == undefined)
{
this.addMethodToType(newType, methods[i]);
}
}
this.remoteTypeCache[newType.typeName] = newType;
return newType;
},
//add a property to a typename; used to define the properties that can be called on an AS proxied object
addPropertyToType: function(ty, propName)
{
var c = propName.charAt(0);
var setterName;
var getterName;
if(c >= "a" && c <= "z")
{
getterName = "get" + c.toUpperCase() + propName.substr(1);
setterName = "set" + c.toUpperCase() + propName.substr(1);
}
else
{
getterName = "get" + propName;
setterName = "set" + propName;
}
ty[setterName] = function(val)
{
this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
}
ty[getterName] = function()
{
return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
}
},
//add a method to a typename; used to define the methods that can be callefd on an AS proxied object
addMethodToType: function(ty, methodName)
{
ty[methodName] = function()
{
return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments)));
}
},
// Function Proxies
//returns the AS proxy for the specified function ID
getFunctionProxy: function(funcID)
{
var bridge = this;
if (this.remoteFunctionCache[funcID] == null)
{
this.remoteFunctionCache[funcID] = function()
{
bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
}
}
return this.remoteFunctionCache[funcID];
},
//reutrns the ID of the given function; if it doesnt exist it is created and added to the local cache
getFunctionID: function(func)
{
if (func.__bridge_id__ == undefined)
{
func.__bridge_id__ = this.makeID(this.nextLocalFuncID++);
this.localFunctionCache[func.__bridge_id__] = func;
}
return func.__bridge_id__;
},
// serialization / deserialization
serialize: function(value)
{
var result = {};
var t = typeof(value);
//primitives are kept as such
if (t == "number" || t == "string" || t == "boolean" || t == null || t == undefined)
{
result = value;
}
else if (value instanceof Array)
{
//arrays are serializesd recursively
result = [];
for (var i = 0; i < value.length; i++)
{
result[i] = this.serialize(value[i]);
}
}
else if (t == "function")
{
//js functions are assigned an ID and stored in the local cache
result.type = FABridge.TYPE_JSFUNCTION;
result.value = this.getFunctionID(value);
}
else if (value instanceof ASProxy)
{
result.type = FABridge.TYPE_ASINSTANCE;
result.value = value.fb_instance_id;
}
else
{
result.type = FABridge.TYPE_ANONYMOUS;
result.value = value;
}
return result;
},
//on deserialization we always check the return for the specific error code that is used to marshall NPE's into JS errors
// the unpacking is done by returning the value on each pachet for objects/arrays
deserialize: function(packedValue)
{
var result;
var t = typeof(packedValue);
if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
{
result = this.handleError(packedValue);
}
else if (packedValue instanceof Array)
{
result = [];
for (var i = 0; i < packedValue.length; i++)
{
result[i] = this.deserialize(packedValue[i]);
}
}
else if (t == "object")
{
for(var i = 0; i < packedValue.newTypes.length; i++)
{
this.addTypeDataToCache(packedValue.newTypes[i]);
}
for (var aRefID in packedValue.newRefs)
{
this.createProxy(aRefID, packedValue.newRefs[aRefID]);
}
if (packedValue.type == FABridge.TYPE_PRIMITIVE)
{
result = packedValue.value;
}
else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
{
result = this.getFunctionProxy(packedValue.value);
}
else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
{
result = this.getProxy(packedValue.value);
}
else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
{
result = packedValue.value;
}
}
return result;
},
//increases the reference count for the given object
addRef: function(obj)
{
this.target.incRef(obj.fb_instance_id);
},
//decrease the reference count for the given object and release it if needed
release:function(obj)
{
this.target.releaseRef(obj.fb_instance_id);
},
// check the given value for the components of the hard-coded error code : __FLASHERROR
// used to marshall NPE's into flash
handleError: function(value)
{
if (typeof(value)=="string" && value.indexOf("__FLASHERROR")==0)
{
var myErrorMessage = value.split("||");
if(FABridge.refCount > 0 )
{
FABridge.refCount--;
}
throw new Error(myErrorMessage[1]);
return value;
}
else
{
return value;
}
}
};
// The root ASProxy class that facades a flash object
ASProxy = function(bridge, typeName)
{
this.bridge = bridge;
this.typeName = typeName;
return this;
};
//methods available on each ASProxy object
ASProxy.prototype =
{
get: function(propName)
{
return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
},
set: function(propName, value)
{
this.bridge.setPropertyInAS(this.fb_instance_id, propName, value);
},
call: function(funcName, args)
{
this.bridge.callASMethod(this.fb_instance_id, funcName, args);
},
addRef: function() {
this.bridge.addRef(this);
},
release: function() {
this.bridge.release(this);
}
};
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
(function() {
if (window.WebSocket) return;
var console = window.console;
if (!console) console = {log: function(){ }, error: function(){ }};
if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
console.error("Flash Player is not installed.");
return;
}
if (location.protocol == "file:") {
console.error(
"WARNING: web-socket-js doesn't work in file:///... URL " +
"unless you set Flash Security Settings properly. " +
"Open the page via Web server i.e. http://...");
}
WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
var self = this;
self.readyState = WebSocket.CONNECTING;
self.bufferedAmount = 0;
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
// Otherwise, when onopen fires immediately, onopen is called before it is set.
setTimeout(function() {
WebSocket.__addTask(function() {
self.__createFlash(url, protocol, proxyHost, proxyPort, headers);
});
}, 1);
}
WebSocket.prototype.__createFlash = function(url, protocol, proxyHost, proxyPort, headers) {
var self = this;
self.__flash =
WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
self.__flash.addEventListener("open", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
if (self.__timer) clearInterval(self.__timer);
if (window.opera) {
// Workaround for weird behavior of Opera which sometimes drops events.
self.__timer = setInterval(function () {
self.__handleMessages();
}, 500);
}
if (self.onopen) self.onopen();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("close", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
if (self.__timer) clearInterval(self.__timer);
if (self.onclose) self.onclose();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("message", function() {
try {
self.__handleMessages();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("error", function(fe) {
try {
if (self.__timer) clearInterval(self.__timer);
if (self.onerror) self.onerror();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("stateChange", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
self.bufferedAmount = fe.getBufferedAmount();
} catch (e) {
console.error(e.toString());
}
});
//console.log("[WebSocket] Flash object is ready");
};
WebSocket.prototype.send = function(data) {
if (this.__flash) {
this.readyState = this.__flash.getReadyState();
}
if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
}
// We use encodeURIComponent() here, because FABridge doesn't work if
// the argument includes some characters. We don't use escape() here
// because of this:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
var result = this.__flash.send(encodeURIComponent(data));
if (result < 0) { // success
return true;
} else {
this.bufferedAmount = result;
return false;
}
};
WebSocket.prototype.close = function() {
var self = this;
if (!self.__flash) return;
self.readyState = self.__flash.getReadyState();
if (self.readyState == WebSocket.CLOSED || self.readyState == WebSocket.CLOSING) return;
self.__flash.close();
// Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
// which causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
self.readyState = WebSocket.CLOSED;
if (self.__timer) clearInterval(self.__timer);
if (self.onclose) {
// Make it asynchronous so that it looks more like an actual
// close event
setTimeout(self.onclose, 1);
}
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture !NB Not implemented yet
* @return void
*/
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
if (!('__events' in this)) {
this.__events = {};
}
if (!(type in this.__events)) {
this.__events[type] = [];
if ('function' == typeof this['on' + type]) {
this.__events[type].defaultHandler = this['on' + type];
this['on' + type] = this.__createEventHandler(this, type);
}
}
this.__events[type].push(listener);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture NB! Not implemented yet
* @return void
*/
WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
if (!('__events' in this)) {
this.__events = {};
}
if (!(type in this.__events)) return;
for (var i = this.__events.length; i > -1; --i) {
if (listener === this.__events[type][i]) {
this.__events[type].splice(i, 1);
break;
}
}
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {WebSocketEvent} event
* @return void
*/
WebSocket.prototype.dispatchEvent = function(event) {
if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
this.__events[event.type][i](event);
if (event.cancelBubble) break;
}
if (false !== event.returnValue &&
'function' == typeof this.__events[event.type].defaultHandler)
{
this.__events[event.type].defaultHandler(event);
}
};
WebSocket.prototype.__handleMessages = function() {
// Gets data using readSocketData() instead of getting it from event object
// of Flash event. This is to make sure to keep message order.
// It seems sometimes Flash events don't arrive in the same order as they are sent.
var arr = this.__flash.readSocketData();
for (var i = 0; i < arr.length; i++) {
var data = decodeURIComponent(arr[i]);
try {
if (this.onmessage) {
var e;
if (window.MessageEvent && !window.opera) {
e = document.createEvent("MessageEvent");
e.initMessageEvent("message", false, false, data, null, null, window, null);
} else { // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes
e = {data: data};
}
this.onmessage(e);
}
} catch (e) {
console.error(e.toString());
}
}
};
/**
* @param {object} object
* @param {string} type
*/
WebSocket.prototype.__createEventHandler = function(object, type) {
return function(data) {
var event = new WebSocketEvent();
event.initEvent(type, true, true);
event.target = event.currentTarget = object;
for (var key in data) {
event[key] = data[key];
}
object.dispatchEvent(event, arguments);
};
}
/**
* Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
*
* @class
* @constructor
*/
function WebSocketEvent(){}
/**
*
* @type boolean
*/
WebSocketEvent.prototype.cancelable = true;
/**
*
* @type boolean
*/
WebSocketEvent.prototype.cancelBubble = false;
/**
*
* @return void
*/
WebSocketEvent.prototype.preventDefault = function() {
if (this.cancelable) {
this.returnValue = false;
}
};
/**
*
* @return void
*/
WebSocketEvent.prototype.stopPropagation = function() {
this.cancelBubble = true;
};
/**
*
* @param {string} eventTypeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @return void
*/
WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
this.type = eventTypeArg;
this.cancelable = cancelableArg;
this.timeStamp = new Date();
};
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
WebSocket.__tasks = [];
WebSocket.__initialize = function() {
if (WebSocket.__swfLocation) {
// For backword compatibility.
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
}
if (!window.WEB_SOCKET_SWF_LOCATION) {
console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
return;
}
var container = document.createElement("div");
container.id = "webSocketContainer";
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
// the best we can do as far as we know now.
container.style.position = "absolute";
if (WebSocket.__isFlashLite()) {
container.style.left = "0px";
container.style.top = "0px";
} else {
container.style.left = "-100px";
container.style.top = "-100px";
}
var holder = document.createElement("div");
holder.id = "webSocketFlash";
container.appendChild(holder);
document.body.appendChild(container);
// See this article for hasPriority:
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
swfobject.embedSWF(
WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
"1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
null, {bridgeName: "webSocket"}, {hasPriority: true, allowScriptAccess: "always"}, null,
function(e) {
if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
}
);
FABridge.addInitializationCallback("webSocket", function() {
try {
//console.log("[WebSocket] FABridge initializad");
WebSocket.__flash = FABridge.webSocket.root();
WebSocket.__flash.setCallerUrl(location.href);
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
WebSocket.__tasks[i]();
}
WebSocket.__tasks = [];
} catch (e) {
console.error("[WebSocket] " + e.toString());
}
});
};
WebSocket.__addTask = function(task) {
if (WebSocket.__flash) {
task();
} else {
WebSocket.__tasks.push(task);
}
};
WebSocket.__isFlashLite = function() {
if (!window.navigator || !window.navigator.mimeTypes) return false;
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
};
// called from Flash
window.webSocketLog = function(message) {
console.log(decodeURIComponent(message));
};
// called from Flash
window.webSocketError = function(message) {
console.error(decodeURIComponent(message));
};
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
if (window.addEventListener) {
window.addEventListener("load", WebSocket.__initialize, false);
} else {
window.attachEvent("onload", WebSocket.__initialize);
}
}
})();
| JavaScript |
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();} | JavaScript |
(function() {
var Textbox = function(label, color, fontsize, bgsource) {
this.initialize(label, color, fontsize, bgsource);
};
var p = Textbox.prototype = new createjs.Container(); // inherit from Container
this.text;
p.label;
this.bg_succ;
this.bg;
this.dragger;
this.width;
this.height;
p.Container_initialize = p.initialize;
p.initialize = function(label, color, fontsize, bgsource) {
this.Container_initialize();
this.label = label;
if (!color) { color = "#CCC"; }
this.text = new createjs.Text(label, fontsize + "px Arial", color);
this.text.textBaseline = "top";
this.text.textAlign = "left";
this.text.lineWidth = stage.canvas.width - 100;
this.width = this.text.getMeasuredWidth()+30;
this.height = this.text.getMeasuredHeight()+20;
this.text.x = 10;
this.text.y = 10;
this.bg_succ = new createjs.Bitmap(queue.getResult("bgTextSuccess"));
this.bg_succ.x = this.bg_succ.y = 0;
this.bgsuccesssize(this.width, this.height);
this.bg = new createjs.Bitmap(queue.getResult(bgsource));
this.bg.x = this.bg.y = 0;
this.bgsize(this.width, this.height);
this.dragger = new createjs.Container();
this.dragger.x = this.dragger.y = 100;
this.dragger.addChild(this.bg, this.text);
stage.addChild(this.dragger);
this.addChild(this.dragger);
this.on("click", this.handleClick);
this.on("tick", this.handleTick);
this.mouseChildren = false;
};
p.removeChild = function() {
};
p.bgsize = function(windowWidth, windowHeight) {
var bounds = this.bg.getBounds();
var currentWidth = bounds.width;
var currentHeight = bounds.height;
this.bg.scaleX = windowWidth / currentWidth;
this.bg.scaleY = windowHeight / currentHeight;
};
p.bgsuccesssize = function(windowWidth, windowHeight) {
var bounds = this.bg_succ.getBounds();
var currentWidth = bounds.width;
var currentHeight = bounds.height;
this.bg_succ.scaleX = windowWidth / currentWidth;
this.bg_succ.scaleY = windowHeight / currentHeight;
};
p.succeed = function() {
this.dragger.removeChild(this.bg, this.text);
this.dragger.addChild(this.bg_succ, this.text);
};
p.appearLine = function(fromX, fromY, moveX, moveY) {
// var bounds = p.bmp.getBounds();
//move the form above the screen
this.dragger.x = fromX;
this.dragger.y = fromY;
createjs.Tween.get(this.dragger).to({alpha: 1, x: moveX, y: moveY}, 2000, createjs.Ease.linear);
};
p.hitTest = function(mouseX, mouseY) {
// var bounds = p.bmp.getBounds();
return this.dragger.x <= mouseX && mouseX <= this.dragger.x + this.width
&& this.dragger.y <= mouseY && mouseY <= this.dragger.y + this.height;
};
p.position = function(x, y) {
this.dragger.x = x;
this.dragger.y = y;
};
p.handleClick = function (event) {
// var target = event.target;
// alert("You clicked on a button: "+ target.label);
};
p.handleTick = function(event) {
// p.alpha = Math.cos(p.count++*0.1)*0.4+0.6;
};
window.Textbox = Textbox;
}()); | JavaScript |
(function() {
var Button = function(label, color) {
this.initialize(label, color);
}
var p = Button.prototype = new createjs.Container(); // inherit from Container
p.label;
p.background;
p.count = 0;
p.Container_initialize = p.initialize;
p.initialize = function(label, color) {
this.Container_initialize();
this.label = label;
if (!color) { color = "#CCC"; }
var text = new createjs.Text(label, "20px Arial", "#000");
text.textBaseline = "top";
text.textAlign = "center";
var width = text.getMeasuredWidth()+30;
var height = text.getMeasuredHeight()+20;
this.background = new createjs.Shape();
this.background.graphics.beginFill(color).drawRoundRect(0,0,width,height,10);
text.x = width/2;
text.y = 10;
this.addChild(this.background,text);
this.on("click", this.handleClick);
this.on("tick", this.handleTick);
this.mouseChildren = false;
}
p.handleClick = function (event) {
var target = event.target;
alert("You clicked on a button: "+ target.label);
}
p.handleTick = function(event) {
p.alpha = Math.cos(p.count++*0.1)*0.4+0.6;
}
window.Button = Button;
}()); | JavaScript |
(function() {
var Laptop = function(label, color) {
this.initialize(label, color);
};
var p = Laptop.prototype = new createjs.Container(); // inherit from Container
this.bmp;
p.background;
p.hitScale = 0.1;
p.Container_initialize = p.initialize;
p.initialize = function(image) {
this.Container_initialize();
this.bmp = new createjs.Bitmap(queue.getResult(image));
// var shadow = new createjs.Shadow("#333", 10, 10, 500);
// this.bmp.shadow = shadow;
stage.addChild(this.bmp);
this.mouseChildren = false;
};
p.hitScale = function() {
this.bmp.scaleX += p.hitScale;
this.bmp.scaleY += p.hitScale;
};
p.unhitScale = function() {
this.bmp.scaleX -= p.hitScale;
this.bmp.scaleY -= p.hitScale;
};
p.addClickListener = function(fn) {
this.bmp.addEventListener("click", fn);
};
p.size = function(windowWidth, windowHeight) {
var bounds = this.bmp.getBounds();
var currentWidth = bounds.width;
var currentHeight = bounds.height;
// Derive a scale. Use the smaller of the two to "fit" the image. Change to Math.max to make it "fill" the window
var scale = Math.min(windowWidth / currentWidth, windowHeight / currentHeight);
this.bmp.scaleX = this.bmp.scaleY = scale;
};
p.appearSpin = function(canvasWidth, canvasHeight) {
var bounds = this.bmp.getBounds();
//move it's rotation center at the center of the form
this.bmp.regX = bounds.width * 0.5;
this.bmp.regY = bounds.height * 0.5;
//move the form above the screen
this.bmp.x = canvasWidth * 0.5;
this.bmp.y = -200;
createjs.Tween.get(this.bmp).to({alpha: 1, y: 300, rotation: 720}, 2000, createjs.Ease.cubicOut).call(this.tweenComplete);
};
p.disappearScale = function() {
p.alpha = 0;
createjs.Tween.get(this.bmp).to({scaleX:0,scaleY:0,alpha:1}, 2000, createjs.Ease.backIn);
};
p.appearScale = function(canvasWidth) {
p.alpha = 0;
this.bmp.x = (canvasWidth - (this.bmp.getBounds().width * this.bmp.scaleX)) * 0.5;
this.bmp.y = 300;
createjs.Tween.get(this.bmp).to({scaleX:0.5,scaleY:0.5,alpha:1}, 2000, createjs.Ease.backIn);
};
p.handleClick = function(event) {
var target = event.target;
alert("You clicked on a button: " + target.label);
};
p.handleTick = function(event) {
p.alpha = Math.cos(p.count++ * 0.1) * 0.4 + 0.6;
};
window.Laptop = Laptop;
}()); | JavaScript |
(function() {
var Part = function(source) {
this.initialize(source);
};
var p = Part.prototype = new createjs.Container(); // inherit from Container
this.dragger;
p.bmp;
p.background;
p.hitScalePixel = 100; //px
this.source;
this.previousX;
this.previousY;
p.width = 0;
p.height = 0;
this.hitWidth = p.width + p.hitScalePixel;
this.hitHeight = p.height + p.hitScalePixel;
p.Container_initialize = p.initialize;
p.initialize = function(source) {
this.Container_initialize();
this.source = source;
p.bmp = new createjs.Bitmap(queue.getResult(source));
// var shadow = new createjs.Shadow("#000000", 10, 10, 15);
// p.bmp.shadow = shadow;
p.addChild(p.bmp);
p.width = p.bmp.getBounds().width;
p.height = p.bmp.getBounds().height;
this.hitWidth = p.width + p.hitScalePixel;
this.hitHeight = p.height + p.hitScalePixel;
// this lets our drag continue to track the mouse even when it leaves the canvas:
// play with commenting this out to see the difference.
//stage.mouseMoveOutside = true;
// var circle = new createjs.Shape();
// circle.graphics.beginFill("red").drawCircle(0, 0, 50);
//
// var label = new createjs.Text("drag me", "bold 14px Arial", "#FFFFFF");
// label.textAlign = "center";
// label.y = -7;
var ba = new createjs.Shape();
// ba.graphics.beginStroke("#000000").rect(0,0,p.bmp.getBounds().width,p.bmp.getBounds().height);
this.dragger = new createjs.Container();
this.dragger.x = this.dragger.y = 100;
this.dragger.addChild(p.bmp, ba);
stage.addChild(this.dragger);
this.dragger.on("pressmove", function(evt) {
var bounds = p.bmp.getBounds();
// currentTarget will be the container that the event listener was added to:
evt.currentTarget.x = evt.stageX - (p.width / 2);
evt.currentTarget.y = evt.stageY - (p.height / 2);
// make sure to redraw the stage to show the change:
stage.update();
});
this.dragger.on("mouseover", function(evt) {
// make sure to redraw the stage to show the change:
stage.update();
});
this.on("tick", this.handleTick);
this.mouseChildren = false;
};
p.removeChild = function() {
stage.removeChild(this.dragger);
};
p.addChild = function() {
stage.addChild(this.dragger);
};
p.hitTest = function(mouseX, mouseY) {
var bounds = p.bmp.getBounds();
var wid = p.bmp.scaleX * bounds.width;
var heg = p.bmp.scaleY * bounds.height;
return this.dragger.x <= mouseX && mouseX <= this.dragger.x + wid
&& this.dragger.y <= mouseY && mouseY <= this.dragger.y + heg;
};
p.calculateHitPixel = function() {
this.hitWidth = p.width + p.hitScalePixel;
this.hitHeight = p.height + p.hitScalePixel;
};
p.appearLine = function(fromX, fromY, moveX, moveY) {
var bounds = p.bmp.getBounds();
//move the form above the screen
this.dragger.x = fromX;
this.dragger.y = fromY;
createjs.Tween.get(this.dragger).to({alpha: 1, x: moveX, y: moveY}, 2000, createjs.Ease.linear);
};
p.hitScale = function() {
p.sizeUnchangeHitSize(this.hitWidth, this.hitHeight);
};
p.unhitScale = function() {
p.sizeUnchangeHitSize(p.width, p.height);
};
p.position = function(x, y) {
this.dragger.x = x;
this.dragger.y = y;
p.previousX = x;
p.previousY = y;
};
p.disappearScale = function() {
p.alpha = 0;
createjs.Tween.get(this.dragger).to({scaleX:0,scaleY:0,alpha:1}, 2000, createjs.Ease.backIn);
};
p.size = function(windowWidth, windowHeight) {
var bounds = p.bmp.getBounds();
var currentWidth = bounds.width;
var currentHeight = bounds.height;
// Derive a scale. Use the smaller of the two to "fit" the image. Change to Math.max to make it "fill" the window
var scale = Math.min(windowWidth / currentWidth, windowHeight / currentHeight);
p.bmp.scaleX = p.bmp.scaleY = scale;
p.width = windowWidth * p.bmp.scaleX;
p.height = windowHeight * p.bmp.scaleY;
p.calculateHitPixel();
};
p.sizeUnchangeHitSize = function(windowWidth, windowHeight) {
var bounds = p.bmp.getBounds();
var currentWidth = bounds.width;
var currentHeight = bounds.height;
// Derive a scale. Use the smaller of the two to "fit" the image. Change to Math.max to make it "fill" the window
var scale = Math.min(windowWidth / currentWidth, windowHeight / currentHeight);
p.bmp.scaleX = p.bmp.scaleY = scale;
};
p.moveSpin = function(canvasWidth, canvasHeight) {
var bounds = p.bmp.getBounds();
createjs.Tween.get(p.bmp, {loop: true}).to({x: 450}, 30000).to({x: 50}, 30000);
};
p.tweenComplete = function(fn) {
};
p.handleClick = function(event) {
var target = event.target;
alert("You clicked on a button: " + target.label);
};
p.handleTick = function(event) {
// myParts[index].unhitScale();
// if (myParts[index].hitTest(stage.mouseX, stage.mouseY)) {
// myParts[index].hitScale();
// }
};
window.Part = Part;
}()); | JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This plugin register Toolbar items for the combos modifying the style to
* not show the box.
*/
FCKToolbarItems.RegisterItem( 'SourceSimple' , new FCKToolbarButton( 'Source', FCKLang.Source, null, FCK_TOOLBARITEM_ONLYICON, true, true, 1 ) ) ;
FCKToolbarItems.RegisterItem( 'StyleSimple' , new FCKToolbarStyleCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontNameSimple' , new FCKToolbarFontsCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontSizeSimple' , new FCKToolbarFontSizeCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontFormatSimple', new FCKToolbarFontFormatCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.